# How to Set Up QMD for Coding Agents and Cut Token Usage on File Search

> AI Release · @ai_release1 · https://ai-release.org/guides/kak-nastroit-qmd-dlya-koding-agentov-i-sokratit-rashod_en.html

## TL;DR
- Time to complete: 30–45 minutes
- Difficulty: Intermediate
- You need: Linux or macOS (Windows via WSL2), `bash` 4+, `git`, `rg` (ripgrep) for the baseline measurement, one repository you can index, and a coding agent that can execute shell commands. QMD must be installed and resolvable on `PATH`. This guide does not pin a QMD version: every QMD-specific subcommand, flag or config field is marked **check the documentation** — run `qmd --help` and confirm the exact spelling for your build before you type it.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-nastroit-qmd-dlya-koding-agentov-i-sokratit-rashod-en-1.jpg?v=1794840584)

- **OS and shell.** Linux or macOS with `bash` 4+; on Windows use WSL2. Verify: `bash --version` prints `GNU bash, version 5.x` or newer.
- **git.** Your project must be a git repository, because the cheapest way to bound the index is to index tracked files only. Verify: `git rev-parse --show-toplevel` prints the repo root.
- **QMD installed and on PATH.** Verify: `qmd --version`. If you get `command not found`, add the install directory to `PATH` (see Troubleshooting, case 1). The install command and supported version are **check the documentation**.
- **A coding agent with shell access.** Any agent that can run commands non-interactively. The agent must be able to call `qfind` (created in Step 2) and read files.
- **Write access to a PATH directory.** You will drop one wrapper script into `~/bin` (or `~/.local/bin`). Verify: `echo $PATH | tr ':' '\n' | grep -F "$HOME/bin"`.
- **Free disk space for the index.** Index size depends on repository size and on how much content you keep. Check `df -h .` and see the sizing notes in the documentation before indexing a large monorepo.

- [ ] `qmd --version` prints a version string
- [ ] `git rev-parse --show-toplevel` prints a path
- [ ] `~/bin` (or `~/.local/bin`) is on `PATH`
- [ ] `df -h .` shows free space you are willing to spend
- [ ] You know which directories are generated (`node_modules/`, `dist/`, `.venv/`, `vendor/`)

**Example:** in a typical Node project the generated directories are `node_modules/` and `dist/`; in a Python project they are `.venv/` and `__pycache__/`. These are the directories you will exclude in Step 2, because indexing them inflates the index and returns files the agent should never open.

