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
34 changed files with 460 additions and 74 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()
}
+1 -3
View File
@@ -124,9 +124,7 @@ impl Default for LimitsConfig {
/// 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()
Config::load().map(|c| c.limits).unwrap_or_default()
}
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
+7 -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));
@@ -562,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),
}
}
+106 -11
View File
@@ -356,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")
});
@@ -434,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);
@@ -603,7 +603,10 @@ fn format_status_output(porcelain: &str) -> String {
output.push_str(&format!(" {}\n", f));
}
if staged_files.len() > max_files {
output.push_str(&format!(" ... +{} more\n", staged_files.len() - max_files));
output.push_str(&format!(
" ... +{} more\n",
staged_files.len() - max_files
));
}
}
@@ -613,7 +616,10 @@ fn format_status_output(porcelain: &str) -> String {
output.push_str(&format!(" {}\n", f));
}
if modified_files.len() > max_files {
output.push_str(&format!(" ... +{} more\n", modified_files.len() - max_files));
output.push_str(&format!(
" ... +{} more\n",
modified_files.len() - max_files
));
}
}
@@ -623,7 +629,10 @@ fn format_status_output(porcelain: &str) -> String {
output.push_str(&format!(" {}\n", f));
}
if untracked_files.len() > max_untracked {
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - max_untracked));
output.push_str(&format!(
" ... +{} more\n",
untracked_files.len() - max_untracked
));
}
}
@@ -838,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 {
@@ -1032,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| {
@@ -1048,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);
@@ -1308,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");
+3
View File
@@ -10,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,
}
@@ -20,6 +22,7 @@ struct Issue {
#[serde(rename = "FromLinter")]
from_linter: String,
#[serde(rename = "Text")]
#[allow(dead_code)]
text: String,
#[serde(rename = "Pos")]
pos: Position,
+1
View File
@@ -5,6 +5,7 @@ use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashMap;
#[allow(clippy::too_many_arguments)]
pub fn run(
pattern: &str,
path: &str,
+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
+2
View File
@@ -36,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"
+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,
+2 -2
View File
@@ -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
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 {
+6
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,6 +90,7 @@ 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 {
+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,
+2 -2
View File
@@ -5,8 +5,8 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, 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)
+5 -1
View File
@@ -7,7 +7,9 @@ use std::collections::HashMap;
#[derive(Debug, Deserialize)]
struct RuffLocation {
#[allow(dead_code)]
row: usize,
#[allow(dead_code)]
column: usize,
}
@@ -20,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>,
@@ -238,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();
+8 -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.
///
@@ -494,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
}
@@ -566,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)
@@ -857,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
}
@@ -977,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,
}
@@ -1181,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()))?;
+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();
+1
View File
@@ -218,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);