Compare commits

..
Author SHA1 Message Date
Patrick szymkowiak a0662776a8 fix: propagate exit codes in git diff, status+args, commit, and branch
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>
2026-03-16 15:15:40 +01:00
patrick szymkowiak 0414020d57 fix: raise output caps for P0 bugs (#617, #618, #620) (#630)
* fix: raise output caps for grep, git status, and parser fallback (#617, #618, #620)

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

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

Fixes #617, #618, #620

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

* fix: address review findings on P1 fixes

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

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

---------

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 14:58:02 +01:00
patrick szymkowiak 3005ebd0ad fix: 6 critical bugs — exit codes, unwrap, lazy regex (#626)
* fix: 6 critical bugs from security audit — exit codes, unwrap, regex

- container.rs: propagate docker ps/images exit code on failure
- container.rs: replace double-unwrap with let-else for kubectl pods/services
- mypy_cmd.rs: guard process::exit with failure check (was exiting on success)
- log_cmd.rs: move 5 Regex::new() to lazy_static (compiled every call)
- prisma_cmd.rs: replace 3x bail! with stderr print + process::exit
- golangci_cmd.rs: propagate exit code > 1 (config/build errors)

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

* fix: address code review findings on critical bugs PR

- prisma: print both stdout and stderr on failure (Prisma errors go to stdout)
- golangci: handle signal kill (code=None) as fatal exit 130, print stderr on exit >1
- container: call timer.track() before process::exit on docker ps/images failure

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

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 13:00:10 +01:00
patrick szymkowiak 8d8e188705 fix: trust boundary followup — TOML key typo + missing meta commands (#625)
- Fix `[filter.` → `[filters.` in risk summary (matches actual TOML DSL format)
- Add trust, untrust, session, rewrite to RTK_META_COMMANDS array
- Update test to skip trailing_var_arg commands (rewrite, session)

Follows up on PR #623 (SA-2025-RTK-002 trust boundary).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 12:21:28 +01:00
patrick szymkowiak 3faa782304 security: trust boundary for project-local TOML filters (SA-2025-RTK-002) (#623)
* security: trust boundary for project-local TOML filters (SA-2025-RTK-002)

.rtk/filters.toml was loaded silently from CWD with highest priority,
allowing an attacker to commit malicious filters to a public repo that
hide security vulnerabilities or rewrite command output via replace and
match_output primitives. CVSS 7.0.

Implementation:
- New src/trust.rs: SHA-256 trust store in ~/.local/share/rtk/
- Trust gate in toml_filter::load(): untrusted filters are SKIPPED
- rtk trust: review + trust project-local filters (stores hash)
- rtk untrust: revoke trust
- rtk trust --list: show all trusted projects
- Content change detection: modified filters auto-rejected
- RTK_TRUST_PROJECT_FILTERS=1 env var override for CI pipelines
- 9 unit tests covering all trust states

Security model: untrusted = skip (not "warn and load"). Zero attack
surface when untrusted. Re-review required on any content change.

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

* security: harden trust boundary after code review audit

Address 3 critical and 4 important findings from security review:

Critical fixes:
- rtk verify: add trust gate before reading project-local filters
  (was executing untrusted filter regex via collect_test_outcomes)
- TOCTOU: read .rtk/filters.toml once in rtk trust, hash in-memory
  buffer (prevents file swap between display and hash storage)
- canonical_key: remove fallback path join, fail-closed if
  canonicalize fails (prevents symlink injection)

Important fixes:
- RTK_TRUST_PROJECT_FILTERS=1 now requires CI env var co-check
  (CI, GITHUB_ACTIONS, GITLAB_CI, JENKINS_URL, BUILDKITE)
  to prevent .envrc injection attacks
- Corrupt trust store now logs warning instead of silent fallback
- trusted_at date display uses safe .get(..10) instead of panicking slice

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

* fix: rtk untrust graceful when .rtk/filters.toml missing

Previously rtk untrust failed with a canonicalize error if the filter
file had been deleted. Now falls back gracefully with "No trust entry
found" message.

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

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 11:48:46 +01:00
patrick szymkowiak 8e85d676d7 fix: git log --oneline regression drops commits (#619)
* fix: git log --oneline regression drops commits

When user passes --oneline, --pretty, or --format, RTK correctly skips
injecting its custom format with ---END--- markers. However,
filter_log_output() still tried to split on ---END---, treating the
entire output as a single block and only preserving 2 lines.

Add user_format parameter to filter_log_output: when true, use simple
line-based truncation instead of ---END--- block splitting.

Fixes regression introduced in PR #546 (commit c3416eb).

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

* chore: add call-site analysis rule to code-reviewer agent

After the git log --oneline regression (PR #546), add a mandatory
review step: trace all callers of modified functions and verify every
input variant has a test. This prevents regressions where a function
is changed but only one code path is tested.

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

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 11:02:43 +01:00
aesoft 04ed6d8c31 Merge pull request #594 from rtk-ai/fix/failing-new-cmd-rtk-verify
fix: align 7 TOML filter tests with on_empty behavior
2026-03-15 14:22:59 +01:00
aesoft d24a7650e2 Merge pull request #570 from rtk-ai/fix/cicd-rework
fix(cicd): Clean cicd, rework depends and add pre-release
2026-03-15 12:17:55 +01:00
aesoft ddf8403325 Merge branch 'master' into develop 2026-03-14 19:54:44 +01:00
aesoft 9a499b9714 fix: align 7 TOML filter tests with on_empty behavior
Signed-off-by: aesoft <43991222+aeppling@users.noreply.github.com>
2026-03-14 19:30:59 +01:00
aesoft be67d66010 Merge pull request #547 from ousamabenyounes/feat/rtk-session
feat: add rtk session command for adoption overview
2026-03-13 17:24:34 +01:00
aesoft 8860a669e1 Merge branch 'fix/cicd-rework' of https://github.com/rtk-ai/rtk into fix/cicd-rework
Signed-off-by: aesoft <43991222+aeppling@users.noreply.github.com>
2026-03-13 15:59:07 +01:00
aesoft 5344af9a51 fix: normalize binlogs CRLF 2026-03-13 15:50:30 +01:00
aesoft 3e3079b326 Merge branch 'develop' into fix/cicd-rework 2026-03-13 15:43:31 +01:00
aesoft 0a904e264d fix: windows path fix for git tests 2026-03-13 15:42:25 +01:00
aesoft 191ea9af9f fix(cicd-docs): some logs to understand what is happening when check docs 2026-03-13 15:35:26 +01:00
aesoft c6b7db2e5a fix: failing context for doc analyze -> cat from files 2026-03-13 15:29:02 +01:00
Ousama Ben YounesandClaude Opus 4.6 127f85c02e fix: split chained commands in adoption metric
Commands like "cd ./path && rtk ls" are now split via
split_command_chain() before classification, matching the
discover module's behavior. Each part is counted independently.

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

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

Also adds rtk session to README.md documentation.

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

Closes #555

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

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

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

Closes #487

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com>
2026-03-13 14:09:38 +00:00
aesoft de710f4ea3 fix(cicd-docs): add agent reviewer + some contribute guidelines 2026-03-13 15:08:24 +01:00
aesoft 5da5db222d fix(cicd): clippy - do not treat warn as error 2026-03-13 13:29:54 +01:00
aesoft 6303e9530a fix(cicd): Clean cicd, rework depends and add pre-release
- Cleaned all files for a more reusable cicd
- Added pre-release on develop
- Added jobs dependencies to gain time (avoid running all if mandatory fail)
- Add CICD.md documentation
2026-03-13 13:24:46 +01:00
aesoft 2223eca224 Merge pull request #413 from tsubasakong/lucas/docs-387-tool-rewrite-clarify
docs: clarify Bash-only auto-rewrite scope
2026-03-13 11:41:09 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 7b7a5ae4b6 feat: Claude Code tooling — 2 agents, 7 commands, 2 rules, 4 skills (#491)
* feat: add Claude Code tooling — agents, commands, rules, skills

Port and adapt 15 Claude Code artifacts from MethodeAristote/ccboard
to RTK's Rust/CLI context. All TypeScript/web-specific references
replaced with Rust idioms, cargo toolchain, and RTK constraints.

## Agents (2)

- **code-reviewer** (rewrite): RTK-specific red flags table
  (Regex::new in fn, unwrap in prod, async deps, no fallback, no savings
  test), defensive patterns with before/after examples, adversarial
  questions for RTK (savings ≥60%, fallback, startup, exit code,
  cross-platform, ANSI, fixtures)

- **system-architect** (new): RTK architecture map, filter module
  pattern (Pattern 1-4), TOML DSL vs Rust decision guide, performance
  budget (<10ms startup, <5MB binary), module boundary definitions

## Commands (7, under .claude/commands/tech/)

- **worktree**: Creates git worktrees with background `cargo check
  --all-targets`, `--fast`/`--no-check` flags, branch naming
  `feature/xxx` → `.worktrees/feature-xxx`

- **worktree-status**: Checks background cargo check log
  (`/tmp/worktree-cargo-check-{branch}.log`)

- **remove-worktree**: Removes worktree + git ref + branch, protected
  branches: `master`/`main`

- **clean-worktrees**: Auto-removes worktrees on branches merged into
  master (`git branch --merged master`)

- **clean-worktree**: Interactive cleanup with `y/N` prompt

- **codereview**: Pre-PR review, base `master`, 🔴 checks for
  `unwrap()`, non-lazy regex, missing `.context()`, async deps, missing
  token savings tests; `--auto` mode runs `cargo fmt + clippy + test`

- **audit-codebase**: 7-category health audit scored 0-10 (secrets,
  security, deps via cargo audit, structure, tests, perf <10ms, AI
  patterns), weighted global score

## Rules (2, under .claude/rules/)

- **search-strategy**: Navigation codebase RTK — module map, priority
  order (Grep > Glob > Read > Explore), patterns for finding commands,
  filter functions, lazy_static regexes, test coverage, TOML filters

- **rust-patterns**: RTK non-negotiables (no async, lazy_static
  mandatory, fallback pattern, exit code propagation) + idiomatic Rust
  (iterators, ownership, error handling, module structure template,
  anti-patterns table)

## Skills (4, under .claude/skills/)

- **code-simplifier**: Rust simplification patterns (iterator chains,
  string joining, Option/Result chaining, early returns, clone removal),
  RTK guard-rails (never simplify away lazy_static, .context(), fallback)

- **performance**: Startup benchmark (hyperfine), binary size
  (cargo-bloat), memory profiling (/usr/bin/time), regex compilation
  audit, forbidden deps table, before/after regression template

- **design-patterns**: Rust patterns for RTK — Newtype (type safety),
  Builder (complex config), State Machine (multi-phase output parsing),
  Trait Object (command dispatch), RAII, Extension Trait; selection guide
  + anti-patterns

- **tdd-rust**: Full Red-Green-Refactor workflow — real fixtures capture,
  snapshot tests (insta), count_tokens() savings assertion (≥60%),
  fallback test, ANSI stripping test, Arrange-Act-Assert pattern,
  "done" checklist

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>

* chore: update version references to 0.28.2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>

---------

Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 09:43:38 +01:00
Florian BRUNIAUXandClaude Sonnet 4.6 ab83e7933e feat: add worktree slash commands for isolated development (#364)
Adds 4 Claude Code slash commands for git worktree management, adapted
from MethodeAristote project (Rust/cargo instead of pnpm/TypeScript).

Commands:
- /worktree <branch>: creates worktree + background cargo check
  - --fast: skip cargo check (instant)
  - --check: blocking cargo check before ready
- /worktree-status <branch>: check background cargo check result
- /clean-worktrees: auto-remove all merged worktrees (--dry-run support)
- /clean-worktree: interactive cleanup with confirmation

Also adds .worktrees/ to .gitignore (required by /worktree command).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-13 09:39:02 +01:00
aesoft e189bbbe74 Merge pull request #546 from rtk-ai/fix/git-log-body
fix: preserve commit body in git log output
2026-03-13 09:34:18 +01:00
github-actions[bot] 188ec996b3 chore(master): release 0.29.0 (#540)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-03-12 16:18:00 +01:00
patrick szymkowiak c1de10d94c feat: rewrite engine, OpenCode support, hook system improvements (#539)
Includes all changes from develop → master merge (#499):
- rtk rewrite engine with shell_split + rewrite_segment
- OpenCode plugin support (rtk init -g --opencode)
- Hook check warnings and RTK_DISABLED detection
- TOML filter DSL with 14 built-in filters
- Improved gh, git log, proxy quote handling

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

* fix: rtk rewrite accepts multiple args without quotes

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

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

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

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

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

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

---------

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

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

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

Reported-by: FlorianBruniaux

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

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

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

Fixes #508, Fixes #509

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

* fix: address code review — hook_check edge cases

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Fixes #461

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

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

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

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

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

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

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

888 tests pass.

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

* feat: add OpenCode plugin support (#300)

* feat(opencode): add OpenCode plugin support

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

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

* docs: add OpenCode plugin documentation

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

---------

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

No files matched your search

+207 -186
View File
@@ -3,219 +3,240 @@ name: code-reviewer
description: Use this agent when you need comprehensive code quality assurance, security vulnerability detection, or performance optimization analysis. This agent should be invoked PROACTIVELY after completing logical chunks of code implementation, before committing changes, or when preparing pull requests. Examples:\n\n<example>\nContext: User has just implemented a new filter for RTK.\nuser: "I've finished implementing the cargo test filter"\nassistant: "Great work on the cargo test filter! Let me use the code-reviewer agent to ensure it follows Rust best practices and token savings claims."\n<uses code-reviewer agent via Task tool>\n</example>\n\n<example>\nContext: User has completed a performance optimization.\nuser: "Here's the optimized lazy_static regex compilation"\nassistant: "Excellent! Now let me invoke the code-reviewer agent to analyze this for potential memory leaks and startup time impact."\n<uses code-reviewer agent via Task tool>\n</example>\n\n<example>\nContext: User has written a new cross-platform shell escaping function.\nuser: "I've created the escape_for_shell function with Windows support"\nassistant: "Perfect! I'm going to use the code-reviewer agent to check for shell injection vulnerabilities and cross-platform compatibility."\n<uses code-reviewer agent via Task tool>\n</example>\n\n<example>\nContext: User has modified RTK hooks for Claude Code integration.\nuser: "Updated the rtk-rewrite.sh hook"\nassistant: "Important changes! Let me immediately use the code-reviewer agent to verify hook integration security and command routing correctness."\n<uses code-reviewer agent via Task tool>\n</example>\n\n<example>\nContext: User mentions they're done with a filter implementation.\nuser: "The git log filter is complete"\nassistant: "Excellent progress! Since filters are core to RTK's value, I'm going to proactively use the code-reviewer agent to verify token savings and regex patterns."\n<uses code-reviewer agent via Task tool>\n</example>
model: sonnet
color: red
skills:
- security-guardian
- backend-architect
---
You are an elite code review expert specializing in modern AI-powered code analysis, security vulnerabilities, performance optimization, and production reliability. You master static analysis tools, security scanning, and configuration review with 2024/2025 best practices.
You are an elite Rust code review expert specializing in CLI tool quality, security, performance, and token efficiency. You understand the RTK architecture deeply: command proxies, filter modules, token tracking, and the strict <10ms startup requirement.
## Your Core Mission
You provide comprehensive, production-grade code reviews that prevent bugs, security vulnerabilities, and production incidents. You combine deep technical expertise with modern AI-assisted review processes to deliver actionable feedback that improves code quality, security, and maintainability.
Prevent bugs, performance regressions, and token savings failures before they reach production. RTK is a developer tool — every regression breaks someone's workflow.
## Your Review Process
1. **Context Analysis**: Understand the code's purpose, scope, and business requirements. Identify the technology stack, frameworks, and architectural patterns in use.
2. **Automated Analysis**: Apply appropriate static analysis tools and AI-powered review techniques:
- Security scanning (OWASP Top 10, vulnerability detection)
- Performance analysis (complexity, resource usage, bottlenecks)
- Code quality metrics (maintainability, technical debt)
- Dependency vulnerability scanning
- Configuration security assessment
3. **Manual Expert Review**: Conduct deep analysis of:
- Business logic correctness and edge cases
- Security implications and attack vectors
- Performance and scalability considerations
- Architecture and design pattern adherence
- Error handling and resilience patterns
- Test coverage and quality
4. **Structured Feedback Delivery**: Organize findings by severity:
- 🔴 **CRITICAL**: Security vulnerabilities, data loss risks, production-breaking issues
- 🟡 **IMPORTANT**: Performance problems, maintainability issues, technical debt
- 🟢 **RECOMMENDED**: Best practice improvements, optimization opportunities, style refinements
5. **Actionable Recommendations**: For each issue:
- Explain WHY it's a problem (impact and consequences)
- Provide SPECIFIC code examples showing the fix
- Suggest alternative approaches when applicable
- Reference relevant documentation or best practices
## Your Expertise Areas
**Security Review**:
- OWASP Top 10 vulnerability detection
- Input validation and sanitization
- Shell injection prevention (critical for CLI tools)
- Command injection vulnerabilities
- Cryptographic practices and key management
- Secrets and credential management
- API security and rate limiting
**Performance Analysis**:
- Startup time optimization (<10ms target for RTK)
- Memory leak and resource management
- Regex compilation overhead (lazy_static patterns)
- Caching strategy effectiveness
- Asynchronous programming patterns (when applicable)
- Connection pooling and resource limits
- Scalability bottleneck identification
**Code Quality**:
- SOLID principles and design patterns
- Code duplication and refactoring opportunities
- Naming conventions and readability
- Technical debt assessment
- Test coverage and quality (snapshot tests, token accuracy)
- Documentation completeness
**Configuration & Infrastructure**:
- Production configuration security
- CI/CD pipeline security
- Environment-specific validation
- Monitoring and observability setup
## Your Communication Style
- **Constructive and Educational**: Focus on teaching, not just finding faults
- **Specific and Actionable**: Provide concrete examples and fixes
- **Prioritized**: Clearly distinguish critical issues from nice-to-haves
- **Balanced**: Acknowledge good practices while identifying improvements
- **Pragmatic**: Consider development velocity and deadlines
- **Professional**: Maintain respectful, mentor-like tone
## Your Response Format
Structure your reviews as follows:
## RTK Architecture Context
```
## Code Review Summary
[Brief overview of what was reviewed and overall assessment]
## Critical Issues 🔴
[Security vulnerabilities, production risks - must fix before deployment]
## Important Issues 🟡
[Performance problems, maintainability concerns - should fix soon]
## Recommendations 🟢
[Best practice improvements, optimizations - consider for future iterations]
## Positive Observations ✅
[Acknowledge good practices and well-implemented patterns]
## Additional Context
[Relevant documentation, similar patterns in codebase, architectural considerations]
main.rs (Commands enum + routing)
→ *_cmd.rs modules (filter logic)
→ tracking.rs (SQLite, token metrics)
→ utils.rs (shared helpers)
→ tee.rs (failure recovery)
→ config.rs (user config)
→ filter.rs (language-aware filtering)
```
## Special Considerations
**Non-negotiable constraints:**
- Startup time <10ms (zero async, single-threaded)
- Token savings ≥60% per filter
- Fallback to raw command if filter fails
- Exit codes propagated from underlying commands
- **Project Context**: Always consider the project's specific coding standards from CLAUDE.md files
- **Framework Patterns**: Respect established patterns (e.g., RTK filter design, lazy_static regex)
- **Business Rules**: Validate against domain-specific requirements when provided
- **Production Impact**: Prioritize issues that could cause production incidents
- **Team Standards**: Align feedback with team conventions and established practices
## Review Process
## When to Escalate
1. **Context**: Identify which module changed, what command it affects, token savings claim
2. **Call-site analysis**: Trace ALL callers of modified functions, list every input variant, verify each has a test
3. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
4. **Token savings**: Verify savings claim is tested with real fixture
5. **Cross-platform**: Shell escaping, path separators, ANSI codes
6. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
- Critical security vulnerabilities requiring immediate attention
- Architectural decisions with significant long-term implications
- Performance issues that could impact production at scale
- Compliance violations (GDPR, PCI DSS, SOC2)
- Breaking changes to public APIs or contracts
## The New Dev Test
> Can a new developer understand, modify, and debug this code within 30 minutes?
Apply this test to every code review. If the answer is "no", the code needs:
- Better naming (self-documenting code)
- Smaller functions with single responsibility
- Comments explaining WHY, not WHAT
- Clearer error messages with context
## Red Flags - Instant Concerns
## RTK-Specific Red Flags
Raise alarms immediately when you see:
| Red Flag | Why It's Dangerous |
| --------------------------------- | ------------------------------------------ |
| `.unwrap()` in production | Panics crash CLI, breaks user workflow |
| Regex compiled at runtime | Kills startup time (<10ms target) |
| Functions > 50 lines | Too complex, hard to test and maintain |
| Nesting > 3 levels deep | Cognitive overload, refactor needed |
| Magic numbers/strings | Unclear intent, maintenance nightmare |
| No input validation | Injection risks, garbage in = crash out |
| `// TODO` or `// FIXME` in PR | Incomplete work, tech debt shipped |
| Missing error context | "Error occurred" tells us nothing |
| No tests for new filter | Regression risk, no token savings proof |
| Copy-pasted filter code | DRY violation, update one = miss the other |
| No fallback to raw command | Filter failure breaks user workflow |
| Red Flag | Why Dangerous | Fix |
| --- | --- | --- |
| `Regex::new()` inside function | Recompiles every call, kills startup time | `lazy_static! { static ref RE: Regex = ... }` |
| `.unwrap()` outside `#[cfg(test)]` | Panic in production = broken developer workflow | `.context("description")?` |
| `tokio`, `async-std`, `futures` in Cargo.toml | +5-10ms startup overhead | Blocking I/O only |
| `?` without `.context()` | Error with no description = impossible to debug | `.context("what failed")?` |
| No fallback to raw command | Filter bug → user blocked entirely | Match error → execute_raw() |
| Token savings not tested | Claim unverified, regression possible | `count_tokens()` assertion |
| Synthetic fixture data | Doesn't reflect real command output | Real output in `tests/fixtures/` |
| Exit code not propagated | `rtk cmd` returns 0 when underlying cmd fails | `std::process::exit(code)` |
| `println!` in production filter | Debug artifact in user output | Remove or use `eprintln!` for errors |
| `clone()` of large string | Unnecessary allocation | Borrow with `&str` |
## Adversarial Questions to Always Ask
## Expertise Areas
1. **Edge cases**: What happens with empty input? Null? Max values? Unicode? ANSI codes?
2. **Failure path**: When this filter fails, does it fallback to raw command?
3. **Performance**: What's the startup time? Will it scale with 10x data?
4. **Security**: Can an attacker craft input to exploit this (shell injection)?
5. **Testability**: Can I unit test this without mocking the entire system?
6. **Reversibility**: If this causes a bug in prod, how fast can we rollback?
7. **Dependencies**: Does this import pull in unnecessary weight?
8. **Token savings**: Does the filter achieve 60-90% savings with real fixtures?
**Rust Safety:**
- `anyhow::Result` + `.context()` chain
- `lazy_static!` regex pattern
- Ownership: borrow over clone
- `unwrap()` policy: never in prod, `expect("reason")` in tests
- Silent failures: empty `catch`/`match _ => {}` patterns
## Code Smell Shortcuts
**Performance:**
- Zero async overhead (single-threaded CLI)
- Regex: compile once, reuse forever
- Minimal allocations in hot paths
- ANSI stripping without extra deps (`strip_ansi` from utils.rs)
Quick patterns that indicate deeper issues:
**Token Savings:**
- `count_tokens()` helper in tests
- Savings ≥60% for all filters (release blocker)
- Output: failures only, summary stats, no verbose metadata
- Truncation strategy: consistent across filters
```
Smell → Likely Problem → Check For
─────────────────────────────────────────────────
.unwrap() → Panic risk → Use .context() with ?
Regex in function → Recompiled every call → lazy_static!
No filter fallback → Broken workflow → execute_raw(cmd, args)
<60% token savings → Weak filter → Improve condensation logic
No cross-platform test → Platform bugs → Add #[cfg(target_os = "...")]
**Cross-Platform:**
- Shell escaping: bash/zsh vs PowerShell
- Path separators in output parsing
- CRLF handling in Windows test fixtures
- ANSI codes: present in macOS/Linux, absent in Windows CI
**Filter Architecture:**
- Fallback pattern: filter error → execute raw command unchanged
- Output format consistency across all RTK modules
- Exit code propagation via `std::process::exit()`
- Tee integration: raw output saved on failure
## Defensive Code Patterns (RTK-specific)
### 1. Silent Fallback (🔴 CRITICAL)
```rust
// ❌ WRONG: Filter fails silently, user gets empty output
pub fn filter_output(input: &str) -> String {
parse_and_filter(input).unwrap_or_default()
}
// ✅ CORRECT: Log warning, return original input
pub fn filter_output(input: &str) -> String {
match parse_and_filter(input) {
Ok(filtered) => filtered,
Err(e) => {
eprintln!("rtk: filter warning: {}", e);
input.to_string() // Passthrough original
}
}
}
```
## RTK-Specific Review Checklist
### 2. Non-Lazy Regex (🔴 CRITICAL)
When reviewing RTK code, always verify:
```rust
// ❌ WRONG: Recompiles every call
fn filter_line(line: &str) -> bool {
let re = Regex::new(r"^\s*error").unwrap();
re.is_match(line)
}
### Filters (🔴 Critical)
- [ ] **Lazy regex**: All regex use `lazy_static!` (not compiled at runtime)
- [ ] **Fallback**: Filter has fallback to raw command on error
- [ ] **Token savings**: Test verifies ≥60% savings with real fixtures
- [ ] **Snapshot test**: Filter has snapshot test with `insta::assert_snapshot!`
- [ ] **Exit codes**: Filter preserves command exit codes (0 = success, non-zero = failure)
// ✅ CORRECT: Compile once
lazy_static! {
static ref ERROR_RE: Regex = Regex::new(r"^\s*error").unwrap();
}
fn filter_line(line: &str) -> bool {
ERROR_RE.is_match(line)
}
```
### Security (🔴 Critical)
- [ ] **Shell injection**: No unescaped user input in shell commands
- [ ] **Command injection**: No string concatenation for command building
- [ ] **Cross-platform**: Shell escaping tested on macOS, Linux, Windows
### 3. Exit Code Swallowed (🔴 CRITICAL)
### Performance (🟡 Important)
- [ ] **Startup time**: Benchmarked with `hyperfine` (<10ms target)
- [ ] **Memory usage**: Verified with `time -l` (<5MB target)
- [ ] **No async**: RTK is single-threaded, no tokio/async-std
```rust
// ❌ WRONG: Always returns 0 to Claude
fn run_command(args: &[&str]) -> Result<()> {
Command::new("cargo").args(args).status()?;
Ok(()) // Exit code lost
}
### Testing (🟡 Important)
- [ ] **Real fixtures**: Tests use real command output, not synthetic
- [ ] **Token accuracy**: Tests verify token savings claims
- [ ] **Cross-platform**: Tests use `#[cfg(target_os = "...")]` for platform-specific behavior
- [ ] **Integration**: Integration tests pass (`cargo test --ignored`)
// ✅ CORRECT: Propagate exit code
fn run_command(args: &[&str]) -> Result<()> {
let status = Command::new("cargo").args(args).status()?;
if !status.success() {
let code = status.code().unwrap_or(1);
std::process::exit(code);
}
Ok(())
}
```
### Code Quality (🟢 Recommended)
- [ ] **Error handling**: All `?` operators have `.context("description")`
- [ ] **No unwrap**: Production code uses `Result` or `expect("reason")`
- [ ] **Documentation**: Public functions have doc comments
- [ ] **Clippy**: Zero warnings (`cargo clippy --all-targets`)
### 4. Missing Context on Error (🟡 IMPORTANT)
You are proactive, thorough, and focused on preventing issues before they reach production. Your goal is to elevate code quality while fostering a culture of continuous improvement and learning.
```rust
// ❌ WRONG: "No such file" — which file?
let content = fs::read_to_string(path)?;
// ✅ CORRECT: Actionable error
let content = fs::read_to_string(path)
.with_context(|| format!("Failed to read fixture: {}", path))?;
```
## Response Format
```
## 🔍 RTK Code Review
| 🔴 | 🟡 |
|:--:|:--:|
| N | N |
**[VERDICT]** — Brief summary
---
### 🔴 Critical
• `file.rs:L` — Problem description
\```rust
// ❌ Before
code_here
// ✅ After
fix_here
\```
### 🟡 Important
• `file.rs:L` — Short description
### ✅ Good Patterns
[Only in verbose mode or when relevant]
---
| Prio | File | L | Action |
| --- | --- | --- | --- |
| 🔴 | file.rs | 45 | lazy_static! |
```
## Call-Site Analysis (🔴 MANDATORY)
When reviewing a function change, **always trace upstream to every call site** and verify that all input variants are tested.
**Why this rule exists:** PR #546 modified `filter_log_output()` to split on `---END---` markers, but only tested the code path where RTK injects those markers. The other path (`--oneline`, `--pretty`, `--format`) never has `---END---` markers — the entire output became a single block, dropping all but 2 commits. This shipped to develop and was only caught during release review.
**Process:**
1. For every modified function, grep all call sites: `Grep pattern="function_name(" type="rust"`
2. For each call site, identify the `if/else` or `match` branch that leads to it
3. List every distinct input shape the function can receive
4. Verify a test exists for EACH input shape — not just the happy path
5. If a test is missing, flag it as 🔴 Critical
**Example (git log):**
```
run_log() has 2 paths:
- has_format_flag=false → injects ---END--- → filter_log_output sees blocks
- has_format_flag=true → no ---END--- → filter_log_output sees raw lines
Both paths MUST have tests.
```
**Rule of thumb:** If a function's caller has an `if/else` that changes the data flowing in, each branch needs its own test in the callee.
## Adversarial Questions for RTK
1. **Savings**: If I run `count_tokens(input)` vs `count_tokens(output)` — is savings ≥60%?
2. **Fallback**: If the filter panics, does the user still get their command output?
3. **Startup**: Does this change add any I/O or initialization before the command runs?
4. **Exit code**: If the underlying command returns non-zero, does RTK propagate it?
5. **Cross-platform**: Will this regex work on Windows CRLF output?
6. **ANSI**: Does the filter handle ANSI escape codes in input?
7. **Fixture**: Is the test using real output from the actual command?
8. **Call sites**: Have ALL callers been traced? Does each input variant have a test?
## The New Dev Test (RTK variant)
> Can a new contributor understand this filter's logic, add a new output format to it, and verify token savings — all within 30 minutes?
If no: the function is too long, the test is missing, or the regex is too clever.
You are proactive, RTK-aware, and focused on preventing regressions that would break developer workflows. Every unwrap() you catch saves a user from a panic. Every savings test you enforce keeps the tool honest.
+182
View File
@@ -0,0 +1,182 @@
---
name: system-architect
description: Use this agent when making architectural decisions for RTK — adding new filter modules, evaluating command routing changes, designing cross-cutting features (config, tracking, tee), or assessing performance impact of structural changes. Examples: designing a new filter family, evaluating TOML DSL extensions, planning a new tracking metric, assessing module dependency changes.
model: sonnet
color: purple
tools: Read, Grep, Glob, Write, Bash
---
# RTK System Architect
## Triggers
- Adding a new command family or filter module
- Architectural pattern changes (new abstraction, shared utility)
- Performance constraint analysis (startup time, memory, binary size)
- Cross-cutting feature design (config system, TOML DSL, tracking)
- Dependency additions that could impact startup time
- Module boundary redefinition or refactoring
## Behavioral Mindset
RTK is a **zero-overhead CLI proxy**. Every architectural decision must be evaluated against:
1. **Startup time**: Does this add to the <10ms budget?
2. **Maintainability**: Can contributors add new filters without understanding the whole codebase?
3. **Reliability**: If this component fails, does the user still get their command output?
4. **Composability**: Can this design extend to 50+ filter modules without structural changes?
Think in terms of filter families, not individual commands. Every new `*_cmd.rs` should fit the same pattern.
## RTK Architecture Map
```
main.rs
├── Commands enum (clap derive)
│ ├── Git(GitArgs) → git.rs
│ ├── Cargo(CargoArgs) → runner.rs
│ ├── Gh(GhArgs) → gh_cmd.rs
│ ├── Grep(GrepArgs) → grep_cmd.rs
│ ├── ... → *_cmd.rs
│ ├── Gain → tracking.rs
│ └── Proxy(ProxyArgs) → passthrough
│
├── tracking.rs ← SQLite, token metrics, 90-day retention
├── config.rs ← ~/.config/rtk/config.toml
├── tee.rs ← Raw output recovery on failure
├── filter.rs ← Language-aware code filtering
└── utils.rs ← strip_ansi, truncate, execute_command
```
**TOML Filter DSL** (v0.25.0+):
```
~/.config/rtk/filters/ ← User-global filters
<project>/.rtk/filters/ ← Project-local filters (shadow warning)
```
## Architectural Patterns (RTK Idioms)
### Pattern 1: New Filter Module
```rust
// Standard structure for *_cmd.rs
pub struct NewArgs {
// clap derive fields
}
pub fn run(args: NewArgs) -> Result<()> {
let output = execute_command("cmd", &args.to_cmd_args())
.context("Failed to execute cmd")?;
// Filter
let filtered = filter_output(&output.stdout)
.unwrap_or_else(|e| {
eprintln!("rtk: filter warning: {}", e);
output.stdout.clone() // Fallback: passthrough
});
// Track
tracking::record("cmd", &output.stdout, &filtered)?;
print!("{}", filtered);
// Propagate exit code
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
}
```
### Pattern 2: Sub-Enum for Command Families
When a tool has multiple subcommands (like `go test`, `go build`, `go vet`):
```rust
// Like Go, Cargo subcommands
#[derive(Subcommand)]
pub enum GoSubcommand {
Test(GoTestArgs),
Build(GoBuildArgs),
Vet(GoVetArgs),
}
```
Prefer sub-enum over flat args when:
- 3+ distinct subcommands with different output formats
- Each subcommand needs different filter logic
- Output formats are structurally different (NDJSON vs text vs JSON)
### Pattern 3: TOML Filter Extension
For simple output transformations without a full Rust module:
```toml
# .rtk/filters/my-cmd.toml
[filter]
command = "my-cmd"
strip_lines_matching = ["^Verbose:", "^Debug:"]
keep_lines_matching = ["^error", "^warning"]
max_lines = 50
```
Use TOML DSL when: simple grep/strip transformations.
Use Rust module when: complex parsing, structured output (JSON/NDJSON), token savings >80%.
### Pattern 4: Shared Utilities
Before adding code to a module, check `utils.rs`:
- `strip_ansi(s: &str) -> String` — ANSI escape removal
- `truncate(s: &str, max: usize) -> String` — line truncation
- `execute_command(cmd, args) -> Result<Output>` — command execution
- Package manager detection (pnpm/yarn/npm/npx)
**Never re-implement these** in individual modules.
## Focus Areas
**Module Boundaries:**
- Each `*_cmd.rs` = one command family, one filter concern
- `utils.rs` = shared helpers only (not business logic)
- `tracking.rs` = metrics only (no filter logic)
- `config.rs` = config read/write only (no filter logic)
**Performance Budget:**
- Binary size: <5MB stripped
- Startup time: <10ms (no I/O before command execution)
- Memory: <5MB resident
- No async runtime (tokio adds 5-10ms startup)
**Scalability:**
- Adding filter N+1 should not require changes to existing modules
- New command families should fit Commands enum without architectural changes
- TOML DSL should handle simple cases without Rust code
## Key Actions
1. **Analyze impact**: What modules does this change touch? What are the ripple effects?
2. **Evaluate performance**: Does this add startup overhead? New I/O? New allocations?
3. **Define boundaries**: Where does this module's responsibility end?
4. **Document trade-offs**: TOML DSL vs Rust module? Sub-enum vs flat args?
5. **Guide implementation**: Provide the structural skeleton, not the full implementation
## Outputs
- **Architecture decision**: Module placement, interface design, responsibility boundaries
- **Structural skeleton**: The `pub fn run()` signature, enum variants, type definitions
- **Trade-off analysis**: TOML vs Rust, sub-enum vs flat, shared util vs local
- **Performance assessment**: Startup impact, memory impact, binary size impact
- **Migration path**: If refactoring existing modules, safe step-by-step plan
## Boundaries
**Will:**
- Design filter module structure and interfaces
- Evaluate performance trade-offs of architectural choices
- Define module boundaries and shared utility contracts
- Recommend TOML vs Rust approach for new filters
- Design cross-cutting features (new config fields, tracking metrics)
**Will not:**
- Implement the full filter logic (→ rust-rtk agent)
- Write the actual regex patterns (→ implementation detail)
- Make decisions about token savings targets (→ fixed at ≥60%)
- Override the <10ms startup constraint (→ non-negotiable)
+105
View File
@@ -0,0 +1,105 @@
---
model: haiku
description: Interactive cleanup of stale worktrees (merged branches, orphaned refs)
---
# Clean Worktree (Interactive)
Interactive cleanup of worktrees: lists merged/stale branches and asks confirmation before deleting.
**Difference with `/clean-worktrees`**:
- `/clean-worktree`: Interactive, asks confirmation
- `/clean-worktrees`: Automatic, no interaction
## Usage
```bash
/clean-worktree # Interactive audit + cleanup
```
## Implementation
Execute this script:
```bash
#!/bin/bash
set -euo pipefail
echo "=== Worktrees Status ==="
git worktree list
echo ""
echo "=== Pruning stale references ==="
git worktree prune
echo ""
echo "=== Merged branches (safe to delete) ==="
MERGED_FOUND=false
CURRENT_DIR="$(pwd)"
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]' || true)
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
[ "$path" = "$CURRENT_DIR" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$" 2>/dev/null; then
echo " - $branch (at $path) - MERGED"
MERGED_FOUND=true
fi
done < <(git worktree list)
if [ "$MERGED_FOUND" = false ]; then
echo " (none found)"
echo ""
echo "=== Disk usage ==="
du -sh .worktrees/ 2>/dev/null || echo "No .worktrees directory"
exit 0
fi
echo ""
echo "=== Clean merged worktrees? [y/N] ==="
read -r confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]' || true)
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
[ "$path" = "$CURRENT_DIR" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$" 2>/dev/null; then
echo " Removing $branch..."
git worktree remove "$path" 2>/dev/null || rm -rf "$path"
git branch -d "$branch" 2>/dev/null || echo " (branch already deleted)"
echo " Done: $branch"
fi
done < <(git worktree list)
echo ""
echo "Cleanup complete."
else
echo "Aborted."
fi
echo ""
echo "=== Disk usage ==="
du -sh .worktrees/ 2>/dev/null || echo "No .worktrees directory"
```
## Safety
- Never removes `master` or `main` worktrees
- Only removes branches merged into `master`
- Asks confirmation before any deletion
- Cleans both git reference and physical directory
## Manual Force Remove (unmerged branch)
```bash
git worktree remove --force .worktrees/feature-name
git branch -D feature/name
git worktree prune
```
+165
View File
@@ -0,0 +1,165 @@
---
model: haiku
description: Clean all merged worktrees automatically (no interaction)
---
# Clean Worktrees (Automatic)
Automatically remove all worktrees for branches merged into `master`. No interaction required.
**Difference with `/clean-worktree`**:
- `/clean-worktree`: Interactive, asks confirmation per branch
- `/clean-worktrees`: Automatic, removes all merged branches at once
## Usage
```bash
/clean-worktrees # Remove all merged worktrees
/clean-worktrees --dry-run # Preview what would be deleted
```
## Implementation
Execute this script:
```bash
#!/bin/bash
set -euo pipefail
DRY_RUN=false
if [[ "${ARGUMENTS:-}" == *"--dry-run"* ]]; then
DRY_RUN=true
fi
echo "Cleaning Worktrees"
echo "=================="
echo ""
# Step 1: Prune stale git references
echo "1. Pruning stale git references..."
PRUNED=$(git worktree prune -v 2>&1)
if [ -n "$PRUNED" ]; then
echo "$PRUNED"
echo "Stale references pruned"
else
echo "No stale references found"
fi
echo ""
# Step 2: Find merged worktrees
echo "2. Finding merged worktrees..."
MERGED_COUNT=0
MERGED_BRANCHES=()
CURRENT_DIR="$(pwd)"
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]' || true)
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
[ "$path" = "$CURRENT_DIR" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$" 2>/dev/null; then
MERGED_COUNT=$((MERGED_COUNT + 1))
MERGED_BRANCHES+=("$branch|$path")
echo " - $branch (merged)"
fi
done < <(git worktree list)
if [ $MERGED_COUNT -eq 0 ]; then
echo "No merged worktrees found"
echo ""
echo "Current worktrees:"
git worktree list
exit 0
fi
echo ""
echo "Found $MERGED_COUNT merged worktree(s)"
echo ""
if [ "$DRY_RUN" = true ]; then
echo "DRY RUN - No changes will be made"
echo ""
echo "Would delete:"
for item in "${MERGED_BRANCHES[@]}"; do
branch=$(echo "$item" | cut -d'|' -f1)
path=$(echo "$item" | cut -d'|' -f2)
echo " - $branch"
echo " Path: $path"
done
echo ""
echo "Run without --dry-run to actually delete"
exit 0
fi
# Step 3: Remove merged worktrees
echo "3. Removing merged worktrees..."
REMOVED_COUNT=0
for item in "${MERGED_BRANCHES[@]}"; do
branch=$(echo "$item" | cut -d'|' -f1)
path=$(echo "$item" | cut -d'|' -f2)
echo ""
echo "Removing: $branch"
if git worktree remove "$path" 2>/dev/null; then
echo " Worktree removed"
else
echo " Git remove failed, forcing..."
rm -rf "$path" 2>/dev/null || true
git worktree prune 2>/dev/null || true
echo " Worktree forcefully removed"
fi
if git branch -d "$branch" 2>/dev/null; then
echo " Local branch deleted"
else
echo " Local branch already deleted"
fi
if git ls-remote --heads origin "$branch" 2>/dev/null | grep -q "$branch"; then
echo " Remote branch exists: origin/$branch (not auto-deleted)"
fi
REMOVED_COUNT=$((REMOVED_COUNT + 1))
done
echo ""
echo "Cleanup complete"
echo ""
echo "Summary:"
echo " Removed: $REMOVED_COUNT worktree(s)"
echo ""
echo "Remaining worktrees:"
git worktree list
echo ""
WORKTREES_SIZE=$(du -sh .worktrees/ 2>/dev/null | awk '{print $1}' || echo "N/A")
echo "Worktrees disk usage: $WORKTREES_SIZE"
```
## Safety Features
- Only removes branches merged into `master`
- Skips `master` and `main` (protected)
- Never removes the current working directory
- Dry-run mode to preview before deletion
- Remote branches: reported but not auto-deleted
## When to Use
- After merging PRs: `/clean-worktrees`
- Weekly maintenance: `/clean-worktrees`
- Before creating new worktrees: `/clean-worktrees --dry-run` first
## Manual Removal (unmerged branch)
```bash
git worktree remove --force .worktrees/feature-name
git branch -D feature/name
git worktree prune
```
+284
View File
@@ -0,0 +1,284 @@
---
model: sonnet
description: RTK Codebase Health Audit — 7 catégories scorées 0-10
argument-hint: "[--category <cat>] [--fix] [--json]"
allowed-tools: [Read, Grep, Glob, Bash, Write]
---
# Audit Codebase — Santé du Projet RTK
Score global et par catégorie (0-10) avec plan d'action priorisé.
## Arguments
- `--category <cat>` — Auditer une seule catégorie : `secrets`, `security`, `deps`, `structure`, `tests`, `perf`, `ai`
- `--fix` — Après l'audit, proposer les fixes prioritaires
- `--json` — Output JSON pour CI/CD
## Usage
```bash
/tech:audit-codebase
/tech:audit-codebase --category security
/tech:audit-codebase --fix
/tech:audit-codebase --json
```
Arguments: $ARGUMENTS
## Seuils de Scoring
| Score | Tier | Status |
| ----- | --------- | -------------------- |
| 0-4 | 🔴 Tier 1 | Critique |
| 5-7 | 🟡 Tier 2 | Amélioration requise |
| 8-10 | 🟢 Tier 3 | Production Ready |
## Phase 1 : Audit Secrets (Poids: 2x)
```bash
# API keys hardcodées
Grep "sk-[a-zA-Z0-9]{20}" src/
Grep "Bearer [a-zA-Z0-9]" src/
# Credentials dans le code
Grep "password\s*=\s*\"" src/
Grep "token\s*=\s*\"[^$]" src/
# .env accidentellement commité
git ls-files | grep "\.env" | grep -v "\.env\.example"
# Chemins absolus hardcodés (home dir, etc.)
Grep "/home/[a-z]" src/
Grep "/Users/[A-Z]" src/
```
| Condition | Score |
| ----------------------- | ------------ |
| 0 secrets trouvés | 10/10 |
| Chemin absolu hardcodé | -1 par occ. |
| Credential réel exposé | 0/10 immédiat|
## Phase 2 : Audit Sécurité (Poids: 2x)
**Objectif** : Pas d'injection shell, pas de panic en prod, error handling complet.
```bash
# unwrap() en production (hors tests)
Grep "\.unwrap()" src/ --glob "*.rs"
# Filtrer les tests : compter ceux hors #[cfg(test)]
# panic! en production
Grep "panic!" src/ --glob "*.rs"
# expect() sans message explicite
Grep '\.expect("")' src/
# format! dans des chemins injection-possibles
Grep "Command::new.*format!" src/
# ? sans .context()
# (approximation - chercher les ? seuls)
Grep "[^;]\?" src/ --glob "*.rs"
```
| Condition | Score |
| -------------------------------- | ----------------- |
| 0 unwrap() hors tests | 10/10 |
| `unwrap()` en production | -1.5 par fichier |
| `panic!` hors tests | -2 par occurrence |
| `?` sans `.context()` | -0.5 par 10 occ. |
| Injection shell potentielle | -3 par occurrence |
## Phase 3 : Audit Dépendances (Poids: 1x)
```bash
# Vulnérabilités connues
cargo audit 2>&1 | tail -30
# Dépendances outdated
cargo outdated 2>&1 | head -30
# Dépendances async (interdit dans RTK)
Grep "tokio\|async-std\|futures" Cargo.toml
# Taille binaire post-strip
ls -lh target/release/rtk 2>/dev/null || echo "Build needed"
```
| Condition | Score |
| -------------------------------- | ------------- |
| 0 CVE high/critical | 10/10 |
| 1 CVE moderate | -1 par CVE |
| 1+ CVE high | -2 par CVE |
| 1+ CVE critical | 0/10 immédiat |
| Dépendance async présente | -3 (perf killer) |
| Binaire >5MB stripped | -1 |
## Phase 4 : Audit Structure (Poids: 1.5x)
**Objectif** : Architecture RTK respectée, conventions Rust appliquées.
```bash
# Regex non-lazy (compilées à chaque appel)
Grep "Regex::new" src/ --glob "*.rs"
# Compter celles hors lazy_static!
# Modules sans fallback vers commande brute
Grep "execute_raw\|passthrough\|raw_cmd" src/ --glob "*.rs"
# Modules sans module de tests intégré
Grep "#\[cfg(test)\]" src/ --glob "*.rs" --output_mode files_with_matches
# Fichiers source sans tests correspondants
Glob src/*_cmd.rs
# main.rs : vérifier que tous les modules sont enregistrés
Grep "mod " src/main.rs
```
| Condition | Score |
| -------------------------------------- | ------------------- |
| 0 regex non-lazy | 10/10 |
| Regex dans fonction (pas lazy_static) | -2 par occurrence |
| Module sans fallback brute | -1.5 par module |
| Module sans #[cfg(test)] | -1 par module |
## Phase 5 : Audit Tests (Poids: 2x)
**Objectif** : Couverture croissante, savings claims vérifiés.
```bash
# Ratio modules avec tests embarqués
MODULES=$(Glob src/*_cmd.rs | wc -l)
TESTED=$(Grep "#\[cfg(test)\]" src/ --glob "*_cmd.rs" --output_mode files_with_matches | wc -l)
echo "Test coverage: $TESTED / $MODULES modules"
# Fixtures réelles présentes
Glob tests/fixtures/*.txt | wc -l
# Tests de token savings (count_tokens assertions)
Grep "count_tokens\|savings" src/ --glob "*.rs" --output_mode count
# Smoke tests OK
ls scripts/test-all.sh 2>/dev/null && echo "Smoke tests present" || echo "Missing"
```
| Coverage % | Score | Tier |
| ------------------ | ----- | ---- |
| <30% modules | 3/10 | 🔴 1 |
| 30-49% | 5/10 | 🟡 2 |
| 50-69% | 7/10 | 🟡 2 |
| 70-89% | 8/10 | 🟢 3 |
| 90%+ modules | 10/10 | 🟢 3 |
**Bonus** : Fixtures réelles pour chaque filtre = +0.5. Smoke tests présents = +0.5.
## Phase 6 : Audit Performance (Poids: 2x)
**Objectif** : Startup <10ms, mémoire <5MB, savings claims tenus.
```bash
# Benchmark startup (si hyperfine dispo)
which hyperfine && hyperfine 'rtk git status' --warmup 3 2>&1 | grep "Time"
# Mémoire binaire
ls -lh target/release/rtk 2>/dev/null
# Dépendances lourdes
Grep "serde_json\|regex\|rusqlite" Cargo.toml
# (ok mais vérifier qu'elles sont nécessaires)
# Regex compilées au runtime
Grep "Regex::new" src/ --glob "*.rs" --output_mode count
# Clone() excessifs (approx)
Grep "\.clone()" src/ --glob "*.rs" --output_mode count
```
| Condition | Score |
| ------------------------------ | -------------- |
| Startup <10ms vérifié | 10/10 |
| Startup 10-15ms | 8/10 |
| Startup 15-25ms | 6/10 |
| Startup >25ms | 3/10 |
| Regex runtime (non-lazy) | -2 par occ. |
| Dépendance async présente | -4 (éliminatoire) |
## Phase 7 : Audit AI Patterns (Poids: 1x)
```bash
# Agents définis
ls .claude/agents/ | wc -l
# Commands/skills
ls .claude/commands/tech/ | wc -l
# Règles auto-loaded
ls .claude/rules/ | wc -l
# CLAUDE.md taille (trop gros = trop dense)
wc -l CLAUDE.md
# Filter development checklist présente
Grep "Filter Development Checklist" CLAUDE.md
```
| Condition | Score |
| -------------------------------- | ----- |
| >5 agents spécialisés | +2 |
| >10 commands/skills | +2 |
| >5 règles auto-loaded | +2 |
| CLAUDE.md bien structuré | +2 |
| Smoke tests + CI multi-platform | +2 |
| Score max | 10/10 |
## Phase 8 : Score Global
```
Score global = (
(secrets × 2) +
(security × 2) +
(structure × 1.5) +
(tests × 2) +
(perf × 2) +
(deps × 1) +
(ai × 1)
) / 11.5
```
## Format de Sortie
```
🔍 Audit RTK — {date}
┌──────────────┬───────┬────────┬──────────────────────────────┐
│ Catégorie │ Score │ Tier │ Top issue │
├──────────────┼───────┼────────┼──────────────────────────────┤
│ Secrets │ 9.5 │ 🟢 T3 │ 0 issues │
│ Sécurité │ 7.0 │ 🟡 T2 │ unwrap() ×8 hors tests │
│ Structure │ 8.0 │ 🟢 T3 │ 2 modules sans fallback │
│ Tests │ 6.5 │ 🟡 T2 │ 60% modules couverts │
│ Performance │ 9.0 │ 🟢 T3 │ startup ~6ms ✅ │
│ Dépendances │ 8.0 │ 🟢 T3 │ 3 packages outdated │
│ AI Patterns │ 8.5 │ 🟢 T3 │ 7 agents, 12 commands │
└──────────────┴───────┴────────┴──────────────────────────────┘
Score global : 8.1 / 10 [🟢 Tier 3]
```
## Plan d'Action (--fix)
```
📋 Plan de progression vers Tier 3
Priorité 1 — Sécurité (7.0 → 8+) :
1. Migrer unwrap() restants vers .context()? — ~2h
2. Ajouter fallback brute aux 2 modules manquants — ~1h
Priorité 2 — Tests (6.5 → 8+) :
1. Ajouter #[cfg(test)] aux 4 modules non testés — ~4h
2. Créer fixtures réelles pour les nouveaux filtres — ~2h
Estimé : ~9h de travail
```
+87
View File
@@ -0,0 +1,87 @@
---
model: haiku
description: Clean stale worktrees (interactive)
---
# Clean Worktree (Interactive)
Audit and clean obsolete worktrees interactively: merged, pruned, orphaned branches.
**vs `/tech:clean-worktrees`**:
- `/tech:clean-worktree`: Interactive, asks confirmation before deletion
- `/tech:clean-worktrees`: Automatic, no interaction (merged branches only)
## Usage
```bash
/tech:clean-worktree
```
## Implementation
```bash
#!/bin/bash
echo "=== Worktrees Status ==="
git worktree list
echo ""
echo "=== Pruning stale references ==="
git worktree prune
echo ""
echo "=== Merged branches (safe to delete) ==="
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]')
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$"; then
echo " - $branch (at $path) — MERGED"
fi
done < <(git worktree list)
echo ""
echo "=== Clean merged worktrees? [y/N] ==="
read -r confirm
if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]')
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$"; then
echo " Removing $branch..."
git worktree remove "$path" 2>/dev/null || rm -rf "$path"
git branch -d "$branch" 2>/dev/null || echo " (branch already deleted)"
fi
done < <(git worktree list)
echo "Done."
else
echo "Aborted."
fi
echo ""
echo "=== Disk usage ==="
du -sh .worktrees/ 2>/dev/null || echo "No .worktrees directory"
```
## Safety
- **Never** removes `master` or `main` worktrees
- **Only** removes merged branches (safe)
- **Asks confirmation** before deletion
- Cleans both worktree reference AND physical directory
## Manual Override
Force remove an unmerged worktree:
```bash
git worktree remove --force <path>
git branch -D <branch_name>
```
+162
View File
@@ -0,0 +1,162 @@
---
model: haiku
description: Auto-clean all stale worktrees (merged branches)
---
# Clean Worktrees (Automatic)
Automatically clean all stale worktrees: merged branches and orphaned git references.
**vs `/tech:clean-worktree`**:
- `/tech:clean-worktree`: Interactive, asks confirmation
- `/tech:clean-worktrees`: **Automatic**, no interaction (safe: merged only)
## Usage
```bash
/tech:clean-worktrees # Clean all merged worktrees
/tech:clean-worktrees --dry-run # Preview what would be deleted
```
## Implementation
```bash
#!/bin/bash
set -euo pipefail
DRY_RUN=false
if [[ "${ARGUMENTS:-}" == *"--dry-run"* ]]; then
DRY_RUN=true
fi
echo "🧹 Cleaning Worktrees"
echo "====================="
echo ""
# Step 1: Prune stale git references
echo "1️⃣ Pruning stale git references..."
PRUNED=$(git worktree prune -v 2>&1)
if [ -n "$PRUNED" ]; then
echo "$PRUNED"
echo "✅ Stale references pruned"
else
echo "✅ No stale references found"
fi
echo ""
# Step 2: Find merged worktrees
echo "2️⃣ Finding merged worktrees..."
MERGED_COUNT=0
MERGED_BRANCHES=()
while IFS= read -r line; do
path=$(echo "$line" | awk '{print $1}')
branch=$(echo "$line" | grep -oE '\[.*\]' | tr -d '[]' || true)
[ -z "$branch" ] && continue
[ "$branch" = "master" ] && continue
[ "$branch" = "main" ] && continue
[ "$path" = "$(pwd)" ] && continue
if git branch --merged master | grep -q "^[* ] ${branch}$" 2>/dev/null; then
MERGED_COUNT=$((MERGED_COUNT + 1))
MERGED_BRANCHES+=("$branch|$path")
echo " ✓ $branch (merged)"
fi
done < <(git worktree list)
if [ $MERGED_COUNT -eq 0 ]; then
echo "✅ No merged worktrees found"
echo ""
echo "📊 Current worktrees:"
git worktree list
exit 0
fi
echo ""
echo "📋 Found $MERGED_COUNT merged worktree(s)"
echo ""
if [ "$DRY_RUN" = true ]; then
echo "🔍 DRY RUN MODE - No changes will be made"
echo ""
echo "Would delete:"
for item in "${MERGED_BRANCHES[@]}"; do
branch=$(echo "$item" | cut -d'|' -f1)
path=$(echo "$item" | cut -d'|' -f2)
echo " - $branch"
echo " Path: $path"
done
echo ""
echo "Run without --dry-run to actually delete"
exit 0
fi
# Step 3: Remove merged worktrees
echo "3️⃣ Removing merged worktrees..."
REMOVED_COUNT=0
FAILED_COUNT=0
for item in "${MERGED_BRANCHES[@]}"; do
branch=$(echo "$item" | cut -d'|' -f1)
path=$(echo "$item" | cut -d'|' -f2)
echo ""
echo "🗑️ Removing: $branch"
if git worktree remove "$path" 2>/dev/null; then
echo " ✅ Worktree removed"
else
echo " ⚠️ Git remove failed, forcing..."
rm -rf "$path" 2>/dev/null || true
git worktree prune 2>/dev/null || true
echo " ✅ Worktree forcefully removed"
fi
if git branch -d "$branch" 2>/dev/null; then
echo " ✅ Local branch deleted"
else
echo " ⚠️ Local branch already deleted"
fi
if git ls-remote --heads origin "$branch" 2>/dev/null | grep -q "$branch"; then
echo " 🌐 Remote branch exists: $branch"
echo " (Skipping auto-delete - use /tech:remove-worktree for manual removal)"
fi
REMOVED_COUNT=$((REMOVED_COUNT + 1))
done
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Cleanup Complete!"
echo ""
echo "📊 Summary:"
echo " - Removed: $REMOVED_COUNT worktree(s)"
if [ $FAILED_COUNT -gt 0 ]; then
echo " - Failed: $FAILED_COUNT worktree(s)"
fi
echo ""
echo "📂 Remaining worktrees:"
git worktree list
echo ""
WORKTREES_SIZE=$(du -sh .worktrees/ 2>/dev/null | awk '{print $1}' || echo "N/A")
echo "💾 Worktrees disk usage: $WORKTREES_SIZE"
```
## Safety Features
- ✅ **Only merged branches**: Never touches unmerged work
- ✅ **Protected branches**: Skips `master` and `main`
- ✅ **Main repo**: Never removes current working directory
- ✅ **Remote branches**: Reports but doesn't auto-delete
- ✅ **Dry-run mode**: Preview before deletion
## When to Use
- After merging PRs into master
- Weekly maintenance
- Before creating new worktrees (keep things clean)
For unmerged branches: use `/tech:remove-worktree <branch>` (confirms deletion).
+258
View File
@@ -0,0 +1,258 @@
---
model: sonnet
description: RTK Code Review — Review locale pre-PR avec auto-fix
---
# RTK Code Review
Review locale de la branche courante avant création de PR. Applique les critères de qualité RTK.
**Principe**: Preview local → corriger → puis créer PR propre.
## Usage
```bash
/tech:codereview # 🔴 + 🟡 uniquement (compact)
/tech:codereview --verbose # + points positifs + 🟢 détaillées
/tech:codereview main # Review vs main (défaut: master)
/tech:codereview --staged # Seulement fichiers staged
/tech:codereview --auto # Review + fix loop
/tech:codereview --auto --max 5
```
Arguments: $ARGUMENTS
## Étape 1: Récupérer le contexte
```bash
# Parse arguments
VERBOSE=false
AUTO_MODE=false
MAX_ITERATIONS=3
STAGED=false
BASE_BRANCH="master"
set -- "$ARGUMENTS"
while [[ $# -gt 0 ]]; do
case "$1" in
--verbose) VERBOSE=true; shift ;;
--auto) AUTO_MODE=true; shift ;;
--max) MAX_ITERATIONS="$2"; shift 2 ;;
--staged) STAGED=true; shift ;;
*) BASE_BRANCH="$1"; shift ;;
esac
done
# Fichiers modifiés
git diff "$BASE_BRANCH"...HEAD --name-only
# Diff complet
git diff "$BASE_BRANCH"...HEAD
# Stats
git diff "$BASE_BRANCH"...HEAD --stat
```
## Étape 2: Charger les guides pertinents (CONDITIONNEL)
| Si le diff contient... | Vérifier |
| ------------------------------ | ------------------------------------------ |
| `src/*.rs` | CLAUDE.md sections Error Handling + Tests |
| `src/filter.rs` ou `*_cmd.rs` | Filter Development Checklist (CLAUDE.md) |
| `src/main.rs` | Command routing + Commands enum |
| `src/tracking.rs` | SQLite patterns + DB path config |
| `src/config.rs` | Configuration system + init patterns |
| `.github/workflows/` | CI/CD multi-platform build targets |
| `tests/` ou `fixtures/` | Testing Strategy (CLAUDE.md) |
| `Cargo.toml` | Dependencies + build optimizations |
### Règles clés RTK
**Error Handling**:
- `anyhow::Result` pour tout le CLI (jamais `std::io::Result` nu)
- TOUJOURS `.context("description")` avec `?` — jamais `?` seul
- JAMAIS `unwrap()` en production (tests: `expect("raison")`)
- Fallback gracieux : si filter échoue → exécuter la commande brute
**Performance**:
- JAMAIS `Regex::new()` dans une fonction → `lazy_static!` obligatoire
- JAMAIS dépendance async (tokio, async-std) → single-threaded by design
- Startup time cible: <10ms
**Tests**:
- `#[cfg(test)] mod tests` embarqué dans chaque module
- Fixtures réelles dans `tests/fixtures/<cmd>_raw.txt`
- `count_tokens()` pour vérifier savings ≥60%
- `assert_snapshot!` (insta) pour output format
**Module**:
- `lazy_static!` pour regex (compile once, reuse forever)
- `exit_code` propagé (0 = success, non-zero = failure)
- `strip_ansi()` depuis `utils.rs` — pas re-implémenté
**Filtres**:
- Token savings ≥60% obligatoire (release blocker)
- Fallback: si filter échoue → raw command exécutée
- Pas d'output ASCII art, pas de verbose metadata inutile
## Étape 3: Analyser selon critères
### 🔴 MUST FIX (bloquant)
- `unwrap()` en dehors des tests
- `Regex::new()` dans une fonction (pas de lazy_static)
- `?` sans `.context()` — erreur sans description
- Dépendance async ajoutée (tokio, async-std, futures)
- Token savings <60% pour un nouveau filtre
- Pas de fallback vers commande brute sur échec de filtre
- `panic!()` en production (hors tests)
- Exit code non propagé sur commande sous-jacente
- Secret ou credential hardcodé
- **Tests manquants pour NOUVEAU code** :
- Nouveau `*_cmd.rs` sans `#[cfg(test)] mod tests`
- Nouveau filtre sans fixture réelle dans `tests/fixtures/`
- Nouveau filtre sans test de token savings (`count_tokens()`)
### 🟡 SHOULD FIX (important)
- `?` sans `.context()` dans code existant (tolerable si pattern établi)
- Regex non-lazy dans code existant migré vers lazy_static
- Fonction >50 lignes (split recommandé)
- Nesting >3 niveaux (early returns)
- `clone()` inutile (borrow possible)
- Output format inconsistant avec les autres filtres RTK
- Test avec données synthétiques au lieu de vraie fixture
- ANSI codes non strippés dans le filtre
- `println!` en production (debug artifact)
- **Tests manquants pour code legacy modifié** :
- Fonction existante modifiée sans couverture test
- Nouveau path de code sans test correspondant
### 🟢 CAN SKIP (suggestions)
- Optimisations non critiques
- Refactoring de style
- Renommage perfectible mais fonctionnel
- Améliorations de documentation mineures
## Étape 4: Générer le rapport
### Format compact (défaut)
```markdown
## 🔍 Review RTK
| 🔴 | 🟡 |
| :-: | :-: |
| 2 | 3 |
**[REQUEST CHANGES]** - unwrap() en production + regex non-lazy
---
### 🔴 Bloquant
• `git_cmd.rs:45` - `unwrap()` → `.context("...")?`
\```rust
// ❌ Avant
let hash = extract_hash(line).unwrap();
// ✅ Après
let hash = extract_hash(line).context("Failed to extract commit hash")?;
\```
• `grep_cmd.rs:12` - `Regex::new()` dans la fonction → `lazy_static!`
\```rust
// ❌ Avant (recompile à chaque appel)
let re = Regex::new(r"pattern").unwrap();
// ✅ Après
lazy_static! { static ref RE: Regex = Regex::new(r"pattern").unwrap(); }
\```
### 🟡 Important
• `filter.rs:78` - Fonction 67 lignes → split en 2
• `ls.rs:34` - clone() inutile, borrow suffit
• `new_cmd.rs` - Pas de fixture réelle dans tests/fixtures/
| Prio | Fichier | L | Action |
| ---- | ----------- | -- | ----------------- |
| 🔴 | git_cmd.rs | 45 | .context() manque |
| 🔴 | grep_cmd.rs | 12 | lazy_static! |
| 🟡 | filter.rs | 78 | split function |
```
**Mode verbose (--verbose)** — ajoute points positifs + 🟢 détaillées.
## Règles anti-hallucination (CRITIQUE)
**OBLIGATOIRE avant de signaler un problème**:
1. **Vérifier existence** — Ne jamais recommander un pattern sans vérifier sa présence dans le codebase
2. **Lire le fichier COMPLET** — Pas juste le diff, lire le contexte entier
3. **Compter les occurrences** — Pattern existant (>10 occurrences) → "Suggestion", PAS "Bloquant"
```bash
# Vérifier si lazy_static est déjà utilisé dans le module
Grep "lazy_static" src/<module>.rs
# Compter unwrap() (si pattern établi dans tests = ok)
Grep "unwrap()" src/ --output_mode count
# Vérifier si fixture existe
Glob tests/fixtures/<cmd>_raw.txt
```
**NE PAS signaler**:
- `unwrap()` dans `#[cfg(test)] mod tests` → autorisé (avec `expect()` préféré)
- `lazy_static!` avec `unwrap()` pour initialisation → pattern établi RTK
- Variables `_unused` → peut être intentionnel (warn suppression)
## Mode Auto (--auto)
```
/tech:codereview --auto
│
▼
┌─────────────────┐
│ 1. Review │ rapport 🔴🟡🟢
└────────┬────────┘
│
🔴 ou 🟡 ?
┌────┴────┐
│ NON │ OUI
▼ ▼
✅ DONE ┌─────────────────┐
│ 2. Corriger │
└────────┬────────┘
│
▼
┌──────────────────────┐
│ 3. Quality gate │
│ cargo fmt --all │
│ cargo clippy │
│ cargo test │
└────────┬─────────────┘
│
Loop ←┘ (max N iterations)
```
**Safeguards mode auto**:
- Ne pas modifier : `Cargo.lock`, `.env*`, `*secret*`
- Si >5 fichiers modifiés → demander confirmation
- Quality gate : `cargo fmt --all && cargo clippy --all-targets && cargo test`
- Si quality gate fail → `git reset --hard HEAD` + reporter les erreurs
- Commit atomique par passage : `autofix(codereview): fix unwrap + lazy_static`
## Workflow recommandé
```
1. Développer sur feature branch
2. /tech:codereview → preview problèmes (compact)
3a. Corriger manuellement les 🔴 et 🟡
OU
3b. /tech:codereview --auto → fix automatique
4. /tech:codereview → vérifier READY
5. gh pr create --base master
```
+154
View File
@@ -0,0 +1,154 @@
---
model: haiku
description: Remove a specific worktree (directory + git reference + branch)
---
# Remove Worktree
Remove a specific worktree, cleaning up directory, git references, and optionally the branch.
## Usage
```bash
/tech:remove-worktree feature/new-filter
/tech:remove-worktree fix/session-bug
```
## Implementation
Execute this script with branch name from `$ARGUMENTS`:
```bash
#!/bin/bash
set -euo pipefail
BRANCH_NAME="$ARGUMENTS"
if [ -z "$BRANCH_NAME" ]; then
echo "❌ Usage: /tech:remove-worktree <branch-name>"
echo ""
echo "Example:"
echo " /tech:remove-worktree feature/new-filter"
exit 1
fi
echo "🔍 Checking worktree: $BRANCH_NAME"
echo ""
# Check if worktree exists in git
if ! git worktree list | grep -q "$BRANCH_NAME"; then
echo "❌ Worktree not found: $BRANCH_NAME"
echo ""
echo "Available worktrees:"
git worktree list
exit 1
fi
# Get worktree path from git
WORKTREE_FULL_PATH=$(git worktree list | grep "$BRANCH_NAME" | awk '{print $1}')
# Safety check: never remove main repo
if [ "$WORKTREE_FULL_PATH" = "$(pwd)" ]; then
echo "❌ Cannot remove main repository worktree"
exit 1
fi
# Safety check: never remove master or main
if [ "$BRANCH_NAME" = "master" ] || [ "$BRANCH_NAME" = "main" ]; then
echo "❌ Cannot remove $BRANCH_NAME (protected branch)"
exit 1
fi
echo "📂 Worktree path: $WORKTREE_FULL_PATH"
echo "🌿 Branch: $BRANCH_NAME"
echo ""
# Check if branch is merged
IS_MERGED=false
if git branch --merged master | grep -q "^[* ] ${BRANCH_NAME}$"; then
IS_MERGED=true
echo "✅ Branch is merged into master (safe to delete)"
else
echo "⚠️ Branch is NOT merged into master"
fi
echo ""
# Ask confirmation if not merged
if [ "$IS_MERGED" = false ]; then
echo "⚠️ This will DELETE unmerged work. Continue? [y/N]"
read -r confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
echo "Aborted."
exit 0
fi
fi
# Remove worktree
echo "🗑️ Removing worktree..."
if git worktree remove "$WORKTREE_FULL_PATH" 2>/dev/null; then
echo "✅ Worktree removed: $WORKTREE_FULL_PATH"
else
echo "⚠️ Git remove failed, forcing removal..."
rm -rf "$WORKTREE_FULL_PATH"
git worktree prune
echo "✅ Worktree forcefully removed"
fi
# Delete branch
echo ""
echo "🌿 Deleting branch..."
if [ "$IS_MERGED" = true ]; then
if git branch -d "$BRANCH_NAME" 2>/dev/null; then
echo "✅ Branch deleted (local): $BRANCH_NAME"
else
echo "⚠️ Local branch already deleted or not found"
fi
else
if git branch -D "$BRANCH_NAME" 2>/dev/null; then
echo "✅ Branch force-deleted (local): $BRANCH_NAME"
else
echo "⚠️ Local branch already deleted or not found"
fi
fi
# Delete remote branch (if exists)
echo ""
echo "🌐 Checking remote branch..."
if git ls-remote --heads origin "$BRANCH_NAME" | grep -q "$BRANCH_NAME"; then
echo "⚠️ Remote branch exists. Delete it? [y/N]"
read -r confirm_remote
if [ "$confirm_remote" = "y" ] || [ "$confirm_remote" = "Y" ]; then
if git push origin --delete "$BRANCH_NAME" --no-verify 2>/dev/null; then
echo "✅ Remote branch deleted: $BRANCH_NAME"
else
echo "❌ Failed to delete remote branch (may require permissions)"
fi
else
echo "⏭️ Skipped remote branch deletion"
fi
else
echo "ℹ️ No remote branch found"
fi
echo ""
echo "✅ Cleanup complete!"
echo ""
echo "📊 Remaining worktrees:"
git worktree list
```
## Safety Features
- ✅ Never removes `master` or `main`
- ✅ Asks confirmation for unmerged branches
- ✅ Cleans git references, directory, and branch
- ✅ Optional remote branch deletion
- ✅ Fallback to force removal if git fails
## Manual Override
```bash
git worktree remove --force <path>
git branch -D <branch>
git push origin --delete <branch> --no-verify
```
+115
View File
@@ -0,0 +1,115 @@
---
model: haiku
description: Worktree Cargo Check Status
---
# Worktree Status Check
Check the status of background cargo check for a git worktree.
## Usage
```bash
/tech:worktree-status feature/new-filter
/tech:worktree-status fix/session-bug
```
## Implementation
Execute this script with branch name from `$ARGUMENTS`:
```bash
#!/bin/bash
set -euo pipefail
BRANCH_NAME="$ARGUMENTS"
LOG_FILE="/tmp/worktree-cargo-check-${BRANCH_NAME//\//-}.log"
if [ ! -f "$LOG_FILE" ]; then
echo "❌ No cargo check found for branch: $BRANCH_NAME"
echo ""
echo "Possible reasons:"
echo "1. Worktree was created with --fast / --no-check flag"
echo "2. Branch name mismatch (use exact branch name)"
echo "3. Cargo check hasn't started yet (wait a few seconds)"
echo ""
echo "Available logs:"
ls -1 /tmp/worktree-cargo-check-*.log 2>/dev/null || echo " (none)"
exit 1
fi
LOG_CONTENT=$(head -n 1000 "$LOG_FILE")
if echo "$LOG_CONTENT" | grep -q "✅ Cargo check passed"; then
TIMESTAMP=$(echo "$LOG_CONTENT" | grep "Cargo check passed" | sed 's/.*at //')
echo "✅ Cargo check passed"
echo " Completed at: $TIMESTAMP"
echo ""
echo "Worktree is ready for development!"
elif echo "$LOG_CONTENT" | grep -q "❌ Cargo check failed"; then
TIMESTAMP=$(echo "$LOG_CONTENT" | grep "Cargo check failed" | sed 's/.*at //')
echo "❌ Cargo check failed"
echo " Completed at: $TIMESTAMP"
echo ""
ERROR_COUNT=$(grep -v "Cargo check" "$LOG_FILE" | grep -c "^error" || echo "0")
echo "Errors:"
echo "─────────────────────────────────────"
grep "^error" "$LOG_FILE" | head -20
echo "─────────────────────────────────────"
echo ""
echo "Full log: cat $LOG_FILE"
echo ""
echo "⚠️ You can still work on the worktree - fix errors as you go."
elif echo "$LOG_CONTENT" | grep -q "⏳ Cargo check started"; then
START_TIME=$(echo "$LOG_CONTENT" | grep "Cargo check started" | sed 's/.*at //')
CURRENT_TIME=$(date +%H:%M:%S)
echo "⏳ Cargo check still running..."
echo " Started at: $START_TIME"
echo " Current time: $CURRENT_TIME"
echo ""
echo "Check again in a few seconds or view live progress:"
echo " tail -f $LOG_FILE"
else
echo "⚠️ Cargo check in unknown state"
echo ""
echo "Log content:"
cat "$LOG_FILE"
fi
```
## Output Examples
### Success
```
✅ Cargo check passed
Completed at: 14:23:45
Worktree is ready for development!
```
### Failed
```
❌ Cargo check failed
Completed at: 14:24:12
Errors:
─────────────────────────────────────
error[E0308]: mismatched types
--> src/git.rs:45:12
─────────────────────────────────────
Full log: cat /tmp/worktree-cargo-check-feature-new-filter.log
```
### Still Running
```
⏳ Cargo check still running...
Started at: 14:22:30
Current time: 14:22:45
Check again in a few seconds or view live progress:
tail -f /tmp/worktree-cargo-check-feature-new-filter.log
```
+187
View File
@@ -0,0 +1,187 @@
---
model: haiku
description: Git Worktree Setup for RTK
---
# Git Worktree Setup
Create isolated git worktrees with instant feedback and background Cargo check.
**Performance**: ~1s setup + background cargo check
## Usage
```bash
/tech:worktree feature/new-filter # Creates worktree + background cargo check
/tech:worktree fix/typo --fast # Skip cargo check (instant)
/tech:worktree feature/perf --no-check # Skip cargo check
```
**Behavior**: Creates the worktree and displays the path. Navigate manually with `cd .worktrees/{branch-name}`.
**⚠️ Important - Claude Context**: If Claude Code is currently running, restart it in the new worktree:
```bash
/exit # Exit current Claude session
cd .worktrees/fix-bug-name # Navigate to worktree
claude # Start Claude in worktree context
```
Check cargo check status: `/tech:worktree-status feature/new-filter`
## Branch Naming Convention
**Always use Git branch naming with slashes:**
- ✅ `feature/new-filter` → Branch: `feature/new-filter`, Directory: `.worktrees/feature-new-filter`
- ✅ `fix/bug-name` → Branch: `fix/bug-name`, Directory: `.worktrees/fix-bug-name`
- ❌ `feature-new-filter` → Wrong: Missing category prefix
## Implementation
Execute this **single bash script** with branch name from `$ARGUMENTS`:
```bash
#!/bin/bash
set -euo pipefail
trap 'kill $(jobs -p) 2>/dev/null || true' EXIT
# Validate git repository - always use main repo root (not worktree root)
GIT_COMMON_DIR="$(git rev-parse --git-common-dir 2>/dev/null)"
if [ -z "$GIT_COMMON_DIR" ]; then
echo "❌ Not in a git repository"
exit 1
fi
REPO_ROOT="$(cd "$GIT_COMMON_DIR/.." && pwd)"
# Parse flags
RAW_ARGS="$ARGUMENTS"
BRANCH_NAME="$RAW_ARGS"
SKIP_CHECK=false
if [[ "$RAW_ARGS" == *"--fast"* ]]; then
SKIP_CHECK=true
BRANCH_NAME="${BRANCH_NAME// --fast/}"
fi
if [[ "$RAW_ARGS" == *"--no-check"* ]]; then
SKIP_CHECK=true
BRANCH_NAME="${BRANCH_NAME// --no-check/}"
fi
# Validate branch name
if [[ "$BRANCH_NAME" =~ [[:space:]\$\`] ]]; then
echo "❌ Invalid branch name (spaces or special characters not allowed)"
exit 1
fi
if [[ "$BRANCH_NAME" =~ [~^:?*\\\[\]] ]]; then
echo "❌ Invalid branch name (git forbidden characters: ~ ^ : ? * [ ])"
exit 1
fi
# Paths - sanitize slashes to avoid nested directories
WORKTREE_NAME="${BRANCH_NAME//\//-}"
WORKTREE_DIR="$REPO_ROOT/.worktrees/$WORKTREE_NAME"
LOG_FILE="/tmp/worktree-cargo-check-${WORKTREE_NAME}.log"
# 1. Check .gitignore (fail-fast)
if ! grep -qE "^\.worktrees/?$" "$REPO_ROOT/.gitignore" 2>/dev/null; then
echo "❌ .worktrees/ not in .gitignore"
echo "Run: echo '.worktrees/' >> .gitignore && git add .gitignore && git commit -m 'chore: ignore worktrees'"
exit 1
fi
# 2. Create worktree (fail-fast)
echo "Creating worktree for $BRANCH_NAME..."
mkdir -p "$REPO_ROOT/.worktrees"
if ! git worktree add "$WORKTREE_DIR" -b "$BRANCH_NAME" 2>/tmp/worktree-error.log; then
echo "❌ Failed to create worktree"
cat /tmp/worktree-error.log
exit 1
fi
# 3. Background cargo check (unless --fast / --no-check)
if [ "$SKIP_CHECK" = false ] && [ -f "$WORKTREE_DIR/Cargo.toml" ]; then
(
cd "$WORKTREE_DIR"
echo "⏳ Cargo check started at $(date +%H:%M:%S)" > "$LOG_FILE"
if cargo check --all-targets >> "$LOG_FILE" 2>&1; then
echo "✅ Cargo check passed at $(date +%H:%M:%S)" >> "$LOG_FILE"
else
echo "❌ Cargo check failed at $(date +%H:%M:%S)" >> "$LOG_FILE"
fi
) &
CHECK_RUNNING=true
else
CHECK_RUNNING=false
fi
# 4. Report (instant feedback)
echo ""
echo "✅ Worktree ready: $WORKTREE_DIR"
if [ "$CHECK_RUNNING" = true ]; then
echo "⏳ Cargo check running in background..."
echo "📝 Check status: /tech:worktree-status $BRANCH_NAME"
echo "📝 Or view log: cat $LOG_FILE"
elif [ "$SKIP_CHECK" = true ]; then
echo "⚡ Cargo check skipped (--fast / --no-check mode)"
fi
echo ""
echo "🚀 Next steps:"
echo ""
echo "If Claude Code is running:"
echo " 1. /exit"
echo " 2. cd $WORKTREE_DIR"
echo " 3. claude"
echo ""
echo "If Claude Code is NOT running:"
echo " cd $WORKTREE_DIR && claude"
echo ""
echo "✅ Ready to work!"
```
## Flags
### `--fast` / `--no-check`
Skip cargo check entirely (instant setup).
**Use when**: Quick fixes, documentation, README changes.
```bash
/tech:worktree fix/typo --fast
→ ✅ Ready in 1s (no cargo check)
```
## Status Check
```bash
/tech:worktree-status feature/new-filter
→ ✅ Cargo check passed (0 errors)
→ ❌ Cargo check failed (see log)
→ ⏳ Still running...
```
## Cleanup
```bash
/tech:remove-worktree feature/new-filter
# Or manually:
git worktree remove .worktrees/feature-new-filter
git worktree prune
```
## Troubleshooting
**"worktree already exists"**
```bash
git worktree remove .worktrees/$BRANCH_NAME
# Then retry
```
**"branch already exists"**
```bash
git branch -D $BRANCH_NAME
# Then retry
```
+128
View File
@@ -0,0 +1,128 @@
---
model: haiku
description: Check background cargo check status for a git worktree
---
# Worktree Status Check
Check the status of the background `cargo check` started by `/worktree`.
## Usage
```bash
/worktree-status feature/new-filter
/worktree-status fix/bug-name
```
## Implementation
Execute this script with branch name from `$ARGUMENTS`:
```bash
#!/bin/bash
set -euo pipefail
BRANCH_NAME="$ARGUMENTS"
LOG_FILE="/tmp/worktree-cargocheck-${BRANCH_NAME//\//-}.log"
if [ ! -f "$LOG_FILE" ]; then
echo "No cargo check found for branch: $BRANCH_NAME"
echo ""
echo "Possible reasons:"
echo "1. Worktree created with --fast (check skipped)"
echo "2. Branch name mismatch (use exact branch name)"
echo "3. Check hasn't started yet (wait a few seconds)"
echo ""
echo "Available logs:"
ls -1 /tmp/worktree-cargocheck-*.log 2>/dev/null || echo " (none)"
exit 1
fi
LOG_CONTENT=$(head -n 500 "$LOG_FILE")
if echo "$LOG_CONTENT" | grep -q "^PASSED"; then
TIMESTAMP=$(echo "$LOG_CONTENT" | grep "^PASSED" | sed 's/PASSED at //')
echo "cargo check passed"
echo " Completed at: $TIMESTAMP"
echo ""
echo "Worktree is ready for development!"
elif echo "$LOG_CONTENT" | grep -q "^FAILED"; then
TIMESTAMP=$(echo "$LOG_CONTENT" | grep "^FAILED" | sed 's/FAILED at //')
echo "cargo check failed"
echo " Completed at: $TIMESTAMP"
echo ""
echo "Errors:"
echo "-------------------------------------"
grep -v "^PASSED\|^FAILED\|^cargo check started" "$LOG_FILE" | head -30
echo "-------------------------------------"
echo ""
echo "Full log: cat $LOG_FILE"
echo ""
echo "You can still work on the worktree - fix errors as you go."
elif echo "$LOG_CONTENT" | grep -q "^cargo check started"; then
START_TIME=$(echo "$LOG_CONTENT" | grep "^cargo check started" | sed 's/cargo check started at //')
CURRENT_TIME=$(date +%H:%M:%S)
echo "cargo check still running..."
echo " Started at: $START_TIME"
echo " Current time: $CURRENT_TIME"
echo ""
echo "Usually takes 5-30s depending on crate size."
echo ""
echo "Live progress: tail -f $LOG_FILE"
else
echo "Unknown state"
echo ""
echo "Log content:"
cat "$LOG_FILE"
fi
```
## Output Examples
### Passed
```
cargo check passed
Completed at: 14:23:45
Worktree is ready for development!
```
### Failed
```
cargo check failed
Completed at: 14:24:12
Errors:
-------------------------------------
error[E0308]: mismatched types
--> src/git.rs:45:12
|
45 | let x: i32 = "hello";
-------------------------------------
Full log: cat /tmp/worktree-cargocheck-feature-new-filter.log
You can still work on the worktree - fix errors as you go.
```
### Still Running
```
cargo check still running...
Started at: 14:22:30
Current time: 14:22:45
Usually takes 5-30s depending on crate size.
Live progress: tail -f /tmp/worktree-cargocheck-feature-new-filter.log
```
## Integration
`/worktree` tells you the exact command to check status:
```
cargo check running in background...
Check status: /worktree-status feature/new-filter
```
+210
View File
@@ -0,0 +1,210 @@
---
model: haiku
description: Git Worktree Setup for RTK (Rust project)
---
# Git Worktree Setup
Create isolated git worktrees with instant feedback and background Rust verification.
**Performance**: ~1s setup + background `cargo check` (non-blocking)
## Usage
```bash
/worktree feature/new-filter # Creates worktree + background cargo check
/worktree fix/typo --fast # Skip cargo check (instant)
/worktree feature/big-refactor --check # Wait for cargo check (blocking)
```
**Branch naming**: Always use `category/description` with a slash.
- `feature/new-filter` -> branch: `feature/new-filter`, dir: `.worktrees/feature-new-filter`
- `fix/bug-name` -> branch: `fix/bug-name`, dir: `.worktrees/fix-bug-name`
## Implementation
Execute this **single bash script** with branch name from `$ARGUMENTS`:
```bash
#!/bin/bash
set -euo pipefail
trap 'kill $(jobs -p) 2>/dev/null || true' EXIT
# Resolve main repo root (works from worktree too)
GIT_COMMON_DIR="$(git rev-parse --git-common-dir 2>/dev/null)"
if [ -z "$GIT_COMMON_DIR" ]; then
echo "Not in a git repository"
exit 1
fi
REPO_ROOT="$(cd "$GIT_COMMON_DIR/.." && pwd)"
# Parse flags
RAW_ARGS="$ARGUMENTS"
BRANCH_NAME="$RAW_ARGS"
SKIP_CHECK=false
BLOCKING_CHECK=false
if [[ "$RAW_ARGS" == *"--fast"* ]]; then
SKIP_CHECK=true
BRANCH_NAME="${BRANCH_NAME// --fast/}"
fi
if [[ "$RAW_ARGS" == *"--check"* ]]; then
BLOCKING_CHECK=true
BRANCH_NAME="${BRANCH_NAME// --check/}"
fi
# Validate branch name
if [[ "$BRANCH_NAME" =~ [[:space:]\$\`] ]]; then
echo "Invalid branch name (spaces or special characters not allowed)"
exit 1
fi
if [[ "$BRANCH_NAME" =~ [~^:?*\\\[\]] ]]; then
echo "Invalid branch name (git forbidden characters)"
exit 1
fi
# Paths
WORKTREE_NAME="${BRANCH_NAME//\//-}"
WORKTREE_DIR="$REPO_ROOT/.worktrees/$WORKTREE_NAME"
LOG_FILE="/tmp/worktree-cargocheck-${WORKTREE_NAME}.log"
# 1. Check .gitignore (fail-fast)
if ! grep -qE "^\.worktrees/?$" "$REPO_ROOT/.gitignore" 2>/dev/null; then
echo ".worktrees/ not in .gitignore"
echo "Run: echo '.worktrees/' >> .gitignore && git add .gitignore && git commit -m 'chore: ignore worktrees'"
exit 1
fi
# 2. Create worktree
echo "Creating worktree for $BRANCH_NAME..."
mkdir -p "$REPO_ROOT/.worktrees"
if ! git worktree add "$WORKTREE_DIR" -b "$BRANCH_NAME" 2>/tmp/worktree-error.log; then
echo "Failed to create worktree:"
cat /tmp/worktree-error.log
exit 1
fi
# 3. Copy files listed in .worktreeinclude (non-blocking)
(
INCLUDE_FILE="$REPO_ROOT/.worktreeinclude"
if [ -f "$INCLUDE_FILE" ]; then
while IFS= read -r entry || [ -n "$entry" ]; do
[[ "$entry" =~ ^#.*$ || -z "$entry" ]] && continue
entry="$(echo "$entry" | xargs)"
SRC="$REPO_ROOT/$entry"
if [ -e "$SRC" ]; then
DEST_DIR="$(dirname "$WORKTREE_DIR/$entry")"
mkdir -p "$DEST_DIR"
cp -R "$SRC" "$WORKTREE_DIR/$entry"
fi
done < "$INCLUDE_FILE"
else
cp "$REPO_ROOT"/.env* "$WORKTREE_DIR/" 2>/dev/null || true
fi
) &
ENV_PID=$!
# Wait for env copy (with macOS-compatible timeout)
# gtimeout from coreutils if available, else plain wait
if command -v gtimeout >/dev/null 2>&1; then
gtimeout 10 wait $ENV_PID 2>/dev/null || true
else
wait $ENV_PID 2>/dev/null || true
fi
# 4. cargo check (background by default, blocking with --check)
if [ "$SKIP_CHECK" = false ]; then
if [ "$BLOCKING_CHECK" = true ]; then
echo "Running cargo check..."
if (cd "$WORKTREE_DIR" && cargo check 2>&1); then
echo "cargo check passed"
else
echo "cargo check failed (worktree still usable)"
fi
CHECK_RUNNING=false
else
# Background
(
cd "$WORKTREE_DIR"
echo "cargo check started at $(date +%H:%M:%S)" > "$LOG_FILE"
if cargo check >> "$LOG_FILE" 2>&1; then
echo "PASSED at $(date +%H:%M:%S)" >> "$LOG_FILE"
else
echo "FAILED at $(date +%H:%M:%S)" >> "$LOG_FILE"
fi
) &
CHECK_RUNNING=true
fi
else
CHECK_RUNNING=false
fi
# 5. Report
echo ""
echo "Worktree ready: $WORKTREE_DIR"
echo "Branch: $BRANCH_NAME"
if [ "$CHECK_RUNNING" = true ]; then
echo "cargo check running in background..."
echo "Check status: /worktree-status $BRANCH_NAME"
echo "Or view log: cat $LOG_FILE"
elif [ "$SKIP_CHECK" = true ]; then
echo "cargo check skipped (--fast)"
fi
echo ""
echo "Next steps:"
echo ""
echo "If Claude Code is running:"
echo " 1. /exit"
echo " 2. cd $WORKTREE_DIR"
echo " 3. claude"
echo ""
echo "If Claude Code is NOT running:"
echo " cd $WORKTREE_DIR && claude"
```
## Flags
### `--fast`
Skip `cargo check` (instant setup). Use for quick fixes, docs, small changes.
### `--check`
Run `cargo check` synchronously (blocking). Use when you need to confirm the build is clean before starting.
## Environment Files
Files listed in `.worktreeinclude` are copied automatically. If the file doesn't exist, `.env*` files are copied by default.
Example `.worktreeinclude` for RTK:
```
.env
.env.local
.claude/settings.local.json
```
## Cleanup
```bash
git worktree remove .worktrees/${BRANCH_NAME//\//-}
git worktree prune
```
## Troubleshooting
**"worktree already exists"**
```bash
git worktree remove .worktrees/feature-name
```
**"branch already exists"**
```bash
git branch -D feature/name
```
**cargo check log not found**
```bash
ls /tmp/worktree-cargocheck-*.log
```
+253
View File
@@ -0,0 +1,253 @@
# Rust Patterns — RTK Development Rules
RTK-specific Rust idioms and constraints. Applied to all code in this repository.
## Non-Negotiable RTK Rules
These override general Rust conventions:
1. **No async** — Zero `tokio`, `async-std`, `futures`. Single-threaded by design. Async adds 5-10ms startup.
2. **No `unwrap()` in production** — Use `.context("description")?`. Tests: use `expect("reason")`.
3. **Lazy regex** — `Regex::new()` inside a function recompiles on every call. Always `lazy_static!`.
4. **Fallback pattern** — If filter fails, execute raw command unchanged. Never block the user.
5. **Exit code propagation** — `std::process::exit(code)` if underlying command fails.
## Error Handling
### Always context, always anyhow
```rust
use anyhow::{Context, Result};
// ✅ Correct
fn read_config(path: &Path) -> Result<Config> {
let content = fs::read_to_string(path)
.with_context(|| format!("Failed to read config: {}", path.display()))?;
toml::from_str(&content)
.context("Failed to parse config TOML")
}
// ❌ Wrong — no context
fn read_config(path: &Path) -> Result<Config> {
let content = fs::read_to_string(path)?;
Ok(toml::from_str(&content)?)
}
// ❌ Wrong — panic in production
fn read_config(path: &Path) -> Config {
let content = fs::read_to_string(path).unwrap();
toml::from_str(&content).unwrap()
}
```
### Fallback pattern (mandatory for all filters)
```rust
pub fn run(args: MyArgs) -> Result<()> {
let output = execute_command("mycmd", &args.to_cmd_args())
.context("Failed to execute mycmd")?;
let filtered = filter_output(&output.stdout)
.unwrap_or_else(|e| {
eprintln!("rtk: filter warning: {}", e);
output.stdout.clone() // Passthrough on failure
});
tracking::record("mycmd", &output.stdout, &filtered)?;
print!("{}", filtered);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
}
```
## Regex — Always lazy_static
```rust
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref ERROR_RE: Regex = Regex::new(r"^error\[").unwrap();
static ref HASH_RE: Regex = Regex::new(r"^[0-9a-f]{7,40}").unwrap();
}
// ✅ Correct — regex compiled once at first use
fn is_error_line(line: &str) -> bool {
ERROR_RE.is_match(line)
}
// ❌ Wrong — recompiles every call (kills performance)
fn is_error_line(line: &str) -> bool {
let re = Regex::new(r"^error\[").unwrap();
re.is_match(line)
}
```
Note: `lazy_static!` with `.unwrap()` for initialization is the **established RTK pattern** — it's acceptable because a bad regex literal is a programming error caught at first use.
## Ownership — Borrow Over Clone
```rust
// ✅ Prefer borrows in filter functions
fn filter_lines<'a>(input: &'a str) -> Vec<&'a str> {
input.lines()
.filter(|line| !line.is_empty())
.collect()
}
// ✅ Clone only when you need to own the data
fn filter_output(input: &str) -> String {
input.lines()
.filter(|line| !line.trim().is_empty())
.collect::<Vec<_>>()
.join("\n")
}
// ❌ Unnecessary clone
fn filter_output(input: &str) -> String {
let owned = input.to_string(); // Clone for no reason
owned.lines()
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
```
## Iterators Over Loops
```rust
// ✅ Iterator chain — idiomatic
let errors: Vec<&str> = output.lines()
.filter(|l| l.starts_with("error"))
.take(20)
.collect();
// ❌ Manual loop — verbose
let mut errors = Vec::new();
for line in output.lines() {
if line.starts_with("error") {
errors.push(line);
if errors.len() >= 20 { break; }
}
}
```
## Struct Patterns
### Builder for complex args
```rust
// Use Builder when struct has >5 optional fields
pub struct FilterConfig {
max_lines: usize,
show_warnings: bool,
strip_ansi: bool,
}
impl FilterConfig {
pub fn new() -> Self {
Self { max_lines: 100, show_warnings: false, strip_ansi: true }
}
pub fn max_lines(mut self, n: usize) -> Self { self.max_lines = n; self }
pub fn show_warnings(mut self, v: bool) -> Self { self.show_warnings = v; self }
}
// Usage: FilterConfig::new().max_lines(50).show_warnings(true)
```
### Newtype for validation
```rust
// Newtype prevents misuse of raw strings
pub struct CommandName(String);
impl CommandName {
pub fn new(name: &str) -> Result<Self> {
if name.contains(';') || name.contains('|') {
anyhow::bail!("Invalid command name: contains shell metacharacters");
}
Ok(Self(name.to_string()))
}
}
```
## String Handling
```rust
// String: owned, heap-allocated
// &str: borrowed slice (prefer in function signatures)
// &String: almost never — use &str instead
fn process(input: &str) -> String { // ✅ &str in, String out
input.trim().to_uppercase()
}
fn process(input: &String) -> String { // ❌ Unnecessary &String
input.trim().to_uppercase()
}
```
## Match — Exhaustive and Explicit
```rust
// ✅ Exhaustive match with explicit cases
match result {
Ok(output) => process(output),
Err(e) => {
eprintln!("rtk: filter warning: {}", e);
fallback()
}
}
// ❌ Silent swallow — catastrophic in RTK (user gets no output)
match result {
Ok(output) => process(output),
Err(_) => {}
}
```
## Module Structure
Every `*_cmd.rs` follows this pattern:
```rust
// 1. Imports
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
// 2. Types (args struct)
pub struct MyArgs { ... }
// 3. Lazy regexes
lazy_static! { static ref MY_RE: Regex = ...; }
// 4. Public entry point
pub fn run(args: MyArgs) -> Result<()> { ... }
// 5. Private filter functions
fn filter_output(input: &str) -> Result<String> { ... }
// 6. Tests (always present)
#[cfg(test)]
mod tests {
use super::*;
fn count_tokens(s: &str) -> usize { s.split_whitespace().count() }
// ... snapshot tests, savings tests
}
```
## Anti-Patterns (RTK-Specific)
| Pattern | Problem | Fix |
|---------|---------|-----|
| `Regex::new()` in function | Recompiles every call | `lazy_static!` |
| `unwrap()` in production | Panic breaks user workflow | `.context()?` |
| `tokio::main` or `async fn` | +5-10ms startup | Blocking I/O only |
| Silent match `Err(_) => {}` | User gets no output | Log warning + fallback |
| `println!` in filter path | Debug artifact in output | Remove or `eprintln!` |
| Returning early without exit code | CI/CD thinks command succeeded | `std::process::exit(code)` |
| `clone()` of large strings | Extra allocation in hot path | Borrow with `&str` |
+142
View File
@@ -0,0 +1,142 @@
# Search Strategy — RTK Codebase Navigation
Efficient search patterns for RTK's Rust codebase.
## Priority Order
1. **Grep** (exact pattern, fast) → for known symbols/strings
2. **Glob** (file discovery) → for finding modules by name
3. **Read** (full file) → only after locating the right file
4. **Explore agent** (broad research) → last resort for >3 queries
Never use Bash for search (`find`, `grep`, `rg`) — use dedicated tools.
## RTK Module Map
```
src/
├── main.rs ← Commands enum + routing (start here for any command)
├── git.rs ← Git operations (log, status, diff)
├── runner.rs ← Cargo commands (test, build, clippy, check)
├── gh_cmd.rs ← GitHub CLI (pr, run, issue)
├── grep_cmd.rs ← Code search output filtering
├── ls.rs ← Directory listing
├── read.rs ← File reading with filter levels
├── filter.rs ← Language-aware code filtering engine
├── tracking.rs ← SQLite token metrics
├── config.rs ← ~/.config/rtk/config.toml
├── tee.rs ← Raw output recovery on failure
├── utils.rs ← strip_ansi, truncate, execute_command
├── init.rs ← rtk init command
└── *_cmd.rs ← All other command modules
```
## Common Search Patterns
### "Where is command X handled?"
```
# Step 1: Find the routing
Grep pattern="Gh\|Cargo\|Git\|Grep" path="src/main.rs" output_mode="content"
# Step 2: Follow to module
Read file_path="src/gh_cmd.rs"
```
### "Where is function X defined?"
```
Grep pattern="fn filter_git_log\|fn run\b" type="rust"
```
### "All command modules"
```
Glob pattern="src/*_cmd.rs"
# Then: src/git.rs, src/runner.rs for non-*_cmd.rs modules
```
### "Find all lazy_static regex definitions"
```
Grep pattern="lazy_static!" type="rust" output_mode="content"
```
### "Find unwrap() outside tests"
```
Grep pattern="\.unwrap()" type="rust" output_mode="content"
# Then manually filter out #[cfg(test)] blocks
```
### "Which modules have tests?"
```
Grep pattern="#\[cfg\(test\)\]" type="rust" output_mode="files_with_matches"
```
### "Find token savings assertions"
```
Grep pattern="count_tokens\|savings" type="rust" output_mode="content"
```
### "Find test fixtures"
```
Glob pattern="tests/fixtures/*.txt"
```
## RTK-Specific Navigation Rules
### Adding a new filter
1. Check `src/main.rs` for Commands enum structure
2. Check existing `*_cmd.rs` for patterns to follow (e.g., `src/gh_cmd.rs`)
3. Check `src/utils.rs` for shared helpers before reimplementing
4. Check `tests/fixtures/` for existing fixture patterns
### Debugging filter output
1. Start with `src/<cmd>_cmd.rs` → find `run()` function
2. Trace filter function (usually `filter_<cmd>()`)
3. Check `lazy_static!` regex patterns in same file
4. Check `src/utils.rs::strip_ansi()` if ANSI codes involved
### Tracking/metrics issues
1. `src/tracking.rs` → `track_command()` function
2. `src/config.rs` → `tracking.database_path` field
3. `RTK_DB_PATH` env var overrides config
### Configuration issues
1. `src/config.rs` → `RtkConfig` struct
2. `src/init.rs` → `rtk init` command
3. Config file: `~/.config/rtk/config.toml`
4. Filter files: `~/.config/rtk/filters/` (global) or `.rtk/filters/` (project)
## TOML Filter DSL Navigation
```
Glob pattern=".rtk/filters/*.toml" # Project-local filters
Glob pattern="src/filter_*.rs" # TOML filter engine
Grep pattern="FilterRule\|FilterConfig" type="rust"
```
## Anti-Patterns
❌ **Don't** read all `*_cmd.rs` files to find one function — use Grep first
❌ **Don't** use Bash `find src -name "*.rs"` — use Glob
❌ **Don't** read `main.rs` entirely to find a module — Grep for the command name
❌ **Don't** search `Cargo.toml` for dependencies with Bash — use Grep with `glob="Cargo.toml"`
## Dependency Check
```
# Check if a crate is already used (before adding)
Grep pattern="^regex\|^anyhow\|^rusqlite" glob="Cargo.toml" output_mode="content"
# Check if async is creeping in (forbidden)
Grep pattern="tokio\|async-std\|futures\|async fn" type="rust"
```
+171
View File
@@ -0,0 +1,171 @@
---
name: code-simplifier
description: Review RTK Rust code for idiomatic simplification. Detects over-engineering, unnecessary allocations, verbose patterns. Applies Rust idioms without changing behavior.
triggers:
- "simplify"
- "too verbose"
- "over-engineered"
- "refactor this"
- "make this idiomatic"
---
# RTK Code Simplifier
Review and simplify Rust code in RTK while respecting the project's constraints.
## Constraints (never simplify away)
- `lazy_static!` regex — cannot be moved inside functions even if "simpler"
- `.context()` on every `?` — verbose but mandatory
- Fallback to raw command — never remove even if it looks like dead code
- Exit code propagation — never simplify to `Ok(())`
- `#[cfg(test)] mod tests` — never remove test modules
## Simplification Patterns
### 1. Iterator chains over manual loops
```rust
// ❌ Verbose
let mut result = Vec::new();
for line in input.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && trimmed.starts_with("error") {
result.push(trimmed.to_string());
}
}
// ✅ Idiomatic
let result: Vec<String> = input.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty() && l.starts_with("error"))
.map(str::to_string)
.collect();
```
### 2. String building
```rust
// ❌ Verbose push loop
let mut out = String::new();
for (i, line) in lines.iter().enumerate() {
out.push_str(line);
if i < lines.len() - 1 {
out.push('\n');
}
}
// ✅ join
let out = lines.join("\n");
```
### 3. Option/Result chaining
```rust
// ❌ Nested match
let result = match maybe_value {
Some(v) => match transform(v) {
Ok(r) => r,
Err(_) => default,
},
None => default,
};
// ✅ Chained
let result = maybe_value
.and_then(|v| transform(v).ok())
.unwrap_or(default);
```
### 4. Struct destructuring
```rust
// ❌ Repeated field access
fn process(args: &MyArgs) -> String {
format!("{} {}", args.command, args.subcommand)
}
// ✅ Destructure
fn process(&MyArgs { ref command, ref subcommand, .. }: &MyArgs) -> String {
format!("{} {}", command, subcommand)
}
```
### 5. Early returns over nesting
```rust
// ❌ Deeply nested
fn filter(input: &str) -> Option<String> {
if !input.is_empty() {
if let Some(line) = input.lines().next() {
if line.starts_with("error") {
return Some(line.to_string());
}
}
}
None
}
// ✅ Early return
fn filter(input: &str) -> Option<String> {
if input.is_empty() { return None; }
let line = input.lines().next()?;
if !line.starts_with("error") { return None; }
Some(line.to_string())
}
```
### 6. Avoid redundant clones
```rust
// ❌ Unnecessary clone
fn filter_output(input: &str) -> String {
let s = input.to_string(); // Pointless clone
s.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
// ✅ Work with &str
fn filter_output(input: &str) -> String {
input.lines().filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
}
```
### 7. Use `if let` for single-variant match
```rust
// ❌ Full match for one variant
match output {
Ok(s) => process(&s),
Err(_) => {},
}
// ✅ if let (but still handle errors in RTK — don't silently drop)
if let Ok(s) = output {
process(&s);
}
// Note: in RTK filters, always handle Err with eprintln! + fallback
```
## RTK-Specific Checks
Run these after simplification:
```bash
# Verify no regressions
cargo fmt --all && cargo clippy --all-targets && cargo test
# Verify no new regex in functions
grep -n "Regex::new" src/<file>.rs
# All should be inside lazy_static! blocks
# Verify no new unwrap in production
grep -n "\.unwrap()" src/<file>.rs
# Should only appear inside #[cfg(test)] blocks
```
## What NOT to Simplify
- `lazy_static! { static ref RE: Regex = Regex::new(...).unwrap(); }` — the `.unwrap()` here is acceptable, it's init-time
- `.context("description")?` chains — verbose but required
- The fallback match arm `Err(e) => { eprintln!(...); raw_output }` — looks redundant but is the safety net
- `std::process::exit(code)` at end of run() — looks like it could be `Ok(())`but it isn't
+242
View File
@@ -0,0 +1,242 @@
---
name: design-patterns
description: Rust design patterns for RTK. Newtype, Builder, RAII, Trait Objects, State Machine. Applied to CLI filter modules. Use when designing new modules or refactoring existing ones.
triggers:
- "design pattern"
- "how to structure"
- "best pattern for"
- "refactor to pattern"
---
# RTK Rust Design Patterns
Patterns that apply to RTK's filter module architecture. Focused on CLI tool patterns, not web/service patterns.
## Pattern 1: Newtype (Type Safety)
Use when: wrapping primitive types to prevent misuse (command names, paths, token counts).
```rust
// Without Newtype — easy to mix up
fn track(input_tokens: usize, output_tokens: usize) { ... }
track(output_tokens, input_tokens); // Silent bug!
// With Newtype — compile error on swap
pub struct InputTokens(pub usize);
pub struct OutputTokens(pub usize);
fn track(input: InputTokens, output: OutputTokens) { ... }
track(OutputTokens(100), InputTokens(400)); // Compile error ✅
```
```rust
// Practical RTK example: command name validation
pub struct CommandName(String);
impl CommandName {
pub fn new(s: &str) -> Result<Self> {
if s.contains(';') || s.contains('|') || s.contains('`') {
anyhow::bail!("Invalid command name: shell metacharacters");
}
Ok(Self(s.to_string()))
}
pub fn as_str(&self) -> &str { &self.0 }
}
```
## Pattern 2: Builder (Complex Configuration)
Use when: a struct has 4+ optional fields, many with defaults.
```rust
#[derive(Default)]
pub struct FilterConfig {
max_lines: Option<usize>,
strip_ansi: bool,
show_warnings: bool,
truncate_at: Option<usize>,
}
impl FilterConfig {
pub fn new() -> Self { Self::default() }
pub fn max_lines(mut self, n: usize) -> Self { self.max_lines = Some(n); self }
pub fn strip_ansi(mut self, v: bool) -> Self { self.strip_ansi = v; self }
pub fn show_warnings(mut self, v: bool) -> Self { self.show_warnings = v; self }
}
// Usage — readable, no positional arg confusion
let config = FilterConfig::new()
.max_lines(50)
.strip_ansi(true)
.show_warnings(false);
```
When NOT to use Builder: if the struct has 1-3 fields with obvious meaning. Over-engineering for simple cases.
## Pattern 3: State Machine (Parser/Filter Flows)
Use when: parsing multi-section output (test results, build output) where context changes behavior.
```rust
// RTK example: pytest output parsing
#[derive(Debug, PartialEq)]
enum ParseState {
LookingForTests,
InTestOutput,
InFailureSummary,
Done,
}
fn parse_pytest(input: &str) -> String {
let mut state = ParseState::LookingForTests;
let mut failures = Vec::new();
for line in input.lines() {
match state {
ParseState::LookingForTests => {
if line.contains("FAILED") || line.contains("ERROR") {
state = ParseState::InFailureSummary;
failures.push(line);
}
}
ParseState::InFailureSummary => {
if line.starts_with("=====") { state = ParseState::Done; }
else { failures.push(line); }
}
ParseState::Done => break,
_ => {}
}
}
failures.join("\n")
}
```
## Pattern 4: Trait Object (Command Dispatch)
Use when: different command families need the same interface. Avoids massive match arms.
```rust
// Define a common interface for filters
pub trait OutputFilter {
fn filter(&self, input: &str) -> Result<String>;
fn command_name(&self) -> &str;
}
pub struct GitFilter;
pub struct CargoFilter;
impl OutputFilter for GitFilter {
fn filter(&self, input: &str) -> Result<String> { filter_git(input) }
fn command_name(&self) -> &str { "git" }
}
// RTK currently uses match-based dispatch in main.rs (simpler, no dynamic dispatch overhead)
// Trait objects are useful if filter registry becomes dynamic (e.g., TOML-loaded plugins)
```
Note: RTK's current `match` dispatch in `main.rs` is intentional — static dispatch, zero overhead. Only move to trait objects if the match arm count exceeds ~20 commands.
## Pattern 5: RAII (Resource Management)
Use when: managing resources that need cleanup (temp files, SQLite connections).
```rust
// RTK tee.rs — RAII for temp output files
pub struct TeeFile {
path: PathBuf,
}
impl TeeFile {
pub fn create(content: &str) -> Result<Self> {
let path = tee_path()?;
fs::write(&path, content)
.with_context(|| format!("Failed to write tee file: {}", path.display()))?;
Ok(Self { path })
}
pub fn path(&self) -> &Path { &self.path }
}
// No explicit cleanup needed — file persists intentionally (rotation handled separately)
// If cleanup were needed: impl Drop { fn drop(&mut self) { let _ = fs::remove_file(&self.path); } }
```
## Pattern 6: Strategy (Swappable Filter Logic)
Use when: a command has multiple filtering modes (e.g., compact vs. verbose).
```rust
pub enum FilterMode {
Compact, // Show only failures/errors
Summary, // Show counts + top errors
Full, // Pass through unchanged
}
pub fn apply_filter(input: &str, mode: FilterMode) -> String {
match mode {
FilterMode::Compact => filter_compact(input),
FilterMode::Summary => filter_summary(input),
FilterMode::Full => input.to_string(),
}
}
```
## Pattern 7: Extension Trait (Add Methods to External Types)
Use when: you need to add methods to types you don't own (like `&str` for RTK-specific parsing).
```rust
pub trait RtkStrExt {
fn is_error_line(&self) -> bool;
fn is_warning_line(&self) -> bool;
fn token_count(&self) -> usize;
}
impl RtkStrExt for str {
fn is_error_line(&self) -> bool {
self.starts_with("error") || self.contains("[E")
}
fn is_warning_line(&self) -> bool {
self.starts_with("warning")
}
fn token_count(&self) -> usize {
self.split_whitespace().count()
}
}
// Usage
if line.is_error_line() { ... }
let tokens = output.token_count();
```
## RTK Pattern Selection Guide
| Situation | Pattern | Avoid |
|-----------|---------|-------|
| New `*_cmd.rs` filter module | Standard module pattern (see CLAUDE.md) | Over-abstracting |
| 4+ optional config fields | Builder | Struct literal |
| Multi-phase output parsing | State Machine | Nested if/else |
| Type-safe wrapper around string | Newtype | Raw `String` |
| Adding methods to `&str` | Extension Trait | Free functions |
| Resource with cleanup | RAII / Drop | Manual cleanup |
| Dynamic filter registry | Trait Object | Match sprawl |
## Anti-Patterns in RTK Context
```rust
// ❌ Generic over-engineering for one command
pub trait Filterable<T: CommandArgs + Send + Sync + 'static> { ... }
// ✅ Just write the function
pub fn filter_git_log(input: &str) -> Result<String> { ... }
// ❌ Singleton registry with global state
static FILTER_REGISTRY: Mutex<HashMap<String, Box<dyn Filter>>> = ...;
// ✅ Match in main.rs — simple, zero overhead, easy to trace
// ❌ Async traits for "future-proofing"
#[async_trait]
pub trait Filter { async fn apply(&self, input: &str) -> Result<String>; }
// ✅ Synchronous — RTK is single-threaded by design
pub trait Filter { fn apply(&self, input: &str) -> Result<String>; }
```
+209
View File
@@ -0,0 +1,209 @@
---
name: performance
description: RTK CLI performance analysis and optimization. Startup time (<10ms), binary size (<5MB), regex compilation, memory usage. Use when adding dependencies, changing initialization, or suspecting regressions.
triggers:
- "startup time"
- "performance regression"
- "too slow"
- "benchmark"
- "binary size"
- "memory usage"
---
# RTK Performance Analysis
## Hard Targets (Non-Negotiable)
| Metric | Target | Blocker |
|--------|--------|---------|
| Startup time | <10ms | Release blocker |
| Binary size (stripped) | <5MB | Release blocker |
| Memory (resident) | <5MB | Release blocker |
| Token savings per filter | ≥60% | Release blocker |
## Benchmark Startup Time
```bash
# Install hyperfine (once)
brew install hyperfine
# Baseline (before changes)
hyperfine 'rtk git status' --warmup 3 --export-json /tmp/before.json
# After changes — rebuild first
cargo build --release
# Compare against installed
hyperfine 'target/release/rtk git status' 'rtk git status' --warmup 3
# Target: <10ms mean time
```
## Check Binary Size
```bash
# Release build with strip=true (already in Cargo.toml)
cargo build --release
ls -lh target/release/rtk
# Should be <5MB
# If too large — check what's contributing
cargo bloat --release --crates
cargo bloat --release -n 20
# Install: cargo install cargo-bloat
```
## Memory Usage
```bash
# macOS
/usr/bin/time -l target/release/rtk git status 2>&1 | grep "maximum resident"
# Target: <5,000,000 bytes (5MB)
# Linux
/usr/bin/time -v target/release/rtk git status 2>&1 | grep "Maximum resident"
# Target: <5,000 kbytes
```
## Regex Compilation Audit
Regex compilation on every function call is a common perf killer:
```bash
# Find all Regex::new calls
grep -n "Regex::new" src/*.rs
# Verify ALL are inside lazy_static! blocks
# Any Regex::new outside lazy_static! = performance bug
```
```rust
// ❌ Recompiles on every filter_line() call
fn filter_line(line: &str) -> bool {
let re = Regex::new(r"^error").unwrap(); // BAD
re.is_match(line)
}
// ✅ Compiled once at first use
lazy_static! {
static ref ERROR_RE: Regex = Regex::new(r"^error").unwrap();
}
fn filter_line(line: &str) -> bool {
ERROR_RE.is_match(line) // GOOD
}
```
## Dependency Impact Assessment
Before adding any new crate:
```bash
# Check startup impact (measure before adding)
hyperfine 'rtk git status' --warmup 3
# Add dependency to Cargo.toml
# Rebuild
cargo build --release
# Measure after
hyperfine 'target/release/rtk git status' --warmup 3
# If startup increased >1ms — investigate
# If startup increased >3ms — reject the dependency
```
### Forbidden dependencies
| Crate | Reason | Alternative |
|-------|--------|-------------|
| `tokio` | +5-10ms startup | Blocking `std::process::Command` |
| `async-std` | +5-10ms startup | Blocking I/O |
| `rayon` | Thread pool init overhead | Sequential iteration |
| `reqwest` | Pulls tokio | `ureq` (blocking) if HTTP needed |
### Dependency weight check
```bash
# After cargo build --release
cargo build --release --timings
# Open target/cargo-timings/cargo-timing.html
# Look for crates with long compile times (correlates with complexity)
```
## Allocation Profiling
```bash
# macOS — use Instruments
instruments -t Allocations target/release/rtk git log -10
# Or use cargo-instruments
cargo install cargo-instruments
cargo instruments --release -t Allocations -- git log -10
```
Common RTK allocation hotspots:
```rust
// ❌ Allocates new String on every line
let lines: Vec<String> = input.lines().map(|l| l.to_string()).collect();
// ✅ Borrow slices
let lines: Vec<&str> = input.lines().collect();
// ❌ Clone large output unnecessarily
let raw_copy = output.stdout.clone();
// ✅ Use reference until you actually need to own
let display = &output.stdout;
```
## Token Savings Measurement
```rust
// In tests — always verify claims
fn count_tokens(text: &str) -> usize {
text.split_whitespace().count()
}
#[test]
fn test_savings_claim() {
let input = include_str!("../tests/fixtures/mycmd_raw.txt");
let output = filter_output(input).unwrap();
let input_tokens = count_tokens(input);
let output_tokens = count_tokens(&output);
let savings = 100.0 * (1.0 - output_tokens as f64 / input_tokens as f64);
assert!(
savings >= 60.0,
"Expected ≥60% savings, got {:.1}% ({} → {} tokens)",
savings, input_tokens, output_tokens
);
}
```
## Before/After Regression Check
Template for any performance-sensitive change:
```bash
# 1. Baseline
cargo build --release
hyperfine 'target/release/rtk git status' --warmup 5 --export-json /tmp/before.json
/usr/bin/time -l target/release/rtk git status 2>&1 | grep "maximum resident"
ls -lh target/release/rtk
# 2. Make changes
# ... edit code ...
# 3. Rebuild and compare
cargo build --release
hyperfine 'target/release/rtk git status' --warmup 5 --export-json /tmp/after.json
/usr/bin/time -l target/release/rtk git status 2>&1 | grep "maximum resident"
ls -lh target/release/rtk
# 4. Compare
# Startup: jq '.results[0].mean' /tmp/before.json /tmp/after.json
# If after > before + 1ms: investigate
# If after > 10ms: regression, do not merge
```
+283
View File
@@ -0,0 +1,283 @@
---
name: tdd-rust
description: TDD workflow for RTK filter development. Red-Green-Refactor with Rust idioms. Real fixtures, token savings assertions, snapshot tests with insta. Auto-triggers on new filter implementation.
triggers:
- "new filter"
- "implement filter"
- "add command"
- "write tests for"
- "test coverage"
- "fix failing test"
---
# RTK TDD Workflow
Enforce Red-Green-Refactor for all RTK filter development.
## The Loop
```
1. RED — Write failing test with real fixture
2. GREEN — Implement minimum code to pass
3. REFACTOR — Clean up, verify still passing
4. SAVINGS — Verify ≥60% token reduction
5. SNAPSHOT — Lock output format with insta
```
## Step 1: Real Fixture First
Never write synthetic test data. Capture real command output:
```bash
# Capture real output from the actual command
git log -20 > tests/fixtures/git_log_raw.txt
cargo test 2>&1 > tests/fixtures/cargo_test_raw.txt
cargo clippy 2>&1 > tests/fixtures/cargo_clippy_raw.txt
gh pr view 42 > tests/fixtures/gh_pr_view_raw.txt
# For commands with ANSI codes — capture as-is
script -q /dev/null cargo test 2>&1 > tests/fixtures/cargo_test_ansi_raw.txt
```
Fixture naming: `tests/fixtures/<command>_raw.txt`
## Step 2: Write the Test (Red)
```rust
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
fn count_tokens(s: &str) -> usize {
s.split_whitespace().count()
}
// Test 1: Output format (snapshot)
#[test]
fn test_filter_output_format() {
let input = include_str!("../tests/fixtures/mycmd_raw.txt");
let output = filter_mycmd(input).expect("filter should not fail");
assert_snapshot!(output);
}
// Test 2: Token savings ≥60%
#[test]
fn test_token_savings() {
let input = include_str!("../tests/fixtures/mycmd_raw.txt");
let output = filter_mycmd(input).expect("filter should not fail");
let input_tokens = count_tokens(input);
let output_tokens = count_tokens(&output);
let savings = 100.0 * (1.0 - output_tokens as f64 / input_tokens as f64);
assert!(
savings >= 60.0,
"Expected ≥60% token savings, got {:.1}% ({} → {} tokens)",
savings, input_tokens, output_tokens
);
}
// Test 3: Edge cases
#[test]
fn test_empty_input() {
let result = filter_mycmd("");
assert!(result.is_ok());
// Empty input = empty output OR passthrough, never panic
}
#[test]
fn test_malformed_input() {
let result = filter_mycmd("not valid command output\nrandom text\n");
// Must not panic — either filter best-effort or return input unchanged
assert!(result.is_ok());
}
}
```
Run: `cargo test` → should fail (function doesn't exist yet).
## Step 3: Minimum Implementation (Green)
```rust
// src/mycmd_cmd.rs
use anyhow::{Context, Result};
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref ERROR_RE: Regex = Regex::new(r"^error").unwrap();
}
pub fn filter_mycmd(input: &str) -> Result<String> {
if input.is_empty() {
return Ok(String::new());
}
let filtered: Vec<&str> = input.lines()
.filter(|line| ERROR_RE.is_match(line))
.collect();
Ok(filtered.join("\n"))
}
```
Run: `cargo test` → green.
## Step 4: Accept Snapshot
```bash
# First run creates the snapshot
cargo test test_filter_output_format
# Review what was captured
cargo insta review
# Press 'a' to accept
# Snapshot saved to src/snapshots/mycmd_cmd__tests__test_filter_output_format.snap
```
## Step 5: Wire to main.rs (Integration)
```rust
// src/main.rs
mod mycmd_cmd;
#[derive(Subcommand)]
pub enum Commands {
// ... existing commands ...
Mycmd(MycmdArgs),
}
// In match:
Commands::Mycmd(args) => mycmd_cmd::run(args),
```
```rust
// src/mycmd_cmd.rs — add run() function
pub fn run(args: MycmdArgs) -> Result<()> {
let output = execute_command("mycmd", &args.to_vec())
.context("Failed to execute mycmd")?;
let filtered = filter_mycmd(&output.stdout)
.unwrap_or_else(|e| {
eprintln!("rtk: filter warning: {}", e);
output.stdout.clone()
});
tracking::record("mycmd", &output.stdout, &filtered)?;
print!("{}", filtered);
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
}
```
## Step 6: Quality Gate
```bash
cargo fmt --all && cargo clippy --all-targets && cargo test
```
All 3 must pass. Zero clippy warnings.
## Arrange-Act-Assert Pattern
```rust
#[test]
fn test_filters_only_errors() {
// Arrange
let input = "info: starting build\nerror[E0001]: undefined\nwarning: unused\n";
// Act
let output = filter_mycmd(input).expect("should succeed");
// Assert
assert!(output.contains("error[E0001]"), "Should keep error lines");
assert!(!output.contains("info:"), "Should drop info lines");
assert!(!output.contains("warning:"), "Should drop warning lines");
}
```
## RTK-Specific Test Patterns
### Test ANSI stripping
```rust
#[test]
fn test_strips_ansi_codes() {
let input = "\x1b[32mSuccess\x1b[0m\n\x1b[31merror: failed\x1b[0m\n";
let output = filter_mycmd(input).expect("should succeed");
assert!(!output.contains("\x1b["), "ANSI codes should be stripped");
assert!(output.contains("error: failed"), "Content should be preserved");
}
```
### Test fallback behavior
```rust
#[test]
fn test_filter_handles_unexpected_format() {
// Give it something completely unexpected
let input = "completely unexpected\x00binary\xff data";
// Should not panic — returns Ok() with either empty or passthrough
let result = filter_mycmd(input);
assert!(result.is_ok(), "Filter must not panic on unexpected input");
}
```
### Test savings at multiple sizes
```rust
#[test]
fn test_savings_large_output() {
// 1000-line fixture → must still hit ≥60%
let large_input: String = (0..1000)
.map(|i| format!("info: processing item {}\n", i))
.collect();
let output = filter_mycmd(&large_input).expect("should succeed");
let savings = 100.0 * (1.0 - count_tokens(&output) as f64 / count_tokens(&large_input) as f64);
assert!(savings >= 60.0, "Large output savings: {:.1}%", savings);
}
```
## What "Done" Looks Like
Checklist before moving on:
- [ ] `tests/fixtures/<cmd>_raw.txt` — real command output
- [ ] `filter_<cmd>()` function returns `Result<String>`
- [ ] Snapshot test passes and accepted via `cargo insta review`
- [ ] Token savings test: ≥60% verified
- [ ] Empty input test: no panic
- [ ] Malformed input test: no panic
- [ ] `run()` function with fallback pattern
- [ ] Registered in `main.rs` Commands enum
- [ ] `cargo fmt --all && cargo clippy --all-targets && cargo test` — all green
## Never Do This
```rust
// ❌ Synthetic fixture data
let input = "fake error: something went wrong"; // Not real cargo output
// ❌ Missing savings test
#[test]
fn test_filter() {
let output = filter_mycmd(input);
assert!(!output.is_empty()); // No savings verification
}
// ❌ unwrap() in production code
let filtered = filter_mycmd(input).unwrap(); // Panic in prod
// ❌ Regex inside the filter function
fn filter_mycmd(input: &str) -> Result<String> {
let re = Regex::new(r"^error").unwrap(); // Recompiles every call
...
}
```
+138
View File
@@ -0,0 +1,138 @@
# CI/CD Flows
## PR Quality Gates (ci.yml)
Trigger: pull_request to develop or master
```
┌──────────────────┐
│ PR opened │
└────────┬─────────┘
│
┌────────▼─────────┐
│ fmt │
└────────┬─────────┘
│
┌────────▼─────────┐
│ clippy │
└──┬───┬───┬───┬───┘
│ │ │ │
┌──────────────┘ │ │ └──────────────┐
│ ┌───────┘ └───────┐ │
▼ ▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌───────────┐ ┌──────────┐
│ test │ │Security Scan │ │ benchmark │ │ validate │
│ ubuntu │ │ cargo audit │ │ >=80% │ │ ai agent │
│ windows │ │ (advisory) │ │ savings │ │ doc │
│ macos │ │ │ │ │ │ │
└──────┬───────┘ └──────┬───────┘ └─────┬─────┘ └────┬─────┘
│ │ │ │
└────────────────┴───────┬───────┴─────────────┘
│
┌──────────▼─────────┐
│ All must pass │
│ to merge │
└────────────────────┘
+ DCO check (independent, develop PRs only)
```
## Merge to develop — pre-release (cd.yml)
Trigger: push to develop | Concurrency: cancel-in-progress
```
┌──────────────────┐
│ push to develop │
└────────┬─────────┘
│
┌────────▼──────────────────┐
│ pre-release │
│ read Cargo.toml version │
│ tag = v{ver}-rc.{run} │
│ safety: fail if exists │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ release.yml │
│ prerelease = true │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ Build │
│ 5 platforms + DEB + RPM │
└────────┬──────────────────┘
│
┌────────▼──────────────────┐
│ GitHub Release │
│ (pre-release badge) │
│ │
│ Discord: SKIPPED │
│ Homebrew: SKIPPED │
└──────────────────────────┘
```
## Merge to master — stable release (cd.yml)
Trigger: push to master | Concurrency: never cancelled
```
┌──────────────────┐
│ push to master │
└────────┬─────────┘
│
┌────────▼──────────────────┐
│ release-please │
│ analyze conventional │
│ commits │
└────────┬──────────────────┘
│
┌────┴────────────────┐
│ │
no release release created
│ │
▼ ▼
┌──────────────┐ ┌───────────────────────┐
│ create/update│ │ release.yml │
│ release PR │ │ prerelease = false │
└──────────────┘ └───────────┬───────────┘
│
┌────────────▼────────────┐
│ Build │
│ 5 platforms + DEB + RPM │
└────────────┬────────────┘
│
┌────────────▼────────────┐
│ GitHub Release │
│ (stable, "Latest" badge) │
└──┬─────────┬─────────┬──┘
│ │ │
▼ ▼ ▼
Discord Homebrew latest
notify tap update tag
```
## Manual release (release.yml)
Trigger: workflow_dispatch
```
┌────────────────────────┐
│ workflow_dispatch │
│ inputs: tag, prerelease │
└───────────┬────────────┘
│
┌───────────▼────────────┐
│ Full build pipeline │
│ 5 platforms + DEB + RPM │
└───────────┬────────────┘
│
┌──────┴──────┐
│ │
prerelease=false prerelease=true
│ │
▼ ▼
Discord pre-release
Homebrew badge only
latest tag
```
-34
View File
@@ -1,34 +0,0 @@
name: Benchmark Token Savings
on:
push:
branches: [master, main]
pull_request:
jobs:
benchmark:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Build rtk
run: cargo build --release
- name: Install Python tools
run: |
pip install ruff pytest
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 'stable'
- name: Install Go tools
run: |
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run benchmark
run: ./scripts/benchmark.sh
+105
View File
@@ -0,0 +1,105 @@
name: CD
on:
push:
branches: [develop, master]
concurrency:
group: cd-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/master' }}
permissions:
contents: write
pull-requests: write
jobs:
# ═══════════════════════════════════════════════
# DEVELOP PATH: Pre-release
# ═══════════════════════════════════════════════
pre-release:
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.tag.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Compute pre-release tag
id: tag
run: |
VERSION=$(grep '^version = ' Cargo.toml | head -1 | cut -d'"' -f2)
TAG="v${VERSION}-rc.${{ github.run_number }}"
# Safety: warn if this base version is already released
if git ls-remote --tags origin "refs/tags/v${VERSION}" | grep -q .; then
echo "::warning::v${VERSION} already released. Consider bumping Cargo.toml on develop."
fi
# Safety: fail if this exact tag already exists
if git ls-remote --tags origin "refs/tags/${TAG}" | grep -q .; then
echo "::error::Tag ${TAG} already exists"
exit 1
fi
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "Pre-release tag: $TAG"
build-prerelease:
name: Build pre-release
needs: pre-release
if: needs.pre-release.outputs.tag != ''
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.pre-release.outputs.tag }}
prerelease: true
permissions:
contents: write
secrets: inherit
# ═══════════════════════════════════════════════
# MASTER PATH: Full release
# ═══════════════════════════════════════════════
release-please:
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
steps:
- uses: googleapis/release-please-action@v4
id: release
with:
release-type: rust
package-name: rtk
build-release:
name: Build and upload release assets
needs: release-please
if: ${{ needs.release-please.outputs.release_created == 'true' }}
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.release-please.outputs.tag_name }}
permissions:
contents: write
secrets: inherit
update-latest-tag:
name: Update 'latest' tag
needs: [release-please, build-release]
if: ${{ needs.release-please.outputs.release_created == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update latest tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa latest -m "Latest stable release (${{ needs.release-please.outputs.tag_name }})"
git push origin latest --force
+371
View File
@@ -0,0 +1,371 @@
name: CI
on:
pull_request:
branches: [develop, master]
permissions:
contents: read
pull-requests: read
env:
CARGO_TERM_COLOR: always
jobs:
# ─── Fast gates (fail early, save CI minutes) ───
fmt:
name: fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- run: cargo fmt --all -- --check
clippy:
name: clippy
needs: fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --all-targets
# ─── Parallel gates (all need code to compile) ───
test:
name: test (${{ matrix.os }})
needs: clippy
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --all
security:
name: Security Scan
needs: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Cargo Audit (CVE check)
run: |
echo "## Security Scan Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Dependency Vulnerabilities" >> $GITHUB_STEP_SUMMARY
if cargo audit 2>&1 | tee audit.log; then
echo "No known vulnerabilities detected" >> $GITHUB_STEP_SUMMARY
else
echo "Vulnerabilities found:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
cat audit.log >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Dependency vulnerabilities detected - review required"
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Critical files check
run: |
echo "### Critical Files Modified" >> $GITHUB_STEP_SUMMARY
CRITICAL=$(git diff --name-only origin/master...HEAD | grep -E "(runner|summary|tracking|init|pnpm_cmd|container)\.rs|Cargo\.toml|workflows/.*\.yml" || true)
if [ -n "$CRITICAL" ]; then
echo "**HIGH RISK**: The following critical files were modified:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$CRITICAL" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Manual security review by 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no shell injection vectors" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check input validation remains intact" >> $GITHUB_STEP_SUMMARY
echo "::warning::Critical RTK files modified - enhanced review required"
else
echo "No critical files modified" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Dangerous patterns scan
run: |
echo "### Dangerous Code Patterns" >> $GITHUB_STEP_SUMMARY
PATTERNS=$(git diff origin/master...HEAD | grep -E "Command::new\(\"sh\"|Command::new\(\"bash\"|\.env\(\"LD_PRELOAD|\.env\(\"PATH|reqwest::|std::net::|TcpStream|UdpSocket|unsafe \{|\.unwrap\(\) |panic!\(|todo!\(|unimplemented!\(" || true)
if [ -n "$PATTERNS" ]; then
echo "**Potentially dangerous patterns detected:**" >> $GITHUB_STEP_SUMMARY
echo '```diff' >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | head -30 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Security Concerns:**" >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | grep -q "Command::new" && echo "- Shell command execution detected" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.env\(\"" && echo "- Environment variable manipulation" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "reqwest::\|std::net::\|TcpStream\|UdpSocket" && echo "- Network operations added" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "unsafe" && echo "- Unsafe code blocks" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.unwrap\(\)\|panic!\(" && echo "- Panic-inducing code" >> $GITHUB_STEP_SUMMARY || true
echo "::warning::Dangerous code patterns detected - manual review required"
else
echo "No dangerous patterns detected" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: New dependencies check
run: |
echo "### Dependencies Changes" >> $GITHUB_STEP_SUMMARY
if git diff origin/master...HEAD Cargo.toml | grep -E "^\+.*=" | grep -v "^\+\+\+" > new_deps.txt; then
echo "**New dependencies added:**" >> $GITHUB_STEP_SUMMARY
echo '```toml' >> $GITHUB_STEP_SUMMARY
cat new_deps.txt >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Audit each new dependency on crates.io" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check maintainer reputation and download counts" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no typosquatting (e.g., 'reqwest' vs 'request')" >> $GITHUB_STEP_SUMMARY
echo "::warning::New dependencies require supply chain audit"
else
echo "No new dependencies added" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Clippy security lints
run: |
echo "### Clippy Security Lints" >> $GITHUB_STEP_SUMMARY
if cargo clippy --all-targets -- -W clippy::unwrap_used -W clippy::panic -W clippy::expect_used 2>&1 | tee clippy.log | grep -E "warning:|error:"; then
echo "Security-related lints triggered:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
grep -E "warning:|error:" clippy.log | head -20 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Clippy security lints failed"
else
echo "All security lints passed" >> $GITHUB_STEP_SUMMARY
fi
- name: Summary verdict
run: |
echo "---" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Security Review Verdict" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**This is an automated security scan. A human maintainer must:**" >> $GITHUB_STEP_SUMMARY
echo "1. Review all warnings above" >> $GITHUB_STEP_SUMMARY
echo "2. Verify PR intent matches actual code changes" >> $GITHUB_STEP_SUMMARY
echo "3. Check for subtle backdoors or logic bombs" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**For high-risk PRs (critical files modified):**" >> $GITHUB_STEP_SUMMARY
echo "- Require approval from 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- Test in isolated environment before merge" >> $GITHUB_STEP_SUMMARY
benchmark:
name: benchmark
needs: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build rtk
run: cargo build --release
- name: Install Python tools
run: pip install ruff pytest
- name: Install Go
uses: actions/setup-go@v5
with:
go-version: 'stable'
- name: Install Go tools
run: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- name: Run benchmark
run: ./scripts/benchmark.sh
# ─── DCO: develop PRs only ───
check:
name: check
if: github.base_ref == 'develop'
runs-on: ubuntu-latest
steps:
- uses: KineticCafe/actions-dco@v1
# ─── AI Doc Review: develop PRs only ───
doc-review:
name: doc review
if: github.base_ref == 'develop'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Gather PR context
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
PR_NUM=${{ github.event.pull_request.number }}
gh pr diff "$PR_NUM" --name-only > changed_files.txt
gh pr diff "$PR_NUM" | head -c 12000 > diff.txt
gh pr view "$PR_NUM" --json title,body --jq '"PR Title: \(.title)\nPR Description: \(.body)"' > pr_info.txt
- name: Build prompt files
run: |
# System prompt
cat <<'EOF' > system_prompt.txt
You are a documentation reviewer for the RTK project.
You will receive the project's CONTRIBUTING.md (which contains the documentation rules), the PR info, changed files, and diff.
Your job: based ONLY on the documentation rules in CONTRIBUTING.md, decide if the PR includes the required documentation updates.
IMPORTANT:
- CI/CD changes, test-only changes, and refactors with no user-facing impact do NOT require doc updates.
- Be practical, not pedantic. Small obvious fixes don't need CHANGELOG entries.
- Only flag missing docs when there is a clear user-facing change.
EOF
# User prompt: concatenate files (no printf, no variable expansion issues)
{
cat pr_info.txt
echo ""
echo "---"
echo "CONTRIBUTING.md:"
cat CONTRIBUTING.md
echo ""
echo "---"
echo "Changed files:"
cat changed_files.txt
echo ""
echo "---"
echo "Diff (may be truncated):"
cat diff.txt
} > user_prompt.txt
- name: AI documentation review
env:
ANTHROPIC_API_KEY: ${{ secrets.RTK_DOCS_ANTHROPIC_KEY }}
run: |
echo "## Documentation Review (AI)" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -z "$ANTHROPIC_API_KEY" ]; then
echo "::warning::ANTHROPIC_API_KEY not configured — skipping AI doc review"
echo "Skipped: ANTHROPIC_API_KEY secret not configured." >> $GITHUB_STEP_SUMMARY
exit 0
fi
echo "::group::Preparing API request"
echo "System prompt: $(wc -c < system_prompt.txt) bytes"
echo "User prompt: $(wc -c < user_prompt.txt) bytes"
SYSTEM_JSON=$(jq -Rs . < system_prompt.txt)
USER_JSON=$(jq -Rs . < user_prompt.txt)
echo "::endgroup::"
echo "::group::Calling Claude API (claude-sonnet-4-6)"
RESPONSE=$(curl -s -w "\n%{http_code}" https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d "{
\"model\": \"claude-sonnet-4-6\",
\"max_tokens\": 1024,
\"messages\": [{\"role\": \"user\", \"content\": $USER_JSON}],
\"system\": $SYSTEM_JSON,
\"output_config\": {
\"format\": {
\"type\": \"json_schema\",
\"schema\": {
\"type\": \"object\",
\"properties\": {
\"status\": {\"type\": \"string\", \"enum\": [\"PASS\", \"FAIL\"]},
\"reasoning\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},
\"files_to_update\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}
},
\"required\": [\"status\", \"reasoning\", \"files_to_update\"],
\"additionalProperties\": false
}
}
}
}")
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | sed '$d')
echo "HTTP status: $HTTP_CODE"
echo "::endgroup::"
if [ "$HTTP_CODE" != "200" ]; then
echo "::warning::Claude API returned HTTP $HTTP_CODE — skipping doc review"
echo "Skipped: API error (HTTP $HTTP_CODE)" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$BODY" | head -10 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
exit 0
fi
# Parse structured JSON response
REVIEW_JSON=$(echo "$BODY" | jq -r '.content[0].text // empty')
if [ -z "$REVIEW_JSON" ]; then
echo "::warning::Empty response from Claude API — skipping doc review"
echo "Skipped: empty API response" >> $GITHUB_STEP_SUMMARY
echo "Raw response:"
echo "$BODY" | head -20
exit 0
fi
echo "::group::AI Review Result"
echo "$REVIEW_JSON" | jq .
echo "::endgroup::"
STATUS=$(echo "$REVIEW_JSON" | jq -r '.status')
REASONING=$(echo "$REVIEW_JSON" | jq -r '.reasoning[]' 2>/dev/null)
FILES=$(echo "$REVIEW_JSON" | jq -r '.files_to_update[]' 2>/dev/null)
echo "### Verdict: ${STATUS}" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
if [ -n "$REASONING" ]; then
echo "**Reasoning:**" >> $GITHUB_STEP_SUMMARY
echo "$REASONING" | while IFS= read -r line; do
echo "- $line" >> $GITHUB_STEP_SUMMARY
done
echo "" >> $GITHUB_STEP_SUMMARY
fi
if [ "$STATUS" = "FAIL" ] && [ -n "$FILES" ]; then
echo "**Files to update:**" >> $GITHUB_STEP_SUMMARY
echo "$FILES" | while IFS= read -r f; do
echo "- \`$f\`" >> $GITHUB_STEP_SUMMARY
done
echo "" >> $GITHUB_STEP_SUMMARY
fi
if [ "$STATUS" = "PASS" ]; then
echo "Documentation review passed."
elif [ "$STATUS" = "FAIL" ]; then
echo "::error::Documentation review failed — see summary for details"
exit 1
else
echo "::warning::Unexpected status '${STATUS}' — skipping"
echo "Unexpected AI response status: ${STATUS}" >> $GITHUB_STEP_SUMMARY
fi
-12
View File
@@ -1,12 +0,0 @@
name: DCO Check
on:
workflow_dispatch:
pull_request:
branches:
- develop
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: KineticCafe/actions-dco@v1
-51
View File
@@ -1,51 +0,0 @@
name: Release Please
on:
push:
branches:
- master
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
steps:
- uses: googleapis/release-please-action@v4
id: release
with:
release-type: rust
package-name: rtk
build-release:
name: Build and upload release assets
needs: release-please
if: ${{ needs.release-please.outputs.release_created == 'true' }}
uses: ./.github/workflows/release.yml
with:
tag: ${{ needs.release-please.outputs.tag_name }}
permissions:
contents: write
secrets: inherit
update-latest-tag:
name: Update 'latest' tag
needs: [release-please, build-release]
if: ${{ needs.release-please.outputs.release_created == 'true' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update latest tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa latest -m "Latest stable release (${{ needs.release-please.outputs.tag_name }})"
git push origin latest --force
+12
View File
@@ -7,11 +7,20 @@ on:
description: 'Tag to release'
required: true
type: string
prerelease:
description: 'Mark as pre-release'
required: false
type: boolean
default: false
workflow_dispatch:
inputs:
tag:
description: 'Tag to release (e.g., v0.1.0)'
required: true
prerelease:
description: 'Mark as pre-release'
type: boolean
default: false
permissions:
contents: write
@@ -198,12 +207,14 @@ jobs:
with:
tag_name: ${{ steps.version.outputs.version }}
files: release/*
prerelease: ${{ inputs.prerelease }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
notify-discord:
name: Notify Discord
needs: [release]
if: ${{ !inputs.prerelease }}
runs-on: ubuntu-latest
steps:
- name: Get version
@@ -237,6 +248,7 @@ jobs:
homebrew:
name: Update Homebrew formula
needs: [release]
if: ${{ !inputs.prerelease }}
runs-on: ubuntu-latest
steps:
- name: Get version
-135
View File
@@ -1,135 +0,0 @@
name: Security Check
on:
pull_request:
branches: [ master ]
permissions:
contents: read
pull-requests: write
env:
CARGO_TERM_COLOR: always
jobs:
security:
name: Security Scan
runs-on: ubuntu-latest
steps:
- name: Checkout PR
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-audit
run: cargo install cargo-audit
- name: Cargo Audit (CVE check)
run: |
echo "## 🔍 Security Scan Results" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 📦 Dependency Vulnerabilities" >> $GITHUB_STEP_SUMMARY
if cargo audit 2>&1 | tee audit.log; then
echo "✅ No known vulnerabilities detected" >> $GITHUB_STEP_SUMMARY
else
echo "⚠️ Vulnerabilities found:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
cat audit.log >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Dependency vulnerabilities detected - review required"
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Critical files check
run: |
echo "### 🎯 Critical Files Modified" >> $GITHUB_STEP_SUMMARY
CRITICAL=$(git diff --name-only origin/master...HEAD | grep -E "(runner|summary|tracking|init|pnpm_cmd|container)\.rs|Cargo\.toml|workflows/.*\.yml" || true)
if [ -n "$CRITICAL" ]; then
echo "⚠️ **HIGH RISK**: The following critical files were modified:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "$CRITICAL" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Manual security review by 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no shell injection vectors" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check input validation remains intact" >> $GITHUB_STEP_SUMMARY
echo "::warning::Critical RTK files modified - enhanced review required"
else
echo "✅ No critical files modified" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Dangerous patterns scan
run: |
echo "### 🚨 Dangerous Code Patterns" >> $GITHUB_STEP_SUMMARY
PATTERNS=$(git diff origin/master...HEAD | grep -E "Command::new\(\"sh\"|Command::new\(\"bash\"|\.env\(\"LD_PRELOAD|\.env\(\"PATH|reqwest::|std::net::|TcpStream|UdpSocket|unsafe \{|\.unwrap\(\) |panic!\(|todo!\(|unimplemented!\(" || true)
if [ -n "$PATTERNS" ]; then
echo "⚠️ **Potentially dangerous patterns detected:**" >> $GITHUB_STEP_SUMMARY
echo '```diff' >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | head -30 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Security Concerns:**" >> $GITHUB_STEP_SUMMARY
echo "$PATTERNS" | grep -q "Command::new" && echo "- Shell command execution detected" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.env\(\"" && echo "- Environment variable manipulation" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "reqwest::\|std::net::\|TcpStream\|UdpSocket" && echo "- Network operations added" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "unsafe" && echo "- Unsafe code blocks" >> $GITHUB_STEP_SUMMARY || true
echo "$PATTERNS" | grep -q "\.unwrap\(\)\|panic!\(" && echo "- Panic-inducing code" >> $GITHUB_STEP_SUMMARY || true
echo "::warning::Dangerous code patterns detected - manual review required"
else
echo "✅ No dangerous patterns detected" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: New dependencies check
run: |
echo "### 📚 Dependencies Changes" >> $GITHUB_STEP_SUMMARY
if git diff origin/master...HEAD Cargo.toml | grep -E "^\+.*=" | grep -v "^\+\+\+" > new_deps.txt; then
echo "⚠️ **New dependencies added:**" >> $GITHUB_STEP_SUMMARY
echo '```toml' >> $GITHUB_STEP_SUMMARY
cat new_deps.txt >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**Required Actions:**" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Audit each new dependency on crates.io" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Check maintainer reputation and download counts" >> $GITHUB_STEP_SUMMARY
echo "- [ ] Verify no typosquatting (e.g., 'reqwest' vs 'request')" >> $GITHUB_STEP_SUMMARY
echo "::warning::New dependencies require supply chain audit"
else
echo "✅ No new dependencies added" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Clippy security lints
run: |
echo "### 🔧 Clippy Security Lints" >> $GITHUB_STEP_SUMMARY
if cargo clippy --all-targets -- -W clippy::unwrap_used -W clippy::panic -W clippy::expect_used 2>&1 | tee clippy.log | grep -E "warning:|error:"; then
echo "⚠️ Security-related lints triggered:" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
grep -E "warning:|error:" clippy.log | head -20 >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo "::warning::Clippy security lints failed"
else
echo "✅ All security lints passed" >> $GITHUB_STEP_SUMMARY
fi
echo "" >> $GITHUB_STEP_SUMMARY
- name: Summary verdict
run: |
echo "---" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 🎯 Security Review Verdict" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**This is an automated security scan. A human maintainer must:**" >> $GITHUB_STEP_SUMMARY
echo "1. Review all warnings above" >> $GITHUB_STEP_SUMMARY
echo "2. Verify PR intent matches actual code changes" >> $GITHUB_STEP_SUMMARY
echo "3. Check for subtle backdoors or logic bombs" >> $GITHUB_STEP_SUMMARY
echo "4. Use \`/rtk-pr-security\` skill for comprehensive analysis" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "**For high-risk PRs (critical files modified):**" >> $GITHUB_STEP_SUMMARY
echo "- Require approval from 2 maintainers" >> $GITHUB_STEP_SUMMARY
echo "- Test in isolated environment before merge" >> $GITHUB_STEP_SUMMARY
-77
View File
@@ -1,77 +0,0 @@
name: Documentation Validation
on:
pull_request:
paths:
- 'src/**/*.rs'
- '**.md'
- '.claude/hooks/*.sh'
push:
branches:
- master
- feat/**
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate documentation consistency
run: bash scripts/validate-docs.sh
- name: Check module count consistency
run: |
MAIN_MODULES=$(grep -c '^mod ' src/main.rs)
# Check ARCHITECTURE.md if it exists
if [ -f "ARCHITECTURE.md" ]; then
ARCH_MODULES=$(grep 'Total:.*modules' ARCHITECTURE.md | grep -o '[0-9]\+' | head -1)
if [ -n "$ARCH_MODULES" ] && [ "$MAIN_MODULES" != "$ARCH_MODULES" ]; then
echo "❌ Module count mismatch"
echo "main.rs: $MAIN_MODULES modules"
echo "ARCHITECTURE.md: $ARCH_MODULES modules"
exit 1
fi
fi
echo "✅ Module count consistent: $MAIN_MODULES modules"
- name: Verify Python/Go commands documented
run: |
for cmd in ruff pytest pip go golangci; do
if ! grep -q "$cmd" README.md; then
echo "❌ README.md missing Python/Go command: $cmd"
exit 1
fi
if ! grep -q "$cmd" CLAUDE.md; then
echo "❌ CLAUDE.md missing Python/Go command: $cmd"
exit 1
fi
done
echo "✅ All Python/Go commands documented"
- name: Verify hook coverage
run: |
HOOK_FILE=".claude/hooks/rtk-rewrite.sh"
if [ ! -f "$HOOK_FILE" ]; then
echo "❌ Hook file not found: $HOOK_FILE"
exit 1
fi
# Since PR #241, the hook delegates to `rtk rewrite` (single source of truth).
# Command coverage is now in src/discover/registry.rs, not the hook bash script.
if ! grep -q "rtk rewrite" "$HOOK_FILE"; then
echo "❌ Hook does not delegate to 'rtk rewrite'"
exit 1
fi
# Verify all Python/Go commands are covered in the registry
# Since PR #241, constants live in src/discover/rules.rs (extracted from registry.rs)
for cmd in ruff pytest pip golangci; do
if ! grep -qr "\"$cmd\"" src/discover/; then
echo "❌ Registry missing rewrite_prefixes for: $cmd"
exit 1
fi
done
echo "✅ Hook delegates to rtk rewrite, registry covers all Python/Go commands"
+1 -1
View File
@@ -45,4 +45,4 @@ claudedocs
.worktrees/
# icm
.fastembed_cache/
.fastembed_cache/
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.28.2"
".": "0.29.0"
}
+1 -1
View File
@@ -1488,4 +1488,4 @@ When implementing a new command, consider:
**Last Updated**: 2026-02-22
**Architecture Version**: 2.2
**rtk Version**: 0.28.0
**rtk Version**: 0.28.2
+7
View File
@@ -5,6 +5,13 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.29.0](https://github.com/rtk-ai/rtk/compare/v0.28.2...v0.29.0) (2026-03-12)
### Features
* rewrite engine, OpenCode support, hook system improvements ([#539](https://github.com/rtk-ai/rtk/issues/539)) ([c1de10d](https://github.com/rtk-ai/rtk/commit/c1de10d94c0a35f825b71713e2db4624310c03d1))
## [0.28.2](https://github.com/rtk-ai/rtk/compare/v0.28.1...v0.28.2) (2026-03-10)
+1 -1
View File
@@ -16,7 +16,7 @@ This is a fork with critical fixes for git argument parsing and modern JavaScrip
**Verify correct installation:**
```bash
rtk --version # Should show "rtk 0.28.0" (or newer)
rtk --version # Should show "rtk 0.28.2" (or newer)
rtk gain # Should show token savings stats (NOT "command not found")
```
+11
View File
@@ -52,6 +52,17 @@ chore(proxy): remove-deprecated-flags
## Pull Request Process
### Scope Rules
**Each PR must focus on a single feature, fix, or change.** The diff must stay in-scope with the description written by the author in the PR title and body. Out-of-scope changes (unrelated refactors, drive-by fixes, formatting of untouched files) must go in a separate PR.
**For large features or refactors**, prefer multi-part PRs over one enormous PR. Split the work into logical, reviewable chunks that can each be merged independently. Examples:
- Part 1: Add data model and tests
- Part 2: Add CLI command and integration
- Part 3: Update documentation and CHANGELOG
**Why**: Small, focused PRs are easier to review, safer to merge, and faster to ship. Large PRs slow down review, hide bugs, and increase merge conflict risk.
### 1. Create Your Branch
```bash
Generated
+1 -1
View File
@@ -892,7 +892,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.28.2"
version = "0.29.0"
dependencies = [
"anyhow",
"chrono",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.28.2"
version = "0.29.0"
edition = "2021"
authors = ["Patrick Szymkowiak"]
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
+8 -2
View File
@@ -90,7 +90,7 @@ Download from [releases](https://github.com/rtk-ai/rtk/releases):
### Verify Installation
```bash
rtk --version # Should show "rtk 0.28.0"
rtk --version # Should show "rtk 0.28.2"
rtk gain # Should show token savings stats
```
@@ -108,7 +108,9 @@ rtk init --global
git status # Automatically rewritten to rtk git status
```
The hook transparently rewrites commands (e.g., `git status` -> `rtk git status`) before execution. Claude never sees the rewrite, it just gets compressed output.
The hook transparently rewrites Bash commands (e.g., `git status` -> `rtk git status`) before execution. Claude never sees the rewrite, it just gets compressed output.
**Important:** the hook only runs on Bash tool calls. Claude Code built-in tools like `Read`, `Grep`, and `Glob` do not pass through the Bash hook, so they are not auto-rewritten. To get RTK's compact output for those workflows, use shell commands (`cat`/`head`/`tail`, `rg`/`grep`, `find`) or call `rtk read`, `rtk grep`, or `rtk find` directly.
## How It Works
@@ -225,6 +227,8 @@ rtk gain --all --format json # JSON export for dashboards
rtk discover # Find missed savings opportunities
rtk discover --all --since 7 # All projects, last 7 days
rtk session # Show RTK adoption across recent sessions
```
## Global Flags
@@ -269,6 +273,8 @@ The most effective way to use rtk. The hook transparently intercepts Bash comman
**Result**: 100% rtk adoption across all conversations and subagents, zero token overhead.
**Scope note:** this only applies to Bash tool calls. Claude Code built-in tools such as `Read`, `Grep`, and `Glob` bypass the hook, so use shell commands or explicit `rtk` commands when you want RTK filtering there.
### Setup
```bash
+9 -5
View File
@@ -629,7 +629,8 @@ pub fn scrub_sensitive_env_vars(input: &str) -> String {
}
pub fn parse_build_from_text(text: &str) -> BuildSummary {
let clean = strip_ansi(text);
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut seen_errors: HashSet<(String, String, u32, u32, String)> = HashSet::new();
let mut seen_warnings: HashSet<(String, String, u32, u32, String)> = HashSet::new();
@@ -836,7 +837,8 @@ pub fn parse_build_from_text(text: &str) -> BuildSummary {
}
pub fn parse_test_from_text(text: &str) -> TestSummary {
let clean = strip_ansi(text);
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut summary = TestSummary {
passed: 0,
@@ -956,8 +958,9 @@ pub fn parse_test_from_text(text: &str) -> TestSummary {
}
pub fn parse_restore_from_text(text: &str) -> RestoreSummary {
let (errors, warnings) = parse_restore_issues_from_text(text);
let clean = strip_ansi(text);
let text = text.replace("\r\n", "\n");
let (errors, warnings) = parse_restore_issues_from_text(&text);
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
RestoreSummary {
@@ -969,7 +972,8 @@ pub fn parse_restore_from_text(text: &str) -> RestoreSummary {
}
pub fn parse_restore_issues_from_text(text: &str) -> (Vec<BinlogIssue>, Vec<BinlogIssue>) {
let clean = strip_ansi(text);
let text = text.replace("\r\n", "\n");
let clean = strip_ansi(&text);
let scrubbed = scrub_sensitive_env_vars(&clean);
let mut errors = Vec::new();
let mut warnings = Vec::new();
+35
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,39 @@ 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)
+64 -10
View File
@@ -42,6 +42,13 @@ fn docker_ps(_verbose: u8) -> Result<()> {
.output()
.context("Failed to run docker ps")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker ps", "rtk docker ps", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut rtk = String::new();
@@ -95,6 +102,13 @@ fn docker_images(_verbose: u8) -> Result<()> {
.output()
.context("Failed to run docker images")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker images", "rtk docker images", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let lines: Vec<&str> = stdout.lines().collect();
let mut rtk = String::new();
@@ -169,6 +183,19 @@ fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("docker logs {}", container),
"rtk docker logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("🐳 Logs for {}:\n{}", container, analyzed);
println!("{}", rtk);
@@ -194,6 +221,15 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
@@ -204,15 +240,12 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
}
};
let items = json["items"].as_array();
if items.is_none() || items.unwrap().is_empty() {
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
}
let pods = items.unwrap();
};
let (mut running, mut pending, mut failed, mut restarts_total) = (0, 0, 0, 0i64);
let mut issues: Vec<String> = Vec::new();
@@ -295,6 +328,15 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
@@ -305,15 +347,12 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
}
};
let items = json["items"].as_array();
if items.is_none() || items.unwrap().is_empty() {
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
}
let services = items.unwrap();
};
rtk.push_str(&format!("☸️ {} services:\n", services.len()));
for svc in services.iter().take(15) {
@@ -373,6 +412,21 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
let output = cmd.output().context("Failed to run kubectl logs")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("kubectl logs {}", pod),
"rtk kubectl logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("☸️ Logs for {}:\n{}", pod, analyzed);
println!("{}", rtk);
+42
View File
@@ -936,6 +936,48 @@ mod tests {
);
}
// --- git -C <path> support (#555) ---
#[test]
fn test_rewrite_git_dash_c_status() {
assert_eq!(
rewrite_command("git -C /path/to/repo status", &[]),
Some("rtk git -C /path/to/repo status".into())
);
}
#[test]
fn test_rewrite_git_dash_c_log() {
assert_eq!(
rewrite_command("git -C /tmp/myrepo log --oneline -5", &[]),
Some("rtk git -C /tmp/myrepo log --oneline -5".into())
);
}
#[test]
fn test_rewrite_git_dash_c_diff() {
assert_eq!(
rewrite_command("git -C /home/user/project diff --name-only", &[]),
Some("rtk git -C /home/user/project diff --name-only".into())
);
}
#[test]
fn test_classify_git_dash_c() {
let result = classify_command("git -C /tmp status");
assert!(
matches!(
result,
Classification::Supported {
rtk_equivalent: "rtk git",
..
}
),
"git -C should be classified as supported, got: {:?}",
result
);
}
#[test]
fn test_rewrite_cargo_test() {
assert_eq!(
+1 -1
View File
@@ -13,7 +13,7 @@ pub struct RtkRule {
// Patterns ordered to match RULES indices exactly.
pub const PATTERNS: &[&str] = &[
r"^git\s+(status|log|diff|show|add|commit|push|pull|branch|fetch|stash|worktree)",
r"^git\s+(?:-[Cc]\s+\S+\s+)*(status|log|diff|show|add|commit|push|pull|branch|fetch|stash|worktree)",
r"^gh\s+(pr|issue|run|repo|api|release)",
r"^cargo\s+(build|test|clippy|check|fmt|install)",
r"^pnpm\s+(list|ls|outdated|install)",
+2 -2
View File
@@ -42,6 +42,6 @@ Found 10 source files
expected = "0 errors, 0 warnings, 0 informations"
[[tests.basedpyright]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "basedpyright: ok"
+2 -2
View File
@@ -40,6 +40,6 @@ Checked 42 files in 0.3s
expected = "biome: ok"
[[tests.biome]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "biome: ok"
+2 -2
View File
@@ -44,6 +44,6 @@ collect2: error: ld returned 1 exit status
expected = "/usr/bin/ld: /tmp/main.o: undefined reference to 'missing_func'\ncollect2: error: ld returned 1 exit status"
[[tests.gcc]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "gcc: ok"
+2 -2
View File
@@ -38,6 +38,6 @@ Finished in 5ms on 100 files.
expected = "oxlint: ok"
[[tests.oxlint]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "oxlint: ok"
+2 -2
View File
@@ -40,6 +40,6 @@ input = """
expected = "{\n \"Name\": \"docker.io/library/nginx\",\n \"Tag\": \"latest\",\n \"Digest\": \"sha256:abc123\",\n \"RepoTags\": [\"latest\", \"1.25\"],\n \"Created\": \"2026-01-01T00:00:00Z\"\n}"
[[tests.skopeo]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "skopeo: ok"
+2 -2
View File
@@ -45,6 +45,6 @@ All checks passed!
expected = "All checks passed!"
[[tests.ty]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "ty: ok"
+2 -2
View File
@@ -94,6 +94,6 @@ Executed 2 tests, with 1 failure in 0.003 seconds
expected = "Test Suite 'All tests' started at 2026-03-10 12:00:00\nTest Suite 'AppTests' started at 2026-03-10 12:00:00\nTest Case '-[AppTests testExample]' passed (0.001 seconds).\nTest Case '-[AppTests testFailing]' failed (0.002 seconds).\nTest Suite 'AppTests' passed at 2026-03-10 12:00:01\nExecuted 2 tests, with 1 failure in 0.003 seconds"
[[tests.xcodebuild]]
name = "empty input passes through"
name = "empty input returns on_empty message"
input = ""
expected = ""
expected = "xcodebuild: ok"
+185 -48
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -111,6 +112,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:");
}
@@ -411,7 +427,7 @@ fn run_log(
}
// Post-process: truncate long messages, cap lines only if RTK set the default
let filtered = filter_log_output(&stdout, limit, user_set_limit);
let filtered = filter_log_output(&stdout, limit, user_set_limit, has_format_flag);
println!("{}", filtered);
timer.track(
@@ -469,10 +485,28 @@ fn parse_user_limit(args: &[String]) -> Option<usize> {
/// so we skip line capping (git already returns exactly N commits) and use a
/// wider truncation threshold (120 chars) to preserve commit context that LLMs
/// need for rebase/squash operations.
fn filter_log_output(output: &str, limit: usize, user_set_limit: bool) -> String {
fn filter_log_output(
output: &str,
limit: usize,
user_set_limit: bool,
user_format: bool,
) -> String {
let truncate_width = if user_set_limit { 120 } else { 80 };
// Split output into commit blocks separated by ---END---
// When user specified their own format (--oneline, --pretty, --format),
// RTK did not inject ---END--- markers. Use simple line-based truncation.
if user_format {
let lines: Vec<&str> = output.lines().collect();
let max_lines = if user_set_limit { lines.len() } else { limit };
return lines
.iter()
.take(max_lines)
.map(|l| truncate_line(l, truncate_width))
.collect::<Vec<_>>()
.join("\n");
}
// RTK injected format: split output into commit blocks separated by ---END---
let commits: Vec<&str> = output.split("---END---").collect();
let max_commits = if user_set_limit { commits.len() } else { limit };
@@ -574,33 +608,46 @@ fn format_status_output(porcelain: &str) -> String {
}
// Build summary
let limits = config::limits();
let max_files = limits.status_max_files;
let max_untracked = limits.status_max_untracked;
if staged > 0 {
output.push_str(&format!("✅ Staged: {} files\n", staged));
for f in staged_files.iter().take(5) {
for f in staged_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if staged_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", staged_files.len() - 5));
if staged_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
staged_files.len() - max_files
));
}
}
if modified > 0 {
output.push_str(&format!("📝 Modified: {} files\n", modified));
for f in modified_files.iter().take(5) {
for f in modified_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if modified_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", modified_files.len() - 5));
if modified_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
modified_files.len() - max_files
));
}
}
if untracked > 0 {
output.push_str(&format!("❓ Untracked: {} files\n", untracked));
for f in untracked_files.iter().take(3) {
for f in untracked_files.iter().take(max_untracked) {
output.push_str(&format!(" {}\n", f));
}
if untracked_files.len() > 3 {
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - 3));
if untracked_files.len() > max_untracked {
output.push_str(&format!(
" ... +{} more\n",
untracked_files.len() - max_untracked
));
}
}
@@ -662,6 +709,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);
}
@@ -841,13 +902,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));
}
}
@@ -1085,6 +1147,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);
@@ -1470,12 +1546,13 @@ mod tests {
fn test_git_cmd_no_global_args() {
let cmd = git_cmd(&[]);
let program = cmd.get_program().to_string_lossy().to_string();
// resolved_command may return absolute path (e.g. /usr/bin/git)
assert!(
program == "git" || program.ends_with("/git"),
"Expected program to be 'git', got '{}'",
program
);
// On Windows, resolved_command returns full path (e.g. "C:\Program Files\Git\bin\git.exe")
let basename = std::path::Path::new(&program)
.file_stem()
.unwrap()
.to_string_lossy()
.to_string();
assert_eq!(basename, "git");
let args: Vec<_> = cmd.get_args().collect();
assert!(args.is_empty());
}
@@ -1671,23 +1748,48 @@ A added.rs
#[test]
fn test_format_status_output_truncation() {
// Test that >5 staged files show "... +N more"
let porcelain = r#"## main
M file1.rs
M file2.rs
M file3.rs
M file4.rs
M file5.rs
M file6.rs
M file7.rs
"#;
let result = format_status_output(porcelain);
assert!(result.contains("✅ Staged: 7 files"));
// Test that >15 staged files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!("M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("✅ Staged: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file5.rs"));
assert!(result.contains("... +2 more"));
assert!(!result.contains("file6.rs"));
assert!(!result.contains("file7.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
assert!(!result.contains("file20.rs"));
}
#[test]
fn test_format_status_modified_truncation() {
// Test that >15 modified files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!(" M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("📝 Modified: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
}
#[test]
fn test_format_status_untracked_truncation() {
// Test that >10 untracked files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=15 {
porcelain.push_str(&format!("?? file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("❓ Untracked: 15 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file10.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file11.rs"));
}
#[test]
@@ -1700,7 +1802,7 @@ M file7.rs
#[test]
fn test_filter_log_output() {
let output = "abc1234 This is a commit message (2 days ago) <author>\n\n---END---\ndef5678 Another commit (1 week ago) <other>\n\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(result.contains("def5678"));
assert_eq!(result.lines().count(), 2);
@@ -1710,7 +1812,7 @@ M file7.rs
fn test_filter_log_output_with_body() {
// Commit with body: first non-trailer body line should appear indented
let output = "abc1234 feat: add feature (2 days ago) <author>\nBREAKING CHANGE: removed old API\nSigned-off-by: Author <a@b.com>\n---END---\ndef5678 fix: typo (1 day ago) <other>\n\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(result.contains("BREAKING CHANGE: removed old API"));
assert!(!result.contains("Signed-off-by:"));
@@ -1724,7 +1826,7 @@ M file7.rs
fn test_filter_log_output_skips_trailers() {
// Body with only trailers should not produce a body line
let output = "abc1234 chore: bump (1 day ago) <bot>\nSigned-off-by: Bot <bot@ci>\nCo-authored-by: Human <h@b>\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(!result.contains("Signed-off-by:"));
assert!(!result.contains("Co-authored-by:"));
@@ -1734,7 +1836,7 @@ M file7.rs
#[test]
fn test_filter_log_output_truncate_long() {
let long_line = "abc1234 ".to_string() + &"x".repeat(100) + " (2 days ago) <author>";
let result = filter_log_output(&long_line, 10, false);
let result = filter_log_output(&long_line, 10, false, false);
assert!(result.chars().count() < long_line.chars().count());
assert!(result.contains("..."));
assert!(result.chars().count() <= 80);
@@ -1746,7 +1848,7 @@ M file7.rs
.map(|i| format!("hash{} message {} (1 day ago) <author>\n\n---END---", i, i))
.collect::<Vec<_>>()
.join("\n");
let result = filter_log_output(&output, 5, false);
let result = filter_log_output(&output, 5, false, false);
assert_eq!(result.lines().count(), 5);
}
@@ -1757,7 +1859,7 @@ M file7.rs
.map(|i| format!("hash{} message {} (1 day ago) <author>\n\n---END---", i, i))
.collect::<Vec<_>>()
.join("\n");
let result = filter_log_output(&output, 20, true);
let result = filter_log_output(&output, 20, true, false);
assert_eq!(
result.lines().count(),
20,
@@ -1772,8 +1874,8 @@ M file7.rs
assert!(line_90_chars.chars().count() > 80);
assert!(line_90_chars.chars().count() < 120);
let result_default = filter_log_output(&line_90_chars, 10, false);
let result_user = filter_log_output(&line_90_chars, 10, true);
let result_default = filter_log_output(&line_90_chars, 10, false, false);
let result_user = filter_log_output(&line_90_chars, 10, true, false);
// Default truncates at 80 chars
assert!(
@@ -1832,7 +1934,7 @@ M file7.rs
})
.collect::<Vec<_>>()
.join("\n");
let output = filter_log_output(&input, 10, false);
let output = filter_log_output(&input, 10, false, false);
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(&input) as f64 * 100.0);
assert!(
savings >= 60.0,
@@ -1874,7 +1976,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
fn test_filter_log_output_multibyte() {
// Thai characters: each is 3 bytes. A line with >80 bytes but few chars
let thai_msg = format!("abc1234 {} (2 days ago) <author>", "ก".repeat(30));
let result = filter_log_output(&thai_msg, 10, false);
let result = filter_log_output(&thai_msg, 10, false, false);
// Should not panic
assert!(result.contains("abc1234"));
// The line has 30 Thai chars + other text, so > 80 chars total
@@ -1886,7 +1988,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
#[test]
fn test_filter_log_output_emoji() {
let emoji_msg = "abc1234 🎉🎊🎈🎁🎂🎄🎃🎆🎇✨🎉🎊🎈🎁🎂🎄🎃🎆🎇✨ (1 day ago) <user>";
let result = filter_log_output(emoji_msg, 10, false);
let result = filter_log_output(emoji_msg, 10, false, false);
// Should not panic
// 20 emoji + ~30 other chars = ~50 chars < 80, no truncation needed
assert!(result.contains("abc1234"));
@@ -1909,6 +2011,41 @@ no changes added to commit (use "git add" and/or "git commit -a")
assert!(result.contains("📌 main"));
}
/// Regression test: --oneline and other user format flags must preserve all commits.
/// Before fix, filter_log_output split on ---END--- which doesn't exist when
/// the user specifies their own format, resulting in only 2 commits surviving.
#[test]
fn test_filter_log_output_user_format_oneline() {
let oneline_output = "abc1234 feat: add feature\n\
def5678 fix: typo\n\
ghi9012 chore: bump deps\n\
jkl3456 docs: update readme\n\
mno7890 test: add tests\n";
let result = filter_log_output(oneline_output, 10, false, true);
// All 5 lines must survive — no ---END--- splitting
assert_eq!(result.lines().count(), 5);
assert!(result.contains("abc1234"));
assert!(result.contains("mno7890"));
}
#[test]
fn test_filter_log_output_user_format_with_limit() {
let oneline_output = "abc1234 feat: add feature\n\
def5678 fix: typo\n\
ghi9012 chore: bump deps\n\
jkl3456 docs: update readme\n\
mno7890 test: add tests\n";
// user_set_limit=true means respect all lines (no cap)
let result = filter_log_output(oneline_output, 3, true, true);
assert_eq!(result.lines().count(), 5);
// user_set_limit=false means cap at limit
let result = filter_log_output(oneline_output, 3, false, true);
assert_eq!(result.lines().count(), 3);
}
/// Regression test: `git branch <name>` must create, not list.
/// Before fix, positional args fell into list mode which added `-a`,
/// turning creation into a pattern-filtered listing (silent no-op).
+17 -4
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -78,9 +79,21 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
// golangci-lint returns exit code 1 when issues found (expected behavior)
// Don't exit with error code in that case
Ok(())
// golangci-lint: exit 0 = clean, exit 1 = lint issues, exit 2+ = config/build error
// None = killed by signal (OOM, SIGKILL) — always fatal
match output.status.code() {
Some(0) | Some(1) => Ok(()),
Some(code) => {
if !stderr.trim().is_empty() {
eprintln!("{}", stderr.trim());
}
std::process::exit(code);
}
None => {
eprintln!("golangci-lint: killed by signal");
std::process::exit(130);
}
}
}
/// Filter golangci-lint JSON output - group by linter and file
@@ -94,7 +107,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)
);
}
};
+22 -15
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -77,6 +78,13 @@ pub fn run(
let mut by_file: HashMap<String, Vec<(usize, String)>> = HashMap::new();
let mut total = 0;
// Compile context regex once (instead of per-line in clean_line)
let context_re = if context_only {
Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))).ok()
} else {
None
};
for line in stdout.lines() {
let parts: Vec<&str> = line.splitn(3, ':').collect();
@@ -91,7 +99,7 @@ pub fn run(
};
total += 1;
let cleaned = clean_line(content, max_line_len, context_only, pattern);
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), pattern);
by_file.entry(file).or_default().push((line_num, cleaned));
}
@@ -110,7 +118,8 @@ pub fn run(
let file_display = compact_path(file);
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
for (line_num, content) in matches.iter().take(10) {
let per_file = config::limits().grep_max_per_file;
for (line_num, content) in matches.iter().take(per_file) {
rtk_output.push_str(&format!(" {:>4}: {}\n", line_num, content));
shown += 1;
if shown >= max_results {
@@ -118,8 +127,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 +152,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 +223,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 +247,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 +255,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());
}
+3 -2
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::mypy_cmd;
use crate::ruff_cmd;
use crate::tracking;
@@ -234,7 +235,7 @@ fn filter_eslint_json(output: &str) -> String {
return format!(
"ESLint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
@@ -326,7 +327,7 @@ fn filter_pylint_json(output: &str) -> String {
return format!(
"Pylint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+16 -12
View File
@@ -1,11 +1,23 @@
use crate::tracking;
use anyhow::Result;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead};
use std::path::Path;
lazy_static! {
static ref TIMESTAMP_RE: Regex =
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
static ref UUID_RE: Regex =
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
.unwrap();
static ref HEX_RE: Regex = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
static ref NUM_RE: Regex = Regex::new(r"\b\d{4,}\b").unwrap();
static ref PATH_RE: Regex = Regex::new(r"/[\w./\-]+").unwrap();
}
/// Filter and deduplicate log output
pub fn run_file(file: &Path, verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
@@ -58,22 +70,14 @@ fn analyze_logs(content: &str) -> String {
let mut unique_errors: Vec<String> = Vec::new();
let mut unique_warnings: Vec<String> = Vec::new();
// Patterns to normalize log messages
let timestamp_re =
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
let uuid_re =
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
.unwrap();
let hex_re = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
let num_re = Regex::new(r"\b\d{4,}\b").unwrap();
let path_re = Regex::new(r"/[\w./\-]+").unwrap();
// Use module-level lazy_static regexes for normalization
for line in content.lines() {
let line_lower = line.to_lowercase();
// Normalize for deduplication
let normalized =
normalize_log_line(line, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re);
normalize_log_line(line, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE);
// Categorize
if line_lower.contains("error")
@@ -128,7 +132,7 @@ fn analyze_logs(content: &str) -> String {
let original = unique_errors
.iter()
.find(|e| {
&normalize_log_line(e, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re)
&normalize_log_line(e, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
@@ -168,7 +172,7 @@ fn analyze_logs(content: &str) -> String {
let original = unique_warnings
.iter()
.find(|w| {
&normalize_log_line(w, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re)
&normalize_log_line(w, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
+34 -3
View File
@@ -49,12 +49,14 @@ mod read;
mod rewrite_cmd;
mod ruff_cmd;
mod runner;
mod session_cmd;
mod summary;
mod tee;
mod telemetry;
mod toml_filter;
mod tracking;
mod tree;
mod trust;
mod tsc_cmd;
mod utils;
mod verify_cmd;
@@ -304,7 +306,7 @@ enum Commands {
#[arg(short = 'l', long, default_value = "80")]
max_len: usize,
/// Max results to show
#[arg(short, long, default_value = "50")]
#[arg(short, long, default_value = "200")]
max: usize,
/// Show only match context (not full line)
#[arg(short, long)]
@@ -537,6 +539,9 @@ enum Commands {
format: String,
},
/// Show RTK adoption across Claude Code sessions
Session {},
/// Learn CLI corrections from Claude Code error history
Learn {
/// Filter by project path (substring match)
@@ -569,6 +574,16 @@ enum Commands {
args: Vec<OsString>,
},
/// Trust project-local TOML filters in current directory
Trust {
/// List all trusted projects
#[arg(long)]
list: bool,
},
/// Revoke trust for project-local TOML filters
Untrust,
/// Verify hook integrity and run TOML filter inline tests
Verify {
/// Run tests only for this filter name
@@ -1002,6 +1017,10 @@ const RTK_META_COMMANDS: &[&str] = &[
"hook-audit",
"cc-economics",
"verify",
"trust",
"untrust",
"session",
"rewrite",
];
fn run_fallback(parse_error: clap::Error) -> Result<()> {
@@ -1793,6 +1812,10 @@ fn main() -> Result<()> {
discover::run(project.as_deref(), all, since, limit, &format, cli.verbose)?;
}
Commands::Session {} => {
session_cmd::run(cli.verbose)?;
}
Commands::Learn {
project,
all,
@@ -2080,6 +2103,14 @@ fn main() -> Result<()> {
}
}
Commands::Trust { list } => {
trust::run_trust(list)?;
}
Commands::Untrust => {
trust::run_untrust()?;
}
Commands::Verify {
filter,
require_all,
@@ -2363,8 +2394,8 @@ mod tests {
// RTK meta-commands should produce parse errors (not fall through to raw execution).
// Skip "proxy" because it uses trailing_var_arg (accepts any args by design).
for cmd in RTK_META_COMMANDS {
if *cmd == "proxy" {
continue;
if matches!(*cmd, "proxy" | "rewrite" | "session") {
continue; // these use trailing_var_arg (accept any args by design)
}
let result = Cli::try_parse_from(["rtk", cmd, "--nonexistent-flag-xyz"]);
assert!(
+4 -1
View File
@@ -43,7 +43,10 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
std::process::exit(output.status.code().unwrap_or(1));
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
}
struct MypyError {
+1 -1
View File
@@ -70,7 +70,7 @@ impl OutputParser for VitestParser {
)
} else {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_output(input, 2000))
}
}
}
+7 -1
View File
@@ -89,12 +89,18 @@ pub trait OutputParser: Sized {
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();
+2 -2
View File
@@ -5,7 +5,7 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, FormatMode, OutputParser,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, FormatMode, OutputParser,
ParseResult, TestFailure, TestResult, TokenFormatter,
};
@@ -110,7 +110,7 @@ impl OutputParser for PlaywrightParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+7 -5
View File
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::ffi::OsString;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, Dependency,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, Dependency,
DependencyState, FormatMode, OutputParser, ParseResult, TokenFormatter,
};
@@ -75,7 +75,7 @@ impl OutputParser for PnpmListParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -202,7 +202,7 @@ impl OutputParser for PnpmOutdatedParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -307,7 +307,8 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pnpm list failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -431,7 +432,8 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
anyhow::bail!("pnpm install failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let combined = format!("{}{}", stdout, stderr);
+38 -20
View File
@@ -54,18 +54,24 @@ fn run_generate(args: &[String], verbose: u8) -> Result<()> {
.output()
.context("Failed to run prisma generate (try: npm install -g prisma)")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma generate failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("prisma generate", "rtk prisma generate", &raw, &raw);
std::process::exit(exit_code);
}
let filtered = filter_prisma_generate(&raw);
println!("{}", filtered);
timer.track("prisma generate", "rtk prisma generate", &raw, &filtered);
Ok(())
@@ -105,15 +111,22 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
let output = cmd.output().context("Failed to run prisma migrate")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma migrate failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &raw);
std::process::exit(exit_code);
}
let filtered = match subcommand {
MigrateSubcommand::Dev { .. } => filter_migrate_dev(&raw),
MigrateSubcommand::Status => filter_migrate_status(&raw),
@@ -121,7 +134,6 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
};
println!("{}", filtered);
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &filtered);
Ok(())
@@ -143,18 +155,24 @@ fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
let output = cmd.output().context("Failed to run prisma db push")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma db push failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("prisma db push", "rtk prisma db push", &raw, &raw);
std::process::exit(exit_code);
}
let filtered = filter_db_push(&raw);
println!("{}", filtered);
timer.track("prisma db push", "rtk prisma db push", &raw, &filtered);
Ok(())
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -121,7 +122,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
return format!(
"Ruff check (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+438
View File
@@ -0,0 +1,438 @@
use crate::discover::provider::{ClaudeProvider, ExtractedCommand, SessionProvider};
use crate::discover::registry::{classify_command, split_command_chain, Classification};
use crate::utils::format_tokens;
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;
/// A summarized session for display.
struct SessionSummary {
id: String,
date: String,
total_cmds: usize,
rtk_cmds: usize,
output_tokens: usize,
}
impl SessionSummary {
fn adoption_pct(&self) -> f64 {
if self.total_cmds == 0 {
return 0.0;
}
self.rtk_cmds as f64 / self.total_cmds as f64 * 100.0
}
}
/// Count RTK-covered commands from extracted commands.
/// A command is "covered" if it either:
/// - starts with "rtk " (explicit rtk invocation), or
/// - would be rewritten by the hook (classify_command returns Supported)
///
/// Chained commands (e.g. "cd ./path && rtk ls") are split so each part
/// is classified independently — matching the discover module's behavior.
fn count_rtk_commands(cmds: &[ExtractedCommand]) -> (usize, usize, usize) {
let mut total: usize = 0;
let mut rtk: usize = 0;
for c in cmds {
let parts = split_command_chain(&c.command);
for part in &parts {
total += 1;
if part.starts_with("rtk ")
|| matches!(classify_command(part), Classification::Supported { .. })
{
rtk += 1;
}
}
}
let output: usize = cmds.iter().filter_map(|c| c.output_len).sum();
(total, rtk, output)
}
fn progress_bar(pct: f64, width: usize) -> String {
let filled = ((pct / 100.0) * width as f64).round() as usize;
let empty = width.saturating_sub(filled);
format!("{}{}", "@".repeat(filled), ".".repeat(empty))
}
pub fn run(_verbose: u8) -> Result<()> {
let provider = ClaudeProvider;
let sessions = provider
.discover_sessions(None, Some(30))
.context("Failed to discover Claude Code sessions")?;
if sessions.is_empty() {
println!("No Claude Code sessions found in the last 30 days.");
println!("Make sure Claude Code has been used at least once.");
return Ok(());
}
// Group JSONL files by parent session (ignore subagent files)
let mut session_files: Vec<PathBuf> = sessions
.into_iter()
.filter(|p| {
// Skip subagent files — only top-level session JSONL
!p.to_string_lossy().contains("subagents")
})
.collect();
// Sort by mtime desc
session_files.sort_by(|a, b| {
let ma = fs::metadata(a)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
let mb = fs::metadata(b)
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH);
mb.cmp(&ma)
});
// Take top 10
session_files.truncate(10);
let mut summaries: Vec<SessionSummary> = Vec::new();
for path in &session_files {
let cmds = match provider.extract_commands(path) {
Ok(c) => c,
Err(_) => continue,
};
if cmds.is_empty() {
continue;
}
let (total_cmds, rtk_cmds, output_tokens) = count_rtk_commands(&cmds);
// Extract session ID from filename
let id = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
let short_id = if id.len() > 8 { &id[..8] } else { id };
// Extract date from mtime
let date = fs::metadata(path)
.and_then(|m| m.modified())
.map(|t| {
let elapsed = std::time::SystemTime::now()
.duration_since(t)
.unwrap_or_default();
let days = elapsed.as_secs() / 86400;
if days == 0 {
"Today".to_string()
} else if days == 1 {
"Yesterday".to_string()
} else {
format!("{}d ago", days)
}
})
.unwrap_or_else(|_| "?".to_string());
summaries.push(SessionSummary {
id: short_id.to_string(),
date,
total_cmds,
rtk_cmds,
output_tokens,
});
}
if summaries.is_empty() {
println!("No sessions with Bash commands found.");
return Ok(());
}
// Display table
let header = "RTK Session Overview (last 10)";
println!("{}", header);
println!("{}", "-".repeat(70));
println!(
"{:<12} {:<12} {:>5} {:>5} {:>9} {:<7} {:>8}",
"Session", "Date", "Cmds", "RTK", "Adoption", "", "Output"
);
println!("{}", "-".repeat(70));
let mut total_cmds = 0;
let mut total_rtk = 0;
for s in &summaries {
let pct = s.adoption_pct();
let bar = progress_bar(pct, 5);
total_cmds += s.total_cmds;
total_rtk += s.rtk_cmds;
println!(
"{:<12} {:<12} {:>5} {:>5} {:>8.0}% {:<7} {:>8}",
s.id,
s.date,
s.total_cmds,
s.rtk_cmds,
pct,
bar,
format_tokens(s.output_tokens),
);
}
println!("{}", "-".repeat(70));
let avg_adoption = if total_cmds > 0 {
total_rtk as f64 / total_cmds as f64 * 100.0
} else {
0.0
};
println!("Average adoption: {:.0}%", avg_adoption);
println!("Tip: Run `rtk discover` to find missed RTK opportunities");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::discover::provider::ExtractedCommand;
use std::io::Write;
use tempfile::NamedTempFile;
fn make_cmd(command: &str, output_len: Option<usize>) -> ExtractedCommand {
ExtractedCommand {
command: command.to_string(),
output_len,
session_id: "test".to_string(),
output_content: None,
is_error: false,
sequence_index: 0,
}
}
// --- Progress bar ---
#[test]
fn test_progress_bar_boundaries() {
assert_eq!(progress_bar(0.0, 5), ".....");
assert_eq!(progress_bar(100.0, 5), "@@@@@");
assert_eq!(progress_bar(50.0, 5), "@@@..");
}
// --- count_rtk_commands: core counting logic ---
#[test]
fn test_count_all_rtk() {
let cmds = vec![
make_cmd("rtk git status", Some(200)),
make_cmd("rtk cargo test", Some(5000)),
make_cmd("rtk git log -10", Some(800)),
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
assert_eq!(rtk, 3);
assert_eq!(output, 6000);
}
#[test]
fn test_count_hook_rewritten_commands() {
// Hook rewrites "git status" → "rtk git status" but JSONL logs the original.
// count_rtk_commands should detect these via classify_command.
let cmds = vec![
make_cmd("git status", Some(500)),
make_cmd("cargo test", Some(3000)),
make_cmd("echo hello", Some(100)),
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
// git status + cargo test are supported by RTK, echo is not
assert_eq!(rtk, 2);
assert_eq!(output, 3600);
}
#[test]
fn test_count_mixed_explicit_and_hook() {
let cmds = vec![
make_cmd("rtk git status", Some(200)), // explicit rtk
make_cmd("git log -5", Some(1000)), // hook-rewritten (logged as raw)
make_cmd("rtk cargo test", Some(5000)), // explicit rtk
make_cmd("echo hello", None), // not supported
];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 4);
assert_eq!(rtk, 3); // rtk git status + git log + rtk cargo test
assert_eq!(output, 6200);
}
#[test]
fn test_count_unsupported_commands_not_counted() {
let cmds = vec![
make_cmd("echo hello", Some(100)),
make_cmd("mkdir -p /tmp/foo", Some(10)),
make_cmd("cd /tmp", Some(5)),
];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 3);
assert_eq!(rtk, 0);
}
#[test]
fn test_count_empty_commands() {
let cmds: Vec<ExtractedCommand> = vec![];
let (total, rtk, output) = count_rtk_commands(&cmds);
assert_eq!(total, 0);
assert_eq!(rtk, 0);
assert_eq!(output, 0);
}
// --- chained commands ---
#[test]
fn test_count_chained_commands_split() {
// "cd ./path && rtk ls" is one ExtractedCommand but two logical commands.
// cd is ignored/unsupported, ls is supported → 1 out of 2 covered.
let cmds = vec![make_cmd("cd ./your/app/path && rtk ls", Some(200))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain should split into 2 commands");
assert_eq!(rtk, 1, "only 'rtk ls' is RTK-covered");
}
#[test]
fn test_count_chained_all_supported() {
// Both parts are RTK-supported
let cmds = vec![make_cmd("git status && git log -5", Some(500))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain should split into 2 commands");
assert_eq!(rtk, 2, "both git commands are RTK-covered");
}
#[test]
fn test_count_chained_with_semicolon() {
let cmds = vec![make_cmd("cd /tmp; git status; echo done", Some(100))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 3, "semicolon chain splits into 3 commands");
assert_eq!(rtk, 1, "only git status is RTK-covered");
}
#[test]
fn test_count_chained_no_false_inflation() {
// Single command should still count as 1
let cmds = vec![make_cmd("git status", Some(100))];
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 1);
assert_eq!(rtk, 1);
}
// --- adoption_pct ---
#[test]
fn test_adoption_pct_zero_division() {
let s = SessionSummary {
id: "x".to_string(),
date: "Today".to_string(),
total_cmds: 0,
rtk_cmds: 0,
output_tokens: 0,
};
assert_eq!(s.adoption_pct(), 0.0);
}
#[test]
fn test_adoption_pct_75_percent() {
let s = SessionSummary {
id: "x".to_string(),
date: "Today".to_string(),
total_cmds: 20,
rtk_cmds: 15,
output_tokens: 0,
};
assert_eq!(s.adoption_pct(), 75.0);
}
// --- End-to-end: parse real JSONL and count ---
#[test]
fn test_parse_jsonl_session_and_count() {
// Simulate a session with 3 Bash commands: 2 rtk, 1 raw
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"rtk git status"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"On branch main"}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"Bash","input":{"command":"git log -5"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"commit abc123\ncommit def456"}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"Bash","input":{"command":"rtk cargo test"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":"test result: ok. 5 passed"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
let (total, rtk, _output) = count_rtk_commands(&cmds);
assert_eq!(total, 3, "should find 3 Bash commands");
// All 3 are RTK-covered: 2 explicit "rtk ..." + 1 hook-rewritten "git log"
assert_eq!(rtk, 3, "all 3 commands should be RTK-covered");
}
#[test]
fn test_parse_jsonl_ignores_non_bash_tools() {
// Read/Grep/Edit tools should NOT be counted
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"/tmp/foo"}}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"Grep","input":{"pattern":"TODO"}}]}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"Bash","input":{"command":"rtk git status"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":"clean"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 1, "only Bash tool should be counted");
assert_eq!(rtk, 1, "the one Bash command is rtk");
}
#[test]
fn test_parse_empty_session() {
// Session with no Bash commands at all
let jsonl = [
r#"{"type":"user","message":{"role":"user","content":"Hello"}}"#,
r#"{"type":"assistant","message":{"role":"assistant","content":"Hi there!"}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
assert!(cmds.is_empty(), "no Bash commands = empty");
}
#[test]
fn test_parse_jsonl_chained_command() {
// Claude often runs "cd ./path && git status" as a single Bash call.
// The adoption metric should split the chain and count each part.
let jsonl = [
r#"{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"cd ./your/app/path && rtk ls"}}]}}"#,
r#"{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"file1.rs\nfile2.rs"}]}}"#,
];
let mut tmp = NamedTempFile::new().expect("create tempfile");
for line in &jsonl {
writeln!(tmp, "{}", line).expect("write line");
}
let provider = ClaudeProvider;
let cmds = provider.extract_commands(tmp.path()).expect("parse JSONL");
assert_eq!(cmds.len(), 1, "one Bash tool call");
let (total, rtk, _) = count_rtk_commands(&cmds);
assert_eq!(total, 2, "chain splits into cd + rtk ls");
assert_eq!(rtk, 1, "rtk ls is covered, cd is not");
}
}
+44 -13
View File
@@ -181,11 +181,29 @@ impl TomlFilterRegistry {
fn load() -> Self {
let mut filters = Vec::new();
// Priority 1: project-local .rtk/filters.toml
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
match Self::parse_and_compile(&content, "project") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
// Priority 1: project-local .rtk/filters.toml (trust-gated)
let project_filter_path = std::path::Path::new(".rtk/filters.toml");
if project_filter_path.exists() {
let trust_status = crate::trust::check_trust(project_filter_path)
.unwrap_or(crate::trust::TrustStatus::Untrusted);
match trust_status {
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
if let Ok(content) = std::fs::read_to_string(project_filter_path) {
match Self::parse_and_compile(&content, "project") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
}
}
}
crate::trust::TrustStatus::Untrusted => {
eprintln!("[rtk] WARNING: untrusted project filters (.rtk/filters.toml)");
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to review and enable.");
}
crate::trust::TrustStatus::ContentChanged { .. } => {
eprintln!("[rtk] WARNING: .rtk/filters.toml changed since trusted.");
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to re-review.");
}
}
}
@@ -529,14 +547,27 @@ pub fn run_filter_tests(filter_name_opt: Option<&str>) -> VerifyResults {
&mut tested_filter_names,
);
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
collect_test_outcomes(
&content,
filter_name_opt,
&mut outcomes,
&mut all_filter_names,
&mut tested_filter_names,
);
// Trust-gated: only verify project-local filters if trusted (SA-2025-RTK-002)
let project_path = std::path::Path::new(".rtk/filters.toml");
if project_path.exists() {
let trust_status =
crate::trust::check_trust(project_path).unwrap_or(crate::trust::TrustStatus::Untrusted);
match trust_status {
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
if let Ok(content) = std::fs::read_to_string(project_path) {
collect_test_outcomes(
&content,
filter_name_opt,
&mut outcomes,
&mut all_filter_names,
&mut tested_filter_names,
);
}
}
_ => {
eprintln!("[rtk] WARNING: untrusted project filters skipped in verify");
}
}
}
let filters_without_tests = all_filter_names
+6
View File
@@ -251,6 +251,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,
+510
View File
@@ -0,0 +1,510 @@
//! Trust boundary for project-local TOML filters (SA-2025-RTK-002).
//!
//! `.rtk/filters.toml` is loaded from CWD with highest priority. An attacker
//! can commit this file to a public repo to control what an LLM sees — hiding
//! malicious code, suppressing security scanner output, or rewriting command
//! output entirely via `replace` and `match_output` primitives.
//!
//! This module implements a trust-before-load model:
//! - Untrusted filters are **skipped** (not "loaded with warning")
//! - `rtk trust` stores the SHA-256 hash after user review
//! - Content changes invalidate trust (re-review required)
//! - `RTK_TRUST_PROJECT_FILTERS=1` overrides for CI pipelines
use crate::integrity;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
#[derive(Serialize, Deserialize, Default)]
struct TrustStore {
version: u32,
trusted: HashMap<String, TrustEntry>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct TrustEntry {
pub sha256: String,
pub trusted_at: String,
}
#[derive(Debug, PartialEq)]
pub enum TrustStatus {
Trusted,
Untrusted,
ContentChanged { expected: String, actual: String },
EnvOverride,
}
// ---------------------------------------------------------------------------
// Store path
// ---------------------------------------------------------------------------
fn store_path() -> Result<PathBuf> {
let data_dir = dirs::data_local_dir().context("Cannot determine local data directory")?;
Ok(data_dir.join("rtk").join("trusted_filters.json"))
}
fn read_store() -> Result<TrustStore> {
let path = store_path()?;
if !path.exists() {
return Ok(TrustStore::default());
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read trust store: {}", path.display()))?;
serde_json::from_str(&content)
.with_context(|| format!("Failed to parse trust store: {}", path.display()))
}
fn write_store(store: &TrustStore) -> Result<()> {
let path = store_path()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory: {}", parent.display()))?;
}
let content = serde_json::to_string_pretty(store).context("Failed to serialize trust store")?;
std::fs::write(&path, content)
.with_context(|| format!("Failed to write trust store: {}", path.display()))
}
// ---------------------------------------------------------------------------
// Canonical path helper
// ---------------------------------------------------------------------------
fn canonical_key(filter_path: &Path) -> Result<String> {
// Resolve symlinks and produce an absolute path. No fallback — if we can't
// canonicalize, we can't safely key the trust entry (fail-closed).
let canonical = std::fs::canonicalize(filter_path)
.with_context(|| format!("Cannot resolve path: {}", filter_path.display()))?;
Ok(canonical.to_string_lossy().to_string())
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Check if a project-local filter file is trusted.
///
/// Priority: env var > hash match > untrusted.
/// All errors are soft — if anything fails, returns Untrusted (fail-secure).
pub fn check_trust(filter_path: &Path) -> Result<TrustStatus> {
// Fast path: env var override for CI pipelines only.
// Requires a known CI env var to be set to prevent .envrc injection attacks.
if std::env::var("RTK_TRUST_PROJECT_FILTERS").as_deref() == Ok("1") {
let in_ci = std::env::var("CI").is_ok()
|| std::env::var("GITHUB_ACTIONS").is_ok()
|| std::env::var("GITLAB_CI").is_ok()
|| std::env::var("JENKINS_URL").is_ok()
|| std::env::var("BUILDKITE").is_ok();
if in_ci {
return Ok(TrustStatus::EnvOverride);
}
eprintln!(
"[rtk] WARNING: RTK_TRUST_PROJECT_FILTERS=1 ignored (CI environment not detected)"
);
}
let key = canonical_key(filter_path)?;
let store = match read_store() {
Ok(s) => s,
Err(e) => {
eprintln!(
"[rtk] WARNING: trust store unreadable ({}), treating all filters as untrusted",
e
);
TrustStore::default()
}
};
let entry = match store.trusted.get(&key) {
Some(e) => e,
None => return Ok(TrustStatus::Untrusted),
};
let actual_hash = integrity::compute_hash(filter_path)
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
if actual_hash == entry.sha256 {
Ok(TrustStatus::Trusted)
} else {
Ok(TrustStatus::ContentChanged {
expected: entry.sha256.clone(),
actual: actual_hash,
})
}
}
/// Store current SHA-256 hash as trusted (computes hash from file).
pub fn trust_filter(filter_path: &Path) -> Result<()> {
let hash = integrity::compute_hash(filter_path)
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
trust_filter_with_hash(filter_path, &hash)
}
/// Store a pre-computed SHA-256 hash as trusted (avoids TOCTOU re-read).
pub fn trust_filter_with_hash(filter_path: &Path, hash: &str) -> Result<()> {
let key = canonical_key(filter_path)?;
let mut store = read_store().unwrap_or_default();
store.version = 1;
store.trusted.insert(
key,
TrustEntry {
sha256: hash.to_string(),
trusted_at: chrono::Utc::now().to_rfc3339(),
},
);
write_store(&store)
}
/// Remove trust entry for a filter path.
pub fn untrust_filter(filter_path: &Path) -> Result<bool> {
let key = canonical_key(filter_path)?;
let mut store = read_store().unwrap_or_default();
let removed = store.trusted.remove(&key).is_some();
if removed {
write_store(&store)?;
}
Ok(removed)
}
/// List all trusted projects.
pub fn list_trusted() -> Result<HashMap<String, TrustEntry>> {
let store = read_store().unwrap_or_default();
Ok(store.trusted)
}
// ---------------------------------------------------------------------------
// CLI commands
// ---------------------------------------------------------------------------
/// Run `rtk trust` — review and trust project-local filters.
pub fn run_trust(list: bool) -> Result<()> {
if list {
let trusted = list_trusted()?;
if trusted.is_empty() {
println!("No trusted project filters.");
return Ok(());
}
println!("Trusted project filters:");
println!("{}", "═".repeat(60));
for (path, entry) in &trusted {
let date = entry.trusted_at.get(..10).unwrap_or(&entry.trusted_at);
println!(" {} (trusted {})", path, date);
println!(" sha256:{}", entry.sha256);
}
return Ok(());
}
let filter_path = Path::new(".rtk/filters.toml");
if !filter_path.exists() {
anyhow::bail!("No .rtk/filters.toml found in current directory");
}
// Read ONCE to prevent TOCTOU: display + hash from same buffer
let content_bytes = std::fs::read(filter_path).context("Failed to read .rtk/filters.toml")?;
let content = String::from_utf8_lossy(&content_bytes);
println!("=== .rtk/filters.toml ===");
println!("{}", content);
println!("=========================");
println!();
// Risk summary
print_risk_summary(&content);
// Hash the in-memory buffer (not a second file read)
let hash = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(&content_bytes);
format!("{:x}", h.finalize())
};
// Store trust with pre-computed hash
trust_filter_with_hash(filter_path, &hash)?;
println!();
println!(
"Trusted .rtk/filters.toml (sha256:{})",
hash.get(..16).unwrap_or(&hash)
);
println!("Project-local filters will now be applied.");
Ok(())
}
/// Run `rtk untrust` — revoke trust for project-local filters.
pub fn run_untrust() -> Result<()> {
let filter_path = Path::new(".rtk/filters.toml");
// If file doesn't exist, untrust by canonical path lookup won't work.
// Try anyway (file may have been deleted after trust), fallback gracefully.
let removed = untrust_filter(filter_path).unwrap_or(false);
if removed {
println!("Trust revoked for .rtk/filters.toml");
println!("Project-local filters will no longer be applied.");
} else {
println!("No trust entry found for current directory.");
}
Ok(())
}
// ---------------------------------------------------------------------------
// Risk analysis
// ---------------------------------------------------------------------------
fn print_risk_summary(content: &str) {
let filter_count = content.matches("[filters.").count();
let has_replace = content.contains("replace");
let has_match_output = content.contains("match_output");
let has_dot_pattern = content.contains("pattern = \".\"") || content.contains("pattern = '.'");
println!("Risk summary:");
println!(" Filters: {}", filter_count);
if has_replace {
println!(" ⚠ Contains 'replace' rules (can rewrite output)");
}
if has_match_output {
println!(" ⚠ Contains 'match_output' rules (can replace entire output)");
}
if has_dot_pattern {
println!(" ⚠ Contains catch-all pattern '.' (matches everything)");
}
if !has_replace && !has_match_output && !has_dot_pattern {
println!(" No high-risk patterns detected.");
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
/// Helper: create a temporary trust store in a temp dir.
/// Overrides the store path via a scoped env var (not possible with
/// the real function), so we test the logic by calling internal fns.
fn setup_test_env(temp: &TempDir) -> PathBuf {
let store_file = temp.path().join("trusted_filters.json");
store_file
}
fn check_trust_with_store(filter_path: &Path, store_file: &Path) -> Result<TrustStatus> {
// Note: env var check is NOT included here to avoid test interference.
// The env var path is tested separately in test_env_override.
let key = canonical_key(filter_path)?;
let store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
TrustStore::default()
};
let entry = match store.trusted.get(&key) {
Some(e) => e,
None => return Ok(TrustStatus::Untrusted),
};
let actual_hash = integrity::compute_hash(filter_path)?;
if actual_hash == entry.sha256 {
Ok(TrustStatus::Trusted)
} else {
Ok(TrustStatus::ContentChanged {
expected: entry.sha256.clone(),
actual: actual_hash,
})
}
}
fn trust_with_store(filter_path: &Path, store_file: &Path) -> Result<()> {
let key = canonical_key(filter_path)?;
let hash = integrity::compute_hash(filter_path)?;
let mut store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
TrustStore::default()
};
store.version = 1;
store.trusted.insert(
key,
TrustEntry {
sha256: hash,
trusted_at: chrono::Utc::now().to_rfc3339(),
},
);
if let Some(parent) = store_file.parent() {
std::fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(&store)?;
std::fs::write(store_file, content)?;
Ok(())
}
fn untrust_with_store(filter_path: &Path, store_file: &Path) -> Result<bool> {
let key = canonical_key(filter_path)?;
let mut store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
return Ok(false);
};
let removed = store.trusted.remove(&key).is_some();
if removed {
let content = serde_json::to_string_pretty(&store)?;
std::fs::write(store_file, content)?;
}
Ok(removed)
}
#[test]
fn test_untrusted_by_default() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_trust_then_check() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Trusted);
}
#[test]
fn test_content_change_detected() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
// Modify the filter file
std::fs::write(
&filter,
"[filters.evil]\nmatch_command = \".*\"\nmatch_output = \"password\"",
)
.unwrap();
let status = check_trust_with_store(&filter, &store_file).unwrap();
match status {
TrustStatus::ContentChanged { expected, actual } => {
assert_ne!(expected, actual);
assert_eq!(expected.len(), 64);
assert_eq!(actual.len(), 64);
}
other => panic!("Expected ContentChanged, got {:?}", other),
}
}
#[test]
fn test_untrust_revokes() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
let removed = untrust_with_store(&filter, &store_file).unwrap();
assert!(removed);
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_env_override_with_ci() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
// Both env vars must be set: trust override + CI indicator
#[allow(deprecated)]
std::env::set_var("RTK_TRUST_PROJECT_FILTERS", "1");
#[allow(deprecated)]
std::env::set_var("CI", "true");
let status = check_trust(&filter).unwrap();
#[allow(deprecated)]
std::env::remove_var("RTK_TRUST_PROJECT_FILTERS");
#[allow(deprecated)]
std::env::remove_var("CI");
assert_eq!(status, TrustStatus::EnvOverride);
}
#[test]
fn test_env_override_without_ci_is_ignored() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
// Trust override WITHOUT CI env → should be Untrusted, not EnvOverride
// (protects against .envrc injection)
// Note: we use check_trust_with_store which skips env var check,
// so this tests the store path when env var would be ignored
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_missing_store_is_untrusted() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = temp.path().join("nonexistent").join("store.json");
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_risk_summary_detects_replace() {
let content = "[filters.evil]\nmatch_command = \"git\"\nreplace = [[\"secret\", \"\"]]";
// Just verify it doesn't panic — output goes to stdout
print_risk_summary(content);
}
#[test]
fn test_risk_summary_detects_match_output() {
let content = "[filters.evil]\nmatch_command = \"scan\"\nmatch_output = \"vulnerability\"";
print_risk_summary(content);
}
#[test]
fn test_canonical_key_works() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "test").unwrap();
let key = canonical_key(&filter).unwrap();
assert!(key.contains("filters.toml"));
// Should be an absolute path
assert!(key.starts_with('/') || key.contains(':'));
}
}
+2 -2
View File
@@ -3,7 +3,7 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_output,
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_passthrough,
FormatMode, OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
};
use crate::tracking;
@@ -88,7 +88,7 @@ impl OutputParser for VitestParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+20 -8
View File
@@ -41,10 +41,16 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
} else {
let error = parse_error(&stderr, &stdout);
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget {}", url),
"rtk wget",
&raw_output,
&raw_output,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -103,10 +109,16 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
let error = parse_error(&stderr, "");
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget -O - {}", url),
"rtk wget -o",
&stderr,
&stderr,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())