diff --git a/.github/docs-pipeline-contract.md b/.github/docs-pipeline-contract.md new file mode 100644 index 000000000..f812912cd --- /dev/null +++ b/.github/docs-pipeline-contract.md @@ -0,0 +1,57 @@ +# RTK Documentation — Interface Contract + +This directory contains user-facing documentation for the RTK website. +It feeds `rtk-ai/rtk-website` via the `prepare-docs.mjs` pipeline. + +**Scope**: `docs/guide/` is website content only. Technical and contributor documentation +lives in the codebase (distributed, co-located pattern): +- `ARCHITECTURE.md` — System design, ADRs, filtering strategies +- `CONTRIBUTING.md` — Design philosophy, PR process, TOML vs Rust +- `SECURITY.md` — Vulnerability policy +- `src/*/README.md` — Per-module implementation docs +- `hooks/README.md` — Hook system and agent integrations + +## Structure + +``` +docs/ + README.md <- This file (interface contract — do not remove) + guide/ -> User-facing documentation (website "Guide" tab) + index.md + getting-started/ + installation.md + quick-start.md + supported-agents.md + what-rtk-covers.md + analytics/ + gain.md + configuration.md + troubleshooting.md +``` + +## Frontmatter (required on every .md) + +Every markdown file under `docs/guide/` must include: + +```yaml +--- +title: string # Page title (used in sidebar + search) +description: string # One-line summary for search results and SEO +sidebar: + order: number # Position within the sidebar group (1 = first) +--- +``` + +The `prepare-docs.mjs` pipeline validates this at build time and fails fast +if frontmatter is missing or malformed. + +## Conventions + +- **Filenames**: kebab-case, `.md` only +- **Subdirectories**: become sidebar groups in Starlight +- **Internal links**: relative (`./foo.md`, `../configuration.md`) +- **Diagrams**: Mermaid in fenced code blocks +- **Code samples**: always specify the language (`rust`, `toml`, `bash`) +- **Language**: English only +- **No `rtk ` syntax**: users never type `rtk` — hooks rewrite commands transparently. + Only `rtk gain`, `rtk init`, `rtk verify`, and `rtk proxy` appear as user-typed commands. diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9a986e169..b9091c583 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.34.1" + ".": "0.34.3" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c203a381..50c8a240d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,37 @@ 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.3](https://github.com/rtk-ai/rtk/compare/v0.34.2...v0.34.3) (2026-04-02) + + +### Bug Fixes + +* **automod:** add auto discovery for cmds ([234909d](https://github.com/rtk-ai/rtk/commit/234909d2c754ade2fdc939b0a1435a8e34ffc305)) +* **ci:** fix validate-docs.sh broken module count check ([bbe3da6](https://github.com/rtk-ai/rtk/commit/bbe3da642b5fc4b065b13a65647ea0ebf5264e65)) +* **cleaning:** constant extract ([aabc016](https://github.com/rtk-ai/rtk/commit/aabc0167bc013fd2d0c61a687580f6e69305500a)) +* **cmds:** migrate remaining exit_code to exit_code_from_output ([ba9fa34](https://github.com/rtk-ai/rtk/commit/ba9fa345f3d1d14bd0af236ec9aa8a9a0e5581d6)) +* **cmds:** more covering for run_filtered ([e48485a](https://github.com/rtk-ai/rtk/commit/e48485adc6a33d12b70664598020595cf7dfcd7e)) +* **docs:** add documentation ([2f7278a](https://github.com/rtk-ai/rtk/commit/2f7278ac5992bf2e84b763fb05642d89900ba495)) +* **docs:** add maintainers docs ([14265b4](https://github.com/rtk-ai/rtk/commit/14265b48c3a15e459a31da11250a51ab5830a508)) +* **refacto-p1:** unified cmds execution flow (+ rm dead code) ([75bd607](https://github.com/rtk-ai/rtk/commit/75bd607d55235f313855f5fe8c9eceafd73700a7)) +* **refacto-p2:** more standardize ([47a76ea](https://github.com/rtk-ai/rtk/commit/47a76ea35ed2fe02a3600792163f727fa3a94ff2)) +* **refacto-p2:** more standardize ([92c671a](https://github.com/rtk-ai/rtk/commit/92c671a175a5e2bf09720fd1a8591140bcb473a0)) +* **refacto:** wrappers for standardization, exit codes lexer tokenizer, constants, code clean ([bff0258](https://github.com/rtk-ai/rtk/commit/bff02584243f1b73418418b0c05365acf56fbb36)) +* **registry:** quoted env prefix + inline regex cleanup + routing docs ([f3217a4](https://github.com/rtk-ai/rtk/commit/f3217a467b543a3181605b257162f2b3ab5d5df0)) +* **review:** address PR [#910](https://github.com/rtk-ai/rtk/issues/910) review feedback ([0a8b8fd](https://github.com/rtk-ai/rtk/commit/0a8b8fd0693fa504f376146cbbcafe9ddf4632c8)) +* **review:** PR [#934](https://github.com/rtk-ai/rtk/issues/934) ([5bd35a3](https://github.com/rtk-ai/rtk/commit/5bd35a33ad6abe5278749726bed19912664531c2)) +* **review:** PR [#934](https://github.com/rtk-ai/rtk/issues/934) ([bae7930](https://github.com/rtk-ai/rtk/commit/bae79301194bbb48d1cbb39554096c3225f7cb73)) +* **rules:** add wc RtkRule with pattern field for develop compat ([d75e864](https://github.com/rtk-ai/rtk/commit/d75e864f20451a5e17918c75f2ea32672f65e1f4)) +* **standardize:** git+kube sub wrappers run_filtered ([7fd221f](https://github.com/rtk-ai/rtk/commit/7fd221f44660bcf411aa333d2c35a49ff89e7961)) +* **standardize:** merge pattern into rues ([08aabb9](https://github.com/rtk-ai/rtk/commit/08aabb95c3ae6e0b734f696264e1e1a8c0f0b22e)) + +## [0.34.2](https://github.com/rtk-ai/rtk/compare/v0.34.1...v0.34.2) (2026-03-30) + + +### Bug Fixes + +* **emots:** replace 📊 with "Summary:" ([495a152](https://github.com/rtk-ai/rtk/commit/495a152059feabc7b516b96e804757608b87a10a)) +* **refacto-codebase:** technical docs & sub folders ([927daef](https://github.com/rtk-ai/rtk/commit/927daef49b8f771d195201d196378e27e0ee8a2b)) ## [Unreleased] ### Features diff --git a/Cargo.lock b/Cargo.lock index 21dbaa3ec..e1309d2eb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -903,7 +903,7 @@ dependencies = [ [[package]] name = "rtk" -version = "0.34.1" +version = "0.34.3" dependencies = [ "anyhow", "automod", diff --git a/Cargo.toml b/Cargo.toml index 843a154da..68ed2aaf6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rtk" -version = "0.34.1" +version = "0.34.3" edition = "2021" authors = ["Patrick Szymkowiak"] description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption" diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md deleted file mode 100644 index cf52f026d..000000000 --- a/docs/TROUBLESHOOTING.md +++ /dev/null @@ -1,337 +0,0 @@ -# RTK Troubleshooting Guide - -## Problem: "rtk gain" command not found - -### Symptom -```bash -$ rtk --version -rtk 1.0.0 # (or similar) - -$ rtk gain -rtk: 'gain' is not a rtk command. See 'rtk --help'. -``` - -### Root Cause -You installed the **wrong rtk package**. You have **Rust Type Kit** (reachingforthejack/rtk) instead of **Rust Token Killer** (rtk-ai/rtk). - -### Solution - -**1. Uninstall the wrong package:** -```bash -cargo uninstall rtk -``` - -**2. Install the correct one (Token Killer):** - -#### Quick Install (Linux/macOS) -```bash -curl -fsSL https://github.com/rtk-ai/rtk/blob/master/install.sh | sh -``` - -#### Alternative: Manual Installation -```bash -cargo install --git https://github.com/rtk-ai/rtk -``` - -**3. Verify installation:** -```bash -rtk --version -rtk gain # MUST show token savings stats, not error -``` - -If `rtk gain` now works, installation is correct. - ---- - -## Problem: Confusion Between Two "rtk" Projects - -### The Two Projects - -| Project | Repository | Purpose | Key Command | -|---------|-----------|---------|-------------| -| **Rust Token Killer** ✅ | rtk-ai/rtk | LLM token optimizer for Claude Code | `rtk gain` | -| **Rust Type Kit** ❌ | reachingforthejack/rtk | Rust codebase query and type generator | `rtk query` | - -### How to Identify Which One You Have - -```bash -# Check if "gain" command exists -rtk gain - -# Token Killer → Shows token savings stats -# Type Kit → Error: "gain is not a rtk command" -``` - ---- - -## Problem: cargo install rtk installs wrong package - -### Why This Happens -If **Rust Type Kit** is published to crates.io under the name `rtk`, running `cargo install rtk` will install the wrong package. - -### Solution -**NEVER use** `cargo install rtk` without verifying. - -**Always use explicit repository URLs:** - -```bash -# CORRECT - Token Killer -cargo install --git https://github.com/rtk-ai/rtk - -# OR install from fork -git clone https://github.com/rtk-ai/rtk.git -cd rtk && git checkout feat/all-features -cargo install --path . --force -``` - -**After any installation, ALWAYS verify:** -```bash -rtk gain # Must work if you want Token Killer -``` - ---- - -## Problem: RTK not working in Claude Code - -### Symptom -Claude Code doesn't seem to be using rtk, outputs are verbose. - -### Checklist - -**1. Verify rtk is installed and correct:** -```bash -rtk --version -rtk gain # Must show stats -``` - -**2. Initialize rtk for Claude Code:** -```bash -# Global (all projects) -rtk init --global - -# Per-project -cd /your/project -rtk init -``` - -**3. Verify CLAUDE.md file exists:** -```bash -# Check global -cat ~/.claude/CLAUDE.md | grep rtk - -# Check project -cat ./CLAUDE.md | grep rtk -``` - -**4. Install auto-rewrite hook (recommended for automatic RTK usage):** - -**Option A: Automatic (recommended)** -```bash -rtk init -g -# → Installs hook + RTK.md automatically -# → Follow printed instructions to add hook to ~/.claude/settings.json -# → Restart Claude Code - -# Verify installation -rtk init --show # Should show "✅ Hook: executable, with guards" -``` - -**Option B: Manual (fallback)** -```bash -# Copy hook to Claude Code hooks directory -mkdir -p ~/.claude/hooks -cp .claude/hooks/rtk-rewrite.sh ~/.claude/hooks/ -chmod +x ~/.claude/hooks/rtk-rewrite.sh -``` - -Then add to `~/.claude/settings.json` (replace `~` with full path): -```json -{ - "hooks": { - "PreToolUse": [ - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "/Users/yourname/.claude/hooks/rtk-rewrite.sh" - } - ] - } - ] - } -} -``` - -**Note**: Use absolute path in `settings.json`, not `~/.claude/...` - ---- - -## Problem: RTK not working in OpenCode - -### Symptom -OpenCode runs commands without rtk, outputs are verbose. - -### Checklist - -**1. Verify rtk is installed and correct:** -```bash -rtk --version -rtk gain # Must show stats -``` - -**2. Install the OpenCode plugin (global only):** -```bash -rtk init -g --opencode -``` - -**3. Verify plugin file exists:** -```bash -ls -la ~/.config/opencode/plugins/rtk.ts -``` - -**4. Restart OpenCode** -OpenCode must be restarted to load the plugin. - -**5. Verify status:** -```bash -rtk init --show # Should show "OpenCode: plugin installed" -``` - ---- - -## Problem: RTK commands fail on Windows ("program not found" or "No such file") - -### Symptom -``` -rtk vitest --run -# Error: program not found -# Or: The system cannot find the file specified - -rtk lint . -# Error: No such file or directory -``` - -### Root Cause -On Windows, Node.js tools (vitest, eslint, tsc, etc.) are installed as `.CMD` or `.BAT` wrapper scripts, not as native `.exe` binaries. Rust's `std::process::Command::new("vitest")` does not honor the Windows `PATHEXT` environment variable, so it cannot find `vitest.CMD` even when it's on PATH. - -### Solution -Update to rtk v0.23.1+ which resolves this via the `which` crate for proper PATH+PATHEXT resolution. All 16+ command modules now use `resolved_command()` instead of `Command::new()`. - -```bash -cargo install --git https://github.com/rtk-ai/rtk -rtk --version # Should be 0.23.1+ -``` - -### Affected Commands -All commands that spawn external tools: `rtk vitest`, `rtk lint`, `rtk tsc`, `rtk pnpm`, `rtk playwright`, `rtk prisma`, `rtk next`, `rtk prettier`, `rtk ruff`, `rtk pytest`, `rtk pip`, `rtk mypy`, `rtk golangci-lint`, and others. - ---- - -## Problem: "command not found: rtk" after installation - -### Symptom -```bash -$ cargo install --path . --force - Compiling rtk v0.7.1 - Finished release [optimized] target(s) - Installing ~/.cargo/bin/rtk - -$ rtk --version -zsh: command not found: rtk -``` - -### Root Cause -`~/.cargo/bin` is not in your PATH. - -### Solution - -**1. Check if cargo bin is in PATH:** -```bash -echo $PATH | grep -o '[^:]*\.cargo[^:]*' -``` - -**2. If not found, add to PATH:** - -For **bash** (`~/.bashrc`): -```bash -export PATH="$HOME/.cargo/bin:$PATH" -``` - -For **zsh** (`~/.zshrc`): -```bash -export PATH="$HOME/.cargo/bin:$PATH" -``` - -For **fish** (`~/.config/fish/config.fish`): -```fish -set -gx PATH $HOME/.cargo/bin $PATH -``` - -**3. Reload shell config:** -```bash -source ~/.bashrc # or ~/.zshrc or restart terminal -``` - -**4. Verify:** -```bash -which rtk -rtk --version -rtk gain -``` - ---- - -## Problem: Compilation errors during installation - -### Symptom -```bash -$ cargo install --path . -error: failed to compile rtk v0.7.1 -``` - -### Solutions - -**1. Update Rust toolchain:** -```bash -rustup update stable -rustup default stable -``` - -**2. Clean and rebuild:** -```bash -cargo clean -cargo build --release -cargo install --path . --force -``` - -**3. Check Rust version (minimum required):** -```bash -rustc --version # Should be 1.70+ for most features -``` - -**4. If still fails, report issue:** -- GitHub: https://github.com/rtk-ai/rtk/issues - ---- - -## Need More Help? - -**Report issues:** -- Fork-specific: https://github.com/rtk-ai/rtk/issues -- Upstream: https://github.com/rtk-ai/rtk/issues - -**Run the diagnostic script:** -```bash -# From the rtk repository root -bash scripts/check-installation.sh -``` - -This script will check: -- ✅ RTK installed and in PATH -- ✅ Correct version (Token Killer, not Type Kit) -- ✅ Available features (pnpm, vitest, next, etc.) -- ✅ Claude Code integration (CLAUDE.md files) -- ✅ Auto-rewrite hook status - -The script provides specific fix commands for any issues found. diff --git a/docs/guide/analytics/discover.md b/docs/guide/analytics/discover.md new file mode 100644 index 000000000..77d21cc65 --- /dev/null +++ b/docs/guide/analytics/discover.md @@ -0,0 +1,58 @@ +--- +title: Discover and Session +description: Find missed savings opportunities with rtk discover, and track RTK adoption with rtk session +sidebar: + order: 2 +--- + +# Discover and Session + +## rtk discover — find missed savings + +`rtk discover` analyzes your Claude Code command history to identify commands that ran without RTK filtering and calculates how many tokens you lost. + +```bash +rtk discover # analyze current project history +rtk discover --all # all projects +rtk discover --all --since 7 # last 7 days, all projects +``` + +**Example output:** + +``` +Missed savings analysis (last 7 days) +──────────────────────────────────── +Command Count Est. lost +cargo test 12 ~48,000 tokens +git log 8 ~12,000 tokens +pnpm list 3 ~6,000 tokens +──────────────────────────────────── +Total missed: 23 ~66,000 tokens + +Run `rtk init --global` to capture these automatically. +``` + +If commands appear in the missed list after installing RTK, it usually means the hook isn't active for that agent. See [Troubleshooting](../troubleshooting.md) — "Agent not using RTK". + +## rtk session — adoption tracking + +`rtk session` shows RTK adoption across recent Claude Code sessions: how many shell commands ran through RTK vs. raw. + +```bash +rtk session +``` + +**Example output:** + +``` +Recent sessions (last 10) +───────────────────────────────────────────────────── +Session Total RTK Coverage +2026-04-06 14:32 (45 cmds) 45 43 95.6% +2026-04-05 09:14 (38 cmds) 38 38 100.0% +2026-04-04 16:50 (52 cmds) 52 49 94.2% +───────────────────────────────────────────────────── +Average coverage: 96.6% +``` + +Low coverage on a session usually means RTK was disabled (`RTK_DISABLED=1`) or the hook wasn't active for a specific subagent. diff --git a/docs/guide/analytics/gain.md b/docs/guide/analytics/gain.md new file mode 100644 index 000000000..db2249d4b --- /dev/null +++ b/docs/guide/analytics/gain.md @@ -0,0 +1,196 @@ +--- +title: Token Savings Analytics +description: Measure and analyze your RTK token savings with rtk gain +sidebar: + order: 1 +--- + +# Token Savings Analytics + +`rtk gain` shows how many tokens RTK has saved across all your commands, with daily, weekly, and monthly breakdowns. + +## Quick reference + +```bash +# Default summary +rtk gain + +# Temporal breakdowns +rtk gain --daily # all days since tracking started +rtk gain --weekly # aggregated by week +rtk gain --monthly # aggregated by month +rtk gain --all # all breakdowns at once + +# Classic flags +rtk gain --graph # ASCII graph, last 30 days +rtk gain --history # last 10 commands +rtk gain --quota -t pro # quota analysis (pro/5x/20x tiers) + +# Export +rtk gain --all --format json > savings.json +rtk gain --all --format csv > savings.csv +``` + +## Daily breakdown + +```bash +rtk gain --daily +``` + +``` +📅 Daily Breakdown (3 days) +════════════════════════════════════════════════════════════════ +Date Cmds Input Output Saved Save% +──────────────────────────────────────────────────────────────── +2026-01-28 89 380.9K 26.7K 355.8K 93.4% +2026-01-29 102 894.5K 32.4K 863.7K 96.6% +2026-01-30 5 749 55 694 92.7% +──────────────────────────────────────────────────────────────── +TOTAL 196 1.3M 59.2K 1.2M 95.6% +``` + +- **Cmds**: RTK commands executed +- **Input**: Estimated tokens from raw command output +- **Output**: Actual tokens after filtering +- **Saved**: Input - Output (tokens that never reached the LLM) +- **Save%**: Saved / Input × 100 + +## Weekly and monthly breakdowns + +```bash +rtk gain --weekly +rtk gain --monthly +``` + +Same columns as daily, aggregated by Sunday-Saturday week or calendar month. + +## Export formats + +| Format | Flag | Use case | +|--------|------|----------| +| `text` | default | Terminal display | +| `json` | `--format json` | Programmatic analysis, dashboards | +| `csv` | `--format csv` | Excel, Python/R, Google Sheets | + +**JSON structure:** +```json +{ + "summary": { + "total_commands": 196, + "total_input": 1276098, + "total_output": 59244, + "total_saved": 1220217, + "avg_savings_pct": 95.62 + }, + "daily": [...], + "weekly": [...], + "monthly": [...] +} +``` + +## Typical savings by command + +| Command | Typical savings | Mechanism | +|---------|----------------|-----------| +| `git status` | 77-93% | Compact stat format | +| `eslint` | 84% | Group by rule | +| `vitest run` | 94-99% | Show failures only | +| `find` | 75% | Tree format | +| `pnpm list` | 70-90% | Compact dependencies | +| `grep` | 70% | Truncate + group | + +## How token estimation works + +RTK estimates tokens using `text.len() / 4` (4 characters per token average). This is accurate to ±10% compared to actual LLM tokenization — sufficient for trend analysis. + +``` +Input Tokens = estimate_tokens(raw_command_output) +Output Tokens = estimate_tokens(rtk_filtered_output) +Saved Tokens = Input - Output +Savings % = (Saved / Input) × 100 +``` + +## Database + +Savings data is stored locally in SQLite: + +- **Location**: `~/.local/share/rtk/history.db` (Linux / macOS) +- **Retention**: 90 days (automatic cleanup) +- **Scope**: Global across all projects and Claude sessions + +```bash +# Inspect raw data +sqlite3 ~/.local/share/rtk/history.db \ + "SELECT timestamp, rtk_cmd, saved_tokens FROM commands + ORDER BY timestamp DESC LIMIT 10" + +# Backup +cp ~/.local/share/rtk/history.db ~/backups/rtk-history-$(date +%Y%m%d).db + +# Reset +rm ~/.local/share/rtk/history.db # recreated on next command +``` + +## Analysis workflows + +```bash +# Weekly progress: generate a CSV report every Monday +rtk gain --weekly --format csv > reports/week-$(date +%Y-%W).csv + +# Monthly budget review +rtk gain --monthly --format json | jq '.monthly[] | + {month, saved_tokens, quota_pct: (.saved_tokens / 6000000 * 100)}' + +# Cron: daily JSON snapshot for a dashboard +0 0 * * * rtk gain --all --format json > /var/www/dashboard/rtk-stats.json +``` + +**Python/pandas:** +```python +import pandas as pd +import subprocess + +result = subprocess.run(['rtk', 'gain', '--all', '--format', 'csv'], + capture_output=True, text=True) +lines = result.stdout.split('\n') +daily_start = lines.index('# Daily Data') + 2 +daily_end = lines.index('', daily_start) +daily_df = pd.read_csv(pd.StringIO('\n'.join(lines[daily_start:daily_end]))) +daily_df['date'] = pd.to_datetime(daily_df['date']) +daily_df.plot(x='date', y='savings_pct', kind='line') +``` + +**GitHub Actions (weekly stats):** +```yaml +on: + schedule: + - cron: '0 0 * * 1' +jobs: + stats: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - run: cargo install rtk + - run: rtk gain --weekly --format json > stats/week-$(date +%Y-%W).json + - run: git add stats/ && git commit -m "Weekly rtk stats" && git push +``` + +## Troubleshooting + +**No data showing:** +```bash +ls -lh ~/.local/share/rtk/history.db +sqlite3 ~/.local/share/rtk/history.db "SELECT COUNT(*) FROM commands" +git status # run any tracked command to generate data +``` + +**Incorrect statistics:** Token estimation is a heuristic. For precise counts, use `tiktoken`: +```bash +pip install tiktoken +git status > output.txt +python -c " +import tiktoken +enc = tiktoken.get_encoding('cl100k_base') +print(len(enc.encode(open('output.txt').read())), 'actual tokens') +" +``` diff --git a/docs/guide/getting-started/configuration.md b/docs/guide/getting-started/configuration.md new file mode 100644 index 000000000..f2b1d5a2e --- /dev/null +++ b/docs/guide/getting-started/configuration.md @@ -0,0 +1,115 @@ +--- +title: Configuration +description: Customize RTK behavior via config.toml, environment variables, and per-project filters +sidebar: + order: 4 +--- + +# Configuration + +## Config file location + +| Platform | Path | +|----------|------| +| Linux | `~/.config/rtk/config.toml` | +| macOS | `~/Library/Application Support/rtk/config.toml` | + +```bash +rtk config # show current configuration +rtk config --create # create config file with defaults +``` + +## Full config structure + +```toml +[tracking] +enabled = true # enable/disable token tracking +history_days = 90 # retention in days (auto-cleanup) +database_path = "/custom/path/tracking.db" # optional override + +[display] +colors = true # colored output +emoji = true # use emojis in output +max_width = 120 # maximum output width + +[filters] +ignore_dirs = [".git", "node_modules", "target", "__pycache__", ".venv", "vendor"] +ignore_files = ["*.lock", "*.min.js", "*.min.css"] + +[tee] +enabled = true # save raw output on failure +mode = "failures" # "failures" (default), "always", "never" +max_files = 20 # rotation: keep last N files +# directory = "/custom/tee/path" # optional override + +[telemetry] +enabled = true # anonymous daily ping (opt-out below) + +[hooks] +exclude_commands = [] # commands to never auto-rewrite +``` + +## Environment variables + +| Variable | Description | +|----------|-------------| +| `RTK_DISABLED=1` | Disable RTK for a single command (`RTK_DISABLED=1 git status`) | +| `RTK_TEE_DIR` | Override the tee directory | +| `RTK_TELEMETRY_DISABLED=1` | Disable telemetry | +| `RTK_HOOK_AUDIT=1` | Enable hook audit logging | +| `SKIP_ENV_VALIDATION=1` | Skip env validation (useful with Next.js) | + +## Tee system + +When a command fails, RTK saves the full raw output to a local file and prints the path: + +``` +FAILED: 2/15 tests +[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log] +``` + +Your AI assistant can then read the file if it needs more detail, without re-running the command. + +| Setting | Default | Description | +|---------|---------|-------------| +| `tee.enabled` | `true` | Enable/disable | +| `tee.mode` | `"failures"` | `"failures"`, `"always"`, `"never"` | +| `tee.max_files` | `20` | Rotation: keep last N files | +| Min size | 500 bytes | Outputs shorter than this are not saved | +| Max file size | 1 MB | Truncated above this | + +## Excluding commands from auto-rewrite + +Prevent specific commands from being rewritten by the hook: + +```toml +[hooks] +exclude_commands = ["git rebase", "git cherry-pick", "docker exec"] +``` + +Or for a single invocation: + +```bash +RTK_DISABLED=1 git rebase main +``` + +## Telemetry + +RTK sends one anonymous ping per day (23h interval). No personal data, no file paths, no command content. + +Data sent: device hash, version, OS, architecture, command count/24h, top commands, savings %. + +To opt out: + +```bash +# Via environment variable +export RTK_TELEMETRY_DISABLED=1 + +# Via config.toml +[telemetry] +enabled = false +``` + +## Per-project filters + +Create `.rtk/filters.toml` in your project root to add custom filters or override built-ins. See [`src/filters/README.md`](https://github.com/rtk-ai/rtk/blob/master/src/filters/README.md) for the full TOML DSL reference. diff --git a/docs/guide/getting-started/installation.md b/docs/guide/getting-started/installation.md new file mode 100644 index 000000000..3f3eac286 --- /dev/null +++ b/docs/guide/getting-started/installation.md @@ -0,0 +1,81 @@ +--- +title: Installation +description: Install RTK via curl, Homebrew, Cargo, or from source, and verify the correct version +sidebar: + order: 1 +--- + +# Installation + +## Name collision warning + +Two unrelated projects share the name `rtk`. Make sure you install the right one: + +- **Rust Token Killer** (`rtk-ai/rtk`) — this project, a token-saving CLI proxy +- **Rust Type Kit** (`reachingforthejack/rtk`) — a different tool for generating Rust types + +The easiest way to verify you have the correct one: run `rtk gain`. It should display token savings stats. If it returns "command not found", you either have the wrong package or RTK is not installed. + +## Check before installing + +```bash +rtk --version # should print: rtk x.y.z +rtk gain # should show token savings stats +``` + +If both commands work, RTK is already installed. Skip to [Project initialization](#project-initialization). + +## Quick install (Linux and macOS) + +```bash +curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh +``` + +## Homebrew (macOS and Linux) + +```bash +brew install rtk-ai/tap/rtk +``` + +## Cargo + +```bash +cargo install rtk +``` + +## Verify installation + +```bash +rtk --version # rtk x.y.z +rtk gain # token savings dashboard +``` + +If `rtk gain` fails but `rtk --version` succeeds, you installed Rust Type Kit by mistake. Uninstall it first: + +```bash +cargo uninstall rtk +``` + +Then reinstall using one of the methods above. + +## Project initialization + +Run once per project to enable the Claude Code hook: + +```bash +rtk init +``` + +For a global install that patches `settings.json` automatically: + +```bash +rtk init --global +``` + +## Uninstall + +```bash +rtk init -g --uninstall # remove hook, RTK.md, and settings.json entry +cargo uninstall rtk # remove binary (if installed via Cargo) +brew uninstall rtk # remove binary (if installed via Homebrew) +``` diff --git a/docs/guide/getting-started/quick-start.md b/docs/guide/getting-started/quick-start.md new file mode 100644 index 000000000..af661ebff --- /dev/null +++ b/docs/guide/getting-started/quick-start.md @@ -0,0 +1,70 @@ +--- +title: Quick Start +description: Get RTK running in 5 minutes and see your first token savings +sidebar: + order: 2 +--- + +# Quick Start + +This guide walks you through your first RTK commands after installation. + +## Prerequisites + +RTK is installed and verified: + +```bash +rtk --version # rtk x.y.z +rtk gain # shows token savings dashboard +``` + +If not, see [Installation](./installation.md). + +## Step 1: Initialize for your AI assistant + +```bash +# For Claude Code (global — applies to all projects) +rtk init --global + +# For a single project only +cd /your/project && rtk init +``` + +This installs the hook that automatically rewrites commands. Restart your AI assistant after this step. + +## Step 2: Use your tools normally + +Once the hook is installed, nothing changes in how you work. Your AI assistant runs commands as usual — the hook intercepts them transparently and rewrites them before execution. + +For example, when Claude Code runs `cargo test`, the hook rewrites it to `rtk cargo test` before it executes. The LLM receives filtered output with only the failures — not 500 lines of passing tests. You never see or type `rtk`. + +Supported ecosystems: Git, Cargo/Rust, JavaScript (vitest, tsc, eslint, pnpm, Next.js, Prisma), Python, Go, Ruby, .NET, Docker/Kubernetes, GitHub CLI, and more. See [What RTK Optimizes](../what-rtk-covers.md) for the full list. + +## Step 3: Check your savings + +After a few commands, see how much was saved: + +```bash +rtk gain +``` + +``` +Total commands : 12 +Input tokens : 45,230 +Output tokens : 4,890 +Saved : 40,340 (89.2%) +``` + +## Step 4: Unsupported commands + +Commands RTK doesn't recognize run through passthrough — output is unchanged, usage is tracked: + +```bash +rtk proxy make install +``` + +## Next steps + +- [What RTK Optimizes](../what-rtk-covers.md) — all supported commands and savings by ecosystem +- [Supported agents](./supported-agents.md) — Claude Code, Cursor, Copilot, and more +- [Configuration](./configuration.md) — customize RTK behavior diff --git a/docs/guide/getting-started/supported-agents.md b/docs/guide/getting-started/supported-agents.md new file mode 100644 index 000000000..dc45bf970 --- /dev/null +++ b/docs/guide/getting-started/supported-agents.md @@ -0,0 +1,147 @@ +--- +title: Supported Agents +description: How to integrate RTK with Claude Code, Cursor, Copilot, Cline, Windsurf, Codex, and OpenCode +sidebar: + order: 3 +--- + +# Supported Agents + +RTK supports 10 AI coding agents across 3 integration tiers. Mistral Vibe support is planned. + +## How it works + +Each agent integration intercepts CLI commands before execution and rewrites them to their RTK equivalent. The agent runs `rtk cargo test` instead of `cargo test`, sees filtered output, and uses up to 90% fewer tokens — without any change to your workflow. + +All rewrite logic lives in the RTK binary (`rtk rewrite`). Agent hooks are thin delegates that parse the agent-specific JSON format and call `rtk rewrite` for the actual decision. + +``` +Agent runs "cargo test" + -> Hook intercepts (PreToolUse / plugin event) + -> Calls rtk rewrite "cargo test" + -> Returns "rtk cargo test" + -> Agent executes filtered command + -> LLM sees 90% fewer tokens +``` + +## Supported agents + +| Agent | Integration tier | Can rewrite transparently? | +|-------|-----------------|---------------------------| +| Claude Code | Shell hook (`PreToolUse`) | Yes | +| VS Code Copilot Chat | Shell hook (`PreToolUse`) | Yes | +| GitHub Copilot CLI | Shell hook (deny-with-suggestion) | No (agent retries) | +| Cursor | Shell hook (`preToolUse`) | Yes | +| Gemini CLI | Rust binary (`BeforeTool`) | Yes | +| OpenCode | TypeScript plugin (`tool.execute.before`) | Yes | +| OpenClaw | TypeScript plugin (`before_tool_call`) | Yes | +| Cline / Roo Code | Rules file (prompt-level) | N/A | +| Windsurf | Rules file (prompt-level) | N/A | +| Codex CLI | AGENTS.md instructions | N/A | +| Mistral Vibe | Planned ([#800](https://github.com/rtk-ai/rtk/issues/800)) | Pending upstream | + +## Installation by agent + +### Claude Code + +```bash +rtk init --global # installs hook + patches settings.json +``` + +Restart Claude Code. Verify: + +```bash +rtk init --show # shows hook status +``` + +### Cursor + +```bash +rtk init --global --cursor +``` + +Restart Cursor. The hook uses `preToolUse` with Cursor's `updated_input` format. + +### VS Code Copilot Chat + +```bash +rtk init --global --copilot +``` + +### Gemini CLI + +```bash +rtk init --global --gemini +``` + +### OpenCode + +```bash +rtk init --global --opencode +``` + +Creates `~/.config/opencode/plugins/rtk.ts`. Uses the `tool.execute.before` hook. + +### OpenClaw + +```bash +openclaw plugins install ./openclaw +``` + +Plugin in the `openclaw/` directory. Uses the `before_tool_call` hook, delegates to `rtk rewrite`. + +### Cline / Roo Code + +```bash +rtk init --cline # creates .clinerules in current project +``` + +Cline reads `.clinerules` as custom instructions. RTK adds guidance telling Cline to prefer `rtk ` over raw commands. + +### Windsurf + +```bash +rtk init --windsurf # creates .windsurfrules in current project +``` + +### Codex CLI + +```bash +rtk init --codex # creates AGENTS.md or patches existing one +``` + +### Mistral Vibe (planned) + +Support is blocked on upstream `BeforeToolCallback` ([mistral-vibe#531](https://github.com/mistralai/mistral-vibe/issues/531)). Tracked in [#800](https://github.com/rtk-ai/rtk/issues/800). + +## Integration tiers explained + +| Tier | Mechanism | How rewrites work | +|------|-----------|------------------| +| **Full hook** | Shell script or Rust binary, intercepts via agent API | Transparent — agent never sees the raw command | +| **Plugin** | TypeScript/JS in agent's plugin system | Transparent — in-place mutation | +| **Rules file** | Prompt-level instructions | Guidance only — agent is told to prefer `rtk ` | + +Rules file integrations (Cline, Windsurf, Codex) rely on the model following instructions. Full hook integrations (Claude Code, Cursor, Gemini) are guaranteed — the command is rewritten before the agent sees it. + +## Graceful degradation + +Hooks never block command execution. If RTK is missing, the hook exits cleanly and the raw command runs unchanged: + +- RTK binary not found: warning to stderr, exit 0 +- Invalid JSON input: pass through unchanged +- RTK version too old: warning to stderr, exit 0 +- Filter logic error: fallback to raw command output + +## Override: disable RTK for one command + +```bash +RTK_DISABLED=1 git status # runs raw git status, no rewrite +``` + +Or exclude commands permanently in `~/.config/rtk/config.toml`: + +```toml +[hooks] +exclude_commands = ["git rebase", "git cherry-pick"] +``` diff --git a/docs/guide/index.md b/docs/guide/index.md new file mode 100644 index 000000000..2b9a09b47 --- /dev/null +++ b/docs/guide/index.md @@ -0,0 +1,55 @@ +--- +title: RTK Documentation +description: RTK (Rust Token Killer) — reduce LLM token consumption by 60-90% on common dev commands, with zero workflow changes +sidebar: + order: 1 +--- + +# RTK — Rust Token Killer + +RTK is a CLI proxy that sits between your AI assistant and your development tools. It filters command output before it reaches the LLM, keeping only what matters and discarding boilerplate, progress bars, and noise. + +**Result:** 60-90% fewer tokens consumed per command, without changing how you work. You run `git status` as usual — RTK's hook intercepts it, filters the output, and the LLM sees a compact 3-line summary instead of 40 lines. + +## How it works + +``` +Your AI assistant runs: git status + ↓ + Hook intercepts (PreToolUse) + ↓ + rtk git status (transparent rewrite) + ↓ + Raw output: 40 lines → Filtered: 3 lines + ~800 tokens → ~60 tokens (92% saved) + ↓ + LLM sees the compact output +``` + +Zero config changes to your workflow. The hook handles everything automatically. + +## What RTK optimizes + +60+ commands across 9 ecosystems — Git, Cargo/Rust, JavaScript, Python, Go, Ruby, .NET, Docker/Kubernetes, and more. See [What RTK Optimizes](./what-rtk-covers.md) for the full list with savings percentages. + +## Get started + +1. **[Installation](./getting-started/installation.md)** — Install RTK and verify you have the right package +2. **[Quick Start](./getting-started/quick-start.md)** — Connect to your AI assistant in 5 minutes +3. **[Supported Agents](./getting-started/supported-agents.md)** — Claude Code, Cursor, Copilot, Gemini, and 7 more + +## Measure your savings + +```bash +rtk gain # total savings across all sessions +rtk gain --daily # day-by-day breakdown +rtk gain --weekly # weekly aggregation +``` + +See [Analytics](./analytics/gain.md) for export formats and analysis workflows. + +## Further reading + +- [Configuration](./getting-started/configuration.md) — config.toml, global flags, env vars, tee recovery +- [Troubleshooting](./troubleshooting.md) — common issues and fixes +- [ARCHITECTURE.md](https://github.com/rtk-ai/rtk/blob/master/ARCHITECTURE.md) — system design for contributors diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.md new file mode 100644 index 000000000..5efcabd9b --- /dev/null +++ b/docs/guide/troubleshooting.md @@ -0,0 +1,156 @@ +--- +title: Troubleshooting +description: Common RTK issues and how to fix them +sidebar: + order: 8 +--- + +# Troubleshooting + +## `rtk gain` says "not a rtk command" + +**Symptom:** +```bash +$ rtk gain +rtk: 'gain' is not a rtk command. See 'rtk --help'. +``` + +**Cause:** You installed **Rust Type Kit** (`reachingforthejack/rtk`) instead of **Rust Token Killer** (`rtk-ai/rtk`). They share the same binary name. + +**Fix:** +```bash +cargo uninstall rtk +curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh +rtk gain # should now show token savings stats +``` + +## How to tell which rtk you have + +| If `rtk gain`... | You have | +|------------------|----------| +| Shows token savings dashboard | Rust Token Killer ✅ | +| Returns "not a rtk command" | Rust Type Kit ❌ | + +## AI assistant not using RTK + +**Symptom:** Claude Code (or another agent) runs `cargo test` instead of `rtk cargo test`. + +**Checklist:** + +1. Verify RTK is installed: + ```bash + rtk --version + rtk gain + ``` + +2. Initialize the hook: + ```bash + rtk init --global # Claude Code + rtk init --global --cursor # Cursor + rtk init --global --opencode # OpenCode + ``` + +3. Restart your AI assistant. + +4. Verify hook status: + ```bash + rtk init --show + ``` + +5. Check `settings.json` has the hook registered (Claude Code): + ```bash + cat ~/.claude/settings.json | grep rtk + ``` + +## RTK not found after `cargo install` + +**Symptom:** +```bash +$ rtk --version +zsh: command not found: rtk +``` + +**Cause:** `~/.cargo/bin` is not in your PATH. + +**Fix:** + +For bash (`~/.bashrc`) or zsh (`~/.zshrc`): +```bash +export PATH="$HOME/.cargo/bin:$PATH" +``` + +For fish (`~/.config/fish/config.fish`): +```fish +set -gx PATH $HOME/.cargo/bin $PATH +``` + +Then reload: +```bash +source ~/.zshrc # or ~/.bashrc +rtk --version +``` + +## RTK not working on Windows + +**Symptom:** +``` +rtk vitest --run +Error: program not found +``` + +**Cause:** On Windows, Node.js tools are installed as `.CMD`/`.BAT` wrappers. Older RTK versions couldn't find them. + +**Fix:** Update to RTK v0.23.1+: +```bash +cargo install --git https://github.com/rtk-ai/rtk +rtk --version # should be 0.23.1+ +``` + +## Compilation error during installation + +```bash +rustup update stable +rustup default stable +cargo clean +cargo build --release +cargo install --path . --force +``` + +Minimum required Rust version: 1.70+. + +## OpenCode not using RTK + +```bash +rtk init --global --opencode +# restart OpenCode +rtk init --show # should show "OpenCode: plugin installed" +``` + +## `cargo install rtk` installs the wrong package + +If Rust Type Kit is published to crates.io under the name `rtk`, `cargo install rtk` may install the wrong one. + +Always use the explicit URL: + +```bash +cargo install --git https://github.com/rtk-ai/rtk +``` + +## Run the diagnostic script + +From the RTK repository root: + +```bash +bash scripts/check-installation.sh +``` + +Checks: +- RTK installed and in PATH +- Correct version (Token Killer, not Type Kit) +- Available features +- Claude Code integration +- Hook status + +## Still stuck? + +Open an issue: https://github.com/rtk-ai/rtk/issues diff --git a/docs/guide/what-rtk-covers.md b/docs/guide/what-rtk-covers.md new file mode 100644 index 000000000..426e91a97 --- /dev/null +++ b/docs/guide/what-rtk-covers.md @@ -0,0 +1,153 @@ +--- +title: What RTK Optimizes +description: Commands and ecosystems automatically optimized by RTK with typical token savings +sidebar: + order: 2 +--- + +# What RTK Optimizes + +Once RTK is installed with a hook, these commands are automatically intercepted and filtered. You run them normally — the hook rewrites them transparently before execution. + +60+ commands across 9 ecosystems. Typical savings: 60-99%. + +## Git + +| Command | Savings | What changes | +|---------|---------|--------------| +| `git status` | 75-93% | Compact stat format, grouped by state | +| `git log` | 80-92% | Hash + author + subject only | +| `git diff` | 70% | Context reduced, headers stripped | +| `git show` | 70% | Same as diff | +| `git stash list` | 75% | Compact one-line per entry | + +## GitHub CLI + +| Command | Savings | What changes | +|---------|---------|--------------| +| `gh pr view` | 87% | Removes ASCII art and verbose metadata | +| `gh pr checks` | 79% | Status + name only, failures highlighted | +| `gh run list` | 82% | Compact workflow run summary | +| `gh issue view` | 80% | Body only, no decoration | + +## Graphite (Stacked PRs) + +| Command | Savings | What changes | +|---------|---------|--------------| +| `gt log` | 75% | Stack summary only | +| `gt status` | 70% | Current branch context | + +## Cargo / Rust + +| Command | Savings | What changes | +|---------|---------|--------------| +| `cargo test` | 90% | Failures only, passed tests suppressed | +| `cargo nextest` | 90% | Same as test | +| `cargo build` | 80% | Errors and warnings only | +| `cargo check` | 80% | Errors and warnings only | +| `cargo clippy` | 80% | Lint warnings grouped by file | + +## JavaScript / TypeScript + +| Command | Savings | What changes | +|---------|---------|--------------| +| `vitest run` | 94-99% | Failures only | +| `tsc` | 75% | Type errors grouped by file | +| `eslint` | 84% | Violations grouped by rule | +| `pnpm list` | 70-90% | Compact dependency tree | +| `pnpm outdated` | 70% | Package + current + latest only | +| `next build` | 80% | Route summary + errors only | +| `prisma migrate` | 75% | Migration status only | +| `playwright test` | 90% | Failures + trace links only | + +## Python + +| Command | Savings | What changes | +|---------|---------|--------------| +| `pytest` | 80-90% | Failures only | +| `ruff check` | 75% | Violations grouped by file | +| `mypy` | 75% | Type errors grouped by file | +| `pip install` | 70% | Installed packages only, progress stripped | + +## Go + +| Command | Savings | What changes | +|---------|---------|--------------| +| `go test` | 80-90% | Failures only | +| `golangci-lint run` | 75% | Violations grouped by file | +| `go build` | 75% | Errors only | + +## Ruby + +| Command | Savings | What changes | +|---------|---------|--------------| +| `rspec` | 80-90% | Failures only | +| `rubocop` | 75% | Offenses grouped by file | +| `rake` | 70% | Task output, build errors highlighted | + +## .NET + +| Command | Savings | What changes | +|---------|---------|--------------| +| `dotnet build` | 80% | Errors and warnings only | +| `dotnet test` | 85-90% | Failures only | +| `dotnet format` | 75% | Changed files only | + +## Docker / Kubernetes + +| Command | Savings | What changes | +|---------|---------|--------------| +| `docker ps` | 65% | Essential columns (name, image, status, port) | +| `docker images` | 60% | Name + tag + size only | +| `docker logs` | 70% | Deduplicated, last N lines | +| `docker compose up` | 75% | Service status, errors highlighted | +| `kubectl get pods` | 65% | Name + status + restarts only | +| `kubectl logs` | 70% | Deduplicated entries | + +## Files and Search + +| Command | Savings | What changes | +|---------|---------|--------------| +| `ls` | 80% | Tree format with file counts | +| `find` | 75% | Tree format | +| `grep` | 70% | Truncated lines, grouped by file | +| `diff` | 65% | Context reduced | +| `wc` | 60% | Compact counts | +| `cat` / `head` / `tail ` | 60-80% | Smart file reading via `rtk read` | +| `rtk smart ` | 85% | 2-line heuristic code summary (signatures only) | + +## Cloud and Data + +| Command | Savings | What changes | +|---------|---------|--------------| +| `aws` | 70% | JSON condensed, relevant fields only | +| `psql` | 65% | Query results without decoration | +| `curl` | 60% | Response body only, headers stripped | + +## Global flags + +These flags apply to all RTK commands and can push savings even higher: + +| Flag | Description | +|------|-------------| +| `-u` / `--ultra-compact` | ASCII icons, inline format — extra token reduction on top of normal filtering | +| `-v` / `--verbose` | Show filtering details on stderr (`-v`, `-vv`, `-vvv` for increasing detail) | + +```bash +# Ultra-compact: even smaller output +git log # → already filtered by RTK +git log -u # → ultra-compact variant (if using rtk directly) + +# Debug: see what RTK is doing +RTK_DISABLED=0 git status -vvv +``` + +## Commands that are not rewritten + +If a command isn't in the list above, RTK runs it through passthrough — the output reaches the LLM unchanged. You can explicitly track unsupported commands: + +```bash +rtk proxy make install # runs make install, tracks usage, no filtering +``` + +To check which commands were missed opportunities: `rtk discover`. diff --git a/src/filters/README.md b/src/filters/README.md index fbd4c4cb0..702f5034f 100644 --- a/src/filters/README.md +++ b/src/filters/README.md @@ -64,3 +64,58 @@ expected = "expected filtered output" Use the command name as the filename: `terraform-plan.toml`, `docker-inspect.toml`, `mix-compile.toml`. For commands with subcommands, prefer `-.toml` over grouping multiple filters in one file. + +## Build and runtime pipeline + +How a `.toml` file goes from contributor → binary → filtered output. + +```mermaid +flowchart TD + A[["src/filters/my-tool.toml\n(new file)"]] --> B + + subgraph BUILD ["cargo build"] + B["build.rs\n1. ls src/filters/*.toml\n2. sort alphabetically\n3. concat → BUILTIN_TOML"] --> C + C{"TOML valid?\nDuplicate names?"} -->|"fail"| D[["Build fails\nerror points to bad file"]] + C -->|"ok"| E[["OUT_DIR/builtin_filters.toml\n(generated)"]] + E --> F["rustc embeds via include_str!"] + F --> G[["rtk binary\nBUILTIN_TOML embedded"]] + end + + subgraph TESTS ["cargo test"] + H["test_builtin_filter_count\nassert_eq!(filters.len(), N)"] -->|"wrong count"| I[["FAIL"]] + J["test_builtin_all_filters_present\nassert!(names.contains('my-tool'))"] -->|"name missing"| K[["FAIL"]] + L["test_builtin_all_filters_have_inline_tests\nassert!(tested.contains(name))"] -->|"no tests"| M[["FAIL"]] + end + + subgraph RUNTIME ["rtk my-tool args"] + R["TomlFilterRegistry::load()\n1. .rtk/filters.toml\n2. ~/.config/rtk/filters.toml\n3. BUILTIN_TOML\n4. passthrough"] --> S + S{"match_command\nmatches?"} -->|"no match"| T[["exec raw (passthrough)"]] + S -->|"match"| U["exec command\ncapture stdout"] + U --> V["8-stage pipeline\nstrip_ansi → replace → match_output\n→ strip/keep_lines → truncate\n→ tail_lines → max_lines → on_empty"] + V --> W[["print filtered output + exit code"]] + end + + G --> H & J & L & R +``` + +## Filter lookup priority + +```mermaid +flowchart LR + CMD["rtk my-tool args"] --> P1 + P1{"1. .rtk/filters.toml\n(project-local)"} + P1 -->|"match"| WIN["apply filter"] + P1 -->|"no match"| P2 + P2{"2. ~/.config/rtk/filters.toml\n(user-global)"} + P2 -->|"match"| WIN + P2 -->|"no match"| P3 + P3{"3. BUILTIN_TOML\n(binary)"} + P3 -->|"match"| WIN + P3 -->|"no match"| P4[["exec raw (passthrough)"]] +``` + +First match wins. A project filter with the same name as a built-in shadows the built-in and triggers a warning: + +``` +[rtk] warning: filter 'make' is shadowing a built-in filter +```