Compare commits

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

Fixes #600

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-15 10:08:01 +01:00
aesoft ddf8403325 Merge branch 'master' into develop 2026-03-14 19:54:44 +01:00
aesoft be67d66010 Merge pull request #547 from ousamabenyounes/feat/rtk-session
feat: add rtk session command for adoption overview
2026-03-13 17:24:34 +01:00
Ousama Ben YounesandClaude Opus 4.6 127f85c02e fix: split chained commands in adoption metric
Commands like "cd ./path && rtk ls" are now split via
split_command_chain() before classification, matching the
discover module's behavior. Each part is counted independently.

4 tests added: chain with &&, semicolons, all-supported,
and JSONL integration with chained command.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:10:18 +00:00
Ousama Ben YounesandClaude Opus 4.6 eb8a2c4a71 fix: improve adoption metric by detecting hook-rewritten commands
The hook rewrites "git status" → "rtk git status" but JSONL logs the
original command. count_rtk_commands now uses classify_command() to
also count commands the hook would rewrite, giving realistic adoption
percentages (68% vs previous 2%).

Also adds rtk session to README.md documentation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:09:38 +00:00
Ousama Ben YounesandClaude Opus 4.6 c916bab33a fix: support git -C <path> in rewrite registry
The regex pattern for git commands now accepts -C and -c flags
before the subcommand, using a non-capturing group to preserve
subcommand extraction.

Closes #555

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:09:38 +00:00
Ousama Ben YounesandClaude Opus 4.6 8e51892beb test: add real JSONL parsing tests for rtk session
Replace trivial progress bar tests with meaningful tests:
- Parse JSONL with mixed rtk/raw commands, verify counts
- Verify non-Bash tools (Read/Grep) are ignored
- Verify empty sessions produce no commands
- Test count_rtk_commands with all-rtk, no-rtk, mixed, empty

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:09:38 +00:00
Ousama Ben YounesandClaude Opus 4.6 12d44c4068 feat: add rtk session command for adoption overview
Shows last 10 Claude Code sessions with RTK vs raw command ratio,
adoption percentage, and output token count. Reuses ClaudeProvider
from discover module — zero JSONL parsing duplication.

Also fixes missing `truncate` import in cargo_cmd.rs (pre-existing
build error on develop).

