Skip to content

CLI reference

The retrieval console script, registered via [project.scripts] in engine/pyproject.toml (retrieval = "retrieval.cli:main"). Thin argparse dispatcher over retrieval.persistence + retrieval.retrievers.

Synopsis

retrieval --version

retrieval index [--root ROOT]
                [--retriever all|lexical|lexical+ctx|turbovec|pi-serini|hybrid|treesitter]
                [--force] [--auto] [--tokenizer plain|code|cjk]
                [--target-chars N] [--config-chars N] [--code-chars N] [--ast-max-chars N]
                [--bm25-k1 F] [--bm25-b F] [--bit-width N] [--embed-model NAME]
                [--lucene-k1 F] [--lucene-b F] [--no-pdf] [--allow-large-context]
                # --retriever defaults to "all"

retrieval query QUERY [--root ROOT]
                       [--retriever all|lexical|lexical+ctx|turbovec|pi-serini|hybrid|treesitter]
                       [--top-k N] [--auto] [--pool N] [--json] [--stale-ok]
                       [--weights "name:w,..."] [--output PATH]
                       # --retriever defaults to "all" (consolidated mode)

retrieval stats [--root ROOT]

retrieval tune [--root ROOT] [--json]

retrieval eval --queries PATH [--root PATH] [--k 5] [--warm-runs 5] [--auto]
               [--json] [--output PATH]

retrieval mcp [--root ROOT]

retrieval extract [--root ROOT] [--force] [--prune] [--json]

retrieval sidecar [--root ROOT] [--json] (--list | --register SOURCE --transcript PATH|-)

index

Build and persist an index for a project root.

Flag Default Purpose
--root ROOT RETRIEVAL_ROOT env, then cwd Project root to index
--retriever {all,lexical,lexical+ctx,turbovec,pi-serini,hybrid,treesitter} all Retriever(s) to build
--tokenizer {plain,code,cjk} plain (or the --auto pick) Lexical tokenizer. code adds identifier subtokens; cjk emits character bigrams for Chinese/Japanese/Korean runs (use for PO translation memories). Applies to lexical, treesitter and the hybrid lexical arm; pi-serini ignores it. Persisted and sticky like the other hyperparameters. --auto picks cjk when CJK characters are at least 10% of word characters
--force off Rebuild even if a fresh (non-stale) cache already exists
--auto off Auto-derive hyperparameters from corpus signals (see tune); explicit flags below still override
--target-chars N static default (see below) Chunk-size bucket (default_chars) for files not matched by --config-chars/--code-chars. Prose files (.md, .markdown, .rst, .txt) use the separate prose_chars bucket and are not resized by this flag. Applies to every strategy
--config-chars N static default (see below) Chunk-size bucket for config files (config_chars). Applies to every strategy
--code-chars N static default (see below) Chunk-size bucket for tree-sitter-mapped code files (code_chars). Applies to every strategy
--ast-max-chars N static default (see below) Maximum size of an AST chunk (ast_max_chars). Affects only the treesitter strategy's AST chunking; other strategies use the line chunker and ignore it
--bm25-k1 F static default (see below) BM25 k1 (bm25_k1). Used by lexical, lexical+ctx, treesitter and the hybrid lexical arm
--bm25-b F static default (see below) BM25 b (bm25_b). Same strategies as --bm25-k1
--bit-width N static default (see below) turbovec quantization bit width (bit_width). Used by turbovec and the hybrid dense arm
--embed-model NAME static default (see below) Embedding model name (model_name). Used by turbovec and the hybrid dense arm
--lucene-k1 F static default (see below) Lucene BM25 k1 (lucene_k1). Used by pi-serini
--lucene-b F static default (see below) Lucene BM25 b (lucene_b). Used by pi-serini
--no-pdf off Exclude PDFs and every other sidecar-routed media suffix (captions, docx/pptx/xlsx/images, audio/video) from discovery — an escape hatch for the default auto-activated sidecar-extraction pipeline (see Customize indexing). Persisted in the cache's meta, so it's sticky across later flag-less index/query calls
--allow-large-context off Skip the lexical+ctx large-corpus guard (warns above 500 chunks, refuses above 2000 without this flag — each chunk costs one LLM call at index time)

Each retriever has its own cache slot per project, so e.g. a fresh lexical cache never short-circuits a hybrid build.

Indexing is chunk-granularity: index chunks every discovered file (retrieval.project_loader.load_chunk_documents) and persists one entry per chunk span, docid "{path}:{start}-{end}". This is what lets query return file:line spans instead of whole-file docids.