If you want semantic (meaning-based) search instead of symbol-based search, that is a different toolchain — see [local semantic file search with Rummage and EmbeddingGemma 2](https://ai-release.org/guides/kak-nastroit-lokalnyy-semanticheskiy-poisk-po-faylam-s.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide). QMD is used here as the fast path-lookup layer in front of your agent's file reads.

## Step 1. Measure the baseline: how many bytes your agent burns on file search
**What to do:** record three numbers for one repository before changing anything — tracked file count, total repository text size, and the number of bytes a naive search returns for one real query.

**Why:** without a baseline you cannot claim a token reduction, and token spend is proportional to the bytes your agent pulls into context.

**How to check:** run these commands from the repository root and write the outputs into a scratch file.

```bash
cd ~/projects/<your-repo>
git ls-files | wc -l
git ls-files -z | xargs -0 cat | wc -c
rg -n "createCheckout" --glob '!node_modules' | wc -c
```

**Example output (your numbers will differ):**

```text
1842
7341002
41208
```

The third number is the important one: it is the byte volume the agent ingests when it greps a common symbol across the tree without any index. A rough token estimate is characters ÷ 4; treat it as an estimate only, and for exact counts use the tokenizer of the model you actually run.

**Example:** if `rg -n "createCheckout" | wc -c` returns `41208`, the naive path costs roughly 10k tokens of context before the agent has read a single function body.

Save the numbers:

```bash
printf 'files=%s\ntotal_bytes=%s\nquery_bytes=%s\n' \
  "$(git ls-files | wc -l)" \
  "$(git ls-files -z | xargs -0 cat | wc -c)" \
  "$(rg -n "createCheckout" | wc -c)" > .qmd-baseline.txt
cat .qmd-baseline.txt
```

Why this works: `.qmd-baseline.txt` is a fixed reference you re-read in Step 3, so the before/after comparison uses identical commands and an identical query.

## Step 2. Build the index and give the agent a single search entry point
![Illustration: Step 2. Build the index and give the agent a single search entry point](https://ai-release.org/guides/img/kak-nastroit-qmd-dlya-koding-agentov-i-sokratit-rashod-en-2.jpg?v=1794840588)

**What to do:** create the QMD index for the repository, restrict it to tracked and hand-written files, then replace the agent's habit of "grep everything, then read everything" with one wrapper command and one written rule.

**Why:** agents burn tokens because they search broadly and read whole files. An index returns a short list of paths; a written rule stops the agent from ignoring that list. The wrapper also gives you one stable contract, so a QMD upgrade does not require rewriting your agent instructions.

**How to check:** `qfind "createCheckout"` returns at most five paths and no file bodies.

First, create the wrapper:

```bash
mkdir -p ~/bin
cat > ~/bin/qfind <<'EOF'
#!/usr/bin/env bash
# ~/bin/qfind — the only file-search entry point the agent may use.
# The QMD subcommand and flags below vary by build: run `qmd --help`
# and check the documentation before the first run.
set -euo pipefail

QUERY="${1:?usage: qfind <symbol-or-phrase>}"
LIMIT="${2:-5}"

qmd search "$QUERY" --limit "$LIMIT" --format paths
EOF
chmod +x ~/bin/qfind
```

If your build exposes a differently named subcommand (for example a query-style command instead of a search-style one), change that single line — **check the documentation**. The agent-facing contract stays `qfind "<query>"`.

Second, write the index configuration. The field names below are a skeleton; confirm each one against the documentation for your installed version.

```yaml
# qmd.config.yaml — skeleton. Field names are version-dependent: check the documentation.
index:
  root: .
  exclude:
    - node_modules/
    - dist/
    - .venv/
    - vendor/
  respect_gitignore: true
```

Third, index the repository:

```bash
cd ~/projects/<your-repo>
qmd index            # flags for incremental vs full reindex: check the documentation
qfind "createCheckout"
```

**Example:** the expected output is a short list, not code:

```text
src/checkout/createCheckout.ts
src/checkout/createCheckout.test.ts
src/api/routes/checkout.ts
```

Fourth, encode the rule in the file your agent reads at startup (`AGENTS.md`, or the equivalent instruction file your agent supports):

```markdown
## File search rules
- Do not run `grep -r` or `rg` across the whole repository.
- Call `qfind "<symbol>"` first; it returns at most 5 paths.
- Open only the returned paths and read at most 80 lines around the match.
- If `qfind` returns nothing, print the query and ask before falling back to `rg`.
```

The `5` and `80` values are your policy choices, not QMD defaults — pick numbers that match how much context your model handles comfortably.

**Example:** with the rule in place, the same question that previously produced a 41,208-byte grep now produces three paths, and the agent opens one file and reads 80 lines instead of reading the whole `src/` tree.

Keep secrets out of the index before you run the first build: exclude `.env`, key material and credential dumps, and treat every indexed file as readable by the agent. The general checklist is in [AI agent security: protecting your data during automation](https://ai-release.org/guides/bezopasnost-ii-agentov-kak-zaschitit-dannye-i-izbezhat.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## Step 3. Verify the reduction and keep the index fresh
![Illustration: Step 3. Verify the reduction and keep the index fresh](https://ai-release.org/guides/img/kak-nastroit-qmd-dlya-koding-agentov-i-sokratit-rashod-en-3.jpg?v=1794840591)

**What to do:** re-run the exact Step 1 query through `qfind`, measure the returned bytes, compute the ratio, and automate reindexing so results never go stale.

**Why:** an index that lags behind `HEAD` returns deleted files and dead symbols, which costs more tokens than no index at all.

**How to check:** the byte count for the same query must be far below the Step 1 number, and the index timestamp must be newer than your last commit.

```bash
cd ~/projects/<your-repo>
time qfind "createCheckout" | tee /tmp/qmd.out | wc -c
head -5 /tmp/qmd.out
```

**Example output:**

```text
412
src/checkout/createCheckout.ts
src/checkout/createCheckout.test.ts
src/api/routes/checkout.ts
```

Fill in the comparison table with your own measurements — the arithmetic is `baseline ÷ after`:

| Metric | Baseline (Step 1) | After (Step 3) | Ratio |
|---|---|---|---|
| Files in repository | `<n>` | `<n>` | — |
| Bytes returned for one symbol query | `<n1>` | `<n2>` | `<n1>/<n2>` |
| Files the agent actually opens | `<n>` | `<n>` | — |

Automate the refresh with a post-commit hook:

```bash
cat > .git/hooks/post-commit <<'EOF'
#!/usr/bin/env bash
# Reindex after every commit. Exact flags: check the documentation.
qmd index --update || echo "qmd reindex failed; agent results may be stale" >&2
EOF
chmod +x .git/hooks/post-commit
```

Confirm it fires:

```bash
git commit --allow-empty -m "test qmd hook"
```

Success looks like a clean commit with no `qmd reindex failed` line on stderr. If your build has no incremental flag, call the full index command in the hook instead — **check the documentation**.

**Example:** after the hook runs, `qfind "createCheckout"` on a branch where the file was renamed must return the new path only. If the old path still appears, the update did not complete.

Token savings are only half the budget story; set hard ceilings so a runaway agent cannot spend the difference — see [How to set spending limits and budgets for AI agents](https://ai-release.org/guides/kak-nastroit-limity-rashodov-i-byudzhety-dlya-ii-agento.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## Troubleshooting

**Problem. The wrapper is not found when the agent runs it**
- Ошибка: `-bash: qmd: command not found`
- Причина: QMD is installed in a directory that is not on `PATH`, or the agent runs in a non-interactive shell that does not source `~/.bashrc`.
- Решение: add the directory to `PATH` explicitly and re-check with the same non-interactive shell the agent uses: `export PATH="$HOME/.local/bin:$PATH" && qmd --version`. Persist it in `~/.profile` or in the environment block of your agent configuration.

**Problem. The wrapper exists but will not execute**
- Ошибка: `bash: /home/<user>/bin/qfind: Permission denied`
- Причина: the file was created without the execute bit, usually because the heredoc was written by a different account or the `chmod` step was skipped.
- Решение: `chmod +x ~/bin/qfind && ~/bin/qfind "createCheckout"`. If the agent still fails, call it by absolute path in the instruction file.

**Problem. Indexing fails or produces an empty index**
- Ошибка: `fatal: not a git repository (or any of the parent directories): .git`
- Причина: the indexer respects `.gitignore` and runs from a directory that is not the repository root — for example a subfolder of the project.
- Решение: `cd "$(git rev-parse --show-toplevel)"` and re-run the index command from there. Verify with `git rev-parse --show-toplevel` that the path matches the directory you are standing in.

## Summary and next steps
You now have a measured baseline, an excluded-directory index behind one `qfind` entry point, and a post-commit hook that keeps results current. Next, run the same baseline measurement on your second-largest repository and compare the ratios before rolling the `AGENTS.md` rules out to the rest of the team.

## FAQ

**What is QMD in one sentence?**
QMD is the file-search and indexing layer you place in front of a coding agent so it receives a short list of paths instead of dumping raw file contents into context; the exact CLI surface differs by build, so check the documentation for your version.

**Does QMD replace ripgrep?**
No. `rg` stays useful for the baseline measurement and as a deliberate fallback when `qfind` returns nothing; the rule is that the agent must ask before using the fallback, not that ripgrep is removed.

**Which directories should I exclude from the index?**
Generated and vendored directories: `node_modules/`, `dist/`, `.venv/`, `vendor/`, plus any file holding secrets such as `.env` or key material. Excluding them keeps the index small and stops the agent from opening files nobody should edit.

**How do I keep the index fresh across branches and machines?**
Reindex on every commit with the post-commit hook from Step 3, and reindex after switching branches with a long diff. Confirm freshness by querying a symbol you just renamed — the old path must not appear in the output.
