ir.grep¶
The grep Retriever leaf: an index-free first stage over a corpus’s raw files.
Embedding indexes find paraphrases but miss the exact things a keyword search is for
(a name, an identifier, an error string) and need a build step that may be stale. This
leaf reads the files where they lie: it runs a regex (rg when available, else
Python re) over the files under some roots and returns
SearchHits, so it can be fused with a dense or BM25 ranking like
any other Retriever (ir.retrieve.Retriever).
Python’s re is the authority: pattern is a Python regex, lines are split on
\n only (a trailing \r is ignored), and counts and snippets come from Python,
so scores never depend on whether rg is installed. rg is only a prefilter that
skips files with no possible match, and it is used only when that is provably safe:
an ASCII literal pattern (no regex metacharacters, see rg_can_prefilter()),
since rg and Python read \w, \s, ., character classes and Unicode case
folding differently and a prefilter that disagrees would silently drop files. Any
other pattern is read in Python (use_rg=True then raises).
Scoring is explicit and tunable: a file’s score is its matching-line count (or, with
score_line, the sum of each matching line’s score: a heading or a title field can
count more than body text, see markdown_heading_score() and
json_field_score()), times a per-file weight (weight_of: e.g. a title or a recent folder counts more), times an
optional recency decay (recency_half_life_days: a file’s weight halves for each
half-life of age). Metadata filters are pushed into the scan: metadata_of(path)
derives a file’s metadata and a Mongo-style filter (the same one
ir.search() takes) drops files before they are read.
The files are either everything under roots (filtered by glob) or, with
paths, an explicit {artifact_id: path} mapping: corpus_paths() reads one
from a built corpus, which is how ir.search(corpus, pattern, mode="grep") greps the
files a corpus indexed, under the corpus’s own artifact ids.
Hit metadata carries only the id-relative path and filename (never an absolute
local path, which would leak into anything published) unless absolute_paths=True.
It returns hits, never a loop and never a plan; whether to grep or to use the index is the caller’s (or the agent layer’s) choice.
>>> import tempfile, pathlib
>>> with tempfile.TemporaryDirectory() as d:
... _ = pathlib.Path(d, "a.md").write_text("Acme invoice\nnothing\nacme again")
... _ = pathlib.Path(d, "b.md").write_text("unrelated")
... hits = grep_hits("acme", roots=d, use_rg=False)
>>> [(h.artifact_id, h.score, h.metadata["n_matches"]) for h in hits]
[('a.md', 2.0, 2)]
Module Attributes
How many files one |
|
Longest snippet kept per hit (the first matching line, trimmed). |
|
Directories never descended into (VCS and tooling noise; override with |
|
The |
|
the score one matching line adds to its file. |
Functions
|
|
|
The top- |
|
A |
|
Bind roots (and defaults) to the uniform |
|
A |
|
A composable |
|
Whether |
|
The files |
- ir.grep.DFLT_EXCLUDE_DIRS = ('.git', 'node_modules', '__pycache__', '.venv')¶
Directories never descended into (VCS and tooling noise; override with
exclude_dirs).
- ir.grep.DFLT_RG_BATCH = 500¶
How many files one
rgcall is handed (keeps argv under the OS limit).
- ir.grep.DFLT_SNIPPET_CHARS = 200¶
Longest snippet kept per hit (the first matching line, trimmed).
- ir.grep.GREP_KIND = 'grep'¶
The
surface_kindof a grep hit.
- ir.grep.LineScore¶
the score one matching line adds to its file.
- Type:
score_line(line, rx) -> float
- ir.grep.corpus_paths(corpus)[source]¶
{artifact_id: file}for the artifacts of a built corpus that are files.Read from the metadata the corpus stored at build time (the
paththat file-backed sources such asfrom_filesandfrom_md_reportsrecord), so no source is walked again; the files themselves are read live bygrep_hits(). Artifacts without a stored path (records, packages, skills) are left out.
- ir.grep.grep_hits(pattern, *, roots=None, paths=None, glob='*', k=10, ignore_case=True, fixed=False, filter=None, metadata_of=None, weight_of=None, score_line=None, recency_half_life_days=None, id_of=None, use_rg=None, rg_batch=500, exclude_dirs=('.git', 'node_modules', '__pycache__', '.venv'), absolute_paths=False, snippet_chars=200, source=None, now=None)[source]¶
The top-
kfiles underrootswhose lines matchpattern, as hits.patternis a Python regex (fixed=True: a literal). Files are those whose root-relative posix path matches the fnmatchglob(*crosses/, so"*.md"means every markdown file below the root); a root that is a file stands for itself.filteris applied tometadata_of(path)before any file is read (a filter withoutmetadata_ofsees{"path", "filename"}, the path relative to its root).id_of(root, path)names the artifact (default: the relative path); two files with the same id raiseValueError(several roots with a common relative path: passid_of).use_rg:None= prefilter withrgif installed,True= require it (RuntimeErrorotherwise),False= Python only. The score is described in the module docstring.pathsreplacesroots: an explicit{artifact_id: path}mapping (e.g.corpus_paths()), its keys used as ids and matched againstglob; a path that is not a file any more is skipped. Give exactly one ofrootsandpaths.score_line(line, rx)scores each matching line (default 1, so the score is the count); seemarkdown_heading_score()andjson_field_score().
- ir.grep.json_field_score(weights, *, default=1.0, other_lines=1.0)[source]¶
A
score_lineseam for JSONL records: field weights, for title-over-body.Each line is read as one JSON object; the line scores the sum of
weights[f]over the top-level fieldsfwhose (string) value matches,defaultfor a matching field not inweights. A match only in a key, or in a non-string value, scores 0. A line that is not a JSON object scoresother_lines.>>> score = json_field_score({"title": 3.0, "body": 1.0}) >>> rx = re.compile("acme", re.I) >>> score('{"title": "Acme", "body": "acme again"}', rx) 4.0 >>> score('{"title": "Other", "body": "about acme"}', rx) 1.0
- ir.grep.make_grep_retriever(roots, **grep_defaults)[source]¶
Bind roots (and defaults) to the uniform
ir.retrieve.Retrievercontract.The result is
retrieve(pattern, **overrides) -> list[SearchHit](rootsmay be overridden per call too), the same shape asir.as_retriever(), so a grep leaf can sit in aMapping[name, Retriever]registry beside index-backed corpora. Overrides are the keywords ofgrep_hits(); an unknown one (mode=) is aTypeError, not silently dropped.
- ir.grep.markdown_heading_score(heading=3.0, *, body=1.0)[source]¶
A
score_lineseam: a match on a markdown heading line countsheading.Any other matching line counts
body, so a document whose title names the pattern outranks one that only mentions it in passing.>>> score = markdown_heading_score(3.0) >>> rx = re.compile("acme", re.I) >>> score("# Acme invoices", rx), score("paid acme today", rx) (3.0, 1.0)
- ir.grep.recency_weight(half_life_days, *, now=None)[source]¶
A composable
weight_ofseam: a file’s weight halves perhalf_life_daysof age.nowpins the clock (default: the time of each call). Multiply it into your ownweight_ofto combine it with other weights; it is whatrecency_half_life_daysuses.>>> import os, tempfile, time >>> from pathlib import Path >>> with tempfile.TemporaryDirectory() as d: ... f = Path(d, "a.md"); _ = f.write_text("x") ... os.utime(f, (0, 0)) ... recency_weight(10, now=10 * _SECONDS_PER_DAY)(f) 0.5
- ir.grep.rg_can_prefilter(pattern, *, ignore_case=False, fixed=False)[source]¶
Whether
rgis guaranteed to select a superset of the files Python matches.Public so other tools (e.g. astern) can share the one safety rule.
>>> rg_can_prefilter("acme") True >>> rg_can_prefilter(r"ac\w+") False >>> rg_can_prefilter(r"ac\w+", fixed=True) True- Return type:
- ir.grep.rg_prefilter(files, pattern, *, ignore_case=False, fixed=False, batch=500)[source]¶
The files
rgsays may match, orNoneifrgis missing or cannot be used for this pattern/batch (the caller then reads every file in Python).Guard the call with
rg_can_prefilter():rgis a safe prefilter only for the patterns it accepts. Files are handed torgbatch at a time.