Repository navigation
feat(read): --intent for surgical lexical extraction on large files (#157) - #163
Merged
Merged
Conversation
…157) The read filter is the #4 absolute leaker per the v0.1.10 audit (1838 runs, 2.5M leaked, 87.3% saved). The existing symmetric head/tail cap works for medium files but degrades on large files where the relevant content sits in the middle. Add `contextcrawler read <file> --intent "<terms>"`. When provided AND the file is > 5KB AND the splitter finds ≥ 3 sections AND at least one section scores above zero, the output becomes: <metadata banner> <head bookend> (omitted on files < 60 lines, byte-capped at 1KB) <top-scoring sections, in original document order> <omission count> <tail bookend> (same gating as head) Otherwise falls through to the existing render path — no regression on small files, no regression when intent omitted. Section splitters covered in v1: - Markdown (.md, .markdown) split on heading lines, skip fenced code - Rust (Language::Rust) top-level item starts (fn, impl, struct, enum, trait, mod, type, const, static), with vis/async/unsafe handled - TOML / Cargo.lock split on lines starting with [ - Unknown paragraph split on blank-line runs Scoring is lexical: per-term occurrence count in body plus heading hits weighted 5×. Stopword list is short and conservative; tokenisation is case-insensitive, alphanumeric + underscore only. No stemming, no LLM — preserves the zero-async, fast-startup posture. Live result on Cargo.lock (this repo, 2316-line / 14K-token file): contextcrawler read Cargo.lock → 0% saved contextcrawler read Cargo.lock --intent "rusqlite chrono" → 96.1% saved Tests added (13 new, total 2681 / 2681 pass): - tokenize_drops_stopwords_and_lowercases - tokenize_handles_punctuation - tokenize_only_stopwords_yields_empty - markdown_splitter_finds_sections - markdown_splitter_ignores_headings_in_fenced_code - rust_splitter_handles_visibility_and_qualifiers - rust_splitter_does_not_split_inner_fns - toml_splitter_array_of_tables - extract_returns_none_for_small_input - extract_returns_none_when_no_section_matches - extract_keeps_matching_section_and_drops_others - extract_preserves_head_and_tail_bookends - extract_achieves_meaningful_reduction Closes #157. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Round-1 peer-review hardening on PR #157. 1. take_capped multibyte UTF-8 safety: Previous version used `line.chars().take(N)` for the truncation prefix when a single line exceeded the byte cap — char count, not byte count, with a `.collect::<String>()` that would happily slice N characters of any width. Safe in this codepath (chars().take is codepoint-aware), but the rationale was muddled and the cap claim was wrong. Replaced with a `char_indices()` walk that finds the largest valid UTF-8 byte prefix at or below (cap - marker.len()) — explicit byte discipline, marker length budget reserved, output guaranteed String-valid. Added two tests: - take_capped_does_not_panic_on_multibyte_overflow (100 emoji, cap=50, must produce the marker without panicking) - take_capped_emits_nothing_when_cap_is_tiny (cap < marker.len) 2. Cargo.lock fixture-backed savings benchmark: The 96.1% live-demo number was unsubstantiated by the test suite; the prior savings assertion ran against a synthetic 5-section markdown fixture. Added extract_on_real_cargo_lock_meets_savings_target which include_str!'s the repo's actual Cargo.lock and asserts ≥80% savings on intent="rusqlite chrono", plus content sanity (the requested terms must actually appear in the output). 80% is the defensible floor; the headline 96.1% is what we see on this specific dependency set today. Verification: 2684/2684 pass (+3 from this commit). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
thehoff
force-pushed
the
feat/read-intent-157
branch
from
May 24, 2026 06:15
6a4b5f3 to
404e7d6
Compare
Round-1 verdict was YELLOW with 2 CONCERNs and 3 MINORs. Closing all
substantive items.
CONCERN Q6: KEEP_TARGET_RATIO premature-stop
When one chunky section pushed past target_bytes, the loop exited
immediately, silently dropping equally-relevant sibling sections at
the same score. Fixed: once target is reached, continue iterating
while the next section's score TIES the last-included one; break on
the first strictly-lower score. Equal-relevance sections now stay
together; non-matching sections still excluded.
Pinned by new test `extract_keeps_tied_scoring_sections_past_target`
— constructs two equally-scoring large sections where the first alone
exceeds target, asserts both are kept and the lower-scoring third is
not.
CONCERN Q8: Cargo.lock fixture brittleness
Previous savings test included `../../../Cargo.lock` directly. Adding
or removing any dep on develop shifts the baseline token count and
the matched section set, causing spurious test failures unrelated to
filter logic. Fixed: snapshot the current Cargo.lock to
`tests/fixtures/cargo_lock_sample.txt` (2316-line static fixture)
and have the test reference that. Test renamed to
`extract_on_pinned_cargo_lock_meets_savings_target` to reflect.
MINOR Q4a: take_capped overflow off-by-one
The check `out.len() + line.len() + 1 > max_bytes` always added +1
for a separator newline even on the first line where no newline is
emitted. An exactly-fitting first line was falsely treated as
overflow. Fixed: `separator_cost = if out.is_empty() { 0 } else { 1 }`.
MINOR Q4b: take_capped marker-alone over-emit
When cap < TRUNCATION_MARKER.len(), the function emitted the bare
marker — exceeding the nominal cap. Honour the cap strictly: return
empty rather than over-emit. Test
`take_capped_emits_nothing_when_cap_is_tiny` updated from old
(incorrect) assertion to the new correct behaviour.
DEFERRED (not addressed):
- Q5 score_section allocation churn — Codex agreed acceptable in
practice given the 5KB activation gate.
- Q7 stopword list — Codex agreed `use` should stay off the list
(legitimate technical token), other additions are low-priority.
Peer-review status:
- Codex: YELLOW round-1 → addressed here
- agy: timed out / hung at ~24min (zero output buffered). Multi-model
gate degraded to Codex-only for this PR. Acknowledged gap; will
retry agy with tighter scope (no --add-dir, inline diff) on a
follow-up round if needed.
Verification: 2692/2692 pass (17/17 intent tests including the new
tie-handling regression guard).
Round-2 peer-review by agy returned YELLOW with one new actionable
concern: take_capped's truncation marker was only emitted on the
first-line overflow path. When truncation happened at a later-line
boundary (out non-empty, next line would overflow), the function
silently broke out of the loop — caller saw clean output and had no
indication that subsequent lines were dropped.
This is an output-integrity issue worth fixing on its own merits:
silent truncation makes the bookend display lie to the reader.
Fix:
- Add a `truncated: bool` flag inside the loop.
- Set it true when overflow occurs at any boundary other than the
first-line-with-room-for-marker case (which writes the marker
inline anyway).
- After the loop, if truncated AND remaining budget can fit
"\n" + TRUNCATION_MARKER, append it. Never push past the cap —
if budget is too tight, omit silently (matches existing first-
line-too-small-for-marker behaviour, which is the only case
where silent truncation is unavoidable).
Pinned by two new tests:
- take_capped_marks_late_truncation_when_budget_allows
(60-byte cap, 4 × 20-byte lines, expects 2 lines + "\n" + marker)
- take_capped_omits_late_marker_when_budget_too_tight
(41-byte cap, expects exactly 2 lines with marker silently dropped)
Round-2 agy also expressed preference for a hand-crafted synthetic
fixture over the live-Cargo.lock snapshot. Deferring — the snapshot
approach is defensible (Codex agreed in Q8 follow-up) and a synthetic
rewrite is bigger than the YELLOW warranted. File as separate polish
issue if it bothers anyone.
Verification: 2694 / 2694 pass.
Round-2 status:
Codex round-1 → YELLOW with 2 CONCERNs + 3 MINORs → all addressed
in b53e744 (round-2 commit, not yet re-reviewed)
agy round-2 → YELLOW with 1 concern (this fix) + 1 preference
(deferred to follow-up) → ALL addressed here
noogalabs
pushed a commit
to noogalabs/contextcrawler
that referenced
this pull request
Jun 4, 2026
* fix: P1 exit codes, grep regex perf, SQLite WAL (rtk-ai#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> * fix: raise output caps for P0 bugs (rtk-ai#617, rtk-ai#618, rtk-ai#620) (rtk-ai#630) * fix: raise output caps for grep, git status, and parser fallback (rtk-ai#617, rtk-ai#618, rtk-ai#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 rtk-ai#617, rtk-ai#618, rtk-ai#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> * feat(.claude): add /rtk-triage skill — cross-analysis of PRs and issues (rtk-ai#662) * feat(.claude): add /rtk-triage skill — orchestrated PR+issue cross-analysis New skill that runs issue-triage + pr-triage in parallel then produces a cross-analysis layer that neither skill can do individually: - Double coverage detection: identifies when 2+ PRs target the same issue (via body scan + file overlap), recommends which to keep/close - Security gap detection: for security review issues, maps each finding to a PR (or flags it as uncovered) - P0/P1 bugs without PR: groups by pattern to suggest sprint batching - Our dirty PRs: identifies probable cause (conflict with sibling PR, needs rebase, missing linked issue) Output is saved automatically to claudedocs/RTK-YYYY-MM-DD.md. Usage: /rtk-triage (French, auto-save) /rtk-triage en (English output) Signed-off-by: Florian Bruniaux <florian@bel-etage.com> Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com> * docs(architecture): update module count to 66 Sync ARCHITECTURE.md with current main.rs state. Previous count (60) was stale since several modules were added (dotnet_cmd, dotnet_format_report, dotnet_trx, npm_cmd, gt_cmd, etc.). Signed-off-by: Florian Bruniaux <florian@bel-etage.com> Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com> --------- Signed-off-by: Florian Bruniaux <florian@bel-etage.com> Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com> * fix: subcommand routing drops unrecognized subcommands (rtk-ai#600) (rtk-ai#601) - git stash: pass unknown subcommands (save, branch, clear) through instead of silently falling back to git stash push - git branch: add --show-current, --set-upstream-to, --format, --sort to flag detection so they don't get overridden by -a injection - pip: replace bail!() with passthrough for unknown subcommands (freeze, download, wheel, etc.) Fixes rtk-ai#600 Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: resolve cargo fmt + 54 clippy warnings blocking CI (rtk-ai#663) cargo fmt diffs in config.rs, git.rs, playwright_cmd.rs were failing the fmt CI check, which cascaded to block clippy/test/security on PRs rtk-ai#632, rtk-ai#635, rtk-ai#638. Also fixes all clippy warnings: dead code annotations, iterator simplifications, assert patterns, and unnecessary allocations. Signed-off-by: Patrick Szymkowiak <patrick@rtk-ai.app> Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: discover absolute paths + git global options (rtk-ai#485, thehoff#163) (rtk-ai#518) * fix: discover classifies absolute paths like /usr/bin/grep (rtk-ai#485) Normalize absolute binary paths before classification: /usr/bin/grep → grep, /bin/ls → ls, /usr/local/bin/git → git Adds strip_absolute_path() helper + 5 tests. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: discover and rewrite support git global options -C, --no-pager, etc. (thehoff#163) Strip git global options (-C <path>, -c <key=val>, --git-dir, --work-tree, --no-pager, --no-optional-locks, --bare, --literal-pathspecs) before classification so git -C /tmp status is recognized as rtk git. Rewrite preserves global options: git -C /tmp status → rtk git -C /tmp status Adds GIT_GLOBAL_OPT lazy_static regex + strip_git_global_opts() helper + 6 tests. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> --------- Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: prevent double `--` separator in cargo clippy with -p flags (rtk-ai#519) When running `rtk cargo clippy -p my-crate -- -D warnings`, Clap with `trailing_var_arg = true` preserves the `--` in parsed args when flags precede it. `restore_double_dash()` then added a second `--`, producing `cargo clippy -p my-crate -- -- -D warnings`. This caused rustc to interpret `-D` as a filename instead of a lint flag. Fix: skip restoration when args already contain `--` (Clap preserved it). Fixes rtk-ai#496 Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * ci: add PR template + target branch check (rtk-ai#521) - PR template reminds contributors to target develop - CI workflow labels PRs targeting master with 'wrong-base' and posts a comment - Excludes develop→master PRs (maintainer releases) Signed-off-by: Patrick <patrick@rtk-ai.com> Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: prevent rtk read from corrupting JSON/YAML/data files (rtk-ai#522) Add Language::Data variant for data formats (JSON, YAML, TOML, XML, CSV, etc.) with empty comment patterns to prevent comment stripping. AggressiveFilter falls back to MinimalFilter for data files. Fixes rtk-ai#464 Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix: skip rewriting find/fd in pipes to preserve xargs compatibility (rtk-ai#439) (rtk-ai#563) rtk find outputs a grouped format incompatible with pipe consumers like xargs, grep, wc, sort. Skip rewrite when find/fd is followed by a pipe, preserving native one-per-line output. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: add hint when git diff is truncated + fix --no-compact passthrough (rtk-ai#427) (rtk-ai#564) When compact_diff truncates output, append a hint line so Claude knows how to get the full diff: [full diff: rtk git diff --no-compact] Also fix --no-compact flag being passed to git (causing usage error) and remove decorative emoji from compact_diff output. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: propagate exit codes in git diff, status+args, commit, and branch (rtk-ai#632) 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> * feat: add 5 new TOML filters (ollama, nx, gradle, spring-boot, jira) (rtk-ai#635) * feat: add 5 new TOML built-in filters (ollama, nx, gradle, spring-boot, jira) New filters for commands not covered by Rust modules: - ollama: strip ANSI spinners, keep final text response (rtk-ai#624) - nx: strip Nx monorepo noise, keep build results (rtk-ai#444) - gradle/gradlew: strip UP-TO-DATE tasks, keep build summary (thehoff#147) - spring-boot: strip banner and verbose logs, keep startup/errors (thehoff#147) - jira: strip blanks, truncate wide columns (rtk-ai#524) All 5 filters pass inline tests via rtk verify (123/123). Updated builtin filter count: 47 -> 52. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * feat: add 5 more TOML filters (turbo, mise, just, task, yadm) New filters for task runners and git wrapper: - turbo: strip cache/Tasks/Duration noise, keep task output (rtk-ai#531) - mise: strip install/download progress, keep task results (rtk-ai#607) - just: strip blanks and recipe headers, keep output (rtk-ai#607) - task: strip task headers and up-to-date lines, keep results (rtk-ai#607) - yadm: strip hint lines, compact git-like output (rtk-ai#567) All verified with fake binaries through catch-all TOML engine. 137/137 TOML tests pass, 934 Rust tests pass. Updated builtin filter count: 52 -> 57. Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> --------- Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu> * fix: replace emojis with plain text in git status output (rtk-ai#603) (rtk-ai#638) Git status output used emojis (📌, 📝, ❓, ✅,⚠️ ) that confuse non-Claude LLMs (GPT, etc.) causing retry loops. Replace with plain text labels (branch:, modified:, staged:, untracked:, conflicts:). Also add "clean — nothing to commit" when working tree is clean, so LLMs understand the repo state without ambiguity. Before: 📌 master After: branch: master clean — nothing to commit Fixes rtk-ai#603 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> Signed-off-by: Florian Bruniaux <florian@bel-etage.com> Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com> Signed-off-by: Patrick Szymkowiak <patrick@rtk-ai.app> Signed-off-by: Ousama Ben Younes <benyounes.ousama@gmail.com> Signed-off-by: Patrick <patrick@rtk-ai.com> Co-authored-by: Florian BRUNIAUX <florian@bruniaux.com> Co-authored-by: Ben Younes <benyounes.ousama@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Closes #157. Adds
contextcrawler read <file> --intent "<terms>"for surgical lexical extraction on large files.When
--intentis provided AND file > 5 KB AND the splitter finds ≥ 3 sections AND at least one section scores above zero, the output becomes:Otherwise falls through to the existing render path — no regression on small files, no regression when intent omitted.
Why
readranks #4 by absolute leaked tokens per the v0.1.10 audit (1838 runs, 2.5M leaked, 87.3% saved). The current symmetric head/tail cap works for medium files but degrades on large files where the relevant content sits in the middle.How
Section splitters covered in v1:
.md,.markdown) — heading lines, skips fenced code blocksLanguage::Rust) — top-level item starts (fn, impl, struct, enum, trait, mod, type, const, static), with vis/async/unsafe qualifiers handled.toml,.lock) — lines starting with[Scoring is lexical: per-term occurrence count in body plus heading hits weighted 5×. Tokenisation is case-insensitive, alphanumeric + underscore only. Stopwords dropped. No stemming, no LLM — preserves the zero-async, fast-startup posture.
Live result
From 2316 lines to 114 lines, with the matching
rusqliteandchronodependency sections preserved verbatim.Tests
16 new (3 commits, 2691/2691 pass total):
tokenize_drops_stopwords_and_lowercasestokenize_handles_punctuationtokenize_only_stopwords_yields_emptymarkdown_splitter_finds_sectionsmarkdown_splitter_ignores_headings_in_fenced_coderust_splitter_handles_visibility_and_qualifiersrust_splitter_does_not_split_inner_fnstoml_splitter_array_of_tablesextract_returns_none_for_small_inputextract_returns_none_when_no_section_matchesextract_keeps_matching_section_and_drops_othersextract_preserves_head_and_tail_bookendsextract_achieves_meaningful_reductionextract_on_real_cargo_lock_meets_savings_target— fixture-backed Cargo.lock benchmark, asserts ≥ 80% savings on intent="rusqlite chrono" plus content sanity (matched terms must appear in output)take_capped_does_not_panic_on_multibyte_overflow— UTF-8 byte safety, 100 emoji at cap=50take_capped_emits_nothing_when_cap_is_tiny— cap < marker.len edge caseCommits
dd3eb274eae7586a4b5f3Risk
--intentis omitted.extract_for_intentreturnsNonefor too-small / no-match / unsupported-format inputs, caller drops to existing render path.