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
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
51 changed files with 2208 additions and 531 deletions

No files matched your search

+29 -4
View File
@@ -32,10 +32,11 @@ main.rs (Commands enum + routing)
## Review Process
1. **Context**: Identify which module changed, what command it affects, token savings claim
2. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
3. **Token savings**: Verify savings claim is tested with real fixture
4. **Cross-platform**: Shell escaping, path separators, ANSI codes
5. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
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
## RTK-Specific Red Flags
@@ -198,6 +199,29 @@ fix_here
| 🔴 | 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%?
@@ -207,6 +231,7 @@ fix_here
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)
+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
@@ -44,5 +44,5 @@ claudedocs
.vitals/
.worktrees/
# icm
# icm
.fastembed_cache/
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.28.2"
".": "0.29.0"
}
+1 -1
View File
@@ -293,7 +293,7 @@ SHARED utils.rs Helpers N/A ✓
tee.rs Full output recovery N/A ✓
```
**Total: 64 modules** (42 command modules + 22 infrastructure modules)
**Total: 60 modules** (38 command modules + 22 infrastructure modules)
### Module Count Breakdown
+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)
+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"
+7 -1
View File
@@ -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)
);
}
};
-37
View File
@@ -59,9 +59,6 @@ pub fn run_err(command: &str, verbose: u8) -> Result<()> {
println!("{}", rtk);
}
timer.track(command, "rtk run-err", &raw, &rtk);
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
@@ -103,9 +100,6 @@ pub fn run_test(command: &str, verbose: u8) -> Result<()> {
println!("{}", summary);
}
timer.track(command, "rtk run-test", &raw, &summary);
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
@@ -274,35 +268,4 @@ mod tests {
assert!(filtered.contains("error"));
assert!(!filtered.contains("info"));
}
#[test]
#[ignore]
fn test_err_forwards_exit_code_nonzero() {
// Requires rtk to be installed on PATH (cargo install --path .)
let output = std::process::Command::new("rtk")
.args(["err", "sh", "-c", "exit 2"])
.output()
.expect("failed to run rtk — install with: cargo install --path .");
assert_eq!(output.status.code(), Some(2));
}
#[test]
#[ignore]
fn test_err_forwards_exit_code_zero() {
let output = std::process::Command::new("rtk")
.args(["err", "sh", "-c", "exit 0"])
.output()
.expect("failed to run rtk — install with: cargo install --path .");
assert_eq!(output.status.code(), Some(0));
}
#[test]
#[ignore]
fn test_test_forwards_exit_code_nonzero() {
let output = std::process::Command::new("rtk")
.args(["test", "sh", "-c", "exit 1"])
.output()
.expect("failed to run rtk — install with: cargo install --path .");
assert_eq!(output.status.code(), Some(1));
}
}
+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");
}
}
-7
View File
@@ -31,16 +31,9 @@ pub fn run(command: &str, verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
let exit_code = output
.status
.code()
.unwrap_or(if output.status.success() { 0 } else { 1 });
let summary = summarize_output(&raw, command, output.status.success());
println!("{}", summary);
timer.track(command, "rtk summary", &raw, &summary);
if exit_code != 0 {
std::process::exit(exit_code);
}
Ok(())
}
+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(())