Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
334eeb2039 |
No files matched your search
@@ -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:**
|
||||
|
||||
@@ -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
@@ -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 } => {
|
||||
|
||||
@@ -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+):
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
#!/bin/bash
|
||||
# Auto-format Rust code before commits
|
||||
# Hook: PreToolUse for git commit
|
||||
|
||||
|
||||
@@ -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,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
---
|
||||
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é,
|
||||
@@ -10,8 +9,6 @@ allowed-tools:
|
||||
- Write
|
||||
- Read
|
||||
- AskUserQuestion
|
||||
effort: high
|
||||
tags: [triage, orchestration, issues, pr, security, cross-analysis, rtk]
|
||||
---
|
||||
|
||||
# /rtk-triage
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Copilot Instructions for rtk
|
||||
|
||||
**rtk (Rust Token Killer)** is a CLI proxy that filters and compresses command outputs before they reach an LLM context, saving 60-90% of tokens. It wraps common tools (`git`, `cargo`, `grep`, `pnpm`, `go`, etc.) and outputs condensed summaries instead of raw output.
|
||||
**rtk (Rust Token Killer)** is a CLI proxy that filters and compresses command outputs before they reach an LLM context, saving 60–90% of tokens. It wraps common tools (`git`, `cargo`, `grep`, `pnpm`, `go`, etc.) and outputs condensed summaries instead of raw output.
|
||||
|
||||
## Using rtk in this session
|
||||
|
||||
**Always prefix commands with `rtk` when running shell commands** — this reduces token consumption for every operation you perform.
|
||||
**Always prefix commands with `rtk` when running shell commands** — this is the entire point of the project and reduces token consumption for every operation you perform.
|
||||
|
||||
```bash
|
||||
# Instead of: Use:
|
||||
@@ -17,7 +17,7 @@ grep -r "pattern" src/ rtk grep -r "pattern" src/
|
||||
|
||||
**rtk meta-commands** (always use these directly, no prefix needed):
|
||||
```bash
|
||||
rtk gain # Show token savings analytics
|
||||
rtk gain # Show token savings analytics for this session
|
||||
rtk gain --history # Full command history with per-command savings
|
||||
rtk discover # Scan session history for missed rtk opportunities
|
||||
rtk proxy <cmd> # Run a command raw (no filtering) but still track it
|
||||
@@ -29,38 +29,99 @@ 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.
|
||||
> ⚠️ **Name collision**: `rtk gain` failing means you have `reachingforthejack/rtk` (Rust Type Kit) installed instead of this project. Run `which rtk` and check the binary source.
|
||||
|
||||
## 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
|
||||
# Development build
|
||||
cargo build
|
||||
|
||||
# Run all tests
|
||||
cargo test
|
||||
|
||||
# Run a single test by name
|
||||
cargo test test_filter_git_log
|
||||
|
||||
# Run all tests in a module
|
||||
cargo test git::tests::
|
||||
|
||||
# Run tests with stdout
|
||||
cargo test -- --nocapture
|
||||
|
||||
# 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)
|
||||
# Smoke tests (requires installed binary)
|
||||
bash scripts/test-all.sh
|
||||
```
|
||||
|
||||
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`.
|
||||
```
|
||||
main.rs ← Clap Commands enum → specialized module (git.rs, *_cmd.rs, etc.)
|
||||
↓
|
||||
execute subprocess
|
||||
↓
|
||||
filter/compress output
|
||||
↓
|
||||
tracking::TimedExecution → SQLite (~/.local/share/rtk/tracking.db)
|
||||
```
|
||||
|
||||
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 modules:
|
||||
- **`main.rs`** — Clap `Commands` enum routes every subcommand to its module. Each arm calls `tracking::TimedExecution::start()` before running, then `.track(...)` after.
|
||||
- **`filter.rs`** — Language-aware filtering with `FilterLevel` (`none` / `minimal` / `aggressive`) and `Language` enum. Used by `read` and `smart` commands.
|
||||
- **`tracking.rs`** — SQLite persistence for token savings, scoped per project path. Powers `rtk gain`.
|
||||
- **`tee.rs`** — On filter failure, saves raw output to `~/.local/share/rtk/tee/` and prints a one-line hint so the LLM can re-read without re-running the command.
|
||||
- **`utils.rs`** — Shared helpers: `truncate`, `strip_ansi`, `execute_command`, package-manager auto-detection (pnpm/yarn/npm/npx).
|
||||
|
||||
New commands follow this structure: one file `src/<cmd>_cmd.rs` with a `pub fn run(...)` entry point, registered in the `Commands` enum in `main.rs`.
|
||||
|
||||
## 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.
|
||||
### Error handling
|
||||
- Use `anyhow::Result` throughout (this is a binary, not a library).
|
||||
- Always attach context: `operation.context("description")?` — never bare `?` without context.
|
||||
- No `unwrap()` in production code; `expect("reason")` is acceptable only in tests.
|
||||
- Every filter must fall back to raw command execution on error — never break the user's workflow.
|
||||
|
||||
For the full contribution workflow, design philosophy, and new-filter checklist, see [CONTRIBUTING.md](../CONTRIBUTING.md).
|
||||
### Regex
|
||||
- Compile once with `lazy_static!`, never inside a function body:
|
||||
```rust
|
||||
lazy_static! {
|
||||
static ref RE: Regex = Regex::new(r"pattern").unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
### Testing
|
||||
- Unit tests live **inside the module file** in `#[cfg(test)] mod tests { ... }` — not in `tests/`.
|
||||
- Fixtures are real captured command output in `tests/fixtures/<cmd>_raw.txt`, loaded with `include_str!("../tests/fixtures/...")`.
|
||||
- Each test module defines its own local `fn count_tokens(text: &str) -> usize` (word-split approximation) — there is no shared utility for this.
|
||||
- Token savings assertions use `assert!(savings >= 60.0, ...)`.
|
||||
- Snapshot tests use `assert_snapshot!()` from the `insta` crate; review with `cargo insta review`.
|
||||
|
||||
### Adding a new command
|
||||
1. Create `src/<cmd>_cmd.rs` with `pub fn run(...)`.
|
||||
2. Add `mod <cmd>_cmd;` at the top of `main.rs`.
|
||||
3. Add a variant to the `Commands` enum with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]` for pass-through flags.
|
||||
4. Route the variant in the `match` block, wrapping execution with `tracking::TimedExecution`.
|
||||
5. Write a fixture from real output, then unit tests in the module file.
|
||||
6. Update `README.md` (command list + savings %) and `CHANGELOG.md`.
|
||||
|
||||
### Exit codes
|
||||
Preserve the underlying command's exit code. Use `std::process::exit(code)` when the child process exits non-zero.
|
||||
|
||||
### Performance constraints
|
||||
- Startup must stay under 10ms — no async runtime (no `tokio`/`async-std`).
|
||||
- No blocking I/O at startup; config is loaded on-demand.
|
||||
- Binary size target: <5 MB stripped.
|
||||
|
||||
### Branch naming
|
||||
```
|
||||
fix(scope): short-description
|
||||
feat(scope): short-description
|
||||
chore(scope): short-description
|
||||
```
|
||||
`scope` is the affected component (e.g. `git`, `filter`, `tracking`).
|
||||
@@ -68,7 +68,7 @@ jobs:
|
||||
fi
|
||||
fi
|
||||
VERSION="${MAJOR}.${MINOR}.${PATCH}"
|
||||
TAG="dev-${VERSION}-rc.${{ github.run_number }}"
|
||||
TAG="v${VERSION}-rc.${{ github.run_number }}"
|
||||
|
||||
echo "Next version: $VERSION (from $LATEST_VERSION)"
|
||||
echo "Pre-release tag: $TAG"
|
||||
|
||||
@@ -14,18 +14,6 @@ env:
|
||||
jobs:
|
||||
# ─── Fast gates (fail early, save CI minutes) ───
|
||||
|
||||
check-test-presence:
|
||||
name: test presence
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 50
|
||||
- name: Check filter modules have tests
|
||||
run: |
|
||||
git fetch origin "${{ github.base_ref }}" --depth=1 || true
|
||||
bash scripts/check-test-presence.sh "origin/${{ github.base_ref }}"
|
||||
|
||||
fmt:
|
||||
name: fmt
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.34.1"
|
||||
".": "0.31.0"
|
||||
}
|
||||
+517
-50
@@ -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,42 +224,90 @@ 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% ✓
|
||||
|
||||
RUBY rake_cmd.rs rake/rails test 85-90% ✓
|
||||
rspec_cmd.rs rspec 60%+ ✓
|
||||
rubocop_cmd.rs rubocop 60%+ ✓
|
||||
|
||||
NETWORK wget_cmd.rs wget 85-95% ✓
|
||||
curl_cmd.rs curl 70% ✓
|
||||
|
||||
INFRA aws_cmd.rs aws 80% ✓
|
||||
psql_cmd.rs psql 75% ✓
|
||||
|
||||
DEPENDENCIES deps.rs deps 80-90% ✓
|
||||
|
||||
ENVIRONMENT env_cmd.rs env 60-80% ✓
|
||||
|
||||
SYSTEM init.rs init N/A ✓
|
||||
gain.rs gain N/A ✓
|
||||
config.rs (internal) N/A ✓
|
||||
rewrite_cmd.rs rewrite N/A ✓
|
||||
|
||||
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: 67 modules** (45 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**: 45 (directly exposed to users)
|
||||
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, trust, etc.)
|
||||
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
|
||||
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
|
||||
- **Python Tooling**: 3 modules (ruff, pytest, pip)
|
||||
- **Go Tooling**: 2 modules (go test/build/vet, golangci-lint)
|
||||
- **Ruby Tooling**: 3 modules (rake/minitest, rspec, rubocop) + 1 TOML filter (bundle install)
|
||||
|
||||
---
|
||||
|
||||
@@ -307,7 +422,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 +482,7 @@ Mirrors: lint, prettier Mirrors: git, cargo
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ Python Commands │
|
||||
│ Python Commands (3 modules) │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Module Strategy Output Format Savings
|
||||
@@ -424,7 +539,7 @@ Commands respect active virtualenv via `sys.executable` paths.
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ Go Commands │
|
||||
│ Go Commands (2 modules) │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Module Strategy Output Format Savings
|
||||
@@ -461,7 +576,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)
|
||||
@@ -527,6 +664,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 +738,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 +918,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 +1064,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 +1137,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 +1234,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 +1308,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 +1500,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 +1522,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
|
||||
@@ -5,98 +5,10 @@ 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
|
||||
@@ -254,7 +166,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))
|
||||
|
||||
@@ -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,293 @@ 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) |
|
||||
| rake_cmd.rs | Minitest via rake/rails test | State machine text parser, failures only (85-90% reduction) |
|
||||
| rspec_cmd.rs | RSpec test runner | JSON injection + text fallback, failures only (60%+ reduction) |
|
||||
| rubocop_cmd.rs | RuboCop linter | JSON injection, group by cop/severity (60%+ reduction) |
|
||||
| tee.rs | Full output recovery | Save raw output to file on failure, print hint for LLM re-read |
|
||||
| utils.rs | Shared utilities | Package manager detection, ruby_exec, common formatting |
|
||||
| discover/ | Claude Code history analysis | Scan JSONL sessions, classify commands, report missed savings |
|
||||
|
||||
## Performance Constraints
|
||||
|
||||
RTK has **strict performance targets** to maintain zero-overhead CLI experience:
|
||||
|
||||
| Metric | Target | Verification Method |
|
||||
|--------|--------|---------------------|
|
||||
| **Startup time** | <10ms | `hyperfine 'rtk git status' 'git status'` |
|
||||
| **Memory overhead** | <5MB resident | `/usr/bin/time -l rtk git status` (macOS) |
|
||||
| **Token savings** | 60-90% | Verify in tests with `count_tokens()` assertions |
|
||||
| **Binary size** | <5MB stripped | `ls -lh target/release/rtk` |
|
||||
|
||||
**Performance regressions are release blockers** - always benchmark before/after changes:
|
||||
|
||||
```bash
|
||||
# Before changes
|
||||
hyperfine 'rtk git log -10' --warmup 3 > /tmp/before.txt
|
||||
|
||||
# After changes
|
||||
cargo build --release
|
||||
hyperfine 'target/release/rtk git log -10' --warmup 3 > /tmp/after.txt
|
||||
|
||||
# Compare (should be <10ms)
|
||||
diff /tmp/before.txt /tmp/after.txt
|
||||
```
|
||||
|
||||
**Why <10ms matters**: Claude Code users expect CLI tools to be instant. Any perceptible delay (>10ms) breaks the developer flow. RTK achieves this through:
|
||||
- **Zero async overhead**: Single-threaded, no tokio runtime
|
||||
- **Lazy regex compilation**: Compile once with `lazy_static!`, reuse forever
|
||||
- **Minimal allocations**: Borrow over clone, in-place filtering
|
||||
- **No user config**: Zero file I/O on startup (config loaded on-demand)
|
||||
|
||||
## Error Handling
|
||||
|
||||
RTK follows Rust best practices for error handling:
|
||||
|
||||
**Rules**:
|
||||
- **anyhow::Result** for CLI binary (RTK is an application, not a library)
|
||||
- **ALWAYS** use `.context("description")` with `?` operator
|
||||
- **NO unwrap()** in production code (tests only - use `expect("explanation")` if needed)
|
||||
- **Graceful degradation**: If filter fails, fallback to raw command execution
|
||||
|
||||
**Example**:
|
||||
|
||||
```rust
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
pub fn filter_git_log(input: &str) -> Result<String> {
|
||||
let lines: Vec<_> = input
|
||||
.lines()
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect();
|
||||
|
||||
// ✅ RIGHT: Context on error
|
||||
let hash = extract_hash(lines[0])
|
||||
.context("Failed to extract commit hash from git log")?;
|
||||
|
||||
// ❌ WRONG: No context
|
||||
let hash = extract_hash(lines[0])?;
|
||||
|
||||
// ❌ WRONG: Panic in production
|
||||
let hash = extract_hash(lines[0]).unwrap();
|
||||
|
||||
Ok(format!("Commit: {}", hash))
|
||||
}
|
||||
```
|
||||
|
||||
**Fallback pattern** (critical for all filters):
|
||||
|
||||
```rust
|
||||
// ✅ RIGHT: Fallback to raw command if filter fails
|
||||
pub fn execute_with_filter(cmd: &str, args: &[&str]) -> Result<()> {
|
||||
match get_filter(cmd) {
|
||||
Some(filter) => match filter.apply(cmd, args) {
|
||||
Ok(output) => println!("{}", output),
|
||||
Err(e) => {
|
||||
eprintln!("Filter failed: {}, falling back to raw", e);
|
||||
execute_raw(cmd, args)?;
|
||||
}
|
||||
},
|
||||
None => execute_raw(cmd, args)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ❌ WRONG: Panic if no filter
|
||||
pub fn execute_with_filter(cmd: &str, args: &[&str]) -> Result<()> {
|
||||
let filter = get_filter(cmd).expect("Filter must exist");
|
||||
filter.apply(cmd, args)?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
**Don't add async dependencies** (kills startup time)
|
||||
- RTK is single-threaded by design
|
||||
- Adding tokio/async-std adds ~5-10ms startup overhead
|
||||
- Use blocking I/O with fallback to raw command
|
||||
|
||||
**Don't recompile regex at runtime** (kills performance)
|
||||
- ❌ WRONG: `let re = Regex::new(r"pattern").unwrap();` inside function
|
||||
- ✅ RIGHT: `lazy_static! { static ref RE: Regex = Regex::new(r"pattern").unwrap(); }`
|
||||
|
||||
**Don't panic on filter failure** (breaks user workflow)
|
||||
- Always fallback to raw command execution
|
||||
- Log error to stderr, execute original command unchanged
|
||||
|
||||
**Don't assume command output format** (breaks across versions)
|
||||
- Test with real fixtures from multiple versions
|
||||
- Use flexible regex patterns that tolerate format changes
|
||||
|
||||
**Don't skip cross-platform testing** (macOS ≠ Linux ≠ Windows)
|
||||
- Shell escaping differs: bash/zsh vs PowerShell
|
||||
- Path separators differ: `/` vs `\`
|
||||
- Line endings differ: LF vs CRLF
|
||||
|
||||
**Don't break pipe compatibility** (users expect Unix behavior)
|
||||
- `rtk git status | grep modified` must work
|
||||
- Preserve stdout/stderr separation
|
||||
- Respect exit codes (0 = success, non-zero = failure)
|
||||
|
||||
## Fork-Specific Features
|
||||
|
||||
### PR #5: Git Argument Parsing Fix (CRITICAL)
|
||||
- **Problem**: Git flags like `--oneline`, `--cached` were rejected
|
||||
- **Solution**: Fixed Clap parsing with proper trailing_var_arg configuration
|
||||
- **Impact**: All git commands now accept native git flags
|
||||
|
||||
### PR #6: pnpm Support
|
||||
- **New Commands**: `rtk pnpm list`, `rtk pnpm outdated`, `rtk pnpm install`
|
||||
- **Token Savings**: 70-90% reduction on package manager operations
|
||||
- **Security**: Package name validation prevents command injection
|
||||
|
||||
### PR #9: Modern JavaScript/TypeScript Tooling (2026-01-29)
|
||||
- **New Commands**: 6 commands for T3 Stack workflows
|
||||
- `rtk lint`: ESLint/Biome with grouped rule violations (84% reduction)
|
||||
- `rtk tsc`: TypeScript compiler errors grouped by file/code (83% reduction)
|
||||
- `rtk next`: Next.js build with route/bundle metrics (87% reduction)
|
||||
- `rtk prettier`: Format checker showing files needing changes (70% reduction)
|
||||
- `rtk playwright`: E2E test results showing failures only (94% reduction)
|
||||
- `rtk prisma`: Prisma CLI without ASCII art (88% reduction)
|
||||
- **Shared Infrastructure**: utils.rs module for package manager auto-detection
|
||||
- **Features**: Exit code preservation, error grouping, consistent formatting
|
||||
- **Testing**: Validated on a production T3 Stack project
|
||||
|
||||
### Python & Go Support (2026-02-12)
|
||||
- **Python Commands**: 3 commands for Python development workflows
|
||||
- `rtk ruff check/format`: Ruff linter/formatter with JSON (check) and text (format) parsing (80%+ reduction)
|
||||
- `rtk pytest`: Pytest test runner with state machine text parser (90%+ reduction)
|
||||
- `rtk pip list/outdated/install`: pip package manager with auto-detect uv (70-85% reduction)
|
||||
- **Go Commands**: 4 commands via sub-enum for Go ecosystem
|
||||
- `rtk go test`: NDJSON line-by-line parser for interleaved events (90%+ reduction)
|
||||
- `rtk go build`: Text filter showing errors only (80% reduction)
|
||||
- `rtk go vet`: Text filter for issues (75% reduction)
|
||||
- `rtk golangci-lint`: JSON parsing grouped by rule (85% reduction)
|
||||
- **Architecture**: Standalone Python commands (mirror lint/prettier), Go sub-enum (mirror git/cargo)
|
||||
- **Patterns**: JSON for structured output (ruff check, golangci-lint, pip), NDJSON streaming (go test), text state machine (pytest), text filters (go build/vet, ruff format)
|
||||
|
||||
### Ruby on Rails Support (2026-03-15)
|
||||
- **Ruby Commands**: 3 modules for Ruby/Rails development
|
||||
- `rtk rspec`: RSpec test runner with JSON injection (`--format json`), text fallback (60%+ reduction)
|
||||
- `rtk rubocop`: RuboCop linter with JSON injection, group by cop/severity (60%+ reduction)
|
||||
- `rtk rake test`: Minitest filter via rake/rails test, state machine parser (85-90% reduction)
|
||||
- **TOML Filter**: `bundle-install.toml` for bundle install/update — strips `Using` lines (90%+ reduction)
|
||||
- **Shared Infrastructure**: `ruby_exec()` in utils.rs auto-detects `bundle exec` when Gemfile exists
|
||||
- **Hook Integration**: Rewrites `rspec`, `rubocop`, `rake test`, `rails test`, `bundle exec` variants
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### TDD Workflow (mandatory)
|
||||
All code follows Red-Green-Refactor. See `.claude/skills/rtk-tdd/` for the full workflow and Rust-idiomatic patterns. See `.claude/skills/rtk-tdd/references/testing-patterns.md` for RTK-specific patterns and untested module backlog.
|
||||
|
||||
### Test Architecture
|
||||
- **Unit tests**: Embedded `#[cfg(test)] mod tests` in each module (105+ tests, 25+ files)
|
||||
- **Smoke tests**: `scripts/test-all.sh` (69 assertions on all commands)
|
||||
- **Dominant pattern**: raw string input -> filter function -> assert output contains/excludes
|
||||
|
||||
### Pre-commit gate
|
||||
```bash
|
||||
cargo fmt --all --check && rtk cargo clippy --all-targets && rtk cargo test
|
||||
```
|
||||
|
||||
### Test commands
|
||||
```bash
|
||||
cargo test # All tests
|
||||
cargo test filter::tests:: # Module-specific
|
||||
cargo test -- --nocapture # With stdout
|
||||
bash scripts/test-all.sh # Smoke tests (installed binary required)
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
Core dependencies (see Cargo.toml):
|
||||
- **clap**: CLI parsing with derive macros
|
||||
- **anyhow**: Error handling
|
||||
- **rusqlite**: SQLite for tracking database
|
||||
- **regex**: Pattern matching for filtering
|
||||
- **ignore**: gitignore-aware file traversal
|
||||
- **colored**: Terminal output formatting
|
||||
- **serde/serde_json**: Configuration and JSON parsing
|
||||
|
||||
## Build Optimizations
|
||||
|
||||
Release profile (Cargo.toml:31-36):
|
||||
- `opt-level = 3`: Maximum optimization
|
||||
- `lto = true`: Link-time optimization
|
||||
- `codegen-units = 1`: Single codegen for better optimization
|
||||
- `strip = true`: Remove debug symbols
|
||||
- `panic = "abort"`: Smaller binary size
|
||||
|
||||
## CI/CD
|
||||
|
||||
GitHub Actions workflow (.github/workflows/release.yml):
|
||||
- Multi-platform builds (macOS, Linux x86_64/ARM64, Windows)
|
||||
- DEB/RPM package generation
|
||||
- Automated releases on version tags (v*)
|
||||
- Checksums for binary verification
|
||||
|
||||
## Build Verification (Mandatory)
|
||||
|
||||
@@ -122,14 +467,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 +553,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
|
||||
```
|
||||
+54
-109
@@ -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,107 +22,30 @@
|
||||
|------|----------|
|
||||
| **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
|
||||
```
|
||||
|
||||
---
|
||||
@@ -135,19 +57,18 @@ chore/release-pipeline-cleanup
|
||||
**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
|
||||
- Part 1: Add data model and tests
|
||||
- Part 2: Add CLI command and integration
|
||||
- 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 +79,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
|
||||
|
||||
@@ -203,8 +124,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 +133,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 +184,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
@@ -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.31.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
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rtk"
|
||||
version = "0.34.1"
|
||||
version = "0.31.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"
|
||||
|
||||
@@ -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, --gemini for Gemini CLI)
|
||||
|
||||
# 2. Restart your AI tool, then test
|
||||
# 2. Restart Claude Code, then test
|
||||
git status # Automatically rewritten to rtk git status
|
||||
```
|
||||
|
||||
@@ -294,106 +291,49 @@ rtk init --show # Verify installation
|
||||
|
||||
After install, **restart Claude Code**.
|
||||
|
||||
## Supported AI Tools
|
||||
## Gemini CLI Support (Global)
|
||||
|
||||
RTK supports 10 AI coding tools. Each integration transparently rewrites shell commands to `rtk` equivalents for 60-90% token savings.
|
||||
|
||||
| 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
|
||||
RTK supports Gemini CLI via a native Rust hook processor. The hook intercepts `run_shell_command` tool calls and rewrites them to `rtk` equivalents using the same rewrite engine as Claude Code.
|
||||
|
||||
**Install Gemini hook:**
|
||||
```bash
|
||||
rtk init -g --gemini
|
||||
```
|
||||
|
||||
**What it creates:**
|
||||
- `~/.gemini/hooks/rtk-hook-gemini.sh` (thin wrapper calling `rtk hook gemini`)
|
||||
- `~/.gemini/GEMINI.md` (RTK awareness instructions)
|
||||
- Patches `~/.gemini/settings.json` with BeforeTool hook
|
||||
|
||||
**Uninstall:**
|
||||
```bash
|
||||
rtk init -g --gemini --uninstall
|
||||
```
|
||||
|
||||
Creates `~/.gemini/hooks/rtk-hook-gemini.sh` + patches `~/.gemini/settings.json` with BeforeTool hook.
|
||||
**Restart Required**: Restart Gemini CLI, then test with `git status` in a session.
|
||||
|
||||
### Codex (OpenAI)
|
||||
## OpenCode Plugin (Global)
|
||||
|
||||
```bash
|
||||
rtk init -g --codex
|
||||
```
|
||||
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.
|
||||
|
||||
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 |
|
||||
@@ -472,10 +412,10 @@ brew uninstall rtk # If installed via Homebrew
|
||||
|
||||
## Privacy & Telemetry
|
||||
|
||||
RTK collects **anonymous, aggregate usage metrics** once per day, **enabled by default**. This helps prioritize development. See opt-out options below.
|
||||
RTK collects **anonymous, aggregate usage metrics** once per day to help prioritize development. This is standard practice for open-source CLI tools.
|
||||
|
||||
**What is collected:**
|
||||
- Device hash (salted SHA-256 — per-user random salt stored locally, not reversible)
|
||||
- Device hash (SHA-256 of hostname+username, 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
|
||||
|
||||
@@ -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**
|
||||
@@ -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");
|
||||
|
||||
@@ -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.
|
||||
@@ -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
@@ -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
@@ -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.
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
File renamed without changes.
@@ -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`
|
||||
@@ -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`
|
||||
File renamed without changes.
@@ -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
|
||||
```
|
||||
Regular → Executable
File renamed without changes.
@@ -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.
@@ -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.
File renamed without changes.
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env bash
|
||||
# rtk-hook-version: 2
|
||||
# RTK Claude Code hook — rewrites commands to use rtk for token savings.
|
||||
# Requires: rtk >= 0.23.0, jq
|
||||
#
|
||||
# This is a thin delegating hook: all rewrite logic lives in `rtk rewrite`,
|
||||
# which is the single source of truth (src/discover/registry.rs).
|
||||
# To add or change rewrite rules, edit the Rust registry — not this file.
|
||||
|
||||
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 logic to the Rust binary.
|
||||
# rtk rewrite exits 1 when there's no rewrite — hook passes through silently.
|
||||
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || exit 0
|
||||
|
||||
# No change — nothing to do.
|
||||
if [ "$CMD" = "$REWRITTEN" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
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
|
||||
}
|
||||
}'
|
||||
Regular → Executable
File renamed without changes.
Regular → Executable
+1
-1
@@ -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.
|
||||
#
|
||||
File renamed without changes.
@@ -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`
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
#!/bin/bash
|
||||
# RTK Installation Verification Script
|
||||
# Helps diagnose if you have the correct rtk (Token Killer) installed
|
||||
|
||||
|
||||
@@ -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,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,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
#!/bin/bash
|
||||
# rtk-economics.sh
|
||||
# Combine ccusage (tokens spent) with rtk (tokens saved) for economic analysis
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
REPORT="benchmark-report.md"
|
||||
|
||||
+29
-13
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
@@ -1,6 +0,0 @@
|
||||
//! Token savings analytics and cost reporting.
|
||||
|
||||
pub mod cc_economics;
|
||||
pub mod ccusage;
|
||||
pub mod gain;
|
||||
pub mod session_cmd;
|
||||
@@ -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) ---
|
||||
@@ -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;
|
||||
@@ -1537,7 +1535,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 +1571,7 @@ Time Elapsed 00:00:00.12
|
||||
|
||||
#[test]
|
||||
fn test_parse_test_from_fixture_text() {
|
||||
let input = include_str!("../../../tests/fixtures/dotnet/test_failed.txt");
|
||||
let input = include_str!("../tests/fixtures/dotnet/test_failed.txt");
|
||||
let summary = parse_test_from_text(input);
|
||||
|
||||
assert_eq!(summary.failed, 1);
|
||||
@@ -1,8 +1,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),
|
||||
@@ -67,17 +65,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 +84,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)
|
||||
}
|
||||
|
||||
@@ -545,7 +564,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 +576,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 +622,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();
|
||||
@@ -867,7 +880,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 +912,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;
|
||||
}
|
||||
@@ -939,17 +950,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 +971,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)]
|
||||
@@ -1362,19 +1382,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
|
||||
@@ -8,12 +8,15 @@ 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 ──
|
||||
|
||||
#[allow(dead_code)]
|
||||
const BILLION: f64 = 1e9;
|
||||
|
||||
// API pricing ratios (verified Feb 2026, consistent across Claude models <=200K context)
|
||||
// Source: https://docs.anthropic.com/en/docs/about-claude/models
|
||||
const WEIGHT_OUTPUT: f64 = 5.0; // Output = 5x input
|
||||
@@ -204,7 +207,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 +237,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);
|
||||
@@ -272,7 +275,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);
|
||||
@@ -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,12 @@ fn build_command() -> Option<Command> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if ccusage CLI is available (binary or via npx)
|
||||
#[allow(dead_code)]
|
||||
pub fn is_available() -> bool {
|
||||
build_command().is_some()
|
||||
}
|
||||
|
||||
/// Fetch usage data from ccusage for the last 90 days
|
||||
///
|
||||
/// Returns `Ok(None)` if ccusage is unavailable (graceful degradation)
|
||||
@@ -322,4 +328,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
|
||||
}
|
||||
}
|
||||
@@ -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**
|
||||
@@ -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 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/cloud");
|
||||
@@ -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 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/dotnet");
|
||||
@@ -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 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/git");
|
||||
@@ -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
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/go");
|
||||
@@ -1,15 +0,0 @@
|
||||
# JavaScript / TypeScript / Node
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `utils::package_manager_exec()` auto-detects pnpm/yarn/npm -- JS modules should use this instead of hardcoding a package manager
|
||||
- `lint_cmd.rs` is a cross-ecosystem router: detects Python projects and delegates to `mypy_cmd` or `ruff_cmd`
|
||||
- `vitest_cmd.rs` uses the `parser/` module for structured output parsing
|
||||
- `playwright_cmd.rs` uses the `parser/` module for test result extraction
|
||||
|
||||
## Cross-command
|
||||
|
||||
- `lint_cmd` routes to `cmds/python/mypy_cmd` and `cmds/python/ruff_cmd` for Python projects
|
||||
- `prettier_cmd` is also called by `cmds/system/format_cmd` as a format dispatcher target
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/js");
|
||||
@@ -1,11 +0,0 @@
|
||||
//! Command filter modules organized by language ecosystem.
|
||||
|
||||
pub mod cloud;
|
||||
pub mod dotnet;
|
||||
pub mod git;
|
||||
pub mod go;
|
||||
pub mod js;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
pub mod rust;
|
||||
pub mod system;
|
||||
@@ -1,15 +0,0 @@
|
||||
# Python Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `pytest_cmd.rs` uses a state machine text parser (no JSON available from pytest)
|
||||
- `ruff_cmd.rs` uses JSON for check mode (`--output-format=json`) and text filtering for format mode
|
||||
- `pip_cmd.rs` auto-detects `uv` as a pip alternative and routes accordingly
|
||||
- `python -m pytest` and `python3 -m mypy` are rewritten by the hook registry to `rtk pytest` / `rtk mypy`
|
||||
|
||||
## Cross-command
|
||||
|
||||
- `ruff_cmd` is called by `cmds/js/lint_cmd` and `cmds/system/format_cmd` for Python projects
|
||||
- `mypy_cmd` is called by `cmds/js/lint_cmd` when detecting Python type checking
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/python");
|
||||
@@ -1,11 +0,0 @@
|
||||
# Ruby on Rails
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `rake_cmd.rs` filters Minitest output via `rake test` / `rails test`; state machine text parser, failures only (85-90% reduction)
|
||||
- `rspec_cmd.rs` uses JSON injection (`--format json`) with text fallback; failures only (60%+ reduction)
|
||||
- `rubocop_cmd.rs` uses JSON injection, groups by cop/severity (60%+ reduction)
|
||||
- All three modules use `ruby_exec()` from `utils.rs` to auto-detect `bundle exec` when a Gemfile exists
|
||||
- TOML filter `bundle-install.toml` strips `Using` lines from `bundle install`/`update` (90%+ reduction)
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/ruby");
|
||||
@@ -1,9 +0,0 @@
|
||||
# Rust Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `cargo_cmd.rs` uses `restore_double_dash()` fix: Clap strips `--` but cargo needs it for test flags (e.g., `cargo test -- --nocapture`)
|
||||
- `runner.rs` is a generic two-mode runner (`err` = stderr only, `test` = failures only) used as fallback for commands without a dedicated filter
|
||||
- `runner.rs` is also referenced by other modules outside this directory as a generic command executor
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/rust");
|
||||
@@ -1,14 +0,0 @@
|
||||
# System and Generic Utilities
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `read.rs` uses `core/filter` for language-aware code stripping (FilterLevel: none/minimal/aggressive)
|
||||
- `grep_cmd.rs` reads `core/config` for `limits.grep_max_results` and `limits.grep_max_per_file`
|
||||
- `local_llm.rs` (`rtk smart`) uses `core/filter` for heuristic file summarization
|
||||
- `format_cmd.rs` is a cross-ecosystem dispatcher: auto-detects and routes to `prettier_cmd` or `ruff_cmd` (black is handled inline, not as a separate module)
|
||||
|
||||
## Cross-command
|
||||
|
||||
- `format_cmd` routes to `cmds/js/prettier_cmd` and `cmds/python/ruff_cmd`
|
||||
@@ -1,28 +0,0 @@
|
||||
pub const NOISE_DIRS: &[&str] = &[
|
||||
"node_modules",
|
||||
".git",
|
||||
"target",
|
||||
"__pycache__",
|
||||
".next",
|
||||
"dist",
|
||||
"build",
|
||||
".cache",
|
||||
".turbo",
|
||||
".vercel",
|
||||
".pytest_cache",
|
||||
".mypy_cache",
|
||||
".tox",
|
||||
".venv",
|
||||
"venv",
|
||||
"env",
|
||||
".env",
|
||||
"coverage",
|
||||
".nyc_output",
|
||||
".DS_Store",
|
||||
"Thumbs.db",
|
||||
".idea",
|
||||
".vscode",
|
||||
".vs",
|
||||
"*.egg-info",
|
||||
".eggs",
|
||||
];
|
||||
@@ -1 +0,0 @@
|
||||
automod::dir!(pub "src/cmds/system");
|
||||
@@ -1,6 +1,3 @@
|
||||
//! Reads user settings from config.toml.
|
||||
|
||||
use super::constants::{CONFIG_TOML, DEFAULT_HISTORY_DAYS, RTK_DATA_DIR};
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
@@ -14,7 +11,7 @@ pub struct Config {
|
||||
#[serde(default)]
|
||||
pub filters: FilterConfig,
|
||||
#[serde(default)]
|
||||
pub tee: crate::core::tee::TeeConfig,
|
||||
pub tee: crate::tee::TeeConfig,
|
||||
#[serde(default)]
|
||||
pub telemetry: TelemetryConfig,
|
||||
#[serde(default)]
|
||||
@@ -43,7 +40,7 @@ impl Default for TrackingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
history_days: DEFAULT_HISTORY_DAYS as u32,
|
||||
history_days: 90,
|
||||
database_path: None,
|
||||
}
|
||||
}
|
||||
@@ -169,7 +166,7 @@ impl Config {
|
||||
|
||||
fn get_config_path() -> Result<PathBuf> {
|
||||
let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
Ok(config_dir.join(RTK_DATA_DIR).join(CONFIG_TOML))
|
||||
Ok(config_dir.join("rtk").join("config.toml"))
|
||||
}
|
||||
|
||||
pub fn show_config() -> Result<()> {
|
||||
@@ -1,12 +1,7 @@
|
||||
//! Filters Docker and kubectl output into compact summaries.
|
||||
|
||||
use crate::core::runner::{self, RunOptions};
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::{exit_code_from_output, resolved_command};
|
||||
use crate::tracking;
|
||||
use crate::utils::resolved_command;
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::Value;
|
||||
use std::ffi::OsString;
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum ContainerCmd {
|
||||
@@ -18,7 +13,7 @@ pub enum ContainerCmd {
|
||||
KubectlLogs,
|
||||
}
|
||||
|
||||
pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<i32> {
|
||||
pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<()> {
|
||||
match cmd {
|
||||
ContainerCmd::DockerPs => docker_ps(verbose),
|
||||
ContainerCmd::DockerImages => docker_images(verbose),
|
||||
@@ -29,28 +24,7 @@ pub fn run(cmd: ContainerCmd, args: &[String], verbose: u8) -> Result<i32> {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_kubectl_json<F>(cmd: Command, label: &str, filter_fn: F) -> Result<i32>
|
||||
where
|
||||
F: Fn(&Value) -> String,
|
||||
{
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"kubectl",
|
||||
label,
|
||||
|stdout| match serde_json::from_str::<Value>(stdout) {
|
||||
Ok(json) => filter_fn(&json),
|
||||
Err(e) => {
|
||||
eprintln!("[rtk] kubectl: JSON parse failed: {}", e);
|
||||
stdout.to_string()
|
||||
}
|
||||
},
|
||||
RunOptions::stdout_only()
|
||||
.early_exit_on_failure()
|
||||
.no_trailing_newline(),
|
||||
)
|
||||
}
|
||||
|
||||
fn docker_ps(_verbose: u8) -> Result<i32> {
|
||||
fn docker_ps(_verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let raw = resolved_command("docker")
|
||||
@@ -72,7 +46,7 @@ fn docker_ps(_verbose: u8) -> Result<i32> {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprint!("{}", stderr);
|
||||
timer.track("docker ps", "rtk docker ps", &raw, &raw);
|
||||
return Ok(exit_code_from_output(&output, "docker"));
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
@@ -82,7 +56,7 @@ fn docker_ps(_verbose: u8) -> Result<i32> {
|
||||
rtk.push_str("[docker] 0 containers");
|
||||
println!("{}", rtk);
|
||||
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
|
||||
return Ok(0);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let count = stdout.lines().count();
|
||||
@@ -116,10 +90,10 @@ fn docker_ps(_verbose: u8) -> Result<i32> {
|
||||
|
||||
print!("{}", rtk);
|
||||
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
|
||||
Ok(0)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn docker_images(_verbose: u8) -> Result<i32> {
|
||||
fn docker_images(_verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let raw = resolved_command("docker")
|
||||
@@ -137,7 +111,7 @@ fn docker_images(_verbose: u8) -> Result<i32> {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprint!("{}", stderr);
|
||||
timer.track("docker images", "rtk docker images", &raw, &raw);
|
||||
return Ok(exit_code_from_output(&output, "docker"));
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
@@ -148,7 +122,7 @@ fn docker_images(_verbose: u8) -> Result<i32> {
|
||||
rtk.push_str("[docker] 0 images");
|
||||
println!("{}", rtk);
|
||||
timer.track("docker images", "rtk docker images", &raw, &rtk);
|
||||
return Ok(0);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut total_size_mb: f64 = 0.0;
|
||||
@@ -197,47 +171,89 @@ fn docker_images(_verbose: u8) -> Result<i32> {
|
||||
|
||||
print!("{}", rtk);
|
||||
timer.track("docker images", "rtk docker images", &raw, &rtk);
|
||||
Ok(0)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn docker_logs(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let container = args.first().map(|s| s.as_str()).unwrap_or("");
|
||||
if container.is_empty() {
|
||||
println!("Usage: rtk docker logs <container>");
|
||||
return Ok(0);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut cmd = resolved_command("docker");
|
||||
cmd.args(["logs", "--tail", "100", container]);
|
||||
let output = resolved_command("docker")
|
||||
.args(["logs", "--tail", "100", container])
|
||||
.output()
|
||||
.context("Failed to run docker logs")?;
|
||||
|
||||
let label = format!("logs {}", container);
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"docker",
|
||||
&label,
|
||||
|raw| {
|
||||
format!(
|
||||
"[docker] Logs for {}:\n{}",
|
||||
container,
|
||||
crate::log_cmd::run_stdin_str(raw)
|
||||
)
|
||||
},
|
||||
RunOptions::default().early_exit_on_failure(),
|
||||
)
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if !output.status.success() {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("docker logs {}", container),
|
||||
"rtk docker logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("[docker] Logs for {}:\n{}", container, analyzed);
|
||||
println!("{}", rtk);
|
||||
timer.track(
|
||||
&format!("docker logs {}", container),
|
||||
"rtk docker logs",
|
||||
&raw,
|
||||
&rtk,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kubectl_pods(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = resolved_command("kubectl");
|
||||
cmd.args(["get", "pods", "-o", "json"]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
run_kubectl_json(cmd, "get pods", format_kubectl_pods)
|
||||
}
|
||||
|
||||
fn format_kubectl_pods(json: &Value) -> String {
|
||||
let output = cmd.output().context("Failed to run kubectl get pods")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
rtk.push_str("No pods found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
return "No pods found\n".to_string();
|
||||
rtk.push_str("No pods found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
return Ok(());
|
||||
};
|
||||
let (mut running, mut pending, mut failed, mut restarts_total) = (0, 0, 0, 0i64);
|
||||
let mut issues: Vec<String> = Vec::new();
|
||||
@@ -292,33 +308,61 @@ fn format_kubectl_pods(json: &Value) -> String {
|
||||
parts.push(format!("{} restarts", restarts_total));
|
||||
}
|
||||
|
||||
let mut out = format!("{} pods: {}\n", pods.len(), parts.join(", "));
|
||||
rtk.push_str(&format!("{} pods: {}\n", pods.len(), parts.join(", ")));
|
||||
if !issues.is_empty() {
|
||||
out.push_str("[warn] Issues:\n");
|
||||
rtk.push_str("[warn] Issues:\n");
|
||||
for issue in issues.iter().take(10) {
|
||||
out.push_str(&format!(" {}\n", issue));
|
||||
rtk.push_str(&format!(" {}\n", issue));
|
||||
}
|
||||
if issues.len() > 10 {
|
||||
out.push_str(&format!(" ... +{} more", issues.len() - 10));
|
||||
rtk.push_str(&format!(" ... +{} more", issues.len() - 10));
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
print!("{}", rtk);
|
||||
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kubectl_services(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = resolved_command("kubectl");
|
||||
cmd.args(["get", "services", "-o", "json"]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
run_kubectl_json(cmd, "get services", format_kubectl_services)
|
||||
}
|
||||
|
||||
fn format_kubectl_services(json: &Value) -> String {
|
||||
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
return "No services found\n".to_string();
|
||||
let output = cmd.output().context("Failed to run kubectl get services")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
let mut rtk = String::new();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let json: serde_json::Value = match serde_json::from_str(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
rtk.push_str("No services found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let mut out = format!("{} services:\n", services.len());
|
||||
|
||||
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
|
||||
rtk.push_str("No services found");
|
||||
println!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
return Ok(());
|
||||
};
|
||||
rtk.push_str(&format!("{} services:\n", services.len()));
|
||||
|
||||
for svc in services.iter().take(15) {
|
||||
let ns = svc["metadata"]["namespace"].as_str().unwrap_or("-");
|
||||
@@ -343,7 +387,7 @@ fn format_kubectl_services(json: &Value) -> String {
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
out.push_str(&format!(
|
||||
rtk.push_str(&format!(
|
||||
" {}/{} {} [{}]\n",
|
||||
ns,
|
||||
name,
|
||||
@@ -352,16 +396,21 @@ fn format_kubectl_services(json: &Value) -> String {
|
||||
));
|
||||
}
|
||||
if services.len() > 15 {
|
||||
out.push_str(&format!(" ... +{} more", services.len() - 15));
|
||||
rtk.push_str(&format!(" ... +{} more", services.len() - 15));
|
||||
}
|
||||
out
|
||||
|
||||
print!("{}", rtk);
|
||||
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kubectl_logs(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let pod = args.first().map(|s| s.as_str()).unwrap_or("");
|
||||
if pod.is_empty() {
|
||||
println!("Usage: rtk kubectl logs <pod>");
|
||||
return Ok(0);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut cmd = resolved_command("kubectl");
|
||||
@@ -370,20 +419,33 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
|
||||
let label = format!("logs {}", pod);
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"kubectl",
|
||||
&label,
|
||||
|stdout| {
|
||||
format!(
|
||||
"Logs for {}:\n{}",
|
||||
pod,
|
||||
crate::log_cmd::run_stdin_str(stdout)
|
||||
)
|
||||
},
|
||||
RunOptions::stdout_only().early_exit_on_failure(),
|
||||
)
|
||||
let output = cmd.output().context("Failed to run kubectl logs")?;
|
||||
let raw = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.trim().is_empty() {
|
||||
eprint!("{}", stderr);
|
||||
}
|
||||
timer.track(
|
||||
&format!("kubectl logs {}", pod),
|
||||
"rtk kubectl logs",
|
||||
&raw,
|
||||
&raw,
|
||||
);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let analyzed = crate::log_cmd::run_stdin_str(&raw);
|
||||
let rtk = format!("Logs for {}:\n{}", pod, analyzed);
|
||||
println!("{}", rtk);
|
||||
timer.track(
|
||||
&format!("kubectl logs {}", pod),
|
||||
"rtk kubectl logs",
|
||||
&raw,
|
||||
&rtk,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Format `docker compose ps --format` output into compact form.
|
||||
@@ -523,12 +585,32 @@ fn compact_ports(ports: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_docker_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
|
||||
crate::core::runner::run_passthrough("docker", args, verbose)
|
||||
/// Runs an unsupported docker subcommand by passing it through directly
|
||||
pub fn run_docker_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("docker passthrough: {:?}", args);
|
||||
}
|
||||
let status = resolved_command("docker")
|
||||
.args(args)
|
||||
.status()
|
||||
.context("Failed to run docker")?;
|
||||
|
||||
let args_str = tracking::args_display(args);
|
||||
timer.track_passthrough(
|
||||
&format!("docker {}", args_str),
|
||||
&format!("rtk docker {} (passthrough)", args_str),
|
||||
);
|
||||
|
||||
if !status.success() {
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run `docker compose ps` with compact output
|
||||
pub fn run_compose_ps(verbose: u8) -> Result<i32> {
|
||||
pub fn run_compose_ps(verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
// Raw output for token tracking
|
||||
@@ -540,7 +622,7 @@ pub fn run_compose_ps(verbose: u8) -> Result<i32> {
|
||||
if !raw_output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&raw_output.stderr);
|
||||
eprintln!("{}", stderr);
|
||||
return Ok(exit_code_from_output(&raw_output, "docker"));
|
||||
std::process::exit(raw_output.status.code().unwrap_or(1));
|
||||
}
|
||||
let raw = String::from_utf8_lossy(&raw_output.stdout).to_string();
|
||||
|
||||
@@ -558,7 +640,7 @@ pub fn run_compose_ps(verbose: u8) -> Result<i32> {
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprintln!("{}", stderr);
|
||||
return Ok(exit_code_from_output(&output, "docker"));
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
let structured = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
|
||||
@@ -569,61 +651,132 @@ pub fn run_compose_ps(verbose: u8) -> Result<i32> {
|
||||
let rtk = format_compose_ps(&structured);
|
||||
println!("{}", rtk);
|
||||
timer.track("docker compose ps", "rtk docker compose ps", &raw, &rtk);
|
||||
Ok(0)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_compose_logs(service: Option<&str>, verbose: u8) -> Result<i32> {
|
||||
/// Run `docker compose logs` with deduplication
|
||||
pub fn run_compose_logs(service: Option<&str>, verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = resolved_command("docker");
|
||||
cmd.args(["compose", "logs", "--tail", "100"]);
|
||||
if let Some(svc) = service {
|
||||
cmd.arg(svc);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run docker compose logs")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprintln!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("raw docker compose logs:\n{}", raw);
|
||||
}
|
||||
|
||||
let rtk = format_compose_logs(&raw);
|
||||
println!("{}", rtk);
|
||||
let svc_label = service.unwrap_or("all");
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"docker",
|
||||
&format!("compose logs {}", svc_label),
|
||||
|raw| {
|
||||
if verbose > 0 {
|
||||
eprintln!("raw docker compose logs:\n{}", raw);
|
||||
}
|
||||
format_compose_logs(raw)
|
||||
},
|
||||
RunOptions::default().early_exit_on_failure(),
|
||||
)
|
||||
timer.track(
|
||||
&format!("docker compose logs {}", svc_label),
|
||||
"rtk docker compose logs",
|
||||
&raw,
|
||||
&rtk,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_compose_build(service: Option<&str>, verbose: u8) -> Result<i32> {
|
||||
/// Run `docker compose build` with summary output
|
||||
pub fn run_compose_build(service: Option<&str>, verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let mut cmd = resolved_command("docker");
|
||||
cmd.args(["compose", "build"]);
|
||||
if let Some(svc) = service {
|
||||
cmd.arg(svc);
|
||||
}
|
||||
|
||||
let output = cmd.output().context("Failed to run docker compose build")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
eprintln!("{}", stderr);
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let raw = format!("{}\n{}", stdout, stderr);
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("raw docker compose build:\n{}", raw);
|
||||
}
|
||||
|
||||
let rtk = format_compose_build(&raw);
|
||||
println!("{}", rtk);
|
||||
let svc_label = service.unwrap_or("all");
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"docker",
|
||||
&format!("compose build {}", svc_label),
|
||||
|raw| {
|
||||
if verbose > 0 {
|
||||
eprintln!("raw docker compose build:\n{}", raw);
|
||||
}
|
||||
format_compose_build(raw)
|
||||
},
|
||||
RunOptions::default().early_exit_on_failure(),
|
||||
)
|
||||
timer.track(
|
||||
&format!("docker compose build {}", svc_label),
|
||||
"rtk docker compose build",
|
||||
&raw,
|
||||
&rtk,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_compose_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
|
||||
let mut combined = vec![OsString::from("compose")];
|
||||
combined.extend_from_slice(args);
|
||||
crate::core::runner::run_passthrough("docker", &combined, verbose)
|
||||
/// Runs an unsupported docker compose subcommand by passing it through directly
|
||||
pub fn run_compose_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("docker compose passthrough: {:?}", args);
|
||||
}
|
||||
let status = resolved_command("docker")
|
||||
.arg("compose")
|
||||
.args(args)
|
||||
.status()
|
||||
.context("Failed to run docker compose")?;
|
||||
|
||||
let args_str = tracking::args_display(args);
|
||||
timer.track_passthrough(
|
||||
&format!("docker compose {}", args_str),
|
||||
&format!("rtk docker compose {} (passthrough)", args_str),
|
||||
);
|
||||
|
||||
if !status.success() {
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn run_kubectl_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
|
||||
crate::core::runner::run_passthrough("kubectl", args, verbose)
|
||||
/// Runs an unsupported kubectl subcommand by passing it through directly
|
||||
pub fn run_kubectl_passthrough(args: &[OsString], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
if verbose > 0 {
|
||||
eprintln!("kubectl passthrough: {:?}", args);
|
||||
}
|
||||
let status = resolved_command("kubectl")
|
||||
.args(args)
|
||||
.status()
|
||||
.context("Failed to run kubectl")?;
|
||||
|
||||
let args_str = tracking::args_display(args);
|
||||
timer.track_passthrough(
|
||||
&format!("kubectl {}", args_str),
|
||||
&format!("rtk kubectl {} (passthrough)", args_str),
|
||||
);
|
||||
|
||||
if !status.success() {
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1,123 +0,0 @@
|
||||
# Core Infrastructure
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
## Scope
|
||||
|
||||
Domain-agnostic building blocks with **no knowledge of any specific command, hook, or agent**. If a module references "git", "cargo", "claude", or any external tool by name, it does not belong here. Core is a leaf in the dependency graph — it is consumed by all other components but imports from none of them.
|
||||
|
||||
Owns: configuration loading, token tracking persistence, TOML filter engine, tee output recovery, display formatting, telemetry, and shared utilities.
|
||||
|
||||
Does **not** own: command-specific filtering logic (that's `cmds/`), hook lifecycle management (that's `src/hooks/`), or analytics dashboards (that's `analytics/`).
|
||||
|
||||
## Purpose
|
||||
Core infrastructure shared by all RTK command modules. Every filter, tracker, and command handler depends on these modules. No inward dependencies — leaf in the dependency graph (no circular imports possible).
|
||||
|
||||
## TOML Filter Pipeline
|
||||
|
||||
The TOML DSL applies 8 stages in order:
|
||||
|
||||
1. **strip_ansi**: Remove ANSI escape codes if enabled
|
||||
2. **replace**: Line-by-line regex substitutions (chainable, supports backreferences)
|
||||
3. **match_output**: Short-circuit rules (if output matches pattern, return message; `unless` field prevents swallowing errors)
|
||||
4. **strip/keep_lines**: Filter lines by regex (mutually exclusive)
|
||||
5. **truncate_lines_at**: Truncate each line to N chars (unicode-safe)
|
||||
6. **head/tail_lines**: Keep first N or last N lines (with omit message)
|
||||
7. **max_lines**: Absolute line cap applied after head/tail
|
||||
8. **on_empty**: Return message if result is empty after all stages
|
||||
|
||||
Three-tier filter lookup (first match wins):
|
||||
1. `.rtk/filters.toml` (project-local, requires `rtk trust`)
|
||||
2. `~/.config/rtk/filters.toml` (user-global)
|
||||
3. Built-in filters concatenated by `build.rs` at compile time
|
||||
|
||||
## Tracking Database Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE commands (
|
||||
id INTEGER PRIMARY KEY,
|
||||
timestamp TEXT, -- UTC ISO8601
|
||||
original_cmd TEXT, -- "ls -la"
|
||||
rtk_cmd TEXT, -- "rtk ls"
|
||||
project_path TEXT, -- cwd (for project-scoped stats)
|
||||
input_tokens INTEGER, -- estimated from raw output
|
||||
output_tokens INTEGER, -- estimated from filtered output
|
||||
saved_tokens INTEGER, -- input - output
|
||||
savings_pct REAL, -- (saved / input) * 100
|
||||
exec_time_ms INTEGER -- elapsed milliseconds
|
||||
);
|
||||
|
||||
CREATE TABLE parse_failures (
|
||||
id INTEGER PRIMARY KEY,
|
||||
timestamp TEXT,
|
||||
raw_command TEXT,
|
||||
error_message TEXT,
|
||||
fallback_succeeded INTEGER -- 1=yes, 0=no
|
||||
);
|
||||
```
|
||||
|
||||
Project-scoped queries use GLOB patterns (not LIKE) to avoid `_`/`%` wildcard issues in paths.
|
||||
|
||||
## Config Sections
|
||||
|
||||
```toml
|
||||
[tracking]
|
||||
enabled = true
|
||||
history_days = 90
|
||||
database_path = "/custom/path/to/tracking.db" # Optional
|
||||
|
||||
[display]
|
||||
colors = true
|
||||
emoji = true
|
||||
max_width = 120
|
||||
|
||||
[tee]
|
||||
enabled = true
|
||||
mode = "failures" # failures | always | never
|
||||
max_files = 20
|
||||
max_file_size = 1048576
|
||||
directory = "/custom/tee/dir"
|
||||
|
||||
[telemetry]
|
||||
enabled = true
|
||||
|
||||
[hooks]
|
||||
exclude_commands = ["curl", "playwright"] # Never auto-rewrite these
|
||||
|
||||
[limits]
|
||||
grep_max_results = 200
|
||||
grep_max_per_file = 25
|
||||
status_max_files = 15
|
||||
status_max_untracked = 10
|
||||
passthrough_max_chars = 2000
|
||||
```
|
||||
|
||||
## Shared Utilities (utils.rs)
|
||||
|
||||
Key functions available to all command modules:
|
||||
|
||||
| Function | Purpose |
|
||||
|----------|---------|
|
||||
| `truncate(s, max)` | Truncate string with `...` suffix |
|
||||
| `strip_ansi(text)` | Remove ANSI escape/color codes |
|
||||
| `resolved_command(name)` | Find command in PATH, returns `Command` |
|
||||
| `tool_exists(name)` | Check if a CLI tool is available |
|
||||
| `detect_package_manager()` | Detect pnpm/yarn/npm from lockfiles |
|
||||
| `package_manager_exec(tool)` | Build `Command` using detected package manager |
|
||||
| `ruby_exec(tool)` | Auto-detect `bundle exec` when `Gemfile` exists |
|
||||
| `count_tokens(text)` | Estimate tokens: `ceil(chars / 4.0)` |
|
||||
|
||||
## Consumer Contracts
|
||||
|
||||
Core provides infrastructure that `cmds/` and other components consume. These contracts define expected usage.
|
||||
|
||||
### Tracking (`TimedExecution`)
|
||||
|
||||
Consumers must call `timer.track()` on **all** code paths — success, failure, and fallback. Calling `std::process::exit()` before `track()` loses metrics. The raw string passed to `track()` should include both stdout and stderr to produce accurate savings percentages.
|
||||
|
||||
### Tee (`tee_and_hint`)
|
||||
|
||||
Consumers that parse structured output (JSON, NDJSON, state machines) should call `tee::tee_and_hint()` to save raw output for LLM recovery on failure. Tee must be called before `std::process::exit()`.
|
||||
|
||||
## Adding New Functionality
|
||||
Place new infrastructure code here if it meets **all** of these criteria: (1) it has no dependencies on command modules or hooks, (2) it is used by two or more other modules, and (3) it provides a general-purpose utility rather than command-specific logic. Follow the existing pattern of lazy-initialized resources (`lazy_static!` for regex, on-demand config loading) to preserve the <10ms startup target. Add `#[cfg(test)] mod tests` with unit tests in the same file.
|
||||
@@ -1,6 +0,0 @@
|
||||
pub const RTK_DATA_DIR: &str = "rtk";
|
||||
pub const HISTORY_DB: &str = "history.db";
|
||||
pub const CONFIG_TOML: &str = "config.toml";
|
||||
pub const FILTERS_TOML: &str = "filters.toml";
|
||||
pub const TRUSTED_FILTERS_JSON: &str = "trusted_filters.json";
|
||||
pub const DEFAULT_HISTORY_DAYS: i64 = 90;
|
||||
@@ -1,12 +0,0 @@
|
||||
//! Building blocks shared across all RTK modules.
|
||||
|
||||
pub mod config;
|
||||
pub mod constants;
|
||||
pub mod display_helpers;
|
||||
pub mod filter;
|
||||
pub mod runner;
|
||||
pub mod tee;
|
||||
pub mod telemetry;
|
||||
pub mod toml_filter;
|
||||
pub mod tracking;
|
||||
pub mod utils;
|
||||
@@ -1,141 +0,0 @@
|
||||
//! Shared command execution skeleton for filter modules.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::{exit_code_from_output, exit_code_from_status};
|
||||
|
||||
pub fn print_with_hint(filtered: &str, raw: &str, tee_label: &str, exit_code: i32) {
|
||||
if let Some(hint) = crate::core::tee::tee_and_hint(raw, tee_label, exit_code) {
|
||||
println!("{}\n{}", filtered, hint);
|
||||
} else {
|
||||
println!("{}", filtered);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RunOptions<'a> {
|
||||
pub tee_label: Option<&'a str>,
|
||||
pub filter_stdout_only: bool,
|
||||
pub skip_filter_on_failure: bool,
|
||||
pub no_trailing_newline: bool,
|
||||
}
|
||||
|
||||
impl<'a> RunOptions<'a> {
|
||||
pub fn with_tee(label: &'a str) -> Self {
|
||||
Self {
|
||||
tee_label: Some(label),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stdout_only() -> Self {
|
||||
Self {
|
||||
filter_stdout_only: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tee(mut self, label: &'a str) -> Self {
|
||||
self.tee_label = Some(label);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn early_exit_on_failure(mut self) -> Self {
|
||||
self.skip_filter_on_failure = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn no_trailing_newline(mut self) -> Self {
|
||||
self.no_trailing_newline = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_filtered<F>(
|
||||
mut cmd: Command,
|
||||
tool_name: &str,
|
||||
args_display: &str,
|
||||
filter_fn: F,
|
||||
opts: RunOptions<'_>,
|
||||
) -> Result<i32>
|
||||
where
|
||||
F: Fn(&str) -> String,
|
||||
{
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
let output = cmd
|
||||
.output()
|
||||
.with_context(|| format!("Failed to run {}", tool_name))?;
|
||||
|
||||
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 = exit_code_from_output(&output, tool_name);
|
||||
|
||||
// On failure, skip filtering and return early (e.g. psql error messages
|
||||
// containing '|' would be misinterpreted by the table parser)
|
||||
if opts.skip_filter_on_failure && exit_code != 0 {
|
||||
if !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr.trim());
|
||||
}
|
||||
timer.track(
|
||||
&format!("{} {}", tool_name, args_display),
|
||||
&format!("rtk {} {}", tool_name, args_display),
|
||||
&raw,
|
||||
stderr.as_ref(),
|
||||
);
|
||||
return Ok(exit_code);
|
||||
}
|
||||
|
||||
let text_to_filter = if opts.filter_stdout_only {
|
||||
&stdout
|
||||
} else {
|
||||
raw.as_str()
|
||||
};
|
||||
let filtered = filter_fn(text_to_filter);
|
||||
|
||||
if let Some(label) = opts.tee_label {
|
||||
print_with_hint(&filtered, &raw, label, exit_code);
|
||||
} else if opts.no_trailing_newline {
|
||||
print!("{}", filtered);
|
||||
} else {
|
||||
println!("{}", filtered);
|
||||
}
|
||||
|
||||
if opts.filter_stdout_only && !stderr.trim().is_empty() {
|
||||
eprintln!("{}", stderr.trim());
|
||||
}
|
||||
|
||||
let raw_for_tracking = if opts.filter_stdout_only {
|
||||
stdout.as_ref()
|
||||
} else {
|
||||
raw.as_str()
|
||||
};
|
||||
timer.track(
|
||||
&format!("{} {}", tool_name, args_display),
|
||||
&format!("rtk {} {}", tool_name, args_display),
|
||||
raw_for_tracking,
|
||||
&filtered,
|
||||
);
|
||||
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
pub fn run_passthrough(tool: &str, args: &[std::ffi::OsString], verbose: u8) -> Result<i32> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
if verbose > 0 {
|
||||
eprintln!("{} passthrough: {:?}", tool, args);
|
||||
}
|
||||
let status = crate::core::utils::resolved_command(tool)
|
||||
.args(args)
|
||||
.status()
|
||||
.with_context(|| format!("Failed to run {}", tool))?;
|
||||
let args_str = tracking::args_display(args);
|
||||
timer.track_passthrough(
|
||||
&format!("{} {}", tool, args_str),
|
||||
&format!("rtk {} {} (passthrough)", tool, args_str),
|
||||
);
|
||||
Ok(exit_code_from_status(&status, tool))
|
||||
}
|
||||
@@ -1,13 +1,9 @@
|
||||
//! Runs curl and auto-compresses JSON responses.
|
||||
|
||||
use crate::core::tracking;
|
||||
use crate::core::utils::{exit_code_from_output, resolved_command, truncate};
|
||||
use crate::json_cmd;
|
||||
use crate::tracking;
|
||||
use crate::utils::{resolved_command, truncate};
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// Not using run_filtered: on failure, curl can return HTML error pages (404, 500)
|
||||
/// that the JSON schema filter would mangle. The early exit skips filtering entirely.
|
||||
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
pub fn run(args: &[String], verbose: u8) -> Result<()> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
let mut cmd = resolved_command("curl");
|
||||
cmd.arg("-s"); // Silent mode (no progress bar)
|
||||
@@ -24,7 +20,6 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
// Early exit: don't feed HTTP error bodies (HTML 404 etc.) through JSON schema filter
|
||||
if !output.status.success() {
|
||||
let msg = if stderr.trim().is_empty() {
|
||||
stdout.trim().to_string()
|
||||
@@ -32,7 +27,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
stderr.trim().to_string()
|
||||
};
|
||||
eprintln!("FAILED: curl {}", msg);
|
||||
return Ok(exit_code_from_output(&output, "curl"));
|
||||
std::process::exit(output.status.code().unwrap_or(1));
|
||||
}
|
||||
|
||||
let raw = stdout.to_string();
|
||||
@@ -48,7 +43,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
&filtered,
|
||||
);
|
||||
|
||||
Ok(0)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn filter_curl_output(output: &str) -> String {
|
||||
@@ -1,6 +1,4 @@
|
||||
//! Summarizes project dependencies from lock files and manifests.
|
||||
|
||||
use crate::core::tracking;
|
||||
use crate::tracking;
|
||||
use anyhow::Result;
|
||||
use regex::Regex;
|
||||
use std::fs;
|
||||
@@ -1,6 +1,5 @@
|
||||
//! Compares two files and shows only the changed lines.
|
||||
|
||||
use crate::core::tracking;
|
||||
use crate::tracking;
|
||||
use crate::utils::truncate;
|
||||
use anyhow::Result;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
@@ -40,17 +39,21 @@ pub fn run(file1: &Path, file2: &Path, verbose: u8) -> Result<()> {
|
||||
diff.added, diff.removed, diff.modified
|
||||
));
|
||||
|
||||
// Never truncate diff content — users make decisions based on this data.
|
||||
// Only the summary header provides compression; all changes are shown in full.
|
||||
for change in &diff.changes {
|
||||
for change in diff.changes.iter().take(50) {
|
||||
match change {
|
||||
DiffChange::Added(ln, c) => rtk.push_str(&format!("+{:4} {}\n", ln, c)),
|
||||
DiffChange::Removed(ln, c) => rtk.push_str(&format!("-{:4} {}\n", ln, c)),
|
||||
DiffChange::Modified(ln, old, new) => {
|
||||
rtk.push_str(&format!("~{:4} {} → {}\n", ln, old, new))
|
||||
}
|
||||
DiffChange::Added(ln, c) => rtk.push_str(&format!("+{:4} {}\n", ln, truncate(c, 80))),
|
||||
DiffChange::Removed(ln, c) => rtk.push_str(&format!("-{:4} {}\n", ln, truncate(c, 80))),
|
||||
DiffChange::Modified(ln, old, new) => rtk.push_str(&format!(
|
||||
"~{:4} {} → {}\n",
|
||||
ln,
|
||||
truncate(old, 70),
|
||||
truncate(new, 70)
|
||||
)),
|
||||
}
|
||||
}
|
||||
if diff.changes.len() > 50 {
|
||||
rtk.push_str(&format!("... +{} more changes", diff.changes.len() - 50));
|
||||
}
|
||||
|
||||
print!("{}", rtk);
|
||||
timer.track(
|
||||
@@ -160,19 +163,17 @@ fn condense_unified_diff(diff: &str) -> String {
|
||||
let mut removed = 0;
|
||||
let mut changes = Vec::new();
|
||||
|
||||
// Never truncate diff content — users make decisions based on this data.
|
||||
// Only strip diff metadata (headers, @@ hunks); all +/- lines shown in full.
|
||||
for line in diff.lines() {
|
||||
if line.starts_with("diff --git") || line.starts_with("--- ") || line.starts_with("+++ ") {
|
||||
// File header
|
||||
if line.starts_with("+++ ") {
|
||||
if !current_file.is_empty() && (added > 0 || removed > 0) {
|
||||
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
|
||||
for c in &changes {
|
||||
for c in changes.iter().take(10) {
|
||||
result.push(format!(" {}", c));
|
||||
}
|
||||
let total = added + removed;
|
||||
if total > 10 {
|
||||
result.push(format!(" ... +{} more", total - 10));
|
||||
if changes.len() > 10 {
|
||||
result.push(format!(" ... +{} more", changes.len() - 10));
|
||||
}
|
||||
}
|
||||
current_file = line
|
||||
@@ -185,22 +186,25 @@ fn condense_unified_diff(diff: &str) -> String {
|
||||
}
|
||||
} else if line.starts_with('+') && !line.starts_with("+++") {
|
||||
added += 1;
|
||||
changes.push(line.to_string());
|
||||
if changes.len() < 15 {
|
||||
changes.push(truncate(line, 70));
|
||||
}
|
||||
} else if line.starts_with('-') && !line.starts_with("---") {
|
||||
removed += 1;
|
||||
changes.push(line.to_string());
|
||||
if changes.len() < 15 {
|
||||
changes.push(truncate(line, 70));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Last file
|
||||
if !current_file.is_empty() && (added > 0 || removed > 0) {
|
||||
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
|
||||
for c in &changes {
|
||||
for c in changes.iter().take(10) {
|
||||
result.push(format!(" {}", c));
|
||||
}
|
||||
let total = added + removed;
|
||||
if total > 10 {
|
||||
result.push(format!(" ... +{} more", total - 10));
|
||||
if changes.len() > 10 {
|
||||
result.push(format!(" ... +{} more", changes.len() - 10));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,6 +246,23 @@ mod tests {
|
||||
assert!(similarity("let x = 1;", "let x = 2;") > 0.5);
|
||||
}
|
||||
|
||||
// --- truncate ---
|
||||
|
||||
#[test]
|
||||
fn test_truncate_short_string() {
|
||||
assert_eq!(truncate("hello", 10), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_truncate_exact_length() {
|
||||
assert_eq!(truncate("hello", 5), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_truncate_long_string() {
|
||||
assert_eq!(truncate("hello world!", 8), "hello...");
|
||||
}
|
||||
|
||||
// --- compute_diff ---
|
||||
|
||||
#[test]
|
||||
@@ -343,93 +364,4 @@ diff --git a/b.rs b/b.rs
|
||||
let result = condense_unified_diff("");
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
// --- truncation accuracy ---
|
||||
|
||||
fn make_large_unified_diff(added: usize, removed: usize) -> String {
|
||||
let mut lines = vec![
|
||||
"diff --git a/config.yaml b/config.yaml".to_string(),
|
||||
"--- a/config.yaml".to_string(),
|
||||
"+++ b/config.yaml".to_string(),
|
||||
"@@ -1,200 +1,200 @@".to_string(),
|
||||
];
|
||||
for i in 0..removed {
|
||||
lines.push(format!("-old_value_{}", i));
|
||||
}
|
||||
for i in 0..added {
|
||||
lines.push(format!("+new_value_{}", i));
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_condense_unified_diff_overflow_count_accuracy() {
|
||||
// 100 added + 100 removed = 200 total changes, only 10 shown
|
||||
// True overflow = 200 - 10 = 190
|
||||
// Bug: changes vec capped at 15, so old code showed "+5 more" (15-10) instead of "+190 more"
|
||||
let diff = make_large_unified_diff(100, 100);
|
||||
let result = condense_unified_diff(&diff);
|
||||
assert!(
|
||||
result.contains("+190 more"),
|
||||
"Expected '+190 more' but got:\n{}",
|
||||
result
|
||||
);
|
||||
assert!(
|
||||
!result.contains("+5 more"),
|
||||
"Bug still present: showing '+5 more' instead of true overflow"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_condense_unified_diff_no_false_overflow() {
|
||||
// 8 changes total — all fit within the 10-line display cap, no overflow message
|
||||
let diff = make_large_unified_diff(4, 4);
|
||||
let result = condense_unified_diff(&diff);
|
||||
assert!(
|
||||
!result.contains("more"),
|
||||
"No overflow message expected for 8 changes, got:\n{}",
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_truncation_large_diff() {
|
||||
// Verify compute_diff returns all changes without truncation
|
||||
let mut a = Vec::new();
|
||||
let mut b = Vec::new();
|
||||
for i in 0..500 {
|
||||
a.push(format!("line_{}", i));
|
||||
if i % 3 == 0 {
|
||||
b.push(format!("CHANGED_{}", i));
|
||||
} else {
|
||||
b.push(format!("line_{}", i));
|
||||
}
|
||||
}
|
||||
let a_refs: Vec<&str> = a.iter().map(|s| s.as_str()).collect();
|
||||
let b_refs: Vec<&str> = b.iter().map(|s| s.as_str()).collect();
|
||||
let result = compute_diff(&a_refs, &b_refs);
|
||||
|
||||
assert!(
|
||||
result.changes.len() > 100,
|
||||
"Expected 100+ changes, got {}",
|
||||
result.changes.len()
|
||||
);
|
||||
assert!(!result.changes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_long_lines_not_truncated() {
|
||||
let long_line = "x".repeat(500);
|
||||
let a = vec![long_line.as_str()];
|
||||
let b = vec!["short"];
|
||||
let result = compute_diff(&a, &b);
|
||||
match &result.changes[0] {
|
||||
DiffChange::Removed(_, content) | DiffChange::Added(_, content) => {
|
||||
assert_eq!(content.len(), 500, "Line was truncated!");
|
||||
}
|
||||
DiffChange::Modified(_, old, _) => {
|
||||
assert_eq!(old.len(), 500, "Line was truncated!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
# Discover — History Analysis & Command Rewrite
|
||||
|
||||
> Full rewrite pipeline diagram: [docs/TECHNICAL.md](../../docs/TECHNICAL.md#32-hook-interception-command-rewriting)
|
||||
|
||||
## What This Module Does
|
||||
|
||||
This module has two jobs:
|
||||
|
||||
1. **Rewrite commands** — Every LLM agent hook calls `rtk rewrite "git status"`. This module decides whether to rewrite it (`rtk git status`) or pass it through unchanged. This is the hot path — every command the LLM runs goes through here.
|
||||
|
||||
2. **Analyze history** — `rtk discover` scans past LLM sessions to find commands that *could have been* rewritten but weren't. Same classification logic, different consumer.
|
||||
|
||||
## How Command Rewriting Works
|
||||
|
||||
When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
|
||||
|
||||
**Tokenization** — The lexer (`lexer.rs`) turns the raw string into typed tokens. It's a single-pass state machine that understands shell quoting, escapes, redirects, and operators. This is critical because naive string splitting breaks on quoted content like `git commit -m "fix && update"`.
|
||||
|
||||
```
|
||||
"cargo test 2>&1 && git status"
|
||||
→ [Arg("cargo"), Arg("test"), Redirect("2>&1"), Operator("&&"), Arg("git"), Arg("status")]
|
||||
```
|
||||
|
||||
**Compound splitting** — The rewrite engine walks the tokens, splitting on `Operator` (`&&`, `||`, `;`) and `Pipe` (`|`). Each segment is rewritten independently. For pipes, only the left side is rewritten (the pipe consumer like `grep` or `head` runs raw). `find`/`fd` before a pipe is never rewritten because rtk's grouped output format breaks pipe consumers like `xargs`.
|
||||
|
||||
**Per-segment rewriting** — Each segment goes through:
|
||||
|
||||
1. Strip trailing redirects (`2>&1`, `>/dev/null`) — matched via lexer tokens, set aside, re-appended after rewriting
|
||||
2. Short-circuit special cases — `head -20 file` → `rtk read file --max-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
|
||||
3. Classify the command — strip env prefixes (`sudo`, `FOO="bar baz"`), normalize paths (`/usr/bin/grep` → `grep`), strip git global opts (`git -C /tmp` → `git`), then match against 60+ regex patterns from `rules.rs`
|
||||
4. Apply the rewrite — find the matching rule, replace the command prefix with `rtk <cmd>`, re-prepend the env prefix, re-append the redirect suffix
|
||||
|
||||
**Guards along the way:**
|
||||
- `RTK_DISABLED=1` in the env prefix → skip rewrite
|
||||
- `gh` with `--json`/`--jq`/`--template` → skip (structured output, rtk would corrupt it)
|
||||
- `cat` with flags other than `-n` → skip (different semantics than `rtk read`)
|
||||
- `cat`/`head`/`tail` with `>` or `>>` → skip (write operation, not a read)
|
||||
- Command in `hooks.exclude_commands` config → skip
|
||||
|
||||
**Result**: `rtk cargo fmt --all && rtk cargo test 2>&1 | tail -20`. Bash handles the `&&` and `|` at execution time — each `rtk` invocation is a separate process.
|
||||
|
||||
## How History Analysis Works
|
||||
|
||||
`rtk discover` reads Claude Code JSONL session files. Each file contains `tool_use`/`tool_result` pairs for every command the LLM ran. The module:
|
||||
|
||||
1. Extracts commands from the JSONL (via `SessionProvider` trait — currently only Claude Code)
|
||||
2. Splits compound commands using the same lexer-based tokenization
|
||||
3. Classifies each command against the same rules used for live rewriting
|
||||
4. Aggregates results: which commands could have been rewritten, estimated token savings, adoption rate
|
||||
|
||||
The classification logic is shared between discover and rewrite — same patterns, same rules, different consumers.
|
||||
|
||||
## Env Prefix Handling
|
||||
|
||||
The `ENV_PREFIX` regex strips env variable assignments, `sudo`, and `env` from the front of commands. It handles:
|
||||
- Unquoted: `FOO=bar`
|
||||
- Double-quoted with spaces: `FOO="bar baz"`
|
||||
- Single-quoted: `FOO='bar baz'`
|
||||
- Escaped quotes: `FOO="he said \"hello\""`
|
||||
- Chained: `A="x y" B=1 sudo git status`
|
||||
|
||||
The prefix is stripped twice: once in `classify_command()` to match the underlying command against rules, and again in `rewrite_segment()` to extract it for re-prepending to the rewritten command.
|
||||
|
||||
## Adding a New Rewrite Rule
|
||||
|
||||
Add an entry to `rules.rs`. Each rule has:
|
||||
- `pattern` — regex that matches the command (used by `RegexSet` for fast matching)
|
||||
- `rtk_cmd` — the RTK command it maps to (e.g., `"rtk cargo"`)
|
||||
- `rewrite_prefixes` — command prefixes to replace (e.g., `&["cargo"]`)
|
||||
- `category`, `savings_pct` — metadata for discover reports
|
||||
- `subcmd_savings`, `subcmd_status` — per-subcommand overrides
|
||||
|
||||
No other files need to change. The registry compiles the patterns at first use via `lazy_static`.
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user