> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Search

> Answer grep and rg from your service's search.

`grep` and `rg` can ask your VFS which files or lines may hold the text,
instead of reading every file. Mirage still matches each line itself, so the
output is the same. Return `None` (TypeScript: `null`) when your search cannot
answer, and Mirage reads the file.

For example, with [Chroma](https://docs.mirage.strukto.ai/python/vfs/chroma.md) at `/knowledge/`,
`grep -r refund /knowledge/` asks Chroma which documents contain `refund` and
reads only those.

## When grep and rg call these methods

Only when every match contains a plain text of 3 or more characters, such as
`refund` in `grep 'refund.*2026'`, or a `-w` or `-x` word of any length.

They never call them with these flags, and read every file instead:

`grep` and `rg`:

* `-v`: print lines that do not match
* `-f FILE`: read patterns from a file

`grep` only:

* `-i`, when the text has a non-ASCII letter, or in a UTF-8 locale an `i`, `k`
  or `s`

`rg` only:

* `-i`, or `-S` with a lowercase pattern, when the text has a `k`, an `s` or a
  non-ASCII letter and more than 16 ways to write its case
* `--passthru`: print every line
* `--files-without-match`: list files with no match
* `--json`: print JSON
* `--stats`: print statistics
* `-z`: search compressed files
* `-L`: follow symlinks
* `--pre COMMAND`: preprocess each file
* `-E ENCODING`: read files in an encoding
* `-c` or `--count-matches`, with `--include-zero`

## `files_containing`

Which files under a folder may contain a text.

> [tab] Python
>
> ```python theme={null}
> async def files_containing(
>     self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool
> ) -> list[PathSpec] | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> filesContaining(
>   path: PathSpec,
>   text: string,
>   opts: { wholeWord: boolean; ignoreCase: boolean },
> ): Promise<PathSpec[] | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The folder `grep -r` or `rg` walks. |
| `text` | A text every match contains. Asked once per text, so `grep -r -e refund -e order` asks twice. |
| `whole_word` | `True` for `-w` or `-x`: `text` must match as a whole word. |
| `ignore_case` | `True` for `-i`, and for `rg -S` with a lowercase pattern. |

Under `rg -i`, a text with a `k`, an `s` or a non-ASCII letter is asked once per
way to write its case, with `ignore_case` `False`, since rg also matches `k` to
the Kelvin sign `K` and `s` to `ſ`: `rg -i café` asks for `café`, `CAFÉ` and 14
other spellings.

| Return | Mirage then |
| - | - |
| The files that may contain `text` | Reads only these files; the others have no match. Include every file that could match. |
| An empty list | Reads no file under `path`. |
| `None` | Reads every file. |

These commands call `files_containing`:

* `grep -r`, `grep -R`, `grep -d recurse`
* `rg` on a folder

A file named on the line is always read.

This example extends `NotesVFS` from [Custom VFS](https://docs.mirage.strukto.ai/home/setup/custom-vfs.md#example-a-read-only-vfs):

> [tab] Python
>
> ```python theme={null}
> from mirage import PathSpec
> from mirage.utils.key_prefix import mounted_path
>
> from notes import NotesVFS
>
>
> class SearchableNotesVFS(NotesVFS):
>     async def files_containing(
>         self, path: PathSpec, text: str, *, whole_word: bool, ignore_case: bool
>     ) -> list[PathSpec] | None:
>         if ignore_case:
>             return None
>         return [
>             mounted_path(path, "/" + name)
>             for name, page in self.pages.items()
>             if text in page
>         ]
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { mountedPath } from '@struktoai/mirage-core/utils/key_prefix'
> import { NotesVFS } from './notes.ts'
>
> export class SearchableNotesVFS extends NotesVFS {
>   override async filesContaining(
>     path: PathSpec,
>     text: string,
>     opts: { wholeWord: boolean; ignoreCase: boolean },
>   ): Promise<PathSpec[] | null> {
>     if (opts.ignoreCase) return null
>     return Object.entries(this.pages)
>       .filter(([, page]) => page.includes(text))
>       .map(([name]) => mountedPath(path, `/${name}`))
>   }
> }
> ```

`grep -rn mirage /notes` then reads only the pages that contain `mirage`.
`mounted_path` turns a name below the mount into a path.

## `lines_containing`

Which lines of one file may contain a text.

> [tab] Python
>
> ```python theme={null}
> async def lines_containing(
>     self, path: PathSpec, text: str, *, ignore_case: bool
> ) -> bytes | AsyncIterator[bytes] | None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> linesContaining(
>   path: PathSpec,
>   text: string,
>   opts: { ignoreCase: boolean },
> ): Promise<Uint8Array | AsyncIterable<Uint8Array> | null>
> ```

| Argument | Meaning |
| - | - |
| `path` | The file `grep` or `rg` would read. |
| `text` | A text every match contains. Asked once per text. |
| `ignore_case` | `True` for `-i`, and for `rg -S` with a lowercase pattern. |

| Return | Mirage then |
| - | - |
| The lines that may contain `text`, in their order, as bytes or as a stream of byte chunks | Matches them instead of reading the file, or reads the file if they hold a match. See the lists below. |
| Empty bytes | The file has no match. It is not read. |
| `None` | Reads the file. Return it for a file that may hold a NUL byte. |

Mirage matches your lines instead of reading the file for `grep` and `rg` with
no flag, or with:

* `-c`: count matching lines
* `-l`: list files with a match
* `-q`: print nothing, exit 0 on a match
* `-o`: print only the matched text
* `-m N`: stop after N matches
* `-i`: ignore case
* `-w`: match whole words
* `-x`: match whole lines
* `-F`: match the text literally
* `-r`: search folders
* `-L`: list files with no match (`grep` only)

Mirage reads the file only if your lines hold a match, and skips it if not, for
`grep` and `rg` with:

* `-n`: print line numbers
* `-b`: print byte offsets
* `-A N`, `-B N`, `-C N`: print lines around each match
* more than one pattern, such as `-e a -e b` or `'a|b'`
* `-z`: lines end with NUL (`grep` only; `--null-data` in `rg`)
* `--column`: print column numbers (`rg` only)
* `--vimgrep`: print every match with its position (`rg` only)
* `-U`: match across lines (`rg` only)

This example extends the same `NotesVFS`:

> [tab] Python
>
> ```python theme={null}
> import io
>
> from mirage import PathSpec
>
> from notes import NotesVFS
>
>
> class LineSearchNotesVFS(NotesVFS):
>     async def lines_containing(
>         self, path: PathSpec, text: str, *, ignore_case: bool
>     ) -> bytes | None:
>         page = self.page(path)
>         if ignore_case or "\0" in page:
>             return None
>         lines = io.StringIO(page, newline="\n").readlines()
>         return "".join(line for line in lines if text in line).encode()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import type { PathSpec } from '@struktoai/mirage-node'
> import { NotesVFS } from './notes.ts'
>
> export class LineSearchNotesVFS extends NotesVFS {
>   override async linesContaining(
>     path: PathSpec,
>     text: string,
>     opts: { ignoreCase: boolean },
>   ): Promise<Uint8Array | null> {
>     const page = this.page(path)
>     if (opts.ignoreCase || page.includes('\0')) return null
>     const lines = page.split(/(?<=\n)/).filter((line) => line.includes(text))
>     return new TextEncoder().encode(lines.join(''))
>   }
> }
> ```

`grep mirage /notes/todo.txt` and `grep -c mirage /notes/todo.txt` then read
nothing. `grep -n mirage /notes/todo.txt` reads the page, since it holds a
match.

## `before_full_walk`

Whether a command may copy, compare, change or remove every file under a folder.

> [tab] Python
>
> ```python theme={null}
> async def before_full_walk(
>     self, path: PathSpec, *, files: int | None = None
> ) -> None: ...
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> beforeFullWalk(path: PathSpec, files: number | null): Promise<void>
> ```

| Argument | Meaning |
| - | - |
| `path` | The folder a command is about to read, change or remove in full. |
| `files` | How many files the session sees under `path`; `None` when Mirage could not count them. |

| Return | Mirage then |
| - | - |
| Nothing | Runs the command. |
| Raises `ValueError` (TypeScript: rejects) | Refuses the command before it touches anything. It prints `<command>: <message>` and exits 1. |

These commands call `before_full_walk`: `tar -c`, `zip -r`, `cp -r`, `rm -r`,
`chmod -R`, `chown -R`, `chgrp -R`, `mv` to another mount and `diff -r`.
Mirage refuses more than the command's `walk_limit` files before it asks, so
the default lets the walk run.

## `walk_limit`

The most files one command walks under a folder (TypeScript: `walkLimit`), a
field of [`command_limits`](https://docs.mirage.strukto.ai/home/core/output-limits).

| Command | Past the limit |
| - | - |
| `grep -r`, `rg` | Stops. It keeps what it printed, prints `grep: <folder>: stopped after <N> files (walk_limit); narrow the path` and exits 2. |
| `git grep` | Stops. It keeps what it printed, prints `fatal: stopped after <N> files (walk_limit); narrow the pathspec` and exits 128. |
| `find`, `ls -R`, `du`, `tree`, `getfattr -R` | Stops listing. It keeps what it printed, prints the same `stopped after` line and exits 1 (`tree`: 2). |
| `git status`, `git add`, `git commit -a`, `git diff`, `git checkout`, `git reset`, `git rm` | Refused before it changes anything. It prints `fatal: more than <N> files in the work tree (walk_limit)` and exits 128. `git add`, `git diff` and `git rm` given paths walk only those, and a file named outright costs nothing. |
| A glob, such as `cat /notes/*` | Refused, so the command does not run. It prints `cat: Argument list too long` and `cat: /notes/*: matches more than <N> files (walk_limit); narrow the path`, and exits 126. |
| `tar -c`, `zip -r`, `cp -r`, `rm -r`, `chmod -R`, `chown -R`, `chgrp -R`, `mv` to another mount, `diff -r`, `gzip -r` | Refused before it touches anything (`before_full_walk`). It prints `tar: more than <N> files in scope (walk_limit); narrow the path` and exits 1. |

A search counts only the files it reads, so a file `files_containing` rules out
costs nothing. A listing counts every entry it lists, folders included. Each
command exits as it does when some files could not be read, so a script treats
a walk cut short as one with an error. A glob, a copy and a removal are refused
instead of cut short, since running on part of what they name would look
complete later. A glob in a `for` list stops the line with
`bash: /notes/*: matches more than <N> files (walk_limit); narrow the path`.

A walk that crosses into another mount counts that mount's files against its
own limit, and names that mount's folder where it stops. Codex's `fs/walk`
([exec-server](https://docs.mirage.strukto.ai/home/agents/codex.md#exec-server-forward)) lists the same way
and returns `truncated: true` where it stops.

| Value | Searches and listings | Globs, copies and removals |
| - | - | - |
| `-1` | Walk every file | Never refused |
| `0` | Read or list nothing under a folder | Always refused |
| A positive number | Stop after that many files | Refused above that many files |

It is 1000 unless your VFS starts at another value or a `command_limits`
entry sets it:

> [tab] Python
>
> ```python theme={null}
> class SearchableNotesVFS(NotesVFS):
>     walk_limit = 500
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> export class SearchableNotesVFS extends NotesVFS {
>   override walkLimit = 500
> }
> ```

`grep -r mirage /notes` on a folder of 600 pages that `files_containing`
cannot narrow then prints the matches in the first 500 pages, and:

```text theme={null}
grep: /notes: stopped after 500 files (walk_limit); narrow the path
```

## Built-in VFSs

These VFSs answer `grep -r` and `rg` with their service's search. A pattern
outside **Searches**, or a VFS not listed, reads every file. A search that can
miss a match leaves out a file that holds the text, so `grep` does not print
it.

| VFS | Searches | Can miss a match |
| - | - | - |
| [Google Drive](https://docs.mirage.strukto.ai/python/vfs/gdrive.md#integration) | Whole words (`-w`, `-x`) | Docs, Sheets and Slides JSON, office files, PDFs, archives, the end of large files, recent writes |
| [Google Docs](https://docs.mirage.strukto.ai/python/vfs/gdocs.md#integration), [Sheets](https://docs.mirage.strukto.ai/python/vfs/gsheets.md#integration), [Slides](https://docs.mirage.strukto.ai/python/vfs/gslides.md#integration) | Whole words | Words only in non-text values (fonts, links, formulas) or split by styling |
| Google Calendar | Whole words | No |
| [Dropbox](https://docs.mirage.strukto.ai/python/vfs/dropbox.md#integration) | Whole words | Office files, PDFs, archives, the end of large files, recent writes; file contents below the Professional plan |
| [Box](https://docs.mirage.strukto.ai/python/vfs/box.md#integration) | Whole words | Office files, PDFs, archives, the end of large files, recent writes |
| [OneDrive](https://docs.mirage.strukto.ai/python/vfs/onedrive.md#integration), [SharePoint](https://docs.mirage.strukto.ai/python/vfs/sharepoint.md#integration) | Whole words; SharePoint within one document library | Office files, PDFs, archives, the end of large files, recent writes |
| [Slack](https://docs.mirage.strukto.ai/python/vfs/slack.md#integration) | Whole words, with a user token | Recent messages, words only in other fields (bot names, link previews) |
| [Trello](https://docs.mirage.strukto.ai/python/vfs/trello.md#integration) | Whole words | Recent writes |
| [Linear](https://docs.mirage.strukto.ai/python/vfs/linear.md#integration) | Issues: whole words. Other files: any text | Recent issue writes |
| [Gmail](https://docs.mirage.strukto.ai/python/vfs/gmail.md#integration) | Any ASCII text | No |
| [Email (IMAP)](https://docs.mirage.strukto.ai/python/vfs/email.md#integration) | Any text | On a server that searches words, not substrings |
| [GitHub](https://docs.mirage.strukto.ai/python/vfs/github.md#integration) | Whole words, default branch, more than 100 files | Recent pushes |
| [Chroma](https://docs.mirage.strukto.ai/python/vfs/chroma.md#integration) | Any text; `-i` reads every page | No |
| [Qdrant](https://docs.mirage.strukto.ai/python/vfs/qdrant.md#integration) | Any ASCII text | No |
| [LanceDB](https://docs.mirage.strukto.ai/python/vfs/lancedb.md#integration) | Any text; not tables with list, struct or bytes columns | No |
| [SSH](https://docs.mirage.strukto.ai/python/vfs/ssh.md#integration) | Any text, on servers that run commands | No |
| [PostgreSQL](https://docs.mirage.strukto.ai/python/vfs/postgres.md#integration), [MongoDB](https://docs.mirage.strukto.ai/python/vfs/mongodb.md#integration), [Airtable](https://docs.mirage.strukto.ai/python/vfs/airtable.md#integration) | Any text, as lines of one file | No |

Every built-in VFS starts at 1000, or 5000 on GitHub, where each file is one
request, and 10000 on disk, RAM and OPFS. A mount's `command_limits` change it:
the `"@all"` entry, for every command, else the workspace's, sets the mount's own
`walk_limit`, and an entry named for one command, such as `find`, changes only
how far that command walks. On the VFSs above from Google Drive to GitHub, the
mount's own `-1` also turns the service's search off, so every file is read and
no match is missed:

> [tab] Python
>
> ```python theme={null}
> import os
>
> from mirage import Limit, MountMode, Workspace
> from mirage.vfs.slack import SlackConfig, SlackVFS
>
> slack = SlackVFS(
>     config=SlackConfig(
>         token=os.environ["SLACK_BOT_TOKEN"],
>         search_token=os.environ["SLACK_USER_TOKEN"],
>     )
> )
> ws = Workspace(
>     {"/slack": (slack, MountMode.READ, {"@all": Limit(walk_limit=5000)})},
>     mode=MountMode.READ,
> )
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Limit, MountMode, SlackVFS, Workspace } from '@struktoai/mirage-node'
>
> const slack = new SlackVFS({
>   token: process.env.SLACK_BOT_TOKEN!,
>   searchToken: process.env.SLACK_USER_TOKEN,
> })
> const ws = new Workspace(
>   { '/slack': [slack, MountMode.READ, { '@all': new Limit({ walkLimit: 5000 }) }] },
>   { mode: MountMode.READ },
> )
> ```

> [tab] YAML
>
> ```yaml theme={null}
> mounts:
>   /slack:
>     vfs: slack
>     mode: read
>     config:
>       token: ${SLACK_BOT_TOKEN}
>       search_token: ${SLACK_USER_TOKEN}
>     command_limits:
>       "@all":
>         walk_limit: 5000
> ```

`grep -rw refund /slack/channels/` then asks Slack's search which days mention
`refund` and reads only those. `grep -r refund /slack/channels/`, which Slack
cannot narrow, reads the first 5000 days and stops there.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.