New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

crg-rg

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

crg-rg

Source
crates.io
Version
0.1.0
Version published
Maintainers
1
Created
Source

crg (Compressed Ripgrep) - deterministic compressed ripgrep for coding agents

crg turns large ripgrep result sets into compact, ranked evidence for coding agents and developers. It runs the real rg, keeps every match exact, selects the most useful and varied results, adds validated source context, and emits text or JSON within a hard output budget.

It does not use an LLM, embeddings, telemetry, a remote API, or runtime network access. It does not rewrite source text or invent a summary.

Why use it

A normal repository search can return hundreds of repeated imports, generated files, test copies, and ordinary call sites. Sending all of that to a coding agent wastes context and can hide the definition or error path that matters.

crg keeps the search exact while reducing the result set. Every output states how many match records and matching files were retained, so the loss is always visible.

COMPRESSED SEARCH RESULT
INCOMPLETE: representative evidence only.
Retained 8 of 146 match records from 5 of 31 matching files.

General flow

flowchart LR
    U[Developer or coding agent] --> E[crg command or transparent rg wrapper]
    E --> R[Real ripgrep executable]
    R --> X[Exact ripgrep JSON events]
    X --> C[Local ranking and compression]
    C --> O[Budgeted text or JSON]
    O --> U
    X -. reversible mode .-> S[Private local cache]
    S --> Q[Filter or rerank without running ripgrep]
    Q --> O

How it works

  • CRG invokes ripgrep directly without a shell and requests its JSON event stream.
  • Each ripgrep match event becomes one immutable candidate. Paths, source lines, offsets, and submatch bytes remain attached to that candidate.
  • Task words, pattern literals, file names, definitions, error paths, test paths, generated paths, and boundary locations contribute bounded ranking signals.
  • Exact and near duplicates are grouped without destroying their original locations.
  • A diverse selector chooses evidence across ranked files while respecting file limits, match limits, and the requested byte, line, or approximate token budget.
  • Source context is read only for selected candidates. If a file changed or cannot be read, CRG displays the exact ripgrep match with an explicit marker.
  • The final serializer checks the complete text or JSON size. It removes extra context and lower value evidence until the hard budget is satisfied.

The selected unit is always a ripgrep JSON match record. Ripgrep submatch counts are tracked separately.

Internal architecture

flowchart TB
    CLI[crg cli<br/>arguments, errors, stdout] --> RG[crg rg<br/>process and JSON parser]
    RG --> RAW[Exact RawMatch records]
    RAW --> CMP[crg compress<br/>features, scores, duplicates, selection]
    MODEL[crg model<br/>configuration and immutable contracts] --> CMP
    CMP --> CTX[crg context<br/>selected source validation]
    CTX --> RENDER[crg render<br/>text, JSON, final budget]
    RENDER --> CLI
    RG -. exact spool .-> STORE[crg store<br/>Zstandard cache and retention]
    STORE -. local retrieval .-> RAW

The crate boundaries prevent retrieval from rerunning ripgrep and prevent the compression code from executing source files or writing search output directly.

Install

Requirements:

  • Rust 1.85 or newer
  • ripgrep available as rg for new searches

Build and install from this repository:

cargo install --path crates/crg-cli --locked
crg --version
crg doctor

For a local release build:

cargo build --release -p crg-cli
./target/release/crg doctor

Quick start

CRG options come before --. Everything after -- is passed to ripgrep.

Find the most relevant implementation

crg \
  --task "find access token validation" \
  --budget-tokens 1800 \
  -- \
  -n -i 'validate|verify|token' src tests

Inspect an error path with a line budget

crg \
  --task "trace timeout retry and fallback behavior" \
  --budget-lines 80 \
  --context-lines 3 \
  -- \
  -n 'timeout|retry|fallback' crates

Search exact text and limit each file

crg \
  --max-files 10 \
  --matches-per-file 3 \
  -- \
  --fixed-strings 'permission denied' .
crg \
  --task "find tests for expired sessions" \
  --budget-tokens 1200 \
  -- \
  -n -i 'expired|session' tests src

Produce JSON for an agent or script

crg \
  --format json \
  --task "find cache cleanup behavior" \
  --budget-bytes 12000 \
  -- \
  -n 'cache|retention|clean' crates

JSON stdout contains exactly one versioned document and a trailing newline. Diagnostics remain on stderr. See the JSON schema.

Inspect ranking details

crg \
  --show-scores \
  --show-statistics \
  --task "find authorization failures" \
  -- \
  -n 'unauthorized|forbidden|access' src

Save a search for local retrieval

crg \
  --reversible \
  --cache-dir .crg-cache \
  --task "find validation fallback" \
  -- \
  -n 'validate|fallback' src

The output includes a retrieval ID. Use it without running ripgrep again:

crg retrieve <ID> --cache-dir .crg-cache
crg retrieve <ID> --cache-dir .crg-cache --file 'src/**'
crg retrieve <ID> --cache-dir .crg-cache --query 'timeout handling'
crg retrieve <ID> --cache-dir .crg-cache --lines 40:120
crg retrieve <ID> --cache-dir .crg-cache --all
crg retrieve <ID> --cache-dir .crg-cache --format raw

--format raw emits the byte identical original ripgrep JSONL stream. Retrieval works even when rg is absent from PATH.

Manage stored entries with:

crg cache list --cache-dir .crg-cache
crg cache clean --cache-dir .crg-cache --older-than 7d
crg cache clean --cache-dir .crg-cache --max-size 2GB

Agent instructions

Coding agents use CRG most effectively when their repository instructions explain both the command shape and the incomplete nature of compressed output. Add the following block to the target repository's AGENTS.md or CLAUDE.md:

## Repository search

Use CRG for content searches that may return a large result set:

`crg --task "describe the investigation" --budget-tokens 2000 -- -n "pattern" .`

Put CRG options before `--` and ripgrep arguments after it. Describe the goal
with `--task`, not only the literal pattern. Treat CRG output as representative
evidence, not proof that omitted matches do not exist. Refine the query or
increase the budget when needed. Use real ripgrep for exhaustive absence checks
and unsupported modes such as file listing, counts, replacement, quiet, or
passthrough output. Request `--format json` when output will be parsed.

This repository includes complete examples for agents that read AGENTS.md and CLAUDE.md.

Agent search examples

Find an implementation together with its tests:

crg \
  --task "find access token validation implementation and tests" \
  --budget-tokens 1800 \
  -- \
  -n -i 'validate|verify|token' src tests

Trace a failure path while retaining more nearby source:

crg \
  --task "trace timeout retry and fallback behavior" \
  --context-lines 4 \
  --budget-lines 100 \
  -- \
  -n 'timeout|retry|fallback' .

Return structured evidence for the next agent step:

crg \
  --format json \
  --task "find configuration precedence and validation" \
  --budget-bytes 12000 \
  -- \
  -n 'config|precedence|unknown field' crates tests

When an agent must prove that no match exists, bypass compression and run the real ripgrep executable. This also applies to unsupported commands such as rg --files and rg --count.

Use CRG transparently as rg

CRG can sit behind the familiar rg command. This is useful when an LLM or coding tool already knows how to call ripgrep but does not know about CRG.

The forwarding rule is simple:

rg PATTERN PATH
        becomes
crg --rg-path REAL_RG -- PATTERN PATH

Pinning the real ripgrep path is essential. Without --rg-path, a wrapper named rg could make CRG discover the wrapper and call itself recursively.

Interactive zsh alias

First find the real executable before creating the alias:

command -v rg

Then add an alias using that absolute path. Replace the example path when needed:

alias rg='crg --rg-path /opt/homebrew/bin/rg --'