Closes #487

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:09:38 +00:00
aesoft 2223eca224 Merge pull request #413 from tsubasakong/lucas/docs-387-tool-rewrite-clarify
docs: clarify Bash-only auto-rewrite scope
2026-03-13 11:41:09 +01:00
github-actions[bot] 188ec996b3 chore(master): release 0.29.0 (#540)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-12 16:18:00 +01:00
patrick szymkowiak c1de10d94c feat: rewrite engine, OpenCode support, hook system improvements (#539)
Includes all changes from develop → master merge (#499):
- rtk rewrite engine with shell_split + rewrite_segment
- OpenCode plugin support (rtk init -g --opencode)
- Hook check warnings and RTK_DISABLED detection
- TOML filter DSL with 14 built-in filters
- Improved gh, git log, proxy quote handling

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-12 16:16:36 +01:00
d0396da1ce chore: merge develop into master (#499)
* fix: handle tail rewrites with read tail-lines

* feat: add 32 TOML-filtered commands to hook rewrite rules (#475)

Add rewrite rules for all TOML-filtered commands so the Claude Code
hook automatically rewrites them to `rtk proxy <cmd>`. This ensures
TOML filters apply transparently without manual `rtk` prefixing.

Commands added: ansible-playbook, brew, composer, df, dotnet, du,
fail2ban-client, gcloud, hadolint, helm, iptables, make,
markdownlint, mix, mvn, ping, pio, poetry, pre-commit, ps, quarto,
rsync, shellcheck, shopify, sops, swift, systemctl, terraform, tofu,
trunk, uv, yamllint.

Tests updated to use `htop` as unsupported command example since
terraform is now supported via TOML filter.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: git log --oneline no longer silently truncated to 10 entries (#461) (#478)

Only inject -10 limit when RTK applies its own compact format.
When user provides --oneline/--pretty/--format, respect git's
default behavior (no limit). Also detect -n and --max-count as
user-provided limit flags.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: gh run view --job flag loses its value (#416) (#477)

Add --job and --attempt to flags_with_value in
extract_identifier_and_extra_args() so their values are not
mistaken for the run identifier when placed before it.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: rtk read no longer corrupts JSON files with glob patterns (#464) (#479)

Add Language::Data variant for JSON, YAML, TOML, XML, Markdown, CSV
and other data formats. These files have no comment syntax, so the
MinimalFilter skips comment stripping entirely.

Previously, `packages/*` in package.json was treated as a block
comment start (`/*`), causing everything until the next `*/` to be
stripped — corrupting the JSON structure.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: npm routing, discover cat redirect, proxy quoted args (#480)

* fix: npm routing, discover cat redirect, proxy quoted args (#470, #315, #388)

#470: rtk npm now correctly routes npm subcommands (install, list,
audit, etc.) without injecting "run". Previously, `rtk npm install`
was executed as `npm run install`.

#315: discover no longer counts `cat >`, `cat >>`, `cat |` as missed
savings. These are write/pipe operations with no terminal output to
compress.

#388: rtk proxy now auto-splits a single quoted argument containing
spaces. `rtk proxy 'head -50 file.php'` now works like
`rtk proxy head -50 file.php`.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: proxy quote-aware split, redirect detection scan all tokens, npm test routing

- Proxy: replace split_whitespace with shell_split() that respects quotes (#388)
  e.g. 'git log --format="%H %s"' no longer splits on space inside quotes
- Discover: scan all tokens for redirect operators, not just nth(1) (#315)
  e.g. 'cat file.txt > output.txt' now correctly detected as write
- npm: replace tautological test with actual routing logic verification

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* feat: add 11 new TOML built-in filters (xcodebuild, jq, basedpyright, ty, skopeo, stat, biome, oxlint, jj, ssh, gcc) (#490)

Closes #484, #483, #449, #448, #428, #283, #316, #195, #271, #333, #87, #376

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: rtk rewrite accepts multiple args without quotes (#504)

* fix: rtk rewrite accepts multiple args without quotes

`rtk rewrite ls -al` now works the same as `rtk rewrite "ls -al"`.
Previously, args after the command were rejected or caused ENOENT.

Also adds rewrite tests to benchmark.sh to prevent regression.

Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* test: add Clap rewrite tests + fix benchmark false failures

- Add 2 Clap try_parse_from tests for rewrite multi-args (catches the
  KuSh bug at unit test level, not just benchmark)
- Fix git diff benchmark: use HEAD~1 on both sides for fair comparison
- Skip cargo/rustc benchmarks when tools not in PATH instead of false FAIL
- Benchmark: 0 fail, 4 skip (env-dependent), 52 green

Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: use rtk <cmd> instead of rtk proxy for TOML-filtered commands (#507)

- Replace all 32 `rtk proxy <cmd>` rules with `rtk <cmd>` so TOML filters
  actually apply (proxy bypasses filters, giving 0% real savings)
- Extract NPM_SUBCOMMANDS to module-level const to prevent test/prod drift

Reported-by: FlorianBruniaux

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: warn when no hook installed + rtk gain hook status + PR #499 fixes

- hook_check: detect missing hook (not just outdated), warn with ⚠️
  Only warns if ~/.claude/ exists (Claude Code user) — once per day
- gain: show hook status warning (missing/outdated) in rtk gain output
- ssh.toml: bump max_lines 50→200, truncate_lines_at 120→200 (Florian review)
- git.rs: mark integration test #[ignore] + assert binary exists (Florian review)
- Add HookStatus enum for reuse across gain/diagnostics

Fixes #508, Fixes #509

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: address code review — hook_check edge cases

- status() checks .claude/ existence (no false warning for non-CC users)
- Unreadable hook file returns Outdated not Missing
- Swap marker/warning order (emit warning before touching rate-limit marker)
- Rename misleading test, add end-to-end status() test

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: review iteration 2 — double-warning, case-sensitive test, ssh truncate

- Refactor check_and_warn to delegate to status() (single source of truth)
- Fix double-warning: skip maybe_warn() for `rtk gain` (has its own inline warning)
- Fix git test: case-insensitive assertion for cross-locale compatibility
- ssh.toml: keep truncate_lines_at=120 (terminal width convention)
- Robust mtime handling: unwrap_or(u64::MAX) instead of nested .ok()?
- Test handles all CI environments (no hook, no .claude, hook present)

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: detect and warn RTK_DISABLED=1 overuse (#508)

- discover: count RTK_DISABLED= bypassed commands, report top 5 examples
- gain: lightweight 7-day JSONL scan, warn if >10% commands bypassed
- registry: add has_rtk_disabled_prefix() and strip_disabled_prefix() helpers
- gitignore: add .fastembed_cache/ and .next/

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: preserve trailing newline in tail_lines + add missing test

- apply_line_window() now preserves trailing newline when input has one
- Add test for tail --lines N (space form) rewrite
- Add test for tail_lines without trailing newline

Signed-off-by: Patrick <patrick@rtk-ai.com>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: respect user-specified git log limits instead of silently truncating

RTK was silently capping git log output in two ways:
1. `--oneline` without `-N` defaulted to 10 entries (now 50)
2. `filter_log_output()` re-truncated even when user explicitly set `-N`
3. Lines >80 chars were truncated, hiding PR numbers and author names

This matters for LLM workflows: Claude needs full commit history for
rebase, squash, and changelog operations. Silent truncation caused
incomplete context and repeated re-runs.

Changes:
- User-explicit `-N` → no line cap, wider 120-char truncation
- `--oneline`/`--pretty` without `-N` → default 50 (was 10)
- No flags → unchanged (default 10)
- Extract `truncate_line()` helper for clarity

Fixes #461

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

* fix: handle -n N and --max-count=N forms in git log limit parsing

- Extract parse_user_limit() to handle all 4 forms: -20, -n 20, --max-count=20, --max-count 20
- Add token savings test for filter_log_output (≥60%)
- Add 5 tests for parse_user_limit edge cases

Signed-off-by: Patrick <patrick@rtk-ai.com>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* feat: add structured dotnet support (build/test/restore/format)

Integrate PR #172 by @danielmarbach onto develop:
- MSBuild binlog parser (binary format, gzip, 7-bit varint)
- TRX test result parser (quick-xml)
- Format report JSON parser
- Subcommand routing: build, test, restore, format + passthrough
- Sensitive env var scrubbing (GH_TOKEN, AWS_SECRET_ACCESS_KEY, etc.)
- Fallback to text parsing when binlog unavailable
- 86-93% token savings on real .NET projects

Maintainer fixes applied:
- Removed binlog temp path from output (wastes tokens)
- Dropped hook file changes (incompatible with develop architecture)
- Fixed unused variable warnings

888 tests pass.

Signed-off-by: Patrick <patrick@rtk-ai.com>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* feat: add OpenCode plugin support (#300)

* feat(opencode): add OpenCode plugin support

Add `--opencode` flag to `rtk init` for installing a global OpenCode
plugin that rewrites Bash/shell commands through `rtk rewrite`.

- New plugin: hooks/opencode-rtk.ts (thin delegator to rtk rewrite)
- New init modes: --opencode (OpenCode only), combinable with Claude modes
- Plugin install/update/remove lifecycle with idempotent writes
- Uninstall cleans up OpenCode plugin alongside Claude Code artifacts
- `rtk init --show` reports OpenCode plugin status
- Replace unreachable!() with bail!() in match exhaustiveness guard

* docs: add OpenCode plugin documentation

- README: OpenCode plugin section, install flags, troubleshooting
- TROUBLESHOOTING: OpenCode-specific checklist
- Update init mode table to reflect Claude Code default

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick Szymkowiak <patrick.szymkowiak@rtk-ai.app>
Signed-off-by: Patrick <patrick@rtk-ai.com>
Co-authored-by: Qingyu Li <2310301201@stu.pku.edu.cn>
Co-authored-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: José Almeida <57680069+zeval@users.noreply.github.com>
2026-03-12 13:49:08 +01:00
Frank 992f2cee1b docs: clarify Bash-only auto-rewrite scope
Signed-off-by: Frank <97429702+tsubasakong@users.noreply.github.com>
2026-03-11 20:53:02 -07:00
12 changed files with 600 additions and 15 deletions

No files matched your search

+1 -1
View File
@@ -44,5 +44,5 @@ claudedocs
.vitals/
.worktrees/
# icm
# icm
.fastembed_cache/
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.28.2"
".": "0.29.0"
}
+7
View File
@@ -5,6 +5,13 @@ 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.29.0](https://github.com/rtk-ai/rtk/compare/v0.28.2...v0.29.0) (2026-03-12)
### Features
* rewrite engine, OpenCode support, hook system improvements ([#539](https://github.com/rtk-ai/rtk/issues/539)) ([c1de10d](https://github.com/rtk-ai/rtk/commit/c1de10d94c0a35f825b71713e2db4624310c03d1))
## [0.28.2](https://github.com/rtk-ai/rtk/compare/v0.28.1...v0.28.2) (2026-03-10)
Generated
+1 -1
View File
@@ -892,7 +892,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.28.2"
version = "0.29.0"
dependencies = [
"anyhow",
"chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.28.2"
version = "0.29.0"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
+7 -1
View File
@@ -108,7 +108,9 @@ rtk init --global
git status # Automatically rewritten to rtk git status
```
The hook transparently rewrites commands (e.g., `git status` -> `rtk git status`) before execution. Claude never sees the rewrite, it just gets compressed output.
The hook transparently rewrites Bash commands (e.g., `git status` -> `rtk git status`) before execution. Claude never sees the rewrite, it just gets compressed output.
**Important:** the hook only runs on Bash tool calls. Claude Code built-in tools like `Read`, `Grep`, and `Glob` do not pass through the Bash hook, so they are not auto-rewritten. To get RTK's compact output for those workflows, use shell commands (`cat`/`head`/`tail`, `rg`/`grep`, `find`) or call `rtk read`, `rtk grep`, or `rtk find` directly.
## How It Works
@@ -225,6 +227,8 @@ rtk gain --all --format json # JSON export for dashboards
rtk discover # Find missed savings opportunities
rtk discover --all --since 7 # All projects, last 7 days
rtk session # Show RTK adoption across recent sessions
```
## Global Flags
@@ -269,6 +273,8 @@ The most effective way to use rtk. The hook transparently intercepts Bash comman
**Result**: 100% rtk adoption across all conversations and subagents, zero token overhead.
**Scope note:** this only applies to Bash tool calls. Claude Code built-in tools such as `Read`, `Grep`, and `Glob` bypass the hook, so use shell commands or explicit `rtk` commands when you want RTK filtering there.
### Setup
```bash
+42
View File
@@ -936,6 +936,48 @@ mod tests {
);
}
// --- git -C <path> support (#555) ---
#[test]
fn test_rewrite_git_dash_c_status() {
assert_eq!(
rewrite_command("git -C /path/to/repo status", &[]),
Some("rtk git -C /path/to/repo status".into())
);
}
#[test]
fn test_rewrite_git_dash_c_log() {
assert_eq!(
rewrite_command("git -C /tmp/myrepo log --oneline -5", &[]),
Some("rtk git -C /tmp/myrepo log --oneline -5".into())
);
}
#[test]
fn test_rewrite_git_dash_c_diff() {
assert_eq!(
rewrite_command("git -C /home/user/project diff --name-only", &[]),
Some("rtk git -C /home/user/project diff --name-only".into())
);
}
#[test]
fn test_classify_git_dash_c() {
let result = classify_command("git -C /tmp status");
assert!(
matches!(
result,
Classification::Supported {
rtk_equivalent: "rtk git",
..
}
),
"git -C should be classified as supported, got: {:?}",
result
);
}
#[test]
fn test_rewrite_cargo_test() {
assert_eq!(
+1 -1
View File
@@ -13,7 +13,7 @@ pub struct RtkRule {
// Patterns ordered to match RULES indices exactly.
pub const PATTERNS: &[&str] = &[
r"^git\s+(status|log|diff|show|add|commit|push|pull|branch|fetch|stash|worktree)",
r"^git\s+(?:-[Cc]\s+\S+\s+)*(status|log|diff|show|add|commit|push|pull|branch|fetch|stash|worktree)",
r"^gh\s+(pr|issue|run|repo|api|release)",
r"^cargo\s+(build|test|clippy|check|fmt|install)",
r"^pnpm\s+(list|ls|outdated|install)",
+91 -5
View File
@@ -1009,10 +1009,23 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
eprintln!("git branch");
}
// Detect write operations: delete, rename, copy
let has_action_flag = args
.iter()
.any(|a| a == "-d" || a == "-D" || a == "-m" || a == "-M" || a == "-c" || a == "-C");
// Detect write operations: delete, rename, copy, upstream tracking
let has_action_flag = args.iter().any(|a| {
a == "-d"
|| a == "-D"
|| a == "-m"
|| a == "-M"
|| a == "-c"
|| a == "-C"
|| a == "--set-upstream-to"
|| a.starts_with("--set-upstream-to=")
|| a == "-u"
|| a == "--unset-upstream"
|| a == "--edit-description"
});
// Detect flags that produce specific output (not a branch list)
let has_show_flag = args.iter().any(|a| a == "--show-current");
// Detect list-mode flags
let has_list_flag = args.iter().any(|a| {
@@ -1025,11 +1038,49 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
|| a == "--no-merged"
|| a == "--contains"
|| a == "--no-contains"
|| a == "--format"
|| a.starts_with("--format=")
|| a == "--sort"
|| a.starts_with("--sort=")
|| a == "--points-at"
|| a.starts_with("--points-at=")
});
// Detect positional arguments (not flags) — indicates branch creation
let has_positional_arg = args.iter().any(|a| !a.starts_with('-'));
// --show-current: passthrough with raw stdout (not "ok ✓")
if has_show_flag {
let mut cmd = git_cmd(global_args);
cmd.arg("branch");
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run git branch")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let combined = format!("{}{}", stdout, stderr);
let trimmed = stdout.trim();
timer.track(
&format!("git branch {}", args.join(" ")),
&format!("rtk git branch {}", args.join(" ")),
&combined,
trimmed,
);
if output.status.success() {
println!("{}", trimmed);
} else {
eprintln!("FAILED: git branch {}", args.join(" "));
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
}
std::process::exit(output.status.code().unwrap_or(1));
}
return Ok(());
}
// Write operation: action flags, or positional args without list flags (= branch creation)
if has_action_flag || (has_positional_arg && !has_list_flag) {
let mut cmd = git_cmd(global_args);
@@ -1285,7 +1336,42 @@ fn run_stash(
std::process::exit(output.status.code().unwrap_or(1));
}
}
_ => {
Some(sub) => {
// Unrecognized subcommand: passthrough to git stash <sub> [args]
let mut cmd = git_cmd(global_args);
cmd.args(["stash", sub]);
for arg in args {
cmd.arg(arg);
}
let output = cmd.output().context("Failed to run git stash")?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let combined = format!("{}{}", stdout, stderr);
let msg = if output.status.success() {
let msg = format!("ok stash {}", sub);
println!("{}", msg);
msg
} else {
eprintln!("FAILED: git stash {}", sub);
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
}
combined.clone()
};
timer.track(
&format!("git stash {}", sub),
&format!("rtk git stash {}", sub),
&combined,
&msg,
);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
}
None => {
// Default: git stash (push)
let mut cmd = git_cmd(global_args);
cmd.arg("stash");
+8
View File
@@ -49,6 +49,7 @@ mod read;
mod rewrite_cmd;
mod ruff_cmd;
mod runner;
mod session_cmd;
mod summary;
mod tee;
mod telemetry;
@@ -537,6 +538,9 @@ enum Commands {
format: String,
},
/// Show RTK adoption across Claude Code sessions
Session {},
/// Learn CLI corrections from Claude Code error history
Learn {
/// Filter by project path (substring match)
@@ -1793,6 +1797,10 @@ fn main() -> Result<()> {
discover::run(project.as_deref(), all, since, limit, &format, cli.verbose)?;
}
Commands::Session {} => {
session_cmd::run(cli.verbose)?;
}
Commands::Learn {
project,
all,
+2 -4
View File
@@ -33,10 +33,8 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
run_passthrough(base_cmd, args, verbose)?
}
_ => {
anyhow::bail!(
"rtk pip: unsupported subcommand '{}'\nSupported: list, outdated, install, uninstall, show",
subcommand
);
// Unknown subcommand: passthrough to pip/uv
run_passthrough(base_cmd, args, verbose)?
}
};
+438
View File
@@ -0,0 +1,438 @@
use crate::discover::provider::{ClaudeProvider, ExtractedCommand, SessionProvider};
use crate::discover::registry::{classify_command, split_command_chain, Classification};
use crate::utils::format_tokens;
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
/// A summarized session for display.
struct SessionSummary {
id: String,
date: String,
total_cmds: usize,
rtk_cmds: usize,
output_tokens: usize,
}
impl SessionSummary {
fn adoption_pct(&self) -> f64 {
if self.total_cmds == 0 {
return 0.0;
}
self.rtk_cmds as f64 / self.total_cmds as f64 * 100.0
}
}
/// Count RTK-covered commands from extracted commands.
/// A command is "covered" if it either:
/// - starts with "rtk " (explicit rtk invocation), or
/// - would be rewritten by the hook (classify_command returns Supported)
///
/// Chained commands (e.g. "cd ./path && rtk ls") are split so each part
/// is classified independently — matching the discover module's behavior.
fn count_rtk_commands(cmds: &[ExtractedCommand]) -> (usize, usize, usize) {
let mut total: usize = 0;
let mut rtk: usize = 0;
for c in cmds {
let parts = split_command_chain(&c.command);
for part in &parts {
total += 1;
if part.starts_with("rtk ")
|| matches!(classify_command(part), Classification::Supported { .. })
{
rtk += 1;
}
}
}
let output: usize = cmds.iter().filter_map(|c| c.output_len).sum();
(total, rtk, output)
}
fn progress_bar(pct: f64, width: usize) -> String {
let filled = ((pct / 100.0) * width as f64).round() as usize;
let empty = width.saturating_sub(filled);
format!("{}{}", "@".repeat(filled), ".".repeat(empty))
}
pub fn run(_verbose: u8) -> Result<()> {
let provider = ClaudeProvider;
let sessions = provider
.discover_sessions(None, Some(30))
.context("Failed to discover Claude Code sessions")?;
if sessions.is_empty() {
println!("No Claude Code sessions found in the last 30 days.");
println!("Make sure Claude Code has been used at least once.");
return Ok(());
}
// Group JSONL files by parent session (ignore subagent files)
let mut session_files: Vec<PathBuf> = sessions
.into_iter()
.filter(|p| {
// Skip subagent files — only top-level session JSONL
!p.to_string_lossy().contains("subagents")
})
.collect();
// Sort by mtime desc
session_files.sort_by(|a, b| {
let ma = fs::metadata(a)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
let mb = fs::metadata(b)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
mb.cmp(&ma)
});
// Take top 10
session_files.truncate(10);
let mut summaries: Vec<SessionSummary> = Vec::new();
for path in &session_files {
let cmds = match provider.extract_commands(path) {
Ok(c) => c,
Err(_) => continue,
};
if cmds.is_empty() {
continue;
}
let (total_cmds, rtk_cmds, output_tokens) = count_rtk_commands(&cmds);
// Extract session ID from filename
let id = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
let short_id = if id.len() > 8 { &id[..8] } else { id };
// Extract date from mtime
let date = fs::metadata(path)
.and_then(|m| m.modified())
.map(|t| {
let elapsed = std::time::SystemTime::now()
.duration_since(t)
.unwrap_or_default();
let days = elapsed.as_secs() / 86400;
if days == 0 {
"Today".to_string()
} else if days == 1 {
"Yesterday".to_string()
} else {
format!("{}d ago", days)
}
})
.unwrap_or_else(|_| "?".to_string());
summaries.push(SessionSummary {
id: short_id.to_string(),
date,
total_cmds,
rtk_cmds,
output_tokens,
});
}
if summaries.is_empty() {
println!("No sessions with Bash commands found.");
return Ok(());
}
// Display table
let header = "RTK Session Overview (last 10)";
println!("{}", header);
println!("{}", "-".repeat(70));
println!(
"{:<12} {:<12} {:>5} {:>5} {:>9} {:<7} {:>8}",
"Session", "Date", "Cmds", "RTK", "Adoption", "", "Output"
);
println!("{}", "-".repeat(70));
let mut total_cmds = 0;
let mut total_rtk = 0;
for s in &summaries {
let pct = s.adoption_pct();
let bar = progress_bar(pct, 5);
total_cmds += s.total_cmds;
total_rtk += s.rtk_cmds;
println!(
"{:<12} {:<12} {:>5} {:>5} {:>8.0}% {:<7} {:>8}",
s.id,
s.date,
s.total_cmds,
s.rtk_cmds,
pct,
bar,
format_tokens(s.output_tokens),
);
}
println!("{}", "-".repeat(70));
let avg_adoption = if total_cmds > 0 {
total_rtk as f64 / total_cmds as f64 * 100.0
} else {
0.0
};
println!("Average adoption: {:.0}%", avg_adoption);
println!("Tip: Run `rtk discover` to find missed RTK opportunities");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::discover::provider::ExtractedCommand;
use std::io::Write;
use tempfile::NamedTempFile;
fn make_cmd(command: &str, output_len: Option<usize>) -> ExtractedCommand {
ExtractedCommand {
command: command.to_string(),
output_len,
session_id: "test".to_string(),
output_content: None,
is_error: false,
sequence_index: 0,
}
}
// --- Progress bar ---
#[test]
fn test_progress_bar_boundaries() {
assert_eq!(progress_bar(0.0, 5), ".....");
assert_eq!(progress_bar(100.0, 5), "@@@@@");
assert_eq!(progress_bar(50.0, 5), "@@@..");
}
// --- count_rtk_commands: core counting logic ---
#[test]
fn test_count_all_rtk() {
let cmds = vec![
make_cmd("rtk git status", Some(200)),
make_cmd("rtk cargo test", Some(5000)),
make_cmd("rtk git log -10", Some(800)),
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
assert_eq!(rtk, 3);
assert_eq!(output, 6000);
}
#[test]
fn test_count_hook_rewritten_commands() {
// Hook rewrites "git status" → "rtk git status" but JSONL logs the original.
// count_rtk_commands should detect these via classify_command.
let cmds = vec![
make_cmd("git status", Some(500)),
make_cmd("cargo test", Some(3000)),
make_cmd("echo hello", Some(100)),
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
// git status + cargo test are supported by RTK, echo is not
assert_eq!(rtk, 2);
assert_eq!(output, 3600);
}
#[test]
fn test_count_mixed_explicit_and_hook() {
let cmds = vec![
make_cmd("rtk git status", Some(200)), // explicit rtk
make_cmd("git log -5", Some(1000)), // hook-rewritten (logged as raw)
make_cmd("rtk cargo test", Some(5000)), // explicit rtk
make_cmd("echo hello", None), // not supported
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 4);
assert_eq!(rtk, 3); // rtk git status + git log + rtk cargo test
assert_eq!(output, 6200);
}
#[test]
fn test_count_unsupported_commands_not_counted() {
let cmds = vec![
make_cmd("echo hello", Some(100)),
make_cmd("mkdir -p /tmp/foo", Some(10)),
make_cmd("cd /tmp", Some(5)),
];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
assert_eq!(rtk, 0);
}
#[test]
fn test_count_empty_commands() {
let cmds: Vec<ExtractedCommand> = vec![];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 0);
assert_eq!(rtk, 0);
assert_eq!(output, 0);
}
// --- chained commands ---
#[test]
fn test_count_chained_commands_split() {
// "cd ./path && rtk ls" is one ExtractedCommand but two logical commands.
// cd is ignored/unsupported, ls is supported → 1 out of 2 covered.
let cmds = vec![make_cmd("cd ./your/app/path && rtk ls", Some(200))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain should split into 2 commands");
assert_eq!(rtk, 1, "only 'rtk ls' is RTK-covered");
}
#[test]
fn test_count_chained_all_supported() {
// Both parts are RTK-supported
let cmds = vec![make_cmd("git status && git log -5", Some(500))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain should split into 2 commands");
assert_eq!(rtk, 2, "both git commands are RTK-covered");
}
#[test]
fn test_count_chained_with_semicolon() {
let cmds = vec![make_cmd("cd /tmp; git status; echo done", Some(100))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 3, "semicolon chain splits into 3 commands");
assert_eq!(rtk, 1, "only git status is RTK-covered");
}
#[test]
fn test_count_chained_no_false_inflation() {
// Single command should still count as 1
let cmds = vec![make_cmd("git status", Some(100))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 1);
assert_eq!(rtk, 1);
}
// --- adoption_pct ---
#[test]
fn test_adoption_pct_zero_division() {
let s = SessionSummary {
id: "x".to_string(),
date: "Today".to_string(),
total_cmds: 0,
rtk_cmds: 0,
output_tokens: 0,
};
assert_eq!(s.adoption_pct(), 0.0);
}
#[test]
fn test_adoption_pct_75_percent() {
let s = SessionSummary {
id: "x".to_string(),
date: "Today".to_string(),
total_cmds: 20,
rtk_cmds: 15,
output_tokens: 0,
};
assert_eq!(s.adoption_pct(), 75.0);
}
// --- End-to-end: parse real JSONL and count ---
#[test]
fn test_parse_jsonl_session_and_count() {
// Simulate a session with 3 Bash commands: 2 rtk, 1 raw
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"rtk git status"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"On branch main"}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"Bash","input":{"command":"git log -5"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"commit abc123\ncommit def456"}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"Bash","input":{"command":"rtk cargo test"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":"test result: ok. 5 passed"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
let (total, rtk, _output) = count_rtk_commands(&cmds);
assert_eq!(total, 3, "should find 3 Bash commands");
// All 3 are RTK-covered: 2 explicit "rtk ..." + 1 hook-rewritten "git log"
assert_eq!(rtk, 3, "all 3 commands should be RTK-covered");
}
#[test]
fn test_parse_jsonl_ignores_non_bash_tools() {
// Read/Grep/Edit tools should NOT be counted
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"/tmp/foo"}}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"Grep","input":{"pattern":"TODO"}}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"Bash","input":{"command":"rtk git status"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":"clean"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 1, "only Bash tool should be counted");
assert_eq!(rtk, 1, "the one Bash command is rtk");
}
#[test]
fn test_parse_empty_session() {
// Session with no Bash commands at all
let jsonl = [
r#"{"type":"user","message":{"role":"user","content":"Hello"}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":"Hi there!"}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
assert!(cmds.is_empty(), "no Bash commands = empty");
}
#[test]
fn test_parse_jsonl_chained_command() {
// Claude often runs "cd ./path && git status" as a single Bash call.
// The adoption metric should split the chain and count each part.
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"cd ./your/app/path && rtk ls"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"file1.rs\nfile2.rs"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
assert_eq!(cmds.len(), 1, "one Bash tool call");
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain splits into cd + rtk ls");
assert_eq!(rtk, 1, "rtk ls is covered, cd is not");
}
}