Hyperparameters and precedence

Precedence, highest first: an explicit flag, then the --auto-derived value, then the static default. Each strategy's meta records only the subset of keys it consumes (the chunking keys apply to all of them).

Key Static default Used by
prose_chars (no flag; --auto only), default_chars, config_chars, code_chars 400 all strategies (chunking)
ast_max_chars 1200 treesitter (AST chunking)
bm25_k1 / bm25_b 1.5 / 0.75 lexical, lexical+ctx, treesitter, hybrid lexical arm
tokenizer plain lexical, lexical+ctx, treesitter, hybrid lexical arm
model_name sentence-transformers/all-MiniLM-L6-v2 turbovec, hybrid dense arm
bit_width 4 turbovec, hybrid dense arm
lucene_k1 / lucene_b 0.9 / 0.4 pi-serini
  • With neither --auto nor any hyperparameter flag, nothing is recorded in the cache meta beyond the usual fields.
  • Hyperparameter flags given without --auto are layered over the heuristics' empty-corpus fallbacks, which equal the static defaults above except config_chars, which is 700.
  • --auto additionally records corpus_stats (n_chunks, mean_chunk_tokens, chunk_token_cv, auto: true) in the meta; query --auto reads it.
  • Recorded hyperparams and corpus_stats are sticky: a later rebuild with no --auto or flags (a plain index refresh, --force, or a query-triggered reindex) reuses them.
  • When --auto or flags are given and the resolved values differ from the ones recorded in a cache, that cache is stale and is rebuilt even without --force.

See Tune hyperparameters for the heuristics and a workflow.

Default (all) — build every strategy in one pass

With no --retriever (or --retriever all), index builds each strategy in lexical, turbovec, pi-serini, hybrid, treesitter — deliberately excluding lexical+ctx, since it shares the lexical cache slot and costs LLM tokens. For each strategy, in order: if a fresh cache exists and --force wasn't passed, prints <name>: up to date (use --force to rebuild) and moves on; otherwise it builds and persists that strategy, printing <name>: indexed <N> chunks. If a strategy's optional extras are missing, it prints <name>: skipped (<reason>) instead of failing — this is the "graceful degradation" mode: the whole run still exits 0 as long as the always-available lexical strategy itself built (or was already fresh). A final -> <cache-dir> line is printed. Within one run, hybrid adopts the turbovec (and lexical) arms built earlier in the same run instead of re-embedding, when they indexed the same documents and are compatible (same lexical parameters; same embedding model and bit_width); otherwise it does a full build. If turbovec was already up to date (not rebuilt in this run), hybrid also builds fully. The corpus is loaded and fingerprinted once per run, and the up-to-date check reads only the cache meta and the first 4 KB of the data file (see Freshness check). Sample output when turbovec is uninstalled:

lexical: indexed 118 chunks
turbovec: skipped (turbovec retriever needs the 'turbovec' + 'local' extras:)
pi-serini: indexed 118 chunks
hybrid: skipped (turbovec retriever needs the 'turbovec' + 'local' extras:)
treesitter: indexed 131 chunks
-> /home/user/project/.agentic-retrieval

The skipped <reason> is the first line of the backend's guidance RuntimeError; run the single-strategy form (--retriever <name>) to see the full message including the exact install command.

Single strategy (--retriever <name>)

Pass an explicit --retriever lexical|lexical+ctx|turbovec|pi-serini|hybrid|treesitter to build just one strategy. This form does not degrade gracefully: without --force, if a fresh cache already exists for the chosen retriever, index skips the rebuild and prints <retriever> index up to date -> <dir> (use --force to rebuild), returning exit code 0. Otherwise it builds the retriever over load_chunk_documents(root), persists it, and prints indexed <N> chunks -> <dir> fingerprint=<12-char prefix>.

Optional extras per retriever: lexical needs none; lexical+ctx needs the contextualizer's own dependencies; turbovec and hybrid need the turbovec + local extras; pi-serini needs the pyserini extra plus a Java 21 runtime. In this single-strategy form, a missing extra surfaces as exit code 1 with a guidance message on stderr — no skip, no fallback.

query

Search the persisted index for a project root.

Flag Default Purpose
query (positional) — Query text (required)
--root ROOT RETRIEVAL_ROOT env, then cwd Project root to search
--retriever {all,lexical,lexical+ctx,turbovec,pi-serini,hybrid,treesitter} all all (default) consolidates every available strategy; a single name queries just that strategy
--top-k N 5 (or the --auto estimate) Number of results
--auto off Resolve --top-k as clamp(round(1500 / mean_chunk_tokens), 5, 30) from the index's recorded corpus_stats (5 if missing). Ignored when --top-k is given; never re-derives index-time hyperparameters (those come from the cache's own meta)
--pool N derived from --top-k Consolidated mode only: per-retriever candidate-pool depth. Default comes from retrieval.fusion.candidate_pool
--json off Emit JSON instead of plain text (shape depends on --retriever; see "Output formats" below)
--stale-ok off Search the cached index even if it's stale, instead of auto-reindexing
--weights "name:w,..." none Consolidated mode only: per-retriever RRF weight override (unlisted retrievers default to 1.0)
--output PATH none Consolidated mode only: also write the JSON envelope to PATH

Default (all) — consolidated, deduplicated, explainable ranking

With no --retriever (or the explicit --retriever all alias), query loads (auto-reindexing as needed) every strategy in lexical, turbovec, pi-serini, hybrid, treesitter, searches each, and merges/fuses the results with retrieval.consolidation.consolidate into a single deduplicated, ranked list — see Consolidated query for the full output format and the span-merge/weighted-RRF mechanics. A missing backend's extras are skipped (reported on stderr in text mode, in the JSON envelope's "skipped" list otherwise) — never a hard failure, as long as lexical consolidates successfully (exit 0); exit 1 only if even lexical is unusable.

Single strategy (--retriever <name>)

Pass an explicit --retriever lexical|lexical+ctx|turbovec|pi-serini|hybrid|treesitter to query just one strategy, unchanged from the pre-consolidation CLI: if the cache is missing, or present but stale (and --stale-ok is not passed), query auto-reindexes (equivalent to a single-strategy index) before searching. Pick --retriever per question (exact tokens -> lexical, paraphrase/synonyms -> turbovec, Lucene-grade BM25 -> pi-serini, uncertain -> hybrid, AST-boundary code spans -> treesitter; see docs/how-to/hybrid-fusion.md). This form never silently falls back to a different retriever: if the chosen backend's extras are missing, it hard-fails with exit code 1 and a guidance message on stderr — retry with --retriever lexical explicitly if you want that fallback.

stats

Report on every persisted index cache for a project root (one block per cached retriever, blank-line separated), without searching or rebuilding.

Flag Default Purpose
--root ROOT RETRIEVAL_ROOT env, then cwd Project root to report on

Prints retriever, root, chunks (chunk count), files (distinct source-file count), created, engine, stale, and cache (the on-disk directory) per cached retriever. If no cache exists, prints no cache for <root> (dir=<cache-dir>) and returns exit code 0. When the cache recorded them (built with --auto or a hyperparameter flag), it also prints hyperparams: {...} and corpus_stats: {...} lines.

tune

Preview the hyperparameters index --auto would pick for a project root. It writes no index cache or meta, but it is not strictly read-only: signal collection calls ensure_sidecar(), which can write extracted-transcript sidecar files and their manifest under <project-root>/.agentic-retrieval/extracted/.

Flag Default Purpose
--root ROOT RETRIEVAL_ROOT env, then cwd Project root to analyze
--json off Emit a JSON report instead of text

Text output:

signals: n_files=.. code_fraction=.. cjk_fraction=..
n_chunks=.. mean_chunk_tokens=.. chunk_token_cv=..
proposed params (vs. static defaults):
  <key>: <value>
  ...
warning: ...

The <key>: <value> lines are sorted by key; warning: appears only when set. With --json the report is {"signals": {...}, "params": {...}, "warning": <str|null>}. signals holds n_files, ext_histogram, total_bytes, code_bytes, code_fraction, median_code_lines, n_chunks, mean_chunk_tokens, chunk_token_cv, p10_chunk_tokens, p50_chunk_tokens, p90_chunk_tokens and cjk_fraction; params holds the twelve keys listed under Hyperparameters and precedence (prose_chars included). The warning is advisory only: it fires when the 10th-percentile chunk size is below 15 tokens (chunks may be sliced too finely), and nothing is auto-corrected.

The per-parameter rules are in Tune hyperparameters.

eval

Run the labeled-query eval harness — recall@k/nDCG@k per retriever vs the consolidated fusion, confidence-signal validity, and cold/warm search latency — entirely in-memory (no <project-root>/.agentic-retrieval writes). See Evaluate retrievers for the query-set schema and how to read the metrics.

Flag Default Purpose
--queries PATH required Path to a labeled eval_queries.json file
--root PATH the query set's own corpus_root Override the corpus to eval against
--k N 5 recall@k / nDCG@k cutoff
--warm-runs N 5 Number of extra warm search repeats per query
--json off Emit a JSON report instead of text
--output PATH none Also write the JSON report to PATH
--auto off Derive hyperparameters from the eval corpus; recorded in the report as auto_params (text mode prints an auto_params: {...} line after the report)

Builds every strategy in lexical, turbovec, pi-serini, hybrid, treesitter over the query set's corpus, skipping (not hard-failing) any whose optional extras are missing — same graceful-degradation convention as index/query's default mode. Exit code 0 as long as lexical produced results; 1 only if even lexical is unusable.

extract

Pre-warm every machine-extractable sidecar transcript (PDF + caption files) under a project root, without building or touching any retriever index — useful for pre-warming a large corpus's extraction cache ahead of time (e.g. in CI, or before a first index run) so that index/query don't pay the extraction cost inline. Machine-extractable formats only — extract never attempts agent-only media (.docx, .pptx, .xlsx, images) or agent-orchestrated audio/video, neither of which has a machine extractor to run; those always need sidecar --register.

Flag Default Purpose
--root ROOT RETRIEVAL_ROOT env, then cwd Project root to extract from
--force off Re-extract every file even if its cached sidecar is already fresh
--prune off Remove manifest entries and sidecar files for media no longer present under --root (registered agent-only/agent-orchestrated sidecars are kept, not just machine-extracted ones, even though this loop never extracts them)
--json off Emit a JSON summary instead of one progress line per file

Discovers files the same way index/query do (discover_files with default kwargs, filtered to MACHINE_EXTRACTABLE_EXTENSIONS), then calls retrieval.extractors.ensure_sidecar on each. This is the only place extraction hard-fails on a missing backend: require_extractors is called with the suffixes actually discovered (not the blanket EXTRACTABLE_EXTENSIONS), so it raises a guidance RuntimeError (exit code 1, error: PDF extraction needs the 'pdf' extra:\n uv pip install -e '.[pdf]' on stderr) only when a discovered file actually needs pypdf — a caption-only tree with zero PDFs succeeds even without it. index/query never hard-fail this way; a PDF degrades to a backend-missing stub instead (see Customize indexing).

Text-mode output is one line per file — "pages" for a PDF, "sections" for a caption file (the manifest field itself is always pages, regardless of format):

docs/paper.pdf -> .agentic-retrieval/extracted/docs/paper.pdf.md (12 pages, 34521 chars)
docs/scan.pdf: stub (no-text-layer)
media/talk.srt -> .agentic-retrieval/extracted/media/talk.srt.md (6 sections, 8120 chars)

--json emits {"root": "<path>", "files": [{"source", "sidecar", "status", "reason", "pages", "chars"}, ...], "pruned": <int>}. Exit code 0 on success even if some files produced stubs (a stub is still a valid, searchable sidecar) — non-zero exit is reserved for the missing-pdf-extra preflight failure.

sidecar

Inspect or author sidecar transcripts for any media tier without touching pypdf — the no-install alternative to extract for PDFs, and the only indexing path for agent-only media (.docx, .pptx, .xlsx, images) and agent-orchestrated media (.mp4, .mov, .mkv, .webm, .mp3, .m4a, .wav, .flac), neither of which has a machine extractor at all. Unlike extract, sidecar never imports/requires pypdf on either mode, so it works identically whether or not the pdf extra is installed, and never reads an audio/video source's bytes (see extractors reference: stat-only identity).

Flag Default Purpose
--root ROOT RETRIEVAL_ROOT env, then cwd Project root
--json off Emit JSON instead of text
--list — Report every discovered media file's sidecar state (mutually exclusive with --register, one required)
--register SOURCE — Register an agent-authored transcript as SOURCE's sidecar (requires --transcript; mutually exclusive with --list, one required)
--transcript PATH\|- required with --register Path to the transcript file, or - for stdin

--list

Reports every media file discover_files would surface, one state per file: missing (no manifest entry yet), outdated (source changed since the entry was written), agent-authored (registered via --register), stub (a placeholder — backend-missing for a PDF, no-cues/malformed for a caption file, agent-only for docx/pptx/xlsx/images, or agent-orchestrated for audio/video), or ok (a fresh machine-extracted transcript — pypdf for a PDF, the stdlib converter for a caption file). Text mode: one line per file, e.g.

docs/paper.pdf: stub (backend-missing) -> needs transcript
docs/spec.pdf: agent-authored (4 pages)
img/diagram.png: stub (agent-only) -> needs transcript
media/recording.mp4: stub (agent-orchestrated) -> needs transcript

A media-heavy corpus can produce a long wall of stubs in text mode; use --json and filter (e.g. jq '.files[] | select(.state != "stub")') rather than scrolling past them.

--json emits {"root", "backend_available", "files": [{"rel", "state", "sidecar", "status", "reason", "pages", "authored_at"}, ...]}.

--register SOURCE --transcript PATH|-

Writes SOURCE's sidecar from a hand-authored transcript — the recovery path when an agent has read the PDF (or docx/pptx/xlsx/image) itself (e.g. via its own Read tool, or vision for an image) instead of installing pypdf, and the only path for audio/video, where an agent orchestrates an ASR tool via Bash and registers its output the same way. See the retrieval skill's "Author the media transcript yourself (the default media path)" and "Audio and video: orchestrate an ASR tool, then register" sections for the full agent workflows (heading format, when to use this, lifecycle). For the audio/video workflow end to end, see Transcribe audio and video. Prints a reindex to pick up this sidecar hint; also warns on stderr if SOURCE isn't discoverable by the default loader, or if the transcript has no ## Page N / ## [HH:MM:SS] ... headings — the manifest's pages counter reads 0 in that case, which is expected and harmless for a page-less format, since section breadcrumbs come from any ## heading, not specifically ## Page N. Missing --transcript is an argument-parsing error (exit code 2, mirroring argparse's own required-argument handling).

Exit codes

Code Meaning
0 Success. Also returned by a default (all) index run, and a default (all) query run, even when one or more optional strategies were skipped for missing extras, as long as lexical itself built/consolidated.
1 A handled runtime error (e.g. an exception raised inside a subcommand) — the message is printed to stderr as error: <exc>. This includes single-strategy index --retriever <name> and query --retriever <name> when that strategy's extras are missing (no graceful skip in single-strategy form), a default index run whose lexical strategy itself fails to build, and a default (all) query run where even lexical couldn't be consolidated.
2 Argument-parsing error (missing/invalid flags, unknown subcommand) — raised by argparse itself via SystemExit, before the CLI's own error handling runs

Output formats

  • index: a single status line to stdout (fast-path or rebuilt message).
  • query (default, consolidated all mode): one source_path:start_line-end_line [score=... agree=n/m conf=... via a,b,c] context line per result, best match first (skip notes go to stderr). The first token stays path:start-end, so it still feeds straight into Read(path, offset=start_line, limit=end_line-start_line+1).
  • query --retriever <name> (single strategy): one source_path:start_line-end_line span per line, best match first, no scores — unchanged from before consolidated mode existed.
  • query --json (default, consolidated all mode): {"query": "<text>", "mode": "consolidated", "retrievers": [...], "skipped": [{"name", "reason"}, ...], "results": [{"docid", "path", "start_line", "end_line", "rank", "context", "score", "provenance", "agreement", "confidence", "contributors"}, ...]}.
  • query --retriever <name> --json (single strategy): {"query": "<text>", "results": [{"docid": "<path:start-end>", "path": "<source_path>", "start_line": <int>, "end_line": <int>, "rank": <int>, "context": "<str>"}, ...]} — unchanged from before consolidated mode existed. Breaking change from 0.2.0: results used to be a flat list of docid strings; it is now a list of objects — see changelog.
  • Record-loader hits (e.g. .po entries; see Customize indexing): both JSON shapes gain an optional metadata object (kind, msgid, msgstr, fuzzy, translated, line, references, ...); it is omitted for every other hit. In text mode, each such hit is followed by indented label: value detail lines chosen by its loader; for PO these are msgid: ... / msgstr: ... ((untranslated) and a [fuzzy] tag where applicable) — consumers that read "first token = path" should skip lines starting with spaces.
  • query --output PATH (consolidated mode only): also writes the --json envelope to PATH.
  • stats: a fixed set of key: value lines to stdout (plus hyperparams and corpus_stats lines when recorded).
  • tune: text lines, or with --json a {"signals", "params", "warning"} envelope (see tune).

retrieval mcp

retrieval mcp [--root ROOT]

Serves search_domain_context, index_project and index_status over MCP stdio for one project (also available as the retrieval-mcp script). Requires the mcp extra; without it the command prints guidance to stderr and exits 1. stdout carries only the MCP protocol; logs go to stderr. Root resolution: --root -> RETRIEVAL_ROOT -> CLAUDE_PROJECT_DIR -> cwd.

--root resolution order

--root -> RETRIEVAL_ROOT environment variable -> current working directory, if neither is given. (retrieval mcp additionally consults CLAUDE_PROJECT_DIR before falling back to cwd.)

Next steps