Skip to content

rtk grep rejects common grep flags (-r/-E/-A/-i) -> silent raw fallback, 0 savings #2614

Closed as duplicate

Description

@voxdei

rtk grep fails to parse the most common real-world grep invocations and silently falls back to raw grep (0 tokens saved). Over my last 90 days: 4,416 grep parse failures, 100% fell back to raw.

The parser rejects standard flags as "unexpected argument":

Flag rejected Failures Typical use
-r (incl. -rn, -rln) 3,301 recursive search
-E 333 extended regex
-A / -B / -C 540 context lines
-i 112 case-insensitive
-o 90 only-matching
-q 85 quiet

Example failing commands, all recovered-but-unfiltered:

grep -rn TRANSACTION_ID app/services/...
grep -rln 'class.*SyncConfiguration\|sync_client_class' lib/
grep -A10 'gitlab.com:' ~/.config/...
grep -nE 'def client|def sync_reference' lib/

Impact: these aren't edge cases — they're the dominant grep form. rtk grep's headline 19% avg save rate is entirely composition: simple greps hit 95–98%, but every -r/-E/-A call scores 0. Fixing flag coverage lifts the most-used command in the proxy.

Ask: accept (and apply filtering to) the standard GNU grep flag set — at minimum -r/-R, -E, -A/-B/-C, -i, -o, -q, and combined short forms like -rn/-rln. Failures are logged silently (99.9% "recovery"), so they read as success while saving nothing.

rtk 0.42.4

Activity

  1. added
    bug
    help wanted
    on Jun 25, 2026
  2. pszymkowiak commented on Jun 25, 2026

    @pszymkowiak
    Collaborator

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟠 Priority high
    🎯 Confidence 87%

    Summary

    rtk grep parser rejects standard GNU grep flags (-r, -E, -A/-B/-C, -i, -o, -q), silently falling back to raw grep with 0 token savings — affects dominant real-world usage patterns

    📁 Relevant files
    • src/parser/grep.rs

    Triaged automatically by wshm · This is an automated analysis, not a human review.

  3. alexisLefebvre commented on Jun 25, 2026

    @alexisLefebvre
  4. voxdei commented on Jun 25, 2026

    @voxdei
    Author

    Not a regression, and not -rln itself. -r/-rn/-rln succeed 2,773 times in my history DB — they parse fine. The clap error: unexpected argument '-r' is a red herring: positional parsing derails on a later token, and clap blames the first short flag it sees.

    Digging into 90 days of my commands + parse_failures tables, the real triggers are:

    1. --include=GLOB is 100% unsupported — 943 failures, 0 successes. Every grep -rn ... --include=*.rb falls back to raw.
    2. Unquoted \| alternation — a bare alternation pattern breaks parsing; the quoted equivalent works:
      • ❌ grep -rn def reactive_years\|alias_method lib/ app/
      • ✅ grep -rn 'def reactive_years\|alias_method' lib/

    Failures interleave with successes across all 90 days in proportion, so nothing broke recently — these two cases were just never handled.

    Sharpened ask: support --include/--exclude glob flags, and tolerate unquoted alternation patterns (or at minimum don't reject the whole invocation — the misleading -r error sends people down the wrong path).

  5. devnulled commented on Jun 25, 2026

    @devnulled
    Contributor

    Independent corroboration from a different environment (macOS, Claude Code 2.1.191, rtk 0.42.4, via the rtk hook claude PreToolUse hook).

    Same pattern in my local history.db: 2,659 grep parse-failures (of 2,695 total failures), 100% recovered via raw fallback → 0 tokens saved.

    Flag rejected Failures
    -r (incl. -rn, -rho, -rln) 1,270
    -A 451
    -E 375
    -B 176
    -c 148
    -i 94
    -o 41
    -F 27
    -q 27
    -C 8

    Plus a separate error: invalid value '...' class when the pattern contains alternation (\|), e.g. grep -n 'getServiceAddress\|getMduChildren' file — clap consumes the pattern as a value for a value-taking flag.

    Confirmed root cause: argument ordering, not missing support

    rtk grep --help advertises that extra ripgrep flags are accepted:

    Usage: rtk grep [OPTIONS] <PATTERN> [PATH] [EXTRA_ARGS]...
      [EXTRA_ARGS]...  Extra ripgrep arguments (e.g., -i, -A 3, -w, --glob)
    

    …but only in the trailing EXTRA_ARGS position. The hook rewrites grep <flags> <pattern> → rtk grep <flags> <pattern>, leaving the flags before <PATTERN>, where clap intercepts them as unknown options. Minimal repro:

    # flags before pattern (what the hook emits) -> rejected -> raw fallback, 0 savings
    rtk grep -n -A1 "telemetry" config.toml      # => raw grep output
    
    # same flags trailing (EXTRA_ARGS slot)       -> parsed -> compact output, savings
    rtk grep "telemetry" config.toml -A1          # => "2 matches in 1 files: ... [+1 more]"
    

    Possible fix directions

    1. In rtk hook claude, when rewriting grep, move recognized native flags to the trailing EXTRA_ARGS position (after <PATTERN> [PATH]).
    2. Or make rtk grep tolerant of leading passthrough flags (e.g. accept trailing_var_arg / allow_hyphen_values, or pre-split argv so native grep flags route to ripgrep regardless of position).

    Related: #1604 (same hook-rewrite root cause, also covers non-existent subcommands like ps/du), #1436 (alternation-pattern mangling).

  6. devnulled commented on Jun 25, 2026

    @devnulled
    Contributor

    Following up on my earlier data. After investigating against current develop, I can confirm @voxdei's read: the broad -r/-E/-A rejection is largely already resolved (the extra_args + allow_hyphen_values design from 84616d1). The historical history.db failures predate that.

    The one residual I can still reproduce: rtk's own grep options -l/-m/-t shadow native grep/rg flags of the same letter. grep -l PATTERN (files-with-matches) becomes rtk grep -l PATTERN, clap tries to parse the pattern as --max-len's usize, exits 2, and falls back to raw grep with 0 savings. -m/-t silently mis-apply.

    Opened a focused PR (#2628) that makes those options long-only so the native flags pass through. Distinct from the --include/alternation work and from #2224/#2532.

  7. pidefrem commented on Jun 26, 2026

    @pidefrem

    This issue (and the cluster around it — #2606, #2301, #2338, #2167, #2120, #2064, #2563) all share one root cause: rtk grep patches GNU-grep-shaped input token-by-token, so each flag that collides between GNU grep and ripgrep is a separate silent-wrong-results special case. The collisions are semantic, not cosmetic — -E means ERE to GNU grep but --encoding (value-taking) to ripgrep; -h is --no-filename to grep but --help to rg — so a token-level patch can't be complete, and new collisions keep surfacing as new issues.

    I opened #2635 as a "fix the class" alternative to the per-flag patches in flight (#2254 -E, #2532 -h, #2460/#2505 rg→rtk rg, #2434, #2628, #2607, #2544, #2138): parse GNU-grep args once into a neutral typed GrepInvocation IR, then render that struct per backend. After it, nothing reaches rg unexamined — every flag is a typed field with a deliberate rendering rule, and genuine divergences (BRE/ERE, build-optional PCRE2) get an explicit policy instead of a silent mis-route. It absorbs the -E and -h point-fixes into the layer.

    Posting here since #2614 is the clearest headline for the class (the 4,416 parse-failures/90d framing). Happy to coordinate with the per-flag PR authors on whether the IR is the direction to take or whether the incremental patches are preferred — just flagging that the underlying defect is one thing, not N.

  8. heyjello commented on Jul 2, 2026

    @heyjello

    Corroboration + still reproduces on the released 0.43.0 bottle (Homebrew, macOS arm64, via rtk hook claude). The "largely resolved on develop" read above doesn't hold for the shipped binary — and there's a regression vs 0.38.0. All verified just now against a real repo (258 git-tracked files):

    1. Bare directory search now fails (regression from 0.38.0):

    $ rtk grep ToolMetrics src
    grep: src: Is a directory        # exit 2, raw fallback, 0 saved
    

    On 0.38.0 this auto-recursed (ripgrep default) and filtered fine. On 0.43.0 it only recurses with an explicit -r.

    2. Leading value-less flags still fall back:

    $ rtk grep -i toolmetrics src    # exit 2, grep: src: Is a directory
    $ rtk grep -A3 ToolMetrics src   # exit 2, same
    

    Trailing position doesn't save it either (grep ToolMetrics src -i → same exit 2).

    3. grep -rn no longer crashes (0.38.0 Abort-trapped) — but now ignores .gitignore:

    $ rtk grep -rn tool .
    31157 matches in 2613 files    # ripgrep on the same tree: ~112 files
    

    It descends .git/, graphify-out/, etc. → token expansion, not savings (cf. #2064).

    4. Path-less form hangs:

    $ rtk grep toolmetrics -i      # blocks on stdin ~2 min until killed
    

    Net: the crash and the -r rejection are fixed, but directory search regressed and .gitignore/stdin handling are unresolved on 0.43.0. Workaround that fully works: rtk proxy rg <pattern> <path> [flags] (bypasses the grep/rg→rtk grep rewrite, real ripgrep, still tracks savings).

    rtk 0.43.0 (brew bottle), Claude Code, macOS 15 arm64

  9. RichelynScott commented on Jul 21, 2026

    @RichelynScott

    Independent corroboration — different fleet, different 5-week window, same dominant failure mode.

    Sample: 11,932 tracked commands, rtk 0.42.2, Linux/WSL2, Claude Code Bash hook, 15+ projects.

    2,142 total parse failures. 1,970 of them (92%) are grep. Fallback succeeded 100% of the time — so, exactly as you describe, they read as success while saving nothing.

    Command Parse failures
    grep 1,970
    du 66
    docker 42
    ps 36
    df 11
    diff 8
    git 5
    uv 4

    Representative rejected invocations from the last few days, all fallback_succeeded=1:

    grep -nE '^\- \*\*Version\*\*: `0.7.85`' SKILL.md
    grep -rn _load_mcp_config --include=*.py .
    grep -nc except (ValueError, RecursionError) <file>.py
    grep -n -A6 '^mcp\s*=\|"mcp"' pyproject.toml
    grep -c REEXTRACT <path>/build_p...
    

    The rewrite happens unconditionally

    The hook rewrites regardless of whether the flags will parse, so the failure is guaranteed downstream rather than avoided:

    $ printf '%s' '{"tool_name":"Bash","tool_input":{"command":"grep -rn foo --include=*.py ."}}' | rtk hook claude
    {"hookSpecificOutput":{ ... "updatedInput":{"command":"rtk grep -rn foo --include=*.py ."}, "permissionDecision":"allow"}}

    rtk grep then rejects -r as an unexpected argument and falls back to raw.

    Worth noting src/cmds/system/grep_cmd.rs already handles both -r (skipped, since rg is recursive by default) and format-flag passthrough (has_format_flag) — the logic exists, it just never runs because clap rejects the argv before extra_args is populated. The flags arrive before the pattern/path positionals, so trailing_var_arg never collects them.

    There's also a latent collision to resolve in any fix: rtk grep -l is currently bound to max_len, whereas GNU grep -l means --files-with-matches.

    Interim mitigation for anyone blocked: adding grep to [hooks] exclude_commands in ~/.config/rtk/config.toml stops the pointless rewrite (you lose filtering on the simple greps that do work, but you also stop paying the parse-failure round trip).

    Given grep is the single highest-frequency command in the proxy here (1,114 successful + 1,970 failed), flag coverage looks like the highest-leverage fix available.

  10. Yohjisakamoto commented on Jul 22, 2026

    @Yohjisakamoto

    This silent raw fallback and zero-savings case reinforces why end-to-end agent outcomes matter more than compressed text alone: DeepSWE found Tura cuts coding-agent rounds by 89% and total token cost by 80%; would you evaluate the methodology? https://turaai.net/docs#benchmark-current-test-set-record

  11. agus-wark0p commented on Jul 25, 2026

    @agus-wark0p

    Independent confirmation, different project, same rtk version (0.42.4).

    Diagnosed via ~/.local/share/rtk/history.db's parse_failures table (fallback_succeeded=1 on all rows — silent, no visible error):

    Flag rejected Failures
    -r 1753
    -A 480
    -E 273
    -i 156
    -c 90
    -o 77
    -B 67

    3388 total grep parse failures out of ~18.7k hook-processed commands over the same window — same shape as OP's numbers (dominated by bare -r), just a different project. rtk discover's adoption-rate report doesn't account for these fallbacks either, so it under-reports the gap: it reads the assistant's original command text, not the hook's fallback outcome, so a silently-failed rewrite looks identical to "never tried RTK."

    +1 on the ask — matching standard grep flags (-r/-R, -E, -A/-B/-C, -i, -o, -q) would fix the dominant real-world grep shape, not an edge case.

  12. KuSh commented on Sep 5, 2026

    @KuSh
    Collaborator

    Closing as a duplicate of #880, which tracks the same problem and is now fixed (PR #2333). Please comment on #880 or open a new issue with a fresh reproduction if you still see this on the latest version.

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:clibughelp wantedpriority:high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions