{"slug": "faster-grep-for-agents", "title": "Faster Grep for Agents", "summary": "Microsoft's tgrep, a trigram-indexed grep with a client/server architecture, was faster than ripgrep in 17 of 18 repo/platform combinations in an August 24, 2026 benchmark sweep, with speedups ranging from 0.93x to 51.9x. The tool is integrated into GitHub Copilot CLI to power fast regex searches across large repositories, narrowing queries to candidate files via the trigram index and verifying them in parallel with the regex engine. The benchmarks measure client/server search latency with the index already built, not indexing time, and tgrep's indexes stored in `.tgrep/` can lag filesystem changes unless the server refreshes them or `--no-index` is used.", "body_md": "Trigram-indexed grep with a client/server architecture for fast regex search in large codebases.\n\n**tgrep is integrated into [GitHub Copilot CLI](https://github.com/github/copilot-cli)\nto power fast grep searches across large repositories.**\n\n[Install tgrep](#installation), then start a server:\n\n```\ntgrep serve .           # builds the index if needed; runs in the foreground\n```\n\nIn another terminal:\n\n```\ntgrep -- \"fn main\" .    # automatically connects to the server\ntgrep status .          # show indexing and refresh status\n```\n\nWithout a server, run `tgrep index .` to build an on-disk index. Searches use\nthe server when available, then the local index, or scan the filesystem if no\nusable index exists. Indexes are stored in `.tgrep/` by default; add this\ndirectory to `.gitignore`. It is generated build output and must not be committed\nor distributed with a repository. Build indexes locally for repositories you\nsearch; index metadata is not a statement of trust or freshness.\n\nIndexed file reads stay beneath the selected root and do not follow descendant\nsymlinks or Windows reparse points. Invalid stored paths are rejected; indexes\nwith an unavailable or unrelated recorded root fall back to a filesystem scan.\nExplicit file arguments and `--no-index --follow` retain their normal scan\nsemantics.\n\n**Indexes can lag filesystem changes.** The server updates asynchronously;\nwithout a server, rerun `tgrep index .` after changes. Use `--no-index` when a\nsearch must read the current files. Queries scan during an initial build until\ncomplete coverage is available.\n\nFor coding agents, see [AGENTS.md](https://github.com/microsoft/tgrep/blob/main/AGENTS.md). To install MCP search tools and\nstartup hooks for Codex or pi, run `bash install-agent.sh` from this checkout\n(Linux/macOS, Python 3.11+). See the\n[agent integration guide](https://github.com/microsoft/tgrep/blob/main/scripts/agent/README.md).\n\nA trigram index narrows each query to files that could match, then verifies those files with the regex engine in parallel. Patterns without useful trigrams may still require searching every indexed file.\n\nIn the August 24, 2026 benchmark sweep, tgrep was faster than ripgrep in 17 of\n18 repo/platform combinations, with speedups from 0.93x to 51.9x. These measure\nclient/server search latency with the index already built, not indexing time.\nResults depend on the query, repository, storage, and match volume. See\n[BENCHMARKS.md](https://github.com/microsoft/tgrep/blob/main/BENCHMARKS.md) for measurements and methodology.\n\nThe [shared-worktree baseline](https://github.com/microsoft/tgrep/blob/main/SHARED_INDEX_BENCHMARKS.md) compares one ordinary\nserver/index per worktree with one shared daemon across 1, 4, 16 and 32 synthetic\nGit worktrees. It covers LF, clean CRLF, private branch changes and bounded churn,\nwith scan-checked results, fresh/restart startup, query percentiles, reconciliation\ncounters, process resources and retained storage. It includes a small Windows/Linux\nsmoke command and distinguishes logical sharing from OS page-cache and RSS effects.\nThe measured baseline saves LF memory/storage but has higher startup/query latency;\nclean CRLF can cost more memory/storage too. Shared mode remains opt-in.\n\n```\ntgrep index .                        # index current directory\ntgrep index /path/to/repo             # index a specific repo\ntgrep index . --index-path /tmp/idx    # custom index location\ntgrep index . --exclude vendor --exclude third_party  # skip directories\n```\n\nEach build reports elapsed time and, where available, peak memory:\n\n```\nIndex built successfully at /tmp/idx\nIndexed in 22.6s using external strategy (peak memory 160.1 MiB)\n```\n\nWindows reports peak private committed bytes; Linux samples anonymous resident memory. Both exclude file-backed mappings and report the working set separately when it is substantially larger. macOS reports resident memory instead.\n\nLike ripgrep, tgrep applies `.gitignore` only inside a Git repository. It warns\nwhen a root `.gitignore` is present but not applied. Use `--no-require-git` on\nindexing, serving, and searching to apply those rules outside Git:\n\n```\ntgrep index . --no-require-git\ntgrep serve . --no-require-git\ntgrep --no-require-git -- \"pattern\" .\n```\n\nWhen Git's `core.ignorecase` is enabled, tgrep applies an additional\ncase-insensitive exclusion pass for the repository's root `.gitignore` and\n`.git/info/exclude`. Git-tracked paths are exempt from this additional pass,\nbut not from ordinary traversal, binary, or size filtering.\n\nNested `.gitignore` files and global ignore rules do not get this additional\npass. `--no-ignore` disables it along with the normal ignore rules.\n\nUse the same `--no-require-git`, `--no-ignore`, `--max-filesize` (or\n`--no-max-filesize`), and `--exclude` settings for `index` and `serve`.\nStartup reconciliation removes indexed files excluded by the server's current\nsettings. For example, serving an uncapped index with `--max-filesize 8M`\nremoves files larger than 8 MiB from that index.\n\nPass the same size policy, `--no-require-git`, and any custom `--index-path`\nto searches too. `--exclude` is only available on `index` and `serve`;\n`--no-ignore` on a search forces a filesystem scan.\n\n```\ntgrep index . --max-filesize 8M\ntgrep serve . --max-filesize 8M\ntgrep --max-filesize 8M -- \"pattern\" .\n```\n\n`tgrep index` defaults to an external merge sort with a 64 MiB posting buffer.\nWhen the buffer fills, sorted segments spill to disk and are merged into the\nindex. This bounds posting-buffer memory, not total process memory: file\ntables, worker buffers, and decoded content also consume memory.\n\n```\ntgrep index .                          # external, 64 MiB posting buffer\ntgrep index . --index-buffer 16        # smaller buffer, lower peak\ntgrep index . --index-strategy=memory  # sort entirely in RAM\n```\n\n`--index-buffer` is in MiB and applies only to the external strategy.\n`--index-strategy=memory` avoids temporary spill files but holds all postings\nin RAM. Both strategies still need a writable index directory.\n\n`tgrep serve` uses the external builder with the default buffer for new\nindexes; it does not accept `--index-strategy` or `--index-buffer`.\nLarge files can be memory-mapped, but files needing decoding or UTF-8 repair\nrequire heap buffers. Use `--max-filesize` to limit admitted file sizes.\nSee [index-build benchmarks](https://github.com/microsoft/tgrep/blob/main/BENCHMARKS.md#index-build-strategies).\n\nOrdinary `index` and `serve` processes share an exclusive `serve.lock` in the\nindex directory. Stop a server before running `index` against the same directory;\nuse the server's `reload` RPC to rebuild without stopping it.\nCore API callers sharing an output directory with the CLI must hold the same lock.\nAfter acquiring the lock, both commands recover journaled interrupted index\npublications, then remove abandoned numeric `spill-<pid>[-<sequence>].tmp`\nartifacts and the known bootstrap, reload, filename, delta, merge, and flush\nstaging directories. Published index files and unrelated entries are preserved.\nLegacy unjournaled backups are left untouched. Invalid or ambiguous recovery\nrecords stop startup rather than guessing which generation to restore.\nLinked or unremovable fixed staging entries stop startup before writers can\nreuse them. Spill cleanup failures produce warnings; spill writers allocate\nfresh names instead of reusing leftovers. Windows files still mapped by readers\nare not force-unlinked, including during recovery.\nIf publication and its rollback both fail, the server preserves the recovery\njournal and blocks further publications, including reloads and filename-only\nsaves. `status` reports that a restart is required; recovery must finish before\nany later index can be published. Existing in-memory readers remain available.\nManaged shared storage uses its own lifecycle and is not cleaned by this path.\n\nBefore extracting content, ordinary builds check available space on the index\nfilesystem. The estimate is three times candidate-file bytes for external\nsorting, or twice for in-memory sorting, plus 1 KiB per candidate path and\n64 MiB of headroom. An unavailable file size is charged as 64 MiB. Staged\nrewrites also check their known posting and lookup sizes before writing.\nThese are estimates, not space reservations or worst-case bounds: content,\npath lengths, concurrent writers, and filesystem quotas can still cause later\nwrite failures. Destination and spill I/O failures, including permission errors,\nstop the build instead of triggering an in-memory retry. An initial preflight\nrejection leaves the existing index intact.\nFree space or choose `--index-path` on another volume if a check fails. A failed\ninitial server build reports the error in `status` and leaves queries scanning;\nfix the storage issue and reload or restart it to retry.\n\n```\ntgrep serve .                         # auto-build index if missing\ntgrep serve . --index-path /tmp/idx   # custom index location\ntgrep serve . --watch-mode poll       # poll without native subscriptions\ntgrep serve . --poll-interval 60      # polling cadence after fallback\ntgrep serve . --watch-budget 4096     # lower this process's native watch ceiling\ntgrep serve . --no-watch              # disable all automatic refresh\ntgrep serve . --exclude node_modules  # exclude directories from indexing\n```\n\nThe server builds the index in the background if none exists and resumes\nincomplete builds. Clients scan the filesystem until the full corpus is ready;\n`tgrep status` reports indexing progress and hidden-file coverage. Legacy\nindexes are upgraded by startup reconciliation. Multiple clients can connect\nsimultaneously.\n\nInitial and resumed builds save a partial checkpoint after the first bounded\nextraction batch, then after approximately 30 seconds of extraction between\ncheckpoints, and at the end. Restart reuses the checkpoint's indexed paths and\nread evidence; edits, deletions, and changed ignore rules are reconciled before\nindexed queries are enabled. Termination during publication is recovered under\n`serve.lock` on the next start, before scratch directories are cleaned.\n\nThe checkpoint cadence is not a hard time limit: the filesystem walk, one\nextraction batch, streaming a checkpoint, or final reconciliation can take\nlonger. Checkpoints stream existing postings into the replacement rather than\nloading them into heap, trading additional disk I/O for restart progress.\n`--no-watch` retains its full catch-up reads before completion. These guarantees\ncover process termination, not storage loss or power-failure durability.\n\nIndex builds and server refreshes exclude `.git` directory subtrees by default,\nincluding nested repositories' Git internals. `--hidden` does not override this;\nuse `--no-ignore` consistently on `index` and `serve` to include them. Explicit\nfilesystem scans (`--no-index`) retain ripgrep-style hidden and ignore behavior.\nGit metadata needed for ignore rules and tracked-file detection is still read.\nAs in ripgrep, a file a scan cannot read is reported and makes the exit code 2.\nOn Windows a shared daemon holds a byte-range lock on\n`.git/tgrep-daemon-v1.lock`, so `--no-index --hidden` scans of that checkout\nreport it; add `-g '!.git'` when Git internals are not wanted.\n\nOn Windows, replaced index generations stay in `.retired` while readers have\nthem memory-mapped. Cleanup retries after publication, every minute, and on\nstartup; journaled uncommitted backups are restored on startup. This does not reclaim\nstorage already stranded in NTFS's `$Deleted` namespace by older versions.\n\nThese tuning options apply only to `tgrep serve`:\n\n| Flag | Default | Effect | \n|---|---|---|\n| `--max-memory <MB>` | 50% of RAM (512 MiB–16 GiB) | Overlay flush threshold for fallback in-memory builds; not a process-wide hard limit | \n| `--max-cpu <PERCENT>` | `50` | Size the indexing worker pool for initial, resumed, fallback, reload, and stale-delta builds as a share of logical cores, with at least one worker | \n| `--auto-save-mutations <N>` | `5000` | Pending content mutations that trigger a background save | \n| `--watcher-queue-cap <N>` | `16384` | Buffered filesystem events; overflow triggers reconciliation | \n\nInitial and resumed external builds use a 64 MiB posting buffer and the\n`--max-cpu` indexing pool. Search parallelism is independent: the server does\nnot change `RAYON_NUM_THREADS` or resize the global search pool. `--max-cpu` is a\nworker-count budget, not an OS CPU quota. `--max-memory` applies only to the\nexceptional in-memory fallback, which is allowed only before any checkpoint\npublication is attempted and never for destination, spill, or disk-space\nfailures. Existing checkpoint progress is not discarded to enter that fallback.\n\nThe server checks for pending saves once a minute. It saves at the mutation threshold, when filename-only membership changes, or when content changes remain unsaved for at least ten minutes since startup or the last successful save. Active builds and flushes defer this check.\n\nStartup watcher traces count filesystem notifications, not confirmed content edits. Replay re-reads notified files and avoids content-index mutations when their decoded contents match the indexed fingerprint. Delta-save traces report the unique candidate paths plus separate scan and live-overlay counts; these inputs can overlap and do not represent a count of user edits.\n\nAutomatic refresh has two modes, configured on `tgrep serve`:\n\n| Flag | Default | Effect | \n|---|---|---|\n| `--watch-mode <auto\\|poll>` | `auto` | Prefer native notifications with polling fallback, or use polling only | \n| `--poll-interval <SECONDS>` | `120` | Minimum wait between managed metadata checks; full rereads wait at least 15 intervals, with cost-based backoff. Legacy polling keeps this interval; range 1-86400 | \n| `--watch-budget <N>` | `8192` | Conservative process-local native watch ceiling; range 1-4294967295 | \n| `--no-watch` | off | Disable all automatic refresh: native watching, polling, and periodic reconciliation | \n\nIn `auto` mode, a watch-budget or native-registration failure releases this\nprocess's watches and switches it to polling until restart. Status reports the\nreason. Explicit `poll` mode creates no native subscriptions.\n\nOn Linux/Android, the budget counts admitted directories; ignored subtrees do\nnot consume watches. The OS inotify quota is shared with other processes, so\nregistration can fail before this budget is reached. Raising `--watch-budget`\ndoes not raise the OS quota. Windows and macOS use one recursive root\nsubscription and filter ignored events after delivery.\n\nPolling checks filesystem metadata for additions, changes, and deletions.\nThe next poll waits `--poll-interval` seconds after the previous reconciliation\nfinishes; scan time and ongoing builds/saves add to the delay. Queries do not\ndefer polling. Queue overflows and native rescan notifications also request\nreconciliation; read-only access events are discarded.\n\nOrdinary (non-shared) native mode reconciles about once an hour to recover missed\nnotifications.\nIt waits for a two-minute gap in queries, deferring no longer than four hours.\n`--poll-interval` does not change this native safety cadence.\n\nNo-change scans do not rewrite the index; changed merges may rewrite it.\nMetadata-preserving changes can be missed, and reconciliation is not an atomic\nfilesystem snapshot. Failures appear in status. Use `--no-index` for current\nfile contents.\n\n`--no-watch` permits the initial build/startup reconciliation but disables later\nrefresh. It conflicts with explicitly supplied `--watch-mode`, `--poll-interval`,\nand `--watch-budget`. `--watch-mode poll` also rejects an explicit\n`--watch-budget`.\n\n```\ntgrep -- \"pattern\" .                    # regex search\ntgrep -- \"pattern\" file1.rs file2.rs     # multiple files/paths\ntgrep -- \"TODO|FIXME\" .                 # alternation\ntgrep -- '\\w+(?!_test)' .               # backtracking-engine fallback\ntgrep -i -- \"error\" .                   # case-insensitive\ntgrep -F -- \"Vec<T>\" .                  # literal string\ntgrep -l -- \"MyStruct\" .                # filenames only\ntgrep -c -- \"pattern\" .                 # matching lines per file\ntgrep -m 5 -- \"pattern\" .               # at most 5 matching lines per file\ntgrep -g \"*.rs\" -g \"*.toml\" -- \"pattern\" .  # multiple globs (OR)\ntgrep -t rust -C 3 -- \"pattern\" .       # Rust files, 3 lines of context\ntgrep -e \"pattern\" -e \"also_this\" .     # multiple patterns (OR)\ntgrep --json -- \"pattern\" .             # JSON stream\ntgrep --vimgrep -- \"pattern\" .          # editor jump targets\ntgrep --stats -- \"pattern\" .            # query plan and timing\ntgrep --no-index -- \"pattern\" .         # read current files, bypass index\ntgrep -U -- 'first\\nsecond' .           # multiline match\ntgrep -q -- \"pattern\" .                 # exit code only\ntgrep --files .                        # list admitted paths, including binary files\ntgrep --files -t rust .                # list Rust files\ntgrep --type-list                      # show file types\n```\n\nWith the default traversal rules, `--files` reads the live server or the local\nindex instead of walking the repository. The local result is an index snapshot;\nuse `--no-index` to inspect the filesystem as it exists now. Flags that change\ntraversal membership or the file-size policy also fall back to a walk.\n\n```\ntgrep status .\nServer status for /src/my-monorepo\n  PID:        37980\n  Port:       51043\n  Files:      152\n  Trigrams:   12265\n  Cache:      2/50000\n  Watcher:    active\n  Watch mode: native (requested: auto)\n  Watch budget: 8192\n  Poll interval: 120s (after completion)\n  Reconcile:  idle\n  Last successful reconcile: 2m ago\n  Reconcile pending: no\n  Reconcile overdue: no\n  Last reconcile duration: 42ms\n  Indexing:   complete\n  Hidden coverage: complete\n```\n\n`Watcher` refers to native notifications, so it is normally inactive in polling\nmode. Refresh fields report fallback reasons, errors, pending work, and elapsed\ndeadlines. Older servers may omit these fields.\n\n`Indexing: complete` and `Hidden coverage: complete` describe index readiness,\nnot freshness. An existing index can be queried while startup reconciliation\nis still running. Without a server, `status` shows on-disk metadata.\n\n```\ntgrep count-files .              # count candidate text files (no server needed)\ntgrep count-files /path/to/repo  # scan a specific repo\n```\n\nCounts files admitted by the walk's ignore, visibility, extension, and default size rules, without reading their contents. The reported \"text files\" can therefore include files containing NUL bytes. Prints the count to stdout and details to stderr:\n\n```\n284957\n284957 text files (47516 binary skipped, 0 too large, 0 errors) in 1200ms\n```\n\nThese tables describe search flags. Use `tgrep index --help` and\n`tgrep serve --help` for subcommand options.\n\n| Flag | Description | \n|---|---|\n| `-i, --ignore-case` | Case-insensitive matching (the last of `-i` ,`-s` and`-S` wins) | \n| `-s, --case-sensitive` | Force case-sensitive matching (the last of `-i` ,`-s` and`-S` wins) | \n| `-S, --smart-case` | Case-insensitive when the patterns contain literals and none are uppercase (the last of `-i` ,`-s` and`-S` wins) | \n| `-F, --fixed-strings` | Treat pattern as a literal string | \n| `-w, --word-regexp` | Require non-word characters or text boundaries on both sides of the match; overrides earlier `-x` | \n| `-v, --invert-match` | Show lines that do NOT match | \n| `-o, --only-matching` | Print only the matched parts | \n| `--match-context <N>` | Like `-o` , with up to N Unicode characters on each side of each match on its line. Nearby excerpts may overlap. Columns and byte offsets still identify the match. JSON keeps its full-line events. | \n| `-e, --regexp <PAT>` | Additional pattern (repeatable for OR) | \n| `-f, --file <FILE>` | Read patterns verbatim, one per line; blank lines are empty patterns (repeatable) | \n| `-U, --multiline` | Enable multiline matching ( `.` still excludes`\\n` ) | \n| `--multiline-dotall` | Make `.` match`\\n` ; implies`-U` | \n| `-n, --line-number` | Show line numbers (default: on when stdout is a terminal) | \n| `-N, --no-line-number` | Suppress line numbers | \n| `-c, --count` | Count matching lines per file | \n| `-l, --files-with-matches` | Print only filenames | \n| `--files-without-match` | Print files that do NOT match | \n| `-q, --quiet` | Suppress output; exit code only | \n| `-m, --max-count <N>` | Limit matching lines per file (see [Match limits](#match-limits) ) | \n| `--max-results <N>` | Stop after the file in which the N-th matching line is found (see [Match limits](#match-limits) ) | \n| `-g, --glob <GLOB>` | Filter files by glob pattern, case-sensitive (repeatable); overrides `-t` /`-T` | \n| `--iglob <GLOB>` | Case-insensitive glob filter (repeatable) | \n| `--glob-case-insensitive` | Treat all `-g` globs as case-insensitive | \n| `-t, --type <TYPE>` | Filter by file type ( `rust` ,`py` ,`js` , …; repeatable) | \n| `-T, --type-not <TYPE>` | Exclude a file type (repeatable); the last `-t` /`-T` matching a file wins | \n| `--type-add <SPEC>` | Add/extend a type, e.g. `--type-add 'web:*.html'` | \n| `--type-clear <TYPE>` | Remove a type's definitions given before it | \n| `--type-list` | Print all supported file types (reflects `--type-add` /`--type-clear` ) | \n| `--files` | List admitted paths without content checks; includes binary files | \n| `-A, --after-context <N>` | Lines of context after match | \n| `-B, --before-context <N>` | Lines of context before match | \n| `-C, --context <N>` | Lines of context before and after | \n| `--heading / --no-heading` | Grouped vs flat output | \n| `-H, --with-filename` | Show filenames (default: on unless a single file was named) | \n| `-I, --no-filename` | Suppress filenames in output | \n| `--json` | ripgrep-compatible JSON stream (one object per line) | \n| `--vimgrep` | Vim-compatible `file:line:col:content` , one row per match | \n| `--color auto/always/never` | Color mode control | \n| `-0, --null` | Follow every printed file path with a NUL byte instead of its separator, in all output modes except JSON (for xargs) | \n| `--trim` | Trim leading ASCII whitespace from printed lines (JSON lines are unchanged) | \n| `-., --hidden` | Include hidden files and directories | \n| `--no-ignore` | Don't respect `.gitignore` or`p4ignore.ini` files | \n| `-a, --text` | Search binary files as if they were text | \n| `--binary` | Search binary files, reporting a note instead of their contents | \n| `--content-eligibility extensions/content` | `content` admits text behind the binary-extension heuristic; uses only a matching managed view (see below) | \n| `-u, --unrestricted` | Unrestricted: `-u` = no-ignore,`-uu` = +hidden,`-uuu` = +binary | \n| `--max-filesize <SIZE>` | Skip files larger than `SIZE` (`K` /`M` /`G` suffixes); default 64M | \n| `--no-max-filesize` | Apply no size limit, as ripgrep does | \n| `-L, --follow` | Follow symbolic links | \n| `--no-messages` | Suppress error messages about unreadable/missing paths | \n| `--no-index` | Read files from disk, bypassing the server and index; normal filters still apply | \n| `--shared` | Require a registered shared view for queries (otherwise scan); on `serve` , opt into the repository daemon | \n| `--exclude <DIR>` | Exclude directory from indexing (repeatable); `index` and`serve` only, not accepted by a search | \n| `--stats` | Print query plan and candidate stats | \n| `--index-path <DIR>` | Custom index directory | \n\n**Pattern matching**\n\n| Flag | Description | \n|---|---|\n| `-x, --line-regexp` | The pattern must match a whole line; overrides earlier `-w` | \n| `-P, --pcre2` | Use the backtracking engine (lookaround, backreferences) | \n| `--engine <auto\\|default\\|pcre2>` | Pick the regex engine explicitly; `auto` falls back to`pcre2` | \n| `--pcre2-version` | Print the backtracking engine in use and exit | \n| `--no-unicode` | Disable Unicode-aware character classes | \n| `--regex-size-limit <SIZE>` | Cap the compiled regex size ( `K` /`M` /`G` suffixes) | \n| `--dfa-size-limit <SIZE>` | Cap the regex DFA cache size | \n| `-r, --replace <TEXT>` | Replace each match; `$1` /`${name}` expand capture groups | \n| `--passthru` | Print every line, matching or not | \n| `--stop-on-nonmatch` | Stop searching a file at its first non-matching line | \n\n`--engine auto` (the default) uses Rust's `regex` crate, with fallback to\n`fancy-regex` for lookaround and backreferences. `-P` and `--engine pcre2`\nselect `fancy-regex`, not the PCRE2 library; they do not promise full PCRE2\nsyntax compatibility.\n\nEach `-e` or `-f` pattern has its own inline-flag scope: `(?i)` in one does\nnot make the others case-insensitive. Smart case considers all supplied patterns\ntogether, counting literal characters rather than escapes such as `\\S` or\nUnicode property names. With `-F`, every pattern character is literal.\n\nPatterns from every `-e` and `-f` accumulate in command-line order, including\nthose given after the `search` subcommand. Case flags do not accumulate: as in\nripgrep, the last of `-i`, `-s` and `-S` decides.\n\nWith `--json`, `-r` leaves `lines` and each submatch's `match` text and offsets\npointing at the source, and adds the expanded text as the submatch's\n`replacement`, as ripgrep does.\n\nPattern files preserve leading and trailing whitespace and accept LF or CRLF\nline endings. A blank line supplies an empty pattern that matches every input\nline. An empty file supplies no patterns: the search produces no output and\nexits 1, unless `-e` supplies another pattern or `-v` inverts the selection.\n\n**Output formatting**\n\n| Flag | Description | \n|---|---|\n| `--column` /`--no-column` | Show the 1-based column of the first match | \n| `-b, --byte-offset` | Show the byte offset of the line (or match, with `-o` ) | \n| `-M, --max-columns <N>` | Omit lines longer than `N` bytes | \n| `--max-columns-preview` | Show a truncated preview instead of omitting | \n| `--count-matches` | Count matches rather than matching lines | \n| `--include-zero` | With `-c` , also print files with a count of`0` | \n| `-p, --pretty` | Alias for `--color always --heading -n` | \n| `--context-separator <SEP>` | Separator between context groups (default `--` ) | \n| `--no-context-separator` | Print no separator between context groups | \n| `--field-match-separator <SEP>` | Separator between match fields (default `:` ) | \n| `--field-context-separator <SEP>` | Separator between context fields (default `-` ) | \n| `--path-separator <SEP>` | Rewrite the separator in printed paths | \n| `--sort <KEY>` /`--sortr <KEY>` | Sort by `path` /`modified` /`accessed` /`created` /`none` | \n| `--sort-files` | Shorthand for `--sort path` | \n| `--line-buffered` /`--block-buffered` | Force line- or block-buffered stdout | \n\n**Encoding**\n\n| Flag | Description | \n|---|---|\n| `-E, --encoding <LABEL>` | Decode as `LABEL` (e.g.`utf-16le` ,`latin1` ,`sjis` );`none` disables BOM sniffing and transcoding | \n| `--no-encoding` | Restore BOM-sniffing auto-detection | \n\nBy default, a UTF-8/UTF-16LE/UTF-16BE BOM selects decoding; otherwise files are\ntreated as UTF-8. A BOM overrides a named encoding, but not `-E none`.\nAny non-`auto` encoding bypasses the index and server. Invalid UTF-8 is still\nrepaired, including with `-E none`; this is not raw-byte matching.\n\n**File walking**\n\n| Flag | Description | \n|---|---|\n| `--max-depth <N>` | Limit directory recursion depth | \n| `--one-file-system` | Don't cross file-system boundaries | \n| `--ignore-file <FILE>` | Read extra ignore rules from `FILE` (repeatable) | \n| `--ignore-file-case-insensitive` | Match `--ignore-file` rules case-insensitively | \n| `--no-ignore-dot` | Ignore `.ignore` files | \n| `--no-ignore-exclude` | Ignore `.git/info/exclude` | \n| `--no-ignore-files` | Ignore any `--ignore-file` arguments | \n| `--no-ignore-global` | Ignore the global gitignore | \n| `--no-ignore-parent` | Ignore rules from parent directories | \n| `--no-ignore-vcs` | Ignore `.gitignore` files | \n| `--no-ignore-messages` | Suppress errors about malformed ignore files | \n| `--no-require-git` | Apply git ignore rules outside a git repository | \n| `-j, --threads <N>` | Filesystem walker threads; does not set the regex-search or server worker pool | \n\n**Accepted for compatibility**\n\n`--mmap`/`--no-mmap` (tgrep chooses memory mapping automatically), `--crlf`/`--no-crlf`\n(a trailing `\\r` is always stripped), `--no-config` (tgrep reads no config\nfile), and `--colors <SPEC>` (colors are not yet configurable) are accepted and\nignored so ripgrep command lines keep working. `--debug`/`--trace` imply\n`--stats`.\n\nFor indexed content searches, `--stats` reports **Raw candidates** before\npath, visibility, glob, and type filters, and **Candidates** after those filters\nbut before size checks, reads, or matching. **`no index narrowing`** means the\nraw set covers the entire nonempty index. **`(via server)`** describes transport,\nnot index effectiveness. Older servers may omit candidate statistics.\n\n`-z/--search-zip` is **not** supported and exits with code `2` rather than\nsilently reporting no matches in compressed files.\n\n**Note:** `-L` means `--follow` (as in ripgrep). Use the long\n`--files-without-match` for the non-matching-files listing.\n\nWithout `-e`/`-f`, the first positional argument is the pattern and the rest are\npaths. As soon as `-e` or `-f` supplies a pattern, **every** positional becomes\na path, matching ripgrep:\n\n```\ntgrep -e needle .            # searches for \"needle\" under .\ntgrep -e needle -e other .   # both patterns, still just one path\n```\n\nUse `--` before a positional pattern that starts with `-` or is a subcommand\nname, such as `serve` or `index`. Quoting alone does not prevent subcommand\nparsing. Put all flags before `--`:\n\n```\ntgrep -F -- serve .\n```\n\n`-t`/`-T` selections and `--type-add`/`--type-clear` definitions apply in\ncommand-line order, as in ripgrep, including flags given after `search`:\n\n- When several `-t` /`-T` selections match a file, the last one decides:`-T rust -t rust` searches Rust files, while`-t rust -T rust` searches none.\n- `--type-clear` removes a type with every definition given before it. A later`--type-add` defines the type afresh, while selecting a cleared type that was\nnot redefined is an error.`--type-list` reflects the same order.\n- Globs take precedence over types. A file that matches a `-g` /`--iglob` glob\nis included or excluded by that glob alone, and when any positive glob is\ngiven, a file matching none of them is excluded.`-t` /`-T` decide only the\nfiles that globs leave open, so`-t rust -g '*.txt'` searches`.txt` files.\n\nServers and shared daemons from releases that predate ordered filters cannot answer searches whose result depends on this order; those searches fall back with a diagnostic. Clients from those releases keep their old filtering when they search a newer server.\n\ntgrep matches ripgrep's context-dependent defaults rather than fixed ones:\n\n- **Line numbers** are on only when stdout is a terminal. Piping to another\ncommand drops them, so`tgrep needle . | cut -d: -f1` behaves the same as it\ndoes with ripgrep.`--column` ,`--vimgrep` and`-p` turn them back on;`-b` and`-A/-B/-C` do not.\n- **Filenames** are shown unless you named exactly one*file* . A directory\nargument always shows them.`-H` /`-I` override either way.\n- **Paths** are printed by appending onto the argument you typed: the argument\nsurvives verbatim and only the appended part uses the platform separator. So`tgrep needle src/` prints`src/main.rs` while`tgrep needle src` prints`src\\main.rs` on Windows.`--path-separator` rewrites every separator.\n\n`-m/--max-count` limits matching lines, not individual matches. All matches\non an admitted line are reported. With `-U`, the unit is a contiguous block\nof lines covered by matches, so a multiline match is not cut short.\n\ntgrep reads a whole-file buffer even with `-m`; its `bytes_searched` statistic\ncan therefore exceed ripgrep's.\n\n`--max-results` limits matching lines across the whole invocation, which\nripgrep has no flag for. Files are reported whole: the search ends after the\nfile that brings the total to the limit, so a few more lines than the limit\ncan be printed. The lines counted are those of the source: a multiline match\ncounts every line it covers, however it is printed, and so do the matching\nlines of a binary file that is reported with a note. A server stops reading\ncandidate files at that point too,\nwhich keeps a broad query on a large tree fast; a shared daemon and a search\nwith `--sort` search every candidate and apply the limit to the result. It\ncannot be combined with `-l`, `--files-without-match`, `-c`,\n`--count-matches`, `-q` or `--files`.\n\n`--json` emits ripgrep-shaped `begin`, `match`, `context`, `end`, and `summary`\nrecords. Result paths, contents, offsets, submatches and match/line counts do\nnot depend on whether an index was used. Statistics describe the work of the\nselected backend, not an imaginary full scan:\n\n- `searches` counts eligible files actually searched, including candidates\nthat produced no rows. Indexed routes can search fewer files than a scan.\n- `bytes_searched` sums those files' existing buffer-byte counts (the binary\ndetection offset when applicable). It is not physical disk I/O: cached\ncontent still counts, index construction is excluded, and whole-buffer\nmatching can count more bytes than ripgrep with an early match limit.\n- Each `end` has one search and that file's bytes. Summary work totals also\ninclude searched files without an`end` ; they are not inferred from output.\n- `searches_with_match` ,`matches` , and`matched_lines` describe emitted\nmatching results.`bytes_printed` counts serialized`begin` /`match` /`context` bytes, including newlines;`end` and`summary` exclude themselves. Summary\nprinted bytes are the sum of the per-file`end` values.\n\nElapsed timings are diagnostic, not equality-comparable output. tgrep's\nper-file elapsed measures the client writer's file-output interval; summary\n`stats.elapsed` equals `elapsed_total`, the writer's invocation-wide wall time.\nRipgrep instead aggregates per-search elapsed into summary `stats.elapsed`,\nwhich is distinct from its wall-clock `elapsed_total`. These timing conventions\nare unchanged; neither proves a search backend or the work done.\n\nJSON clients request per-file search-work statistics from ordinary and shared servers. A server too old to supply them is not used for JSON output: an ordinary connection falls back to the local index, and a shared connection that rejects the request falls back to scanning, with the usual diagnostics. Non-JSON requests retain their existing protocol behavior.\n\n`-U/--multiline` allows matches across line boundaries and prints every covered\nline. `--vimgrep` reports one row per match, on its starting line.\nAdjacent matches remain separate for `-o`, `--vimgrep`, `--count-matches`\nand JSON submatches.\n`--count-matches` counts each original regex match once, after applying `-m`,\neven when the match spans several lines. This does not depend on `--stats`;\n`-c` retains its matching-line count and `-v` counts selected non-matching lines.\nServer `-c` and `--count-matches` requests return one count or path row per\nmatching file, rather than transmitting every matching line, span and column.\n`--stats` still reports the original match and matched-line totals; it does not\nrestore unused line detail. Counts therefore do not consume reply space\nproportional to matching content, but remain subject to the same response limit.\nServer `-l` returns one path row per file and, without `--stats`, stops at the\nfirst match in each file.\nOrdinary older servers that ignore `-c` projection retain line-row counting.\nShared servers that reject the new option, and servers without metadata needed\nfor `--count-matches`, fall back with a diagnostic. Malformed projected counts\nor incomplete match totals are rejected before any counts are printed.\nWithout `-r`, tgrep reports columns relative to each printed line, whereas\nripgrep repeats the starting column on continuation lines.\n\nWith `-r`, each block of lines joined by matches is rewritten as a whole, as in\nripgrep: the rewritten text replaces the block, so a match that spans lines can\nbecome a single line, and `-o` prints the expanded replacement of each match.\nLine numbers and columns of the rewritten lines follow ripgrep, which numbers\nthem consecutively from the block's first line and repeats its starting column.\nA block whose rewrite is empty prints nothing. With context, a file that then\nprints no lines at all still adds a `--` under `--sort` or `-j1`, or on a single\nCPU, as ripgrep's one-file-at-a-time search does; otherwise it adds none, as in\nripgrep's parallel search.\nServers and shared daemons that predate this rendering are bypassed with a\ndiagnostic.\n\n`--json` reports a multiline match as one `match` event per covered line,\nwhile ripgrep emits a single event whose `lines.text` holds the whole block.\nWith `-r`, the first of these fragments carries the whole replacement and the\nothers an empty one.\n\nA file is treated as binary if its decoded content contains a NUL byte:\n\n- Binary files found by walking a directory are **skipped silently** — they\nappear in neither the output,`-l` ,`-c` , nor`--files-without-match` .\n- A binary file **named explicitly** on the command line reports a note:`bin.dat: binary file matches (found \"\\0\" byte around offset 7)` .\n- `--binary` promotes traversal to the explicit behaviour, so binary files are\nsearched and summarised with that note.\n- `-a` /`--text` disables binary detection entirely and prints matches as text.\n- `--json` has no note. As in ripgrep, the matching lines are emitted as\nordinary`match` events and the file's`end` message carries`binary_offset` — the offset of the first NUL — so a consumer can still tell\na binary hit apart from a text one.`stats.bytes_searched` stops at that\noffset rather than counting the whole file.\n\ntgrep also skips known binary extensions during directory content searches\nand indexing, unlike ripgrep. For searches, `--binary` and `-a` lift this\nrestriction and bypass the index; they do not change what `index` or `serve`\nindexes. `--files` lists binary paths too.\n\n`--content-eligibility content` is the explicit ripgrep-parity alternative for\nmanaged shared views. It drops only the extension heuristic: files are still\nclassified by content, so NUL-containing files stay excluded as binary, and\nignore, hidden, size and filename rules are unchanged. It is indexed only by a\nmanaged v2 view attached with the `content-only` eligibility profile (see\n[SHARED_WORKTREE_INDEXES.md](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#content-eligibility-profiles)).\nIt bypasses ordinary servers and local indexes, which use the extension rule.\nAny profile mismatch, in either direction, produces the usual shared-fallback\nwarning and a filesystem scan using the requested rule. The default,\n`extensions`, keeps the behaviour above. `index` and `serve` reject the flag.\n\n`index` and `serve` include hidden, **non-ignored** files by default.\n`--hidden` is accepted on either command but is redundant. Ordinary queries\nstill hide hidden files and directories; `-./--hidden` includes them using the\nindex or server, for content searches and `--files`. Visibility is relative to\nthe requested search root and includes Windows hidden attributes. Ignore rules\ninside hidden directories remain active. The configured index directory,\nincluding its staging and retired generations, is always excluded from indexing\nand query filesystem walks.\n\nFlags that widen or re-interpret the indexed corpus still walk the tree:\nnon-`auto` `-E/--encoding`, `-a/--text`, `--binary`, and ignore-disabling flags\nsuch as `--no-ignore`. Explicit file arguments also bypass the index.\n\nFor content searches, `--follow`, `--one-file-system`, `--ignore-file`, and\n`--ignore-file-case-insensitive` do **not** trigger fallback: indexed searches\nignore them. Add `--no-index` to apply them. `--files` falls back to walking\nfor these options automatically. `index` and `serve` reject these traversal options,\n`--max-depth`, and individual `--no-ignore-*` discovery switches.\n\nBoth positive and negative `--glob`/`--iglob` patterns filter the indexed corpus\nwhen a compatible index or server is available, for content searches and\n`--files`. Positive globs such as `--glob '*.ts'` do not reinclude ignored files\nin indexed mode. Use `--no-index` when those matches are needed: filesystem\nscans retain ripgrep-style glob overrides, which can reinclude ignored files.\nNegative globs, such as `--glob '!.git'`, exclude entire matching directory\nsubtrees. `--hidden` never disables ignore rules.\n\nIncomplete indexes and legacy indexes without hidden-file coverage fall back\nto scanning. Rebuild with `tgrep index .` or let a current server reconcile\nthem. Older servers without coverage support also cause fallback.\n\nOlder binaries reject the new content-index format. To downgrade, rebuild\nwith the older binary, preferably at a separate `--index-path`.\n\nripgrep can search raw bytes; tgrep searches decoded text, replacing invalid\nUTF-8 sequences with `U+FFFD`. A pattern can match those replacement characters.\nFor UTF-8 repair, text-output columns and byte offsets are mapped back to the\nsource bytes.\n\nJSON output follows ripgrep for invalid UTF-8: such a line is emitted as base64\n`lines.bytes` of the original source bytes, with submatch offsets into those\nbytes and each submatch as `text` when valid UTF-8, otherwise `bytes`.\n`lines.text` keeps each line's own terminator, including `\\r\\n`.\nPaths are always emitted as `path.text`.\nTranscoded encodings use decoded-text offsets rather than original byte\npositions; offsets also exclude stripped BOM bytes.\n\nDirectory searches and indexing skip files larger than **64 MiB** by default;\nripgrep has no default limit. These files are absent from the index and its\nfilename listing, so their matches will not appear.\n\nUse `--max-filesize` to choose another bound, or `--no-max-filesize` to remove\nit. Rebuild or serve the index with the same setting; an uncapped query cannot\nrecover paths that a capped index never recorded. Use\n`--no-index --no-max-filesize` to scan without either restriction.\n\nA directly named file ignores the inherited cap, but respects an explicit\n`--max-filesize`: `tgrep -- pattern ./huge.log` searches that file regardless\nof its size.\n\nSame as ripgrep:\n\n| Code | Meaning | \n|---|---|\n| `0` | At least one match was found | \n| `1` | No matches | \n| `2` | An error occurred (e.g. a path could not be read) | \n\nA match plus an error yields `2`, unless `-q` is set, which yields `0`.\n\nAn ignore file that fails to parse is *not* one of these errors. Like ripgrep,\ntgrep reports it on stderr, skips the offending rule and carries on, leaving the\nexit code determined by the search alone. Suppress the message with\n`--no-ignore-messages`, or with `--no-messages`, which covers it as well.\n\n1. **Indexing** walks the repository with ignore rules, including root-level`p4ignore.ini` , and filters by size and binary extension. It decodes files,\nchecks the first 8 KiB for NUL bytes, and extracts overlapping three-byte\ntrigrams in parallel. Sorted postings map trigrams to candidate files.\n2. **Querying** decomposes regex literals into trigram lookups, intersects or\nunions posting lists, and verifies candidates with the full regex engine.\nConcatenations retain alternation constraints:`React\\.(useImperativeHandle|useReducer)` intersects the prefix's candidates with the union of the branches' candidates,\nwithout expanding combinations of multiple alternations.\nInline case flags participate in planning; unsupported constructs use\nconservative plans rather than excluding possible matches. Case-insensitive\nfixed strings use the same Unicode-aware planning after escaping regex\nsyntax. Both paths require only trigrams safe for the index's ASCII folding;\nif none remain, all indexed files are candidates.\n3. **Serving** combines a memory-mapped`IndexReader` with a mutable`LiveIndex` overlay in`HybridIndex` . Updates take precedence over disk entries.\nClients use JSON-RPC 2.0 over newline-delimited TCP on loopback, with one\nthread per connection. Shared read locks allow concurrent queries but can\ncontend with writers. A`search` request with`\"stream\": true` is answered\nin several lines with the same`id` : results marked`\"partial\": true` , each\nwith the rows of the candidates searched since the last one and the`candidates` and`searched` counts so far, then the final result with the\nremaining rows. The CLI asks for this when it prints one file's rows after\nanother, and prints each part as it arrives.`\"max_results\": N` ends the\nsearch after the file in which the N-th matching line is found, and the\nfinal result then carries`\"truncated\": true` .\n\nThe server's content cache is limited to 50,000 entries and 1 GiB of decoded\ncontent, with a 64 MiB per-entry limit. `--files` combines content-index paths\nwith a filename-only sidecar for admitted paths without searchable content.\n\nAn agent runtime can explicitly attach linked Git worktrees to one repository\ndaemon. They share an immutable committed-tree index and keep private overlays.\nOrdinary `serve`/` index` and unattached queries retain their existing behavior.\nDo **not** point ordinary servers at a shared `--index-path`.\n**New shared-daemon integrations should use\n[managed v2](#managed-shared-lifecycle-opt-in)** with an explicit\n`--shared-policy <FILE>` and the managed client lifecycle.\n\nShared daemon v1 is **deprecated as of tgrep 1.2.1**, not removed.\nOmitting `--shared-policy` still selects v1 and emits one deprecation warning\non stderr per daemon startup; stdout and protocol JSON are unchanged.\nExisting v1 clients retain the **retain-all, fixed-pin** contract below.\nThis is staged retirement, not a silent switch to v2 or an implicit storage\nmigration. No removal date or release is set.\n\n```\nmkdir /trusted/external/tgrep-cache\ntgrep serve --shared /repo --shared-storage /trusted/external/tgrep-cache\n# In another terminal (the runtime owns the foreground daemon's supervision):\ntgrep shared attach /worktrees/session-a --revision <starting-commit> --lease <session-a-token>\ntgrep shared attach /worktrees/session-b --revision <starting-commit> --lease <session-b-token>\ntgrep status /worktrees/session-a\ntgrep -- 'pattern' /worktrees/session-a/src\ntgrep --files /worktrees/session-b\ntgrep shared refresh /worktrees/session-a --lease <lease-from-attach> --changed src/file.rs\ntgrep shared refresh /worktrees/session-a --lease <lease-from-attach> --full\ntgrep shared detach /worktrees/session-a --lease <lease-from-attach>\n```\n\n`attach` returns JSON with the caller's **lease**, view ID, exact generation key,\nrequested commit and readiness. Wait for `\"ready\": true` in `status`; attaching\ndoes not expose the base before reconciliation. Use a unique caller-owned\n`--lease` token (1-128 ASCII letters, digits, hyphens or underscores) per logical\nattachment and retain it **before** sending the request. Retrying that token with\nthe same root/revision/profile returns the original attachment without consuming\nanother lease, even if symbolic `HEAD` moved or the lease budget is full. A lost\nresponse can also be recovered by `detach --lease` without knowing the view ID.\nReusing a live token with another root or revision is rejected.\nWithout `--lease`, the CLI generates a token and prints it on stderr before the\nrequest; capture it and pass it explicitly on retry. Independent compatible\nattachments use different tokens and share the view. The last detach removes only that\ninstance/view's registration, not another worktree or the daemon. Leases do not\nexpire automatically; the runtime must release them or restart the daemon.\nMarker cleanup failures do not prevent lease release: detach reports\n`registration_warning` and leaves unrecognized/corrupt metadata for safe scan fallback.\nBefore removing a worktree, detach all its leases and let in-flight operations\nfinish. On Windows, retained root handles prevent removal while the view is live.\nAn attached view stays pinned across commits/checkouts. Selecting another tree\nfor the same root requires releasing **all** its leases first; incompatible\nreattachment is rejected before building or publishing a generation.\n\nAttachment is the opt-in: subsequent normal search, `--files`, and `status`\ndiscover a versioned registration in the worktree's Git metadata, including from\nsubdirectories. Merely running the daemon does not attach other roots. Nested\nGit repositories/worktrees are discovery boundaries. `--shared` on a query\nexplicitly requires shared discovery; missing, stale, not-ready, wrong-protocol,\nor incompatible registrations **scan the filesystem**, never a legacy index or\nbare base. `status` reports those errors instead of displaying legacy status.\nAn explicit `--index-path` retains legacy intent unless `--shared` is also set\n(then queries scan). `--no-index` always reads the filesystem.\nAn attached CLI invocation discovers its daemon once per worktree and reuses\nthat client for every path argument, revalidating the view with `lookup`.\nLegacy v1 discovery validates the repository with three Git processes. Managed\nv2 discovery reads the gitfile, `commondir` and markers instead of running Git,\nand proceeds only when the canonical common-directory identity matches the\nregistration bound by the daemon's owner-only credential; otherwise it falls\nback to Git discovery. Daemon lookup/search/files/status reuse the attached\nidentity with filesystem boundary/gitfile/common-directory checks and launch no\nGit subprocesses.\nQueries open candidates through the view's retained root handle and verify that\nidentity before and after snapshot callbacks, including empty and filename-only\nresults. Replacing the root closes readiness rather than mixing old candidates\nwith a new directory. Daemon readiness also stays closed until reconciliation\nand checkpoint publication have both finished.\n\nThe v1 profile is raw-Git-blob automatic decoding, tracked regular files and a\n64 MiB size cap. Worktree reconciliation separately applies local ignores,\nhidden visibility, binary classification, and filename-only membership.\nSearch/types/globs/output flags reuse the ordinary matching/output code.\nPositive indexed globs do not reinclude ignored paths; use `--no-index` for\nfilesystem glob overrides. Explicit files, non-default encoding/size/traversal\noptions, `--no-ignore` variants, `--text`, `--binary`, `--follow`,\n`--one-file-system`, `--ignore-file`, passthru, files-without-match and zero-count\noutput scan with a diagnostic rather than claiming incompatible coverage.\n\n**Legacy v1 freshness:** native notifications close readiness as they arrive;\nbounded hints are an optimization, not proof that all events arrived. Every automatic\nmode also fully reconciles after `--poll-interval` seconds (default 120, measured\nafter completion). Native registration failures/budget exhaustion fall back to\npolling. `--watch-mode poll` skips native registration; `--no-watch` disables both\nautomatic modes after initial reconciliation, leaving refresh to the runtime.\n`refresh --changed` returns `processed_epoch`; this acknowledges those changes,\nnot an atomic filesystem snapshot. `refresh --full` also detects missed\nsame-size/restored-mtime changes and Git/ignore configuration changes.\nPersistent reconciliation failures retain not-ready/last-error status and retry\nwith completion-based exponential delays from 1 to 30 seconds. Explicit refresh\nbypasses and resets this backoff; a successful repair resets it too. Status includes\nattempt counts, consecutive failures and the current retry delay.\nNative registration and event filtering include searchable nested `.tgrep`\ndirectories; only the root `.tgrep` storage directory is excluded.\n\nThe daemon bounds views (default 32, `--shared-max-views`), leases (256,\n`--shared-max-leases`), native watches (8192, `--watch-budget`), and hint slots\n(16384, `--watcher-queue-cap`). Watch/hint budgets are partitioned equally by\nthe configured maximum views; unused shares are not borrowed. There is one\nindex/reconcile worker, two independent query workers, bounded connection and\nwork queues, 1 MiB requests and 64 MiB responses. Queries search on their own\nthread pool, so they never wait for threads held by reconciliation, although\nthey still share CPU and disk with it. There is no content cache.\nThe response limit is enforced while producing individual match/context rows,\nfile paths and statistics, including JSON escaping and envelope overhead, and\nagain during final serialization. Daemons advertising `paged_results` (v1) or\nthe `paged-results` capability (managed v2) split a large search or `--files`\nresult into pages of at most that size, ending a page after about a minute of\nwork; clients request each `next_page` cursor in path order and merge the rows.\nEach page reads the then-current snapshot, so a multi-page result is\neventually consistent. Only a single file whose rows exceed the limit, or a\ndaemon without paging, fails explicitly, and CLI queries then scan;\ngeneration mappings and private posting memory still scale with admitted data.\nDaemons advertising `filtered_files` (v1) or the `filtered-files` capability\n(managed v2) also apply `--glob`/`--iglob` and `-t`/`-T` to a `--files` listing\nbefore sending it; an older daemon sends the whole scope and the client filters\nit.\n\nStorage must already exist, be trusted and outside **all** registered worktrees,\nGit metadata and index snapshots. It contains separate `bases` and `overlays`\ntrees. Each successful reconciliation saves only the private delta with its\nexact base/root key. Restart the same daemon, then reattach with the same starting\nrevision: old leases/instance IDs are invalid and restored checkpoints undergo\nfull validation before readiness. Corrupt checkpoints/generations are explicit\nerrors, not base-only results. Published generations/checkpoints are retained:\nthe **v1 store has no online GC**, automatic migration, or checkpoint eviction.\nShared JSON RPC requires UTF-8 canonical worktree roots; unsupported roots,\nincluding symlink aliases to them, fail before attachment or generation publication.\n\nSharing avoids repeated trigram extraction, not all content reads. Tests measure\nthree identical **tracked** files as three reads/decodes and **zero** private\nextractions. A linked worktree additionally reads/decodes and extracts its ordinary\n`.git` pointer file once, for totals of four reads and one private extraction;\nthat file participates in `--hidden` searches and filename listings, unlike a\nreal `.git` metadata directory. Four CRLF-transformed files need **four** private\nextractions, plus one for a linked worktree's gitfile (five total). Full no-op\nverification reuses those overlays with zero new extractions. Smudge/encoding\ntransformations may similarly require full overlays. See the [wire contract and design](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#daemon-wire-contract-v1)\nfor generic runtime integration.\n\n**Recommended for new shared-daemon integrations.** Managed v2 adds owner\nlifetimes, optional base advancement and reference-aware reclamation. Start it\nwith a complete [managed policy](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#managed-policy):\n\n```\ntgrep serve --shared /repo --shared-storage /trusted/external/tgrep-cache \\\n  --shared-policy /trusted/managed-policy.json\ntgrep shared manage /repo hello\ntgrep shared manage /repo namespace.status\ntgrep shared manage /repo maintenance.status\n```\n\nThe policy selects `managed` storage or `compatibility-retain-all`. Managed\ngenerations/checkpoints live in an isolated namespace with a transactional\ncatalog and OS-backed reader protection. Old binaries and unguarded core readers\ncannot open its data, even when files are renamed to legacy names. Compatibility\nmode supports v1 clients but **never collects legacy generations**. Storage mode\nis immutable; omitting `--shared-policy` still selects the deprecated, supported\nv1 daemon, not managed v2.\nOrdinary indexing, non-Git directories and unborn repositories are unchanged.\n\nA managed daemon authenticates every RPC with a rotating per-daemon credential\nstored in an owner-only file; loopback and public namespace IDs alone do not\nauthorize access. The CLI handles this automatically. Direct clients follow\nthe [per-user authentication contract](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#per-user-rpc-authentication).\n\nA generic managed client persists its operation and lease tokens, prepares an\ninstance-bound owner, holds the issued guard with `tgrep shared owner-hold`,\nregisters that claim, then calls `views.attach` through `shared manage`. Operations\nare asynchronous: inspect their receipts and wait for a reconciled ready view.\nAfter attachment, normal search and `--files` discover that view. Do not use\nthe v1 `shared attach` command to create a managed lease.\nA typed owner-hold failure before its `holding:true` handshake is one\n`{\"ok\":false,\"error\":...}` stdout line; retry the same claim only as the\nclient contract linked below specifies.\nThe [v2 client contract](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#managed-client-contract)\nspecifies complete request shapes, recovery and token acknowledgement.\n\nTo migrate an existing integration, implement that client contract rather than only adding a startup flag. Detach all v1 leases and drain in-flight operations and root handles before stopping the v1 daemon. Start v2 with the explicit policy above, establish fresh ownership and tokens, and attach the intended exact revision through the managed lifecycle. Enabling v2 does not convert existing v1 stores or authorize their collection; legacy storage remains retain-all.\n\nManaged reconciliation verifies files in bounded parallel batches, with shared\nnamespace-wide CPU, input-byte and parent-handle admission.\nNamespace operation-worker limits do not need to be raised. Exact checkout bytes,\nidentity checks, cancellation and final readiness gates are preserved; clean Git\nstatus never replaces first-attachment verification. Receipts and status expose\n[phase timings and resource counters](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#bounded-managed-reconciliation).\nAncestor-ID comparisons detect observed substitutions, but are not lifetime\npins: IDs may be reused after batch handles close. Reconciliation retains its\nper-read containment and publication-epoch checks, not an atomic filesystem\nsnapshot or uninterrupted ancestor-lifetime guarantee.\nA [same-binary Windows/ReFS measurement](https://github.com/microsoft/tgrep/blob/main/SHARED_INDEX_BENCHMARKS.md#large-checkout-reconciliation-rc2)\ncompleted a fresh warm-base attachment in 186.144 seconds versus 542.469 seconds\nfor a standalone full build (2.914x), while still reading every required file.\nThat result is one ordered pair without a file-cache flush, not a universal speedup.\nHealthy native managed views use two serving verification tiers. A metadata\ncheck rewalks membership and visibility after at least `--poll-interval`\nseconds (default 120) without reconciliation. It retains content whose trusted\nfile identity, size and mtime still match evidence from a verified read; only\nchanged, hinted or unverified files need content reads and parent batches.\nFull rereads check every admitted file after at least 15 intervals (30 minutes\nby default), repairing same-stat rewrites and missed notifications. Each tier\nalso waits at least 19 times its preceding pass cost before running again,\nlimiting its own steady-state idle duty cycle to about 5% for similar-cost passes.\nThese are minimum delays, not freshness deadlines: queueing, failures and\nvariable pass costs can extend them. An unchanged check keeps the view ready;\n`ready` closes when a difference is found and the repair is published.\nWatcher errors/rescans, explicit full invalidation and concurrent edits still\nclose `ready` first. Managed views are eventually consistent: once published\nthey report `serving: true` and keep answering from their last publication\nwhile `ready` is closed, instead of sending clients to a filesystem scan.\nResults can lag recent edits until the next reconciliation publishes. A\nverification that exhausts its deadline or is\ncancelled leaves the view ready but unverified, reports `failed`/` cancelled`,\nand retries subject to interval and cost backoff measured from that attempt's\ncompletion, without advancing the successful-content age. An unchanged\ncontent pass interrupted by a newer notification retains its verified metadata;\nthe follow-up rewalks the tree and reads the queued hints instead of reopening\nevery unchanged file. Timestamps, clean Git status and an\nunavailable journal never prove that nothing changed. Status reports\n`last_verification` with its outcome, tier, ages and effective delays, and `watch_events` counts\nwatcher input by kind, metadata-only notifications filtered as unchanged, file\nnotifications kept and why, invalidated paths and epoch advances. `queued_work` shows whether the view's\naccepted work is running or queued, and in which scheduling class; work for a\nview that is not ready runs ahead of other views' background verification.\nSearches are not queued work: they run on their own threads and thread pool,\nso a running reconciliation or verification slows them only by sharing CPU\nand disk. Use `--no-index` for current disk bytes.\n\nOn Windows/macOS, managed views use recursive worktree and Git metadata-root\nsubscriptions, without pre-enumerating descendant directories. The unchanged\nper-view watch budget counts these roots, not their descendants; typically one\nsubscription covers a main worktree and two cover a linked worktree. New nested\ndirectories are covered automatically. Linux/Android keep bounded per-directory\nregistration and may still fall back on large trees. Status exposes `watch_count`,\n`native_registration_mode` and `native_watch_budget_per_view`; the latter two are\nin `reconciliation_policy`. OS resource limits remain independent of this budget.\nSee [managed registration and update policy](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#advancing-and-reconciling-views).\n\nExplicit `--watch-mode poll` and actual native-watcher failure/budget fallback\nuse the same two tiers and cost backoff following completion.\n`--no-watch` disables watching and polling, not initial\nverification or explicit refresh. `reconciliation_policy` distinguishes these\nper-view modes and namespace monitor counts. Polling views close `ready` for\neach pass but keep serving their previous publication; healthy native views\nstay ready through theirs. These\nrecurring-mode changes postdate the immutable benchmark source and are not\nmeasured there.\nLegacy v1 and ordinary-server refresh policies are unchanged.\n\n`views.advance` prepares and reconciles a complete replacement while unrelated\nready views continue serving. The current exact commit, physical generation,\nview version and checkpoint commit together before acknowledgement. Queries\nalready holding an old snapshot retain it. Adaptive advancement is optional,\nuses the worktree's own exact `HEAD`, and requires measured benefit, hysteresis\nand cooldown; untracked-only or ineffective transformed changes do not repeatedly\nrebuild the base. Any fixed-pin participant blocks advancement.\n\nCollection withdraws eligible checkpoints before releasing their generation\nreferences, then retires and removes unprotected physical incarnations in bounded\npasses. Live readers, active ownership and persistent cache references take\nprecedence over byte targets. A shortfall is reported, not solved by deleting\nlive data. Owner death requires acquisition of the original OS guard; missing,\nreplaced or inaccessible proof is **unknown**, not death. Legacy leases never\ngain a timeout. Releasing a lease does not imply escaped readers or worktree\nhandles have drained: inspect detach results before removing a worktree.\n\nExternal storage remains manageable after the repository is gone:\n\n```\ntgrep shared discover /trusted/external/tgrep-cache\ntgrep shared maintenance /trusted/external/tgrep-cache/tgrep-managed-v2/<repository-id> namespace.status\ntgrep shared maintenance /trusted/external/tgrep-cache/tgrep-managed-v2/<repository-id> collections.preview\n```\n\nPreview is not deletion authorization. Mutation requires `--apply`, persisted\nnamespace-scoped tokens, current policy/allocation versions and bounded\n`collections.run` or `maintenance.recover` requests. A maintenance `session`\nkeeps paginated inspection under one ownership lifetime. Startup and maintenance\nshare the namespace's exclusive lock; foreign entries are preserved, not swept.\nSee [offline maintenance and durability](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md#managed-maintenance-and-durability)\nand [native qualification](https://github.com/microsoft/tgrep/blob/main/CONTRIBUTING.md#managed-lifecycle-qualification).\n\nSee the [shared worktree index design](https://github.com/microsoft/tgrep/blob/main/SHARED_WORKTREE_INDEXES.md) for\narchitecture diagrams, the agent runtime boundary, base-generation lifecycle,\nand both the legacy and managed lifecycle contracts.\n\n`tgrep-core::generations` manages immutable committed-tree bases:\n\n```\nuse std::path::Path;\nuse tgrep_core::generations::{GenerationManager, IndexingProfile, Repository};\n\nlet repository = Repository::discover(Path::new(\".\"))?;\nlet manager = GenerationManager::new(repository)?;\nlet first = manager.ensure(\"HEAD\", IndexingProfile::default(), None)?;\nlet next = manager.ensure(\"main\", IndexingProfile::default(), Some(&first.generation))?;\n// Keep this exact pin with the synchronized worktree registration below.\nlet pin = next.generation;\n```\n\nRepository identity is the **canonical Git common directory**, shared by linked\nworktrees but not independent clones. Git is required; commands use arguments,\nnot shell interpolation, and ignore ambient `GIT_*` overrides. Symbolic revisions\nsuch as `HEAD` resolve in the discovered worktree. Keys contain repository\nidentity, exact committed tree OID, indexing profile, and format/schema versions;\ncommit OIDs are retained for diagnostics. `new` stores generations below the\ncommon directory's `tgrep-bases-v1`. `with_storage` accepts an existing trusted\ndirectory outside registered worktrees and Git metadata.\nBoth that parent and its effective repository-identity subdirectory are checked;\nthe effective directory cannot itself be a linked worktree or index snapshot.\n\nThe current profile indexes **raw Git blobs** with the existing automatic text\ndecoder. It covers all tracked regular files, including hidden, ignored, and\nextension-filtered paths: a superset, not a worktree's searchable membership.\n`entries()` records each tracked path's mode, object OID, size and classification.\n`Indexed { content_id }` includes empty/short files; `Binary`, `TooLarge`, and\n`NotRegular` have no content-index entry. Symlinks and gitlinks are never followed.\nNon-UTF-8 tracked paths and paths the platform/index cannot represent return\nexplicit unsupported errors; repository roots preserve their native identity.\nClean Git status does **not** establish compatibility with CRLF, encoding, LFS\nor smudge transformations. `entry.matches_worktree_bytes(bytes)` compares the\ndecoded identity only; it proves neither stable filesystem reads nor visibility.\n\nA compatible predecessor reuses unchanged blob postings and masks, including\ncopies/renames, while extracting only new content through one Git batch process.\nDestination mode and size eligibility are recomputed. Without a predecessor,\na missing generation requires a full build. `EnsureResult.stats` reports actual\nblob reads/extractions, bytes, reused files/postings, and publication/reuse.\n`predecessor_posting_lists_read` counts actual predecessor traversal; it is zero\nwhen no indexed paths can reuse postings, including when only empty/short files\nare unchanged. Their paths and content identities still reuse normally.\nPosting presence is collected during existing strict snapshot validation;\nno persisted metadata or index-format change is required.\nAn OS file lock deduplicates cooperating starters across processes; live\ngeneration pins share one in-process `Arc<Generation>` and `Arc<SharedBase>`.\nThe spill sorter bounds posting accumulation; one raw/decoded blob and its\nextracted masks are held at a time. Removing the size cap can therefore require\nsubstantial memory. Publication still streams a complete new index.\n\n`open(key)` reopens an exact generation; `list()` returns validated published\nkeys. Complete staging directories are validated and atomically renamed before\ndiscovery. Corrupt/incomplete final generations error rather than being replaced;\nabandoned staging directories are not discoverable. File contents are synced,\nbut parent-directory power-loss durability is not guaranteed.\n**Retention is explicitly `RetainAll`: no published generation is deleted**, even\nafter pins drop. Persist the key with retained overlay checkpoints. Online GC,\ncheckpoint eviction remain deferred; daemon request/view budgets are described above;\noffline cleanup requires stopping all users and discarding dependent checkpoints.\nStorage and its ancestors must not be externally renamed, modified or removed\nwhile in use. Do not run mutable index builders against generation directories.\n\n`tgrep_core::worktrees` provides the core registration and synchronization layer:\n\n```\nuse tgrep_core::query::build_query_plan;\nuse tgrep_core::worktrees::{WorktreeOptions, WorktreeView};\n\nlet view = WorktreeView::new(Path::new(\".\"), pin, WorktreeOptions::default())?;\n// An agent runtime subscribes to changes NOW, before the first refresh.\n// Forward file/subtree events to invalidate_path; overflow/config changes\n// and unknown events to invalidate_all. The core does not create a watcher.\nlet stats = view.refresh()?; // initially a full verification; now ready\n\nlet plan = build_query_plan(\"needle\", false)?;\nview.with_snapshot(|snapshot| -> std::io::Result<()> {\n    for path in snapshot.candidates(&plan, \"\", false) {\n        let file = snapshot.open_file(&path)?; // uses the view's retained root handle\n        // Bounded-read `file`, auto-decode and run your final matcher here,\n        // buffering results until with_snapshot succeeds; or use a private cache.\n    }\n    Ok(())\n})??;\nlet files = view.with_snapshot(|snapshot| snapshot.files(\"\", false))?;\n// Candidates are root-relative paths, not final matches. Do not read a joined\n// pathname with ordinary filesystem APIs: a raced link could leave the worktree.\n```\n\nThe root must be the actual worktree root in the pin's repository, not a\nsubdirectory, bare repository or independent clone. `root()`, `repository()`\nand `generation()` preserve its canonical identity and exact pin. Each view\nkeeps private whole-file replacements and tombstones relative to **that pin**,\nnot current `HEAD`; committing an edit does not clear its override. Missing,\nsparse, ignored and ineligible base paths are hidden. Membership and visibility\nuse the existing hidden-inclusive walker and a frozen case-insensitive tracked\nexemption snapshot. `files()` includes eligible filename-only binary paths.\nQuery `prefix` is empty or a root-relative directory ending in `/`.\n\n`invalidate_path(relative_path)` immediately closes the query gate and queues\na bounded file/subtree hint (both paths for renames). Case aliases trigger\nconservative verification. Non-ASCII hints cover their longest ASCII directory\nancestor; overflowing queues coarsen to ancestor hints. A full pass is required\nonly when those hints cannot be represented within the budget.\nAccepted trailing/repeated separators and interior `.` components are normalized,\nso `dir/` still invalidates the entire `dir` subtree. Absolute paths, parent\ncomponents, and leading `.` remain explicit errors that force full repair.\n`invalidate_all()` handles native watcher overflow and full missed-event repair.\n`invalidate_tree()` requests a membership/metadata walk without rereading\nunchanged contents; Git/ignore changes use this walk too.\n`refresh()` rewalks membership/visibility and processes hints; without hints or\na queued tree check it does full content\nverification. `reconcile_full()` always verifies all admitted bytes, including\nsame-size/restored-mtime edits, assume-unchanged and skip-worktree files.\n\nConstruction and checkpoint restoration are **not ready**. A successful refresh\natomically publishes overlay, filenames and visibility. `status()` exposes\nreadiness, invalidation/published epochs and pending/tree/full work. A concurrent\ninvalidation causes `ChangedDuringReconcile`, not stale ready publication:\nretry or scan. There is one attempt per call, never an unbounded churn loop.\nEvery reconciliation advances the epoch, including refreshes without hints;\nthe published epoch acknowledges all earlier invalidation tokens.\nDiscovery/read errors likewise leave the view unavailable and force full retry.\nReconciliation pins a root directory handle and opens only regular files:\nUnix uses component-relative no-follow, nonblocking opens; Windows guards\nancestor handles against replacement and checks resolved handle\ncontainment before reading. Detected root identity changes and read-path\nswaps leave the view not-ready. Windows retains the root guard until view drop, so\nan agent runtime should release registrations before removing or renaming a\nworktree. Ordinary servers also retain their root guard for their lifetime:\nstop `tgrep serve` before removing or renaming its served root on Windows.\nThe shared helper is `tgrep_core::rooted::RootedDir`\n(`open`, `open_file` with a relative path, and `verify_root`); ordinary serving\nretains one per server and reuses it across build, watcher and verification reads.\n`WorktreeSnapshot::open_file` uses the view's existing reader, not a new root\nregistration per candidate. Neither API freezes file contents.\nLocal-index and shared content queries reuse one pinned ancestor chain for at\nmost 64 consecutive sibling candidates, without reordering or limiting results.\nThey still read and match one file at a time and verify the ancestors when the\nbatch ends. Shared queries size groups so that a small search still uses the\nquery threads: the candidate count divided by the smaller of six and the thread\ncount, at least 8 files per group. A shared group of two or more siblings pins\nits ancestors through one root-verified snapshot and opens the siblings through\nthat pin, without per-candidate snapshots; `finish` verifies the root and\nancestor identities again, and the final snapshot verifies the root. A single\ncandidate still opens through its own snapshot. Every read still revalidates\nthe query first, and a failed open counts as a filesystem failure only after\nthat check passes. Generation/root protection and the final epoch check are\nunchanged. `RootedDir::read_batch` exposes this scoped reader; managed callers\nobtain a `WorktreeSnapshot::candidate_batch`, open siblings with\n`CandidateBatch::open` (or `open_candidate_in` through a snapshot of the same\nview), and call `finish` before publishing buffered results. A batch stays bound\nto the root and generation it pinned. Reply and file-size limits are unchanged.\nMetadata discovery rejects unrepresentable native names before conversion:\nnon-Unicode paths and literal Unix backslashes cannot alias other indexed paths.\nOrdinary full scans retain native paths and remain available as the fallback.\n`with_snapshot` holds readiness and overlay guards through candidate-ID\nresolution, and verifies the pinned root before and after the callback, even for\nempty/file-only results. Verification failure closes readiness and queues full\nrepair. Candidate-open failures are recorded too: `with_snapshot` returns an\nouter I/O error and invalidates readiness before releasing the guard, even if\nthe callback swallowed the inner error or subsequently opened another file.\nNo live IDs or mutable `HybridIndex` escape. A callback may return an\nowned read-only file handle for bounded matching outside the guard; before\npublishing buffered results, reenter `with_snapshot` and reject a changed epoch.\nLater reads through that handle remain caller-owned: report read errors and call\n`invalidate_all()` after leaving the guard rather than publishing partial results.\nDo not reenter the view from its closure. A refresh acknowledges processed hints,\n**not an atomic filesystem snapshot**. For verification independent of\nnotifications, use explicit or periodic full repair. Managed metadata checks\nand content rereads have separate minimum intervals and cost backoff, not a\nfixed freshness bound; no-watch callers must explicitly refresh.\nFinal reads can race subsequent edits.\n\nFull verification reads, auto-decodes and hashes checkout bytes; clean Git\nstatus, blob identity and index stat data are never byte-equivalence proofs.\nMatching decoded content reuses base postings without extraction. Verified\nrenames/copies can copy base masks in one streaming posting pass; unchanged\nprivate overlays also avoid extraction. A hinted refresh can avoid rereading\nunaffected, previously verified files under the event-driven freshness contract,\nbut still performs a metadata/membership walk. `ReconcileStats` separates\nreads/bytes/decodes, actual extraction calls, base and overlay reuse, copied\nfiles/postings, content reads avoided, and `metadata_reused` (paths needing\nneither a content open nor a verification parent batch). Metadata reuse is an\neventual-consistency optimization, not proof against concurrent writes:\ndirectory-entry metadata can lag an active writer on Windows, and same-stat\nrewrites need a hint or the full reread tier.\n`hint_lookups` counts ordered-set probes: each file checks its normalized path\nand ancestor prefixes, at most one probe per component rather than a scan of\nall queued hints. Each probe is logarithmic in the hint count. Even a hinted\npass opens eligible file handles to verify regular-file metadata safely;\navoided content reads do not mean zero filesystem I/O.\n\n**Raw LF bases versus CRLF/smudge checkouts can require an all-file overlay**,\neven for equal committed trees and clean Git status. Position and next-byte\nmasks make line-ending normalization unsafe. Regression fixtures measure zero\nextractions for three byte-identical tracked files, but four for four transformed\ntracked files. A linked worktree's plain `.git` file adds one private extraction\nin either case; subsequent unchanged reconciliation reuses those private postings. There is no\ncross-view transformed-content cache. Preparation retains per-path evidence\nand changed-file masks until atomic publication; removing the size cap increases\nper-file memory, and widespread transforms can make the private overlay large.\n\nFor persistence, configure an existing dedicated `checkpoint_directory` in\n`WorktreeOptions`. Construction, restoration and saving explicitly reject\nnon-directory checkpoint paths. `save_checkpoint()` requires readiness and atomically writes\nonly `overlay.json`: private postings/tombstones plus exact generation key, base\nfingerprint and canonical root, through the existing directory-bound publisher.\nThe entire checkpoint directory, `.tgrep`, Git metadata directories and the generation store\nare excluded, even with `no_ignore`. A linked worktree's plain `.git` pointer\nfile remains eligible under ordinary walker rules: `--hidden` exposes its\nfilename and searchable text unless ignored or over the size cap. This does\nnot expose the metadata directory it names. Custom storage directories belong in\n`walk.exclude_paths`. Checkpoint storage and ancestors must remain trusted and\nnot externally renamed while in use. The directory cannot be an index snapshot,\nGit metadata, or a worktree ancestor. `WorktreeView::restore(root, exact_pin, options)` rejects missing, malformed, wrong-key and wrong-root checkpoints.\nSuccessful restoration still requires subscribing and full reconciliation;\nrestored overlays have no trusted read evidence and may re-extract private\npostings on that first pass. Generation retention remains `RetainAll`.\n\n`tgrep-core::shared::SharedBase` is the first building block for sharing one\ncontent index across worktrees. Open a complete, current-format index in an\n**immutable snapshot directory** once, then call `create_worktree(root)` for\neach worktree. The returned `HybridIndex` instances share the same\n`Arc<IndexReader>` (including the path table), but have independent roots,\nlive postings, and deletion tombstones. Cloning `SharedBase` does not copy the\nbase index.\n\nShared-base opening rejects mismatched empty lookup/posting sections and\nmetadata counts inconsistent with the opened index. Legitimately empty\nindexes and files too short to produce trigrams remain supported. Shared\nsnapshots also require aligned, contiguous posting ranges covering `index.bin`,\nvalid trigrams, strictly increasing valid file IDs within each posting list,\nand nonzero location masks; ordinary readers retain their existing validation\nbehavior.\n\nThe caller must populate each overlay before exposing it to searches:\nindex whole changed/new files using `view.live.upsert_file`, and hide deleted\nor ineligible base paths using `view.live.delete_file`. Include committed\nbranch differences, staged and unstaged edits, and eligible untracked files,\nnot just `git diff HEAD`. Only reuse base postings when their decoded content\nmatches the worktree's indexing semantics; Git checkout filters, encoding,\nand line-ending conversion can change that content. Clear a path's override\nwith `clear_reconciled_paths` only after proving it matches the base again.\n\n`save_overlay(&view, checkpoint_path)` atomically saves only the worktree's\nlive postings, masks, and tombstones. It never merges changes into the base.\n`restore_worktree(root, checkpoint_path)` checks the checkpoint version,\ncanonical root, and a fingerprint of the base's path table, lookup table,\nand postings. Wrong-base, wrong-root, missing, and malformed checkpoints\nreturn errors rather than silently revealing base entries. Opening the base\ncomputes its fingerprint once; attaching more worktrees does not rescan it.\nCheckpoint parent directories must already exist and be outside the base\nsnapshot directory. Repeated saves atomically replace the existing checkpoint,\nincluding on Windows. Base-directory exclusion checks directory identities,\nnot just pathname prefixes. On Unix, staging, replacement, and cleanup use the\nopened parent directory handle. On Windows, open handles prevent renaming or\ndeleting the canonical parent and its ancestors until publication finishes.\nReplacing a parent pathname cannot redirect a save into the shared base.\nPaths with trailing separators or `/.` are rejected rather than normalized\ninto filenames.\nUnicode worktree roots retain the existing JSON string representation;\nnon-Unicode roots use tagged Unix bytes or Windows UTF-16 units to preserve\ntheir exact identity. Existing Unicode-root checkpoints remain readable;\nolder readers cannot restore the new non-Unicode representation.\nAtomic replacement does not guarantee power-loss\ndurability: file contents are synced before replacement, but the parent\ndirectory is not synced afterwards. A successful save may be lost after a\nsystem crash; callers must reconcile or rebuild stale/missing checkpoints.\n\nThe lower-level `SharedBase` API alone does not synchronize a checkout; use\n`WorktreeView` for the reconciliation/readiness contract above. Neither API\ncreates native watchers or content caches. The opt-in shared daemon supplies\nworktree registration, native/poll refresh and CLI routing separately.\nThe existing single-root RPC protocol, index format, and server are unchanged.\nDo not point existing servers at a common `--index-path`: their\npublication path still writes a complete index. Keep shared base files\nimmutable for the lifetime of every view or query holding their reader.\n\n| File | Description | \n|---|---|\n| `lookup.bin` | Sorted 16-byte entries: `trigram(u32) + offset(u64) + length(u32)` | \n| `index.bin` | Concatenated 6-byte postings: `file_id(u32) + loc_mask(u8) + next_mask(u8)` | \n| `files.bin` | Version 3 header, then `file_id(u32) + path_len(u16) + path_bytes` ; legacy headerless tables remain readable | \n| `files-extra.bin` | Version 2 filename-only paths, visibility, and file-table identity | \n| `meta.json` | Version, file/trigram counts, timestamps, coverage, visibility, and file-table identity | \n| `filestamps.json` | Per-file metadata, content identities, and version evidence for reconciliation | \n| `serve.json` | Server PID and TCP port (for client discovery) | \n| `serve.lock` | Exclusive lock preventing multiple servers from owning the same index | \n\n| Directory | Contents | \n|---|---|\n| `tgrep-core/` | Traversal, decoding, trigram extraction, index storage, and query planning | \n| `tgrep-cli/` | CLI parsing, matching, output, server, and integration tests | \n| `scripts/` | Benchmarks, agent integration, and development utilities | \n| `fuzz/` | Fuzz targets for index reading and query/trigram parsing | \n\n```\ncargo build --release --locked  # build optimized binary\ncargo test --workspace          # run tests\nmake check                      # check formatting and run clippy\nmake install                    # install to ~/.cargo/bin (Unix)\ngit clone https://github.com/microsoft/tgrep.git\ncd tgrep\ncargo install --path tgrep-cli --locked\n```\n\nKeep `vendor/ignore` in the checkout: it contains the locked dependency with a\nsmall native Git-metadata path fix. Source installs and release builds use it\ndirectly; see its [provenance and patch notes](https://github.com/microsoft/tgrep/blob/main/vendor/ignore/PATCHES.md).\n\n```\nbrew install tgrep\n```\n\nDownload from [GitHub Releases](https://github.com/microsoft/tgrep/releases)\nfor Linux, macOS (Intel & Apple Silicon), and Windows.\n\nDownload the archive for your architecture, extract it to a temporary\ndirectory, then copy the executable into a directory on `PATH`.\n\n```\n# Linux (x86_64)\ntmpdir=\"$(mktemp -d)\"\ngh release download --repo microsoft/tgrep -p '*x86_64-unknown-linux-musl.tar.gz' -D \"$tmpdir\"\ntar xzf \"$tmpdir\"/tgrep-*-x86_64-unknown-linux-musl.tar.gz -C \"$tmpdir\"\ninstall -Dm755 \"$tmpdir/tgrep\" \"$HOME/.local/bin/tgrep\"\nrm -rf \"$tmpdir\"\n\n# macOS (Apple Silicon)\n# For Intel, replace aarch64 with x86_64.\ntmpdir=\"$(mktemp -d)\"\ngh release download --repo microsoft/tgrep -p '*aarch64-apple-darwin.tar.gz' -D \"$tmpdir\"\ntar xzf \"$tmpdir\"/tgrep-*-aarch64-apple-darwin.tar.gz -C \"$tmpdir\"\nmkdir -p \"$HOME/.local/bin\"\ninstall -m755 \"$tmpdir/tgrep\" \"$HOME/.local/bin/tgrep\"\nrm -rf \"$tmpdir\"\nphp\n# Windows x64 (PowerShell); for ARM64, replace x86_64 with aarch64.\n$download = Join-Path $env:TEMP (\"tgrep-dl-\" + [guid]::NewGuid())\nNew-Item -ItemType Directory -Path $download | Out-Null\ngh release download --repo microsoft/tgrep -p '*x86_64-pc-windows-msvc.zip' -D $download\nGet-ChildItem $download -Filter '*.zip' | ForEach-Object {\n    Expand-Archive -LiteralPath $_.FullName -DestinationPath \"$HOME\\.cargo\\bin\" -Force\n}\nRemove-Item -LiteralPath $download -Recurse\n```\n\nEnsure `$HOME/.local/bin` (Unix) or `$HOME\\.cargo\\bin` (Windows) is on `PATH`.\n\nThis project welcomes contributions and suggestions.  Most contributions require you to agree to a\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\nthe rights to use your contribution. For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.", "url": "https://wpnews.pro/news/faster-grep-for-agents", "canonical_source": "https://github.com/microsoft/tgrep", "published_at": "2026-12-03 09:14:56+00:00", "updated_at": "2026-12-03 09:47:26.964565+00:00", "lang": "en", "topics": ["ai-tools", "ai-agents", "developer-tools", "ai-products"], "entities": ["Microsoft", "tgrep", "GitHub Copilot CLI", "ripgrep", "Codex", "pi"], "also_reported_by": [], "takeaway": "tgrep's trigram index beat ripgrep in 17 of 18 repo/platform combinations with 0.93x to 51.9x speedups on already-built indexes, but indexes lag filesystem changes, so pass --no-index when a search must read current files.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/faster-grep-for-agents", "markdown": "https://wpnews.pro/news/faster-grep-for-agents.md", "text": "https://wpnews.pro/news/faster-grep-for-agents.txt", "jsonld": "https://wpnews.pro/news/faster-grep-for-agents.jsonld"}}