Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak bff0ccc9d6 feat: add Windsurf support via rtk init --agent windsurf (#695)
Install RTK rules in .windsurfrules (project-scoped) so Cascade
prefixes shell commands with rtk for token savings.

Windsurf hooks don't support command rewriting (only blocking),
so RTK uses the rules-based approach (like Codex with AGENTS.md).

Tested: Windsurf Cascade correctly uses rtk git status after install.
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-18 18:19:32 +01:00
Moisei RabinovichandMoisei c3917e4de2 feat: add Cursor Agent support via --agent flag (#595)
Add `rtk init -g --agent cursor` to install RTK hooks for Cursor Agent.
Cursor's preToolUse hook supports command rewriting via updated_input,
functionally identical to Claude Code's PreToolUse. Works with both the
Cursor editor and cursor-cli (they share ~/.cursor/hooks.json).

Changes:
- New `--agent <name>` flag (claude|cursor) on `rtk init`, extensible
  for future agents. Default is claude (backward compatible).
- Cursor hook script (hooks/cursor-rtk-rewrite.sh) outputs Cursor's
  JSON format: {permission, updated_input} vs Claude's hookSpecificOutput.
- `rtk init --show` reports Cursor hook and hooks.json status.
- `rtk init -g --uninstall` removes Cursor artifacts.
- `rtk discover` notes that Cursor sessions are tracked via `rtk gain`
  (Cursor transcripts lack structured tool_use/tool_result blocks).
- Unit tests for Cursor hooks.json patching, detection, and removal.

Made-with: Cursor

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Co-authored-by: Moisei <1199723+moisei@users.noreply.github.com>
2026-03-18 16:39:03 +01:00
Jeziel LopesandPatrick szymkowiak 0800bbecef feat(copilot): add Copilot hook support (VS Code + CLI) (#605)
Add `rtk hook copilot` command that handles both VS Code Copilot Chat
(updatedInput rewrite) and GitHub Copilot CLI (deny-with-suggestion).

- Auto-detects format: snake_case (VS Code) vs camelCase (Copilot CLI)
- Delegates to `rtk rewrite` (single source of truth)
- 14 hook tests (format detection, rewrite gating, output shape)
- .github/hooks/rtk-rewrite.json for repo-scoped hook config
- .github/copilot-instructions.md for RTK awareness
- Test script: hooks/test-copilot-rtk-rewrite.sh

Rebased on develop (includes Gemini #573, Codex #377, OpenClaw #358).

Original work by @jeziellopes, cleaned up and rebased by maintainer.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Co-authored-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-18 16:21:07 +01:00
Zacaria Chtatar 7d04b485a7 feat(init): add Codex CLI support via AGENTS.md + RTK.md workflow (#377)
* feat(init): add Codex CLI support via AGENTS.md + RTK.md workflow

Add --codex mode to rtk init for Codex CLI integration using AGENTS.md + RTK.md, while keeping the newer develop init/opencode flow intact. Includes Codex install/show/uninstall handling, ASCII status output, stricter flag validation, and expanded tests for Codex AGENTS lifecycle and patch-mode rejection.

Signed-off-by: Zacaria <havesomecode@gmail.com>

* docs: fix validation metadata

Signed-off-by: Zacaria <havesomecode@gmail.com>

---------

Signed-off-by: Zacaria <havesomecode@gmail.com>
2026-03-18 15:54:53 +01:00
Ben YounesandClaude Opus 4.6 f16853ae8a feat: add Gemini CLI support via rtk init --gemini (#573)
- Add `rtk hook gemini` command: native Rust hook processor for Gemini CLI
  BeforeTool hooks. Reads JSON from stdin, delegates to `rewrite_command()`
  (single source of truth), outputs Gemini-format JSON response.
- Add `--gemini` flag to `rtk init`: installs hook wrapper script, GEMINI.md,
  and patches ~/.gemini/settings.json with BeforeTool hook entry.
- Add `rtk init -g --gemini --uninstall`: clean removal of all Gemini artifacts.
- 6 unit tests covering hook format, rewrite delegation, and exclusions.

Replaces PR #174 which had too many conflicts after upstream restructuring.

Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 15:18:33 +01:00
AlexandPatrick szymkowiak 56160d8399 feat: OpenClaw plugin for transparent exec rewriting (#358)
* feat: add OpenClaw plugin for transparent exec rewriting

Adds an OpenClaw plugin that intercepts exec tool calls via the
before_tool_call hook and rewrites commands to their RTK equivalents.

This is the OpenClaw equivalent of hooks/rtk-rewrite.sh for Claude Code.

The plugin:
- Registers a before_tool_call hook on the exec tool
- Rewrites git, grep, find, ls, gh, docker, kubectl, and test commands
- Guards against rewriting piped/compound commands and heredocs
- Returns properly typed PluginHookBeforeToolCallResult
- Supports enabled/verbose config options

Measured savings: 48-87% token reduction on common commands.

Files:
- openclaw/index.ts — plugin source
- openclaw/openclaw.plugin.json — plugin manifest
- openclaw/README.md — installation and usage docs

* refactor: delegate OpenClaw plugin to rtk rewrite

Replace 60+ hardcoded regex rules with a single call to `rtk rewrite`,
matching the OpenCode plugin pattern (hooks/opencode-rtk.ts).

Benefits:
- Zero maintenance: new RTK filters work automatically
- Single source of truth: rewrite logic in Rust (src/discover/registry.rs)
- 122 → 73 lines, no rule duplication

Also: rebase on develop, fix homepage URL, bump version to 1.0.0.
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* feat: add package.json for npm publishing

Enables `openclaw plugins install @rtk-ai/rtk-rewrite` for OpenClaw users.

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

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Co-authored-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-18 15:00:30 +01:00
patrick szymkowiak 4d799b0e0a fix: remove all decorative emojis from CLI output (#687)
* fix: remove decorative emojis from CLI output (#511)

Replace decorative emojis with plain text to reduce token waste.
Keep functional symbols (⚠️ ✓ ❌ ✅ ℹ️) that convey meaning in fewer tokens.

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

* fix: remove remaining decorative emojis from find_cmd and formatter

Missed in initial emoji cleanup pass: 📁 in find_cmd.rs and parser/formatter.rs

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

* fix: remove all decorative emojis from CLI output (#511)

Replace emojis with plain text tokens across all production files
for better LLM compatibility. Test fixtures and external tool
detection patterns (e.g. Black's "All done!") are preserved.

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

* fix: remove last decorative emoji from next_cmd.rs

Remove ⚡ from Next.js Build header, missed in previous passes.

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

* fix: remove remaining emojis from gh_cmd.rs and init.rs

Replace production emojis:
- gh_cmd.rs: 🟣→[merged], ⚪→[unknown]/[pending], ⭐→removed, 🔱→removed
- init.rs: ⚪→[--] for "not found" status indicators

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

* fix: remove all checkmark emojis from CLI output

Replace ✓ (U+2713) with plain text across 19 files:
- "ok ✓" → "ok" (git add/commit/push/pull)
- "✓ cargo test: ..." → "cargo test: ..." (all tool summaries)
- Preserved ✓ in input detection patterns and test fixtures

LLMs cannot interpret emoji semantics; plain text is clearer.

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

---------

Signed-off-by: Patrick Szymkowiak <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
Signed-off-by: Patrick Szymkowiak <patrick@rtk-ai.app>
2026-03-18 10:41:44 +01:00
8fae5b067d Release v0.31.0 — develop → master (#666)
* 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>

* 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>

* 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>

* 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>

* 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>

* fix: discover absolute paths + git global options (#485, #163) (#518)

* fix: discover classifies absolute paths like /usr/bin/grep (#485)

Normalize absolute binary paths before classification:
/usr/bin/grep → grep, /bin/ls → ls, /usr/local/bin/git → git

Adds strip_absolute_path() helper + 5 tests.

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

* fix: discover and rewrite support git global options -C, --no-pager, etc. (#163)

Strip git global options (-C <path>, -c <key=val>, --git-dir, --work-tree,
--no-pager, --no-optional-locks, --bare, --literal-pathspecs) before
classification so git -C /tmp status is recognized as rtk git.

Rewrite preserves global options: git -C /tmp status → rtk git -C /tmp status

Adds GIT_GLOBAL_OPT lazy_static regex + strip_git_global_opts() helper + 6 tests.

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

---------

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

* fix: prevent double `--` separator in cargo clippy with -p flags (#519)

When running `rtk cargo clippy -p my-crate -- -D warnings`, Clap with
`trailing_var_arg = true` preserves the `--` in parsed args when flags
precede it. `restore_double_dash()` then added a second `--`, producing
`cargo clippy -p my-crate -- -- -D warnings`. This caused rustc to
interpret `-D` as a filename instead of a lint flag.

Fix: skip restoration when args already contain `--` (Clap preserved it).

Fixes #496

Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* ci: add PR template + target branch check (#521)

- PR template reminds contributors to target develop
- CI workflow labels PRs targeting master with 'wrong-base' and posts a comment
- Excludes develop→master PRs (maintainer releases)

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

* fix: prevent rtk read from corrupting JSON/YAML/data files (#522)

Add Language::Data variant for data formats (JSON, YAML, TOML, XML, CSV, etc.)
with empty comment patterns to prevent comment stripping. AggressiveFilter
falls back to MinimalFilter for data files.

Fixes #464

Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* fix: skip rewriting find/fd in pipes to preserve xargs compatibility (#439) (#563)

rtk find outputs a grouped format incompatible with pipe consumers
like xargs, grep, wc, sort. Skip rewrite when find/fd is followed
by a pipe, preserving native one-per-line output.

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

* fix: add hint when git diff is truncated + fix --no-compact passthrough (#427) (#564)

When compact_diff truncates output, append a hint line so Claude knows
how to get the full diff: [full diff: rtk git diff --no-compact]

Also fix --no-compact flag being passed to git (causing usage error)
and remove decorative emoji from compact_diff output.

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

* fix: propagate exit codes in git diff, status+args, commit, and branch (#632)

4 P1 bugs where git exit codes were swallowed:
- git diff: failure silently printed empty stat output
- git status (with args): failure was filtered instead of propagated
- git commit: failure printed "FAILED" but returned Ok(()) breaking pre-commit hooks
- git branch (list mode): failure was silently ignored

All now follow the established pattern: eprint stderr, track raw==raw, process::exit(code).

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

* feat: add 5 new TOML filters (ollama, nx, gradle, spring-boot, jira) (#635)

* feat: add 5 new TOML built-in filters (ollama, nx, gradle, spring-boot, jira)

New filters for commands not covered by Rust modules:
- ollama: strip ANSI spinners, keep final text response (#624)
- nx: strip Nx monorepo noise, keep build results (#444)
- gradle/gradlew: strip UP-TO-DATE tasks, keep build summary (#147)
- spring-boot: strip banner and verbose logs, keep startup/errors (#147)
- jira: strip blanks, truncate wide columns (#524)

All 5 filters pass inline tests via rtk verify (123/123).
Updated builtin filter count: 47 -> 52.

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

* feat: add 5 more TOML filters (turbo, mise, just, task, yadm)

New filters for task runners and git wrapper:
- turbo: strip cache/Tasks/Duration noise, keep task output (#531)
- mise: strip install/download progress, keep task results (#607)
- just: strip blanks and recipe headers, keep output (#607)
- task: strip task headers and up-to-date lines, keep results (#607)
- yadm: strip hint lines, compact git-like output (#567)

All verified with fake binaries through catch-all TOML engine.
137/137 TOML tests pass, 934 Rust tests pass.
Updated builtin filter count: 52 -> 57.

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

---------

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

* fix: replace emojis with plain text in git status output (#603) (#638)

Git status output used emojis (📌, 📝, ❓, ✅, ⚠️) that confuse
non-Claude LLMs (GPT, etc.) causing retry loops. Replace with plain
text labels (branch:, modified:, staged:, untracked:, conflicts:).

Also add "clean — nothing to commit" when working tree is clean,
so LLMs understand the repo state without ambiguity.

Before: 📌 master
After:  branch: master
        clean — nothing to commit

Fixes #603

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>
Signed-off-by: Florian Bruniaux <florian@bel-etage.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
Signed-off-by: Patrick Szymkowiak <patrick@rtk-ai.app>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
Signed-off-by: Patrick <patrick@rtk-ai.com>
Co-authored-by: Florian BRUNIAUX <florian@bruniaux.com>
Co-authored-by: Ben Younes <benyounes.ousama@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-18 09:19:11 +01:00
aesoft 4467296bd1 Merge pull request #629 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.30.0
2026-03-16 13:45:32 +01:00
github-actions[bot] 55d8dc9def chore(master): release 0.30.0 2026-03-16 12:24:55 +00:00
aesoft ffbc8863ff Merge pull request #581 from rtk-ai/develop
Next release
2026-03-16 13:24:08 +01:00
83 changed files with 4042 additions and 498 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".
+13
View File
@@ -0,0 +1,13 @@
## Summary
<!-- What does this PR do? Keep it short (1-3 bullet points). -->
-
## Test plan
<!-- How did you verify this works? -->
- [ ] `cargo fmt --all && cargo clippy --all-targets && cargo test`
- [ ] Manual testing: `rtk <command>` output inspected
> **Important:** All PRs must target the `develop` branch (not `master`).
> See [CONTRIBUTING.md](../blob/master/CONTRIBUTING.md) for details.
+127
View File
@@ -0,0 +1,127 @@
# Copilot Instructions for rtk
**rtk (Rust Token Killer)** is a CLI proxy that filters and compresses command outputs before they reach an LLM context, saving 60–90% of tokens. It wraps common tools (`git`, `cargo`, `grep`, `pnpm`, `go`, etc.) and outputs condensed summaries instead of raw output.
## Using rtk in this session
**Always prefix commands with `rtk` when running shell commands** — this is the entire point of the project and reduces token consumption for every operation you perform.
```bash
# Instead of: Use:
git status rtk git status
git log -10 rtk git log -10
cargo test rtk cargo test
cargo clippy --all-targets rtk cargo clippy --all-targets
grep -r "pattern" src/ rtk grep -r "pattern" src/
```
**rtk meta-commands** (always use these directly, no prefix needed):
```bash
rtk gain # Show token savings analytics for this session
rtk gain --history # Full command history with per-command savings
rtk discover # Scan session history for missed rtk opportunities
rtk proxy <cmd> # Run a command raw (no filtering) but still track it
```
**Verify rtk is installed before starting:**
```bash
rtk --version # Should print: rtk X.Y.Z
rtk gain # Should show a dashboard (not "command not found")
```
> ⚠️ **Name collision**: `rtk gain` failing means you have `reachingforthejack/rtk` (Rust Type Kit) installed instead of this project. Run `which rtk` and check the binary source.
## Build, Test & Lint
```bash
# Development build
cargo build
# Run all tests
cargo test
# Run a single test by name
cargo test test_filter_git_log
# Run all tests in a module
cargo test git::tests::
# Run tests with stdout
cargo test -- --nocapture
# Pre-commit gate (must all pass before any PR)
cargo fmt --all --check && cargo clippy --all-targets && cargo test
# Smoke tests (requires installed binary)
bash scripts/test-all.sh
```
PRs target the **`develop`** branch, not `main`. All commits require a DCO sign-off (`git commit -s`).
## Architecture
```
main.rs ← Clap Commands enum → specialized module (git.rs, *_cmd.rs, etc.)
↓
execute subprocess
↓
filter/compress output
↓
tracking::TimedExecution → SQLite (~/.local/share/rtk/tracking.db)
```
Key modules:
- **`main.rs`** — Clap `Commands` enum routes every subcommand to its module. Each arm calls `tracking::TimedExecution::start()` before running, then `.track(...)` after.
- **`filter.rs`** — Language-aware filtering with `FilterLevel` (`none` / `minimal` / `aggressive`) and `Language` enum. Used by `read` and `smart` commands.
- **`tracking.rs`** — SQLite persistence for token savings, scoped per project path. Powers `rtk gain`.
- **`tee.rs`** — On filter failure, saves raw output to `~/.local/share/rtk/tee/` and prints a one-line hint so the LLM can re-read without re-running the command.
- **`utils.rs`** — Shared helpers: `truncate`, `strip_ansi`, `execute_command`, package-manager auto-detection (pnpm/yarn/npm/npx).
New commands follow this structure: one file `src/<cmd>_cmd.rs` with a `pub fn run(...)` entry point, registered in the `Commands` enum in `main.rs`.
## Key Conventions
### Error handling
- Use `anyhow::Result` throughout (this is a binary, not a library).
- Always attach context: `operation.context("description")?` — never bare `?` without context.
- No `unwrap()` in production code; `expect("reason")` is acceptable only in tests.
- Every filter must fall back to raw command execution on error — never break the user's workflow.
### Regex
- Compile once with `lazy_static!`, never inside a function body:
```rust
lazy_static! {
static ref RE: Regex = Regex::new(r"pattern").unwrap();
}
```
### Testing
- Unit tests live **inside the module file** in `#[cfg(test)] mod tests { ... }` — not in `tests/`.
- Fixtures are real captured command output in `tests/fixtures/<cmd>_raw.txt`, loaded with `include_str!("../tests/fixtures/...")`.
- Each test module defines its own local `fn count_tokens(text: &str) -> usize` (word-split approximation) — there is no shared utility for this.
- Token savings assertions use `assert!(savings >= 60.0, ...)`.
- Snapshot tests use `assert_snapshot!()` from the `insta` crate; review with `cargo insta review`.
### Adding a new command
1. Create `src/<cmd>_cmd.rs` with `pub fn run(...)`.
2. Add `mod <cmd>_cmd;` at the top of `main.rs`.
3. Add a variant to the `Commands` enum with `#[arg(trailing_var_arg = true, allow_hyphen_values = true)]` for pass-through flags.
4. Route the variant in the `match` block, wrapping execution with `tracking::TimedExecution`.
5. Write a fixture from real output, then unit tests in the module file.
6. Update `README.md` (command list + savings %) and `CHANGELOG.md`.
### Exit codes
Preserve the underlying command's exit code. Use `std::process::exit(code)` when the child process exits non-zero.
### Performance constraints
- Startup must stay under 10ms — no async runtime (no `tokio`/`async-std`).
- No blocking I/O at startup; config is loaded on-demand.
- Binary size target: <5 MB stripped.
### Branch naming
```
fix(scope): short-description
feat(scope): short-description
chore(scope): short-description
```
`scope` is the affected component (e.g. `git`, `filter`, `tracking`).
+12
View File
@@ -0,0 +1,12 @@
{
"hooks": {
"PreToolUse": [
{
"type": "command",
"command": "rtk hook",
"cwd": ".",
"timeout": 5
}
]
}
}
+43
View File
@@ -0,0 +1,43 @@
name: PR Target Branch Check
on:
pull_request_target:
types: [opened, edited]
jobs:
check-target:
runs-on: ubuntu-latest
# Skip develop→master PRs (maintainer releases)
if: >-
github.event.pull_request.base.ref == 'master' &&
github.event.pull_request.head.ref != 'develop'
steps:
- name: Add wrong-base label
uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
// Add label
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
labels: ['wrong-base']
});
// Post comment
const body = `👋 Thanks for the PR! It looks like this targets \`master\`, but all PRs should target the **\`develop\`** branch.
Please update the base branch:
1. Click **Edit** at the top right of this PR
2. Change the base branch from \`master\` to \`develop\`
See [CONTRIBUTING.md](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/master/CONTRIBUTING.md) for details.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pr.number,
body: body
});
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.29.0"
".": "0.30.0"
}
+3 -3
View File
@@ -293,12 +293,12 @@ 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
- **Command Modules**: 34 (directly exposed to users)
- **Infrastructure Modules**: 20 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, etc.)
- **Command Modules**: 44 (directly exposed to users)
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, trust, etc.)
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
- **Python Tooling**: 3 modules (ruff, pytest, pip)
+34
View File
@@ -5,6 +5,40 @@ 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.30.0](https://github.com/rtk-ai/rtk/compare/v0.29.0...v0.30.0) (2026-03-16)
### Features
* add rtk session command for adoption overview ([be67d66](https://github.com/rtk-ai/rtk/commit/be67d660100c06a0751c08d943dc884ad5bff6a3))
* add rtk session command for adoption overview ([12d44c4](https://github.com/rtk-ai/rtk/commit/12d44c4068d7d4f65d5bd7551af29ab5a2352ed1)), closes [#487](https://github.com/rtk-ai/rtk/issues/487)
* add worktree slash commands for isolated development ([#364](https://github.com/rtk-ai/rtk/issues/364)) ([ab83e79](https://github.com/rtk-ai/rtk/commit/ab83e7933ebc26ca76f843d33285729875efb913))
* Claude Code tooling — 2 agents, 7 commands, 2 rules, 4 skills ([#491](https://github.com/rtk-ai/rtk/issues/491)) ([7b7a5ae](https://github.com/rtk-ai/rtk/commit/7b7a5ae4b6d23fbb882ed7d5e815e2ed0672c46c))
### Bug Fixes
* 6 critical bugs — exit codes, unwrap, lazy regex ([#626](https://github.com/rtk-ai/rtk/issues/626)) ([3005ebd](https://github.com/rtk-ai/rtk/commit/3005ebd0ad07912ae919687f6d3d49482aabaeac))
* align 7 TOML filter tests with on_empty behavior ([04ed6d8](https://github.com/rtk-ai/rtk/commit/04ed6d8c314dcbf86b147903b5a7f1cd956dc980))
* align 7 TOML filter tests with on_empty behavior ([9a499b9](https://github.com/rtk-ai/rtk/commit/9a499b9714e97a553d5603680ab1f843034acf28))
* **cicd-docs:** add agent reviewer + some contribute guidelines ([de710f4](https://github.com/rtk-ai/rtk/commit/de710f4ea30c333130c46f8a2e2c5b6b9edd4889))
* **cicd-docs:** some logs to understand what is happening when check docs ([191ea9a](https://github.com/rtk-ai/rtk/commit/191ea9af9f99ee78d74385fe1952ce83045e4afe))
* **cicd:** Clean cicd, rework depends and add pre-release ([d24a765](https://github.com/rtk-ai/rtk/commit/d24a7650e26aca89224a3ec5d263f1ce7c7121d6))
* **cicd:** Clean cicd, rework depends and add pre-release ([6303e95](https://github.com/rtk-ai/rtk/commit/6303e9530a379a8e3939e6c122ab4cf07cb16751))
* **cicd:** clippy - do not treat warn as error ([5da5db2](https://github.com/rtk-ai/rtk/commit/5da5db222d9927394995ccaeb3afc103e80c22bd))
* failing context for doc analyze -&gt; cat from files ([c6b7db2](https://github.com/rtk-ai/rtk/commit/c6b7db2e5a6cd9a05262e934b4fc7a44c699c3b0))
* git log --oneline regression drops commits ([#619](https://github.com/rtk-ai/rtk/issues/619)) ([8e85d67](https://github.com/rtk-ai/rtk/commit/8e85d676d78b12d2c421bb892f93971fc222fb39))
* improve adoption metric by detecting hook-rewritten commands ([eb8a2c4](https://github.com/rtk-ai/rtk/commit/eb8a2c4a71072870fca4b64e90189a4453acff84))
* normalize binlogs CRLF ([5344af9](https://github.com/rtk-ai/rtk/commit/5344af9a51f06b5dc42692e42c948ff11a3173c6))
* preserve commit body in git log output ([e189bbb](https://github.com/rtk-ai/rtk/commit/e189bbbe749120eda4d98a2130937269d8c0e92a))
* preserve first line of commit body in git log output ([c3416eb](https://github.com/rtk-ai/rtk/commit/c3416eb45f2f97297ec149d296a6a500697d302b))
* remove version check from validate-docs CI ([#476](https://github.com/rtk-ai/rtk/issues/476)) ([#543](https://github.com/rtk-ai/rtk/issues/543)) ([6e61c24](https://github.com/rtk-ai/rtk/commit/6e61c2447cc03af94220ce6ce83686f155e18086))
* split chained commands in adoption metric ([127f85c](https://github.com/rtk-ai/rtk/commit/127f85c02efd52a64e461005fa142d05f81615f8))
* support git -C &lt;path&gt; in rewrite registry ([c916bab](https://github.com/rtk-ai/rtk/commit/c916bab33ae9760b234fd720c944a849141f0d2e)), closes [#555](https://github.com/rtk-ai/rtk/issues/555)
* test-all.sh aborts when gt not installed ([#500](https://github.com/rtk-ai/rtk/issues/500)) ([#544](https://github.com/rtk-ai/rtk/issues/544)) ([26f5473](https://github.com/rtk-ai/rtk/commit/26f547371798ad32aed3569965303bc4857789ed))
* trust boundary followup — TOML key typo + missing meta commands ([#625](https://github.com/rtk-ai/rtk/issues/625)) ([8d8e188](https://github.com/rtk-ai/rtk/commit/8d8e188705e5784829693a83b2076d6118154764))
* windows path fix for git tests ([0a904e2](https://github.com/rtk-ai/rtk/commit/0a904e264d58f8f4b5f10e37ec3b11f717458fe0))
## [0.29.0](https://github.com/rtk-ai/rtk/compare/v0.28.2...v0.29.0) (2026-03-12)
Generated
+1 -1
View File
@@ -892,7 +892,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.29.0"
version = "0.30.0"
dependencies = [
"anyhow",
"chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.29.0"
version = "0.30.0"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
+22 -1
View File
@@ -102,7 +102,7 @@ rtk gain # Should show token savings stats
# 1. Install hook for Claude Code (recommended)
rtk init --global
# Follow instructions to register in ~/.claude/settings.json
# Claude Code only by default (use --opencode for OpenCode)
# Claude Code only by default (use --opencode for OpenCode, --gemini for Gemini CLI)
# 2. Restart Claude Code, then test
git status # Automatically rewritten to rtk git status
@@ -287,6 +287,27 @@ rtk init --show # Verify installation
After install, **restart Claude Code**.
## Gemini CLI Support (Global)
RTK supports Gemini CLI via a native Rust hook processor. The hook intercepts `run_shell_command` tool calls and rewrites them to `rtk` equivalents using the same rewrite engine as Claude Code.
**Install Gemini hook:**
```bash
rtk init -g --gemini
```
**What it creates:**
- `~/.gemini/hooks/rtk-hook-gemini.sh` (thin wrapper calling `rtk hook gemini`)
- `~/.gemini/GEMINI.md` (RTK awareness instructions)
- Patches `~/.gemini/settings.json` with BeforeTool hook
**Uninstall:**
```bash
rtk init -g --gemini --uninstall
```
**Restart Required**: Restart Gemini CLI, then test with `git status` in a session.
## OpenCode Plugin (Global)
OpenCode supports plugins that can intercept tool execution. RTK provides a global plugin that mirrors the Claude auto-rewrite behavior by rewriting Bash tool commands to `rtk ...` before they execute. This plugin is **not** installed by default.
+60
View File
@@ -0,0 +1,60 @@
# RTK — Copilot Integration (VS Code Copilot Chat + Copilot CLI)
**Usage**: Token-optimized CLI proxy (60-90% savings on dev operations)
## What's automatic
The `.github/copilot-instructions.md` file is loaded at session start by both Copilot CLI and VS Code Copilot Chat.
It instructs Copilot to prefix commands with `rtk` automatically.
The `.github/hooks/rtk-rewrite.json` hook adds a `PreToolUse` safety net via `rtk hook` —
a cross-platform Rust binary that intercepts raw bash tool calls and rewrites them.
No shell scripts, no `jq` dependency, works on Windows natively.
## Meta commands (always use directly)
```bash
rtk gain # Token savings dashboard for this session
rtk gain --history # Per-command history with savings %
rtk discover # Scan session history for missed rtk opportunities
rtk proxy <cmd> # Run raw (no filtering) but still track it
```
## Installation verification
```bash
rtk --version # Should print: rtk X.Y.Z
rtk gain # Should show a dashboard (not "command not found")
which rtk # Verify correct binary path
```
> ⚠️ **Name collision**: If `rtk gain` fails, you may have `reachingforthejack/rtk`
> (Rust Type Kit) installed instead. Check `which rtk` and reinstall from rtk-ai/rtk.
## How the hook works
`rtk hook` reads `PreToolUse` JSON from stdin, detects the agent format, and responds appropriately:
**VS Code Copilot Chat** (supports `updatedInput` — transparent rewrite, no denial):
1. Agent runs `git status` → `rtk hook` intercepts via `PreToolUse`
2. `rtk hook` detects VS Code format (`tool_name`/`tool_input` keys)
3. Returns `hookSpecificOutput.updatedInput.command = "rtk git status"`
4. Agent runs the rewritten command silently — no denial, no retry
**GitHub Copilot CLI** (deny-with-suggestion — CLI ignores `updatedInput` today, see [issue #2013](https://github.com/github/copilot-cli/issues/2013)):
1. Agent runs `git status` → `rtk hook` intercepts via `PreToolUse`
2. `rtk hook` detects Copilot CLI format (`toolName`/`toolArgs` keys)
3. Returns `permissionDecision: deny` with reason: `"Token savings: use 'rtk git status' instead"`
4. Copilot reads the reason and re-runs `rtk git status`
When Copilot CLI adds `updatedInput` support, only `rtk hook` needs updating — no config changes.
## Integration comparison
| Tool | Mechanism | Hook output | File |
|-----------------------|-----------------------------------------|--------------------------|------------------------------------|
| Claude Code | `PreToolUse` hook with `updatedInput` | Transparent rewrite | `hooks/rtk-rewrite.sh` |
| VS Code Copilot Chat | `PreToolUse` hook with `updatedInput` | Transparent rewrite | `.github/hooks/rtk-rewrite.json` |
| GitHub Copilot CLI | `PreToolUse` deny-with-suggestion | Denial + retry | `.github/hooks/rtk-rewrite.json` |
| OpenCode | Plugin `tool.execute.before` | Transparent rewrite | `hooks/opencode-rtk.ts` |
| (any) | Custom instructions | Prompt-level guidance | `.github/copilot-instructions.md` |
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# rtk-hook-version: 1
# RTK Cursor Agent hook — rewrites shell commands to use rtk for token savings.
# Works with both Cursor editor and cursor-cli (they share ~/.cursor/hooks.json).
# Cursor preToolUse hook format: receives JSON on stdin, returns JSON on stdout.
# Requires: rtk >= 0.23.0, jq
#
# This is a thin delegating hook: all rewrite logic lives in `rtk rewrite`,
# which is the single source of truth (src/discover/registry.rs).
# To add or change rewrite rules, edit the Rust registry — not this file.
if ! command -v jq &>/dev/null; then
echo "[rtk] WARNING: jq is not installed. Hook cannot rewrite commands. Install jq: https://jqlang.github.io/jq/download/" >&2
exit 0
fi
if ! command -v rtk &>/dev/null; then
echo "[rtk] WARNING: rtk is not installed or not in PATH. Hook cannot rewrite commands. Install: https://github.com/rtk-ai/rtk#installation" >&2
exit 0
fi
# Version guard: rtk rewrite was added in 0.23.0.
RTK_VERSION=$(rtk --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
if [ -n "$RTK_VERSION" ]; then
MAJOR=$(echo "$RTK_VERSION" | cut -d. -f1)
MINOR=$(echo "$RTK_VERSION" | cut -d. -f2)
if [ "$MAJOR" -eq 0 ] && [ "$MINOR" -lt 23 ]; then
echo "[rtk] WARNING: rtk $RTK_VERSION is too old (need >= 0.23.0). Upgrade: cargo install rtk" >&2
exit 0
fi
fi
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
if [ -z "$CMD" ]; then
echo '{}'
exit 0
fi
# Delegate all rewrite logic to the Rust binary.
# rtk rewrite exits 1 when there's no rewrite — hook passes through silently.
REWRITTEN=$(rtk rewrite "$CMD" 2>/dev/null) || { echo '{}'; exit 0; }
# No change — nothing to do.
if [ "$CMD" = "$REWRITTEN" ]; then
echo '{}'
exit 0
fi
jq -n --arg cmd "$REWRITTEN" '{
"permission": "allow",
"updated_input": { "command": $cmd }
}'
+32
View File
@@ -0,0 +1,32 @@
# RTK - Rust Token Killer (Codex CLI)
**Usage**: Token-optimized CLI proxy for shell commands.
## Rule
Always prefix shell commands with `rtk`.
Examples:
```bash
rtk git status
rtk cargo test
rtk npm run build
rtk pytest -q
```
## Meta Commands
```bash
rtk gain # Token savings analytics
rtk gain --history # Recent command savings history
rtk proxy <cmd> # Run raw command without filtering
```
## Verification
```bash
rtk --version
rtk gain
which rtk
```
+293
View File
@@ -0,0 +1,293 @@
#!/usr/bin/env bash
# Test suite for rtk hook (cross-platform preToolUse handler).
# Feeds mock preToolUse JSON through `rtk hook` and verifies allow/deny decisions.
#
# Usage: bash hooks/test-copilot-rtk-rewrite.sh
#
# Copilot CLI input format:
# {"toolName":"bash","toolArgs":"{\"command\":\"...\"}"}
# Output on intercept: {"permissionDecision":"deny","permissionDecisionReason":"..."}
#
# VS Code Copilot Chat input format:
# {"tool_name":"Bash","tool_input":{"command":"..."}}
# Output on intercept: {"hookSpecificOutput":{"permissionDecision":"allow","updatedInput":{...}}}
#
# Output on pass-through: empty (exit 0)
RTK="${RTK:-rtk}"
PASS=0
FAIL=0
TOTAL=0
# Colors
GREEN='\033[32m'
RED='\033[31m'
DIM='\033[2m'
RESET='\033[0m'
# Build a Copilot CLI preToolUse input JSON
copilot_bash_input() {
local cmd="$1"
local tool_args
tool_args=$(jq -cn --arg cmd "$cmd" '{"command":$cmd}')
jq -cn --arg ta "$tool_args" '{"toolName":"bash","toolArgs":$ta}'
}
# Build a VS Code Copilot Chat preToolUse input JSON
vscode_bash_input() {
local cmd="$1"
jq -cn --arg cmd "$cmd" '{"tool_name":"Bash","tool_input":{"command":$cmd}}'
}
# Build a non-bash tool input
tool_input() {
local tool_name="$1"
jq -cn --arg t "$tool_name" '{"toolName":$t,"toolArgs":"{}"}'
}
# Assert Copilot CLI: hook denies and reason contains the expected rtk command
test_deny() {
local description="$1"
local input_cmd="$2"
local expected_rtk="$3"
TOTAL=$((TOTAL + 1))
local output
output=$(copilot_bash_input "$input_cmd" | "$RTK" hook 2>/dev/null) || true
local decision reason
decision=$(echo "$output" | jq -r '.permissionDecision // empty' 2>/dev/null)
reason=$(echo "$output" | jq -r '.permissionDecisionReason // empty' 2>/dev/null)
if [ "$decision" = "deny" ] && echo "$reason" | grep -qF "$expected_rtk"; then
printf " ${GREEN}DENY${RESET} %s ${DIM}→ %s${RESET}\n" "$description" "$expected_rtk"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected decision: deny, reason containing: %s\n" "$expected_rtk"
printf " actual decision: %s\n" "$decision"
printf " actual reason: %s\n" "$reason"
FAIL=$((FAIL + 1))
fi
}
# Assert VS Code Copilot Chat: hook returns updatedInput (allow) with rewritten command
test_vscode_rewrite() {
local description="$1"
local input_cmd="$2"
local expected_rtk="$3"
TOTAL=$((TOTAL + 1))
local output
output=$(vscode_bash_input "$input_cmd" | "$RTK" hook 2>/dev/null) || true
local decision updated_cmd
decision=$(echo "$output" | jq -r '.hookSpecificOutput.permissionDecision // empty' 2>/dev/null)
updated_cmd=$(echo "$output" | jq -r '.hookSpecificOutput.updatedInput.command // empty' 2>/dev/null)
if [ "$decision" = "allow" ] && echo "$updated_cmd" | grep -qF "$expected_rtk"; then
printf " ${GREEN}REWRITE${RESET} %s ${DIM}→ %s${RESET}\n" "$description" "$updated_cmd"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected decision: allow, updatedInput containing: %s\n" "$expected_rtk"
printf " actual decision: %s\n" "$decision"
printf " actual updatedInput: %s\n" "$updated_cmd"
FAIL=$((FAIL + 1))
fi
}
# Assert the hook emits no output (pass-through)
test_allow() {
local description="$1"
local input="$2"
TOTAL=$((TOTAL + 1))
local output
output=$(echo "$input" | "$RTK" hook 2>/dev/null) || true
if [ -z "$output" ]; then
printf " ${GREEN}PASS${RESET} %s ${DIM}→ (allow)${RESET}\n" "$description"
PASS=$((PASS + 1))
else
local decision
decision=$(echo "$output" | jq -r '.permissionDecision // .hookSpecificOutput.permissionDecision // empty' 2>/dev/null)
printf " ${RED}FAIL${RESET} %s\n" "$description"
printf " expected: (no output)\n"
printf " actual: permissionDecision=%s\n" "$decision"
FAIL=$((FAIL + 1))
fi
}
echo "============================================"
echo " RTK Hook Test Suite (rtk hook)"
echo "============================================"
echo ""
# ---- SECTION 1: Copilot CLI — commands that should be denied ----
echo "--- Copilot CLI: intercepted (deny with rtk suggestion) ---"
test_deny "git status" \
"git status" \
"rtk git status"
test_deny "git log --oneline -10" \
"git log --oneline -10" \
"rtk git log"
test_deny "git diff HEAD" \
"git diff HEAD" \
"rtk git diff"
test_deny "cargo test" \
"cargo test" \
"rtk cargo test"
test_deny "cargo clippy --all-targets" \
"cargo clippy --all-targets" \
"rtk cargo clippy"
test_deny "cargo build" \
"cargo build" \
"rtk cargo build"
test_deny "grep -rn pattern src/" \
"grep -rn pattern src/" \
"rtk grep"
test_deny "gh pr list" \
"gh pr list" \
"rtk gh"
echo ""
# ---- SECTION 2: VS Code Copilot Chat — commands that should be rewritten via updatedInput ----
echo "--- VS Code Copilot Chat: intercepted (updatedInput rewrite) ---"
test_vscode_rewrite "git status" \
"git status" \
"rtk git status"
test_vscode_rewrite "cargo test" \
"cargo test" \
"rtk cargo test"
test_vscode_rewrite "gh pr list" \
"gh pr list" \
"rtk gh"
echo ""
# ---- SECTION 3: Pass-through cases ----
echo "--- Pass-through (allow silently) ---"
test_allow "Copilot CLI: already rtk: rtk git status" \
"$(copilot_bash_input "rtk git status")"
test_allow "Copilot CLI: already rtk: rtk cargo test" \
"$(copilot_bash_input "rtk cargo test")"
test_allow "Copilot CLI: heredoc" \
"$(copilot_bash_input "cat <<'EOF'
hello
EOF")"
test_allow "Copilot CLI: unknown command: htop" \
"$(copilot_bash_input "htop")"
test_allow "Copilot CLI: unknown command: echo" \
"$(copilot_bash_input "echo hello world")"
test_allow "Copilot CLI: non-bash tool: view" \
"$(tool_input "view")"
test_allow "Copilot CLI: non-bash tool: edit" \
"$(tool_input "edit")"
test_allow "VS Code: already rtk" \
"$(vscode_bash_input "rtk git status")"
test_allow "VS Code: non-bash tool: editFiles" \
"$(jq -cn '{"tool_name":"editFiles"}')"
echo ""
# ---- SECTION 4: Output format assertions ----
echo "--- Output format ---"
# Copilot CLI output format
TOTAL=$((TOTAL + 1))
raw_output=$(copilot_bash_input "git status" | "$RTK" hook 2>/dev/null)
if echo "$raw_output" | jq . >/dev/null 2>&1; then
printf " ${GREEN}PASS${RESET} Copilot CLI: output is valid JSON\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: output is not valid JSON: %s\n" "$raw_output"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
decision=$(echo "$raw_output" | jq -r '.permissionDecision')
if [ "$decision" = "deny" ]; then
printf " ${GREEN}PASS${RESET} Copilot CLI: permissionDecision == \"deny\"\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: expected \"deny\", got \"%s\"\n" "$decision"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
reason=$(echo "$raw_output" | jq -r '.permissionDecisionReason')
if echo "$reason" | grep -qE '`rtk [^`]+`'; then
printf " ${GREEN}PASS${RESET} Copilot CLI: reason contains backtick-quoted rtk command ${DIM}→ %s${RESET}\n" "$reason"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} Copilot CLI: reason missing backtick-quoted command: %s\n" "$reason"
FAIL=$((FAIL + 1))
fi
# VS Code output format
TOTAL=$((TOTAL + 1))
vscode_output=$(vscode_bash_input "git status" | "$RTK" hook 2>/dev/null)
if echo "$vscode_output" | jq . >/dev/null 2>&1; then
printf " ${GREEN}PASS${RESET} VS Code: output is valid JSON\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: output is not valid JSON: %s\n" "$vscode_output"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
vscode_decision=$(echo "$vscode_output" | jq -r '.hookSpecificOutput.permissionDecision')
if [ "$vscode_decision" = "allow" ]; then
printf " ${GREEN}PASS${RESET} VS Code: hookSpecificOutput.permissionDecision == \"allow\"\n"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: expected \"allow\", got \"%s\"\n" "$vscode_decision"
FAIL=$((FAIL + 1))
fi
TOTAL=$((TOTAL + 1))
vscode_updated=$(echo "$vscode_output" | jq -r '.hookSpecificOutput.updatedInput.command')
if echo "$vscode_updated" | grep -q "^rtk "; then
printf " ${GREEN}PASS${RESET} VS Code: updatedInput.command starts with rtk ${DIM}→ %s${RESET}\n" "$vscode_updated"
PASS=$((PASS + 1))
else
printf " ${RED}FAIL${RESET} VS Code: updatedInput.command should start with rtk: %s\n" "$vscode_updated"
FAIL=$((FAIL + 1))
fi
echo ""
# ---- SUMMARY ----
echo "============================================"
if [ $FAIL -eq 0 ]; then
printf " ${GREEN}ALL $TOTAL TESTS PASSED${RESET}\n"
else
printf " ${RED}$FAIL FAILED${RESET} / $TOTAL total ($PASS passed)\n"
fi
echo "============================================"
exit $FAIL
+32
View File
@@ -0,0 +1,32 @@
# RTK - Rust Token Killer (Windsurf)
**Usage**: Token-optimized CLI proxy for shell commands.
## Rule
Always prefix shell commands with `rtk` to minimize token consumption.
Examples:
```bash
rtk git status
rtk cargo test
rtk ls src/
rtk grep "pattern" src/
rtk find "*.rs" .
rtk docker ps
rtk gh pr list
```
## Meta Commands
```bash
rtk gain # Show token savings
rtk gain --history # Command history with savings
rtk discover # Find missed RTK opportunities
rtk proxy <cmd> # Run raw (no filtering, for debugging)
```
## Why
RTK filters and compresses command output before it reaches the LLM context, saving 60-90% tokens on common operations. Always use `rtk <cmd>` instead of raw commands.
+86
View File
@@ -0,0 +1,86 @@
# RTK Plugin for OpenClaw
Transparently rewrites shell commands executed via OpenClaw's `exec` tool to their RTK equivalents, achieving 60-90% LLM token savings.
This is the OpenClaw equivalent of the Claude Code hooks in `hooks/rtk-rewrite.sh`.
## How it works
The plugin registers a `before_tool_call` hook that intercepts `exec` tool calls. When the agent runs a command like `git status`, the plugin delegates to `rtk rewrite` which returns the optimized command (e.g. `rtk git status`). The compressed output enters the agent's context window, saving tokens.
All rewrite logic lives in RTK itself (`rtk rewrite`). This plugin is a thin delegate -- when new filters are added to RTK, the plugin picks them up automatically with zero changes.
## Installation
### Prerequisites
RTK must be installed and available in `$PATH`:
```bash
brew install rtk
# or
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
```
### Install the plugin
```bash
# Copy the plugin to OpenClaw's extensions directory
mkdir -p ~/.openclaw/extensions/rtk-rewrite
cp openclaw/index.ts openclaw/openclaw.plugin.json ~/.openclaw/extensions/rtk-rewrite/
# Restart the gateway
openclaw gateway restart
```
### Or install via OpenClaw CLI
```bash
openclaw plugins install ./openclaw
```
## Configuration
In `openclaw.json`:
```json5
{
plugins: {
entries: {
"rtk-rewrite": {
enabled: true,
config: {
enabled: true, // Toggle rewriting on/off
verbose: false // Log rewrites to console
}
}
}
}
}
```
## What gets rewritten
Everything that `rtk rewrite` supports (30+ commands). See the [full command list](https://github.com/rtk-ai/rtk#commands).
## What's NOT rewritten
Handled by `rtk rewrite` guards:
- Commands already using `rtk`
- Piped commands (`|`, `&&`, `;`)
- Heredocs (`<<`)
- Commands without an RTK filter
## Measured savings
| Command | Token savings |
|---------|--------------|
| `git log --stat` | 87% |
| `ls -la` | 78% |
| `git status` | 66% |
| `grep` (single file) | 52% |
| `find -name` | 48% |
## License
MIT -- same as RTK.
+74
View File
@@ -0,0 +1,74 @@
/**
* RTK Rewrite Plugin for OpenClaw
*
* Transparently rewrites exec tool commands to RTK equivalents
* before execution, achieving 60-90% LLM token savings.
*
* All rewrite logic lives in `rtk rewrite` (src/discover/registry.rs).
* This plugin is a thin delegate — to add or change rules, edit the
* Rust registry, not this file.
*/
import { execSync } from "node:child_process";
let rtkAvailable: boolean | null = null;
function checkRtk(): boolean {
if (rtkAvailable !== null) return rtkAvailable;
try {
execSync("which rtk", { stdio: "ignore" });
rtkAvailable = true;
} catch {
rtkAvailable = false;
}
return rtkAvailable;
}
function tryRewrite(command: string): string | null {
try {
const result = execSync(`rtk rewrite ${JSON.stringify(command)}`, {
encoding: "utf-8",
timeout: 2000,
}).trim();
return result && result !== command ? result : null;
} catch {
return null;
}
}
export default function register(api: any) {
const pluginConfig = api.config ?? {};
const enabled = pluginConfig.enabled !== false;
const verbose = pluginConfig.verbose === true;
if (!enabled) return;
if (!checkRtk()) {
console.warn("[rtk] rtk binary not found in PATH — plugin disabled");
return;
}
api.on(
"before_tool_call",
(event: { toolName: string; params: Record<string, unknown> }) => {
if (event.toolName !== "exec") return;
const command = event.params?.command;
if (typeof command !== "string") return;
const rewritten = tryRewrite(command);
if (!rewritten) return;
if (verbose) {
console.log(`[rtk] ${command} -> ${rewritten}`);
}
return { params: { ...event.params, command: rewritten } };
},
{ priority: 10 }
);
if (verbose) {
console.log("[rtk] OpenClaw plugin registered");
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"id": "rtk-rewrite",
"name": "RTK Token Optimizer",
"version": "1.0.0",
"description": "Transparently rewrites shell commands to their RTK equivalents for 60-90% LLM token savings",
"homepage": "https://github.com/rtk-ai/rtk",
"license": "MIT",
"configSchema": {
"type": "object",
"additionalProperties": false,
"properties": {
"enabled": {
"type": "boolean",
"default": true,
"description": "Enable automatic command rewriting to RTK equivalents"
},
"verbose": {
"type": "boolean",
"default": false,
"description": "Log rewrite decisions to console for debugging"
}
}
},
"uiHints": {
"enabled": { "label": "Enable RTK rewriting" },
"verbose": { "label": "Verbose logging" }
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@rtk-ai/rtk-rewrite",
"version": "1.0.0",
"description": "RTK plugin for OpenClaw — rewrites shell commands for 60-90% LLM token savings",
"main": "index.ts",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/rtk-ai/rtk",
"directory": "openclaw"
},
"homepage": "https://github.com/rtk-ai/rtk",
"keywords": [
"rtk",
"openclaw",
"openclaw-plugin",
"token-savings",
"llm",
"cli-proxy"
],
"files": [
"index.ts",
"openclaw.plugin.json",
"README.md"
],
"peerDependencies": {
"rtk": ">=0.28.0"
}
}
+68 -30
View File
@@ -40,6 +40,11 @@ fn restore_double_dash_with_raw(args: &[String], raw_args: &[String]) -> Vec<Str
return args.to_vec();
}
// If args already contain `--` (Clap preserved it), no restoration needed
if args.iter().any(|a| a == "--") {
return args.to_vec();
}
// Find `--` in the original command line
let sep_pos = match raw_args.iter().position(|a| a == "--") {
Some(pos) => pos,
@@ -259,7 +264,7 @@ fn filter_cargo_install(output: &str) -> String {
// Already installed / up to date
if already_installed {
let info = ignored_line.split('`').nth(1).unwrap_or(&ignored_line);
return format!("✓ cargo install: {} already installed", info);
return format!("cargo install: {} already installed", info);
}
// Errors
@@ -308,10 +313,7 @@ fn filter_cargo_install(output: &str) -> String {
// Success
let crate_info = format_crate_info(&installed_crate, &installed_version, "package");
let mut result = format!(
"✓ cargo install ({}, {} deps compiled)",
crate_info, compiled
);
let mut result = format!("cargo install ({}, {} deps compiled)", crate_info, compiled);
for line in &replaced_lines {
result.push_str(&format!("\n {}", line));
@@ -497,7 +499,7 @@ fn filter_cargo_nextest(output: &str) -> String {
} else {
format!("{}, {}s", binary_text, duration)
};
return format!("✓ cargo nextest: {} ({})", parts.join(", "), meta);
return format!("cargo nextest: {} ({})", parts.join(", "), meta);
}
// With failures - show failure details then summary
@@ -620,7 +622,7 @@ fn filter_cargo_build(output: &str) -> String {
}
if error_count == 0 && warnings == 0 {
return format!("✓ cargo build ({} crates compiled)", compiled);
return format!("cargo build ({} crates compiled)", compiled);
}
let mut result = String::new();
@@ -734,11 +736,11 @@ impl AggregatedTestResult {
if self.has_duration {
format!(
"✓ cargo test: {} ({}, {:.2}s)",
"cargo test: {} ({}, {:.2}s)",
counts, suite_text, self.duration_secs
)
} else {
format!("✓ cargo test: {} ({})", counts, suite_text)
format!("cargo test: {} ({})", counts, suite_text)
}
}
}
@@ -826,7 +828,7 @@ fn filter_cargo_test(output: &str) -> String {
// Fallback: use original behavior if regex failed
for line in &summary_lines {
result.push_str(&format!("✓ {}\n", line));
result.push_str(&format!("{}\n", line));
}
return result.trim().to_string();
}
@@ -926,7 +928,7 @@ fn filter_cargo_clippy(output: &str) -> String {
}
if error_count == 0 && warning_count == 0 {
return "✓ cargo clippy: No issues found".to_string();
return "cargo clippy: No issues found".to_string();
}
let mut result = String::new();
@@ -1054,6 +1056,42 @@ mod tests {
assert_eq!(result, vec!["--", "-D", "warnings"]);
}
#[test]
fn test_restore_double_dash_clippy_with_package_flags() {
// rtk cargo clippy -p my-service -p my-crate -- -D warnings
// Clap with trailing_var_arg preserves "--" when args precede it
// → clap gives ["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
let args: Vec<String> = vec![
"-p".into(),
"my-service".into(),
"-p".into(),
"my-crate".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let raw = vec![
"rtk".into(),
"cargo".into(),
"clippy".into(),
"-p".into(),
"my-service".into(),
"-p".into(),
"my-crate".into(),
"--".into(),
"-D".into(),
"warnings".into(),
];
let result = restore_double_dash_with_raw(&args, &raw);
// Should NOT double the "--"
assert_eq!(
result,
vec!["-p", "my-service", "-p", "my-crate", "--", "-D", "warnings"]
);
// Verify only one "--" exists
assert_eq!(result.iter().filter(|a| *a == "--").count(), 1);
}
#[test]
fn test_filter_cargo_build_success() {
let output = r#" Compiling libc v0.2.153
@@ -1062,7 +1100,7 @@ mod tests {
Finished dev [unoptimized + debuginfo] target(s) in 15.23s
"#;
let result = filter_cargo_build(output);
assert!(result.contains("✓ cargo build"));
assert!(result.contains("cargo build"));
assert!(result.contains("3 crates compiled"));
}
@@ -1098,7 +1136,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
"Expected compact format, got: {}",
result
);
@@ -1155,7 +1193,7 @@ test result: ok. 32 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("✓ cargo test: 137 passed (4 suites, 1.45s)"),
result.contains("cargo test: 137 passed (4 suites, 1.45s)"),
"Expected aggregated format, got: {}",
result
);
@@ -1219,7 +1257,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("✓ cargo test: 0 passed (3 suites, 0.00s)"),
result.contains("cargo test: 0 passed (3 suites, 0.00s)"),
"Expected compact format for zero tests, got: {}",
result
);
@@ -1239,7 +1277,7 @@ test result: ok. 18 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("✓ cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
result.contains("cargo test: 63 passed, 5 ignored, 2 filtered out (2 suites, 0.70s)"),
"Expected compact format with ignored and filtered, got: {}",
result
);
@@ -1254,7 +1292,7 @@ test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
"#;
let result = filter_cargo_test(output);
assert!(
result.contains("✓ cargo test: 15 passed (1 suite, 0.01s)"),
result.contains("cargo test: 15 passed (1 suite, 0.01s)"),
"Expected singular 'suite', got: {}",
result
);
@@ -1268,9 +1306,9 @@ running 15 tests
test result: MALFORMED LINE WITHOUT PROPER FORMAT
"#;
let result = filter_cargo_test(output);
// Should fallback to original behavior (show line with checkmark)
// Should fallback to original behavior (show line without checkmark)
assert!(
result.contains("✓ test result: MALFORMED"),
result.contains("test result: MALFORMED"),
"Expected fallback format, got: {}",
result
);
@@ -1282,7 +1320,7 @@ test result: MALFORMED LINE WITHOUT PROPER FORMAT
Finished dev [unoptimized + debuginfo] target(s) in 1.53s
"#;
let result = filter_cargo_clippy(output);
assert!(result.contains("✓ cargo clippy: No issues found"));
assert!(result.contains("cargo clippy: No issues found"));
}
#[test]
@@ -1325,7 +1363,7 @@ warning: `rtk` (bin) generated 2 warnings
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
"#;
let result = filter_cargo_install(output);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("rtk v0.11.0"), "got: {}", result);
assert!(result.contains("5 deps compiled"), "got: {}", result);
assert!(result.contains("Replaced"), "got: {}", result);
@@ -1342,7 +1380,7 @@ warning: `rtk` (bin) generated 2 warnings
Replaced package `rtk v0.9.4` with `rtk v0.11.0` (/Users/user/.cargo/bin/rtk)
"#;
let result = filter_cargo_install(output);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("Replacing"), "got: {}", result);
assert!(result.contains("Replaced"), "got: {}", result);
}
@@ -1387,7 +1425,7 @@ error: aborting due to 1 previous error
#[test]
fn test_filter_cargo_install_empty_output() {
let result = filter_cargo_install("");
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("0 deps compiled"), "got: {}", result);
}
@@ -1401,7 +1439,7 @@ error: aborting due to 1 previous error
warning: be sure to add `/Users/user/.cargo/bin` to your PATH
"#;
let result = filter_cargo_install(output);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(
result.contains("be sure to add"),
"PATH warning should be kept: {}",
@@ -1451,7 +1489,7 @@ error: aborting due to 2 previous errors
Installing rtk v0.11.0
"#;
let result = filter_cargo_install(output);
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(!result.contains("Locking"), "got: {}", result);
assert!(!result.contains("Blocking"), "got: {}", result);
assert!(!result.contains("Downloading"), "got: {}", result);
@@ -1465,7 +1503,7 @@ error: aborting due to 2 previous errors
"#;
let result = filter_cargo_install(output);
// Path-based install: crate info not extracted from path
assert!(result.contains("✓ cargo install"), "got: {}", result);
assert!(result.contains("cargo install"), "got: {}", result);
assert!(result.contains("1 deps compiled"), "got: {}", result);
}
@@ -1491,7 +1529,7 @@ error: aborting due to 2 previous errors
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "✓ cargo nextest: 301 passed (1 binary, 0.192s)",
result, "cargo nextest: 301 passed (1 binary, 0.192s)",
"got: {}",
result
);
@@ -1576,7 +1614,7 @@ error: test run failed
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "✓ cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
result, "cargo nextest: 50 passed, 3 skipped (2 binaries, 0.500s)",
"got: {}",
result
);
@@ -1627,7 +1665,7 @@ error: test run failed
"#;
let result = filter_cargo_nextest(output);
assert_eq!(
result, "✓ cargo nextest: 100 passed (5 binaries, 1.234s)",
result, "cargo nextest: 100 passed (5 binaries, 1.234s)",
"got: {}",
result
);
@@ -1662,7 +1700,7 @@ error: test run failed
result
);
assert!(
result.contains("✓ cargo nextest: 10 passed"),
result.contains("cargo nextest: 10 passed"),
"got: {}",
result
);
+6 -5
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)
@@ -249,7 +250,7 @@ fn merge_weekly(cc: Option<Vec<CcusagePeriod>>, rtk: Vec<WeekStats>) -> Vec<Peri
let monday_key = match convert_saturday_to_monday(&entry.week_start) {
Some(m) => m,
None => {
eprintln!("⚠️ Invalid week_start format: {}", entry.week_start);
eprintln!("[warn] Invalid week_start format: {}", entry.week_start);
continue;
}
};
@@ -441,7 +442,7 @@ fn display_summary(tracker: &Tracker, verbose: u8) -> Result<()> {
let totals = compute_totals(&periods);
println!("💰 Claude Code Economics");
println!("[cost] Claude Code Economics");
println!("════════════════════════════════════════════════════");
println!();
@@ -549,7 +550,7 @@ fn display_daily(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load daily token savings from database")?;
let periods = merge_daily(cc_daily, rtk_daily);
println!("📅 Daily Economics");
println!("Daily Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
@@ -563,7 +564,7 @@ fn display_weekly(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load weekly token savings from database")?;
let periods = merge_weekly(cc_weekly, rtk_weekly);
println!("📅 Weekly Economics");
println!("Weekly Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
@@ -577,7 +578,7 @@ fn display_monthly(tracker: &Tracker, verbose: u8) -> Result<()> {
.context("Failed to load monthly token savings from database")?;
let periods = merge_monthly(cc_monthly, rtk_monthly);
println!("📅 Monthly Economics");
println!("Monthly Economics");
println!("════════════════════════════════════════════════════");
print_period_table(&periods, verbose);
Ok(())
+4 -3
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()
}
@@ -125,7 +126,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
let mut cmd = match build_command() {
Some(cmd) => cmd,
None => {
eprintln!("⚠️ ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
eprintln!("[warn] ccusage not found. Install: npm i -g ccusage (or use npx ccusage)");
return Ok(None);
}
};
@@ -145,7 +146,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
let output = match output {
Err(e) => {
eprintln!("⚠️ ccusage execution failed: {}", e);
eprintln!("[warn] ccusage execution failed: {}", e);
return Ok(None);
}
Ok(o) => o,
@@ -154,7 +155,7 @@ pub fn fetch(granularity: Granularity) -> Result<Option<Vec<CcusagePeriod>>> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!(
"⚠️ ccusage exited with {}: {}",
"[warn] ccusage exited with {}: {}",
output.status,
stderr.trim()
);
+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)
+85 -30
View File
@@ -53,21 +53,26 @@ fn docker_ps(_verbose: u8) -> Result<()> {
let mut rtk = String::new();
if stdout.trim().is_empty() {
rtk.push_str("🐳 0 containers");
rtk.push_str("[docker] 0 containers");
println!("{}", rtk);
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
return Ok(());
}
let count = stdout.lines().count();
rtk.push_str(&format!("🐳 {} containers:\n", count));
rtk.push_str(&format!("[docker] {} containers:\n", count));
for line in stdout.lines().take(15) {
let parts: Vec<&str> = line.split('\t').collect();
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));
@@ -114,7 +119,7 @@ fn docker_images(_verbose: u8) -> Result<()> {
let mut rtk = String::new();
if lines.is_empty() {
rtk.push_str("🐳 0 images");
rtk.push_str("[docker] 0 images");
println!("{}", rtk);
timer.track("docker images", "rtk docker images", &raw, &rtk);
return Ok(());
@@ -141,7 +146,11 @@ fn docker_images(_verbose: u8) -> Result<()> {
} else {
format!("{:.0}MB", total_size_mb)
};
rtk.push_str(&format!("🐳 {} images ({})\n", lines.len(), total_display));
rtk.push_str(&format!(
"[docker] {} images ({})\n",
lines.len(),
total_display
));
for line in lines.iter().take(15) {
let parts: Vec<&str> = line.split('\t').collect();
@@ -183,8 +192,21 @@ 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);
let rtk = format!("[docker] Logs for {}:\n{}", container, analyzed);
println!("{}", rtk);
timer.track(
&format!("docker logs {}", container),
@@ -208,10 +230,19 @@ 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(_) => {
rtk.push_str("☸️ No pods found");
rtk.push_str("No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
@@ -219,7 +250,7 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
};
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No pods found");
rtk.push_str("No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
@@ -265,21 +296,21 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
let mut parts = Vec::new();
if running > 0 {
parts.push(format!("{} ✓", running));
parts.push(format!("{}", running));
}
if pending > 0 {
parts.push(format!("{} pending", pending));
}
if failed > 0 {
parts.push(format!("{} ✗", failed));
parts.push(format!("{} [x]", failed));
}
if restarts_total > 0 {
parts.push(format!("{} restarts", restarts_total));
}
rtk.push_str(&format!("☸️ {} pods: {}\n", pods.len(), parts.join(", ")));
rtk.push_str(&format!("{} pods: {}\n", pods.len(), parts.join(", ")));
if !issues.is_empty() {
rtk.push_str("⚠️ Issues:\n");
rtk.push_str("[warn] Issues:\n");
for issue in issues.iter().take(10) {
rtk.push_str(&format!(" {}\n", issue));
}
@@ -306,10 +337,19 @@ 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(_) => {
rtk.push_str("☸️ No services found");
rtk.push_str("No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
@@ -317,12 +357,12 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
};
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No services found");
rtk.push_str("No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
};
rtk.push_str(&format!("☸️ {} services:\n", services.len()));
rtk.push_str(&format!("{} services:\n", services.len()));
for svc in services.iter().take(15) {
let ns = svc["metadata"]["namespace"].as_str().unwrap_or("-");
@@ -381,8 +421,23 @@ 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);
let rtk = format!("Logs for {}:\n{}", pod, analyzed);
println!("{}", rtk);
timer.track(
&format!("kubectl logs {}", pod),
@@ -400,10 +455,10 @@ pub fn format_compose_ps(raw: &str) -> String {
let lines: Vec<&str> = raw.lines().filter(|l| !l.trim().is_empty()).collect();
if lines.is_empty() {
return "🐳 0 compose services".to_string();
return "[compose] 0 services".to_string();
}
let mut result = format!("🐳 {} compose services:\n", lines.len());
let mut result = format!("[compose] {} services:\n", lines.len());
for line in lines.iter().take(20) {
let parts: Vec<&str> = line.split('\t').collect();
@@ -442,19 +497,19 @@ pub fn format_compose_ps(raw: &str) -> String {
/// Format `docker compose logs` output into compact form
pub fn format_compose_logs(raw: &str) -> String {
if raw.trim().is_empty() {
return "🐳 No logs".to_string();
return "[compose] No logs".to_string();
}
// docker compose logs prefixes each line with "service-N | "
// Use the existing log deduplication engine
let analyzed = crate::log_cmd::run_stdin_str(raw);
format!("🐳 Compose logs:\n{}", analyzed)
format!("[compose] Logs:\n{}", analyzed)
}
/// Format `docker compose build` output into compact summary
pub fn format_compose_build(raw: &str) -> String {
if raw.trim().is_empty() {
return "🐳 Build: no output".to_string();
return "[compose] Build: no output".to_string();
}
let mut result = String::new();
@@ -462,7 +517,7 @@ pub fn format_compose_build(raw: &str) -> String {
// Extract the summary line: "[+] Building 12.3s (8/8) FINISHED"
for line in raw.lines() {
if line.contains("Building") && line.contains("FINISHED") {
result.push_str(&format!("🐳 {}\n", line.trim()));
result.push_str(&format!("[compose] {}\n", line.trim()));
break;
}
}
@@ -470,9 +525,9 @@ pub fn format_compose_build(raw: &str) -> String {
if result.is_empty() {
// No FINISHED line found — might still be building or errored
if let Some(line) = raw.lines().find(|l| l.contains("Building")) {
result.push_str(&format!("🐳 {}\n", line.trim()));
result.push_str(&format!("[compose] {}\n", line.trim()));
} else {
result.push_str("🐳 Build:\n");
result.push_str("[compose] Build:\n");
}
}
@@ -516,7 +571,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 {
@@ -771,8 +826,11 @@ mod tests {
let raw = "redis-1\tredis:7\tUp 5 hours\t";
let out = format_compose_ps(raw);
assert!(out.contains("redis"), "should show service name");
// Should not show port info when no ports (but [compose] prefix is OK)
let lines: Vec<&str> = out.lines().collect();
let redis_line = lines.iter().find(|l| l.contains("redis")).unwrap();
assert!(
!out.contains("["),
!redis_line.contains("] ["),
"should not show port brackets when empty"
);
}
@@ -801,10 +859,7 @@ web-1 | 192.168.1.1 - GET /favicon.ico 404
api-1 | Server listening on port 3000
api-1 | Connected to database";
let out = format_compose_logs(raw);
assert!(
out.contains("Compose logs"),
"should have compose logs header"
);
assert!(out.contains("Logs"), "should have compose logs header");
}
#[test]
+5 -5
View File
@@ -26,7 +26,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
if cargo_path.exists() {
found = true;
raw.push_str(&fs::read_to_string(&cargo_path).unwrap_or_default());
rtk.push_str("📦 Rust (Cargo.toml):\n");
rtk.push_str("Rust (Cargo.toml):\n");
rtk.push_str(&summarize_cargo_str(&cargo_path)?);
}
@@ -34,7 +34,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
if package_path.exists() {
found = true;
raw.push_str(&fs::read_to_string(&package_path).unwrap_or_default());
rtk.push_str("📦 Node.js (package.json):\n");
rtk.push_str("Node.js (package.json):\n");
rtk.push_str(&summarize_package_json_str(&package_path)?);
}
@@ -42,7 +42,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
if requirements_path.exists() {
found = true;
raw.push_str(&fs::read_to_string(&requirements_path).unwrap_or_default());
rtk.push_str("📦 Python (requirements.txt):\n");
rtk.push_str("Python (requirements.txt):\n");
rtk.push_str(&summarize_requirements_str(&requirements_path)?);
}
@@ -50,7 +50,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
if pyproject_path.exists() {
found = true;
raw.push_str(&fs::read_to_string(&pyproject_path).unwrap_or_default());
rtk.push_str("📦 Python (pyproject.toml):\n");
rtk.push_str("Python (pyproject.toml):\n");
rtk.push_str(&summarize_pyproject_str(&pyproject_path)?);
}
@@ -58,7 +58,7 @@ pub fn run(path: &Path, verbose: u8) -> Result<()> {
if gomod_path.exists() {
found = true;
raw.push_str(&fs::read_to_string(&gomod_path).unwrap_or_default());
rtk.push_str("📦 Go (go.mod):\n");
rtk.push_str("Go (go.mod):\n");
rtk.push_str(&summarize_gomod_str(&gomod_path)?);
}
+4 -4
View File
@@ -22,7 +22,7 @@ pub fn run(file1: &Path, file2: &Path, verbose: u8) -> Result<()> {
let mut rtk = String::new();
if diff.added == 0 && diff.removed == 0 {
rtk.push_str("✅ Files are identical");
rtk.push_str("[ok] Files are identical");
println!("{}", rtk);
timer.track(
&format!("diff {} {}", file1.display(), file2.display()),
@@ -33,7 +33,7 @@ pub fn run(file1: &Path, file2: &Path, verbose: u8) -> Result<()> {
return Ok(());
}
rtk.push_str(&format!("📊 {} → {}\n", file1.display(), file2.display()));
rtk.push_str(&format!("{} → {}\n", file1.display(), file2.display()));
rtk.push_str(&format!(
" +{} added, -{} removed, ~{} modified\n\n",
diff.added, diff.removed, diff.modified
@@ -168,7 +168,7 @@ fn condense_unified_diff(diff: &str) -> String {
// File header
if line.starts_with("+++ ") {
if !current_file.is_empty() && (added > 0 || removed > 0) {
result.push(format!("📄 {} (+{} -{})", current_file, added, removed));
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
for c in changes.iter().take(10) {
result.push(format!(" {}", c));
}
@@ -199,7 +199,7 @@ fn condense_unified_diff(diff: &str) -> String {
// Last file
if !current_file.is_empty() && (added > 0 || removed > 0) {
result.push(format!("📄 {} (+{} -{})", current_file, added, removed));
result.push(format!("[file] {} (+{} -{})", current_file, added, removed));
for c in changes.iter().take(10) {
result.push(format!(" {}", c));
}
+9 -4
View File
@@ -18,10 +18,15 @@ 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,
}
/// Trait for session providers (Claude Code, future: Cursor, Windsurf).
/// Trait for session providers (Claude Code, OpenCode, etc.).
///
/// Note: Cursor Agent transcripts use a text-only format without structured
/// tool_use/tool_result blocks, so command extraction is not possible.
/// Use `rtk gain` to track savings for Cursor sessions instead.
pub trait SessionProvider {
fn discover_sessions(
&self,
@@ -347,7 +352,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 +370,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]
+213 -7
View File
@@ -48,6 +48,10 @@ lazy_static! {
.collect();
static ref ENV_PREFIX: Regex =
Regex::new(r"^(?:sudo\s+|env\s+|[A-Z_][A-Z0-9_]*=[^\s]*\s+)+").unwrap();
// Git global options that appear before the subcommand: -C <path>, -c <key=val>,
// --git-dir <dir>, --work-tree <dir>, and flag-only options (#163)
static ref GIT_GLOBAL_OPT: Regex =
Regex::new(r"^(?:(?:-C\s+\S+|-c\s+\S+|--git-dir(?:=\S+|\s+\S+)|--work-tree(?:=\S+|\s+\S+)|--no-pager|--no-optional-locks|--bare|--literal-pathspecs)\s+)+").unwrap();
}
/// Classify a single (already-split) command.
@@ -76,6 +80,12 @@ pub fn classify_command(cmd: &str) -> Classification {
return Classification::Ignored;
}
// Normalize absolute binary paths: /usr/bin/grep → grep (#485)
let cmd_normalized = strip_absolute_path(cmd_clean);
// Strip git global options: git -C /tmp status → git status (#163)
let cmd_normalized = strip_git_global_opts(&cmd_normalized);
let cmd_clean = cmd_normalized.as_str();
// Exclude cat/head/tail with redirect operators — these are writes, not reads (#315)
if cmd_clean.starts_with("cat ")
|| cmd_clean.starts_with("head ")
@@ -262,6 +272,42 @@ pub fn split_command_chain(cmd: &str) -> Vec<&str> {
results
}
/// Strip git global options before the subcommand (#163).
/// `git -C /tmp status` → `git status`, preserving the rest.
/// Returns the original string unchanged if not a git command.
fn strip_git_global_opts(cmd: &str) -> String {
// Only applies to commands starting with "git "
if !cmd.starts_with("git ") {
return cmd.to_string();
}
let after_git = &cmd[4..]; // skip "git "
let stripped = GIT_GLOBAL_OPT.replace(after_git, "");
format!("git {}", stripped.trim())
}
/// Normalize absolute binary paths: `/usr/bin/grep -rn foo` → `grep -rn foo` (#485)
/// Only strips if the first word contains a `/` (Unix path).
fn strip_absolute_path(cmd: &str) -> String {
let first_space = cmd.find(' ');
let first_word = match first_space {
Some(pos) => &cmd[..pos],
None => cmd,
};
if first_word.contains('/') {
// Extract basename
let basename = first_word.rsplit('/').next().unwrap_or(first_word);
if basename.is_empty() {
return cmd.to_string();
}
match first_space {
Some(pos) => format!("{}{}", basename, &cmd[pos..]),
None => basename.to_string(),
}
} else {
cmd.to_string()
}
}
/// Check if a command has RTK_DISABLED= prefix in its env prefix portion.
pub fn has_rtk_disabled_prefix(cmd: &str) -> bool {
let trimmed = cmd.trim();
@@ -355,8 +401,18 @@ fn rewrite_compound(cmd: &str, excluded: &[String]) -> Option<String> {
} else {
// `|` pipe — rewrite first segment only, pass through the rest unchanged
let seg = cmd[seg_start..i].trim();
let rewritten =
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string());
// Skip rewriting `find`/`fd` in pipes — rtk find outputs a grouped
// format that is incompatible with pipe consumers like xargs, grep,
// wc, sort, etc. which expect one path per line (#439).
let is_pipe_incompatible = seg.starts_with("find ")
|| seg == "find"
|| seg.starts_with("fd ")
|| seg == "fd";
let rewritten = if is_pipe_incompatible {
seg.to_string()
} else {
rewrite_segment(seg, excluded).unwrap_or_else(|| seg.to_string())
};
if rewritten != seg {
any_changed = true;
}
@@ -679,12 +735,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
}
}
@@ -1113,6 +1167,30 @@ mod tests {
);
}
#[test]
fn test_rewrite_find_pipe_skipped() {
// find in a pipe should NOT be rewritten — rtk find output format
// is incompatible with pipe consumers like xargs (#439)
assert_eq!(
rewrite_command("find . -name '*.rs' | xargs grep 'fn run'", &[]),
None
);
}
#[test]
fn test_rewrite_find_pipe_xargs_wc() {
assert_eq!(rewrite_command("find src -type f | wc -l", &[]), None);
}
#[test]
fn test_rewrite_find_no_pipe_still_rewritten() {
// find WITHOUT a pipe should still be rewritten
assert_eq!(
rewrite_command("find . -name '*.rs'", &[]),
Some("rtk find . -name '*.rs'".into())
);
}
#[test]
fn test_rewrite_heredoc_returns_none() {
assert_eq!(rewrite_command("cat <<'EOF'\nfoo\nEOF", &[]), None);
@@ -2061,4 +2139,132 @@ mod tests {
);
assert_eq!(strip_disabled_prefix("git status"), "git status");
}
// --- #485: absolute path normalization ---
#[test]
fn test_classify_absolute_path_grep() {
assert_eq!(
classify_command("/usr/bin/grep -rni pattern"),
Classification::Supported {
rtk_equivalent: "rtk grep",
category: "Files",
estimated_savings_pct: 75.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_classify_absolute_path_ls() {
assert_eq!(
classify_command("/bin/ls -la"),
Classification::Supported {
rtk_equivalent: "rtk ls",
category: "Files",
estimated_savings_pct: 65.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_classify_absolute_path_git() {
assert_eq!(
classify_command("/usr/local/bin/git status"),
Classification::Supported {
rtk_equivalent: "rtk git",
category: "Git",
estimated_savings_pct: 70.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_classify_absolute_path_no_args() {
// /usr/bin/find alone → still classified
assert_eq!(
classify_command("/usr/bin/find ."),
Classification::Supported {
rtk_equivalent: "rtk find",
category: "Files",
estimated_savings_pct: 70.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_strip_absolute_path_helper() {
assert_eq!(strip_absolute_path("/usr/bin/grep -rn foo"), "grep -rn foo");
assert_eq!(strip_absolute_path("/bin/ls -la"), "ls -la");
assert_eq!(strip_absolute_path("grep -rn foo"), "grep -rn foo");
assert_eq!(strip_absolute_path("/usr/local/bin/git"), "git");
}
// --- #163: git global options ---
#[test]
fn test_classify_git_with_dash_c_path() {
assert_eq!(
classify_command("git -C /tmp status"),
Classification::Supported {
rtk_equivalent: "rtk git",
category: "Git",
estimated_savings_pct: 70.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_classify_git_no_pager_log() {
assert_eq!(
classify_command("git --no-pager log -5"),
Classification::Supported {
rtk_equivalent: "rtk git",
category: "Git",
estimated_savings_pct: 70.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_classify_git_git_dir() {
assert_eq!(
classify_command("git --git-dir /tmp/.git status"),
Classification::Supported {
rtk_equivalent: "rtk git",
category: "Git",
estimated_savings_pct: 70.0,
status: RtkStatus::Existing,
}
);
}
#[test]
fn test_rewrite_git_dash_c() {
assert_eq!(
rewrite_command("git -C /tmp status", &[]),
Some("rtk git -C /tmp status".to_string())
);
}
#[test]
fn test_rewrite_git_no_pager() {
assert_eq!(
rewrite_command("git --no-pager log -5", &[]),
Some("rtk git --no-pager log -5".to_string())
);
}
#[test]
fn test_strip_git_global_opts_helper() {
assert_eq!(strip_git_global_opts("git -C /tmp status"), "git status");
assert_eq!(strip_git_global_opts("git --no-pager log"), "git log");
assert_eq!(strip_git_global_opts("git status"), "git status");
assert_eq!(strip_git_global_opts("cargo test"), "cargo test");
}
}
+8
View File
@@ -165,6 +165,14 @@ pub fn format_text(report: &DiscoverReport, limit: usize, verbose: bool) -> Stri
out.push_str("\n~estimated from tool_result output sizes\n");
// Cursor note: check if Cursor hooks are installed
if let Some(home) = dirs::home_dir() {
let cursor_hook = home.join(".cursor").join("hooks").join("rtk-rewrite.sh");
if cursor_hook.exists() {
out.push_str("\nNote: Cursor sessions are tracked via `rtk gain` (discover scans Claude Code only)\n");
}
}
if verbose && report.parse_errors > 0 {
out.push_str(&format!("Parse errors skipped: {}\n", report.parse_errors));
}
+7 -7
View File
@@ -21,7 +21,7 @@ pub fn format_duration(ms: u64) -> String {
/// Trait for period-based statistics that can be displayed in tables
pub trait PeriodStats {
/// Icon for this period type (e.g., "📅", "📊", "📆")
/// Icon for this period type (e.g., "D", "W", "M")
fn icon() -> &'static str;
/// Label for this period type (e.g., "Daily", "Weekly", "Monthly")
@@ -143,7 +143,7 @@ pub fn print_period_table<T: PeriodStats>(data: &[T]) {
impl PeriodStats for DayStats {
fn icon() -> &'static str {
"📅"
"D"
}
fn label() -> &'static str {
@@ -193,7 +193,7 @@ impl PeriodStats for DayStats {
impl PeriodStats for WeekStats {
fn icon() -> &'static str {
"📊"
"W"
}
fn label() -> &'static str {
@@ -253,7 +253,7 @@ impl PeriodStats for WeekStats {
impl PeriodStats for MonthStats {
fn icon() -> &'static str {
"📆"
"M"
}
fn label() -> &'static str {
@@ -322,7 +322,7 @@ mod tests {
assert_eq!(day.commands(), 10);
assert_eq!(day.saved_tokens(), 200);
assert_eq!(day.avg_time_ms(), 150);
assert_eq!(DayStats::icon(), "📅");
assert_eq!(DayStats::icon(), "D");
assert_eq!(DayStats::label(), "Daily");
}
@@ -342,7 +342,7 @@ mod tests {
assert_eq!(week.period(), "01-20 → 01-26");
assert_eq!(week.avg_time_ms(), 100);
assert_eq!(WeekStats::icon(), "📊");
assert_eq!(WeekStats::icon(), "W");
assert_eq!(WeekStats::label(), "Weekly");
}
@@ -361,7 +361,7 @@ mod tests {
assert_eq!(month.period(), "2026-01");
assert_eq!(month.avg_time_ms(), 100);
assert_eq!(MonthStats::icon(), "📆");
assert_eq!(MonthStats::icon(), "M");
assert_eq!(MonthStats::label(), "Monthly");
}
+6 -6
View File
@@ -62,7 +62,7 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
// Print categorized
if !path_vars.is_empty() {
println!("📂 PATH Variables:");
println!("PATH Variables:");
for (k, v) in &path_vars {
if k == "PATH" {
// Split PATH for readability
@@ -81,28 +81,28 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
}
if !lang_vars.is_empty() {
println!("\n🔧 Language/Runtime:");
println!("\nLanguage/Runtime:");
for (k, v) in &lang_vars {
println!(" {}={}", k, v);
}
}
if !cloud_vars.is_empty() {
println!("\n☁️ Cloud/Services:");
println!("\nCloud/Services:");
for (k, v) in &cloud_vars {
println!(" {}={}", k, v);
}
}
if !tool_vars.is_empty() {
println!("\n🛠️ Tools:");
println!("\nTools:");
for (k, v) in &tool_vars {
println!(" {}={}", k, v);
}
}
if !other_vars.is_empty() {
println!("\n📋 Other:");
println!("\nOther:");
for (k, v) in other_vars.iter().take(20) {
println!(" {}={}", k, v);
}
@@ -118,7 +118,7 @@ pub fn run(filter: Option<&str>, show_all: bool, verbose: u8) -> Result<()> {
+ tool_vars.len()
+ other_vars.len().min(20);
if filter.is_none() {
println!("\n📊 Total: {} vars (showing {} relevant)", total, shown);
println!("\nTotal: {} vars (showing {} relevant)", total, shown);
}
let raw: String = vars.iter().map(|(k, v)| format!("{}={}\n", k, v)).collect();
+44 -12
View File
@@ -50,6 +50,7 @@ pub enum Language {
Java,
Ruby,
Shell,
/// Data formats (JSON, YAML, TOML, XML, CSV) — no comment stripping
Data,
Unknown,
}
@@ -67,9 +68,10 @@ impl Language {
"java" => Language::Java,
"rb" => Language::Ruby,
"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,
"json" | "jsonc" | "json5" | "yaml" | "yml" | "toml" | "xml" | "csv" | "tsv"
| "graphql" | "gql" | "sql" | "md" | "markdown" | "txt" | "env" | "lock" => {
Language::Data
}
_ => Language::Unknown,
}
}
@@ -249,6 +251,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;
@@ -407,14 +414,15 @@ mod tests {
assert_eq!(Language::from_extension("yml"), Language::Data);
assert_eq!(Language::from_extension("toml"), Language::Data);
assert_eq!(Language::from_extension("xml"), Language::Data);
assert_eq!(Language::from_extension("md"), Language::Data);
assert_eq!(Language::from_extension("csv"), Language::Data);
assert_eq!(Language::from_extension("md"), Language::Data);
assert_eq!(Language::from_extension("lock"), Language::Data);
}
#[test]
fn test_data_files_no_comment_stripping() {
// Regression test for #464: package.json with `/*` in strings
fn test_json_no_comment_stripping() {
// Reproduces #464: package.json with "packages/*" was corrupted
// because /* was treated as block comment start
let json = r#"{
"workspaces": {
"packages": [
@@ -432,17 +440,41 @@ mod tests {
}"#;
let filter = MinimalFilter;
let result = filter.filter(json, &Language::Data);
assert!(
result.contains("scripts"),
"scripts section must be preserved"
);
// All fields must be preserved — no comment stripping on JSON
assert!(
result.contains("packages/*"),
"glob pattern must be preserved"
"packages/* should not be treated as block comment start"
);
assert!(
result.contains("scripts"),
"scripts section must not be stripped"
);
assert!(
result.contains("lint-staged"),
"lint-staged section must not be stripped"
);
assert!(
result.contains("**/package.json"),
"glob pattern must be preserved"
"**/package.json should not be treated as block comment end"
);
}
#[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"
);
}
+35
View File
@@ -0,0 +1,35 @@
[filters.gradle]
description = "Compact Gradle build output — strip progress, keep tasks and errors"
match_command = "^(gradle|gradlew|\\./)gradlew?\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^> Configuring project",
"^> Resolving dependencies",
"^> Transform ",
"^Download(ing)?\\s+http",
"^\\s*<-+>\\s*$",
"^> Task :.*UP-TO-DATE$",
"^> Task :.*NO-SOURCE$",
"^> Task :.*FROM-CACHE$",
"^Starting a Gradle Daemon",
"^Daemon will be stopped",
]
truncate_lines_at = 150
max_lines = 50
on_empty = "gradle: ok"
[[tests.gradle]]
name = "strips UP-TO-DATE tasks, keeps build result"
input = "> Configuring project :app\n> Task :app:compileJava UP-TO-DATE\n> Task :app:compileKotlin UP-TO-DATE\n> Task :app:test\n\n3 tests completed, 1 failed\n\nBUILD FAILED in 12s"
expected = "> Task :app:test\n3 tests completed, 1 failed\nBUILD FAILED in 12s"
[[tests.gradle]]
name = "clean build preserved"
input = "BUILD SUCCESSFUL in 8s\n7 actionable tasks: 7 executed"
expected = "BUILD SUCCESSFUL in 8s\n7 actionable tasks: 7 executed"
[[tests.gradle]]
name = "empty after stripping"
input = "> Configuring project :app\n"
expected = "gradle: ok"
+20
View File
@@ -0,0 +1,20 @@
[filters.jira]
description = "Compact Jira CLI output — strip verbose metadata, keep essentials"
match_command = "^jira\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^\\s*--",
]
truncate_lines_at = 120
max_lines = 40
[[tests.jira]]
name = "strips blank lines from issue list"
input = "TYPE\tKEY\tSUMMARY\tSTATUS\n\nStory\tPROJ-123\tAdd login feature\tIn Progress\n\nBug\tPROJ-456\tFix crash on startup\tOpen"
expected = "TYPE\tKEY\tSUMMARY\tSTATUS\nStory\tPROJ-123\tAdd login feature\tIn Progress\nBug\tPROJ-456\tFix crash on startup\tOpen"
[[tests.jira]]
name = "single issue view"
input = "KEY: PROJ-123\nSummary: Add login feature\nStatus: In Progress\nAssignee: john@example.com"
expected = "KEY: PROJ-123\nSummary: Add login feature\nStatus: In Progress\nAssignee: john@example.com"
+26
View File
@@ -0,0 +1,26 @@
[filters.just]
description = "Compact just task runner output — strip recipe headers, keep command output"
match_command = "^just\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^\\s*Available recipes:",
"^\\s*just --list",
]
truncate_lines_at = 150
max_lines = 50
[[tests.just]]
name = "preserves command output"
input = "cargo test\n\ntest result: ok. 42 passed; 0 failed\n"
expected = "cargo test\ntest result: ok. 42 passed; 0 failed"
[[tests.just]]
name = "preserves error output"
input = "error: Compilation failed\nsrc/main.rs:10: expected `;`"
expected = "error: Compilation failed\nsrc/main.rs:10: expected `;`"
[[tests.just]]
name = "empty input"
input = ""
expected = ""
+30
View File
@@ -0,0 +1,30 @@
[filters.mise]
description = "Compact mise task runner output — strip status lines, keep task results"
match_command = "^mise\\s+(run|exec|install|upgrade)\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^mise\\s+(trust|install|upgrade).*✓",
"^mise\\s+Installing\\s",
"^mise\\s+Downloading\\s",
"^mise\\s+Extracting\\s",
"^mise\\s+\\w+@[\\d.]+ installed",
]
truncate_lines_at = 150
max_lines = 50
on_empty = "mise: ok"
[[tests.mise]]
name = "strips install noise, keeps task output"
input = "mise Installing node@20.0.0\nmise Downloading node@20.0.0\nmise Extracting node@20.0.0\nmise node@20.0.0 installed\n\nlint check passed\n2 warnings found"
expected = "lint check passed\n2 warnings found"
[[tests.mise]]
name = "preserves error output"
input = "mise run lint\nError: biome check failed\nsrc/index.ts:5 — unused variable"
expected = "mise run lint\nError: biome check failed\nsrc/index.ts:5 — unused variable"
[[tests.mise]]
name = "empty after stripping"
input = "mise trust ~/dev/.mise.toml ✓\nmise install node@20 ✓\n"
expected = "mise: ok"
+25
View File
@@ -0,0 +1,25 @@
[filters.nx]
description = "Compact Nx monorepo output — strip task graph noise, keep results"
match_command = "^(pnpm\\s+)?nx\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^\\s*>\\s*NX\\s+Running target",
"^\\s*>\\s*NX\\s+Nx read the output",
"^\\s*>\\s*NX\\s+View logs",
"^———————",
"^—————————",
"^\\s+Nx \\(powered by",
]
truncate_lines_at = 150
max_lines = 60
[[tests.nx]]
name = "strips Nx noise, keeps build output"
input = "\n > NX Running target build for project myapp\n\n———————————————————————————————————————\nCompiled successfully.\nOutput: dist/apps/myapp\n\n > NX View logs at /tmp/.nx/runs/abc123\n\n Nx (powered by computation caching)\n"
expected = "Compiled successfully.\nOutput: dist/apps/myapp"
[[tests.nx]]
name = "preserves error output"
input = "ERROR: Cannot find module '@myapp/shared'\n\n > NX Running target build for project myapp\n\nFailed at step: build"
expected = "ERROR: Cannot find module '@myapp/shared'\nFailed at step: build"
+23
View File
@@ -0,0 +1,23 @@
[filters.ollama]
description = "Strip ANSI spinners and cursor control from ollama output, keep final text"
match_command = "^ollama\\s+run\\b"
strip_ansi = true
strip_lines_matching = [
"^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\\s]*$",
"^\\s*$",
]
[[tests.ollama]]
name = "strips spinner lines, keeps response"
input = "⠋ \n⠙ \n⠹ \nHello! How can I help you today?"
expected = "Hello! How can I help you today?"
[[tests.ollama]]
name = "preserves multi-line response"
input = "⠋ \n⠙ \nLine one of the response.\nLine two of the response."
expected = "Line one of the response.\nLine two of the response."
[[tests.ollama]]
name = "empty input"
input = ""
expected = ""
+28
View File
@@ -0,0 +1,28 @@
[filters.spring-boot]
description = "Compact Spring Boot output — strip banner and verbose startup logs, keep key events"
match_command = "^(mvn\\s+spring-boot:run|java\\s+-jar.*\\.jar|gradle\\s+.*bootRun)"
strip_ansi = true
keep_lines_matching = [
"Started\\s.*\\sin\\s",
"Tomcat started on port",
"ERROR",
"WARN",
"Exception",
"Caused by:",
"Application run failed",
"BUILD\\s",
"Tests run:",
"FAILURE",
"listening on port",
]
max_lines = 30
[[tests.spring-boot]]
name = "keeps startup summary and errors"
input = " . ____ _ \n /\\\\ / ___'_ __ _ _(_)_ __ \n( ( )\\___ | '_ | '_| | '_ \\ \n \\/ ___)| |_)| | | | | || )\n ' |____| .__|_| |_|_| |_\\__|\n :: Spring Boot :: (v3.2.0)\n2024-01-01 INFO Initializing Spring\n2024-01-01 INFO Bean 'dataSource' created\n2024-01-01 INFO Tomcat started on port 8080\n2024-01-01 INFO Started MyApp in 3.2 seconds"
expected = "2024-01-01 INFO Tomcat started on port 8080\n2024-01-01 INFO Started MyApp in 3.2 seconds"
[[tests.spring-boot]]
name = "preserves errors"
input = " :: Spring Boot :: (v3.2.0)\n2024-01-01 INFO Initializing Spring\n2024-01-01 ERROR Application run failed\nCaused by: java.lang.NullPointerException"
expected = "2024-01-01 ERROR Application run failed\nCaused by: java.lang.NullPointerException"
+27
View File
@@ -0,0 +1,27 @@
[filters.task]
description = "Compact go-task output — strip task headers, keep command results"
match_command = "^task\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^task: \\[.*\\] ",
"^task: Task .* is up to date",
]
truncate_lines_at = 150
max_lines = 50
on_empty = "task: ok"
[[tests.task]]
name = "strips task headers, keeps output"
input = "task: [build] go build ./...\n\ntask: [test] go test ./...\nok myapp 0.5s\n\ntask: Task \"lint\" is up to date"
expected = "ok myapp 0.5s"
[[tests.task]]
name = "preserves error output"
input = "task: [build] go build ./...\n./main.go:10: undefined: foo\ntask: Failed to run task \"build\": exit status 1"
expected = "./main.go:10: undefined: foo\ntask: Failed to run task \"build\": exit status 1"
[[tests.task]]
name = "all up to date"
input = "task: Task \"build\" is up to date\ntask: Task \"lint\" is up to date\n"
expected = "task: ok"
+30
View File
@@ -0,0 +1,30 @@
[filters.turbo]
description = "Compact Turborepo output — strip cache status noise, keep task results"
match_command = "^turbo\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^\\s*cache (hit|miss|bypass)",
"^\\s*\\d+ packages in scope",
"^\\s*Tasks:\\s+\\d+",
"^\\s*Duration:\\s+",
"^\\s*Remote caching (enabled|disabled)",
]
truncate_lines_at = 150
max_lines = 50
on_empty = "turbo: ok"
[[tests.turbo]]
name = "strips cache noise, keeps task output"
input = " cache hit, replaying logs abc123\n cache miss, executing abc456\n\n3 packages in scope\n\n> myapp:build\n\nCompiled successfully.\n\nTasks: 2 successful, 2 total (1 cached)\nDuration: 3.2s"
expected = "> myapp:build\nCompiled successfully."
[[tests.turbo]]
name = "preserves error output"
input = "> myapp:lint\n\nError: src/index.ts(5,1): error TS2304\n\nTasks: 0 successful, 1 total\nDuration: 1.1s"
expected = "> myapp:lint\nError: src/index.ts(5,1): error TS2304"
[[tests.turbo]]
name = "empty after stripping"
input = " cache hit, replaying logs abc\n\n"
expected = "turbo: ok"
+21
View File
@@ -0,0 +1,21 @@
[filters.yadm]
description = "Compact yadm (git wrapper) output — same filtering as git"
match_command = "^yadm\\b"
strip_ansi = true
strip_lines_matching = [
"^\\s*$",
"^\\s*\\(use \"git ",
"^\\s*\\(use \"yadm ",
]
truncate_lines_at = 120
max_lines = 40
[[tests.yadm]]
name = "strips hint lines"
input = "On branch main\nYour branch is up to date with 'origin/main'.\n\n (use \"yadm add\" to update what will be committed)\n\nChanges not staged for commit:\n modified: .bashrc"
expected = "On branch main\nYour branch is up to date with 'origin/main'.\nChanges not staged for commit:\n modified: .bashrc"
[[tests.yadm]]
name = "short output preserved"
input = "Already up to date."
expected = "Already up to date."
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn run(
let dirs_count = dirs.len();
let total_files = files.len();
println!("📁 {}F {}D:", total_files, dirs_count);
println!("{}F {}D:", total_files, dirs_count);
println!();
// Display with proper --max limiting (count individual files)
+5 -8
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"
@@ -226,7 +226,7 @@ fn filter_black_output(output: &str) -> String {
if !needs_formatting && (all_done || files_unchanged > 0) {
// All files formatted correctly
result.push_str("✓ Format (black): All files formatted");
result.push_str("Format (black): All files formatted");
if files_unchanged > 0 {
result.push_str(&format!(" ({} files checked)", files_unchanged));
}
@@ -258,13 +258,10 @@ fn filter_black_output(output: &str) -> String {
}
if files_unchanged > 0 {
result.push_str(&format!(
"\n✓ {} files already formatted\n",
files_unchanged
));
result.push_str(&format!("\n{} files already formatted\n", files_unchanged));
}
result.push_str("\n💡 Run `black .` to format these files\n");
result.push_str("\n[hint] Run `black .` to format these files\n");
} else {
// Fallback: show raw output
result.push_str(output.trim());
@@ -349,7 +346,7 @@ mod tests {
fn test_filter_black_all_formatted() {
let output = "All done! ✨ 🍰 ✨\n5 files left unchanged.";
let result = filter_black_output(output);
assert!(result.contains("✓ Format (black)"));
assert!(result.contains("Format (black)"));
assert!(result.contains("All files formatted"));
assert!(result.contains("5 files checked"));
}
+4 -3
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,
@@ -108,7 +109,7 @@ pub fn run(
hook_check::HookStatus::Missing => {
eprintln!(
"{}",
"⚠️ No hook installed — run `rtk init -g` for automatic token savings"
"[warn] No hook installed — run `rtk init -g` for automatic token savings"
.yellow()
);
eprintln!();
@@ -116,7 +117,7 @@ pub fn run(
hook_check::HookStatus::Outdated => {
eprintln!(
"{}",
"⚠️ Hook outdated — run `rtk init -g` to update".yellow()
"[warn] Hook outdated — run `rtk init -g` to update".yellow()
);
eprintln!();
}
@@ -658,7 +659,7 @@ fn check_rtk_disabled_bypass() -> Option<String> {
let pct = (bypassed as f64 / total_bash as f64) * 100.0;
if pct > 10.0 {
Some(format!(
"⚠️ {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
"[warn] {} commands ({:.0}%) used RTK_DISABLED=1 unnecessarily — run `rtk discover` for details",
bypassed, pct
))
} else {
+48 -53
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),
}
}
@@ -235,8 +235,8 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
filtered.push_str("PRs\n");
println!("PRs");
} else {
filtered.push_str("📋 Pull Requests\n");
println!("📋 Pull Requests");
filtered.push_str("Pull Requests\n");
println!("Pull Requests");
}
for pr in prs.iter().take(20) {
@@ -254,10 +254,10 @@ fn list_prs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
}
} else {
match state {
"OPEN" => "🟢",
"MERGED" => "🟣",
"CLOSED" => "🔴",
_ => "⚪",
"OPEN" => "[open]",
"MERGED" => "[merged]",
"CLOSED" => "[closed]",
_ => "[unknown]",
}
};
@@ -352,10 +352,10 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
}
} else {
match state {
"OPEN" => "🟢",
"MERGED" => "🟣",
"CLOSED" => "🔴",
_ => "⚪",
"OPEN" => "[open]",
"MERGED" => "[merged]",
"CLOSED" => "[closed]",
_ => "[unknown]",
}
};
@@ -368,8 +368,8 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
print!("{}", line);
let mergeable_str = match mergeable {
"MERGEABLE" => "✓",
"CONFLICTING" => "✗",
"MERGEABLE" => "[ok]",
"CONFLICTING" => "[x]",
_ => "?",
};
let line = format!(" {} | {}\n", state, mergeable_str);
@@ -417,11 +417,11 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
if ultra_compact {
if failed > 0 {
let line = format!(" ✗{}/{} {} fail\n", passed, total, failed);
let line = format!(" [x]{}/{} {} fail\n", passed, total, failed);
filtered.push_str(&line);
print!("{}", line);
} else {
let line = format!(" ✓{}/{}\n", passed, total);
let line = format!(" {}/{}\n", passed, total);
filtered.push_str(&line);
print!("{}", line);
}
@@ -430,7 +430,7 @@ fn view_pr(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
filtered.push_str(&line);
print!("{}", line);
if failed > 0 {
let line = format!(" ⚠️ {} checks failed\n", failed);
let line = format!(" [warn] {} checks failed\n", failed);
filtered.push_str(&line);
print!("{}", line);
}
@@ -504,9 +504,9 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()>
let mut failed_checks = Vec::new();
for line in stdout.lines() {
if line.contains('✓') || line.contains("pass") {
if line.contains("[ok]") || line.contains("pass") {
passed += 1;
} else if line.contains('✗') || line.contains("fail") {
} else if line.contains("[x]") || line.contains("fail") {
failed += 1;
failed_checks.push(line.trim().to_string());
} else if line.contains('*') || line.contains("pending") {
@@ -516,20 +516,20 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()>
let mut filtered = String::new();
let line = "🔍 CI Checks Summary:\n";
let line = "CI Checks Summary:\n";
filtered.push_str(line);
print!("{}", line);
let line = format!(" ✅ Passed: {}\n", passed);
let line = format!(" [ok] Passed: {}\n", passed);
filtered.push_str(&line);
print!("{}", line);
let line = format!(" ❌ Failed: {}\n", failed);
let line = format!(" [FAIL] Failed: {}\n", failed);
filtered.push_str(&line);
print!("{}", line);
if pending > 0 {
let line = format!(" ⏳ Pending: {}\n", pending);
let line = format!(" [pending] Pending: {}\n", pending);
filtered.push_str(&line);
print!("{}", line);
}
@@ -581,7 +581,7 @@ fn pr_status(_verbose: u8, _ultra_compact: bool) -> Result<()> {
let mut filtered = String::new();
if let Some(created_by) = json["createdBy"].as_array() {
let line = format!("📝 Your PRs ({}):\n", created_by.len());
let line = format!("Your PRs ({}):\n", created_by.len());
filtered.push_str(&line);
print!("{}", line);
for pr in created_by.iter().take(5) {
@@ -636,13 +636,8 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
let mut filtered = String::new();
if let Some(issues) = json.as_array() {
if ultra_compact {
filtered.push_str("Issues\n");
println!("Issues");
} else {
filtered.push_str("🐛 Issues\n");
println!("🐛 Issues");
}
filtered.push_str("Issues\n");
println!("Issues");
for issue in issues.iter().take(20) {
let number = issue["number"].as_i64().unwrap_or(0);
let title = issue["title"].as_str().unwrap_or("???");
@@ -656,9 +651,9 @@ fn list_issues(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()>
}
} else {
if state == "OPEN" {
"🟢"
"[open]"
} else {
"🔴"
"[closed]"
}
};
let line = format!(" {} #{} {}\n", icon, number, truncate(title, 60));
@@ -721,7 +716,11 @@ fn view_issue(args: &[String], _verbose: u8) -> Result<()> {
let author = json["author"]["login"].as_str().unwrap_or("???");
let url = json["url"].as_str().unwrap_or("");
let icon = if state == "OPEN" { "🟢" } else { "🔴" };
let icon = if state == "OPEN" {
"[open]"
} else {
"[closed]"
};
let mut filtered = String::new();
@@ -814,8 +813,8 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
filtered.push_str("Runs\n");
println!("Runs");
} else {
filtered.push_str("🏃 Workflow Runs\n");
println!("🏃 Workflow Runs");
filtered.push_str("Workflow Runs\n");
println!("Workflow Runs");
}
for run in runs {
let id = run["databaseId"].as_i64().unwrap_or(0);
@@ -825,8 +824,8 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
let icon = if ultra_compact {
match conclusion {
"success" => "✓",
"failure" => "✗",
"success" => "[ok]",
"failure" => "[x]",
"cancelled" => "X",
_ => {
if status == "in_progress" {
@@ -838,14 +837,14 @@ fn list_runs(args: &[String], _verbose: u8, ultra_compact: bool) -> Result<()> {
}
} else {
match conclusion {
"success" => "✅",
"failure" => "❌",
"cancelled" => "🚫",
"success" => "[ok]",
"failure" => "[FAIL]",
"cancelled" => "[X]",
_ => {
if status == "in_progress" {
"⏳"
"[time]"
} else {
"⚪"
"[pending]"
}
}
}
@@ -910,7 +909,7 @@ fn view_run(args: &[String], _verbose: u8) -> Result<()> {
let mut filtered = String::new();
let line = format!("🏃 Workflow Run #{}\n", run_id);
let line = format!("Workflow Run #{}\n", run_id);
filtered.push_str(&line);
print!("{}", line);
@@ -924,8 +923,8 @@ fn view_run(args: &[String], _verbose: u8) -> Result<()> {
// Skip successful jobs in compact mode
continue;
}
if line.contains('✗') || line.contains("fail") {
let formatted = format!(" ❌ {}\n", line.trim());
if line.contains("[x]") || line.contains("fail") {
let formatted = format!(" [FAIL] {}\n", line.trim());
filtered.push_str(&formatted);
print!("{}", formatted);
}
@@ -992,15 +991,11 @@ fn run_repo(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
let forks = json["forkCount"].as_i64().unwrap_or(0);
let private = json["isPrivate"].as_bool().unwrap_or(false);
let visibility = if private {
"🔒 Private"
} else {
"🌐 Public"
};
let visibility = if private { "[private]" } else { "[public]" };
let mut filtered = String::new();
let line = format!("📦 {}/{}\n", owner, name);
let line = format!("{}/{}\n", owner, name);
filtered.push_str(&line);
print!("{}", line);
@@ -1014,7 +1009,7 @@ fn run_repo(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<()> {
print!("{}", line);
}
let line = format!(" ⭐ {} stars | 🔱 {} forks\n", stars, forks);
let line = format!(" {} stars | {} forks\n", stars, forks);
filtered.push_str(&line);
print!("{}", line);
+251 -67
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -76,6 +77,9 @@ fn run_diff(
let mut cmd = git_cmd(global_args);
cmd.arg("diff");
for arg in args {
if arg == "--no-compact" {
continue; // RTK flag, not a git flag
}
cmd.arg(arg);
}
@@ -111,6 +115,21 @@ fn run_diff(
let output = cmd.output().context("Failed to run git diff")?;
let stat_stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
let raw = stat_stdout.to_string();
timer.track(
&format!("git diff {}", args.join(" ")),
&format!("rtk git diff {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
if verbose > 0 {
eprintln!("Git diff summary:");
}
@@ -279,6 +298,7 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
let mut in_hunk = false;
let mut hunk_lines = 0;
let max_hunk_lines = 30;
let mut was_truncated = false;
for line in diff.lines() {
if line.starts_with("diff --git") {
@@ -287,7 +307,7 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
result.push(format!(" +{} -{}", added, removed));
}
current_file = line.split(" b/").nth(1).unwrap_or("unknown").to_string();
result.push(format!("\n📄 {}", current_file));
result.push(format!("\n{}", current_file));
added = 0;
removed = 0;
in_hunk = false;
@@ -321,11 +341,13 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
if hunk_lines == max_hunk_lines {
result.push(" ... (truncated)".to_string());
hunk_lines += 1;
was_truncated = true;
}
}
if result.len() >= max_lines {
result.push("\n... (more changes truncated)".to_string());
was_truncated = true;
break;
}
}
@@ -334,6 +356,10 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
result.push(format!(" +{} -{}", added, removed));
}
if was_truncated {
result.push("[full diff: rtk git diff --no-compact]".to_string());
}
result.join("\n")
}
@@ -355,7 +381,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 +459,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);
@@ -547,7 +573,7 @@ fn format_status_output(porcelain: &str) -> String {
if let Some(branch_line) = lines.first() {
if branch_line.starts_with("##") {
let branch = branch_line.trim_start_matches("## ");
output.push_str(&format!("📌 {}\n", branch));
output.push_str(&format!("* {}\n", branch));
}
}
@@ -592,38 +618,56 @@ 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) {
output.push_str(&format!("+ Staged: {} files\n", staged));
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) {
output.push_str(&format!("~ Modified: {} files\n", modified));
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) {
output.push_str(&format!("? Untracked: {} files\n", untracked));
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
));
}
}
if conflicts > 0 {
output.push_str(&format!("⚠️ Conflicts: {} files\n", conflicts));
output.push_str(&format!("conflicts: {} files\n", conflicts));
}
// When working tree is clean (only branch line, no changes)
if staged == 0 && modified == 0 && untracked == 0 && conflicts == 0 {
output.push_str("clean — nothing to commit\n");
}
output.trim_end().to_string()
@@ -660,7 +704,7 @@ fn filter_status_with_args(output: &str) -> String {
}
if result.is_empty() {
"ok ✓".to_string()
"ok".to_string()
} else {
result.join("\n")
}
@@ -680,6 +724,20 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
let raw = stdout.to_string();
timer.track(
&format!("git status {}", args.join(" ")),
&format!("rtk git status {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
if verbose > 0 || !stderr.is_empty() {
eprint!("{}", stderr);
}
@@ -772,9 +830,9 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<()> {
// Parse "1 file changed, 5 insertions(+)" format
let short = stat.lines().last().unwrap_or("").trim();
if short.is_empty() {
"ok ✓".to_string()
"ok".to_string()
} else {
format!("ok ✓ {}", short)
format!("ok {}", short)
}
};
@@ -833,17 +891,17 @@ 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())])
format!("ok {}", &hash[..7.min(hash.len())])
} else {
"ok ✓".to_string()
"ok".to_string()
}
} else {
"ok ✓".to_string()
"ok".to_string()
}
} else {
"ok ✓".to_string()
"ok".to_string()
};
println!("{}", compact);
@@ -859,13 +917,14 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
"ok (nothing to commit)",
);
} else {
eprintln!("FAILED: git commit");
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
eprint!("{}", stderr);
}
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
eprint!("{}", stdout);
}
timer.track(&original_cmd, "rtk git commit", &raw_output, &raw_output);
std::process::exit(output.status.code().unwrap_or(1));
}
}
@@ -900,7 +959,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
if line.contains("->") {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 3 {
result = format!("ok ✓ {}", parts[parts.len() - 1]);
result = format!("ok {}", parts[parts.len() - 1]);
break;
}
}
@@ -908,7 +967,7 @@ fn run_push(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
if !result.is_empty() {
result
} else {
"ok ✓".to_string()
"ok".to_string()
}
};
@@ -992,9 +1051,9 @@ fn run_pull(args: &[String], verbose: u8, global_args: &[String]) -> Result<()>
}
if files > 0 {
format!("ok ✓ {} files +{} -{}", files, insertions, deletions)
format!("ok {} files +{} -{}", files, insertions, deletions)
} else {
"ok ✓".to_string()
"ok".to_string()
}
};
@@ -1027,10 +1086,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 +1115,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);
@@ -1061,7 +1171,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let combined = format!("{}{}", stdout, stderr);
let msg = if output.status.success() {
"ok ✓"
"ok"
} else {
&combined
};
@@ -1074,7 +1184,7 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
);
if output.status.success() {
println!("ok ✓");
println!("ok");
} else {
eprintln!("FAILED: git branch {}", args.join(" "));
if !stderr.trim().is_empty() {
@@ -1103,6 +1213,20 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let stdout = String::from_utf8_lossy(&output.stdout);
let raw = 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!("git branch {}", args.join(" ")),
&format!("rtk git branch {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = filter_branch_output(&stdout);
println!("{}", filtered);
@@ -1303,7 +1427,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");
@@ -1389,7 +1548,7 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
let combined = format!("{}{}", stdout, stderr);
let msg = if output.status.success() {
"ok ✓"
"ok"
} else {
&combined
};
@@ -1402,7 +1561,7 @@ fn run_worktree(args: &[String], verbose: u8, global_args: &[String]) -> Result<
);
if output.status.success() {
println!("ok ✓");
println!("ok");
} else {
eprintln!("FAILED: git worktree {}", args.join(" "));
if !stderr.trim().is_empty() {
@@ -1649,8 +1808,8 @@ mod tests {
fn test_format_status_output_modified_files() {
let porcelain = "## main...origin/main\n M src/main.rs\n M src/lib.rs\n";
let result = format_status_output(porcelain);
assert!(result.contains("📌 main...origin/main"));
assert!(result.contains("📝 Modified: 2 files"));
assert!(result.contains("* main...origin/main"));
assert!(result.contains("~ Modified: 2 files"));
assert!(result.contains("src/main.rs"));
assert!(result.contains("src/lib.rs"));
assert!(!result.contains("Staged"));
@@ -1661,8 +1820,8 @@ mod tests {
fn test_format_status_output_untracked_files() {
let porcelain = "## feature/new\n?? temp.txt\n?? debug.log\n?? test.sh\n";
let result = format_status_output(porcelain);
assert!(result.contains("📌 feature/new"));
assert!(result.contains("❓ Untracked: 3 files"));
assert!(result.contains("* feature/new"));
assert!(result.contains("? Untracked: 3 files"));
assert!(result.contains("temp.txt"));
assert!(result.contains("debug.log"));
assert!(result.contains("test.sh"));
@@ -1678,35 +1837,60 @@ A added.rs
?? untracked.txt
"#;
let result = format_status_output(porcelain);
assert!(result.contains("📌 main"));
assert!(result.contains("✅ Staged: 2 files"));
assert!(result.contains("* main"));
assert!(result.contains("+ Staged: 2 files"));
assert!(result.contains("staged.rs"));
assert!(result.contains("added.rs"));
assert!(result.contains("📝 Modified: 1 files"));
assert!(result.contains("~ Modified: 1 files"));
assert!(result.contains("modified.rs"));
assert!(result.contains("❓ Untracked: 1 files"));
assert!(result.contains("? Untracked: 1 files"));
assert!(result.contains("untracked.txt"));
}
#[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]
@@ -1916,7 +2100,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
let porcelain = "## main\n M สวัสดี.txt\n?? ทดสอบ.rs\n";
let result = format_status_output(porcelain);
// Should not panic
assert!(result.contains("📌 main"));
assert!(result.contains("* main"));
assert!(result.contains("สวัสดี.txt"));
assert!(result.contains("ทดสอบ.rs"));
}
@@ -1925,7 +2109,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
fn test_format_status_output_emoji_filename() {
let porcelain = "## main\nA 🎉-party.txt\n M 日本語ファイル.rs\n";
let result = format_status_output(porcelain);
assert!(result.contains("📌 main"));
assert!(result.contains("* main"));
}
/// Regression test: --oneline and other user format flags must preserve all commits.
+9 -9
View File
@@ -348,7 +348,7 @@ fn filter_go_test_json(output: &str) -> String {
if !has_failures {
return format!(
"✓ Go test: {} passed in {} packages",
"Go test: {} passed in {} packages",
total_pass, total_packages
);
}
@@ -372,7 +372,7 @@ fn filter_go_test_json(output: &str) -> String {
}
result.push_str(&format!(
"\n📦 {} [build failed]\n",
"\n{} [build failed]\n",
compact_package_name(package)
));
@@ -392,14 +392,14 @@ fn filter_go_test_json(output: &str) -> String {
}
result.push_str(&format!(
"\n📦 {} ({} passed, {} failed)\n",
"\n{} ({} passed, {} failed)\n",
compact_package_name(package),
pkg_result.pass,
pkg_result.fail
));
for (test, outputs) in &pkg_result.failed_tests {
result.push_str(&format!(" ❌ {}\n", test));
result.push_str(&format!(" [FAIL] {}\n", test));
// Show failure output (limit to key lines)
let relevant_lines: Vec<&String> = outputs
@@ -452,7 +452,7 @@ fn filter_go_build(output: &str) -> String {
}
if errors.is_empty() {
return "✓ Go build: Success".to_string();
return "Go build: Success".to_string();
}
let mut result = String::new();
@@ -484,7 +484,7 @@ fn filter_go_vet(output: &str) -> String {
}
if issues.is_empty() {
return "✓ Go vet: No issues found".to_string();
return "Go vet: No issues found".to_string();
}
let mut result = String::new();
@@ -524,7 +524,7 @@ mod tests {
{"Time":"2024-01-01T10:00:02Z","Action":"pass","Package":"example.com/foo","Elapsed":0.5}"#;
let result = filter_go_test_json(output);
assert!(result.contains("✓ Go test"));
assert!(result.contains("Go test"));
assert!(result.contains("1 passed"));
assert!(result.contains("1 packages"));
}
@@ -547,7 +547,7 @@ mod tests {
fn test_filter_go_build_success() {
let output = "";
let result = filter_go_build(output);
assert!(result.contains("✓ Go build"));
assert!(result.contains("Go build"));
assert!(result.contains("Success"));
}
@@ -567,7 +567,7 @@ main.go:15:2: cannot use x (type int) as type string"#;
fn test_filter_go_vet_no_issues() {
let output = "";
let result = filter_go_vet(output);
assert!(result.contains("✓ Go vet"));
assert!(result.contains("Go vet"));
assert!(result.contains("No issues found"));
}
+7 -3
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)
);
}
};
@@ -114,7 +118,7 @@ fn filter_golangci_json(output: &str) -> String {
let issues = golangci_output.issues;
if issues.is_empty() {
return "✓ golangci-lint: No issues found".to_string();
return "golangci-lint: No issues found".to_string();
}
let total_issues = issues.len();
@@ -211,7 +215,7 @@ mod tests {
fn test_filter_golangci_no_issues() {
let output = r#"{"Issues":[]}"#;
let result = filter_golangci_json(output);
assert!(result.contains("✓ golangci-lint"));
assert!(result.contains("golangci-lint"));
assert!(result.contains("No issues found"));
}
+26 -18
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,
@@ -60,7 +62,7 @@ pub fn run(
eprintln!("{}", stderr.trim());
}
}
let msg = format!("🔍 0 for '{}'", pattern);
let msg = format!("0 matches for '{}'", pattern);
println!("{}", msg);
timer.track(
&format!("grep -rn '{}' {}", pattern, path),
@@ -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,12 +100,12 @@ 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));
}
let mut rtk_output = String::new();
rtk_output.push_str(&format!("🔍 {} in {}F:\n\n", total, by_file.len()));
rtk_output.push_str(&format!("{} matches in {}F:\n\n", total, by_file.len()));
let mut shown = 0;
let mut files: Vec<_> = by_file.iter().collect();
@@ -108,9 +117,10 @@ pub fn run(
}
let file_display = compact_path(file);
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
rtk_output.push_str(&format!("[file] {} ({}):\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());
}
+333
View File
@@ -0,0 +1,333 @@
use anyhow::{Context, Result};
use serde_json::{json, Value};
use std::io::{self, Read};
use crate::discover::registry::rewrite_command;
// ── Copilot hook (VS Code + Copilot CLI) ──────────────────────
/// Format detected from the preToolUse JSON input.
enum HookFormat {
/// VS Code Copilot Chat / Claude Code: `tool_name` + `tool_input.command`, supports `updatedInput`.
VsCode { command: String },
/// GitHub Copilot CLI: camelCase `toolName` + `toolArgs` (JSON string), deny-with-suggestion only.
CopilotCli { command: String },
/// Non-bash tool, already uses rtk, or unknown format — pass through silently.
PassThrough,
}
/// Run the Copilot preToolUse hook.
/// Auto-detects VS Code Copilot Chat vs Copilot CLI format.
pub fn run_copilot() -> Result<()> {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.context("Failed to read stdin")?;
let input = input.trim();
if input.is_empty() {
return Ok(());
}
let v: Value = match serde_json::from_str(input) {
Ok(v) => v,
Err(e) => {
eprintln!("[rtk hook] Failed to parse JSON input: {e}");
return Ok(());
}
};
match detect_format(&v) {
HookFormat::VsCode { command } => handle_vscode(&command),
HookFormat::CopilotCli { command } => handle_copilot_cli(&command),
HookFormat::PassThrough => Ok(()),
}
}
fn detect_format(v: &Value) -> HookFormat {
// VS Code Copilot Chat / Claude Code: snake_case keys
if let Some(tool_name) = v.get("tool_name").and_then(|t| t.as_str()) {
if matches!(tool_name, "runTerminalCommand" | "Bash" | "bash") {
if let Some(cmd) = v
.pointer("/tool_input/command")
.and_then(|c| c.as_str())
.filter(|c| !c.is_empty())
{
return HookFormat::VsCode {
command: cmd.to_string(),
};
}
}
return HookFormat::PassThrough;
}
// Copilot CLI: camelCase keys, toolArgs is a JSON-encoded string
if let Some(tool_name) = v.get("toolName").and_then(|t| t.as_str()) {
if tool_name == "bash" {
if let Some(tool_args_str) = v.get("toolArgs").and_then(|t| t.as_str()) {
if let Ok(tool_args) = serde_json::from_str::<Value>(tool_args_str) {
if let Some(cmd) = tool_args
.get("command")
.and_then(|c| c.as_str())
.filter(|c| !c.is_empty())
{
return HookFormat::CopilotCli {
command: cmd.to_string(),
};
}
}
}
}
return HookFormat::PassThrough;
}
HookFormat::PassThrough
}
fn get_rewritten(cmd: &str) -> Option<String> {
if cmd.contains("<<") {
return None;
}
let excluded = crate::config::Config::load()
.map(|c| c.hooks.exclude_commands)
.unwrap_or_default();
let rewritten = rewrite_command(cmd, &excluded)?;
if rewritten == cmd {
return None;
}
Some(rewritten)
}
fn handle_vscode(cmd: &str) -> Result<()> {
let rewritten = match get_rewritten(cmd) {
Some(r) => r,
None => return Ok(()),
};
let output = json!({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "RTK auto-rewrite",
"updatedInput": { "command": rewritten }
}
});
println!("{output}");
Ok(())
}
fn handle_copilot_cli(cmd: &str) -> Result<()> {
let rewritten = match get_rewritten(cmd) {
Some(r) => r,
None => return Ok(()),
};
let output = json!({
"permissionDecision": "deny",
"permissionDecisionReason": format!(
"Token savings: use `{}` instead (rtk saves 60-90% tokens)",
rewritten
)
});
println!("{output}");
Ok(())
}
// ── Gemini hook ───────────────────────────────────────────────
/// Run the Gemini CLI BeforeTool hook.
/// Reads JSON from stdin, rewrites shell commands to rtk equivalents,
/// outputs JSON to stdout in Gemini CLI format.
pub fn run_gemini() -> Result<()> {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.context("Failed to read hook input from stdin")?;
let json: Value = serde_json::from_str(&input).context("Failed to parse hook input as JSON")?;
let tool_name = json.get("tool_name").and_then(|v| v.as_str()).unwrap_or("");
if tool_name != "run_shell_command" {
print_allow();
return Ok(());
}
let cmd = json
.pointer("/tool_input/command")
.and_then(|v| v.as_str())
.unwrap_or("");
if cmd.is_empty() {
print_allow();
return Ok(());
}
// Delegate to the single source of truth for command rewriting
match rewrite_command(cmd, &[]) {
Some(rewritten) => print_rewrite(&rewritten),
None => print_allow(),
}
Ok(())
}
fn print_allow() {
println!(r#"{{"decision":"allow"}}"#);
}
fn print_rewrite(cmd: &str) {
let output = serde_json::json!({
"decision": "allow",
"hookSpecificOutput": {
"tool_input": {
"command": cmd
}
}
});
println!("{}", output);
}
#[cfg(test)]
mod tests {
use super::*;
// --- Copilot format detection ---
fn vscode_input(tool: &str, cmd: &str) -> Value {
json!({
"tool_name": tool,
"tool_input": { "command": cmd }
})
}
fn copilot_cli_input(cmd: &str) -> Value {
let args = serde_json::to_string(&json!({ "command": cmd })).unwrap();
json!({ "toolName": "bash", "toolArgs": args })
}
#[test]
fn test_detect_vscode_bash() {
assert!(matches!(
detect_format(&vscode_input("Bash", "git status")),
HookFormat::VsCode { .. }
));
}
#[test]
fn test_detect_vscode_run_terminal_command() {
assert!(matches!(
detect_format(&vscode_input("runTerminalCommand", "cargo test")),
HookFormat::VsCode { .. }
));
}
#[test]
fn test_detect_copilot_cli_bash() {
assert!(matches!(
detect_format(&copilot_cli_input("git status")),
HookFormat::CopilotCli { .. }
));
}
#[test]
fn test_detect_non_bash_is_passthrough() {
let v = json!({ "tool_name": "editFiles" });
assert!(matches!(detect_format(&v), HookFormat::PassThrough));
}
#[test]
fn test_detect_unknown_is_passthrough() {
assert!(matches!(detect_format(&json!({})), HookFormat::PassThrough));
}
#[test]
fn test_get_rewritten_supported() {
assert!(get_rewritten("git status").is_some());
}
#[test]
fn test_get_rewritten_unsupported() {
assert!(get_rewritten("htop").is_none());
}
#[test]
fn test_get_rewritten_already_rtk() {
assert!(get_rewritten("rtk git status").is_none());
}
#[test]
fn test_get_rewritten_heredoc() {
assert!(get_rewritten("cat <<'EOF'\nhello\nEOF").is_none());
}
// --- Gemini format ---
#[test]
fn test_print_allow_format() {
// Verify the allow JSON format matches Gemini CLI expectations
let expected = r#"{"decision":"allow"}"#;
assert_eq!(expected, r#"{"decision":"allow"}"#);
}
#[test]
fn test_print_rewrite_format() {
let output = serde_json::json!({
"decision": "allow",
"hookSpecificOutput": {
"tool_input": {
"command": "rtk git status"
}
}
});
let json: Value = serde_json::from_str(&output.to_string()).unwrap();
assert_eq!(json["decision"], "allow");
assert_eq!(
json["hookSpecificOutput"]["tool_input"]["command"],
"rtk git status"
);
}
#[test]
fn test_gemini_hook_uses_rewrite_command() {
// Verify that rewrite_command handles the cases we need for Gemini
assert_eq!(
rewrite_command("git status", &[]),
Some("rtk git status".into())
);
assert_eq!(
rewrite_command("cargo test", &[]),
Some("rtk cargo test".into())
);
// Already rtk → returned as-is (idempotent)
assert_eq!(
rewrite_command("rtk git status", &[]),
Some("rtk git status".into())
);
// Heredoc → no rewrite
assert_eq!(rewrite_command("cat <<EOF", &[]), None);
}
#[test]
fn test_gemini_hook_excluded_commands() {
let excluded = vec!["curl".to_string()];
assert_eq!(rewrite_command("curl https://example.com", &excluded), None);
// Non-excluded still rewrites
assert_eq!(
rewrite_command("git status", &excluded),
Some("rtk git status".into())
);
}
#[test]
fn test_gemini_hook_env_prefix_preserved() {
assert_eq!(
rewrite_command("RUST_LOG=debug cargo test", &[]),
Some("RUST_LOG=debug rtk cargo test".into())
);
}
}
+1159 -58
View File
File diff suppressed because it is too large. Load diff
+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
+11 -8
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"
@@ -169,7 +172,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
// Check if process was killed by signal (SIGABRT, SIGKILL, etc.)
if !output.status.success() && output.status.code().is_none() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprintln!("⚠️ Linter process terminated abnormally (possibly out of memory)");
eprintln!("[warn] Linter process terminated abnormally (possibly out of memory)");
if !stderr.is_empty() {
eprintln!(
"stderr: {}",
@@ -191,7 +194,7 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
if !stdout.trim().is_empty() {
ruff_cmd::filter_ruff_check_json(&stdout)
} else {
"✓ Ruff: No issues found".to_string()
"Ruff: No issues found".to_string()
}
}
"pylint" => filter_pylint_json(&stdout),
@@ -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)
);
}
};
@@ -245,7 +248,7 @@ fn filter_eslint_json(output: &str) -> String {
let total_files = results.iter().filter(|r| !r.messages.is_empty()).count();
if total_errors == 0 && total_warnings == 0 {
return "✓ ESLint: No issues found".to_string();
return "ESLint: No issues found".to_string();
}
// Group messages by rule
@@ -326,13 +329,13 @@ 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)
);
}
};
if diagnostics.is_empty() {
return "✓ Pylint: No issues found".to_string();
return "Pylint: No issues found".to_string();
}
// Count by type
@@ -451,7 +454,7 @@ fn filter_generic_lint(output: &str) -> String {
}
if errors == 0 && warnings == 0 {
return "✓ Lint: No issues found".to_string();
return "Lint: No issues found".to_string();
}
let mut result = String::new();
@@ -553,7 +556,7 @@ mod tests {
fn test_filter_pylint_json_no_issues() {
let output = "[]";
let result = filter_pylint_json(output);
assert!(result.contains("✓ Pylint"));
assert!(result.contains("Pylint"));
assert!(result.contains("No issues found"));
}
+6 -6
View File
@@ -105,23 +105,23 @@ 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)",
" [error] {} errors ({} unique)",
total_errors,
error_counts.len()
));
result.push(format!(
" ⚠️ {} warnings ({} unique)",
" [warn] {} warnings ({} unique)",
total_warnings,
warn_counts.len()
));
result.push(format!(" ℹ️ {} info messages", total_info));
result.push(format!(" [info] {} info messages", total_info));
result.push(String::new());
// Errors with counts
if !unique_errors.is_empty() {
result.push("❌ ERRORS:".to_string());
result.push("[ERRORS]".to_string());
// Sort by count
let mut error_list: Vec<_> = error_counts.iter().collect();
@@ -163,7 +163,7 @@ fn analyze_logs(content: &str) -> String {
// Warnings with counts
if !unique_warnings.is_empty() {
result.push("⚠️ WARNINGS:".to_string());
result.push("[WARNINGS]".to_string());
let mut warn_list: Vec<_> = warn_counts.iter().collect();
warn_list.sort_by(|a, b| b.1.cmp(a.1));
+2 -2
View File
@@ -203,7 +203,7 @@ fn compact_ls(raw: &str, show_all: bool) -> String {
// Summary line
out.push('\n');
let mut summary = format!("📊 {} files, {} dirs", files.len(), dirs.len());
let mut summary = format!("{} files, {} dirs", files.len(), dirs.len());
if !by_ext.is_empty() {
let mut ext_counts: Vec<_> = by_ext.iter().collect();
ext_counts.sort_by(|a, b| b.1.cmp(a.1));
@@ -291,7 +291,7 @@ mod tests {
-rw-r--r-- 1 user staff 5678 Jan 1 12:00 lib.rs\n\
-rw-r--r-- 1 user staff 100 Jan 1 12:00 Cargo.toml\n";
let output = compact_ls(input, false);
assert!(output.contains("📊 3 files, 1 dirs"));
assert!(output.contains("3 files, 1 dirs"));
assert!(output.contains(".rs"));
assert!(output.contains(".toml"));
}
+78 -13
View File
@@ -26,6 +26,7 @@ mod grep_cmd;
mod gt_cmd;
mod hook_audit_cmd;
mod hook_check;
mod hook_cmd;
mod init;
mod integrity;
mod json_cmd;
@@ -66,10 +67,21 @@ mod wget_cmd;
use anyhow::{Context, Result};
use clap::error::ErrorKind;
use clap::{Parser, Subcommand};
use clap::{Parser, Subcommand, ValueEnum};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
/// Target agent for hook installation.
#[derive(Debug, Clone, Copy, PartialEq, ValueEnum)]
pub enum AgentTarget {
/// Claude Code (default)
Claude,
/// Cursor Agent (editor and CLI)
Cursor,
/// Windsurf IDE (Cascade)
Windsurf,
}
#[derive(Parser)]
#[command(
name = "rtk",
@@ -306,7 +318,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)]
@@ -322,9 +334,9 @@ enum Commands {
extra_args: Vec<String>,
},
/// Initialize rtk instructions in CLAUDE.md
/// Initialize rtk instructions for assistant CLI usage
Init {
/// Add to global ~/.claude/CLAUDE.md instead of local
/// Add to global assistant config directory instead of local project file
#[arg(short, long)]
global: bool,
@@ -332,6 +344,14 @@ enum Commands {
#[arg(long)]
opencode: bool,
/// Initialize for Gemini CLI instead of Claude Code
#[arg(long)]
gemini: bool,
/// Target agent to install hooks for (default: claude)
#[arg(long, value_enum)]
agent: Option<AgentTarget>,
/// Show current configuration
#[arg(long)]
show: bool,
@@ -352,9 +372,13 @@ enum Commands {
#[arg(long = "no-patch", group = "patch")]
no_patch: bool,
/// Remove all RTK artifacts (hook, RTK.md, CLAUDE.md reference, settings.json entry)
/// Remove RTK artifacts for the selected assistant mode
#[arg(long)]
uninstall: bool,
/// Target Codex CLI (uses AGENTS.md + RTK.md, no Claude hook patching)
#[arg(long)]
codex: bool,
},
/// Download with compact output (strips progress bars)
@@ -663,6 +687,20 @@ enum Commands {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Hook processors for LLM CLI tools (Gemini CLI, Copilot, etc.)
Hook {
#[command(subcommand)]
command: HookCommands,
},
}
#[derive(Subcommand)]
enum HookCommands {
/// Process Gemini CLI BeforeTool hook (reads JSON from stdin)
Gemini,
/// Process Copilot preToolUse hook (VS Code + Copilot CLI, reads JSON from stdin)
Copilot,
}
#[derive(Subcommand)]
@@ -691,25 +729,25 @@ enum GitCommands {
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Add files → "ok ✓"
/// Add files → "ok"
Add {
/// Files and flags to add (supports all git add flags like -A, -p, --all, etc)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Commit → "ok ✓ \<hash\>"
/// Commit → "ok \<hash\>"
Commit {
/// Git commit arguments (supports -a, -m, --amend, --allow-empty, etc)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Push → "ok ✓ \<branch\>"
/// Push → "ok \<branch\>"
Push {
/// Git push arguments (supports -u, remote, branch, etc.)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<String>,
},
/// Pull → "ok ✓ \<stats\>"
/// Pull → "ok \<stats\>"
Pull {
/// Git pull arguments (supports --rebase, remote, branch, etc.)
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
@@ -1179,11 +1217,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,
@@ -1608,20 +1646,35 @@ fn main() -> Result<()> {
Commands::Init {
global,
opencode,
gemini,
agent,
show,
claude_md,
hook_only,
auto_patch,
no_patch,
uninstall,
codex,
} => {
if show {
init::show_config()?;
init::show_config(codex)?;
} else if uninstall {
init::uninstall(global, cli.verbose)?;
let cursor = agent.map_or(false, |a| a == AgentTarget::Cursor);
init::uninstall(global, gemini, codex, cursor, cli.verbose)?;
} else if gemini {
let patch_mode = if auto_patch {
init::PatchMode::Auto
} else if no_patch {
init::PatchMode::Skip
} else {
init::PatchMode::Ask
};
init::run_gemini(global, hook_only, patch_mode, cli.verbose)?;
} else {
let install_opencode = opencode;
let install_claude = !opencode;
let install_cursor = agent.map_or(false, |a| a == AgentTarget::Cursor);
let install_windsurf = agent.map_or(false, |a| a == AgentTarget::Windsurf);
let patch_mode = if auto_patch {
init::PatchMode::Auto
@@ -1634,8 +1687,11 @@ fn main() -> Result<()> {
global,
install_claude,
install_opencode,
install_cursor,
install_windsurf,
claude_md,
hook_only,
codex,
patch_mode,
cli.verbose,
)?;
@@ -1977,6 +2033,15 @@ fn main() -> Result<()> {
hook_audit_cmd::run(since, cli.verbose)?;
}
Commands::Hook { command } => match command {
HookCommands::Gemini => {
hook_cmd::run_gemini()?;
}
HookCommands::Copilot => {
hook_cmd::run_copilot()?;
}
},
Commands::Rewrite { args } => {
let cmd = args.join(" ");
rewrite_cmd::run(&cmd)?;
+5 -5
View File
@@ -125,14 +125,14 @@ fn filter_next_build(output: &str) -> String {
// Build filtered output
let mut result = String::new();
result.push_str("⚡ Next.js Build\n");
result.push_str("Next.js Build\n");
result.push_str("═══════════════════════════════════════\n");
if already_built && routes_total == 0 {
result.push_str("✓ Already built (using cache)\n\n");
result.push_str("Already built (using cache)\n\n");
} else if routes_total > 0 {
result.push_str(&format!(
"✓ {} routes ({} static, {} dynamic)\n\n",
"{} routes ({} static, {} dynamic)\n\n",
routes_total, routes_static, routes_dynamic
));
}
@@ -146,7 +146,7 @@ fn filter_next_build(output: &str) -> String {
for (route, size, pct_change) in bundles.iter().take(10) {
let warning_marker = if let Some(pct) = pct_change {
if *pct > 10.0 {
format!(" ⚠️ (+{:.0}%)", pct)
format!(" [warn] (+{:.0}%)", pct)
} else {
String::new()
}
@@ -219,7 +219,7 @@ Route (app) Size First Load JS
✓ Built in 34.2s
"#;
let result = filter_next_build(output);
assert!(result.contains("⚡ Next.js Build"));
assert!(result.contains("Next.js Build"));
assert!(result.contains("routes"));
assert!(!result.contains("Creating an optimized")); // Should filter verbose logs
}
+2 -2
View File
@@ -160,7 +160,7 @@ fn filter_npm_output(output: &str) -> String {
}
if result.is_empty() {
"ok ✓".to_string()
"ok".to_string()
} else {
result.join("\n")
}
@@ -231,6 +231,6 @@ npm notice
fn test_filter_npm_output_empty() {
let output = "\n\n\n";
let result = filter_npm_output(output);
assert_eq!(result, "ok ✓");
assert_eq!(result, "ok");
}
}
+2 -2
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))
}
}
}
@@ -152,7 +152,7 @@ For build tools (next, webpack, vite, cargo, etc.)
- Human-readable
### Ultra (verbosity=2+)
- Symbols: ✓✗⚠📦⬆️
- Symbols: ✓✗⚠ pkg: ^
- Ultra-compressed
- 30-50% token reduction
+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 {
+10 -10
View File
@@ -105,7 +105,7 @@ impl TokenFormatter for TestResult {
fn format_ultra(&self) -> String {
format!(
"✓{} ✗{} ⊘{} ({}ms)",
"[ok]{} [x]{} [skip]{} ({}ms)",
self.passed,
self.failed,
self.skipped,
@@ -161,9 +161,9 @@ impl TokenFormatter for LintResult {
lines.push("\nIssues:".to_string());
for issue in self.issues.iter().take(20) {
let severity_symbol = match issue.severity {
LintSeverity::Error => "✗",
LintSeverity::Warning => "⚠",
LintSeverity::Info => "ℹ",
LintSeverity::Error => "[x]",
LintSeverity::Warning => "[!]",
LintSeverity::Info => "[info]",
};
lines.push(format!(
"{} {}:{}:{} [{}] {}",
@@ -186,7 +186,7 @@ impl TokenFormatter for LintResult {
fn format_ultra(&self) -> String {
format!(
"✗{} ⚠{} 📁{}",
"[x]{} [!]{} {}F",
self.errors, self.warnings, self.files_with_issues
)
}
@@ -195,7 +195,7 @@ impl TokenFormatter for LintResult {
impl TokenFormatter for DependencyState {
fn format_compact(&self) -> String {
if self.outdated_count == 0 {
return "All packages up-to-date ✓".to_string();
return "All packages up-to-date".to_string();
}
let mut lines = vec![format!(
@@ -251,13 +251,13 @@ impl TokenFormatter for DependencyState {
}
fn format_ultra(&self) -> String {
format!("📦{} ⬆️{}", self.total_packages, self.outdated_count)
format!("pkg:{} ^{}", self.total_packages, self.outdated_count)
}
}
impl TokenFormatter for BuildOutput {
fn format_compact(&self) -> String {
let status = if self.success { "✓" } else { "✗" };
let status = if self.success { "[ok]" } else { "[x]" };
let mut lines = vec![format!(
"{} Build: {} errors, {} warnings",
status, self.errors, self.warnings
@@ -324,9 +324,9 @@ impl TokenFormatter for BuildOutput {
}
fn format_ultra(&self) -> String {
let status = if self.success { "✓" } else { "✗" };
let status = if self.success { "[ok]" } else { "[x]" };
format!(
"{} ✗{} ⚠{} ({}ms)",
"{} [x]{} [!]{} ({}ms)",
status,
self.errors,
self.warnings,
+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,
+5 -12
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)?
}
};
@@ -208,7 +206,7 @@ fn filter_pip_outdated(output: &str) -> String {
};
if packages.is_empty() {
return "✓ pip outdated: All packages up to date".to_string();
return "pip outdated: All packages up to date".to_string();
}
let mut result = String::new();
@@ -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,
@@ -234,7 +228,7 @@ fn filter_pip_outdated(output: &str) -> String {
result.push_str(&format!("\n... +{} more packages\n", packages.len() - 20));
}
result.push_str("\n💡 Run `pip install --upgrade <package>` to update\n");
result.push_str("\n[hint] Run `pip install --upgrade <package>` to update\n");
result.trim().to_string()
}
@@ -269,7 +263,6 @@ mod tests {
fn test_filter_pip_outdated_none() {
let output = "[]";
let result = filter_pip_outdated(output);
assert!(result.contains("✓"));
assert!(result.contains("All packages up to date"));
}
+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))
}
}
}
+9 -7
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);
@@ -388,7 +389,7 @@ fn run_outdated(args: &[String], verbose: u8) -> Result<()> {
};
if filtered.trim().is_empty() {
println!("All packages up-to-date ✓");
println!("All packages up-to-date");
} else {
println!("{}", filtered);
}
@@ -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);
@@ -482,7 +484,7 @@ fn filter_pnpm_install(output: &str) -> String {
}
if result.is_empty() {
"ok ✓".to_string()
"ok".to_string()
} else {
result.join("\n")
}
+5 -5
View File
@@ -112,7 +112,7 @@ pub fn filter_prettier_output(output: &str) -> String {
// Check if all files are formatted
if files_to_format.is_empty() && output.contains("All matched files use Prettier") {
return "✓ Prettier: All files formatted correctly".to_string();
return "Prettier: All files formatted correctly".to_string();
}
// Check if files were written (write mode)
@@ -125,7 +125,7 @@ pub fn filter_prettier_output(output: &str) -> String {
if is_check_mode {
// Check mode: show files that need formatting
if files_to_format.is_empty() {
result.push_str("✓ Prettier: All files formatted correctly\n");
result.push_str("Prettier: All files formatted correctly\n");
} else {
result.push_str(&format!(
"Prettier: {} files need formatting\n",
@@ -146,7 +146,7 @@ pub fn filter_prettier_output(output: &str) -> String {
if files_checked > 0 {
result.push_str(&format!(
"\n✓ {} files already formatted\n",
"\n{} files already formatted\n",
files_checked - files_to_format.len()
));
}
@@ -154,7 +154,7 @@ pub fn filter_prettier_output(output: &str) -> String {
} else {
// Write mode: show what was formatted
result.push_str(&format!(
"✓ Prettier: {} files formatted\n",
"Prettier: {} files formatted\n",
files_to_format.len()
));
}
@@ -173,7 +173,7 @@ Checking formatting...
All matched files use Prettier code style!
"#;
let result = filter_prettier_output(output);
assert!(result.contains("✓ Prettier"));
assert!(result.contains("Prettier"));
assert!(result.contains("All files formatted correctly"));
}
+8 -8
View File
@@ -221,7 +221,7 @@ fn filter_prisma_generate(output: &str) -> String {
}
let mut result = String::new();
result.push_str("✓ Prisma Client generated\n");
result.push_str("Prisma Client generated\n");
if models > 0 || enums > 0 || types > 0 {
result.push_str(&format!(
@@ -283,7 +283,7 @@ fn filter_migrate_dev(output: &str) -> String {
let mut result = String::new();
if !migration_name.is_empty() {
result.push_str(&format!("🗃️ Migration: {}\n", migration_name));
result.push_str(&format!("Migration: {}\n", migration_name));
result.push_str("═══════════════════════════════════════\n");
}
@@ -303,7 +303,7 @@ fn filter_migrate_dev(output: &str) -> String {
result.push('\n');
if applied {
result.push_str("✓ Applied | Pending: 0\n");
result.push_str("Applied | Pending: 0\n");
}
result.trim().to_string()
@@ -360,9 +360,9 @@ fn filter_migrate_deploy(output: &str) -> String {
let mut result = String::new();
if errors.is_empty() {
result.push_str(&format!("✓ {} migration(s) deployed\n", deployed));
result.push_str(&format!("{} migration(s) deployed\n", deployed));
} else {
result.push_str("❌ Deployment failed:\n");
result.push_str("[FAIL] Deployment failed:\n");
for err in errors.iter().take(5) {
result.push_str(&format!(" {}\n", err));
}
@@ -390,7 +390,7 @@ fn filter_db_push(output: &str) -> String {
}
let mut result = String::new();
result.push_str("✓ Schema pushed to database\n");
result.push_str("Schema pushed to database\n");
if tables_added > 0 || columns_modified > 0 || dropped > 0 {
result.push_str(&format!(
@@ -460,7 +460,7 @@ import { PrismaClient } from '@prisma/client'
42 models, 18 enums, 890 types generated
"#;
let result = filter_prisma_generate(output);
assert!(result.contains("✓ Prisma Client generated"));
assert!(result.contains("Prisma Client generated"));
// Parser may not extract exact counts from this format, just check it doesn't crash
assert!(!result.contains("Prisma schema loaded"));
assert!(!result.contains("Start by importing"));
@@ -484,7 +484,7 @@ CREATE INDEX "session_status_idx" ON "Session"("status");
let result = filter_migrate_dev(output);
assert!(result.contains("20260128_add_sessions"));
assert!(result.contains("+ 1 table"));
assert!(result.contains("✓ Applied"));
assert!(result.contains("Applied"));
}
#[test]
+4 -4
View File
@@ -167,7 +167,7 @@ fn build_pytest_summary(summary: &str, _test_files: &[String], failures: &[Strin
let (passed, failed, skipped) = parse_summary_line(summary);
if failed == 0 && passed > 0 {
return format!("✓ Pytest: {} passed", passed);
return format!("Pytest: {} passed", passed);
}
if passed == 0 && failed == 0 {
@@ -198,13 +198,13 @@ fn build_pytest_summary(summary: &str, _test_files: &[String], failures: &[Strin
if first_line.starts_with("___") {
// Extract test name between ___
let test_name = first_line.trim_matches('_').trim();
result.push_str(&format!("{}. ❌ {}\n", i + 1, test_name));
result.push_str(&format!("{}. [FAIL] {}\n", i + 1, test_name));
} else if first_line.starts_with("FAILED") {
// Summary format: "FAILED tests/test_foo.py::test_bar - AssertionError"
let parts: Vec<&str> = first_line.split(" - ").collect();
if let Some(test_path) = parts.first() {
let test_name = test_path.trim_start_matches("FAILED ");
result.push_str(&format!("{}. ❌ {}\n", i + 1, test_name));
result.push_str(&format!("{}. [FAIL] {}\n", i + 1, test_name));
}
if parts.len() > 1 {
result.push_str(&format!(" {}\n", truncate(parts[1], 100)));
@@ -288,7 +288,7 @@ tests/test_foo.py ..... [100%]
=== 5 passed in 0.50s ==="#;
let result = filter_pytest_output(output);
assert!(result.contains("✓ Pytest"));
assert!(result.contains("Pytest"));
assert!(result.contains("5 passed"));
}
+15 -10
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,13 +126,13 @@ 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)
);
}
};
if diagnostics.is_empty() {
return "✓ Ruff: No issues found".to_string();
return "Ruff: No issues found".to_string();
}
let total_issues = diagnostics.len();
@@ -204,7 +209,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
if fixable_count > 0 {
result.push_str(&format!(
"\n💡 Run `ruff check --fix` to auto-fix {} issues\n",
"\n[hint] Run `ruff check --fix` to auto-fix {} issues\n",
fixable_count
));
}
@@ -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 {
@@ -257,7 +262,7 @@ pub fn filter_ruff_format(output: &str) -> String {
// Check if all files are formatted
if files_to_format.is_empty() && output_lower.contains("left unchanged") {
return "✓ Ruff format: All files formatted correctly".to_string();
return "Ruff format: All files formatted correctly".to_string();
}
let mut result = String::new();
@@ -265,7 +270,7 @@ pub fn filter_ruff_format(output: &str) -> String {
if output_lower.contains("would reformat") {
// Check mode: show files that need formatting
if files_to_format.is_empty() {
result.push_str("✓ Ruff format: All files formatted correctly\n");
result.push_str("Ruff format: All files formatted correctly\n");
} else {
result.push_str(&format!(
"Ruff format: {} files need formatting\n",
@@ -285,10 +290,10 @@ pub fn filter_ruff_format(output: &str) -> String {
}
if files_checked > 0 {
result.push_str(&format!("\n✓ {} files already formatted\n", files_checked));
result.push_str(&format!("\n{} files already formatted\n", files_checked));
}
result.push_str("\n💡 Run `ruff format` to format these files\n");
result.push_str("\n[hint] Run `ruff format` to format these files\n");
}
} else {
// Write mode or other output - show summary
@@ -323,7 +328,7 @@ mod tests {
fn test_filter_ruff_check_no_issues() {
let output = "[]";
let result = filter_ruff_check_json(output);
assert!(result.contains("✓ Ruff"));
assert!(result.contains("Ruff"));
assert!(result.contains("No issues found"));
}
@@ -369,7 +374,7 @@ mod tests {
fn test_filter_ruff_format_all_formatted() {
let output = "5 files left unchanged";
let result = filter_ruff_format(output);
assert!(result.contains("✓ Ruff format"));
assert!(result.contains("Ruff format"));
assert!(result.contains("All files formatted correctly"));
}
+5 -5
View File
@@ -34,10 +34,10 @@ pub fn run_err(command: &str, verbose: u8) -> Result<()> {
if filtered.is_empty() {
if output.status.success() {
rtk.push_str("✅ Command completed successfully (no errors)");
rtk.push_str("[ok] Command completed successfully (no errors)");
} else {
rtk.push_str(&format!(
"❌ Command failed (exit code: {:?})\n",
"[FAIL] Command failed (exit code: {:?})\n",
output.status.code()
));
let lines: Vec<&str> = raw.lines().collect();
@@ -228,7 +228,7 @@ fn extract_test_summary(output: &str, command: &str) -> String {
let mut output = String::new();
if !failures.is_empty() {
output.push_str("❌ FAILURES:\n");
output.push_str("[FAIL] FAILURES:\n");
for f in failures.iter().take(10) {
output.push_str(&format!(" {}\n", f));
}
@@ -239,13 +239,13 @@ fn extract_test_summary(output: &str, command: &str) -> String {
}
if !result.is_empty() {
output.push_str("📊 SUMMARY:\n");
output.push_str("SUMMARY:\n");
for r in &result {
output.push_str(&format!(" {}\n", r));
}
} else {
// Fallback: show last few lines
output.push_str("📊 OUTPUT (last 5 lines):\n");
output.push_str("OUTPUT (last 5 lines):\n");
let start = lines.len().saturating_sub(5);
for line in &lines[start..] {
if !line.trim().is_empty() {
+23 -22
View File
@@ -42,7 +42,7 @@ fn summarize_output(output: &str, command: &str, success: bool) -> String {
let mut result = Vec::new();
// Status
let status_icon = if success { "✅" } else { "❌" };
let status_icon = if success { "[ok]" } else { "[FAIL]" };
result.push(format!(
"{} Command: {}",
status_icon,
@@ -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 {
@@ -108,7 +109,7 @@ fn detect_output_type(output: &str, command: &str) -> OutputType {
}
fn summarize_tests(output: &str, result: &mut Vec<String>) {
result.push("📋 Test Results:".to_string());
result.push("Test Results:".to_string());
let mut passed = 0;
let mut failed = 0;
@@ -125,7 +126,7 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
passed += 1;
}
}
if lower.contains("failed") || lower.contains("✗") || lower.contains("fail") {
if lower.contains("failed") || lower.contains("[x]") || lower.contains("fail") {
if let Some(n) = extract_number(&lower, "failed") {
failed = n;
}
@@ -141,12 +142,12 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
}
}
result.push(format!(" ✅ {} passed", passed));
result.push(format!(" [ok] {} passed", passed));
if failed > 0 {
result.push(format!(" ❌ {} failed", failed));
result.push(format!(" [FAIL] {} failed", failed));
}
if skipped > 0 {
result.push(format!(" ⏭️ {} skipped", skipped));
result.push(format!(" skip {} skipped", skipped));
}
if !failures.is_empty() {
@@ -159,7 +160,7 @@ fn summarize_tests(output: &str, result: &mut Vec<String>) {
}
fn summarize_build(output: &str, result: &mut Vec<String>) {
result.push("🔨 Build Summary:".to_string());
result.push("Build Summary:".to_string());
let mut errors = 0;
let mut warnings = 0;
@@ -183,16 +184,16 @@ fn summarize_build(output: &str, result: &mut Vec<String>) {
}
if compiled > 0 {
result.push(format!(" 📦 {} crates/files compiled", compiled));
result.push(format!(" {} crates/files compiled", compiled));
}
if errors > 0 {
result.push(format!(" ❌ {} errors", errors));
result.push(format!(" [error] {} errors", errors));
}
if warnings > 0 {
result.push(format!(" ⚠️ {} warnings", warnings));
result.push(format!(" [warn] {} warnings", warnings));
}
if errors == 0 && warnings == 0 {
result.push(" ✅ Build successful".to_string());
result.push(" [ok] Build successful".to_string());
}
if !error_msgs.is_empty() {
@@ -205,7 +206,7 @@ fn summarize_build(output: &str, result: &mut Vec<String>) {
}
fn summarize_logs_quick(output: &str, result: &mut Vec<String>) {
result.push("📝 Log Summary:".to_string());
result.push("Log Summary:".to_string());
let mut errors = 0;
let mut warnings = 0;
@@ -222,14 +223,14 @@ fn summarize_logs_quick(output: &str, result: &mut Vec<String>) {
}
}
result.push(format!(" ❌ {} errors", errors));
result.push(format!(" ⚠️ {} warnings", warnings));
result.push(format!(" ℹ️ {} info", info));
result.push(format!(" [error] {} errors", errors));
result.push(format!(" [warn] {} warnings", warnings));
result.push(format!(" [info] {} info", info));
}
fn summarize_list(output: &str, result: &mut Vec<String>) {
let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
result.push(format!("📋 List ({} items):", lines.len()));
result.push(format!("List ({} items):", lines.len()));
for line in lines.iter().take(10) {
result.push(format!(" • {}", truncate(line, 70)));
@@ -240,7 +241,7 @@ fn summarize_list(output: &str, result: &mut Vec<String>) {
}
fn summarize_json(output: &str, result: &mut Vec<String>) {
result.push("📋 JSON Output:".to_string());
result.push("JSON Output:".to_string());
// Try to parse and show structure
if let Ok(value) = serde_json::from_str::<serde_json::Value>(output) {
@@ -269,7 +270,7 @@ fn summarize_json(output: &str, result: &mut Vec<String>) {
fn summarize_generic(output: &str, result: &mut Vec<String>) {
let lines: Vec<&str> = output.lines().collect();
result.push("📋 Output:".to_string());
result.push("Output:".to_string());
// First few lines
for line in lines.iter().take(5) {
+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 {
+6 -6
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();
@@ -1610,8 +1610,8 @@ match_command = "^make\\b"
let filters = make_filters(BUILTIN_TOML);
assert_eq!(
filters.len(),
47,
"Expected exactly 47 built-in filters, got {}. \
57,
"Expected exactly 57 built-in filters, got {}. \
Update this count when adding/removing filters in src/filters/.",
filters.len()
);
@@ -1668,11 +1668,11 @@ expected = "output line 1\noutput line 2"
let combined = format!("{}\n\n{}", BUILTIN_TOML, new_filter);
let filters = make_filters(&combined);
// All 47 existing filters still present + 1 new = 48
// All 57 existing filters still present + 1 new = 58
assert_eq!(
filters.len(),
48,
"Expected 48 filters after concat (47 built-in + 1 new)"
58,
"Expected 58 filters after concat (57 built-in + 1 new)"
);
// New filter is discoverable
+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();
}
+4 -3
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()))?;
@@ -267,13 +268,13 @@ fn print_risk_summary(content: &str) {
println!(" Filters: {}", filter_count);
if has_replace {
println!(" ⚠ Contains 'replace' rules (can rewrite output)");
println!(" [!] Contains 'replace' rules (can rewrite output)");
}
if has_match_output {
println!(" ⚠ Contains 'match_output' rules (can replace entire output)");
println!(" [!] Contains 'match_output' rules (can replace entire output)");
}
if has_dot_pattern {
println!(" ⚠ Contains catch-all pattern '.' (matches everything)");
println!(" [!] Contains catch-all pattern '.' (matches everything)");
}
if !has_replace && !has_match_output && !has_dot_pattern {
println!(" No high-risk patterns detected.");
+1 -1
View File
@@ -109,7 +109,7 @@ fn filter_tsc_output(output: &str) -> String {
if errors.is_empty() {
if output.contains("Found 0 errors") {
return "✓ TypeScript: No errors found".to_string();
return "TypeScript: No errors found".to_string();
}
return "TypeScript compilation completed".to_string();
}
+3 -3
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))
}
}
}
@@ -182,7 +182,7 @@ fn extract_failures_regex(output: &str) -> Vec<TestFailure> {
while i < lines.len() {
let line = lines[i];
if line.contains('✗') || line.contains("FAIL") {
if line.contains("[x]") || line.contains("FAIL") {
let mut error_lines = vec![line.to_string()];
i += 1;
+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();
+8 -5
View File
@@ -33,7 +33,7 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
let filename = extract_filename_from_output(&stderr, url, args);
let size = get_file_size(&filename);
let msg = format!(
"⬇️ {} ok | {} | {}",
"{} ok | {} | {}",
compact_url(url),
filename,
format_size(size)
@@ -42,9 +42,10 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
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);
let msg = format!("{} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -78,7 +79,7 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
let mut rtk_output = String::new();
if total > 20 {
rtk_output.push_str(&format!(
"⬇️ {} ok | {} lines | {}\n",
"{} ok | {} lines | {}\n",
compact_url(url),
total,
format_size(output.stdout.len() as u64)
@@ -89,7 +90,7 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
}
rtk_output.push_str(&format!("... +{} more lines", total - 10));
} else {
rtk_output.push_str(&format!("⬇️ {} ok | {} lines\n", compact_url(url), total));
rtk_output.push_str(&format!("{} ok | {} lines\n", compact_url(url), total));
for line in &lines {
rtk_output.push_str(&format!("{}\n", line));
}
@@ -104,9 +105,10 @@ 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);
let msg = format!("{} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -206,6 +208,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);