Compare commits

..
Author SHA1 Message Date
Patrick szymkowiak e3af2f1130 fix: subcommand routing drops unrecognized subcommands (#600)
- git stash: pass unknown subcommands (save, branch, clear) through
  instead of silently falling back to git stash push
- git branch: add --show-current, --set-upstream-to, --format, --sort
  to flag detection so they don't get overridden by -a injection
- pip: replace bail!() with passthrough for unknown subcommands
  (freeze, download, wheel, etc.)

Fixes #600

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-15 10:08:01 +01:00
220 changed files with 6147 additions and 16911 deletions

No files matched your search

+11 -38
View File
@@ -14,15 +14,13 @@ Prevent bugs, performance regressions, and token savings failures before they re
## RTK Architecture Context
```
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)
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)
```
**Non-negotiable constraints:**
@@ -34,11 +32,10 @@ src/main.rs (Commands enum + routing)
## Review Process
1. **Context**: Identify which module changed, what command it affects, token savings claim
2. **Call-site analysis**: Trace ALL callers of modified functions, list every input variant, verify each has a test
3. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
4. **Token savings**: Verify savings claim is tested with real fixture
5. **Cross-platform**: Shell escaping, path separators, ANSI codes
6. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
2. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
3. **Token savings**: Verify savings claim is tested with real fixture
4. **Cross-platform**: Shell escaping, path separators, ANSI codes
5. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
## RTK-Specific Red Flags
@@ -201,29 +198,6 @@ fix_here
| 🔴 | file.rs | 45 | lazy_static! |
```
## Call-Site Analysis (🔴 MANDATORY)
When reviewing a function change, **always trace upstream to every call site** and verify that all input variants are tested.
**Why this rule exists:** PR #546 modified `filter_log_output()` to split on `---END---` markers, but only tested the code path where RTK injects those markers. The other path (`--oneline`, `--pretty`, `--format`) never has `---END---` markers — the entire output became a single block, dropping all but 2 commits. This shipped to develop and was only caught during release review.
**Process:**
1. For every modified function, grep all call sites: `Grep pattern="function_name(" type="rust"`
2. For each call site, identify the `if/else` or `match` branch that leads to it
3. List every distinct input shape the function can receive
4. Verify a test exists for EACH input shape — not just the happy path
5. If a test is missing, flag it as 🔴 Critical
**Example (git log):**
```
run_log() has 2 paths:
- has_format_flag=false → injects ---END--- → filter_log_output sees blocks
- has_format_flag=true → no ---END--- → filter_log_output sees raw lines
Both paths MUST have tests.
```
**Rule of thumb:** If a function's caller has an `if/else` that changes the data flowing in, each branch needs its own test in the callee.
## Adversarial Questions for RTK
1. **Savings**: If I run `count_tokens(input)` vs `count_tokens(output)` — is savings ≥60%?
@@ -233,7 +207,6 @@ Both paths MUST have tests.
5. **Cross-platform**: Will this regex work on Windows CRLF output?
6. **ANSI**: Does the filter handle ANSI escape codes in input?
7. **Fixture**: Is the test using real output from the actual command?
8. **Call sites**: Have ALL callers been traced? Does each input variant have a test?
## The New Dev Test (RTK variant)
+11 -20
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/cmds/<ecosystem>/newcmd_cmd.rs`:
2. **Add snapshot test** to `src/newcmd_cmd.rs`:
```rust
#[cfg(test)]
mod tests {
@@ -439,27 +439,18 @@ cargo test --ignored
```
rtk/
├── src/
│ ├── 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/
│ ├── git.rs # Filter implementation
│ │ └── #[cfg(test)] mod tests { ... } # Unit tests
│ ├── snapshots/ # Insta snapshots (gitignored pattern)
│ │ └── git.rs.snap # Snapshot for git tests
├── tests/
│ ├── common/
│ │ └── 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])
│ │ └── 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])
```
**Best practices**:
+24 -36
View File
@@ -306,27 +306,20 @@ fn test_real_git_log() {
## Key Files Reference
**Core infrastructure** (`src/core/`):
**Core modules**:
- `src/main.rs` - CLI entry point, Clap command parsing, routing to modules
- `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)
- `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`)
**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
**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
**Tests**:
- `tests/fixtures/` - Real command output fixtures for testing
@@ -408,11 +401,11 @@ When adding a new filter (e.g., `rtk newcmd`):
### 1. Create Module
```bash
touch src/cmds/<ecosystem>/newcmd_cmd.rs
touch src/newcmd_cmd.rs
```
```rust
// src/cmds/<ecosystem>/newcmd_cmd.rs
// src/newcmd_cmd.rs
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
@@ -443,23 +436,18 @@ mod tests {
}
```
### 2. Register Module
### 2. Add to main.rs Commands Enum
Add to ecosystem `mod.rs` (e.g., `src/cmds/system/mod.rs`):
```rust
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>,
},
// src/main.rs
#[derive(Subcommand)]
enum Commands {
// ... existing commands
Newcmd {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
}
// In match statement
Commands::Newcmd { args } => {
+12 -15
View File
@@ -30,24 +30,21 @@ Think in terms of filter families, not individual commands. Every new `*_cmd.rs`
## RTK Architecture Map
```
src/main.rs
main.rs
├── Commands enum (clap derive)
│ ├── 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
│ ├── Git(GitArgs) → git.rs
│ ├── Cargo(CargoArgs) → runner.rs
│ ├── Gh(GhArgs) → gh_cmd.rs
│ ├── Grep(GrepArgs) → grep_cmd.rs
│ ├── ... → *_cmd.rs
│ ├── Gain → tracking.rs
│ └── Proxy(ProxyArgs) → passthrough
│
├── 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
├── 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
```
**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/cmds/<ecosystem>/newcmd_cmd.rs
touch src/newcmd_cmd.rs
```
```rust
// src/cmds/<ecosystem>/newcmd_cmd.rs
// src/newcmd_cmd.rs
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
+4 -5
View File
@@ -57,12 +57,11 @@ git diff "$BASE_BRANCH"...HEAD --stat
| Si le diff contient... | Vérifier |
| ------------------------------ | ------------------------------------------ |
| `src/**/*.rs` | CLAUDE.md sections Error Handling + Tests |
| `src/core/filter.rs` ou `src/cmds/**/*_cmd.rs` | Filter Development Checklist (CLAUDE.md) |
| `src/*.rs` | CLAUDE.md sections Error Handling + Tests |
| `src/filter.rs` ou `*_cmd.rs` | Filter Development Checklist (CLAUDE.md) |
| `src/main.rs` | Command routing + Commands enum |
| `src/core/tracking.rs` | SQLite patterns + DB path config |
| `src/core/config.rs` | Configuration system |
| `src/hooks/init.rs` | Init patterns + hook installation |
| `src/tracking.rs` | SQLite patterns + DB path config |
| `src/config.rs` | Configuration system + init patterns |
| `.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 @@
#!/usr/bin/env bash
#!/bin/bash
# Auto-format Rust code before commits
# Hook: PreToolUse for git commit
+24 -61
View File
@@ -1,16 +1,9 @@
#!/usr/bin/env bash
# rtk-hook-version: 3
#!/bin/bash
# RTK auto-rewrite hook for Claude Code PreToolUse:Bash
# Transparently rewrites raw commands to their RTK equivalents.
# Uses `rtk rewrite` as single source of truth — no duplicate mapping logic here.
#
# To add support for new commands, update src/discover/registry.rs (PATTERNS + RULES).
#
# Exit code protocol for `rtk rewrite`:
# 0 + stdout Rewrite found, no deny/ask rule matched → auto-allow
# 1 No RTK equivalent → pass through unchanged
# 2 Deny rule matched → pass through (Claude Code native deny handles it)
# 3 + stdout Ask rule matched → rewrite but let Claude Code prompt the user
# --- Audit logging (opt-in via RTK_HOOK_AUDIT=1) ---
_rtk_audit_log() {
@@ -44,37 +37,19 @@ case "$CMD" in
*'<<'*) _rtk_audit_log "skip:heredoc" "$CMD"; exit 0 ;;
esac
# Rewrite via rtk — single source of truth for all command mappings and permission checks.
# Use "|| EXIT_CODE=$?" to capture non-zero exit codes without triggering set -e.
EXIT_CODE=0
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || EXIT_CODE=$?
# Rewrite via rtk — single source of truth for all command mappings.
# Exit 1 = no RTK equivalent, pass through unchanged.
# Exit 0 = rewritten command (or already RTK, identical output).
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || {
_rtk_audit_log "skip:no_match" "$CMD"
exit 0
}
case $EXIT_CODE in
0)
# Rewrite found, no permission rules matched — safe to auto-allow.
if [ "$CMD" = "$REWRITTEN" ]; then
_rtk_audit_log "skip:already_rtk" "$CMD"
exit 0
fi
;;
1)
# No RTK equivalent — pass through unchanged.
_rtk_audit_log "skip:no_match" "$CMD"
exit 0
;;
2)
# Deny rule matched — let Claude Code's native deny rule handle it.
_rtk_audit_log "skip:deny_rule" "$CMD"
exit 0
;;
3)
# Ask rule matched — rewrite the command but do NOT auto-allow so that
# Claude Code prompts the user for confirmation.
;;
*)
exit 0
;;
esac
# If output is identical, command was already using RTK — nothing to do.
if [ "$CMD" = "$REWRITTEN" ]; then
_rtk_audit_log "skip:already_rtk" "$CMD"
exit 0
fi
_rtk_audit_log "rewrite" "$CMD" "$REWRITTEN"
@@ -82,26 +57,14 @@ _rtk_audit_log "rewrite" "$CMD" "$REWRITTEN"
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
if [ "$EXIT_CODE" -eq 3 ]; then
# Ask: rewrite the command, omit permissionDecision so Claude Code prompts.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"updatedInput": $updated
}
}'
else
# Allow: output the rewrite instruction in Claude Code hook format.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": $updated
}
}'
fi
# Output the rewrite instruction in Claude Code hook format.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": $updated
}
}'
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/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.
+11 -19
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/cmds/git/git.rs <<'EOF'
cat > src/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/cmds/git/snapshots/git__tests__*.snap
# 5. Snapshot saved in src/snapshots/git.rs.snap
```
## Token Accuracy Testing (🔴 Critical)
@@ -299,32 +299,24 @@ diff /tmp/before.txt /tmp/after.txt
```
rtk/
├── src/
│ ├── 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
│ ├── git.rs # Filter implementation
│ │ └── #[cfg(test)] mod tests { ... } # Unit tests
│ ├── snapshots/ # Insta snapshots
│ │ └── git.rs.snap # Snapshot for git tests
├── 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
│ │ └── dotnet/ # Dotnet-specific fixtures
│ └── integration_test.rs # Integration tests (#[ignore])
│ │ └── gh_pr_view_raw.txt
│ └── 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/cmds/<ecosystem>/snapshots/` (by insta)
- **Snapshots**: Auto-generated in `src/snapshots/` (by insta)
- **Shared utils**: `tests/common/mod.rs` (count_tokens, helpers)
- **Integration**: `tests/` with `#[ignore]` attribute
+26 -49
View File
@@ -15,43 +15,20 @@ Never use Bash for search (`find`, `grep`, `rg`) — use dedicated tools.
```
src/
├── 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
├── 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
```
## Common Search Patterns
@@ -63,7 +40,7 @@ src/
Grep pattern="Gh\|Cargo\|Git\|Grep" path="src/main.rs" output_mode="content"
# Step 2: Follow to module
Read file_path="src/cmds/git/gh_cmd.rs"
Read file_path="src/gh_cmd.rs"
```
### "Where is function X defined?"
@@ -75,8 +52,8 @@ Grep pattern="fn filter_git_log\|fn run\b" type="rust"
### "All command modules"
```
Glob pattern="src/cmds/**/*_cmd.rs"
# Also: src/cmds/git/git.rs, src/cmds/rust/runner.rs, src/cmds/cloud/container.rs
Glob pattern="src/*_cmd.rs"
# Then: src/git.rs, src/runner.rs for non-*_cmd.rs modules
```
### "Find all lazy_static regex definitions"
@@ -115,27 +92,27 @@ Glob pattern="tests/fixtures/*.txt"
### Adding a new filter
1. Check `src/main.rs` for Commands enum structure
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
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
4. Check `tests/fixtures/` for existing fixture patterns
### Debugging filter output
1. Start with `src/cmds/<ecosystem>/<cmd>_cmd.rs` → find `run()` function
1. Start with `src/<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/core/utils.rs::strip_ansi()` if ANSI codes involved
4. Check `src/utils.rs::strip_ansi()` if ANSI codes involved
### Tracking/metrics issues
1. `src/core/tracking.rs` → `track_command()` function
2. `src/core/config.rs` → `tracking.database_path` field
1. `src/tracking.rs` → `track_command()` function
2. `src/config.rs` → `tracking.database_path` field
3. `RTK_DB_PATH` env var overrides config
### Configuration issues
1. `src/core/config.rs` → `RtkConfig` struct
2. `src/hooks/init.rs` → `rtk init` command
1. `src/config.rs` → `RtkConfig` struct
2. `src/init.rs` → `rtk init` command
3. Config file: `~/.config/rtk/config.toml`
4. Filter files: `~/.config/rtk/filters/` (global) or `.rtk/filters/` (project)
@@ -143,7 +120,7 @@ Glob pattern="tests/fixtures/*.txt"
```
Glob pattern=".rtk/filters/*.toml" # Project-local filters
Glob pattern="src/core/toml_filter.rs" # TOML filter engine
Glob pattern="src/filter_*.rs" # TOML filter engine
Grep pattern="FilterRule\|FilterConfig" type="rust"
```
-7
View File
@@ -7,13 +7,6 @@ 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,12 +6,6 @@ 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,14 +1,7 @@
---
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,12 +8,6 @@ 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,15 +1,7 @@
---
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,13 +5,6 @@ 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
-244
View File
@@ -1,244 +0,0 @@
---
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é,
P0 sans PR, et conflits internes. Sauvegarde dans claudedocs/RTK-YYYY-MM-DD.md.
Args: "en"/"fr" pour la langue (défaut: fr), "save" pour forcer la sauvegarde.
allowed-tools:
- Bash
- Write
- Read
- AskUserQuestion
effort: high
tags: [triage, orchestration, issues, pr, security, cross-analysis, rtk]
---
# /rtk-triage
Orchestrateur de triage RTK. Fusionne issue-triage + pr-triage et produit une analyse croisée.
---
## Quand utiliser
- Hebdomadaire ou avant chaque sprint
- Quand le backlog PR/issues grossit rapidement
- Pour identifier les doublons avant de reviewer
---
## Workflow en 4 phases
### Phase 0 — Préconditions
```bash
git rev-parse --is-inside-work-tree
gh auth status
```
Vérifier que la date actuelle est connue (utiliser `date +%Y-%m-%d`).
---
### Phase 1 — Data gathering (parallèle)
Lancer les deux collectes simultanément :
**Issues** :
```bash
gh repo view --json nameWithOwner -q .nameWithOwner
gh issue list --state open --limit 150 \
--json number,title,author,createdAt,updatedAt,labels,assignees,body
gh issue list --state closed --limit 20 \
--json number,title,labels,closedAt
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
```
**PRs** :
```bash
# Fetcher toutes les PRs ouvertes — paginer si nécessaire (gh limite à 200 par appel)
gh pr list --state open --limit 200 \
--json number,title,author,createdAt,updatedAt,additions,deletions,changedFiles,isDraft,mergeable,reviewDecision,statusCheckRollup,body
# Si le repo a >200 PRs ouvertes, relancer avec --search pour paginer :
# gh pr list --state open --limit 200 --search "is:pr is:open sort:updated-desc" ...
# Pour chaque PR, récupérer les fichiers modifiés (nécessaire pour overlap detection)
# Prioriser les PRs candidates (même domaine, même auteur)
gh pr view {num} --json files --jq '[.files[].path] | join(",")'
```
---
### Phase 2 — Triage individuel
Exécuter les analyses de `/issue-triage` et `/pr-triage` séparément (même logique que les skills individuels) pour produire :
**Issues** :
- Catégorisation (Bug/Feature/Enhancement/Question/Duplicate)
- Risque (Rouge/Jaune/Vert)
- Staleness (>30j)
- Map `issue_number → [PR numbers]` via scan `fixes #N`, `closes #N`, `resolves #N`
**PRs** :
- Taille (XS/S/M/L/XL)
- CI status (clean/dirty)
- Nos PRs vs externes
- Overlaps (>50% fichiers communs entre 2 PRs)
- Clusters (auteur avec 3+ PRs)
Afficher les tableaux standards de chaque skill (voir SKILL.md de issue-triage et pr-triage pour le format exact).
---
### Phase 3 — Analyse croisée (cœur de ce skill)
C'est ici que ce skill apporte de la valeur au-delà des deux skills individuels.
#### 3.1 Double couverture — 2 PRs pour 1 issue
Pour chaque issue liée à ≥2 PRs (via scan des bodies + overlap fichiers) :
| Issue | PR1 (infos) | PR2 (infos) | Verdict recommandé |
|-------|-------------|-------------|-------------------|
| #N (titre) | PR#X — auteur, taille, CI | PR#Y — auteur, taille, CI | Garder la plus ciblée. Fermer/coordonner l'autre |
Règle de verdict :
- Préférer la plus petite (XS < S < M) si même scope
- Préférer CI clean sur CI dirty
- Préférer "nos PRs" si l'une est interne
- Si overlap de fichiers >80% → conflit quasi-certain, signaler
#### 3.2 Trous de couverture sécurité
Pour chaque issue rouge (#640-type security review) :
- Lister les sous-findings mentionnés dans le body
- Croiser avec les PRs existantes (mots-clés dans titre/body)
- Identifier les findings sans PR
Format :
```
## Issue #N — security review (finding par finding)
| Finding | PR associée | Status |
|---------|-------------|--------|
| Description finding 1 | PR#X | En review |
| **Description finding critique** | **AUCUNE** | ⚠️ Trou |
```
#### 3.3 P0/P1 bugs sans PR
Issues labelisées P0 ou P1 (ou mots-clés : "crash", "truncat", "cap", "hardcoded") sans aucune PR liée.
Format :
```
## Bugs critiques sans PR
| Issue | Titre | Pattern commun | Effort estimé |
|-------|-------|----------------|---------------|
```
Chercher un pattern commun (ex: "cap hardcodé", "exit code perdu") — si 3+ bugs partagent un pattern, suggérer un sprint groupé.
#### 3.4 Nos PRs dirty — causes probables
Pour chaque PR interne avec CI dirty ou CONFLICTING :
- Vérifier si un autre PR touche les mêmes fichiers
- Vérifier si un merge récent sur develop peut expliquer le conflit
- Recommander : rebase, fermeture, ou attente
Format :
```
## Nos PRs dirty
| PR | Issue(s) | Cause probable | Action |
|----|----------|----------------|--------|
```
#### 3.5 PRs sans issue trackée
PRs internes sans `fixes #N` dans le body — signaler pour traçabilité.
---
### Phase 4 — Output final
#### Afficher l'analyse croisée complète (sections 3.1 → 3.5)
Puis afficher le résumé chiffré :
```
## Résumé chiffré — YYYY-MM-DD
| Catégorie | Count |
|-----------|-------|
| PRs prêtes à merger (nos) | N |
| Quick wins externes | N |
| Double couverture (conflicts) | N paires |
| P0/P1 bugs sans PR | N |
| Security findings sans PR | N |
| Nos PRs dirty à rebaser | N |
| PRs à fermer (recommandé) | N |
```
#### Sauvegarder dans claudedocs
```bash
date +%Y-%m-%d # Pour construire le nom de fichier
```
Sauvegarder dans `claudedocs/RTK-YYYY-MM-DD.md` avec :
- Les tableaux de triage issues + PRs (Phase 2)
- L'analyse croisée complète (Phase 3)
- Le résumé chiffré
Confirmer : `Sauvegardé dans claudedocs/RTK-YYYY-MM-DD.md`
---
## Format du fichier sauvegardé
```markdown
# RTK Triage — YYYY-MM-DD
Croisement issues × PRs. {N} PRs ouvertes, {N} issues ouvertes.
---
## 1. Double couverture
...
## 2. Trous sécurité
...
## 3. P0/P1 sans PR
...
## 4. Nos PRs dirty
...
## 5. Nos PRs prêtes à merger
...
## 6. Quick wins externes
...
## 7. Actions prioritaires
(liste ordonnée par impact/urgence)
---
## Résumé chiffré
...
```
---
## Règles
- Langue : argument `en`/`fr`. Défaut : `fr`. Les commentaires GitHub restent toujours en anglais.
- Ne jamais poster de commentaires GitHub sans validation utilisateur (AskUserQuestion).
- Si >200 issues ou >200 PRs : prévenir l'utilisateur et paginer (relancer avec `--search` ou `gh api` avec pagination).
- L'analyse croisée (Phase 3) est toujours exécutée — c'est la valeur ajoutée de ce skill.
- Le fichier claudedocs est sauvegardé automatiquement sauf si l'utilisateur dit "no save".
-7
View File
@@ -8,13 +8,6 @@ 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
-13
View File
@@ -1,13 +0,0 @@
## Summary
<!-- What does this PR do? Keep it short (1-3 bullet points). -->
-
## Test plan
<!-- How did you verify this works? -->
- [ ] `cargo fmt --all && cargo clippy --all-targets && cargo test`
- [ ] Manual testing: `rtk <command>` output inspected
> **Important:** All PRs must target the `develop` branch (not `master`).
> See [CONTRIBUTING.md](../blob/master/CONTRIBUTING.md) for details.
-66
View File
@@ -1,66 +0,0 @@
# 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.
## Using rtk in this session
**Always prefix commands with `rtk` when running shell commands** — this reduces token consumption for every operation you perform.
```bash
# Instead of: Use:
git status rtk git status
git log -10 rtk git log -10
cargo test rtk cargo test
cargo clippy --all-targets rtk cargo clippy --all-targets
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
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
```
**Verify rtk is installed before starting:**
```bash
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. Run `which rtk` to check.
## Build, Test & Lint
```bash
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
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
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`.
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**: `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.
For the full contribution workflow, design philosophy, and new-filter checklist, see [CONTRIBUTING.md](../CONTRIBUTING.md).
-12
View File
@@ -1,12 +0,0 @@
{
"hooks": {
"PreToolUse": [
{
"type": "command",
"command": "rtk hook",
"cwd": ".",
"timeout": 5
}
]
}
}
-139
View File
@@ -1,139 +0,0 @@
# CI/CD Flows
## PR Quality Gates (ci.yml)
Trigger: pull_request to develop or master
```
┌──────────────────┐
│ PR opened │
└────────┬─────────┘
│
┌────────▼─────────┐
│ fmt │
└────────┬─────────┘
│
┌────────▼─────────┐
│ clippy │
└──┬───┬───┬───┬───┘
│ │ │ │
┌──────────────┘ │ │ └──────────────┐
│ ┌───────┘ └───────┐ │
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌───────────┐ ┌──────────┐
│ test │ │Security Scan │ │ benchmark │ │ validate │
│ ubuntu │ │ cargo audit │ │ >=80% │ │ ai agent │
│ windows │ │ (advisory) │ │ savings │ │ doc │
│ macos │ │ │ │ │ │ │
└──────┬───────┘ └──────┬───────┘ └─────┬─────┘ └────┬─────┘
│ │ │ │
└────────────────┴───────┬───────┴─────────────┘
│
┌──────────▼─────────┐
│ All must pass │
│ to merge │
└────────────────────┘
+ DCO check (independent, develop PRs only)
```
## Merge to develop — pre-release (cd.yml)
Trigger: push to develop | workflow_dispatch (not master) | Concurrency: cancel-in-progress
```
┌──────────────────┐
│ push to develop │
│ OR dispatch │
└────────┬─────────┘
│
┌────────▼──────────────────┐
│ pre-release │
│ compute next version │
│ from conventional commits │
│ tag = v{next}-rc.{run} │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ release.yml │
│ prerelease = true │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ Build │
│ 5 platforms + DEB + RPM │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ GitHub Release │
│ (pre-release badge) │
│ │
│ Discord: SKIPPED │
│ Homebrew: SKIPPED │
└──────────────────────────┘
```
## Merge to master — stable release (cd.yml)
Trigger: push to master (only) | Concurrency: never cancelled
```
┌──────────────────┐
│ push to master │
└────────┬─────────┘
│
┌────────▼──────────────────┐
│ release-please │
│ analyze conventional │
│ commits │
└────────┬──────────────────┘
│
┌────┴────────────────┐
│ │
no release release created
│ │
▼ ▼
┌──────────────┐ ┌───────────────────────┐
│ create/update│ │ release.yml │
│ release PR │ │ prerelease = false │
└──────────────┘ └───────────┬───────────┘
│
┌────────────▼────────────┐
│ Build │
│ 5 platforms + DEB + RPM │
└────────────┬────────────┘
│
┌────────────▼────────────┐
│ GitHub Release │
│ (stable, "Latest" badge) │
└──┬─────────┬─────────┬──┘
│ │ │
▼ ▼ ▼
Discord Homebrew latest
notify tap update tag
```
## Manual release (release.yml)
Trigger: workflow_dispatch
```
┌────────────────────────┐
│ workflow_dispatch │
│ inputs: tag, prerelease │
└───────────┬────────────┘
│
┌───────────▼────────────┐
│ Full build pipeline │
│ 5 platforms + DEB + RPM │
└───────────┬────────────┘
│
┌──────┴──────┐
│ │
prerelease=false prerelease=true
│ │
▼ ▼
Discord pre-release
Homebrew badge only
latest tag
```
+34
View File
@@ -0,0 +1,34 @@
name: Benchmark Token Savings
on:
push:
branches: [master, main]
pull_request:
jobs:
benchmark:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Build rtk
run: cargo build --release
- name: Install Python tools
run: |
pip install ruff pytest
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 'stable'
- name: Install Go tools
run: |
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run benchmark
run: ./scripts/benchmark.sh
-139
View File
@@ -1,139 +0,0 @@
name: CD
on:
workflow_dispatch:
push:
branches: [develop, master]
concurrency:
group: cd-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}
permissions:
contents: write
pull-requests: write
jobs:
# ═══════════════════════════════════════════════
# DEVELOP PATH: Pre-release
# ═══════════════════════════════════════════════
pre-release:
if: >-
github.ref == 'refs/heads/develop'
|| (github.event_name == 'workflow_dispatch' && github.ref != 'refs/heads/master')
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Compute version from commits like release please
id: tag
run: |
LATEST_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' --sort=-version:refname | grep -v '-' | head -1)
if [ -z "$LATEST_TAG" ]; then
echo "::error::No stable release tag found"
exit 1
fi
LATEST_VERSION="${LATEST_TAG#v}"
echo "Latest release: $LATEST_TAG"
# ── Analyse conventional commits since that tag ──
COMMITS=$(git log "${LATEST_TAG}..HEAD" --format="%s")
HAS_BREAKING=$(echo "$COMMITS" | grep -cE '^[a-z]+(\(.+\))?!:' || true)
HAS_FEAT=$(echo "$COMMITS" | grep -cE '^feat(\(.+\))?:' || true)
HAS_FIX=$(echo "$COMMITS" | grep -cE '^fix(\(.+\))?:' || true)
echo "Commits since ${LATEST_TAG} — breaking=$HAS_BREAKING feat=$HAS_FEAT fix=$HAS_FIX"
# ── Compute next version (matches release-please observed behaviour) ──
# Pre-1.0 with bump-minor-pre-major: breaking → minor, feat → minor, fix → patch
IFS='.' read -r MAJOR MINOR PATCH <<< "$LATEST_VERSION"
if [ "$MAJOR" -eq 0 ]; then
if [ "$HAS_BREAKING" -gt 0 ] || [ "$HAS_FEAT" -gt 0 ]; then
MINOR=$((MINOR + 1)); PATCH=0 # breaking or feat → minor
else
PATCH=$((PATCH + 1)) # fix only → patch
fi
else
if [ "$HAS_BREAKING" -gt 0 ]; then
MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 # breaking → major
elif [ "$HAS_FEAT" -gt 0 ]; then
MINOR=$((MINOR + 1)); PATCH=0 # feat → minor
else
PATCH=$((PATCH + 1)) # fix → patch
fi
fi
VERSION="${MAJOR}.${MINOR}.${PATCH}"
TAG="dev-${VERSION}-rc.${{ github.run_number }}"
echo "Next version: $VERSION (from $LATEST_VERSION)"
echo "Pre-release tag: $TAG"
# Safety: fail if this exact tag already exists
if git ls-remote --tags origin "refs/tags/${TAG}" | grep -q .; then
echo "::error::Tag ${TAG} already exists"
exit 1
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
build-prerelease:
name: Build pre-release
needs: pre-release
if: needs.pre-release.outputs.tag != ''
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.pre-release.outputs.tag }}
prerelease: true
permissions:
contents: write
secrets: inherit
# ═══════════════════════════════════════════════
# MASTER PATH: Full release
# ═══════════════════════════════════════════════
release-please:
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
steps:
- uses: googleapis/release-please-action@v4
id: release
with:
release-type: rust
package-name: rtk
build-release:
name: Build and upload release assets
needs: release-please
if: ${{ needs.release-please.outputs.release_created == 'true' }}
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.release-please.outputs.tag_name }}
permissions:
contents: write
secrets: inherit
update-latest-tag:
name: Update 'latest' tag
needs: [release-please, build-release]
if: ${{ needs.release-please.outputs.release_created == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update latest tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa latest -m "Latest stable release (${{ needs.release-please.outputs.tag_name }})"
git push origin latest --force
-375
View File
@@ -1,375 +0,0 @@
name: CI
on:
pull_request:
branches: [develop, master]
permissions:
contents: read
pull-requests: read
env:
CARGO_TERM_COLOR: always
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
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- run: cargo fmt --all -- --check
clippy:
name: clippy
needs: fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --all-targets
# ─── Parallel gates (all need code to compile) ───
test:
name: test (${{ matrix.os }})
needs: clippy
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --all
security:
name: Security Scan
needs: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Cargo Audit (CVE check)
run: |
echo "## Security Scan Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Dependency Vulnerabilities" >> $GITHUB_STEP_SUMMARY
if cargo audit 2>&1 | tee audit.log; then
echo "No known vulnerabilities detected" >> $GITHUB_STEP_SUMMARY
else
echo "Vulnerabilities found:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
cat audit.log >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Dependency vulnerabilities detected - review required"
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Critical files check
run: |
echo "### Critical Files Modified" >> $GITHUB_STEP_SUMMARY
CRITICAL=$(git diff --name-only origin/master...HEAD | grep -E "(runner|summary|tracking|init|pnpm_cmd|container)\.rs|Cargo\.toml|workflows/.*\.yml" || true)
if [ -n "$CRITICAL" ]; then
echo "**HIGH RISK**: The following critical files were modified:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$CRITICAL" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Manual security review by 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no shell injection vectors" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check input validation remains intact" >> $GITHUB_STEP_SUMMARY
echo "::warning::Critical RTK files modified - enhanced review required"
else
echo "No critical files modified" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Dangerous patterns scan
run: |
echo "### Dangerous Code Patterns" >> $GITHUB_STEP_SUMMARY
PATTERNS=$(git diff origin/master...HEAD | grep -E "Command::new\(\"sh\"|Command::new\(\"bash\"|\.env\(\"LD_PRELOAD|\.env\(\"PATH|reqwest::|std::net::|TcpStream|UdpSocket|unsafe \{|\.unwrap\(\) |panic!\(|todo!\(|unimplemented!\(" || true)
if [ -n "$PATTERNS" ]; then
echo "**Potentially dangerous patterns detected:**" >> $GITHUB_STEP_SUMMARY
echo '```diff' >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | head -30 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Security Concerns:**" >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | grep -q "Command::new" && echo "- Shell command execution detected" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.env\(\"" && echo "- Environment variable manipulation" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "reqwest::\|std::net::\|TcpStream\|UdpSocket" && echo "- Network operations added" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "unsafe" && echo "- Unsafe code blocks" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.unwrap\(\)\|panic!\(" && echo "- Panic-inducing code" >> $GITHUB_STEP_SUMMARY || true
echo "::warning::Dangerous code patterns detected - manual review required"
else
echo "No dangerous patterns detected" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: New dependencies check
run: |
echo "### Dependencies Changes" >> $GITHUB_STEP_SUMMARY
if git diff origin/master...HEAD Cargo.toml | grep -E "^\+.*=" | grep -v "^\+\+\+" > new_deps.txt; then
echo "**New dependencies added:**" >> $GITHUB_STEP_SUMMARY
echo '```toml' >> $GITHUB_STEP_SUMMARY
cat new_deps.txt >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Audit each new dependency on crates.io" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check maintainer reputation and download counts" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no typosquatting (e.g., 'reqwest' vs 'request')" >> $GITHUB_STEP_SUMMARY
echo "::warning::New dependencies require supply chain audit"
else
echo "No new dependencies added" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Clippy security lints
run: |
echo "### Clippy Security Lints" >> $GITHUB_STEP_SUMMARY
if cargo clippy --all-targets -- -W clippy::unwrap_used -W clippy::panic -W clippy::expect_used 2>&1 | tee clippy.log | grep -E "warning:|error:"; then
echo "Security-related lints triggered:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
grep -E "warning:|error:" clippy.log | head -20 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Clippy security lints failed"
else
echo "All security lints passed" >> $GITHUB_STEP_SUMMARY
fi
- name: Summary verdict
run: |
echo "---" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Security Review Verdict" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**This is an automated security scan. A human maintainer must:**" >> $GITHUB_STEP_SUMMARY
echo "1. Review all warnings above" >> $GITHUB_STEP_SUMMARY
echo "2. Verify PR intent matches actual code changes" >> $GITHUB_STEP_SUMMARY
echo "3. Check for subtle backdoors or logic bombs" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**For high-risk PRs (critical files modified):**" >> $GITHUB_STEP_SUMMARY
echo "- Require approval from 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- Test in isolated environment before merge" >> $GITHUB_STEP_SUMMARY
benchmark:
name: benchmark
needs: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build rtk
run: cargo build --release
- name: Install Python tools
run: pip install ruff pytest
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 'stable'
- name: Install Go tools
run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run benchmark
run: ./scripts/benchmark.sh
# ─── AI Doc Review: develop PRs only ───
doc-review:
name: doc review
if: github.base_ref == 'develop'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Gather PR context
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
PR_NUM=${{ github.event.pull_request.number }}
gh pr diff "$PR_NUM" --name-only > changed_files.txt
gh pr diff "$PR_NUM" | head -c 12000 > diff.txt
gh pr view "$PR_NUM" --json title,body --jq '"PR Title: \(.title)\nPR Description: \(.body)"' > pr_info.txt
- name: Build prompt files
run: |
# System prompt
cat <<'EOF' > system_prompt.txt
You are a documentation reviewer for the RTK project.
You will receive the project's CONTRIBUTING.md (which contains the documentation rules), the PR info, changed files, and diff.
Your job: based ONLY on the documentation rules in CONTRIBUTING.md, decide if the PR includes the required documentation updates.
IMPORTANT:
- CI/CD changes, test-only changes, and refactors with no user-facing impact do NOT require doc updates.
- Be practical, not pedantic. Small obvious fixes don't need CHANGELOG entries.
- Only flag missing docs when there is a clear user-facing change.
EOF
# User prompt: concatenate files (no printf, no variable expansion issues)
{
cat pr_info.txt
echo ""
echo "---"
echo "CONTRIBUTING.md:"
cat CONTRIBUTING.md
echo ""
echo "---"
echo "Changed files:"
cat changed_files.txt
echo ""
echo "---"
echo "Diff (may be truncated):"
cat diff.txt
} > user_prompt.txt
- name: AI documentation review
env:
ANTHROPIC_API_KEY: ${{ secrets.RTK_DOCS_ANTHROPIC_KEY }}
run: |
echo "## Documentation Review (AI)" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -z "$ANTHROPIC_API_KEY" ]; then
echo "::warning::ANTHROPIC_API_KEY not configured — skipping AI doc review"
echo "Skipped: ANTHROPIC_API_KEY secret not configured." >> $GITHUB_STEP_SUMMARY
exit 0
fi
echo "::group::Preparing API request"
echo "System prompt: $(wc -c < system_prompt.txt) bytes"
echo "User prompt: $(wc -c < user_prompt.txt) bytes"
SYSTEM_JSON=$(jq -Rs . < system_prompt.txt)
USER_JSON=$(jq -Rs . < user_prompt.txt)
echo "::endgroup::"
echo "::group::Calling Claude API (claude-sonnet-4-6)"
RESPONSE=$(curl -s -w "\n%{http_code}" https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d "{
\"model\": \"claude-sonnet-4-6\",
\"max_tokens\": 1024,
\"messages\": [{\"role\": \"user\", \"content\": $USER_JSON}],
\"system\": $SYSTEM_JSON,
\"output_config\": {
\"format\": {
\"type\": \"json_schema\",
\"schema\": {
\"type\": \"object\",
\"properties\": {
\"status\": {\"type\": \"string\", \"enum\": [\"PASS\", \"FAIL\"]},
\"reasoning\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},
\"files_to_update\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}
},
\"required\": [\"status\", \"reasoning\", \"files_to_update\"],
\"additionalProperties\": false
}
}
}
}")
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
echo "HTTP status: $HTTP_CODE"
echo "::endgroup::"
if [ "$HTTP_CODE" != "200" ]; then
echo "::warning::Claude API returned HTTP $HTTP_CODE — skipping doc review"
echo "Skipped: API error (HTTP $HTTP_CODE)" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$BODY" | head -10 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
exit 0
fi
# Parse structured JSON response
REVIEW_JSON=$(echo "$BODY" | jq -r '.content[0].text // empty')
if [ -z "$REVIEW_JSON" ]; then
echo "::warning::Empty response from Claude API — skipping doc review"
echo "Skipped: empty API response" >> $GITHUB_STEP_SUMMARY
echo "Raw response:"
echo "$BODY" | head -20
exit 0
fi
echo "::group::AI Review Result"
echo "$REVIEW_JSON" | jq .
echo "::endgroup::"
STATUS=$(echo "$REVIEW_JSON" | jq -r '.status')
REASONING=$(echo "$REVIEW_JSON" | jq -r '.reasoning[]' 2>/dev/null)
FILES=$(echo "$REVIEW_JSON" | jq -r '.files_to_update[]' 2>/dev/null)
echo "### Verdict: ${STATUS}" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -n "$REASONING" ]; then
echo "**Reasoning:**" >> $GITHUB_STEP_SUMMARY
echo "$REASONING" | while IFS= read -r line; do
echo "- $line" >> $GITHUB_STEP_SUMMARY
done
echo "" >> $GITHUB_STEP_SUMMARY
fi
if [ "$STATUS" = "FAIL" ] && [ -n "$FILES" ]; then
echo "**Files to update:**" >> $GITHUB_STEP_SUMMARY
echo "$FILES" | while IFS= read -r f; do
echo "- \`$f\`" >> $GITHUB_STEP_SUMMARY
done
echo "" >> $GITHUB_STEP_SUMMARY
fi
if [ "$STATUS" = "PASS" ]; then
echo "Documentation review passed."
elif [ "$STATUS" = "FAIL" ]; then
echo "::error::Documentation review failed — see summary for details"
exit 1
else
echo "::warning::Unexpected status '${STATUS}' — skipping"
echo "Unexpected AI response status: ${STATUS}" >> $GITHUB_STEP_SUMMARY
fi
+12
View File
@@ -0,0 +1,12 @@
name: DCO Check
on:
workflow_dispatch:
pull_request:
branches:
- develop
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: KineticCafe/actions-dco@v1
-43
View File
@@ -1,43 +0,0 @@
name: PR Target Branch Check
on:
pull_request_target:
types: [opened, edited]
jobs:
check-target:
runs-on: ubuntu-latest
# Skip develop→master PRs (maintainer releases)
if: >-
github.event.pull_request.base.ref == 'master' &&
github.event.pull_request.head.ref != 'develop'
steps:
- name: Add wrong-base label
uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
// Add label
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: ['wrong-base']
});
// Post comment
const body = `👋 Thanks for the PR! It looks like this targets \`master\`, but all PRs should target the **\`develop\`** branch.
Please update the base branch:
1. Click **Edit** at the top right of this PR
2. Change the base branch from \`master\` to \`develop\`
See [CONTRIBUTING.md](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/master/CONTRIBUTING.md) for details.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: body
});
+51
View File
@@ -0,0 +1,51 @@
name: Release Please
on:
push:
branches:
- master
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
steps:
- uses: googleapis/release-please-action@v4
id: release
with:
release-type: rust
package-name: rtk
build-release:
name: Build and upload release assets
needs: release-please
if: ${{ needs.release-please.outputs.release_created == 'true' }}
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.release-please.outputs.tag_name }}
permissions:
contents: write
secrets: inherit
update-latest-tag:
name: Update 'latest' tag
needs: [release-please, build-release]
if: ${{ needs.release-please.outputs.release_created == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update latest tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa latest -m "Latest stable release (${{ needs.release-please.outputs.tag_name }})"
git push origin latest --force
-12
View File
@@ -7,20 +7,11 @@ on:
description: 'Tag to release'
required: true
type: string
prerelease:
description: 'Mark as pre-release'
required: false
type: boolean
default: false
workflow_dispatch:
inputs:
tag:
description: 'Tag to release (e.g., v0.1.0)'
required: true
prerelease:
description: 'Mark as pre-release'
type: boolean
default: false
permissions:
contents: write
@@ -207,14 +198,12 @@ jobs:
with:
tag_name: ${{ steps.version.outputs.version }}
files: release/*
prerelease: ${{ inputs.prerelease }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
notify-discord:
name: Notify Discord
needs: [release]
if: ${{ !inputs.prerelease }}
runs-on: ubuntu-latest
steps:
- name: Get version
@@ -248,7 +237,6 @@ jobs:
homebrew:
name: Update Homebrew formula
needs: [release]
if: ${{ !inputs.prerelease }}
runs-on: ubuntu-latest
steps:
- name: Get version
+135
View File
@@ -0,0 +1,135 @@
name: Security Check
on:
pull_request:
branches: [ master ]
permissions:
contents: read
pull-requests: write
env:
CARGO_TERM_COLOR: always
jobs:
security:
name: Security Scan
runs-on: ubuntu-latest
steps:
- name: Checkout PR
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Cargo Audit (CVE check)
run: |
echo "## 🔍 Security Scan Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 📦 Dependency Vulnerabilities" >> $GITHUB_STEP_SUMMARY
if cargo audit 2>&1 | tee audit.log; then
echo "✅ No known vulnerabilities detected" >> $GITHUB_STEP_SUMMARY
else
echo "⚠️ Vulnerabilities found:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
cat audit.log >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Dependency vulnerabilities detected - review required"
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Critical files check
run: |
echo "### 🎯 Critical Files Modified" >> $GITHUB_STEP_SUMMARY
CRITICAL=$(git diff --name-only origin/master...HEAD | grep -E "(runner|summary|tracking|init|pnpm_cmd|container)\.rs|Cargo\.toml|workflows/.*\.yml" || true)
if [ -n "$CRITICAL" ]; then
echo "⚠️ **HIGH RISK**: The following critical files were modified:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$CRITICAL" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Manual security review by 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no shell injection vectors" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check input validation remains intact" >> $GITHUB_STEP_SUMMARY
echo "::warning::Critical RTK files modified - enhanced review required"
else
echo "✅ No critical files modified" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Dangerous patterns scan
run: |
echo "### 🚨 Dangerous Code Patterns" >> $GITHUB_STEP_SUMMARY
PATTERNS=$(git diff origin/master...HEAD | grep -E "Command::new\(\"sh\"|Command::new\(\"bash\"|\.env\(\"LD_PRELOAD|\.env\(\"PATH|reqwest::|std::net::|TcpStream|UdpSocket|unsafe \{|\.unwrap\(\) |panic!\(|todo!\(|unimplemented!\(" || true)
if [ -n "$PATTERNS" ]; then
echo "⚠️ **Potentially dangerous patterns detected:**" >> $GITHUB_STEP_SUMMARY
echo '```diff' >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | head -30 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Security Concerns:**" >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | grep -q "Command::new" && echo "- Shell command execution detected" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.env\(\"" && echo "- Environment variable manipulation" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "reqwest::\|std::net::\|TcpStream\|UdpSocket" && echo "- Network operations added" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "unsafe" && echo "- Unsafe code blocks" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.unwrap\(\)\|panic!\(" && echo "- Panic-inducing code" >> $GITHUB_STEP_SUMMARY || true
echo "::warning::Dangerous code patterns detected - manual review required"
else
echo "✅ No dangerous patterns detected" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: New dependencies check
run: |
echo "### 📚 Dependencies Changes" >> $GITHUB_STEP_SUMMARY
if git diff origin/master...HEAD Cargo.toml | grep -E "^\+.*=" | grep -v "^\+\+\+" > new_deps.txt; then
echo "⚠️ **New dependencies added:**" >> $GITHUB_STEP_SUMMARY
echo '```toml' >> $GITHUB_STEP_SUMMARY
cat new_deps.txt >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Audit each new dependency on crates.io" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check maintainer reputation and download counts" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no typosquatting (e.g., 'reqwest' vs 'request')" >> $GITHUB_STEP_SUMMARY
echo "::warning::New dependencies require supply chain audit"
else
echo "✅ No new dependencies added" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Clippy security lints
run: |
echo "### 🔧 Clippy Security Lints" >> $GITHUB_STEP_SUMMARY
if cargo clippy --all-targets -- -W clippy::unwrap_used -W clippy::panic -W clippy::expect_used 2>&1 | tee clippy.log | grep -E "warning:|error:"; then
echo "⚠️ Security-related lints triggered:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
grep -E "warning:|error:" clippy.log | head -20 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Clippy security lints failed"
else
echo "✅ All security lints passed" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Summary verdict
run: |
echo "---" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 🎯 Security Review Verdict" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**This is an automated security scan. A human maintainer must:**" >> $GITHUB_STEP_SUMMARY
echo "1. Review all warnings above" >> $GITHUB_STEP_SUMMARY
echo "2. Verify PR intent matches actual code changes" >> $GITHUB_STEP_SUMMARY
echo "3. Check for subtle backdoors or logic bombs" >> $GITHUB_STEP_SUMMARY
echo "4. Use \`/rtk-pr-security\` skill for comprehensive analysis" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**For high-risk PRs (critical files modified):**" >> $GITHUB_STEP_SUMMARY
echo "- Require approval from 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- Test in isolated environment before merge" >> $GITHUB_STEP_SUMMARY
+77
View File
@@ -0,0 +1,77 @@
name: Documentation Validation
on:
pull_request:
paths:
- 'src/**/*.rs'
- '**.md'
- '.claude/hooks/*.sh'
push:
branches:
- master
- feat/**
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate documentation consistency
run: bash scripts/validate-docs.sh
- name: Check module count consistency
run: |
MAIN_MODULES=$(grep -c '^mod ' src/main.rs)
# Check ARCHITECTURE.md if it exists
if [ -f "ARCHITECTURE.md" ]; then
ARCH_MODULES=$(grep 'Total:.*modules' ARCHITECTURE.md | grep -o '[0-9]\+' | head -1)
if [ -n "$ARCH_MODULES" ] && [ "$MAIN_MODULES" != "$ARCH_MODULES" ]; then
echo "❌ Module count mismatch"
echo "main.rs: $MAIN_MODULES modules"
echo "ARCHITECTURE.md: $ARCH_MODULES modules"
exit 1
fi
fi
echo "✅ Module count consistent: $MAIN_MODULES modules"
- name: Verify Python/Go commands documented
run: |
for cmd in ruff pytest pip go golangci; do
if ! grep -q "$cmd" README.md; then
echo "❌ README.md missing Python/Go command: $cmd"
exit 1
fi
if ! grep -q "$cmd" CLAUDE.md; then
echo "❌ CLAUDE.md missing Python/Go command: $cmd"
exit 1
fi
done
echo "✅ All Python/Go commands documented"
- name: Verify hook coverage
run: |
HOOK_FILE=".claude/hooks/rtk-rewrite.sh"
if [ ! -f "$HOOK_FILE" ]; then
echo "❌ Hook file not found: $HOOK_FILE"
exit 1
fi
# Since PR #241, the hook delegates to `rtk rewrite` (single source of truth).
# Command coverage is now in src/discover/registry.rs, not the hook bash script.
if ! grep -q "rtk rewrite" "$HOOK_FILE"; then
echo "❌ Hook does not delegate to 'rtk rewrite'"
exit 1
fi
# Verify all Python/Go commands are covered in the registry
# Since PR #241, constants live in src/discover/rules.rs (extracted from registry.rs)
for cmd in ruff pytest pip golangci; do
if ! grep -qr "\"$cmd\"" src/discover/; then
echo "❌ Registry missing rewrite_prefixes for: $cmd"
exit 1
fi
done
echo "✅ Hook delegates to rtk rewrite, registry covers all Python/Go commands"
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.34.1"
".": "0.29.0"
}
+512 -81
View File
@@ -1,8 +1,8 @@
# rtk Architecture Documentation
> **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).
> **rtk (Rust Token Killer)** - A high-performance CLI proxy that minimizes LLM token consumption through intelligent output filtering and compression.
**rtk (Rust Token Killer)** is a high-performance CLI proxy that minimizes LLM token consumption through intelligent output filtering and compression.
This document provides a comprehensive architectural overview of rtk, including system design, data flows, module organization, and implementation patterns.
---
@@ -17,16 +17,51 @@
7. [Global Flags Architecture](#global-flags-architecture)
8. [Error Handling](#error-handling)
9. [Configuration System](#configuration-system)
10. [Common Patterns](#common-patterns)
10. [Module Development Pattern](#module-development-pattern)
11. [Build Optimizations](#build-optimizations)
12. [Extensibility Guide](#extensibility-guide)
13. [Architecture Decision Records](#architecture-decision-records)
---
## System Overview
> For the proxy pattern diagram and key components table, see [docs/TECHNICAL.md](docs/TECHNICAL.md#2-architecture-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 |
### Design Principles
@@ -38,7 +73,39 @@
### Hook Architecture (v0.9.5+)
> 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).
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)
```
Two hook strategies:
@@ -157,38 +224,81 @@ Database: ~/.local/share/rtk/history.db
## Module Organization
### 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:**
### Complete Module Map (30 Modules)
```
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
┌────────────────────────────────────────────────────────────────────────┐
│ 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% ✓
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 ✓
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 ✓
```
**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
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
### Module Count Breakdown
- **Command Modules**: 42 (directly exposed to users)
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, etc.)
- **Command Modules**: 34 (directly exposed to users)
- **Infrastructure Modules**: 20 (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)
@@ -307,7 +417,7 @@ Strategy Modules Technique Reduction
Used by: go test (NDJSON stream, interleaved package events)
```
### Code Filtering Levels (src/core/filter.rs)
### Code Filtering Levels (filter.rs)
```rust
// FilterLevel::None - Keep everything
@@ -367,7 +477,7 @@ Mirrors: lint, prettier Mirrors: git, cargo
```
┌────────────────────────────────────────────────────────────────────────┐
│ Python Commands │
│ Python Commands (3 modules) │
└────────────────────────────────────────────────────────────────────────┘
Module Strategy Output Format Savings
@@ -424,7 +534,7 @@ Commands respect active virtualenv via `sys.executable` paths.
```
┌────────────────────────────────────────────────────────────────────────┐
│ Go Commands │
│ Go Commands (2 modules) │
└────────────────────────────────────────────────────────────────────────┘
Module Strategy Output Format Savings
@@ -461,7 +571,29 @@ golangci_cmd.rs JSON PARSING JSON API 85%
#### Sub-Enum Pattern (go_cmd.rs)
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.
```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),
}
}
```
**Why Sub-Enum?**
- `go test/build/vet` are semantically related (core Go toolchain)
@@ -473,37 +605,6 @@ Uses `Commands::Go { #[command(subcommand)] command: GoCommand }` in main.rs, wi
- Different output format (JSON API vs text)
- Distinct use case (comprehensive linting vs single-tool diagnostics)
### Ruby Module Architecture
**Added**: 2026-03-15
**Motivation**: Ruby on Rails development support (minitest, RSpec, RuboCop, Bundler)
Ruby modules follow the standalone command pattern (like Python) with a shared `ruby_exec()` utility for auto-detecting `bundle exec`.
```
Module Strategy Output Format Savings
─────────────────────────────────────────────────────────────────────────
rake_cmd.rs STATE MACHINE Text parser 85-90%
Minitest output (rake test / rails test)
→ State machine: Header → Running → Failures → Summary
→ All pass: "ok rake test: 8 runs, 0 failures"
→ Failures: summary + numbered failure details
rspec_cmd.rs JSON/TEXT DUAL JSON → 60%+ 60%+
Injects --format json, parses structured results
→ Fallback to text state machine when JSON unavailable
→ Strips Spring, SimpleCov, DEPRECATION, Capybara noise
rubocop_cmd.rs JSON PARSING JSON API 60%+
Injects --format json, groups by cop/severity
→ Skips JSON injection in autocorrect mode (-a, -A)
bundle-install.toml TOML FILTER Text rules 90%+
→ Strips "Using" lines, short-circuits to "ok bundle: complete"
```
**Shared**: `ruby_exec(tool)` in utils.rs auto-detects `bundle exec` when `Gemfile` exists. Used by rake_cmd, rspec_cmd, rubocop_cmd.
### Format Strategy Decision Tree
```
@@ -527,6 +628,38 @@ 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
```
@@ -569,13 +702,30 @@ When adding Python/Go module support:
## Shared Infrastructure
### Utilities Layer
### Utilities Layer (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.
```
┌────────────────────────────────────────────────────────────────────────┐
│ 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)
```
### Package Manager Detection Pattern
**Critical Infrastructure for JS/TS Stack**
**Critical Infrastructure for JS/TS Stack (8 modules)**
```
┌────────────────────────────────────────────────────────────────────────┐
@@ -732,7 +882,15 @@ Flow:
### Thread Safety
Single-threaded execution with `Mutex<Option<Tracker>>` for future-proofing. No multi-threading currently, but safe concurrent access is possible if needed.
```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.
---
@@ -870,11 +1028,43 @@ Modules with Exit Code Preservation:
## Configuration System
### Configuration
### Two-Tier Configuration
> For config file format, tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
```
┌────────────────────────────────────────────────────────────────────────┐
│ Configuration Architecture │
└────────────────────────────────────────────────────────────────────────┘
Two tiers: **User settings** (`~/.config/rtk/config.toml`) and **LLM integration** (CLAUDE.md via `rtk init`).
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
```
### Initialization Flow
@@ -911,7 +1101,85 @@ Success: "✓ Initialized rtk for LLM integration"
---
## Common Patterns
## 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
#### 1. Package Manager Detection (JS/TS modules)
@@ -930,7 +1198,18 @@ let mut cmd = if is_pnpm {
};
```
#### 2. Verbosity Guards
#### 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
```rust
if verbose > 0 {
@@ -993,11 +1272,162 @@ 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
> 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).
### 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
---
@@ -1034,11 +1464,11 @@ Overhead Sources:
## 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)
---
@@ -1056,5 +1486,6 @@ Overhead Sources:
---
**Last Updated**: 2026-03-24
**Architecture Version**: 3.1
**Last Updated**: 2026-02-22
**Architecture Version**: 2.2
**rtk Version**: 0.28.2
-155
View File
@@ -5,160 +5,6 @@ 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)
### Features
* **init:** add --copilot flag for GitHub Copilot integration ([9e19aac](https://github.com/rtk-ai/rtk/commit/9e19aac75e790ecbfd1dc5b2d01786f6b9edf506)), closes [#823](https://github.com/rtk-ai/rtk/issues/823)
### Bug Fixes
* **diff:** correct truncation overflow count in condense_unified_diff ([5399f83](https://github.com/rtk-ai/rtk/commit/5399f836a5c642121f0f6e7812ff4131d84d0509))
* **diff:** never truncate diff content — show all changes in full ([80fc29a](https://github.com/rtk-ai/rtk/commit/80fc29a839f51ef605474037e1a8fd86b4aac05a)), closes [#827](https://github.com/rtk-ai/rtk/issues/827)
* **git:** replace vague truncation markers with exact counts ([185fb97](https://github.com/rtk-ai/rtk/commit/185fb97061517922ea5844d8c6008f2eb86fd55d))
* **merge:** resolve conflict with develop in diff_cmd.rs ([6a5ae14](https://github.com/rtk-ai/rtk/commit/6a5ae1484b32c38bd99baca925175ae610e3d1e3))
* **read:** default to no filtering — show full file content ([5e0f3ba](https://github.com/rtk-ai/rtk/commit/5e0f3ba774eab52f8ca2ac603e2ae4eae79b2edc)), closes [#822](https://github.com/rtk-ai/rtk/issues/822)
* **read:** detect binary files and prevent empty output on filter failure ([8886c14](https://github.com/rtk-ai/rtk/commit/8886c14c9cf97fb4413efec3be8e50fdb84824e9)), closes [#822](https://github.com/rtk-ai/rtk/issues/822)
* rewrite swift test commands ([599ad25](https://github.com/rtk-ai/rtk/commit/599ad25deb0f8dc9ecab37f4bbe26324dac07b2e))
* truncation accuracy + Copilot init + binary file detection ([966bcbe](https://github.com/rtk-ai/rtk/commit/966bcbe638be18bbaba4298df985804643f82c85))
* **truncation:** accurate overflow counts and omission indicators ([58a9633](https://github.com/rtk-ai/rtk/commit/58a963347467613d48db05ad56bc8f1f3a06b65d))
## [Unreleased]
### 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))
## [0.33.1](https://github.com/rtk-ai/rtk/compare/v0.33.0...v0.33.1) (2026-03-25)
### Bug Fixes
* **cicd:** dev- prefix for pre-release tags ([522bd64](https://github.com/rtk-ai/rtk/commit/522bd648c8cae41f6cadedcd40a96d879c6ecf0a))
* **cicd:** use dev- prefix for pre-release tags ([9c21275](https://github.com/rtk-ai/rtk/commit/9c212752fc0401820f8665198f00882684496175))
* **cicd:** use dev- prefix for pre-release tags to avoid polluting release-please ([32c67e0](https://github.com/rtk-ai/rtk/commit/32c67e01326374f0365602f61542a3639a8f121b))
* hook security + stderr redirects + version bump ([#807](https://github.com/rtk-ai/rtk/issues/807)) ([0649e97](https://github.com/rtk-ai/rtk/commit/0649e974fb8f27778ef0d22aa97905d9ebc8f03c))
* **hook:** respect Claude Code deny/ask permission rules on rewrite ([a051a6f](https://github.com/rtk-ai/rtk/commit/a051a6f5e56c7ee59375a365580bced634e29c02))
* strip trailing stderr redirects before rewrite matching ([#530](https://github.com/rtk-ai/rtk/issues/530)) ([edd9c02](https://github.com/rtk-ai/rtk/commit/edd9c02e892b297a7e349031b61ef971c982b53d))
* strip trailing stderr redirects before rewrite matching ([#530](https://github.com/rtk-ai/rtk/issues/530)) ([36a6f48](https://github.com/rtk-ai/rtk/commit/36a6f482296d6fc85f8116040a16de2e128733f8))
## [0.33.0-rc.54](https://github.com/rtk-ai/rtk/compare/v0.32.0-rc.54...v0.33.0-rc.54) (2026-03-24)
### Features
* **ruby:** add Ruby on Rails support (rspec, rubocop, rake, bundle) ([#724](https://github.com/rtk-ai/rtk/issues/724)) ([15bc0f8](https://github.com/rtk-ai/rtk/commit/15bc0f8d6e135371688d5fd42decc6d8a99454f0))
### Bug Fixes
* add telemetry documentation and init notice ([#640](https://github.com/rtk-ai/rtk/issues/640)) ([#788](https://github.com/rtk-ai/rtk/issues/788)) ([0eecee5](https://github.com/rtk-ai/rtk/commit/0eecee5bf35ffd8b13f36a59ec39bd52626948d3))
* **cargo:** preserve test compile diagnostics ([97b6878](https://github.com/rtk-ai/rtk/commit/97b68783f50d209c2c599ae42cc638520749e668))
* **cicd:** explicit fetch tag ([3b94b60](https://github.com/rtk-ai/rtk/commit/3b94b602ed24b9ecec597ce001e59f325caaadd4))
* **cicd:** gete release like tag for pre-release ([53bc81e](https://github.com/rtk-ai/rtk/commit/53bc81e9e6d3d0876fb1a23dbf6f08bc074b68be))
* **cicd:** issue 668 - pre release tag ([200af43](https://github.com/rtk-ai/rtk/commit/200af436d48dd2539cb00652b082f25c57873c9c))
* **cicd:** missing doc ([8657494](https://github.com/rtk-ai/rtk/commit/865749438e67f6da7f719d054bf377d857925ad3))
* **cicd:** pre-release correct tag ([1536667](https://github.com/rtk-ai/rtk/commit/15366678adeece701f38e91204128b070c0e3fc4))
* **dotnet:** TRX injection for Microsoft.Testing.Platform projects ([8eefef1](https://github.com/rtk-ai/rtk/commit/8eefef1b496035ce898effc5446e6851084d6fa4))
* **formatter:** show full error message for test failures ([#690](https://github.com/rtk-ai/rtk/issues/690)) ([dc6b026](https://github.com/rtk-ai/rtk/commit/dc6b0260ab4c1bdbccb4b775d879eb473b212c21))
* **formatter:** show full error message for test failures ([#690](https://github.com/rtk-ai/rtk/issues/690)) ([f7b09fc](https://github.com/rtk-ai/rtk/commit/f7b09fc86a693acf2b52954215ff0c4e6c5d03f9))
* **gh:** passthrough --comments flag in issue/pr view ([75cd223](https://github.com/rtk-ai/rtk/commit/75cd2232e274f898d8a335ba866fc507ce64b949))
* **gh:** passthrough --comments flag in issue/pr view ([fdeb09f](https://github.com/rtk-ai/rtk/commit/fdeb09fb93564e795711e9a531d2e2e20187c3a7)), closes [#720](https://github.com/rtk-ai/rtk/issues/720)
* **gh:** skip compact_diff for --name-only/--stat flags in pr diff ([2ef0690](https://github.com/rtk-ai/rtk/commit/2ef0690767eb733c705e4de56d02c64696a4acc6)), closes [#730](https://github.com/rtk-ai/rtk/issues/730)
* **gh:** skip compact_diff for --name-only/--stat in pr diff ([c576249](https://github.com/rtk-ai/rtk/commit/c57624931a96181f869645817fdd96bc056da044))
* **golangci-lint:** add v2 compatibility with runtime version detection ([95a4961](https://github.com/rtk-ai/rtk/commit/95a4961e4aa3ba5307b3dfad246c6168c4caeab8))
* **golangci:** use resolved_command for version detection, move test fixture to file ([6aa5e90](https://github.com/rtk-ai/rtk/commit/6aa5e90dc466f87c88a2401b4eb2aa0f323379f4))
* increase signal in git diff, git log, and json filters ([#621](https://github.com/rtk-ai/rtk/issues/621)) ([#708](https://github.com/rtk-ai/rtk/issues/708)) ([4edc3fc](https://github.com/rtk-ai/rtk/commit/4edc3fc0838e25ee6d1754c7e987b5507742f600))
* **playwright:** add tee_and_hint pass-through on failure ([#690](https://github.com/rtk-ai/rtk/issues/690)) ([b4ccf04](https://github.com/rtk-ai/rtk/commit/b4ccf046f59ce6ed1396e4d8c46f8a35152d6d09))
* preserve cargo test compile diagnostics ([15d5beb](https://github.com/rtk-ai/rtk/commit/15d5beb9f70caf1f84e9b506faaf840c70c1cf4e))
* **ruby:** use rails test for positional file args in rtk rake ([ec92c43](https://github.com/rtk-ai/rtk/commit/ec92c43f231eb2321a4b423b0eb8487f98161aac))
* **ruby:** use rails test for positional file args in rtk rake ([138e914](https://github.com/rtk-ai/rtk/commit/138e91411b4802e445a97429056cca73282d09e1))
* update Discord invite link ([#711](https://github.com/rtk-ai/rtk/issues/711)) ([#786](https://github.com/rtk-ai/rtk/issues/786)) ([af56573](https://github.com/rtk-ai/rtk/commit/af56573ae2b234123e4685fd945980e644f40fa3))
## [Unreleased]
### Bug Fixes
* **hook:** respect Claude Code deny/ask permission rules on rewrite — hook now checks settings.json before rewriting commands, preventing bypass of user-configured deny/ask permissions
* **git:** replace symbol prefixes (`* branch`, `+ Staged:`, `~ Modified:`, `? Untracked:`) with plain lowercase labels (`branch:`, `staged:`, `modified:`, `untracked:`) in git status output
* **ruby:** use `rails test` instead of `rake test` when positional file args are passed — `rake test` ignores positional files and only supports `TEST=path`
### Features
* **ruby:** add RSpec test runner filter with JSON parsing and text fallback (60%+ reduction)
* **ruby:** add RuboCop linter filter with JSON parsing, grouped by cop/severity (60%+ reduction)
* **ruby:** add Minitest filter for `rake test` / `rails test` with state machine parser (85-90% reduction)
* **ruby:** add TOML filter for `bundle install/update` — strip `Using` lines (90%+ reduction)
* **ruby:** add `ruby_exec()` shared utility for auto-detecting `bundle exec` when Gemfile exists
* **ruby:** add discover/rewrite rules for rake, rails, rspec, rubocop, and bundle commands
### Bug Fixes
* **cargo:** preserve compile diagnostics when `cargo test` fails before any test suites run
## [0.31.0](https://github.com/rtk-ai/rtk/compare/v0.30.1...v0.31.0) (2026-03-19)
### Features
* 9-tool AI agent support + emoji removal ([#704](https://github.com/rtk-ai/rtk/issues/704)) ([737dada](https://github.com/rtk-ai/rtk/commit/737dada4a56c0d7a482cc438e7280340d634f75d))
## [0.30.1](https://github.com/rtk-ai/rtk/compare/v0.30.0...v0.30.1) (2026-03-18)
### Bug Fixes
* remove all decorative emojis from CLI output ([#687](https://github.com/rtk-ai/rtk/issues/687)) ([#686](https://github.com/rtk-ai/rtk/issues/686)) ([4792008](https://github.com/rtk-ai/rtk/commit/4792008fc15553cbb9aeaa602f773a5f8f7f7afe))
## [0.30.0](https://github.com/rtk-ai/rtk/compare/v0.29.0...v0.30.0) (2026-03-16)
### Features
* add rtk session command for adoption overview ([be67d66](https://github.com/rtk-ai/rtk/commit/be67d660100c06a0751c08d943dc884ad5bff6a3))
* add rtk session command for adoption overview ([12d44c4](https://github.com/rtk-ai/rtk/commit/12d44c4068d7d4f65d5bd7551af29ab5a2352ed1)), closes [#487](https://github.com/rtk-ai/rtk/issues/487)
* add worktree slash commands for isolated development ([#364](https://github.com/rtk-ai/rtk/issues/364)) ([ab83e79](https://github.com/rtk-ai/rtk/commit/ab83e7933ebc26ca76f843d33285729875efb913))
* Claude Code tooling — 2 agents, 7 commands, 2 rules, 4 skills ([#491](https://github.com/rtk-ai/rtk/issues/491)) ([7b7a5ae](https://github.com/rtk-ai/rtk/commit/7b7a5ae4b6d23fbb882ed7d5e815e2ed0672c46c))
### Bug Fixes
* 6 critical bugs — exit codes, unwrap, lazy regex ([#626](https://github.com/rtk-ai/rtk/issues/626)) ([3005ebd](https://github.com/rtk-ai/rtk/commit/3005ebd0ad07912ae919687f6d3d49482aabaeac))
* align 7 TOML filter tests with on_empty behavior ([04ed6d8](https://github.com/rtk-ai/rtk/commit/04ed6d8c314dcbf86b147903b5a7f1cd956dc980))
* align 7 TOML filter tests with on_empty behavior ([9a499b9](https://github.com/rtk-ai/rtk/commit/9a499b9714e97a553d5603680ab1f843034acf28))
* **cicd-docs:** add agent reviewer + some contribute guidelines ([de710f4](https://github.com/rtk-ai/rtk/commit/de710f4ea30c333130c46f8a2e2c5b6b9edd4889))
* **cicd-docs:** some logs to understand what is happening when check docs ([191ea9a](https://github.com/rtk-ai/rtk/commit/191ea9af9f99ee78d74385fe1952ce83045e4afe))
* **cicd:** Clean cicd, rework depends and add pre-release ([d24a765](https://github.com/rtk-ai/rtk/commit/d24a7650e26aca89224a3ec5d263f1ce7c7121d6))
* **cicd:** Clean cicd, rework depends and add pre-release ([6303e95](https://github.com/rtk-ai/rtk/commit/6303e9530a379a8e3939e6c122ab4cf07cb16751))
* **cicd:** clippy - do not treat warn as error ([5da5db2](https://github.com/rtk-ai/rtk/commit/5da5db222d9927394995ccaeb3afc103e80c22bd))
* failing context for doc analyze -&gt; cat from files ([c6b7db2](https://github.com/rtk-ai/rtk/commit/c6b7db2e5a6cd9a05262e934b4fc7a44c699c3b0))
* git log --oneline regression drops commits ([#619](https://github.com/rtk-ai/rtk/issues/619)) ([8e85d67](https://github.com/rtk-ai/rtk/commit/8e85d676d78b12d2c421bb892f93971fc222fb39))
* improve adoption metric by detecting hook-rewritten commands ([eb8a2c4](https://github.com/rtk-ai/rtk/commit/eb8a2c4a71072870fca4b64e90189a4453acff84))
* normalize binlogs CRLF ([5344af9](https://github.com/rtk-ai/rtk/commit/5344af9a51f06b5dc42692e42c948ff11a3173c6))
* preserve commit body in git log output ([e189bbb](https://github.com/rtk-ai/rtk/commit/e189bbbe749120eda4d98a2130937269d8c0e92a))
* preserve first line of commit body in git log output ([c3416eb](https://github.com/rtk-ai/rtk/commit/c3416eb45f2f97297ec149d296a6a500697d302b))
* remove version check from validate-docs CI ([#476](https://github.com/rtk-ai/rtk/issues/476)) ([#543](https://github.com/rtk-ai/rtk/issues/543)) ([6e61c24](https://github.com/rtk-ai/rtk/commit/6e61c2447cc03af94220ce6ce83686f155e18086))
* split chained commands in adoption metric ([127f85c](https://github.com/rtk-ai/rtk/commit/127f85c02efd52a64e461005fa142d05f81615f8))
* support git -C &lt;path&gt; in rewrite registry ([c916bab](https://github.com/rtk-ai/rtk/commit/c916bab33ae9760b234fd720c944a849141f0d2e)), closes [#555](https://github.com/rtk-ai/rtk/issues/555)
* test-all.sh aborts when gt not installed ([#500](https://github.com/rtk-ai/rtk/issues/500)) ([#544](https://github.com/rtk-ai/rtk/issues/544)) ([26f5473](https://github.com/rtk-ai/rtk/commit/26f547371798ad32aed3569965303bc4857789ed))
* trust boundary followup — TOML key typo + missing meta commands ([#625](https://github.com/rtk-ai/rtk/issues/625)) ([8d8e188](https://github.com/rtk-ai/rtk/commit/8d8e188705e5784829693a83b2076d6118154764))
* windows path fix for git tests ([0a904e2](https://github.com/rtk-ai/rtk/commit/0a904e264d58f8f4b5f10e37ec3b11f717458fe0))
## [0.29.0](https://github.com/rtk-ai/rtk/compare/v0.28.2...v0.29.0) (2026-03-12)
@@ -254,7 +100,6 @@ 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))
+478 -42
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,51 +29,133 @@ If `rtk gain` fails, you have the wrong package installed.
### Build & Run
```bash
# Development build
cargo build # raw
rtk cargo build # preferred (token-optimized)
cargo build --release # release build (optimized)
cargo run -- <command> # run directly
cargo install --path . # install locally
# Release build (optimized)
cargo build --release
rtk cargo build --release
# Run directly
cargo run -- <command>
# Install locally
cargo install --path .
```
### Testing
```bash
cargo test # all tests
# Run all tests
cargo test # raw
rtk cargo test # preferred (token-optimized)
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)
# 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>::
```
### Linting & Quality
```bash
cargo check # check without building
cargo fmt # format code
cargo clippy --all-targets # all clippy lints
rtk cargo clippy --all-targets # preferred
```
# Check without building
cargo check # raw
rtk cargo check # preferred (token-optimized)
### Pre-commit Gate
```bash
cargo fmt --all && cargo clippy --all-targets && cargo test --all
# 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
```
### Package Building
```bash
cargo deb # DEB package (needs cargo-deb)
cargo generate-rpm # RPM package (needs cargo-generate-rpm, after release build)
# 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
```
## Architecture
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`.
### Core Design Pattern
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
rtk uses a **command proxy architecture** with specialized modules for each output type:
Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header. Browse `src/cmds/*/` to discover available filters.
```
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
```
### Proxy Mode
@@ -85,30 +167,281 @@ Module responsibilities are documented in each folder's `README.md` and each fil
- **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
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
# 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
```
All proxy commands appear in `rtk gain --history` with 0% savings (input = output).
**Tracking**: All proxy commands appear in `rtk gain --history` with 0% savings (input = output) but preserve usage statistics.
## Coding Rules
### Critical Implementation Details
Rust patterns, error handling, and anti-patterns are defined in `.claude/rules/rust-patterns.md` (auto-loaded into context). Key points:
**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)
- **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
**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 ✓")
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.
**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)
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).
### 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) |
| 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, 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)
## 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
## Build Verification (Mandatory)
@@ -122,14 +455,55 @@ 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
hyperfine 'rtk git log -10' --warmup 3 # before
# Benchmark before/after
hyperfine 'rtk git log -10' --warmup 3
cargo build --release
hyperfine 'target/release/rtk git log -10' --warmup 3 # after (should be <10ms)
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
```
## 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**:
@@ -167,3 +541,65 @@ 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
```
+57 -124
View File
@@ -7,7 +7,6 @@
- [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
---
@@ -23,131 +22,42 @@
|------|----------|
| **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, new features (for core features, discuss with maintainers before) |
| **Build** | New filters, new command support, performance improvements |
| **Review** | Review open PRs, test changes locally, leave constructive feedback |
| **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).
| **Document** | Improve docs, add usage examples, clarify existing docs |
---
## Branch Naming Convention
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.
Every branch **must** follow one of these prefixes to identify the level of change:
| Prefix | Semver Impact | When to Use |
|--------|---------------|-------------|
| `fix/` | Patch | Bug fixes, corrections, minor adjustments |
| `feat/` | Minor | New features, new filters, new command support |
| `chore/` | Major | Breaking changes, API changes, removed functionality |
| `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 |
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>`.
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.**
Examples:
```
fix/git-log-filter-drops-merge-commits
feat/kubectl-add-pod-list-filter
chore/release-pipeline-cleanup
fix(git): log-filter-drops-merge-commits
feat(kubectl): add-pod-list-filter
chore(proxy): remove-deprecated-flags
```
---
## Pull Request Process
### Scope Rules
**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:
- 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
@@ -158,7 +68,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. This will be moved in the future.
**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.
### 3. Add Tests
@@ -168,16 +78,15 @@ Every change **must** include tests. See [Testing](#testing) below.
Every change **must** include documentation updates. See [Documentation](#documentation) below.
### Contributor License Agreement (CLA)
### Developer Certificate of Origin (DCO)
All contributions require signing our [Contributor License Agreement (CLA)](CLA.md) before being merged.
All contributions must be signed off (git commit -s) to certify
you have the right to submit the code under the project's license.
By signing, you certify that:
- You have authored 100% of the contribution, or have the necessary rights to submit it.
- You grant **rtk-ai** and **rtk-ai Labs** a perpetual, worldwide, royalty-free license to use your contribution — including in commercial products such as **rtk Pro** — under the [Apache License 2.0](LICENSE).
- If your employer has rights over your work, you have obtained their permission.
Expected format: Signed-off-by: Your Name your@email.com
https://developercertificate.org/
**This is automatic.** When you open a Pull Request, [CLA Assistant](https://cla-assistant.io) will post a comment asking you to sign. Click the link in that comment to sign with your GitHub account. You only need to sign once.
By signing off, you agree to the DCO.
### 5. Merge into `develop`
@@ -203,8 +112,6 @@ 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 |
@@ -214,6 +121,36 @@ For how to write tests (fixtures, snapshots, token savings verification), see [d
| **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:
@@ -235,19 +172,15 @@ cargo fmt --all --check && cargo clippy --all-targets && cargo test
## Documentation
Every change **must** include documentation updates. Use this table to find which docs to update:
Every change **must** include documentation updates. Update the relevant file(s) depending on what you changed:
| 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) |
| 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) |
| Bug fix or breaking change | [CHANGELOG.md](CHANGELOG.md) |
**Navigation**: [CONTRIBUTING.md](CONTRIBUTING.md) (you are here) → [docs/TECHNICAL.md](docs/TECHNICAL.md) (architecture + flow) → each folder's `README.md` (implementation details).
| Tracking / analytics | [docs/tracking.md](docs/tracking.md) |
Keep documentation concise and practical -- examples over explanations.
Generated
+2 -14
View File
@@ -100,17 +100,6 @@ 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"
@@ -903,16 +892,14 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.34.1"
version = "0.29.0"
dependencies = [
"anyhow",
"automod",
"chrono",
"clap",
"colored",
"dirs",
"flate2",
"getrandom 0.4.2",
"hostname",
"ignore",
"lazy_static",
@@ -923,6 +910,7 @@ dependencies = [
"serde_json",
"sha2",
"tempfile",
"thiserror",
"toml",
"ureq",
"walkdir",
+2 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.34.1"
version = "0.29.0"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
@@ -25,15 +25,14 @@ 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"
+17 -186
View File
@@ -1,190 +1,21 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
MIT License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (c) 2024 Patrick Szymkowiak
1. Definitions.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2024 rtk-ai and rtk-ai Labs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+19 -130
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1470188214710046894?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/pvHdzAec"><img src="https://img.shields.io/discord/1470188214710046894?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#installation">Install</a> &bull;
<a href="docs/TROUBLESHOOTING.md">Troubleshooting</a> &bull;
<a href="ARCHITECTURE.md">Architecture</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/pvHdzAec">Discord</a>
</p>
<p align="center">
@@ -33,7 +33,7 @@
---
rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, 100+ supported commands, <10ms overhead.
rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, zero dependencies, <10ms overhead.
## Token Savings (30-min Claude Code Session)
@@ -99,15 +99,12 @@ rtk gain # Should show token savings stats
## Quick Start
```bash
# 1. Install for your AI tool
rtk init -g # Claude Code / Copilot (default)
rtk init -g --gemini # Gemini CLI
rtk init -g --codex # Codex (OpenAI)
rtk init -g --agent cursor # Cursor
rtk init --agent windsurf # Windsurf
rtk init --agent cline # Cline / Roo Code
# 1. Install hook for Claude Code (recommended)
rtk init --global
# Follow instructions to register in ~/.claude/settings.json
# Claude Code only by default (use --opencode for OpenCode)
# 2. Restart your AI tool, then test
# 2. Restart Claude Code, then test
git status # Automatically rewritten to rtk git status
```
@@ -174,8 +171,6 @@ rtk playwright test # E2E results (failures only)
rtk pytest # Python tests (-90%)
rtk go test # Go tests (NDJSON, -90%)
rtk cargo test # Cargo tests (-90%)
rtk rake test # Ruby minitest (-90%)
rtk rspec # RSpec tests (JSON, -60%+)
```
### Build & Lint
@@ -189,7 +184,6 @@ rtk cargo build # Cargo build (-80%)
rtk cargo clippy # Cargo clippy (-80%)
rtk ruff check # Python linting (JSON, -80%)
rtk golangci-lint run # Go linting (JSON, -85%)
rtk rubocop # Ruby linting (JSON, -60%+)
```
### Package Managers
@@ -197,7 +191,6 @@ rtk rubocop # Ruby linting (JSON, -60%+)
rtk pnpm list # Compact dependency tree
rtk pip list # Python packages (auto-detect uv)
rtk pip outdated # Outdated packages
rtk bundle install # Ruby gems (strip Using lines)
rtk prisma generate # Schema generation (no ASCII art)
```
@@ -294,106 +287,28 @@ rtk init --show # Verify installation
After install, **restart Claude Code**.
## Supported AI Tools
## OpenCode Plugin (Global)
RTK supports 10 AI coding tools. Each integration transparently rewrites shell commands to `rtk` equivalents for 60-90% token savings.
OpenCode supports plugins that can intercept tool execution. RTK provides a global plugin that mirrors the Claude auto-rewrite behavior by rewriting Bash tool commands to `rtk ...` before they execute. This plugin is **not** installed by default.
| Tool | Install | Method |
|------|---------|--------|
| **Claude Code** | `rtk init -g` | PreToolUse hook (bash) |
| **GitHub Copilot (VS Code)** | `rtk init -g --copilot` | PreToolUse hook (`rtk hook copilot`) — transparent rewrite |
| **GitHub Copilot CLI** | `rtk init -g --copilot` | PreToolUse deny-with-suggestion (CLI limitation) |
| **Cursor** | `rtk init -g --agent cursor` | preToolUse hook (hooks.json) |
| **Gemini CLI** | `rtk init -g --gemini` | BeforeTool hook (`rtk hook gemini`) |
| **Codex** | `rtk init -g --codex` | AGENTS.md + RTK.md instructions |
| **Windsurf** | `rtk init --agent windsurf` | .windsurfrules (project-scoped) |
| **Cline / Roo Code** | `rtk init --agent cline` | .clinerules (project-scoped) |
| **OpenCode** | `rtk init -g --opencode` | Plugin TS (tool.execute.before) |
| **OpenClaw** | `openclaw plugins install ./openclaw` | Plugin TS (before_tool_call) |
| **Mistral Vibe** | Planned (#800) | Blocked on upstream BeforeToolCallback |
### Claude Code (default)
```bash
rtk init -g # Install hook + RTK.md
rtk init -g --auto-patch # Non-interactive (CI/CD)
rtk init --show # Verify installation
rtk init -g --uninstall # Remove
```
### GitHub Copilot (VS Code + CLI)
```bash
rtk init -g --copilot # Install hook + instructions
```
Creates `.github/hooks/rtk-rewrite.json` (PreToolUse hook) and `.github/copilot-instructions.md` (prompt-level awareness).
The hook (`rtk hook copilot`) auto-detects the format:
- **VS Code Copilot Chat**: transparent rewrite via `updatedInput` (same as Claude Code)
- **Copilot CLI**: deny-with-suggestion (CLI does not support `updatedInput` yet — see [copilot-cli#2013](https://github.com/github/copilot-cli/issues/2013))
### Cursor
```bash
rtk init -g --agent cursor
```
Creates `~/.cursor/hooks/rtk-rewrite.sh` + patches `~/.cursor/hooks.json` with preToolUse matcher. Works with both Cursor editor and `cursor-agent` CLI.
### Gemini CLI
```bash
rtk init -g --gemini
rtk init -g --gemini --uninstall
```
Creates `~/.gemini/hooks/rtk-hook-gemini.sh` + patches `~/.gemini/settings.json` with BeforeTool hook.
### Codex (OpenAI)
```bash
rtk init -g --codex
```
Creates `~/.codex/RTK.md` + `~/.codex/AGENTS.md` with `@RTK.md` reference. Codex reads these as global instructions.
### Windsurf
```bash
rtk init --agent windsurf
```
Creates `.windsurfrules` in the current project. Cascade reads rules and prefixes commands with `rtk`.
### Cline / Roo Code
```bash
rtk init --agent cline
```
Creates `.clinerules` in the current project. Cline reads rules and prefixes commands with `rtk`.
### OpenCode
> **Note**: This plugin uses OpenCode's `tool.execute.before` hook. Known limitation: plugin hooks do not intercept subagent tool calls ([upstream issue](https://github.com/sst/opencode/issues/5894)). See [OpenCode plugin docs](https://open-code.ai/en/docs/plugins) for API details.
**Install OpenCode plugin:**
```bash
rtk init -g --opencode
```
Creates `~/.config/opencode/plugins/rtk.ts`. Uses `tool.execute.before` hook.
**What it creates:**
- `~/.config/opencode/plugins/rtk.ts`
### OpenClaw
**Restart Required**: Restart OpenCode, then test with `git status` in a session.
**Manual install (fallback):**
```bash
openclaw plugins install ./openclaw
mkdir -p ~/.config/opencode/plugins
cp hooks/opencode-rtk.ts ~/.config/opencode/plugins/rtk.ts
```
Plugin in `openclaw/` directory. Uses `before_tool_call` hook, delegates to `rtk rewrite`.
### Mistral Vibe (planned)
Blocked on upstream BeforeToolCallback support ([mistral-vibe#531](https://github.com/mistralai/mistral-vibe/issues/531), [PR #533](https://github.com/mistralai/mistral-vibe/pull/533)). Tracked in [#800](https://github.com/rtk-ai/rtk/issues/800).
### Commands Rewritten
| Raw Command | Rewritten To |
@@ -415,10 +330,6 @@ Blocked on upstream BeforeToolCallback support ([mistral-vibe#531](https://githu
| `pip list/install` | `rtk pip ...` |
| `go test/build/vet` | `rtk go ...` |
| `golangci-lint` | `rtk golangci-lint` |
| `rake test` / `rails test` | `rtk rake test` |
| `rspec` / `bundle exec rspec` | `rtk rspec` |
| `rubocop` / `bundle exec rubocop` | `rtk rubocop` |
| `bundle install/update` | `rtk bundle ...` |
| `docker ps/images/logs` | `rtk docker ...` |
| `kubectl get/logs` | `rtk kubectl ...` |
| `curl` | `rtk curl` |
@@ -470,33 +381,11 @@ brew uninstall rtk # If installed via Homebrew
- **[SECURITY.md](SECURITY.md)** - Security policy and PR review process
- **[AUDIT_GUIDE.md](docs/AUDIT_GUIDE.md)** - Token savings analytics guide
## Privacy & Telemetry
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 (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
**What is NOT collected:** source code, file paths, command arguments, secrets, environment variables, or any personally identifiable information.
**Opt-out** (any of these):
```bash
# Environment variable
export RTK_TELEMETRY_DISABLED=1
# Or in config file (~/.config/rtk/config.toml)
[telemetry]
enabled = false
```
## Contributing
Contributions welcome! Please open an issue or PR on [GitHub](https://github.com/rtk-ai/rtk).
Join the community on [Discord](https://discord.gg/RySmvNF5kF).
Join the community on [Discord](https://discord.gg/pvHdzAec).
## License
+3 -3
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#instalacion">Instalar</a> &bull;
<a href="docs/TROUBLESHOOTING.md">Solucion de problemas</a> &bull;
<a href="ARCHITECTURE.md">Arquitectura</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
@@ -152,7 +152,7 @@ rtk discover # Descubrir ahorros perdidos
Las contribuciones son bienvenidas. Abre un issue o PR en [GitHub](https://github.com/rtk-ai/rtk).
Unete a la comunidad en [Discord](https://discord.gg/RySmvNF5kF).
Unete a la comunidad en [Discord](https://discord.gg/pvHdzAec).
## Licencia
+3 -3
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#installation">Installer</a> &bull;
<a href="docs/TROUBLESHOOTING.md">Depannage</a> &bull;
<a href="ARCHITECTURE.md">Architecture</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
@@ -190,7 +190,7 @@ mode = "failures"
Les contributions sont les bienvenues ! Ouvrez une issue ou une PR sur [GitHub](https://github.com/rtk-ai/rtk).
Rejoignez la communaute sur [Discord](https://discord.gg/RySmvNF5kF).
Rejoignez la communaute sur [Discord](https://discord.gg/pvHdzAec).
## Licence
+3 -3
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#インストール">インストール</a> &bull;
<a href="docs/TROUBLESHOOTING.md">トラブルシューティング</a> &bull;
<a href="ARCHITECTURE.md">アーキテクチャ</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
@@ -152,7 +152,7 @@ rtk discover # 見逃した節約機会を発見
コントリビューション歓迎![GitHub](https://github.com/rtk-ai/rtk) で issue または PR を作成してください。
[Discord](https://discord.gg/RySmvNF5kF) コミュニティに参加。
[Discord](https://discord.gg/pvHdzAec) コミュニティに参加。
## ライセンス
+3 -3
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#설치">설치</a> &bull;
<a href="docs/TROUBLESHOOTING.md">문제 해결</a> &bull;
<a href="ARCHITECTURE.md">아키텍처</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
@@ -152,7 +152,7 @@ rtk discover # 놓친 절약 기회 발견
기여를 환영합니다! [GitHub](https://github.com/rtk-ai/rtk)에서 issue 또는 PR을 생성해 주세요.
[Discord](https://discord.gg/RySmvNF5kF) 커뮤니티에 참여하세요.
[Discord](https://discord.gg/pvHdzAec) 커뮤니티에 참여하세요.
## 라이선스
+3 -3
View File
@@ -10,7 +10,7 @@
<a href="https://github.com/rtk-ai/rtk/actions"><img src="https://github.com/rtk-ai/rtk/workflows/Security%20Check/badge.svg" alt="CI"></a>
<a href="https://github.com/rtk-ai/rtk/releases"><img src="https://img.shields.io/github/v/release/rtk-ai/rtk" alt="Release"></a>
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
<a href="https://discord.gg/RySmvNF5kF"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://discord.gg/gFwRPEKq4p"><img src="https://img.shields.io/discord/1478373640461488159?label=Discord&logo=discord" alt="Discord"></a>
<a href="https://formulae.brew.sh/formula/rtk"><img src="https://img.shields.io/homebrew/v/rtk" alt="Homebrew"></a>
</p>
@@ -19,7 +19,7 @@
<a href="#安装">安装</a> &bull;
<a href="docs/TROUBLESHOOTING.md">故障排除</a> &bull;
<a href="ARCHITECTURE.md">架构</a> &bull;
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
<a href="https://discord.gg/gFwRPEKq4p">Discord</a>
</p>
<p align="center">
@@ -160,7 +160,7 @@ rtk discover # 发现遗漏的节省机会
欢迎贡献!请在 [GitHub](https://github.com/rtk-ai/rtk) 上提交 issue 或 PR。
加入 [Discord](https://discord.gg/RySmvNF5kF) 社区。
加入 [Discord](https://discord.gg/pvHdzAec) 社区。
## 许可证
+102
View File
@@ -0,0 +1,102 @@
# 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,15 +3,6 @@ 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
@@ -1,432 +0,0 @@
# 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
@@ -1,72 +0,0 @@
# 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**: 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`
- **Local storage only**: Database never leaves the machine
- **No telemetry**: RTK does not phone home or send analytics
- **User control**: Users can delete `~/.local/share/rtk/tracking.db` anytime
- **90-day retention**: Old data automatically purged
-235
View File
@@ -1,235 +0,0 @@
# 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
@@ -1,24 +0,0 @@
# 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
```
-98
View File
@@ -1,98 +0,0 @@
#!/usr/bin/env bash
# rtk-hook-version: 3
# RTK Claude Code hook — rewrites commands to use rtk for token savings.
# Requires: rtk >= 0.23.0, jq
#
# This is a thin delegating hook: all rewrite logic lives in `rtk rewrite`,
# which is the single source of truth (src/discover/registry.rs).
# To add or change rewrite rules, edit the Rust registry — not this file.
#
# Exit code protocol for `rtk rewrite`:
# 0 + stdout Rewrite found, no deny/ask rule matched → auto-allow
# 1 No RTK equivalent → pass through unchanged
# 2 Deny rule matched → pass through (Claude Code native deny handles it)
# 3 + stdout Ask rule matched → rewrite but let Claude Code prompt the user
if ! command -v jq &>/dev/null; then
echo "[rtk] WARNING: jq is not installed. Hook cannot rewrite commands. Install jq: https://jqlang.github.io/jq/download/" >&2
exit 0
fi
if ! command -v rtk &>/dev/null; then
echo "[rtk] WARNING: rtk is not installed or not in PATH. Hook cannot rewrite commands. Install: https://github.com/rtk-ai/rtk#installation" >&2
exit 0
fi
# Version guard: rtk rewrite was added in 0.23.0.
# Older binaries: warn once and exit cleanly (no silent failure).
RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [ -n "$RTK_VERSION" ]; then
MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
# Require >= 0.23.0
if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
exit 0
fi
fi
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if [ -z "$CMD" ]; then
exit 0
fi
# Delegate all rewrite + permission logic to the Rust binary.
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null)
EXIT_CODE=$?
case $EXIT_CODE in
0)
# Rewrite found, no permission rules matched — safe to auto-allow.
# If the output is identical, the command was already using RTK.
[ "$CMD" = "$REWRITTEN" ] && exit 0
;;
1)
# No RTK equivalent — pass through unchanged.
exit 0
;;
2)
# Deny rule matched — let Claude Code's native deny rule handle it.
exit 0
;;
3)
# Ask rule matched — rewrite the command but do NOT auto-allow so that
# Claude Code prompts the user for confirmation.
;;
*)
exit 0
;;
esac
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
if [ "$EXIT_CODE" -eq 3 ]; then
# Ask: rewrite the command, omit permissionDecision so Claude Code prompts.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"updatedInput": $updated
}
}'
else
# Allow: rewrite the command and auto-allow.
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": $updated
}
}'
fi
-9
View File
@@ -1,9 +0,0 @@
# 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`
-32
View File
@@ -1,32 +0,0 @@
# RTK - Rust Token Killer (Cline)
**Usage**: Token-optimized CLI proxy for shell commands.
## Rule
Always prefix shell commands with `rtk` to minimize token consumption.
Examples:
```bash
rtk git status
rtk cargo test
rtk ls src/
rtk grep "pattern" src/
rtk find "*.rs" .
rtk docker ps
rtk gh pr list
```
## Meta Commands
```bash
rtk gain # Show token savings
rtk gain --history # Command history with savings
rtk discover # Find missed RTK opportunities
rtk proxy <cmd> # Run raw (no filtering, for debugging)
```
## Why
RTK filters and compresses command output before it reaches the LLM context, saving 60-90% tokens on common operations. Always use `rtk <cmd>` instead of raw commands.
-9
View File
@@ -1,9 +0,0 @@
# 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`
-32
View File
@@ -1,32 +0,0 @@
# RTK - Rust Token Killer (Codex CLI)
**Usage**: Token-optimized CLI proxy for shell commands.
## Rule
Always prefix shell commands with `rtk`.
Examples:
```bash
rtk git status
rtk cargo test
rtk npm run build
rtk pytest -q
```
## Meta Commands
```bash
rtk gain # Token savings analytics
rtk gain --history # Recent command savings history
rtk proxy <cmd> # Run raw command without filtering
```
## Verification
```bash
rtk --version
rtk gain
which rtk
```
-16
View File
@@ -1,16 +0,0 @@
# 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
```
-60
View File
@@ -1,60 +0,0 @@
# RTK — Copilot Integration (VS Code Copilot Chat + Copilot CLI)
**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)
## What's automatic
The `.github/copilot-instructions.md` file is loaded at session start by both Copilot CLI and VS Code Copilot Chat.
It instructs Copilot to prefix commands with `rtk` automatically.
The `.github/hooks/rtk-rewrite.json` hook adds a `PreToolUse` safety net via `rtk hook` —
a cross-platform Rust binary that intercepts raw bash tool calls and rewrites them.
No shell scripts, no `jq` dependency, works on Windows natively.
## Meta commands (always use directly)
```bash
rtk gain # Token savings dashboard for this session
rtk gain --history # Per-command history with savings %
rtk discover # Scan session history for missed rtk opportunities
rtk proxy <cmd> # Run raw (no filtering) but still track it
```
## Installation verification
```bash
rtk --version # Should print: rtk X.Y.Z
rtk gain # Should show a dashboard (not "command not found")
which rtk # Verify correct binary path
```
> ⚠️ **Name collision**: If `rtk gain` fails, you may have `reachingforthejack/rtk`
> (Rust Type Kit) installed instead. Check `which rtk` and reinstall from rtk-ai/rtk.
## How the hook works
`rtk hook` reads `PreToolUse` JSON from stdin, detects the agent format, and responds appropriately:
**VS Code Copilot Chat** (supports `updatedInput` — transparent rewrite, no denial):
1. Agent runs `git status` → `rtk hook` intercepts via `PreToolUse`
2. `rtk hook` detects VS Code format (`tool_name`/`tool_input` keys)
3. Returns `hookSpecificOutput.updatedInput.command = "rtk git status"`
4. Agent runs the rewritten command silently — no denial, no retry
**GitHub Copilot CLI** (deny-with-suggestion — CLI ignores `updatedInput` today, see [issue #2013](https://github.com/github/copilot-cli/issues/2013)):
1. Agent runs `git status` → `rtk hook` intercepts via `PreToolUse`
2. `rtk hook` detects Copilot CLI format (`toolName`/`toolArgs` keys)
3. Returns `permissionDecision: deny` with reason: `"Token savings: use 'rtk git status' instead"`
4. Copilot reads the reason and re-runs `rtk git status`
When Copilot CLI adds `updatedInput` support, only `rtk hook` needs updating — no config changes.
## Integration comparison
| Tool | Mechanism | Hook output | File |
|-----------------------|-----------------------------------------|--------------------------|------------------------------------|
| Claude Code | `PreToolUse` hook with `updatedInput` | Transparent rewrite | `hooks/rtk-rewrite.sh` |
| VS Code Copilot Chat | `PreToolUse` hook with `updatedInput` | Transparent rewrite | `.github/hooks/rtk-rewrite.json` |
| GitHub Copilot CLI | `PreToolUse` deny-with-suggestion | Denial + retry | `.github/hooks/rtk-rewrite.json` |
| OpenCode | Plugin `tool.execute.before` | Transparent rewrite | `hooks/opencode-rtk.ts` |
| (any) | Custom instructions | Prompt-level guidance | `.github/copilot-instructions.md` |
-293
View File
@@ -1,293 +0,0 @@
#!/usr/bin/env bash
# Test suite for rtk hook (cross-platform preToolUse handler).
# Feeds mock preToolUse JSON through `rtk hook` and verifies allow/deny decisions.
#
# Usage: bash hooks/test-copilot-rtk-rewrite.sh
#
# Copilot CLI input format:
# {"toolName":"bash","toolArgs":"{\"command\":\"...\"}"}
# Output on intercept: {"permissionDecision":"deny","permissionDecisionReason":"..."}
#
# VS Code Copilot Chat input format:
# {"tool_name":"Bash","tool_input":{"command":"..."}}
# Output on intercept: {"hookSpecificOutput":{"permissionDecision":"allow","updatedInput":{...}}}
#
# Output on pass-through: empty (exit 0)
RTK="${RTK:-rtk}"
PASS=0
FAIL=0
TOTAL=0
# Colors
GREEN='\033[32m'
RED='\033[31m'
DIM='\033[2m'
RESET='\033[0m'
# Build a Copilot CLI preToolUse input JSON
copilot_bash_input() {
local cmd="$1"
local tool_args
tool_args=$(jq -cn --arg cmd "$cmd" '{"command":$cmd}')
jq -cn --arg ta "$tool_args" '{"toolName":"bash","toolArgs":$ta}'
}
# Build a VS Code Copilot Chat preToolUse input JSON
vscode_bash_input() {
local cmd="$1"
jq -cn --arg cmd "$cmd" '{"tool_name":"Bash","tool_input":{"command":$cmd}}'
}
# Build a non-bash tool input
tool_input() {
local tool_name="$1"
jq -cn --arg t "$tool_name" '{"toolName":$t,"toolArgs":"{}"}'
}
# Assert Copilot CLI: hook denies and reason contains the expected rtk command
test_deny() {
local description="$1"
local input_cmd="$2"
local expected_rtk="$3"
TOTAL=$((TOTAL + 1))
local output
output=$(copilot_bash_input "$input_cmd" | "$RTK" hook 2>/dev/null) || true
local decision reason
decision=$(echo "$output" | jq -r '.permissionDecision // empty' 2>/dev/null)
reason=$(echo "$output" | jq -r '.permissionDecisionReason // empty' 2>/dev/null)
if [ "$decision" = "deny" ] && echo "$reason" | grep -qF "$expected_rtk"; then
printf " ${GREEN}DENY${RESET} %s ${DIM}→ %s${RESET}\n" "$description" "$expected_rtk"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected decision: deny, reason containing: %s\n" "$expected_rtk"
printf " actual decision: %s\n" "$decision"
printf " actual reason: %s\n" "$reason"
FAIL=$((FAIL + 1))
fi
}
# Assert VS Code Copilot Chat: hook returns updatedInput (allow) with rewritten command
test_vscode_rewrite() {
local description="$1"
local input_cmd="$2"
local expected_rtk="$3"
TOTAL=$((TOTAL + 1))
local output
output=$(vscode_bash_input "$input_cmd" | "$RTK" hook 2>/dev/null) || true
local decision updated_cmd
decision=$(echo "$output" | jq -r '.hookSpecificOutput.permissionDecision // empty' 2>/dev/null)
updated_cmd=$(echo "$output" | jq -r '.hookSpecificOutput.updatedInput.command // empty' 2>/dev/null)
if [ "$decision" = "allow" ] && echo "$updated_cmd" | grep -qF "$expected_rtk"; then
printf " ${GREEN}REWRITE${RESET} %s ${DIM}→ %s${RESET}\n" "$description" "$updated_cmd"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected decision: allow, updatedInput containing: %s\n" "$expected_rtk"
printf " actual decision: %s\n" "$decision"
printf " actual updatedInput: %s\n" "$updated_cmd"
FAIL=$((FAIL + 1))
fi
}
# Assert the hook emits no output (pass-through)
test_allow() {
local description="$1"
local input="$2"
TOTAL=$((TOTAL + 1))
local output
output=$(echo "$input" | "$RTK" hook 2>/dev/null) || true
if [ -z "$output" ]; then
printf " ${GREEN}PASS${RESET} %s ${DIM}→ (allow)${RESET}\n" "$description"
PASS=$((PASS + 1))
else
local decision
decision=$(echo "$output" | jq -r '.permissionDecision // .hookSpecificOutput.permissionDecision // empty' 2>/dev/null)
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected: (no output)\n"
printf " actual: permissionDecision=%s\n" "$decision"
FAIL=$((FAIL + 1))
fi
}
echo "============================================"
echo " RTK Hook Test Suite (rtk hook)"
echo "============================================"
echo ""
# ---- SECTION 1: Copilot CLI — commands that should be denied ----
echo "--- Copilot CLI: intercepted (deny with rtk suggestion) ---"
test_deny "git status" \
"git status" \
"rtk git status"
test_deny "git log --oneline -10" \
"git log --oneline -10" \
"rtk git log"
test_deny "git diff HEAD" \
"git diff HEAD" \
"rtk git diff"
test_deny "cargo test" \
"cargo test" \
"rtk cargo test"
test_deny "cargo clippy --all-targets" \
"cargo clippy --all-targets" \
"rtk cargo clippy"
test_deny "cargo build" \
"cargo build" \
"rtk cargo build"
test_deny "grep -rn pattern src/" \
"grep -rn pattern src/" \
"rtk grep"
test_deny "gh pr list" \
"gh pr list" \
"rtk gh"
echo ""
# ---- SECTION 2: VS Code Copilot Chat — commands that should be rewritten via updatedInput ----
echo "--- VS Code Copilot Chat: intercepted (updatedInput rewrite) ---"
test_vscode_rewrite "git status" \
"git status" \
"rtk git status"
test_vscode_rewrite "cargo test" \
"cargo test" \
"rtk cargo test"
test_vscode_rewrite "gh pr list" \
"gh pr list" \
"rtk gh"
echo ""
# ---- SECTION 3: Pass-through cases ----
echo "--- Pass-through (allow silently) ---"
test_allow "Copilot CLI: already rtk: rtk git status" \
"$(copilot_bash_input "rtk git status")"
test_allow "Copilot CLI: already rtk: rtk cargo test" \
"$(copilot_bash_input "rtk cargo test")"
test_allow "Copilot CLI: heredoc" \
"$(copilot_bash_input "cat <<'EOF'
hello
EOF")"
test_allow "Copilot CLI: unknown command: htop" \
"$(copilot_bash_input "htop")"
test_allow "Copilot CLI: unknown command: echo" \
"$(copilot_bash_input "echo hello world")"
test_allow "Copilot CLI: non-bash tool: view" \
"$(tool_input "view")"
test_allow "Copilot CLI: non-bash tool: edit" \
"$(tool_input "edit")"
test_allow "VS Code: already rtk" \
"$(vscode_bash_input "rtk git status")"
test_allow "VS Code: non-bash tool: editFiles" \
"$(jq -cn '{"tool_name":"editFiles"}')"
echo ""
# ---- SECTION 4: Output format assertions ----
echo "--- Output format ---"
# Copilot CLI output format
TOTAL=$((TOTAL + 1))
raw_output=$(copilot_bash_input "git status" | "$RTK" hook 2>/dev/null)
if echo "$raw_output" | jq . >/dev/null 2>&1; then
printf " ${GREEN}PASS${RESET} Copilot CLI: output is valid JSON\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: output is not valid JSON: %s\n" "$raw_output"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
decision=$(echo "$raw_output" | jq -r '.permissionDecision')
if [ "$decision" = "deny" ]; then
printf " ${GREEN}PASS${RESET} Copilot CLI: permissionDecision == \"deny\"\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: expected \"deny\", got \"%s\"\n" "$decision"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
reason=$(echo "$raw_output" | jq -r '.permissionDecisionReason')
if echo "$reason" | grep -qE '`rtk [^`]+`'; then
printf " ${GREEN}PASS${RESET} Copilot CLI: reason contains backtick-quoted rtk command ${DIM}→ %s${RESET}\n" "$reason"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: reason missing backtick-quoted command: %s\n" "$reason"
FAIL=$((FAIL + 1))
fi
# VS Code output format
TOTAL=$((TOTAL + 1))
vscode_output=$(vscode_bash_input "git status" | "$RTK" hook 2>/dev/null)
if echo "$vscode_output" | jq . >/dev/null 2>&1; then
printf " ${GREEN}PASS${RESET} VS Code: output is valid JSON\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: output is not valid JSON: %s\n" "$vscode_output"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
vscode_decision=$(echo "$vscode_output" | jq -r '.hookSpecificOutput.permissionDecision')
if [ "$vscode_decision" = "allow" ]; then
printf " ${GREEN}PASS${RESET} VS Code: hookSpecificOutput.permissionDecision == \"allow\"\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: expected \"allow\", got \"%s\"\n" "$vscode_decision"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
vscode_updated=$(echo "$vscode_output" | jq -r '.hookSpecificOutput.updatedInput.command')
if echo "$vscode_updated" | grep -q "^rtk "; then
printf " ${GREEN}PASS${RESET} VS Code: updatedInput.command starts with rtk ${DIM}→ %s${RESET}\n" "$vscode_updated"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: updatedInput.command should start with rtk: %s\n" "$vscode_updated"
FAIL=$((FAIL + 1))
fi
echo ""
# ---- SUMMARY ----
echo "============================================"
if [ $FAIL -eq 0 ]; then
printf " ${GREEN}ALL $TOTAL TESTS PASSED${RESET}\n"
else
printf " ${RED}$FAIL FAILED${RESET} / $TOTAL total ($PASS passed)\n"
fi
echo "============================================"
exit $FAIL
-9
View File
@@ -1,9 +0,0 @@
# 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`
File renamed without changes.
-11
View File
@@ -1,11 +0,0 @@
# 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.
@@ -1,8 +1,6 @@
#!/usr/bin/env bash
# rtk-hook-version: 1
# RTK Cursor Agent hook — rewrites shell commands to use rtk for token savings.
# Works with both Cursor editor and cursor-cli (they share ~/.cursor/hooks.json).
# Cursor preToolUse hook format: receives JSON on stdin, returns JSON on stdout.
# rtk-hook-version: 2
# RTK Claude Code hook — rewrites commands to use rtk for token savings.
# Requires: rtk >= 0.23.0, jq
#
# This is a thin delegating hook: all rewrite logic lives in `rtk rewrite`,
@@ -20,10 +18,12 @@ if ! command -v rtk &>/dev/null; then
fi
# Version guard: rtk rewrite was added in 0.23.0.
# Older binaries: warn once and exit cleanly (no silent failure).
RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [ -n "$RTK_VERSION" ]; then
MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
# Require >= 0.23.0
if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
exit 0
@@ -34,21 +34,28 @@ INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if [ -z "$CMD" ]; then
echo '{}'
exit 0
fi
# Delegate all rewrite logic to the Rust binary.
# rtk rewrite exits 1 when there's no rewrite — hook passes through silently.
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || { echo '{}'; exit 0; }
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || exit 0
# No change — nothing to do.
if [ "$CMD" = "$REWRITTEN" ]; then
echo '{}'
exit 0
fi
jq -n --arg cmd "$REWRITTEN" '{
"permission": "allow",
"updated_input": { "command": $cmd }
}'
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
jq -n \
--argjson updated "$UPDATED_INPUT" \
'{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": $updated
}
}'
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/bash
# Test suite for rtk-rewrite.sh
# Feeds mock JSON through the hook and verifies the rewritten commands.
#
-9
View File
@@ -1,9 +0,0 @@
# 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`
-32
View File
@@ -1,32 +0,0 @@
# RTK - Rust Token Killer (Windsurf)
**Usage**: Token-optimized CLI proxy for shell commands.
## Rule
Always prefix shell commands with `rtk` to minimize token consumption.
Examples:
```bash
rtk git status
rtk cargo test
rtk ls src/
rtk grep "pattern" src/
rtk find "*.rs" .
rtk docker ps
rtk gh pr list
```
## Meta Commands
```bash
rtk gain # Show token savings
rtk gain --history # Command history with savings
rtk discover # Find missed RTK opportunities
rtk proxy <cmd> # Run raw (no filtering, for debugging)
```
## Why
RTK filters and compresses command output before it reaches the LLM context, saving 60-90% tokens on common operations. Always use `rtk <cmd>` instead of raw commands.
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env sh
#!/bin/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
-86
View File
@@ -1,86 +0,0 @@
# RTK Plugin for OpenClaw
Transparently rewrites shell commands executed via OpenClaw's `exec` tool to their RTK equivalents, achieving 60-90% LLM token savings.
This is the OpenClaw equivalent of the Claude Code hooks in `hooks/rtk-rewrite.sh`.
## How it works
The plugin registers a `before_tool_call` hook that intercepts `exec` tool calls. When the agent runs a command like `git status`, the plugin delegates to `rtk rewrite` which returns the optimized command (e.g. `rtk git status`). The compressed output enters the agent's context window, saving tokens.
All rewrite logic lives in RTK itself (`rtk rewrite`). This plugin is a thin delegate -- when new filters are added to RTK, the plugin picks them up automatically with zero changes.
## Installation
### Prerequisites
RTK must be installed and available in `$PATH`:
```bash
brew install rtk
# or
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
```
### Install the plugin
```bash
# Copy the plugin to OpenClaw's extensions directory
mkdir -p ~/.openclaw/extensions/rtk-rewrite
cp openclaw/index.ts openclaw/openclaw.plugin.json ~/.openclaw/extensions/rtk-rewrite/
# Restart the gateway
openclaw gateway restart
```
### Or install via OpenClaw CLI
```bash
openclaw plugins install ./openclaw
```
## Configuration
In `openclaw.json`:
```json5
{
plugins: {
entries: {
"rtk-rewrite": {
enabled: true,
config: {
enabled: true, // Toggle rewriting on/off
verbose: false // Log rewrites to console
}
}
}
}
}
```
## What gets rewritten
Everything that `rtk rewrite` supports (30+ commands). See the [full command list](https://github.com/rtk-ai/rtk#commands).
## What's NOT rewritten
Handled by `rtk rewrite` guards:
- Commands already using `rtk`
- Piped commands (`|`, `&&`, `;`)
- Heredocs (`<<`)
- Commands without an RTK filter
## Measured savings
| Command | Token savings |
|---------|--------------|
| `git log --stat` | 87% |
| `ls -la` | 78% |
| `git status` | 66% |
| `grep` (single file) | 52% |
| `find -name` | 48% |
## License
MIT -- same as RTK.
-74
View File
@@ -1,74 +0,0 @@
/**
* RTK Rewrite Plugin for OpenClaw
*
* Transparently rewrites exec tool commands to RTK equivalents
* before execution, achieving 60-90% LLM token savings.
*
* All rewrite logic lives in `rtk rewrite` (src/discover/registry.rs).
* This plugin is a thin delegate — to add or change rules, edit the
* Rust registry, not this file.
*/
import { execSync } from "node:child_process";
let rtkAvailable: boolean | null = null;
function checkRtk(): boolean {
if (rtkAvailable !== null) return rtkAvailable;
try {
execSync("which rtk", { stdio: "ignore" });
rtkAvailable = true;
} catch {
rtkAvailable = false;
}
return rtkAvailable;
}
function tryRewrite(command: string): string | null {
try {
const result = execSync(`rtk rewrite ${JSON.stringify(command)}`, {
encoding: "utf-8",
timeout: 2000,
}).trim();
return result && result !== command ? result : null;
} catch {
return null;
}
}
export default function register(api: any) {
const pluginConfig = api.config ?? {};
const enabled = pluginConfig.enabled !== false;
const verbose = pluginConfig.verbose === true;
if (!enabled) return;
if (!checkRtk()) {
console.warn("[rtk] rtk binary not found in PATH — plugin disabled");
return;
}
api.on(
"before_tool_call",
(event: { toolName: string; params: Record<string, unknown> }) => {
if (event.toolName !== "exec") return;
const command = event.params?.command;
if (typeof command !== "string") return;
const rewritten = tryRewrite(command);
if (!rewritten) return;
if (verbose) {
console.log(`[rtk] ${command} -> ${rewritten}`);
}
return { params: { ...event.params, command: rewritten } };
},
{ priority: 10 }
);
if (verbose) {
console.log("[rtk] OpenClaw plugin registered");
}
}
-28
View File
@@ -1,28 +0,0 @@
{
"id": "rtk-rewrite",
"name": "RTK Token Optimizer",
"version": "1.0.0",
"description": "Transparently rewrites shell commands to their RTK equivalents for 60-90% LLM token savings",
"homepage": "https://github.com/rtk-ai/rtk",
"license": "MIT",
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {
"enabled": {
"type": "boolean",
"default": true,
"description": "Enable automatic command rewriting to RTK equivalents"
},
"verbose": {
"type": "boolean",
"default": false,
"description": "Log rewrite decisions to console for debugging"
}
}
},
"uiHints": {
"enabled": { "label": "Enable RTK rewriting" },
"verbose": { "label": "Verbose logging" }
}
}
-29
View File
@@ -1,29 +0,0 @@
{
"name": "@rtk-ai/rtk-rewrite",
"version": "1.0.0",
"description": "RTK plugin for OpenClaw — rewrites shell commands for 60-90% LLM token savings",
"main": "index.ts",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/rtk-ai/rtk",
"directory": "openclaw"
},
"homepage": "https://github.com/rtk-ai/rtk",
"keywords": [
"rtk",
"openclaw",
"openclaw-plugin",
"token-savings",
"llm",
"cli-proxy"
],
"files": [
"index.ts",
"openclaw.plugin.json",
"README.md"
],
"peerDependencies": {
"rtk": ">=0.28.0"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/bash
set -e
# Use local release build if available, otherwise fall back to installed rtk
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/bash
# RTK Installation Verification Script
# Helps diagnose if you have the correct rtk (Token Killer) installed
-69
View File
@@ -1,69 +0,0 @@
#!/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 @@
#!/usr/bin/env bash
#!/bin/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 @@
#!/usr/bin/env bash
#!/bin/bash
# rtk-economics.sh
# Combine ccusage (tokens spent) with rtk (tokens saved) for economic analysis
+3 -25
View File
@@ -437,42 +437,20 @@ else
skip_test "rtk gt" "gt not installed"
fi
# ── 30. Ruby (conditional) ──────────────────────────
section "Ruby (conditional)"
if command -v rspec &>/dev/null; then
assert_help "rtk rspec" rtk rspec --help
else
skip_test "rtk rspec" "rspec not installed"
fi
if command -v rubocop &>/dev/null; then
assert_help "rtk rubocop" rtk rubocop --help
else
skip_test "rtk rubocop" "rubocop not installed"
fi
if command -v rake &>/dev/null; then
assert_help "rtk rake" rtk rake --help
else
skip_test "rtk rake" "rake not installed"
fi
# ── 31. Global flags ────────────────────────────────
# ── 30. Global flags ────────────────────────────────
section "Global flags"
assert_ok "rtk -u ls ." rtk -u ls .
assert_ok "rtk --skip-env npm --help" rtk --skip-env npm --help
# ── 32. CcEconomics ─────────────────────────────────
# ── 31. CcEconomics ─────────────────────────────────
section "CcEconomics"
assert_ok "rtk cc-economics" rtk cc-economics
# ── 33. Learn ───────────────────────────────────────
# ── 32. Learn ───────────────────────────────────────
section "Learn"
-463
View File
@@ -1,463 +0,0 @@
#!/usr/bin/env bash
#
# RTK Smoke Tests — Ruby (RSpec, RuboCop, Minitest, Bundle)
# Creates a minimal Rails app, exercises all Ruby RTK filters, then cleans up.
# Usage: bash scripts/test-ruby.sh
#
# Prerequisites: rtk (installed), ruby, bundler, rails gem
# Duration: ~60-120s (rails new + bundle install dominate)
#
set -euo pipefail
PASS=0
FAIL=0
SKIP=0
FAILURES=()
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
# ── Helpers ──────────────────────────────────────────
assert_ok() {
local name="$1"; shift
local output
if output=$("$@" 2>&1); then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s\n" "$name"
else
FAIL=$((FAIL + 1))
FAILURES+=("$name")
printf " ${RED}FAIL${NC} %s\n" "$name"
printf " cmd: %s\n" "$*"
printf " out: %s\n" "$(echo "$output" | head -3)"
fi
}
assert_contains() {
local name="$1"; local needle="$2"; shift 2
local output
if output=$("$@" 2>&1) && echo "$output" | grep -q "$needle"; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s\n" "$name"
else
FAIL=$((FAIL + 1))
FAILURES+=("$name")
printf " ${RED}FAIL${NC} %s\n" "$name"
printf " expected: '%s'\n" "$needle"
printf " got: %s\n" "$(echo "$output" | head -3)"
fi
}
# Allow non-zero exit but check output
assert_output() {
local name="$1"; local needle="$2"; shift 2
local output
output=$("$@" 2>&1) || true
if echo "$output" | grep -qi "$needle"; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s\n" "$name"
else
FAIL=$((FAIL + 1))
FAILURES+=("$name")
printf " ${RED}FAIL${NC} %s\n" "$name"
printf " expected: '%s'\n" "$needle"
printf " got: %s\n" "$(echo "$output" | head -3)"
fi
}
skip_test() {
local name="$1"; local reason="$2"
SKIP=$((SKIP + 1))
printf " ${YELLOW}SKIP${NC} %s (%s)\n" "$name" "$reason"
}
# Assert command exits with non-zero and output matches needle
assert_exit_nonzero() {
local name="$1"; local needle="$2"; shift 2
local output
local rc=0
output=$("$@" 2>&1) || rc=$?
if [[ $rc -ne 0 ]] && echo "$output" | grep -qi "$needle"; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} %s (exit=%d)\n" "$name" "$rc"
else
FAIL=$((FAIL + 1))
FAILURES+=("$name")
printf " ${RED}FAIL${NC} %s (exit=%d)\n" "$name" "$rc"
if [[ $rc -eq 0 ]]; then
printf " expected non-zero exit, got 0\n"
else
printf " expected: '%s'\n" "$needle"
fi
printf " out: %s\n" "$(echo "$output" | head -3)"
fi
}
section() {
printf "\n${BOLD}${CYAN}── %s ──${NC}\n" "$1"
}
# ── Prerequisite checks ─────────────────────────────
RTK=$(command -v rtk || echo "")
if [[ -z "$RTK" ]]; then
echo "rtk not found in PATH. Run: cargo install --path ."
exit 1
fi
if ! command -v ruby >/dev/null 2>&1; then
echo "ruby not found in PATH. Install Ruby first."
exit 1
fi
if ! command -v bundle >/dev/null 2>&1; then
echo "bundler not found in PATH. Run: gem install bundler"
exit 1
fi
if ! command -v rails >/dev/null 2>&1; then
echo "rails not found in PATH. Run: gem install rails"
exit 1
fi
# ── Preamble ─────────────────────────────────────────
printf "${BOLD}RTK Smoke Tests — Ruby (RSpec, RuboCop, Minitest, Bundle)${NC}\n"
printf "Binary: %s (%s)\n" "$RTK" "$(rtk --version)"
printf "Ruby: %s\n" "$(ruby --version)"
printf "Rails: %s\n" "$(rails --version)"
printf "Bundler: %s\n" "$(bundle --version)"
printf "Date: %s\n\n" "$(date '+%Y-%m-%d %H:%M')"
# ── Temp dir + cleanup trap ──────────────────────────
TMPDIR=$(mktemp -d /tmp/rtk-ruby-smoke-XXXXXX)
trap 'rm -rf "$TMPDIR"' EXIT
printf "${BOLD}Setting up temporary Rails app in %s ...${NC}\n" "$TMPDIR"
# ── Setup phase (not counted in assertions) ──────────
cd "$TMPDIR"
# 1. Create minimal Rails app
printf " → rails new (--minimal --skip-git --skip-docker) ...\n"
rails new rtk_smoke_app --minimal --skip-git --skip-docker --quiet 2>&1 | tail -1 || true
cd rtk_smoke_app
# 2. Add rspec-rails and rubocop to Gemfile
cat >> Gemfile <<'GEMFILE'
group :development, :test do
gem 'rspec-rails'
gem 'rubocop', require: false
end
GEMFILE
# 3. Bundle install
printf " → bundle install ...\n"
bundle install --quiet 2>&1 | tail -1 || true
# 4. Generate scaffold (creates model + minitest files)
printf " → rails generate scaffold Post ...\n"
rails generate scaffold Post title:string body:text published:boolean --quiet 2>&1 | tail -1 || true
# 5. Install RSpec + create manual spec file
printf " → rails generate rspec:install ...\n"
rails generate rspec:install --quiet 2>&1 | tail -1 || true
mkdir -p spec/models
cat > spec/models/post_spec.rb <<'SPEC'
require 'rails_helper'
RSpec.describe Post, type: :model do
it "is valid with valid attributes" do
post = Post.new(title: "Test", body: "Body", published: false)
expect(post).to be_valid
end
end
SPEC
# 6. Create + migrate database
printf " → rails db:create && db:migrate ...\n"
rails db:create --quiet 2>&1 | tail -1 || true
rails db:migrate --quiet 2>&1 | tail -1 || true
# 7. Create a file with intentional RuboCop offenses
printf " → creating rubocop_bait.rb with intentional offenses ...\n"
cat > app/models/rubocop_bait.rb <<'BAIT'
class RubocopBait < ApplicationRecord
def messy_method()
x = 1
y = 2
if x == 1
puts "hello world"
end
return nil
end
end
BAIT
# 8. Create a failing RSpec spec
printf " → creating failing rspec spec ...\n"
cat > spec/models/post_fail_spec.rb <<'FAILSPEC'
require 'rails_helper'
RSpec.describe Post, type: :model do
it "intentionally fails validation check" do
post = Post.new(title: "Hello", body: "World", published: false)
expect(post.title).to eq("Wrong Title On Purpose")
end
end
FAILSPEC
# 9. Create an RSpec spec with pending example
printf " → creating rspec spec with pending example ...\n"
cat > spec/models/post_pending_spec.rb <<'PENDSPEC'
require 'rails_helper'
RSpec.describe Post, type: :model do
it "is valid with title" do
post = Post.new(title: "OK", body: "Body", published: false)
expect(post).to be_valid
end
it "will support markdown later" do
pending "Not yet implemented"
expect(Post.new.render_markdown).to eq("<p>hello</p>")
end
end
PENDSPEC
# 10. Create a failing minitest test
printf " → creating failing minitest test ...\n"
cat > test/models/post_fail_test.rb <<'FAILTEST'
require "test_helper"
class PostFailTest < ActiveSupport::TestCase
test "intentionally fails" do
assert_equal "wrong", Post.new(title: "right").title
end
end
FAILTEST
# 11. Create a passing minitest test
printf " → creating passing minitest test ...\n"
cat > test/models/post_pass_test.rb <<'PASSTEST'
require "test_helper"
class PostPassTest < ActiveSupport::TestCase
test "post is valid" do
post = Post.new(title: "OK", body: "Body", published: false)
assert post.valid?
end
end
PASSTEST
printf "\n${BOLD}Setup complete. Running tests...${NC}\n"
# ══════════════════════════════════════════════════════
# Test sections
# ══════════════════════════════════════════════════════
# ── 1. RSpec ─────────────────────────────────────────
section "RSpec"
assert_output "rtk rspec (with failure)" \
"failed" \
rtk rspec
assert_output "rtk rspec spec/models/post_spec.rb (pass)" \
"RSpec.*passed" \
rtk rspec spec/models/post_spec.rb
assert_output "rtk rspec spec/models/post_fail_spec.rb (fail)" \
"failed\|❌" \
rtk rspec spec/models/post_fail_spec.rb
# ── 2. RuboCop ───────────────────────────────────────
section "RuboCop"
assert_output "rtk rubocop (with offenses)" \
"offense" \
rtk rubocop
assert_output "rtk rubocop app/ (with offenses)" \
"rubocop_bait\|offense" \
rtk rubocop app/
# ── 3. Minitest (rake test) ──────────────────────────
section "Minitest (rake test)"
assert_output "rtk rake test (with failure)" \
"failure\|error\|FAIL" \
rtk rake test
assert_output "rtk rake test single passing file" \
"ok rake test\|0 failures" \
rtk rake test TEST=test/models/post_pass_test.rb
assert_exit_nonzero "rtk rake test single failing file" \
"failure\|FAIL" \
rtk rake test test/models/post_fail_test.rb
# ── 4. Bundle install ────────────────────────────────
section "Bundle install"
assert_output "rtk bundle install (idempotent)" \
"bundle\|ok\|complete\|install" \
rtk bundle install
# ── 5. Exit code preservation ────────────────────────
section "Exit code preservation"
assert_exit_nonzero "rtk rspec exits non-zero on failure" \
"failed\|failure" \
rtk rspec spec/models/post_fail_spec.rb
assert_exit_nonzero "rtk rubocop exits non-zero on offenses" \
"offense" \
rtk rubocop app/models/rubocop_bait.rb
assert_exit_nonzero "rtk rake test exits non-zero on failure" \
"failure\|FAIL" \
rtk rake test test/models/post_fail_test.rb
# ── 6. bundle exec variants ─────────────────────────
section "bundle exec variants"
assert_output "bundle exec rspec spec/models/post_spec.rb" \
"passed\|example" \
rtk bundle exec rspec spec/models/post_spec.rb
assert_output "bundle exec rubocop app/" \
"offense" \
rtk bundle exec rubocop app/
# ── 7. RuboCop autocorrect ───────────────────────────
section "RuboCop autocorrect"
# Copy bait file so autocorrect has something to fix
cp app/models/rubocop_bait.rb app/models/rubocop_bait_ac.rb
sed -i.bak 's/RubocopBait/RubocopBaitAc/' app/models/rubocop_bait_ac.rb
assert_output "rtk rubocop -A (autocorrect)" \
"autocorrected\|rubocop\|ok\|offense\|inspected" \
rtk rubocop -A app/models/rubocop_bait_ac.rb
# Clean up autocorrect test file
rm -f app/models/rubocop_bait_ac.rb app/models/rubocop_bait_ac.rb.bak
# ── 8. RSpec pending ─────────────────────────────────
section "RSpec pending"
assert_output "rtk rspec with pending example" \
"pending" \
rtk rspec spec/models/post_pending_spec.rb
# ── 9. RSpec text fallback ───────────────────────────
section "RSpec text fallback"
assert_output "rtk rspec --format documentation (text path)" \
"valid\|example\|post" \
rtk rspec --format documentation spec/models/post_spec.rb
# ── 10. RSpec empty suite ────────────────────────────
section "RSpec empty suite"
assert_output "rtk rspec nonexistent tag" \
"0 examples\|No examples" \
rtk rspec --tag nonexistent spec/models/post_spec.rb
# ── 11. Token savings ────────────────────────────────
section "Token savings"
# rspec (passing spec)
raw_len=$( (bundle exec rspec spec/models/post_spec.rb 2>&1 || true) | wc -c | tr -d ' ')
rtk_len=$( (rtk rspec spec/models/post_spec.rb 2>&1 || true) | wc -c | tr -d ' ')
if [[ "$rtk_len" -lt "$raw_len" ]]; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} rspec: rtk (%s bytes) < raw (%s bytes)\n" "$rtk_len" "$raw_len"
else
FAIL=$((FAIL + 1))
FAILURES+=("token savings: rspec")
printf " ${RED}FAIL${NC} rspec: rtk (%s bytes) >= raw (%s bytes)\n" "$rtk_len" "$raw_len"
fi
# rubocop (exits non-zero on offenses, so || true)
raw_len=$( (bundle exec rubocop app/ 2>&1 || true) | wc -c | tr -d ' ')
rtk_len=$( (rtk rubocop app/ 2>&1 || true) | wc -c | tr -d ' ')
if [[ "$rtk_len" -lt "$raw_len" ]]; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} rubocop: rtk (%s bytes) < raw (%s bytes)\n" "$rtk_len" "$raw_len"
else
FAIL=$((FAIL + 1))
FAILURES+=("token savings: rubocop")
printf " ${RED}FAIL${NC} rubocop: rtk (%s bytes) >= raw (%s bytes)\n" "$rtk_len" "$raw_len"
fi
# rake test (passing file)
raw_len=$( (bundle exec rake test TEST=test/models/post_pass_test.rb 2>&1 || true) | wc -c | tr -d ' ')
rtk_len=$( (rtk rake test test/models/post_pass_test.rb 2>&1 || true) | wc -c | tr -d ' ')
if [[ "$rtk_len" -lt "$raw_len" ]]; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} rake test: rtk (%s bytes) < raw (%s bytes)\n" "$rtk_len" "$raw_len"
else
FAIL=$((FAIL + 1))
FAILURES+=("token savings: rake test")
printf " ${RED}FAIL${NC} rake test: rtk (%s bytes) >= raw (%s bytes)\n" "$rtk_len" "$raw_len"
fi
# bundle install (idempotent)
raw_len=$( (bundle install 2>&1 || true) | wc -c | tr -d ' ')
rtk_len=$( (rtk bundle install 2>&1 || true) | wc -c | tr -d ' ')
if [[ "$rtk_len" -lt "$raw_len" ]]; then
PASS=$((PASS + 1))
printf " ${GREEN}PASS${NC} bundle install: rtk (%s bytes) < raw (%s bytes)\n" "$rtk_len" "$raw_len"
else
FAIL=$((FAIL + 1))
FAILURES+=("token savings: bundle install")
printf " ${RED}FAIL${NC} bundle install: rtk (%s bytes) >= raw (%s bytes)\n" "$rtk_len" "$raw_len"
fi
# ── 12. Verbose flag ─────────────────────────────────
section "Verbose flag (-v)"
assert_output "rtk -v rspec (verbose)" \
"RSpec\|passed\|Running\|example" \
rtk -v rspec spec/models/post_spec.rb
# ══════════════════════════════════════════════════════
# Report
# ══════════════════════════════════════════════════════
printf "\n${BOLD}══════════════════════════════════════${NC}\n"
printf "${BOLD}Results: ${GREEN}%d passed${NC}, ${RED}%d failed${NC}, ${YELLOW}%d skipped${NC}\n" "$PASS" "$FAIL" "$SKIP"
if [[ ${#FAILURES[@]} -gt 0 ]]; then
printf "\n${RED}Failures:${NC}\n"
for f in "${FAILURES[@]}"; do
printf " - %s\n" "$f"
done
fi
printf "${BOLD}══════════════════════════════════════${NC}\n"
exit "$FAIL"
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/bin/bash
set -e
REPORT="benchmark-report.md"
+29 -13
View File
@@ -1,27 +1,43 @@
#!/usr/bin/env bash
#!/bin/bash
set -e
echo "🔍 Validating RTK documentation consistency..."
# 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"
# 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
# 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
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
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
done
echo "✅ Python/Go commands: documented in README.md"
echo "✅ Python/Go commands: documented in README.md and CLAUDE.md"
# 4. Hooks cohérents avec doc
HOOK_FILE=".claude/hooks/rtk-rewrite.sh"
-21
View File
@@ -1,21 +0,0 @@
# 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.
-6
View File
@@ -1,6 +0,0 @@
//! Token savings analytics and cost reporting.
pub mod cc_economics;
pub mod ccusage;
pub mod gain;
pub mod session_cmd;
+197 -77
View File
@@ -3,12 +3,9 @@
//! 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;
@@ -16,7 +13,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<i32> {
pub fn run(subcommand: &str, args: &[String], verbose: u8) -> Result<()> {
// 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()
@@ -61,7 +58,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<i32> {
fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -> Result<()> {
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("aws");
@@ -98,7 +95,7 @@ fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -
&stderr,
);
eprintln!("{}", stderr.trim());
return Ok(exit_code_from_output(&output, "aws"));
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = match json_cmd::filter_json_string(&raw, JSON_COMPRESS_DEPTH) {
@@ -120,7 +117,7 @@ fn run_generic(subcommand: &str, args: &[String], verbose: u8, full_sub: &str) -
&filtered,
);
Ok(0)
Ok(())
}
fn run_aws_json(
@@ -166,36 +163,36 @@ fn run_aws_json(
Ok((stdout, stderr, output.status))
}
fn run_aws_filtered(
sub_args: &[&str],
extra_args: &[String],
verbose: u8,
filter_fn: fn(&str) -> Option<String>,
) -> Result<i32> {
fn run_sts_identity(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
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)?;
let (raw, stderr, status) = run_aws_json(&["sts", "get-caller-identity"], extra_args, verbose)?;
if !status.success() {
timer.track(&label, &rtk_label, &stderr, &stderr);
return Ok(exit_code_from_status(&status, "aws"));
timer.track(
"aws sts get-caller-identity",
"rtk aws sts get-caller-identity",
&stderr,
&stderr,
);
std::process::exit(status.code().unwrap_or(1));
}
let filtered = filter_fn(&raw).unwrap_or_else(|| raw.clone());
let filtered = match filter_sts_identity(&raw) {
Some(f) => f,
None => raw.clone(),
};
println!("{}", filtered);
timer.track(&label, &rtk_label, &raw, &filtered);
Ok(0)
timer.track(
"aws sts get-caller-identity",
"rtk aws sts get-caller-identity",
&raw,
&filtered,
);
Ok(())
}
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> {
fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
// s3 ls doesn't support --output json, run as-is and filter text
@@ -216,68 +213,191 @@ fn run_s3_ls(extra_args: &[String], verbose: u8) -> Result<i32> {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
timer.track("aws s3 ls", "rtk aws s3 ls", &stderr, &stderr);
eprintln!("{}", stderr.trim());
return Ok(exit_code_from_output(&output, "aws"));
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = filter_s3_ls(&raw);
println!("{}", filtered);
timer.track("aws s3 ls", "rtk aws s3 ls", &raw, &filtered);
Ok(0)
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_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_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_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_describe_services(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["ecs", "describe-services"],
extra_args,
verbose,
filter_ecs_describe_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_rds_describe(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["rds", "describe-db-instances"],
extra_args,
verbose,
filter_rds_instances,
)
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_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_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_describe_stacks(extra_args: &[String], verbose: u8) -> Result<i32> {
run_aws_filtered(
&["cloudformation", "describe-stacks"],
extra_args,
verbose,
filter_cfn_describe_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(())
}
// --- Filter functions (all use serde_json::Value for resilience) ---
+8 -14
View File
@@ -1,6 +1,4 @@
//! Reads MSBuild binary log files and extracts errors and test results.
use crate::core::utils::strip_ansi;
use crate::utils::strip_ansi;
use anyhow::{Context, Result};
use flate2::read::GzDecoder;
use lazy_static::lazy_static;
@@ -631,8 +629,7 @@ pub fn scrub_sensitive_env_vars(input: &str) -> String {
}
pub fn parse_build_from_text(text: &str) -> BuildSummary {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let clean = strip_ansi(text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut seen_errors: HashSet<(String, String, u32, u32, String)> = HashSet::new();
let mut seen_warnings: HashSet<(String, String, u32, u32, String)> = HashSet::new();
@@ -839,8 +836,7 @@ pub fn parse_build_from_text(text: &str) -> BuildSummary {
}
pub fn parse_test_from_text(text: &str) -> TestSummary {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let clean = strip_ansi(text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut summary = TestSummary {
passed: 0,
@@ -960,9 +956,8 @@ pub fn parse_test_from_text(text: &str) -> TestSummary {
}
pub fn parse_restore_from_text(text: &str) -> RestoreSummary {
let text = text.replace("\r\n", "\n");
let (errors, warnings) = parse_restore_issues_from_text(&text);
let clean = strip_ansi(&text);
let (errors, warnings) = parse_restore_issues_from_text(text);
let clean = strip_ansi(text);
let scrubbed = scrub_sensitive_env_vars(&clean);
RestoreSummary {
@@ -974,8 +969,7 @@ pub fn parse_restore_from_text(text: &str) -> RestoreSummary {
}
pub fn parse_restore_issues_from_text(text: &str) -> (Vec<BinlogIssue>, Vec<BinlogIssue>) {
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let clean = strip_ansi(text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut errors = Vec::new();
let mut warnings = Vec::new();
@@ -1537,7 +1531,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);
@@ -1573,7 +1567,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);
+98 -164
View File
@@ -1,8 +1,6 @@
//! Filters cargo output — build errors, test results, clippy warnings.
use crate::core::runner;
use crate::core::utils::{resolved_command, truncate};
use anyhow::Result;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::ffi::OsString;
use std::sync::OnceLock;
@@ -17,7 +15,7 @@ pub enum CargoCommand {
Nextest,
}
pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<i32> {
pub fn run(cmd: CargoCommand, args: &[String], verbose: u8) -> Result<()> {
match cmd {
CargoCommand::Build => run_build(args, verbose),
CargoCommand::Test => run_test(args, verbose),
@@ -42,11 +40,6 @@ fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<Str
return args.to_vec();
}
// If args already contain `--` (Clap preserved it), no restoration needed
if args.iter().any(|a| a == "--") {
return args.to_vec();
}
// Find `--` in the original command line
let sep_pos = match raw_args.iter().position(|a| a == "--") {
Some(pos) => pos,
@@ -67,17 +60,13 @@ fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<Str
result
}
/// Generic cargo command runner with filtering.
/// Builds the Command with restored `--` separator, then delegates to shared runner.
fn run_cargo_filtered<F>(
subcommand: &str,
args: &[String],
verbose: u8,
filter_fn: F,
) -> Result<i32>
/// Generic cargo command runner with filtering
fn run_cargo_filtered<F>(subcommand: &str, args: &[String], verbose: u8, filter_fn: F) -> Result<()>
where
F: Fn(&str) -> String,
{
let timer = tracking::TimedExecution::start();
let mut cmd = resolved_command("cargo");
cmd.arg(subcommand);
@@ -90,36 +79,61 @@ where
eprintln!("Running: cargo {} {}", subcommand, restored_args.join(" "));
}
runner::run_filtered(
cmd,
&format!("cargo {}", subcommand),
&restored_args.join(" "),
filter_fn,
runner::RunOptions::with_tee(&format!("cargo_{}", subcommand)),
)
let output = cmd
.output()
.with_context(|| format!("Failed to run cargo {}", subcommand))?;
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_fn(&raw);
if let Some(hint) = crate::tee::tee_and_hint(&raw, &format!("cargo_{}", subcommand), exit_code)
{
println!("{}\n{}", filtered, hint);
} else {
println!("{}", filtered);
}
timer.track(
&format!("cargo {} {}", subcommand, restored_args.join(" ")),
&format!("rtk cargo {} {}", subcommand, restored_args.join(" ")),
&raw,
&filtered,
);
if !output.status.success() {
std::process::exit(exit_code);
}
Ok(())
}
fn run_build(args: &[String], verbose: u8) -> Result<i32> {
fn run_build(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("build", args, verbose, filter_cargo_build)
}
fn run_test(args: &[String], verbose: u8) -> Result<i32> {
fn run_test(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("test", args, verbose, filter_cargo_test)
}
fn run_clippy(args: &[String], verbose: u8) -> Result<i32> {
fn run_clippy(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("clippy", args, verbose, filter_cargo_clippy)
}
fn run_check(args: &[String], verbose: u8) -> Result<i32> {
fn run_check(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("check", args, verbose, filter_cargo_build)
}
fn run_install(args: &[String], verbose: u8) -> Result<i32> {
fn run_install(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("install", args, verbose, filter_cargo_install)
}
fn run_nextest(args: &[String], verbose: u8) -> Result<i32> {
fn run_nextest(args: &[String], verbose: u8) -> Result<()> {
run_cargo_filtered("nextest", args, verbose, filter_cargo_nextest)
}
@@ -245,7 +259,7 @@ fn filter_cargo_install(output: &str) -> String {
// Already installed / up to date
if already_installed {
let info = ignored_line.split('`').nth(1).unwrap_or(&ignored_line);
return format!("cargo install: {} already installed", info);
return format!("✓ cargo install: {} already installed", info);
}
// Errors
@@ -294,7 +308,10 @@ fn filter_cargo_install(output: &str) -> String {
// Success
let crate_info = format_crate_info(&installed_crate, &installed_version, "package");
let mut result = format!("cargo install ({}, {} deps compiled)", crate_info, compiled);
let mut result = format!(
"✓ cargo install ({}, {} deps compiled)",
crate_info, compiled
);
for line in &replaced_lines {
result.push_str(&format!("\n {}", line));
@@ -480,7 +497,7 @@ fn filter_cargo_nextest(output: &str) -> String {
} else {
format!("{}, {}s", binary_text, duration)
};
return format!("cargo nextest: {} ({})", parts.join(", "), meta);
return format!("✓ cargo nextest: {} ({})", parts.join(", "), meta);
}
// With failures - show failure details then summary
@@ -545,7 +562,6 @@ fn filter_cargo_build(output: &str) -> String {
let mut compiled = 0;
let mut in_error = false;
let mut current_error = Vec::new();
let mut finished_line: Option<String> = None;
for line in output.lines() {
if line.trim_start().starts_with("Compiling") || line.trim_start().starts_with("Checking") {
@@ -558,7 +574,6 @@ fn filter_cargo_build(output: &str) -> String {
continue;
}
if line.trim_start().starts_with("Finished") {
finished_line = Some(line.trim_start().to_string());
continue;
}
@@ -605,11 +620,7 @@ fn filter_cargo_build(output: &str) -> String {
}
if error_count == 0 && warnings == 0 {
return if let Some(finished) = finished_line {
format!("cargo build ({} crates compiled)\n{}", compiled, finished)
} else {
format!("cargo build ({} crates compiled)", compiled)
};
return format!("✓ cargo build ({} crates compiled)", compiled);
}
let mut result = String::new();
@@ -723,11 +734,11 @@ impl AggregatedTestResult {
if self.has_duration {
format!(
"cargo test: {} ({}, {:.2}s)",
"✓ cargo test: {} ({}, {:.2}s)",
counts, suite_text, self.duration_secs
)
} else {
format!("cargo test: {} ({})", counts, suite_text)
format!("✓ cargo test: {} ({})", counts, suite_text)
}
}
}
@@ -815,7 +826,7 @@ fn filter_cargo_test(output: &str) -> String {
// Fallback: use original behavior if regex failed
for line in &summary_lines {
result.push_str(&format!("{}\n", line));
result.push_str(&format!("✓ {}\n", line));
}
return result.trim().to_string();
}
@@ -837,18 +848,6 @@ fn filter_cargo_test(output: &str) -> String {
}
if result.trim().is_empty() {
let has_compile_errors = output.lines().any(|line| {
let trimmed = line.trim_start();
trimmed.starts_with("error[") || trimmed.starts_with("error:")
});
if has_compile_errors {
let build_filtered = filter_cargo_build(output);
if build_filtered.starts_with("cargo build:") {
return build_filtered.replacen("cargo build:", "cargo test:", 1);
}
}
// Fallback: show last meaningful lines
let meaningful: Vec<&str> = output
.lines()
@@ -867,7 +866,6 @@ fn filter_cargo_clippy(output: &str) -> String {
let mut by_rule: HashMap<String, Vec<String>> = HashMap::new();
let mut error_count = 0;
let mut warning_count = 0;
let mut error_details: Vec<String> = Vec::new();
// Parse clippy output lines
// Format: "warning: description\n --> file:line:col\n |\n | code\n"
@@ -900,7 +898,6 @@ fn filter_cargo_clippy(output: &str) -> String {
let is_error = line.starts_with("error");
if is_error {
error_count += 1;
error_details.push(truncate(line.trim(), 160));
} else {
warning_count += 1;
}
@@ -929,7 +926,7 @@ fn filter_cargo_clippy(output: &str) -> String {
}
if error_count == 0 && warning_count == 0 {
return "cargo clippy: No issues found".to_string();
return "✓ cargo clippy: No issues found".to_string();
}
let mut result = String::new();
@@ -939,17 +936,6 @@ fn filter_cargo_clippy(output: &str) -> String {
));
result.push_str("═══════════════════════════════════════\n");
if !error_details.is_empty() {
result.push_str("\nError details:\n");
for (idx, detail) in error_details.iter().take(5).enumerate() {
result.push_str(&format!(" {}. {}\n", idx + 1, detail));
}
if error_details.len() > 5 {
result.push_str(&format!(" ... +{} more errors\n", error_details.len() - 5));
}
result.push('\n');
}
// Sort rules by frequency
let mut rule_counts: Vec<_> = by_rule.iter().collect();
rule_counts.sort_by(|a, b| b.1.len().cmp(&a.1.len()));
@@ -971,8 +957,28 @@ fn filter_cargo_clippy(output: &str) -> String {
result.trim().to_string()
}
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
crate::core::runner::run_passthrough("cargo", args, verbose)
/// Runs an unsupported cargo subcommand by passing it through directly
pub fn run_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
if verbose > 0 {
eprintln!("cargo passthrough: {:?}", args);
}
let status = resolved_command("cargo")
.args(args)
.status()
.context("Failed to run cargo")?;
let args_str = tracking::args_display(args);
timer.track_passthrough(
&format!("cargo {}", args_str),
&format!("rtk cargo {} (passthrough)", args_str),
);
if !status.success() {
std::process::exit(status.code().unwrap_or(1));
}
Ok(())
}
#[cfg(test)]
@@ -1048,42 +1054,6 @@ mod tests {
assert_eq!(result, vec!["--", "-D", "warnings"]);
}
#[test]
fn test_restore_double_dash_clippy_with_package_flags() {
// rtk cargo clippy -p my-service -p my-crate -- -D warnings
// Clap with trailing_var_arg preserves "--" when args precede it
// → clap gives ["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
let args: Vec<String> = vec![
"-p".into(),
"my-service".into(),
"-p".into(),
"my-crate".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let raw = vec![
"rtk".into(),
"cargo".into(),
"clippy".into(),
"-p".into(),
"my-service".into(),
"-p".into(),
"my-crate".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
// Should NOT double the "--"
assert_eq!(
result,
vec!["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
);
// Verify only one "--" exists
assert_eq!(result.iter().filter(|a| *a == "--").count(), 1);
}
#[test]
fn test_filter_cargo_build_success() {
let output = r#" Compiling libc v0.2.153
@@ -1092,7 +1062,7 @@ mod tests {
Finished dev [unoptimized + debuginfo] target(s) in 15.23s
"#;
let result = filter_cargo_build(output);
assert!(result.contains("cargo build"));
assert!(result.contains("✓ cargo build"));
assert!(result.contains("3 crates compiled"));
}
@@ -1128,7 +1098,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
"Expected compact format, got: {}",
result
);
@@ -1185,7 +1155,7 @@ test result: ok. 32 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("cargo test: 137 passed (4 suites, 1.45s)"),
result.contains("✓ cargo test: 137 passed (4 suites, 1.45s)"),
"Expected aggregated format, got: {}",
result
);
@@ -1249,7 +1219,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("cargo test: 0 passed (3 suites, 0.00s)"),
result.contains("✓ cargo test: 0 passed (3 suites, 0.00s)"),
"Expected compact format for zero tests, got: {}",
result
);
@@ -1269,7 +1239,7 @@ test result: ok. 18 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
result.contains("✓ cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
"Expected compact format with ignored and filtered, got: {}",
result
);
@@ -1284,7 +1254,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
"Expected singular 'suite', got: {}",
result
);
@@ -1298,44 +1268,21 @@ running 15 tests
test result: MALFORMED LINE WITHOUT PROPER FORMAT
"#;
let result = filter_cargo_test(output);
// Should fallback to original behavior (show line without checkmark)
// Should fallback to original behavior (show line with checkmark)
assert!(
result.contains("test result: MALFORMED"),
result.contains("✓ test result: MALFORMED"),
"Expected fallback format, got: {}",
result
);
}
#[test]
fn test_filter_cargo_test_compile_error_preserves_error_header() {
let output = r#" Compiling rtk v0.31.0 (/workspace/projects/rtk)
error[E0425]: cannot find value `missing_symbol` in this scope
--> tests/repro_compile_fail.rs:3:13
|
3 | let _ = missing_symbol;
| ^^^^^^^^^^^^^^ not found in this scope
For more information about this error, try `rustc --explain E0425`.
error: could not compile `rtk` (test "repro_compile_fail") due to 1 previous error
"#;
let result = filter_cargo_test(output);
assert!(result.contains("cargo test: 1 errors, 0 warnings (1 crates)"));
assert!(result.contains("error[E0425]"), "got: {}", result);
assert!(
result.contains("--> tests/repro_compile_fail.rs:3:13"),
"got: {}",
result
);
assert!(!result.starts_with('|'), "got: {}", result);
}
#[test]
fn test_filter_cargo_clippy_clean() {
let output = r#" Checking rtk v0.5.0
Finished dev [unoptimized + debuginfo] target(s) in 1.53s
"#;
let result = filter_cargo_clippy(output);
assert!(result.contains("cargo clippy: No issues found"));
assert!(result.contains("✓ cargo clippy: No issues found"));
}
#[test]
@@ -1362,19 +1309,6 @@ warning: `rtk` (bin) generated 2 warnings
assert!(result.contains("clippy::too_many_arguments"));
}
#[test]
fn test_filter_cargo_clippy_includes_error_details() {
let output = r#" Checking rtk v0.5.0
error: struct literals are not allowed here
warning: unused variable: `x` [unused_variables]
Finished dev [unoptimized + debuginfo] target(s) in 1.53s
"#;
let result = filter_cargo_clippy(output);
assert!(result.contains("cargo clippy: 1 errors, 1 warnings"));
assert!(result.contains("Error details:"));
assert!(result.contains("struct literals are not allowed here"));
}
#[test]
fn test_filter_cargo_install_success() {
let output = r#" Installing rtk v0.11.0
@@ -1391,7 +1325,7 @@ warning: unused variable: `x` [unused_variables]
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
"#;
let result = filter_cargo_install(output);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("rtk v0.11.0"), "got: {}", result);
assert!(result.contains("5 deps compiled"), "got: {}", result);
assert!(result.contains("Replaced"), "got: {}", result);
@@ -1408,7 +1342,7 @@ warning: unused variable: `x` [unused_variables]
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
"#;
let result = filter_cargo_install(output);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("Replacing"), "got: {}", result);
assert!(result.contains("Replaced"), "got: {}", result);
}
@@ -1453,7 +1387,7 @@ error: aborting due to 1 previous error
#[test]
fn test_filter_cargo_install_empty_output() {
let result = filter_cargo_install("");
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("0 deps compiled"), "got: {}", result);
}
@@ -1467,7 +1401,7 @@ error: aborting due to 1 previous error
warning: be sure to add `/Users/user/.cargo/bin` to your PATH
"#;
let result = filter_cargo_install(output);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(
result.contains("be sure to add"),
"PATH warning should be kept: {}",
@@ -1517,7 +1451,7 @@ error: aborting due to 2 previous errors
Installing rtk v0.11.0
"#;
let result = filter_cargo_install(output);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(!result.contains("Locking"), "got: {}", result);
assert!(!result.contains("Blocking"), "got: {}", result);
assert!(!result.contains("Downloading"), "got: {}", result);
@@ -1531,7 +1465,7 @@ error: aborting due to 2 previous errors
"#;
let result = filter_cargo_install(output);
// Path-based install: crate info not extracted from path
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("1 deps compiled"), "got: {}", result);
}
@@ -1557,7 +1491,7 @@ error: aborting due to 2 previous errors
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "cargo nextest: 301 passed (1 binary, 0.192s)",
result, "✓ cargo nextest: 301 passed (1 binary, 0.192s)",
"got: {}",
result
);
@@ -1642,7 +1576,7 @@ error: test run failed
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
result, "✓ cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
"got: {}",
result
);
@@ -1693,7 +1627,7 @@ error: test run failed
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "cargo nextest: 100 passed (5 binaries, 1.234s)",
result, "✓ cargo nextest: 100 passed (5 binaries, 1.234s)",
"got: {}",
result
);
@@ -1728,7 +1662,7 @@ error: test run failed
result
);
assert!(
result.contains("cargo nextest: 10 passed"),
result.contains("✓ cargo nextest: 10 passed"),
"got: {}",
result
);
@@ -8,12 +8,14 @@ use chrono::NaiveDate;
use serde::Serialize;
use std::collections::HashMap;
use super::ccusage::{self, CcusagePeriod, Granularity};
use crate::core::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::core::utils::{format_cpt, format_tokens, format_usd};
use crate::ccusage::{self, CcusagePeriod, Granularity};
use crate::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::utils::{format_cpt, format_tokens, format_usd};
// ── Constants ──
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
@@ -204,7 +206,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 super::ccusage::CcusagePeriod { key, metrics } = entry;
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
@@ -234,7 +236,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 super::ccusage::CcusagePeriod { key, metrics } = entry;
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
@@ -247,7 +249,7 @@ fn merge_weekly(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<WeekStats>) -> Vec<Peri
let monday_key = match convert_saturday_to_monday(&entry.week_start) {
Some(m) => m,
None => {
eprintln!("[warn] Invalid week_start format: {}", entry.week_start);
eprintln!("⚠️ Invalid week_start format: {}", entry.week_start);
continue;
}
};
@@ -272,7 +274,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 super::ccusage::CcusagePeriod { key, metrics } = entry;
let crate::ccusage::CcusagePeriod { key, metrics } = entry;
map.entry(key)
.or_insert_with_key(|k| PeriodEconomics::new(k))
.set_ccusage(&metrics);
@@ -439,7 +441,7 @@ fn display_summary(tracker: &Tracker, verbose: u8) -> Result<()> {
let totals = compute_totals(&periods);
println!("[cost] Claude Code Economics");
println!("💰 Claude Code Economics");
println!("════════════════════════════════════════════════════");
println!();
@@ -547,7 +549,7 @@ fn display_daily(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load daily token savings from database")?;
let periods = merge_daily(cc_daily, rtk_daily);
println!("Daily Economics");
println!("📅 Daily Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
@@ -561,7 +563,7 @@ fn display_weekly(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load weekly token savings from database")?;
let periods = merge_weekly(cc_weekly, rtk_weekly);
println!("Weekly Economics");
println!("📅 Weekly Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
@@ -575,7 +577,7 @@ fn display_monthly(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load monthly token savings from database")?;
let periods = merge_monthly(cc_monthly, rtk_monthly);
println!("Monthly Economics");
println!("📅 Monthly Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
+17 -5
View File
@@ -1,10 +1,10 @@
//! Parses Claude Code spending data for economics reporting.
//! ccusage CLI integration module
//!
//! 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::core::utils::{resolved_command, tool_exists};
use crate::utils::{resolved_command, tool_exists};
use anyhow::{Context, Result};
use serde::Deserialize;
use std::process::Command;
@@ -111,6 +111,11 @@ fn build_command() -> Option<Command> {
None
}
/// Check if ccusage CLI is available (binary or via npx)
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)
@@ -120,7 +125,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
let mut cmd = match build_command() {
Some(cmd) => cmd,
None => {
eprintln!("[warn] ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
eprintln!("⚠️ ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
return Ok(None);
}
};
@@ -140,7 +145,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
let output = match output {
Err(e) => {
eprintln!("[warn] ccusage execution failed: {}", e);
eprintln!("⚠️ ccusage execution failed: {}", e);
return Ok(None);
}
Ok(o) => o,
@@ -149,7 +154,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!(
"[warn] ccusage exited with {}: {}",
"⚠️ ccusage exited with {}: {}",
output.status,
stderr.trim()
);
@@ -322,4 +327,11 @@ 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
}
}
-203
View File
@@ -1,203 +0,0 @@
# 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
@@ -1,11 +0,0 @@
# 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
-1
View File
@@ -1 +0,0 @@
automod::dir!(pub "src/cmds/cloud");
-9
View File
@@ -1,9 +0,0 @@
# .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)
-1
View File
@@ -1 +0,0 @@
automod::dir!(pub "src/cmds/dotnet");
-15
View File
@@ -1,15 +0,0 @@
# 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`)
-1
View File
@@ -1 +0,0 @@
automod::dir!(pub "src/cmds/git");
-9
View File
@@ -1,9 +0,0 @@
# 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
-501
View File
@@ -1,501 +0,0 @@
//! 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;
#[derive(Debug, Deserialize)]
struct Position {
#[serde(rename = "Filename")]
filename: String,
#[serde(rename = "Line")]
#[allow(dead_code)]
line: usize,
#[serde(rename = "Column")]
#[allow(dead_code)]
column: usize,
#[serde(rename = "Offset", default)]
#[allow(dead_code)]
offset: usize,
}
#[derive(Debug, Deserialize)]
struct Issue {
#[serde(rename = "FromLinter")]
from_linter: String,
#[serde(rename = "Text")]
#[allow(dead_code)]
text: String,
#[serde(rename = "Pos")]
pos: Position,
#[serde(rename = "SourceLines", default)]
source_lines: Vec<String>,
#[serde(rename = "Severity", default)]
#[allow(dead_code)]
severity: String,
}
#[derive(Debug, Deserialize)]
struct GolangciOutput {
#[serde(rename = "Issues")]
issues: Vec<Issue>,
}
/// Parse major version number from `golangci-lint --version` output.
/// Returns 1 on any failure (safe fallback — v1 behaviour).
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 ..."
for word in version_output.split_whitespace() {
if let Some(major) = word.split('.').next().and_then(|s| s.parse::<u32>().ok()) {
if word.contains('.') {
return major;
}
}
}
1
}
/// Run `golangci-lint --version` and return the major version number.
/// Returns 1 on any failure.
pub(crate) fn detect_major_version() -> u32 {
let output = resolved_command("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
};
parse_major_version(version_text)
}
Err(_) => 1,
}
}
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let version = detect_major_version();
let mut cmd = resolved_command("golangci-lint");
// Force JSON output (only if user hasn't specified it)
let has_format = args.iter().any(|a| {
a == "--out-format"
|| a.starts_with("--out-format=")
|| a == "--output.json.path"
|| a.starts_with("--output.json.path=")
});
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");
}
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
if version >= 2 {
eprintln!("Running: golangci-lint run --output.json.path stdout");
} else {
eprintln!("Running: golangci-lint run --out-format=json");
}
}
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(),
)?;
// 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
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 {
Ok(o) => o,
Err(e) => {
return format!(
"golangci-lint (JSON parse failed: {})\n{}",
e,
truncate(output, config::limits().passthrough_max_chars)
);
}
};
let issues = golangci_output.issues;
if issues.is_empty() {
return "golangci-lint: No issues found".to_string();
}
let total_issues = issues.len();
// Count unique files
let unique_files: std::collections::HashSet<_> =
issues.iter().map(|i| &i.pos.filename).collect();
let total_files = unique_files.len();
// Group by linter
let mut by_linter: HashMap<String, usize> = HashMap::new();
for issue in &issues {
*by_linter.entry(issue.from_linter.clone()).or_insert(0) += 1;
}
// Group by file
let mut by_file: HashMap<&str, usize> = HashMap::new();
for issue in &issues {
*by_file.entry(issue.pos.filename.as_str()).or_insert(0) += 1;
}
let mut file_counts: Vec<_> = by_file.iter().collect();
file_counts.sort_by(|a, b| b.1.cmp(a.1));
// Build output
let mut result = String::new();
result.push_str(&format!(
"golangci-lint: {} issues in {} files\n",
total_issues, total_files
));
result.push_str("═══════════════════════════════════════\n");
// Show top linters
let mut linter_counts: Vec<_> = by_linter.iter().collect();
linter_counts.sort_by(|a, b| b.1.cmp(a.1));
if !linter_counts.is_empty() {
result.push_str("Top linters:\n");
for (linter, count) in linter_counts.iter().take(10) {
result.push_str(&format!(" {} ({}x)\n", linter, count));
}
result.push('\n');
}
// Show top files
result.push_str("Top files:\n");
for (file, count) in file_counts.iter().take(10) {
let short_path = compact_path(file);
result.push_str(&format!(" {} ({} issues)\n", short_path, count));
// Show top 3 linters in this file
let mut file_linters: HashMap<String, Vec<&Issue>> = HashMap::new();
for issue in issues.iter().filter(|i| i.pos.filename.as_str() == **file) {
file_linters
.entry(issue.from_linter.clone())
.or_default()
.push(issue);
}
let mut file_linter_counts: Vec<_> = file_linters.iter().collect();
file_linter_counts.sort_by(|a, b| b.1.len().cmp(&a.1.len()));
for (linter, linter_issues) in file_linter_counts.iter().take(3) {
result.push_str(&format!(" {} ({})\n", linter, linter_issues.len()));
// v2 only: show first source line for this linter-file group
if version >= 2 {
if let Some(first_issue) = linter_issues.first() {
if let Some(source_line) = first_issue.source_lines.first() {
let trimmed = source_line.trim();
let display = match trimmed.char_indices().nth(80) {
Some((i, _)) => &trimmed[..i],
None => trimmed,
};
result.push_str(&format!(" → {}\n", display));
}
}
}
}
}
if file_counts.len() > 10 {
result.push_str(&format!("\n... +{} more files\n", file_counts.len() - 10));
}
result.trim().to_string()
}
/// Compact file path (remove common prefixes)
fn compact_path(path: &str) -> String {
let path = path.replace('\\', "/");
if let Some(pos) = path.rfind("/pkg/") {
format!("pkg/{}", &path[pos + 5..])
} else if let Some(pos) = path.rfind("/cmd/") {
format!("cmd/{}", &path[pos + 5..])
} else if let Some(pos) = path.rfind("/internal/") {
format!("internal/{}", &path[pos + 10..])
} else if let Some(pos) = path.rfind('/') {
path[pos + 1..].to_string()
} else {
path
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_golangci_no_issues() {
let output = r#"{"Issues":[]}"#;
let result = filter_golangci_json(output, 1);
assert!(result.contains("golangci-lint"));
assert!(result.contains("No issues found"));
}
#[test]
fn test_filter_golangci_with_issues() {
let output = r#"{
"Issues": [
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Pos": {"Filename": "main.go", "Line": 42, "Column": 5}
},
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Pos": {"Filename": "main.go", "Line": 50, "Column": 10}
},
{
"FromLinter": "gosimple",
"Text": "Should use strings.Contains",
"Pos": {"Filename": "utils.go", "Line": 15, "Column": 2}
}
]
}"#;
let result = filter_golangci_json(output, 1);
assert!(result.contains("3 issues"));
assert!(result.contains("2 files"));
assert!(result.contains("errcheck"));
assert!(result.contains("gosimple"));
assert!(result.contains("main.go"));
assert!(result.contains("utils.go"));
}
#[test]
fn test_compact_path() {
assert_eq!(
compact_path("/Users/foo/project/pkg/handler/server.go"),
"pkg/handler/server.go"
);
assert_eq!(
compact_path("/home/user/app/cmd/main/main.go"),
"cmd/main/main.go"
);
assert_eq!(
compact_path("/project/internal/config/loader.go"),
"internal/config/loader.go"
);
assert_eq!(compact_path("relative/file.go"), "file.go");
}
#[test]
fn test_parse_version_v1_format() {
assert_eq!(parse_major_version("golangci-lint version 1.59.1"), 1);
}
#[test]
fn test_parse_version_v2_format() {
assert_eq!(
parse_major_version("golangci-lint has version 2.10.0 built with go1.26.0 from 95dcb68a on 2026-02-17T13:05:51Z"),
2
);
}
#[test]
fn test_parse_version_empty_returns_1() {
assert_eq!(parse_major_version(""), 1);
}
#[test]
fn test_parse_version_malformed_returns_1() {
assert_eq!(parse_major_version("not a version string"), 1);
}
#[test]
fn test_filter_golangci_v2_fields_parse_cleanly() {
// v2 JSON includes Severity, SourceLines, Offset — must not panic
let output = r#"{
"Issues": [
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Severity": "error",
"SourceLines": [" if err := foo(); err != nil {"],
"Pos": {"Filename": "main.go", "Line": 42, "Column": 5, "Offset": 1024}
}
]
}"#;
let result = filter_golangci_json(output, 2);
assert!(result.contains("errcheck"));
assert!(result.contains("main.go"));
}
#[test]
fn test_filter_v2_shows_source_lines() {
let output = r#"{
"Issues": [
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Severity": "error",
"SourceLines": [" if err := foo(); err != nil {"],
"Pos": {"Filename": "main.go", "Line": 42, "Column": 5, "Offset": 0}
}
]
}"#;
let result = filter_golangci_json(output, 2);
assert!(
result.contains("→"),
"v2 should show source line with → prefix"
);
assert!(result.contains("if err := foo()"));
}
#[test]
fn test_filter_v1_does_not_show_source_lines() {
let output = r#"{
"Issues": [
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Severity": "error",
"SourceLines": [" if err := foo(); err != nil {"],
"Pos": {"Filename": "main.go", "Line": 42, "Column": 5, "Offset": 0}
}
]
}"#;
let result = filter_golangci_json(output, 1);
assert!(!result.contains("→"), "v1 should not show source lines");
}
#[test]
fn test_filter_v2_empty_source_lines_graceful() {
let output = r#"{
"Issues": [
{
"FromLinter": "errcheck",
"Text": "Error return value not checked",
"Severity": "",
"SourceLines": [],
"Pos": {"Filename": "main.go", "Line": 42, "Column": 5, "Offset": 0}
}
]
}"#;
let result = filter_golangci_json(output, 2);
assert!(result.contains("errcheck"));
assert!(
!result.contains("→"),
"no source line to show, should degrade gracefully"
);
}
#[test]
fn test_filter_v2_source_line_truncated_to_80_chars() {
let long_line = "x".repeat(120);
let output = format!(
r#"{{
"Issues": [
{{
"FromLinter": "lll",
"Text": "line too long",
"Severity": "",
"SourceLines": ["{}"],
"Pos": {{"Filename": "main.go", "Line": 1, "Column": 1, "Offset": 0}}
}}
]
}}"#,
long_line
);
let result = filter_golangci_json(&output, 2);
// Content truncated at 80 chars; prefix " → " = 10 bytes (6 spaces + 3-byte arrow + space)
// Total line max = 80 + 10 = 90 bytes
for line in result.lines() {
if line.trim_start().starts_with('→') {
assert!(line.len() <= 90, "source line too long: {}", line.len());
}
}
}
#[test]
fn test_filter_v2_source_line_truncated_non_ascii() {
// Japanese characters are 3 bytes each; 30 chars = 90 bytes > 80 bytes naive slice would panic
let long_line = "日".repeat(30); // 30 chars, 90 bytes
let output = format!(
r#"{{
"Issues": [
{{
"FromLinter": "lll",
"Text": "line too long",
"Severity": "",
"SourceLines": ["{}"],
"Pos": {{"Filename": "main.go", "Line": 1, "Column": 1, "Offset": 0}}
}}
]
}}"#,
long_line
);
// Should not panic and output should be ≤ 80 chars
let result = filter_golangci_json(&output, 2);
for line in result.lines() {
if line.trim_start().starts_with('→') {
let content = line.trim_start().trim_start_matches('→').trim();
assert!(
content.chars().count() <= 80,
"content chars: {}",
content.chars().count()
);
}
}
}
fn count_tokens(text: &str) -> usize {
text.split_whitespace().count()
}
#[test]
fn test_golangci_v2_token_savings() {
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);
assert!(
savings >= 60.0,
"Expected ≥60% token savings, got {:.1}%\nFiltered output:\n{}",
savings,
filtered
);
}
}
-1
View File
@@ -1 +0,0 @@
automod::dir!(pub "src/cmds/go");
Loaded 100 of 220 files, more files were not shown because too many files have changed in this diff. Show more