Persist it in ~/.zshrc. Set REAL_RG to the absolute path reported before the alias existed:

REAL_RG=/opt/homebrew/bin/rg
echo "alias rg='crg --rg-path $REAL_RG --'" >> ~/.zshrc
source ~/.zshrc

After that, an ordinary call produces compressed output:

rg 'validate_token' src

Shell aliases usually exist only in interactive shells. Many coding agents run commands without loading ~/.zshrc, so an alias alone may not affect their tool calls.

PATH wrapper for coding agents

A wrapper executable works for tools that resolve rg through PATH. Capture the real path before placing the wrapper first in PATH. In zsh, whence -p ignores aliases and prints the executable path:

REAL_RG="$(whence -p rg)"
mkdir -p "$HOME/.local/bin" "$HOME/.local/libexec/crg"
ln -sf "$REAL_RG" "$HOME/.local/libexec/crg/rg_real"
printf '%s\n' \
  '#!/bin/sh' \
  'exec crg --rg-path "$HOME/.local/libexec/crg/rg_real" -- "$@"' \
  > "$HOME/.local/bin/rg"
chmod 0755 "$HOME/.local/bin/rg"
export PATH="$HOME/.local/bin:$PATH"

Persist the PATH order for zsh:

echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc

Verify both layers:

"$HOME/.local/libexec/crg/rg_real" --version
rg 'needle' src

An agent can now issue its normal rg PATTERN PATH command and receive CRG output without changing its prompt or tool definition. Repository defaults can be placed in .crg.toml, which lets transparent calls inherit budgets and selection limits without adding CRG options.

This mode is intended for normal match searches. CRG rejects ripgrep modes that do not produce the match stream it compresses, including rg --files, count, replacement, quiet, and passthrough modes. Call the pinned real executable for those operations:

"$HOME/.local/libexec/crg/rg_real" --files

Tools that invoke a hard coded ripgrep path instead of searching PATH will not see the wrapper. Configure that tool to use $HOME/.local/bin/rg if it supports a custom executable path.

Configuration

Precedence is:

CLI > environment > repository .crg.toml > user config > defaults

A small repository configuration looks like this:

[compression]
budget_tokens = 2000
max_files = 12
matches_per_file = 4
context_lines = 2
deduplicate = true

[ranking]
diversity_lambda = 0.35
near_duplicate_threshold = 0.88

[cache]
enabled = false
ttl = "7d"
max_size = "2GB"

Unknown fields are errors. Environment overrides include CRG_BUDGET_TOKENS, CRG_MAX_FILES, CRG_MATCHES_PER_FILE, CRG_CONTEXT_LINES, and CRG_CACHE_DIR. The complete schema is in examples/crg.toml.

Exactness, safety, and privacy

  • Every selected result originates from one exact ripgrep match event.
  • Final output is checked against the requested serialized budget.
  • Invalid UTF 8 paths retain a reversible byte representation in JSON.
  • Terminal control characters are escaped.
  • Source context accepts only safe relative paths and never modifies files.
  • Reversible cache directories and files use modes 0700 and 0600 on Unix.
  • Cache identifiers use versioned, length delimited BLAKE3 input.
  • Reversible data stays local and is compressed with fixed Zstandard settings.

If compression fails internally, --fallback raw displays every exact match in a terminal safe conventional form. --fallback error returns an internal error instead. A budget too small for mandatory retained and total counts returns exit code 64 without partial stdout.

Current limitations

  • Pattern files passed through -f or --file are used by ripgrep but are not read merely to derive ranking hints.
  • Approximate token budgets use a deterministic local estimate, not a model specific tokenizer.
  • Transparent rg mode cannot support ripgrep output modes that CRG rejects.
  • A shell alias does not affect tools that skip shell startup or use a hard coded executable path.

More documentation

License

Licensed under Apache License 2.0. See LICENSE.

FAQs

Package last updated on 13 Jul 2026

Related posts