Skip to content

discover over-reports missed savings when PreToolUse hook is active #789

Closed

Description

@wkup

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 gain data (which logs all actually-processed commands)
  • Detect that the hook is configured (check ~/.claude/settings.json for rtk-rewrite in 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

  1. added
    bug
    effort-medium
    enhancement
    on Mar 23, 2026
  2. pszymkowiak commented on Mar 23, 2026

    @pszymkowiak
    Collaborator

    Closing as duplicate of #2036. See the original issue for updates.

  3. wkup commented on Mar 25, 2026

    @wkup
    Author

    Update: expanded local-rewrite.sh for broader PHP ecosystem coverage

    After further analysis with rtk discover, a few additional unhandled patterns surfaced beyond what was in the original workaround:

    Command pattern Count Mapping Issue in original hook
    php -l <file> ~456 rtk err Not handled at all
    ./vendor/bin/pest (no args) ~18 rtk test Trailing space required in pattern — "./vendor/bin/pest "* didn't match
    php vendor/bin/phpstan analyse ~12 rtk err php prefix variant missing
    script -qc "php vendor/bin/pest ..." ~12 rtk test script wrapper not unwrapped
    php artisan ... several rtk err Not handled
    composer config / composer create-project ~8 rtk composer Not handled

    The updated local-rewrite.sh now also unwraps script -qc "..." wrappers (commonly used to work around TTY issues with pest) before routing:

    #!/usr/bin/env bash
    # Local rewrite hook — maps commands that rtk rewrite doesn't handle                                                                                                                                             
    # to generic rtk handlers (rtk test, rtk err, rtk composer).                                                                                                                                                     
    # 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
                                                                                                                                                                                                                     
    # Unwrap script -qc "..." wrapper (used to avoid TTY issues with pest)                                                                                                                                           
    if [[ "$CMD" =~ ^script\ -qc\ [\"\'](.+)[\"\'] ]]; then
      CMD="${BASH_REMATCH[1]}"                                                                                                                                                                                       
    fi              
                                                                                                                                                                                                                     
    case "$CMD" in  
      # Test runners → rtk test (show only failures)
      "php vendor/bin/pest"*)               REWRITTEN="rtk test $CMD" ;;                                                                                                                                             
      "./vendor/bin/pest"*)                 REWRITTEN="rtk test $CMD" ;;                                                                                                                                             
      "vendor/bin/pest"*)                   REWRITTEN="rtk test $CMD" ;;                                                                                                                                             
      # Static analysis → rtk err (show only errors/warnings)                                                                                                                                                        
      "php vendor/bin/phpstan analyse"*)    REWRITTEN="rtk err $CMD" ;;                                                                                                                                              
      "vendor/bin/phpstan analyse"*)        REWRITTEN="rtk err $CMD" ;;
      "./vendor/bin/phpstan analyse"*)      REWRITTEN="rtk err $CMD" ;;                                                                                                                                              
      # PHP lint check → rtk err (show only errors)
      "php -l "*)                           REWRITTEN="rtk err $CMD" ;;                                                                                                                                              
      # PHP artisan → rtk err (capture errors from artisan commands)
      "php artisan "*)                      REWRITTEN="rtk err $CMD" ;;                                                                                                                                              
      # Composer subcommands not in rtk rewrite
      "composer show"*)                     REWRITTEN="rtk composer ${CMD#composer }" ;;                                                                                                                             
      "composer config"*)                   REWRITTEN="rtk composer ${CMD#composer }" ;;
      "composer create-project"*)           REWRITTEN="rtk composer ${CMD#composer }" ;;                                                                                                                             
      # No match — let rtk-rewrite.sh handle it
      *) 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
        }                                                                                                                                                                                                            
      }'            

    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.

  4. wkup commented on Apr 9, 2026

    @wkup
    Author

    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

    • 10K commands processed, 52.5M tokens saved (94.6% savings)
    • rtk discover still 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 discover still counts them
    as missed:

    Command Count (30d) Reported savings
    find 3,326 ~894K
    grep -r 2,236 ~408K
    docker exec 2,130 ~282K
    git add 2,469 ~251K
    cat -n 687 ~245K
    ls -la 1,851 ~74K

    Problem 2 update — expanded coverage gaps in rtk rewrite

    Beyond the PHP commands from the original report, several more high-volume
    patterns aren't caught natively:

    Command Count (30d) Suggested handler
    docker compose 604 rtk docker
    vue-tsc / npx vue-tsc 288 rtk err
    docker cp 159 rtk docker
    tailwindcss (standalone binary) 228 rtk err
    docker restart 72 rtk docker
    docker logs — rtk docker
    ansible <host> -m shell 107 rtk err

    rtk test silent success — UX issue

    When all tests pass, rtk test outputs nothing — the LLM gets an
    empty result and has no confirmation that tests succeeded. In contrast,
    rtk err outputs [ok] Command completed successfully, which is much
    better feedback.

    I switched all my test runners from rtk test to rtk err in my local
    hook for this reason. Suggestion: either make rtk test emit a one-line
    summary on success (e.g. [ok] 48 tests passed), or document rtk err as
    the recommended wrapper for test commands.

    Updated local hook

    My local-rewrite.sh now covers all the above. Available here if useful
    for reference or for baking into rtk rewrite natively:

    local-rewrite.sh (click to expand)
    case "$CMD" in                                                            
      # Test runners                                            
      "php vendor/bin/pest"*)               REWRITTEN="rtk err $CMD" ;;
      "./vendor/bin/pest"*)                 REWRITTEN="rtk err $CMD" ;;
      "vendor/bin/pest"*)                   REWRITTEN="rtk err $CMD" ;;       
      # Static analysis
      "php vendor/bin/phpstan analyse"*)    REWRITTEN="rtk err $CMD" ;;       
      "vendor/bin/phpstan analyse"*)        REWRITTEN="rtk err $CMD" ;;       
      "./vendor/bin/phpstan analyse"*)      REWRITTEN="rtk err $CMD" ;;
      # PHP CS Fixer                                                          
      "php vendor/bin/php-cs-fixer"*)       REWRITTEN="rtk err $CMD" ;;
      "vendor/bin/php-cs-fixer"*)           REWRITTEN="rtk err $CMD" ;;       
      # PHP lint
      "php -l "*)                           REWRITTEN="rtk err $CMD" ;;       
      # Docker subcommands                                                    
      "docker exec "*)                      REWRITTEN="rtk docker ${CMD#docker
     }" ;;                                                                    
      "docker compose "*)                   REWRITTEN="rtk docker compose
    ${CMD#docker compose }" ;;                                                
      "docker restart "*)                   REWRITTEN="rtk docker ${CMD#docker
     }" ;;                                                                    
      "docker cp "*)                        REWRITTEN="rtk docker ${CMD#docker
     }" ;;
      "docker logs "*)                      REWRITTEN="rtk docker ${CMD#docker
     }" ;;                                                                    
      # Build tools
      "./bin/tailwindcss "*)                REWRITTEN="rtk err $CMD" ;;       
      *"/tailwindcss-linux-x64 "*)          REWRITTEN="rtk err $CMD" ;;
      "./node_modules/.bin/vue-tsc "*)      REWRITTEN="rtk err $CMD" ;;       
      "npx vue-tsc "*)                      REWRITTEN="rtk err $CMD" ;;
      # Ansible ad-hoc                                                        
      "ansible "*)                          REWRITTEN="rtk err $CMD" ;;
      # Composer                                                              
      "composer show"*)                     REWRITTEN="rtk composer
    ${CMD#composer }" ;;
      "composer config"*)                   REWRITTEN="rtk composer
    ${CMD#composer }" ;;                                                      
      *) exit 0 ;;
    esac     
  5. wkup commented on May 5, 2026

    @wkup
    Author

    Additional findings (follow-up to absolute-path / \cmd rewrite 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 … and php vendor/bin/pest …

    rtk rewrite returns exit code 1 (no equivalent) and the hook falls back to rtk 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 err and rtk test already provide perfect filters for these tools. The registry should rewrite:

    Original Suggested rewrite
    php vendor/bin/pest …, vendor/bin/pest …, ./vendor/bin/pest … rtk err <cmd> (or rtk test <cmd>)
    php vendor/bin/phpstan analyse … (and vendor/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 --short on a busy repository

    rtk rewrite "git status --short" correctly maps to rtk git status --short, but rtk git status --short produces output identical in size to raw git (26 408
    chars 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:

    • Either apply the + N more truncation pattern to rtk git status --short past a threshold (e.g. 50 lines), or
    • Document the limitation and add a hint in rtk discover so users know to drop --short on large repos.

    3. PreToolUse hook chain semantics — Claude Code-side caveat

    Not strictly an RTK bug, but relevant to anyone shipping a local-rewrite.sh alongside rtk-rewrite.sh: Claude Code runs PreToolUse hooks under the same
    matcher
    in parallel, on the original input. Last updatedInput wins. 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.sh invoke rtk-rewrite.sh directly when no local pattern matches:

    *)                                                                                                                                   
      printf '%s' "$INPUT" | /home/<user>/.claude/hooks/rtk-rewrite.sh
      exit $?
      ;;                                                                                                                                                                 
     
    A note in the README's "How to extend" section about this trap (or shipping a single composable script) would save users the diagnostic round-trip.                  
                                                                                                                                         
    Empirical impact                                                                                                                                                     
                                                                                                                                         
    Patching local-rewrite.sh to cover the 3 patterns and merging the hook chain restored savings to expected levels in our manual tests:                                
     
    - php vendor/bin/pest tests/…: 0 % → ~95 % (rtk err filter)                                                                                                          
    - php vendor/bin/phpstan analyse …: 0 % → ~95 %                                                                                      
    - git status --short (bare, busy repo): 0 % → 96 %                                                                                                                   
                                                                                                                                                                         
    Output of rtk discover on our 30-day history confirms ~3 K php invocations + 60+ pest / 79 docker restart / 137 git flagged as unhandled, ~10–15 % of total volume. 
  6. wkup commented on May 5, 2026

    @wkup
    Author

    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 flags

    Recent commands log:

    • rtk fallback: grep -rl... -0% (0)
    • rtk fallback: grep -rl... -0% (0)                                                                                                                        
    • rtk fallback: grep -rn... -0% (0)                                                                                           
    

    rtk grep accepts the command but falls back to raw grep for:

    • recursive list-files mode (-rl)
    • recursive line-numbered mode (-rn with 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 (typical grep -rl output 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 help

    2. docker exec — no compression strategy

    • rtk docker exec <container>... -0% (0)
    • rtk docker exec <container>... -0% (0)                                                                                                                   
    • rtk docker exec <container>... -0% (0)
    

    rtk docker rewrites the command but docker exec <container> <inner_cmd> returns the inner command's output verbatim.

    This is the #2 top unhandled command in rtk discover (~850 occurrences over 3 days, ~150K tokens missed).

    Suggested handling

    Parse docker exec <container> <inner> and dispatch the inner command through RTK's existing handlers:

    Original Dispatched as
    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> and git log <range>

    • rtk git diff <sha1>..<sha2>  -0%  (0)
    • rtk git log  <sha1>..<sha2>  -1%  (1)                                                                                                                    
    • rtk git diff <sha1>..<sha2>  -0%  (0)
    

    rtk git compresses status (~56%), commit (~99%), and add well. But git diff <sha1>..<sha2> and git log <sha1>..<sha2> return raw output. These
    are 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:
      • default to --stat summary with a flag to opt back into full diff, or
      • compress hunks: keep @@ headers + N lines of context, drop unchanged regions

    Daily impact data

    Day Commands Input Output Out/In ratio Saved
    Day A (good) ~3.2k 5.4M 256K 4.7% 95.4%
    Day B (bad) ~1.0k 3.5M 2.5M 71% 28.4%

    The output / input ratio is the cleanest indicator: when RTK can't compress, output stays huge relative to input. On the bad day, the dominant
    uncompressed contributors were the three patterns above.


    Detection summary

    $ rtk discover --since 3 | head
    Already using RTK: 449 commands (6.9%)                                                                                                                     
    …
    docker exec    ~850   rtk docker   ~150K tokens                                                                                                            
    grep -n       ~1.5k   rtk grep     ~200K tokens                                                                               

    ⚠️ Note: the discover "missed savings" line is misleading — these commands are rewritten by the local hook, but RTK's internal handlers don't
    compress them. The numbers should rather be read as "tokens still leaking through after rewrite", which matches the observation here.


    Happy to provide more raw data (rtk gain --history, sanitised transcript excerpts) if useful.

  7. added
    duplicate
    on May 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:clibugduplicateeffort-mediumenhancementpriority:medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions