Repository navigation
Description
Symptom
Common `grep` invocations bypass `contextcrawler`'s filter entirely and run raw via the fallback path. Tracking DB confirms the path:
```
$ sqlite3 ~/Library/Application\ Support/rtk/history.db \
"SELECT raw_command, substr(error_message,1,80) FROM parse_failures WHERE raw_command LIKE '%grep%' ORDER BY timestamp DESC LIMIT 10;"
grep -r needle . | error: unexpected argument '-r' found
grep -rn needle . | error: unexpected argument '-r' found
grep -nr needle . | error: unexpected argument '-r' found
grep -Rn needle . | error: unexpected argument '-R' found
grep --recursive needle . | error: unexpected argument '--recursive' found
grep -A3 -i pat file | error: unexpected argument '-A' found
grep -n -A 3 pat file | error: unexpected argument '-A' found
```
All seven fall through `run_fallback` (`src/main.rs:1255`), exec raw grep, record `saved_tokens=0`. On the live `contextcrawler gain` dashboard this currently shows as:
```
9. grep 262 50.1K 13.2% 8ms
05-19 21:57 • fallback: grep -rn too… -0% (0)
```
i.e. most grep calls hit the fallback. The 13.2% headline savings on grep is mostly noise from the small minority that happened to pattern-match clap's positionals.
Root cause
`Commands::Grep` at `src/main.rs:320` declares:
```rust
Grep {
pattern: String, // positional
path: String, // positional (default ".")
#[arg(short = 'l', long, default_value = "80")] max_len: usize,
#[arg(short, long, default_value = "200")] max: usize, // -m
#[arg(short = 't', long)] file_type: Option,
#[arg(short = 'n', long)] line_numbers: bool,
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
extra_args: Vec,
}
```
clap parses left-to-right. `contextcrawler grep -r needle .` → first token is `-r` → unknown flag → `ErrorKind::UnknownArgument`. `trailing_var_arg + allow_hyphen_values` on `extra_args` doesn't apply until clap has consumed both leading positionals (`pattern`, `path`). The clap-suggested workaround is `contextcrawler grep -- -r needle .`, which is unusable when the wrapper is invoked transparently by the auto-rewrite hook.
The runtime filter at `src/cmds/system/grep_cmd.rs:60` does strip bare `-r`/`--recursive` from `extra_args` — but that code never runs because clap fails before dispatch.
Impact
- Zero savings on the most common grep path. Tracking DB shows 13.2% average grep savings; without the fallback population the rest of the grep calls would average ~75%. Headline savings on the gain dashboard understated.
- Discover false-negatives compound — see discover: MISSED SAVINGS is structurally misleading — reads pre-hook command #82. A grep that fell back is invisible to the reconciler.
- Security blind spot. `check_forbidden_rg_args` (issue SECURITY [P1]:
RIPGREP_CONFIG_PATHenv var + rg--preenables silent arbitrary-code-execution via everycontextcrawler grepcall #32) lives in the runtime filter path. Fallback calls bypass it. `grep --pre-glob ./evil` would not be rejected. Worth verifying.
Proposed fix
Two-pass pre-clap stripper, just before `Cli::try_parse()` in `run_cli()` at `src/main.rs:~1880` (next to the existing `grep_format_flag_present` intercept).
Pass 1 — silently strip recursive flags
rg is recursive by default; these tokens are noise.
```rust
fn strip_recursive_flags(args: &mut Vec) {
args.retain_mut(|arg| {
if arg == "-r" || arg == "-R" || arg == "--recursive" {
return false;
}
// Single-dash bundle: drop r/R chars, keep the rest
if arg.starts_with('-') && !arg.starts_with("--") && arg.len() > 1
&& arg[1..].chars().all(|c| c.is_ascii_alphabetic())
{
let kept: String = arg[1..].chars().filter(|c| *c != 'r' && *c != 'R').collect();
if kept.is_empty() {
return false; // arg was "-r", "-R", "-rR" etc.
}
*arg = format!("-{}", kept);
}
true
});
}
```
Examples:
| In | Out |
|---|---|
| `-r` | dropped |
| `-R` | dropped |
| `--recursive` | dropped |
| `-rn` | `-n` |
| `-nr` | `-n` |
| `-Rn` | `-n` |
| `-rin` | `-in` |
| `-iA3` | unchanged (contains digit, not all alphabetic) |
Pass 2 — route context-flag invocations to rg-passthrough
`-A`/`-B`/`-C` (and `-A`, `--after-context` etc.) need to reach rg with their argument. Send the whole call through the existing `run_grep_format_passthrough` (already shells out to rg, already records tracking).
Extend `grep_format_flag_present` to also match:
- short letters: `A`, `B`, `C` (any single-`-` bundle that contains one of these and is followed by digits/separator)
- long forms: `--after-context`, `--before-context`, `--context`
```rust
const CONTEXT_LONG: &[&str] = &[
"--after-context", "--before-context", "--context",
];
const CONTEXT_SHORT_LETTERS: &[char] = &['A', 'B', 'C'];
```
Anything matching either set → route via `run_grep_format_passthrough`.
Acceptance
- Unit test: every entry in the symptom table above results in either a successful `rtk grep` filtered output (after Pass 1) or an `rg`-passthrough with tracking row, never a `run_fallback`.
- `parse_failures` table no longer accumulates `grep` rows for these flag combinations.
- `contextcrawler gain`: grep average savings rises from ~13% to expected ~75%.
- Security: `check_forbidden_rg_args` runs on the passthrough path too (it already does — `run_grep_format_passthrough` calls it at line 1685).
Related
- discover: MISSED SAVINGS is structurally misleading — reads pre-hook command #82 — discover MISSED SAVINGS is structurally misleading; every fallback grep is also invisible to its reconciler.
- SECURITY [P1]:
RIPGREP_CONFIG_PATHenv var + rg--preenables silent arbitrary-code-execution via everycontextcrawler grepcall #32 — forbidden rg args (`--pre`, `--pre-glob`, `-z`); verify those are still blocked on the new strip path.
Activity
merge: D grep-clap (#88)
fix(grep): pre-clap stripper for -r/-R/--recursive + passthrough for …
fix(cli): close pre-clap intercept gaps for meta flags and grep