Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3af2f1130 | ||
|
|
ddf8403325 | ||
|
|
be67d66010 | ||
|
|
127f85c02e | ||
|
|
eb8a2c4a71 | ||
|
|
c916bab33a | ||
|
|
8e51892beb | ||
|
|
12d44c4068 | ||
|
|
2223eca224 | ||
|
|
188ec996b3 | ||
|
|
c1de10d94c | ||
|
|
d0396da1ce | ||
|
|
992f2cee1b |
No files matched your search
+1
-1
@@ -44,5 +44,5 @@ claudedocs
|
||||
.vitals/
|
||||
.worktrees/
|
||||
|
||||
# icm
|
||||
# icm
|
||||
.fastembed_cache/
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.28.2"
|
||||
".": "0.29.0"
|
||||
}
|
||||
@@ -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
@@ -892,7 +892,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtk"
|
||||
version = "0.28.2"
|
||||
version = "0.29.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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
@@ -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");
|
||||
|
||||
@@ -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
@@ -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)?
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user