Compare commits

...
Author SHA1 Message Date
Ousama Ben YounesandClaude Opus 4.6 91a635622f fix: prevent rtk read from corrupting JSON/YAML/data files
The comment-stripping filter treated `/*` and `*/` inside JSON string
values as block comment delimiters. This caused `"packages/*"` to open
a block comment and `"**/package.json"` to close it, silently deleting
everything in between (scripts, lint-staged config, etc.).

Fix: add `Language::Data` variant for JSON, YAML, TOML, XML, CSV, MD,
and other data formats. Data files skip all comment stripping and code
filtering, preserving structure integrity.

Affected extensions: json, jsonc, json5, yaml, yml, toml, xml, csv,
tsv, graphql, gql, sql, md, markdown, txt, env, lock

Fixes #464

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 17:22:29 +01:00
patrick szymkowiak 810d7ffb63 fix: resolve cargo fmt + 54 clippy warnings blocking CI (#663)
cargo fmt diffs in config.rs, git.rs, playwright_cmd.rs were failing
the fmt CI check, which cascaded to block clippy/test/security on
PRs #632, #635, #638. Also fixes all clippy warnings: dead code
annotations, iterator simplifications, assert patterns, and
unnecessary allocations.

Signed-off-by: Patrick Szymkowiak <patrick@rtk-ai.app>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-17 17:18:35 +01:00
patrick szymkowiak ff8e490c85 fix: subcommand routing drops unrecognized subcommands (#600) (#601)
- 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-17 15:36:04 +01:00
Florian BRUNIAUX b29344f68b feat(.claude): add /rtk-triage skill — cross-analysis of PRs and issues (#662)
* feat(.claude): add /rtk-triage skill — orchestrated PR+issue cross-analysis

New skill that runs issue-triage + pr-triage in parallel then produces
a cross-analysis layer that neither skill can do individually:

- Double coverage detection: identifies when 2+ PRs target the same issue
  (via body scan + file overlap), recommends which to keep/close
- Security gap detection: for security review issues, maps each finding
  to a PR (or flags it as uncovered)
- P0/P1 bugs without PR: groups by pattern to suggest sprint batching
- Our dirty PRs: identifies probable cause (conflict with sibling PR,
  needs rebase, missing linked issue)

Output is saved automatically to claudedocs/RTK-YYYY-MM-DD.md.

Usage: /rtk-triage           (French, auto-save)
       /rtk-triage en        (English output)

Signed-off-by: Florian Bruniaux <florian@bel-etage.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>

* docs(architecture): update module count to 66

Sync ARCHITECTURE.md with current main.rs state.
Previous count (60) was stale since several modules were added
(dotnet_cmd, dotnet_format_report, dotnet_trx, npm_cmd, gt_cmd, etc.).

Signed-off-by: Florian Bruniaux <florian@bel-etage.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>

---------

Signed-off-by: Florian Bruniaux <florian@bel-etage.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-03-17 15:35:24 +01:00
patrick szymkowiak 0414020d57 fix: raise output caps for P0 bugs (#617, #618, #620) (#630)
* fix: raise output caps for grep, git status, and parser fallback (#617, #618, #620)

- grep: per-file match cap 10 → 25, global max 50 → 200
- git status: file list caps 5/5/3 → 15/15/10
- parser fallback: truncate 500 → 2000 chars across all modules

These P0 bugs caused LLM retry loops when RTK returned less signal
than the raw command, making RTK worse than not using it.

Fixes #617, #618, #620

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

* fix: update README example and add truncation tests for modified/untracked

- parser/README.md: update example from 500 → 2000 to match code
- git.rs: add test_format_status_modified_truncation (cap 15)
- git.rs: add test_format_status_untracked_truncation (cap 10)

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

* refactor: extract output caps into [limits] config section

Move hardcoded caps into config.toml so users can tune them:

  [limits]
  grep_max_results = 200      # global grep match limit
  grep_max_per_file = 25      # per-file match limit
  status_max_files = 15       # staged/modified file list cap
  status_max_untracked = 10   # untracked file list cap
  passthrough_max_chars = 2000 # parser fallback truncation

All 8 modules now read from config::limits() instead of hardcoded
values. Defaults unchanged from previous commit.

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

---------

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 14:58:14 +01:00
patrick szymkowiak 5b57c4204a fix: P1 exit codes, grep regex perf, SQLite WAL (#631)
* fix: P1 exit codes, grep regex perf, SQLite concurrency

Exit code propagation (same pattern as existing modules):
- wget_cmd: run() and run_stdout() now exit on failure
- container: docker_logs, kubectl_pods/services/logs now check
  status before parsing JSON (was showing "No pods found" on error)
- pnpm_cmd: replace bail!() with eprint + process::exit in
  run_list and run_install

Performance:
- grep_cmd: compile context regex once before loop instead of
  per-line in clean_line() (was N compilations per grep call)

Data integrity:
- tracking: add PRAGMA journal_mode=WAL and busy_timeout=5000
  to prevent SQLite corruption with concurrent Claude Code instances

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

* fix: address review findings on P1 fixes

- tracking: WAL pragma non-fatal (NFS/read-only compat)
- wget: forward raw stderr on failure, track raw==raw (no fake savings)
- container: remove stderr shadow in docker_logs, add empty-stderr
  guard on all 4 new exit code paths for consistency with prisma pattern

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

---------

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 14:58:02 +01:00
37 changed files with 664 additions and 131 deletions

No files matched your search

+237
View File
@@ -0,0 +1,237 @@
---
description: >
Triage complet RTK : exécute issue-triage + pr-triage en parallèle,
puis croise les données pour détecter doubles couvertures, trous sécurité,
P0 sans PR, et conflits internes. Sauvegarde dans claudedocs/RTK-YYYY-MM-DD.md.
Args: "en"/"fr" pour la langue (défaut: fr), "save" pour forcer la sauvegarde.
allowed-tools:
- Bash
- Write
- Read
- AskUserQuestion
---
# /rtk-triage
Orchestrateur de triage RTK. Fusionne issue-triage + pr-triage et produit une analyse croisée.
---
## Quand utiliser
- Hebdomadaire ou avant chaque sprint
- Quand le backlog PR/issues grossit rapidement
- Pour identifier les doublons avant de reviewer
---
## Workflow en 4 phases
### Phase 0 — Préconditions
```bash
git rev-parse --is-inside-work-tree
gh auth status
```
Vérifier que la date actuelle est connue (utiliser `date +%Y-%m-%d`).
---
### Phase 1 — Data gathering (parallèle)
Lancer les deux collectes simultanément :
**Issues** :
```bash
gh repo view --json nameWithOwner -q .nameWithOwner
gh issue list --state open --limit 150 \
--json number,title,author,createdAt,updatedAt,labels,assignees,body
gh issue list --state closed --limit 20 \
--json number,title,labels,closedAt
gh api "repos/{owner}/{repo}/collaborators" --jq '.[].login'
```
**PRs** :
```bash
gh pr list --state open --limit 60 \
--json number,title,author,createdAt,updatedAt,additions,deletions,changedFiles,isDraft,mergeable,reviewDecision,statusCheckRollup,body
# Pour chaque PR, récupérer les fichiers modifiés (nécessaire pour overlap detection)
# Prioriser les PRs candidates (même domaine, même auteur)
gh pr view {num} --json files --jq '[.files[].path] | join(",")'
```
---
### Phase 2 — Triage individuel
Exécuter les analyses de `/issue-triage` et `/pr-triage` séparément (même logique que les skills individuels) pour produire :
**Issues** :
- Catégorisation (Bug/Feature/Enhancement/Question/Duplicate)
- Risque (Rouge/Jaune/Vert)
- Staleness (>30j)
- Map `issue_number → [PR numbers]` via scan `fixes #N`, `closes #N`, `resolves #N`
**PRs** :
- Taille (XS/S/M/L/XL)
- CI status (clean/dirty)
- Nos PRs vs externes
- Overlaps (>50% fichiers communs entre 2 PRs)
- Clusters (auteur avec 3+ PRs)
Afficher les tableaux standards de chaque skill (voir SKILL.md de issue-triage et pr-triage pour le format exact).
---
### Phase 3 — Analyse croisée (cœur de ce skill)
C'est ici que ce skill apporte de la valeur au-delà des deux skills individuels.
#### 3.1 Double couverture — 2 PRs pour 1 issue
Pour chaque issue liée à ≥2 PRs (via scan des bodies + overlap fichiers) :
| Issue | PR1 (infos) | PR2 (infos) | Verdict recommandé |
|-------|-------------|-------------|-------------------|
| #N (titre) | PR#X — auteur, taille, CI | PR#Y — auteur, taille, CI | Garder la plus ciblée. Fermer/coordonner l'autre |
Règle de verdict :
- Préférer la plus petite (XS < S < M) si même scope
- Préférer CI clean sur CI dirty
- Préférer "nos PRs" si l'une est interne
- Si overlap de fichiers >80% → conflit quasi-certain, signaler
#### 3.2 Trous de couverture sécurité
Pour chaque issue rouge (#640-type security review) :
- Lister les sous-findings mentionnés dans le body
- Croiser avec les PRs existantes (mots-clés dans titre/body)
- Identifier les findings sans PR
Format :
```
## Issue #N — security review (finding par finding)
| Finding | PR associée | Status |
|---------|-------------|--------|
| Description finding 1 | PR#X | En review |
| **Description finding critique** | **AUCUNE** | ⚠️ Trou |
```
#### 3.3 P0/P1 bugs sans PR
Issues labelisées P0 ou P1 (ou mots-clés : "crash", "truncat", "cap", "hardcoded") sans aucune PR liée.
Format :
```
## Bugs critiques sans PR
| Issue | Titre | Pattern commun | Effort estimé |
|-------|-------|----------------|---------------|
```
Chercher un pattern commun (ex: "cap hardcodé", "exit code perdu") — si 3+ bugs partagent un pattern, suggérer un sprint groupé.
#### 3.4 Nos PRs dirty — causes probables
Pour chaque PR interne avec CI dirty ou CONFLICTING :
- Vérifier si un autre PR touche les mêmes fichiers
- Vérifier si un merge récent sur develop peut expliquer le conflit
- Recommander : rebase, fermeture, ou attente
Format :
```
## Nos PRs dirty
| PR | Issue(s) | Cause probable | Action |
|----|----------|----------------|--------|
```
#### 3.5 PRs sans issue trackée
PRs internes sans `fixes #N` dans le body — signaler pour traçabilité.
---
### Phase 4 — Output final
#### Afficher l'analyse croisée complète (sections 3.1 → 3.5)
Puis afficher le résumé chiffré :
```
## Résumé chiffré — YYYY-MM-DD
| Catégorie | Count |
|-----------|-------|
| PRs prêtes à merger (nos) | N |
| Quick wins externes | N |
| Double couverture (conflicts) | N paires |
| P0/P1 bugs sans PR | N |
| Security findings sans PR | N |
| Nos PRs dirty à rebaser | N |
| PRs à fermer (recommandé) | N |
```
#### Sauvegarder dans claudedocs
```bash
date +%Y-%m-%d # Pour construire le nom de fichier
```
Sauvegarder dans `claudedocs/RTK-YYYY-MM-DD.md` avec :
- Les tableaux de triage issues + PRs (Phase 2)
- L'analyse croisée complète (Phase 3)
- Le résumé chiffré
Confirmer : `Sauvegardé dans claudedocs/RTK-YYYY-MM-DD.md`
---
## Format du fichier sauvegardé
```markdown
# RTK Triage — YYYY-MM-DD
Croisement issues × PRs. {N} PRs ouvertes, {N} issues ouvertes.
---
## 1. Double couverture
...
## 2. Trous sécurité
...
## 3. P0/P1 sans PR
...
## 4. Nos PRs dirty
...
## 5. Nos PRs prêtes à merger
...
## 6. Quick wins externes
...
## 7. Actions prioritaires
(liste ordonnée par impact/urgence)
---
## Résumé chiffré
...
```
---
## Règles
- Langue : argument `en`/`fr`. Défaut : `fr`. Les commentaires GitHub restent toujours en anglais.
- Ne jamais poster de commentaires GitHub sans validation utilisateur (AskUserQuestion).
- Si >150 issues ou >60 PRs : prévenir l'utilisateur, proposer de filtrer par label ou date.
- L'analyse croisée (Phase 3) est toujours exécutée — c'est la valeur ajoutée de ce skill.
- Le fichier claudedocs est sauvegardé automatiquement sauf si l'utilisateur dit "no save".
+1 -1
View File
@@ -293,7 +293,7 @@ SHARED utils.rs Helpers N/A ✓
tee.rs Full output recovery N/A ✓
```
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
**Total: 66 modules** (44 command modules + 22 infrastructure modules)
### Module Count Breakdown
+1
View File
@@ -14,6 +14,7 @@ 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)
+1
View File
@@ -112,6 +112,7 @@ fn build_command() -> Option<Command> {
}
/// Check if ccusage CLI is available (binary or via npx)
#[allow(dead_code)]
pub fn is_available() -> bool {
build_command().is_some()
}
+33
View File
@@ -16,6 +16,8 @@ pub struct Config {
pub telemetry: TelemetryConfig,
#[serde(default)]
pub hooks: HooksConfig,
#[serde(default)]
pub limits: LimitsConfig,
}
#[derive(Debug, Serialize, Deserialize, Default)]
@@ -94,6 +96,37 @@ impl Default for TelemetryConfig {
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LimitsConfig {
/// Max total grep results to show (default: 200)
pub grep_max_results: usize,
/// Max matches per file in grep output (default: 25)
pub grep_max_per_file: usize,
/// Max staged/modified files shown in git status (default: 15)
pub status_max_files: usize,
/// Max untracked files shown in git status (default: 10)
pub status_max_untracked: usize,
/// Max chars for parser passthrough fallback (default: 2000)
pub passthrough_max_chars: usize,
}
impl Default for LimitsConfig {
fn default() -> Self {
Self {
grep_max_results: 200,
grep_max_per_file: 25,
status_max_files: 15,
status_max_untracked: 10,
passthrough_max_chars: 2000,
}
}
}
/// Get limits config. Falls back to defaults if config can't be loaded.
pub fn limits() -> LimitsConfig {
Config::load().map(|c| c.limits).unwrap_or_default()
}
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
pub fn telemetry_enabled() -> Option<bool> {
Config::load().ok().map(|c| c.telemetry.enabled)
+53 -2
View File
@@ -67,7 +67,12 @@ fn docker_ps(_verbose: u8) -> Result<()> {
if parts.len() >= 4 {
let id = &parts[0][..12.min(parts[0].len())];
let name = parts[1];
let short_image = parts.get(3).unwrap_or(&"").split('/').last().unwrap_or("");
let short_image = parts
.get(3)
.unwrap_or(&"")
.split('/')
.next_back()
.unwrap_or("");
let ports = compact_ports(parts.get(4).unwrap_or(&""));
if ports == "-" {
rtk.push_str(&format!(" {} {} ({})\n", id, name, short_image));
@@ -183,6 +188,19 @@ fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
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!("🐳 Logs for {}:\n{}", container, analyzed);
println!("{}", rtk);
@@ -208,6 +226,15 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
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(_) => {
@@ -306,6 +333,15 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
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(_) => {
@@ -381,6 +417,21 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
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);
@@ -516,7 +567,7 @@ fn compact_ports(ports: &str) -> String {
// Extract just the port numbers
let port_nums: Vec<&str> = ports
.split(',')
.filter_map(|p| p.split("->").next().and_then(|s| s.split(':').last()))
.filter_map(|p| p.split("->").next().and_then(|s| s.split(':').next_back()))
.collect();
if port_nums.len() <= 3 {
+4 -3
View File
@@ -18,6 +18,7 @@ pub struct ExtractedCommand {
/// Whether the tool_result indicated an error
pub is_error: bool,
/// Chronological sequence index within the session
#[allow(dead_code)]
pub sequence_index: usize,
}
@@ -347,7 +348,7 @@ mod tests {
let cmds = provider.extract_commands(jsonl.path()).unwrap();
assert_eq!(cmds.len(), 1);
assert_eq!(cmds[0].command, "git commit --ammend");
assert_eq!(cmds[0].is_error, true);
assert!(cmds[0].is_error);
assert!(cmds[0].output_content.is_some());
assert_eq!(
cmds[0].output_content.as_ref().unwrap(),
@@ -365,8 +366,8 @@ mod tests {
let provider = ClaudeProvider;
let cmds = provider.extract_commands(jsonl.path()).unwrap();
assert_eq!(cmds.len(), 2);
assert_eq!(cmds[0].is_error, false);
assert_eq!(cmds[1].is_error, true);
assert!(!cmds[0].is_error);
assert!(cmds[1].is_error);
}
#[test]
+3 -5
View File
@@ -679,12 +679,10 @@ mod tests {
"tail -f app.log > /dev/null",
];
for cmd in &write_commands {
match classify_command(cmd) {
Classification::Supported { .. } => {
panic!("{} should NOT be classified as Supported", cmd)
}
_ => {} // Unsupported or Ignored is fine
if let Classification::Supported { .. } = classify_command(cmd) {
panic!("{} should NOT be classified as Supported", cmd)
}
// Unsupported or Ignored is fine
}
}
+30 -1
View File
@@ -50,6 +50,7 @@ pub enum Language {
Java,
Ruby,
Shell,
/// Data formats (JSON, YAML, TOML, XML, CSV) — no comment stripping
Data,
Unknown,
}
@@ -69,7 +70,7 @@ impl Language {
"sh" | "bash" | "zsh" => Language::Shell,
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "html" | "htm"
| "css" | "scss" | "svg" | "md" | "markdown" | "txt" | "csv" | "tsv" | "env"
| "ini" | "cfg" | "conf" | "lock" => Language::Data,
| "ini" | "cfg" | "conf" | "lock" | "graphql" | "gql" | "sql" => Language::Data,
_ => Language::Unknown,
}
}
@@ -249,6 +250,11 @@ lazy_static! {
impl FilterStrategy for AggressiveFilter {
fn filter(&self, content: &str, lang: &Language) -> String {
// Data formats (JSON, YAML, etc.) must never be code-filtered
if *lang == Language::Data {
return MinimalFilter.filter(content, lang);
}
let minimal = MinimalFilter.filter(content, lang);
let mut result = String::with_capacity(minimal.len() / 2);
let mut brace_depth = 0;
@@ -444,6 +450,29 @@ mod tests {
result.contains("**/package.json"),
"glob pattern must be preserved"
);
assert!(
result.contains("lint-staged"),
"lint-staged section must not be stripped"
);
}
#[test]
fn test_json_aggressive_filter_preserves_structure() {
let json = r#"{
"name": "my-app",
"dependencies": {
"react": "^18.0.0"
},
"scripts": {
"dev": "next dev /* not a comment */"
}
}"#;
let filter = AggressiveFilter;
let result = filter.filter(json, &Language::Data);
assert!(
result.contains("/* not a comment */"),
"Aggressive filter must not strip comment-like patterns in JSON"
);
}
#[test]
+1 -1
View File
@@ -168,7 +168,7 @@ fn filter_black_output(output: &str) -> String {
// Split by comma to handle both parts
for part in trimmed.split(',') {
let part_lower = part.to_lowercase();
let words: Vec<&str> = part.trim().split_whitespace().collect();
let words: Vec<&str> = part.split_whitespace().collect();
if part_lower.contains("would be reformatted") {
// Parse "X file(s) would be reformatted"
+1
View File
@@ -8,6 +8,7 @@ use serde::Serialize;
use std::io::IsTerminal;
use std::path::PathBuf;
#[allow(clippy::too_many_arguments)]
pub fn run(
project: bool, // added: per-project scope flag
graph: bool,
+2 -2
View File
@@ -193,8 +193,8 @@ fn run_pr(args: &[String], verbose: u8, ultra_compact: bool) -> Result<()> {
"create" => pr_create(&args[1..], verbose),
"merge" => pr_merge(&args[1..], verbose),
"diff" => pr_diff(&args[1..], verbose),
"comment" => pr_action("commented", &args, verbose),
"edit" => pr_action("edited", &args, verbose),
"comment" => pr_action("commented", args, verbose),
"edit" => pr_action("edited", args, verbose),
_ => run_passthrough("gh", "pr", args),
}
}
+158 -33
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -355,7 +356,7 @@ fn run_log(
// Check if user provided limit flag (-N, -n N, --max-count=N, --max-count N)
let has_limit_flag = args.iter().any(|arg| {
(arg.starts_with('-') && arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit()))
(arg.starts_with('-') && arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit()))
|| arg == "-n"
|| arg.starts_with("--max-count")
});
@@ -433,7 +434,7 @@ fn parse_user_limit(args: &[String]) -> Option<usize> {
// -20 (combined digit form)
if arg.starts_with('-')
&& arg.len() > 1
&& arg.chars().nth(1).map_or(false, |c| c.is_ascii_digit())
&& arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit())
{
if let Ok(n) = arg[1..].parse::<usize>() {
return Some(n);
@@ -592,33 +593,46 @@ fn format_status_output(porcelain: &str) -> String {
}
// Build summary
let limits = config::limits();
let max_files = limits.status_max_files;
let max_untracked = limits.status_max_untracked;
if staged > 0 {
output.push_str(&format!("✅ Staged: {} files\n", staged));
for f in staged_files.iter().take(5) {
for f in staged_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if staged_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", staged_files.len() - 5));
if staged_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
staged_files.len() - max_files
));
}
}
if modified > 0 {
output.push_str(&format!("📝 Modified: {} files\n", modified));
for f in modified_files.iter().take(5) {
for f in modified_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if modified_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", modified_files.len() - 5));
if modified_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
modified_files.len() - max_files
));
}
}
if untracked > 0 {
output.push_str(&format!("❓ Untracked: {} files\n", untracked));
for f in untracked_files.iter().take(3) {
for f in untracked_files.iter().take(max_untracked) {
output.push_str(&format!(" {}\n", f));
}
if untracked_files.len() > 3 {
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - 3));
if untracked_files.len() > max_untracked {
output.push_str(&format!(
" ... +{} more\n",
untracked_files.len() - max_untracked
));
}
}
@@ -833,7 +847,7 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
// Extract commit hash from output like "[main abc1234] message"
let compact = if let Some(line) = stdout.lines().next() {
if let Some(hash_start) = line.find(' ') {
let hash = line[1..hash_start].split(' ').last().unwrap_or("");
let hash = line[1..hash_start].split(' ').next_back().unwrap_or("");
if !hash.is_empty() && hash.len() >= 7 {
format!("ok ✓ {}", &hash[..7.min(hash.len())])
} else {
@@ -1027,10 +1041,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| {
@@ -1043,11 +1070,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);
@@ -1303,7 +1368,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");
@@ -1690,23 +1790,48 @@ A added.rs
#[test]
fn test_format_status_output_truncation() {
// Test that >5 staged files show "... +N more"
let porcelain = r#"## main
M file1.rs
M file2.rs
M file3.rs
M file4.rs
M file5.rs
M file6.rs
M file7.rs
"#;
let result = format_status_output(porcelain);
assert!(result.contains("✅ Staged: 7 files"));
// Test that >15 staged files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!("M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("✅ Staged: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file5.rs"));
assert!(result.contains("... +2 more"));
assert!(!result.contains("file6.rs"));
assert!(!result.contains("file7.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
assert!(!result.contains("file20.rs"));
}
#[test]
fn test_format_status_modified_truncation() {
// Test that >15 modified files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!(" M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("📝 Modified: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
}
#[test]
fn test_format_status_untracked_truncation() {
// Test that >10 untracked files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=15 {
porcelain.push_str(&format!("?? file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("❓ Untracked: 15 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file10.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file11.rs"));
}
#[test]
+5 -1
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -9,8 +10,10 @@ struct Position {
#[serde(rename = "Filename")]
filename: String,
#[serde(rename = "Line")]
#[allow(dead_code)]
line: usize,
#[serde(rename = "Column")]
#[allow(dead_code)]
column: usize,
}
@@ -19,6 +22,7 @@ struct Issue {
#[serde(rename = "FromLinter")]
from_linter: String,
#[serde(rename = "Text")]
#[allow(dead_code)]
text: String,
#[serde(rename = "Pos")]
pos: Position,
@@ -106,7 +110,7 @@ fn filter_golangci_json(output: &str) -> String {
return format!(
"golangci-lint (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+23 -15
View File
@@ -1,9 +1,11 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashMap;
#[allow(clippy::too_many_arguments)]
pub fn run(
pattern: &str,
path: &str,
@@ -77,6 +79,13 @@ pub fn run(
let mut by_file: HashMap<String, Vec<(usize, String)>> = HashMap::new();
let mut total = 0;
// Compile context regex once (instead of per-line in clean_line)
let context_re = if context_only {
Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))).ok()
} else {
None
};
for line in stdout.lines() {
let parts: Vec<&str> = line.splitn(3, ':').collect();
@@ -91,7 +100,7 @@ pub fn run(
};
total += 1;
let cleaned = clean_line(content, max_line_len, context_only, pattern);
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), pattern);
by_file.entry(file).or_default().push((line_num, cleaned));
}
@@ -110,7 +119,8 @@ pub fn run(
let file_display = compact_path(file);
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
for (line_num, content) in matches.iter().take(10) {
let per_file = config::limits().grep_max_per_file;
for (line_num, content) in matches.iter().take(per_file) {
rtk_output.push_str(&format!(" {:>4}: {}\n", line_num, content));
shown += 1;
if shown >= max_results {
@@ -118,8 +128,8 @@ pub fn run(
}
}
if matches.len() > 10 {
rtk_output.push_str(&format!(" +{}\n", matches.len() - 10));
if matches.len() > per_file {
rtk_output.push_str(&format!(" +{}\n", matches.len() - per_file));
}
rtk_output.push('\n');
}
@@ -143,16 +153,14 @@ pub fn run(
Ok(())
}
fn clean_line(line: &str, max_len: usize, context_only: bool, pattern: &str) -> String {
fn clean_line(line: &str, max_len: usize, context_re: Option<&Regex>, pattern: &str) -> String {
let trimmed = line.trim();
if context_only {
if let Ok(re) = Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))) {
if let Some(m) = re.find(trimmed) {
let matched = m.as_str();
if matched.len() <= max_len {
return matched.to_string();
}
if let Some(re) = context_re {
if let Some(m) = re.find(trimmed) {
let matched = m.as_str();
if matched.len() <= max_len {
return matched.to_string();
}
}
}
@@ -216,7 +224,7 @@ mod tests {
#[test]
fn test_clean_line() {
let line = " const result = someFunction();";
let cleaned = clean_line(line, 50, false, "result");
let cleaned = clean_line(line, 50, None, "result");
assert!(!cleaned.starts_with(' '));
assert!(cleaned.len() <= 50);
}
@@ -240,7 +248,7 @@ mod tests {
fn test_clean_line_multibyte() {
// Thai text that exceeds max_len in bytes
let line = " สวัสดีครับ นี่คือข้อความที่ยาวมากสำหรับทดสอบ ";
let cleaned = clean_line(line, 20, false, "ครับ");
let cleaned = clean_line(line, 20, None, "ครับ");
// Should not panic
assert!(!cleaned.is_empty());
}
@@ -248,7 +256,7 @@ mod tests {
#[test]
fn test_clean_line_emoji() {
let line = "🎉🎊🎈🎁🎂🎄 some text 🎃🎆🎇✨";
let cleaned = clean_line(line, 15, false, "text");
let cleaned = clean_line(line, 15, None, "text");
assert!(!cleaned.is_empty());
}
+6 -10
View File
@@ -507,7 +507,7 @@ pub fn uninstall(global: bool, verbose: u8) -> Result<()> {
fs::write(&claude_md_path, cleaned).with_context(|| {
format!("Failed to write CLAUDE.md: {}", claude_md_path.display())
})?;
removed.push(format!("CLAUDE.md: removed @RTK.md reference"));
removed.push("CLAUDE.md: removed @RTK.md reference".to_string());
}
}
@@ -566,7 +566,7 @@ fn patch_settings_json(
};
// Check idempotency
if hook_already_present(&root, &hook_command) {
if hook_already_present(&root, hook_command) {
if verbose > 0 {
eprintln!("settings.json: hook already present");
}
@@ -591,7 +591,7 @@ fn patch_settings_json(
}
// Deep-merge hook
insert_hook_entry(&mut root, &hook_command);
insert_hook_entry(&mut root, hook_command);
// Backup original
if settings_path.exists() {
@@ -637,7 +637,6 @@ fn clean_double_blanks(content: &str) -> String {
if line.trim().is_empty() {
// Count consecutive blank lines
let mut blank_count = 0;
let start = i;
while i < lines.len() && lines[i].trim().is_empty() {
blank_count += 1;
i += 1;
@@ -645,9 +644,7 @@ fn clean_double_blanks(content: &str) -> String {
// Keep at most 2 blank lines
let keep = blank_count.min(2);
for _ in 0..keep {
result.push("");
}
result.extend(std::iter::repeat_n("", keep));
} else {
result.push(line);
i += 1;
@@ -1405,7 +1402,6 @@ fn run_opencode_only_mode(verbose: u8) -> Result<()> {
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
use tempfile::TempDir;
#[test]
@@ -1774,8 +1770,8 @@ More notes
let serialized = serde_json::to_string(&parsed).unwrap();
// Keys should appear in same order
let original_keys: Vec<&str> = original.split("\"").filter(|s| s.contains(":")).collect();
let serialized_keys: Vec<&str> =
let _original_keys: Vec<&str> = original.split("\"").filter(|s| s.contains(":")).collect();
let _serialized_keys: Vec<&str> =
serialized.split("\"").filter(|s| s.contains(":")).collect();
// Just check that keys exist (preserve_order doesn't guarantee exact order in nested objects)
+2 -3
View File
@@ -5,6 +5,7 @@ use regex::Regex;
pub enum ErrorType {
UnknownFlag,
CommandNotFound,
#[allow(dead_code)]
WrongSyntax,
WrongPath,
MissingArg,
@@ -229,9 +230,7 @@ pub fn find_corrections(commands: &[CommandExecution]) -> Vec<CorrectionPair> {
}
// Look ahead for correction within CORRECTION_WINDOW
for j in (i + 1)..std::cmp::min(i + 1 + CORRECTION_WINDOW, commands.len()) {
let candidate = &commands[j];
for candidate in commands.iter().skip(i + 1).take(CORRECTION_WINDOW) {
let similarity = command_similarity(&cmd.command, &candidate.command);
// Must meet minimum similarity
+5 -2
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::mypy_cmd;
use crate::ruff_cmd;
use crate::tracking;
@@ -35,11 +36,13 @@ struct PylintDiagnostic {
module: String,
#[allow(dead_code)]
obj: String,
#[allow(dead_code)]
line: usize,
#[allow(dead_code)]
column: usize,
path: String,
symbol: String, // rule code like "unused-variable"
#[allow(dead_code)]
message: String,
#[serde(rename = "message-id")]
message_id: String, // e.g., "W0612"
@@ -234,7 +237,7 @@ fn filter_eslint_json(output: &str) -> String {
return format!(
"ESLint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
@@ -326,7 +329,7 @@ fn filter_pylint_json(output: &str) -> String {
return format!(
"Pylint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+1 -1
View File
@@ -105,7 +105,7 @@ fn analyze_logs(content: &str) -> String {
let total_warnings: usize = warn_counts.values().sum();
let total_info: usize = info_counts.values().sum();
result.push(format!("📊 Log Summary"));
result.push("📊 Log Summary".to_string());
result.push(format!(
" ❌ {} errors ({} unique)",
total_errors,
+3 -3
View File
@@ -306,7 +306,7 @@ enum Commands {
#[arg(short = 'l', long, default_value = "80")]
max_len: usize,
/// Max results to show
#[arg(short, long, default_value = "50")]
#[arg(short, long, default_value = "200")]
max: usize,
/// Show only match context (not full line)
#[arg(short, long)]
@@ -1179,11 +1179,11 @@ enum GtCommands {
fn shell_split(input: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut chars = input.chars().peekable();
let chars = input.chars();
let mut in_single = false;
let mut in_double = false;
while let Some(c) = chars.next() {
for c in chars {
match c {
'\'' if !in_double => in_single = !in_single,
'"' if !in_single => in_double = !in_double,
+1 -1
View File
@@ -70,7 +70,7 @@ impl OutputParser for VitestParser {
)
} else {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_output(input, 2000))
}
}
}
+1
View File
@@ -2,6 +2,7 @@
use thiserror::Error;
#[derive(Error, Debug)]
#[allow(dead_code)]
pub enum ParseError {
#[error("JSON parse failed at line {line}, column {col}: {msg}")]
JsonError {
+13 -1
View File
@@ -29,6 +29,7 @@ pub enum ParseResult<T> {
impl<T> ParseResult<T> {
/// Unwrap the parsed data, panicking on Passthrough
#[allow(dead_code)]
pub fn unwrap(self) -> T {
match self {
ParseResult::Full(data) => data,
@@ -38,6 +39,7 @@ impl<T> ParseResult<T> {
}
/// Get the tier level (1 = Full, 2 = Degraded, 3 = Passthrough)
#[allow(dead_code)]
pub fn tier(&self) -> u8 {
match self {
ParseResult::Full(_) => 1,
@@ -47,11 +49,13 @@ impl<T> ParseResult<T> {
}
/// Check if parsing succeeded (Full or Degraded)
#[allow(dead_code)]
pub fn is_ok(&self) -> bool {
!matches!(self, ParseResult::Passthrough(_))
}
/// Map the parsed data while preserving tier
#[allow(dead_code)]
pub fn map<U, F>(self, f: F) -> ParseResult<U>
where
F: FnOnce(T) -> U,
@@ -64,6 +68,7 @@ impl<T> ParseResult<T> {
}
/// Get warnings if Degraded tier
#[allow(dead_code)]
pub fn warnings(&self) -> Vec<String> {
match self {
ParseResult::Degraded(_, warnings) => warnings.clone(),
@@ -85,16 +90,23 @@ pub trait OutputParser: Sized {
fn parse(input: &str) -> ParseResult<Self::Output>;
/// Parse with explicit tier preference (for testing/debugging)
#[allow(dead_code)]
fn parse_with_tier(input: &str, max_tier: u8) -> ParseResult<Self::Output> {
let result = Self::parse(input);
if result.tier() > max_tier {
// Force degradation to passthrough if exceeds max tier
return ParseResult::Passthrough(truncate_output(input, 500));
return ParseResult::Passthrough(truncate_passthrough(input));
}
result
}
}
/// Truncate output using configured passthrough limit
pub fn truncate_passthrough(output: &str) -> String {
let max_chars = crate::config::limits().passthrough_max_chars;
truncate_output(output, max_chars)
}
/// Truncate output to max length with ellipsis
pub fn truncate_output(output: &str, max_chars: usize) -> String {
let chars: Vec<char> = output.chars().collect();
+9
View File
@@ -23,6 +23,7 @@ pub struct TestFailure {
/// Linting result (eslint, biome, tsc, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct LintResult {
pub total_files: usize,
pub files_with_issues: usize,
@@ -33,6 +34,7 @@ pub struct LintResult {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct LintIssue {
pub file_path: String,
pub line: usize,
@@ -43,6 +45,7 @@ pub struct LintIssue {
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[allow(dead_code)]
pub enum LintSeverity {
Error,
Warning,
@@ -68,6 +71,7 @@ pub struct Dependency {
/// Build output (next, webpack, vite, cargo, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct BuildOutput {
pub success: bool,
pub duration_ms: Option<u64>,
@@ -78,6 +82,7 @@ pub struct BuildOutput {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct BundleInfo {
pub name: String,
pub size_bytes: u64,
@@ -85,6 +90,7 @@ pub struct BundleInfo {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct RouteInfo {
pub path: String,
pub size_kb: f64,
@@ -93,6 +99,7 @@ pub struct RouteInfo {
/// Git operation result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct GitResult {
pub operation: String,
pub files_changed: usize,
@@ -102,6 +109,7 @@ pub struct GitResult {
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct GitCommit {
pub hash: String,
pub author: String,
@@ -111,6 +119,7 @@ pub struct GitCommit {
/// Generic command output (for tools without specific types)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct GenericOutput {
pub exit_code: i32,
pub stdout: String,
+3 -9
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)?
}
};
@@ -216,11 +214,7 @@ fn filter_pip_outdated(output: &str) -> String {
result.push_str("═══════════════════════════════════════\n");
for (i, pkg) in packages.iter().take(20).enumerate() {
let latest = pkg
.latest_version
.as_ref()
.map(|v| v.as_str())
.unwrap_or("unknown");
let latest = pkg.latest_version.as_deref().unwrap_or("unknown");
result.push_str(&format!(
"{}. {} ({} → {})\n",
i + 1,
+3 -3
View File
@@ -5,8 +5,8 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, FormatMode, OutputParser,
ParseResult, TestFailure, TestResult, TokenFormatter,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, FormatMode,
OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
};
/// Matches real Playwright JSON reporter output (suites → specs → tests → results)
@@ -110,7 +110,7 @@ impl OutputParser for PlaywrightParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+7 -5
View File
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::ffi::OsString;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, Dependency,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, Dependency,
DependencyState, FormatMode, OutputParser, ParseResult, TokenFormatter,
};
@@ -75,7 +75,7 @@ impl OutputParser for PnpmListParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -202,7 +202,7 @@ impl OutputParser for PnpmOutdatedParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -307,7 +307,8 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pnpm list failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -431,7 +432,8 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
anyhow::bail!("pnpm install failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let combined = format!("{}{}", stdout, stderr);
+7 -2
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -6,7 +7,9 @@ use std::collections::HashMap;
#[derive(Debug, Deserialize)]
struct RuffLocation {
#[allow(dead_code)]
row: usize,
#[allow(dead_code)]
column: usize,
}
@@ -19,7 +22,9 @@ struct RuffFix {
#[derive(Debug, Deserialize)]
struct RuffDiagnostic {
code: String,
#[allow(dead_code)]
message: String,
#[allow(dead_code)]
location: RuffLocation,
#[allow(dead_code)]
end_location: Option<RuffLocation>,
@@ -121,7 +126,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
return format!(
"Ruff check (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
@@ -237,7 +242,7 @@ pub fn filter_ruff_format(output: &str) -> String {
for part in parts {
let part_lower = part.to_lowercase();
if part_lower.contains("left unchanged") {
let words: Vec<&str> = part.trim().split_whitespace().collect();
let words: Vec<&str> = part.split_whitespace().collect();
// Look for number before "file" or "files"
for (i, word) in words.iter().enumerate() {
if (word == &"file" || word == &"files") && i > 0 {
+5 -4
View File
@@ -96,10 +96,11 @@ fn detect_output_type(output: &str, command: &str) -> OutputType {
OutputType::JsonOutput
} else if output.lines().all(|l| {
l.len() < 200
&& !l
.contains('\t')
.then_some(true)
.unwrap_or(l.split_whitespace().count() < 10)
&& if l.contains('\t') {
false
} else {
l.split_whitespace().count() < 10
}
}) {
OutputType::ListOutput
} else {
+2 -7
View File
@@ -182,20 +182,15 @@ pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<Str
}
/// TeeMode controls when tee writes files.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum TeeMode {
#[default]
Failures,
Always,
Never,
}
impl Default for TeeMode {
fn default() -> Self {
Self::Failures
}
}
/// Configuration for the tee feature.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeeConfig {
+1 -1
View File
@@ -574,7 +574,7 @@ pub fn run_filter_tests(filter_name_opt: Option<&str>) -> VerifyResults {
.into_iter()
.filter(|name| {
// When a specific filter is requested, only report that one as missing tests
filter_name_opt.map_or(true, |f| name == f)
filter_name_opt.is_none_or(|f| name == f)
})
.filter(|name| !tested_filter_names.contains(name))
.collect();
+14 -1
View File
@@ -221,6 +221,9 @@ pub struct MonthStats {
pub avg_time_ms: u64,
}
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
type CommandStats = (String, usize, usize, f64, u64);
impl Tracker {
/// Create a new tracker instance.
///
@@ -251,6 +254,12 @@ impl Tracker {
}
let conn = Connection::open(&db_path)?;
// WAL mode + busy_timeout for concurrent access (multiple Claude Code instances).
// Non-fatal: NFS/read-only filesystems may not support WAL.
let _ = conn.execute_batch(
"PRAGMA journal_mode=WAL;
PRAGMA busy_timeout=5000;",
);
conn.execute(
"CREATE TABLE IF NOT EXISTS commands (
id INTEGER PRIMARY KEY,
@@ -488,6 +497,7 @@ impl Tracker {
/// summary.total_saved, summary.avg_savings_pct);
/// # Ok::<(), anyhow::Error>(())
/// ```
#[allow(dead_code)]
pub fn get_summary(&self) -> Result<GainSummary> {
self.get_summary_filtered(None) // delegate to filtered variant
}
@@ -560,7 +570,7 @@ impl Tracker {
fn get_by_command(
&self,
project_path: Option<&str>, // added
) -> Result<Vec<(String, usize, usize, f64, u64)>> {
) -> Result<Vec<CommandStats>> {
let (project_exact, project_glob) = project_filter_params(project_path); // added
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
@@ -851,6 +861,7 @@ impl Tracker {
/// }
/// # Ok::<(), anyhow::Error>(())
/// ```
#[allow(dead_code)]
pub fn get_recent(&self, limit: usize) -> Result<Vec<CommandRecord>> {
self.get_recent_filtered(limit, None) // delegate to filtered variant
}
@@ -971,6 +982,7 @@ fn get_db_path() -> Result<PathBuf> {
pub struct ParseFailureRecord {
pub timestamp: String,
pub raw_command: String,
#[allow(dead_code)]
pub error_message: String,
pub fallback_succeeded: bool,
}
@@ -1175,6 +1187,7 @@ pub fn args_display(args: &[OsString]) -> String {
/// timer.track("ls -la", "rtk ls", "input", "output");
/// ```
#[deprecated(note = "Use TimedExecution instead")]
#[allow(dead_code)]
pub fn track(original_cmd: &str, rtk_cmd: &str, input: &str, output: &str) {
let input_tokens = estimate_tokens(input);
let output_tokens = estimate_tokens(output);
+1 -1
View File
@@ -125,7 +125,7 @@ fn filter_tree_output(raw: &str) -> String {
}
// Remove trailing empty lines
while filtered_lines.last().map_or(false, |l| l.trim().is_empty()) {
while filtered_lines.last().is_some_and(|l| l.trim().is_empty()) {
filtered_lines.pop();
}
+1
View File
@@ -140,6 +140,7 @@ pub fn check_trust(filter_path: &Path) -> Result<TrustStatus> {
}
/// Store current SHA-256 hash as trusted (computes hash from file).
#[allow(dead_code)]
pub fn trust_filter(filter_path: &Path) -> Result<()> {
let hash = integrity::compute_hash(filter_path)
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
+2 -2
View File
@@ -3,7 +3,7 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_output,
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_passthrough,
FormatMode, OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
};
use crate::tracking;
@@ -88,7 +88,7 @@ impl OutputParser for VitestParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+3 -3
View File
@@ -167,7 +167,7 @@ fn format_single_line(line: &str, mode: &WcMode) -> String {
WcMode::Mixed => {
// Strip file path, keep numbers only
if parts.len() >= 2 {
let last_is_path = parts.last().map_or(false, |p| p.parse::<u64>().is_err());
let last_is_path = parts.last().is_some_and(|p| p.parse::<u64>().is_err());
if last_is_path {
parts[..parts.len() - 1].join(" ")
} else {
@@ -202,7 +202,7 @@ fn format_multi_line(lines: &[&str], mode: &WcMode) -> String {
continue;
}
let is_total = parts.last().map_or(false, |p| *p == "total");
let is_total = parts.last().is_some_and(|p| *p == "total");
match mode {
WcMode::Lines | WcMode::Words | WcMode::Bytes | WcMode::Chars => {
@@ -236,7 +236,7 @@ fn format_multi_line(lines: &[&str], mode: &WcMode) -> String {
let nums: Vec<&str> = parts[..parts.len() - 1].to_vec();
result.push(format!("Σ {}", nums.join(" ")));
} else if parts.len() >= 2 {
let last_is_path = parts.last().map_or(false, |p| p.parse::<u64>().is_err());
let last_is_path = parts.last().is_some_and(|p| p.parse::<u64>().is_err());
if last_is_path {
let name = strip_prefix(parts.last().unwrap_or(&""), &common_prefix);
let nums: Vec<&str> = parts[..parts.len() - 1].to_vec();
+21 -8
View File
@@ -41,10 +41,16 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
} else {
let error = parse_error(&stderr, &stdout);
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget {}", url),
"rtk wget",
&raw_output,
&raw_output,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -103,10 +109,16 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
let error = parse_error(&stderr, "");
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget -O - {}", url),
"rtk wget -o",
&stderr,
&stderr,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -206,6 +218,7 @@ fn compact_url(url: &str) -> String {
}
}
#[allow(dead_code)]
fn parse_error(stderr: &str, stdout: &str) -> String {
// Common wget error patterns
let combined = format!("{}\n{}", stderr, stdout);