Repository navigation
Description
Context
Using rtk v0.31.0 with the official Claude Code PreToolUse hook (rtk rewrite).
The hook is correctly rewriting commands — rtk gain confirms 567 commands processed with 51.8K tokens saved (54.5%).
Problem 1
rtk discover scans Claude Code session history and matches against original command text, not the actually-executed commands. When the PreToolUse hook rewrites find ... → rtk find ..., the session log still records the original find command.
Result: discover reports these already-rewritten commands as "missed savings":
Scanned: 125 sessions (last 30 days), 1841 Bash commands
Already using RTK: 6 commands (0%)
MISSED SAVINGS:
find 471 rtk find ~137.0K tokens
git add 181 rtk git ~33.2K tokens
grep -r 169 rtk grep ~19.4K tokens
ls -la 189 rtk ls ~4.4K tokens
composer 8 rtk composer ~4.1K tokens
cat 38 rtk read ~2.8K tokens
tree 9 rtk tree ~1.4K tokens
Total: 1066 commands -> ~202.4K tokens saveable
Most of these 1066 "missed" commands were actually handled by the hook. The 6 "already using RTK" only counts commands where the LLM explicitly wrote rtk ... in the Bash call.
I confirmed that rtk rewrite does handle all the "missed" commands correctly:
cat /tmp/file.txt → rtk read /tmp/file.txt ✅
composer update → rtk composer update ✅
tree -L 2 → rtk tree -L 2 ✅
git status → rtk git status ✅
git log --oneline -5 → rtk git log --oneline -5 ✅
git diff → rtk git diff ✅
find ... -name *.php → rtk find ... ✅
grep -r 'pattern' src → rtk grep ... ✅
ls -la → rtk ls -la ✅
Expected behavior
discover should account for hook-based rewrites. Possible approaches:
- Cross-reference with
rtk gaindata (which logs all actually-processed commands) - Detect that the hook is configured (check
~/.claude/settings.jsonforrtk-rewritein PreToolUse hooks) and adjust the report - Show a separate "likely handled by hook" category instead of "missed"
Problem 2: high-volume commands not handled by rtk rewrite
These commands fail rtk rewrite (exit 1) but could be mapped to existing generic handlers:
| Command | Count | Existing handler | Notes |
|---|---|---|---|
php vendor/bin/pest ... |
276 | rtk test |
Test runner — verbose output with stack traces |
./vendor/bin/pest ... |
14 | rtk test |
Direct invocation |
vendor/bin/phpstan analyse ... |
12 | rtk err |
Static analysis — can output hundreds of lines |
composer show ... |
3 | rtk composer |
composer update works, but not show |
Local workaround
Until native support is added, I worked around this with a second PreToolUse hook (local-rewrite.sh) placed before rtk-rewrite.sh in the Claude Code
hook chain. It doesn't modify rtk-rewrite.sh (no integrity conflict):
#!/usr/bin/env bash
# local-rewrite.sh — maps unhandled commands to generic rtk handlers
# Runs BEFORE rtk-rewrite.sh in the PreToolUse hook chain.
command -v jq &>/dev/null || exit 0
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
[ -z "$CMD" ] && exit 0
case "$CMD" in
"php vendor/bin/pest "*) REWRITTEN="rtk test $CMD" ;;
"./vendor/bin/pest "*) REWRITTEN="rtk test $CMD" ;;
"vendor/bin/pest "*) REWRITTEN="rtk test $CMD" ;;
"vendor/bin/phpstan analyse"*) REWRITTEN="rtk err $CMD" ;;
"./vendor/bin/phpstan analyse"*) REWRITTEN="rtk err $CMD" ;;
"composer show"*) REWRITTEN="rtk composer ${CMD#composer }" ;;
*) exit 0 ;;
esac
ORIGINAL_INPUT=$(echo "$INPUT" | jq -c '.tool_input')
UPDATED_INPUT=$(echo "$ORIGINAL_INPUT" | jq --arg cmd "$REWRITTEN" '.command = $cmd')
jq -n --argjson updated "$UPDATED_INPUT" '{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "Local rtk rewrite",
"updatedInput": $updated
}
}' settings.json config (local hook before rtk hook):
"PreToolUse": [
{ "hooks": [{ "command": "~/.claude/hooks/local-rewrite.sh", "type": "command" }], "matcher": "Bash" },
{ "hooks": [{ "command": "~/.claude/hooks/rtk-rewrite.sh", "type": "command" }], "matcher": "Bash" }
] Ideally, rtk rewrite could handle these mappings natively (pest/phpstan → rtk test/rtk err) so this workaround wouldn't be needed.
Environment
- rtk 0.31.0
- Claude Code with PreToolUse hook via
rtk rewrite - Linux (Ubuntu)
Activity
pszymkowiak commentedon Mar 23, 2026
Closing as duplicate of #2036. See the original issue for updates.
wkup commentedon Mar 25, 2026
Update: expanded
local-rewrite.shfor broader PHP ecosystem coverageAfter further analysis with
rtk discover, a few additional unhandled patterns surfaced beyond what was in the original workaround:php -l <file>rtk err./vendor/bin/pest(no args)rtk test"./vendor/bin/pest "*didn't matchphp vendor/bin/phpstan analysertk errphpprefix variant missingscript -qc "php vendor/bin/pest ..."rtk testscriptwrapper not unwrappedphp artisan ...rtk errcomposer config/composer create-projectrtk composerThe updated
local-rewrite.shnow also unwrapsscript -qc "..."wrappers (commonly used to work around TTY issues with pest) before routing:Feature request angle: php -l alone represents the biggest volume (~456 commands). Since PHP lint, Pest, and PHPStan are common in PHP/Symfony/Laravel projects, would it make sense to add native rtk php or at least have rtk rewrite recognize these patterns? That would remove the need for the local hook entirely for PHP developers.
wkup commentedon Apr 9, 2026
Follow-up: 30-day usage data & expanded local hook
After 18 days of additional usage (v0.34.2 → upgrading to v0.35.0), here's
an update with broader data.
Stats overview
rtk discoverstill reports ~2.2M tokens saveable from 14K+commands
Problem 1 update — discover still over-reports hook-rewritten
commands
Same root cause as originally reported. These commands are being
rewritten by the PreToolUse hook chain, but
discoverstill counts themas missed:
findgrep -rdocker execgit addcat -nls -laProblem 2 update — expanded coverage gaps in
rtk rewriteBeyond the PHP commands from the original report, several more high-volume
patterns aren't caught natively:
docker composertk dockervue-tsc/npx vue-tscrtk errdocker cprtk dockertailwindcss(standalone binary)rtk errdocker restartrtk dockerdocker logsrtk dockeransible <host> -m shellrtk errrtk testsilent success — UX issueWhen all tests pass,
rtk testoutputs nothing — the LLM gets anempty result and has no confirmation that tests succeeded. In contrast,
rtk erroutputs[ok] Command completed successfully, which is muchbetter feedback.
I switched all my test runners from
rtk testtortk errin my localhook for this reason. Suggestion: either make
rtk testemit a one-linesummary on success (e.g.
[ok] 48 tests passed), or documentrtk errasthe recommended wrapper for test commands.
Updated local hook
My
local-rewrite.shnow covers all the above. Available here if usefulfor reference or for baking into
rtk rewritenatively:local-rewrite.sh (click to expand)
fix(discover): cross-reference tracking DB to exclude hook-handled co…
wkup commentedon May 5, 2026
Additional findings (follow-up to absolute-path /
\cmdrewrite issue)After deploying the workaround for absolute-path invocations, our daily token-savings rate dropped to 21.9 % (vs. ~85 % typical) on a session dominated by PHP
tooling. RTK history DB analysis (
/home/<user>/.local/share/rtk/history.db) shows three patterns that account for ~90 % of unsaved output:1.
php vendor/bin/phpstan analyse …andphp vendor/bin/pest …rtk rewritereturns exit code 1 (no equivalent) and the hook falls back tortk proxy(passthrough + tracking, 0 % savings).$ rtk rewrite "php vendor/bin/pest tests/Unit" # exit=1
$ rtk rewrite "php vendor/bin/phpstan analyse" # exit=1
Yet
rtk errandrtk testalready provide perfect filters for these tools. The registry should rewrite:php vendor/bin/pest …,vendor/bin/pest …,./vendor/bin/pest …rtk err <cmd>(orrtk test <cmd>)php vendor/bin/phpstan analyse …(andvendor/bin/…,./vendor/bin/…)rtk err <cmd>php vendor/bin/php-cs-fixer …rtk err <cmd>php bin/console …,php artisan …,php -l …rtk err <cmd>Same logic likely applies to
bundle exec rspec,bundle exec rubocop, etc. — any tool typically invoked through a vendored binary.2.
git status --shorton a busy repositoryrtk rewrite "git status --short"correctly maps tortk git status --short, butrtk git status --shortproduces output identical in size to raw git (26 408chars on a repo with 444 modified files in our case — 0 % savings).
By contrast,
rtk git status(without--short) yields the expected compact summary (1 099 chars, 96 % savings) using the "Modified: 272 files / first 15 /+257 more" pattern. Suggested behaviors:
+ N moretruncation pattern tortk git status --shortpast a threshold (e.g. 50 lines), orrtk discoverso users know to drop--shorton large repos.3. PreToolUse hook chain semantics — Claude Code-side caveat
Not strictly an RTK bug, but relevant to anyone shipping a
local-rewrite.shalongsidertk-rewrite.sh: Claude Code runs PreToolUse hooks under the samematcher in parallel, on the original input. Last
updatedInputwins. Two separate matcher entries ({matcher: "Bash", hooks: [local]},{matcher: "Bash", hooks: [rtk]}) cause the second hook to silently override the first, even though the README implies sequential composition.We worked around this by having
local-rewrite.shinvokertk-rewrite.shdirectly when no local pattern matches:wkup commentedon May 5, 2026
Update — additional unhandled patterns observed in production usage
Following up with concrete data from a heavy-usage day (~1k commands, 28.4% savings vs 86.1% global average). The drop was caused by three RTK patterns
that pass through the rewrite hook correctly but are not compressed by RTK itself.
1.
rtk fallback: grep -r{l,n}with recursive flagsRecent commands log:
rtk grepaccepts the command but falls back to rawgrepfor:-rl)-rnwith multi-pattern or piped output)The fallback mechanism works as designed, but the output is not compressed.
Suggested handling
-rl→ compress to a deduplicated file list (typicalgrep -rloutput is 10–500 paths, easy to cap at one path per line)-rn→ already has a handler in some cases; investigating why the fallback is triggered would help2.
docker exec— no compression strategyrtk dockerrewrites the command butdocker exec <container> <inner_cmd>returns the inner command's output verbatim.Suggested handling
Parse
docker exec <container> <inner>and dispatch the inner command through RTK's existing handlers:docker exec <c> grep <pattern> <file>rtk grep <pattern> <file>docker exec <c> tail -n 100 <file>rtk read(tail mode)docker exec <c> cat <file>rtk read <file>docker exec <c> ls <path>rtk ls <path>docker exec <c> find <path> ...rtk find <path> ...docker exec <c> wc -l <file>rtk wc -l <file>This would unlock most of the missed savings.
3.
git diff <range>andgit log <range>rtk gitcompressesstatus(~56%),commit(~99%), andaddwell. Butgit diff <sha1>..<sha2>andgit log <sha1>..<sha2>return raw output. Theseare heavily used for code review and cross-commit exploration.
Suggested handling
git log <range>→ keep first line of each commit (%h %s), drop body, drop merge commits (already supported elsewhere?)git diff <range>→ either:--statsummary with a flag to opt back into full diff, or@@headers + N lines of context, drop unchanged regionsDaily impact data
Detection summary
Happy to provide more raw data (
rtk gain --history, sanitised transcript excerpts) if useful.