---
title: Code index architecture
lastModified: '2026-12-01T12:08:18.000Z'
description: 'This page is the inside view of the code index: how files become chunks, symbols and edges, and how the two tiers stay current.'
---

This page is the inside view of the code index: how files become chunks, symbols and
edges, and how the two tiers stay current. What each op answers, the languages and their
depth, and how to read `as_of` are in the
[code index overview](/docs/features/code-index/overview) and
[freshness](/docs/features/code-index/freshness). Running it (clones, backfills, the compiler tiers)
is in [code index operations](/docs/operations/code-index-operations).

## Goals and non-goals

| Goals                                                                                                    | Non-goals                                                                                            |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| Per-merge freshness of the fast tier from a poll of a local bare mirror; no inbound webhook.             | Indexing a working tree. Uncommitted and unpushed changes are never in the index.                    |
| Exact call, override and inheritance edges where a compiler indexer exists; graded heuristics elsewhere. | Running a compiler in the server process. SCIP producers run in subprocesses of the workers process. |
| Idempotent ingest: unchanged bytes yield the same rows and cost no embedding.                            | A general-purpose code host. The index is read-only reference data keyed by namespace.               |
| Every answer names the commit and tier it read, and says why an empty answer is empty.                   | Hiding staleness. A lagging tier is reported.                                                        |
| A new language lands without re-indexing the others.                                                     | Equal depth for every language ([languages](/docs/features/code-index/overview)).                    |

## One namespace, one branch

A code namespace is one repository branch at one commit. It has `kind='code'` in
`loom.namespaces` (`code/app/index/registry.py`, `ensure_registered`), holds no
memories, and keys every `code_*` row by `(org, namespace)`. Loom keeps one bare git
mirror per repository, a cache of the remote recorded in ClickHouse: `code_ingest` clones
a missing one (or `loom code init` does, ahead of time) and fetches it on every pass.
`server/code/app/index/gitrepo.py` shells out to `git`; it has no working tree and writes
nothing except `fetch`. Branches of one repository share the mirror.

CLI backfills resolve sibling imports and re-exports from the mirror at the pinned
backfill commit, including their edge reconciliation pass. Search chunks can carry
doc comments and overlapping context, so their concatenation is not authoritative
source text for parsing a sibling module.

Sibling text, Python layouts, workspace registries, module indexes, compiler configs
and barrel targets cache by tenant and namespace plus the pinned Git directory and
commit. Concurrent passes share a pending read only within that source. Indexed-text
reads use a separate cache scope. Each cache expires entries and bounds their count;
the text cache also bounds the bytes it holds. Python ingestion resolves its layout
before chunking and passes the layout snapshot to facet extraction; chunking threads
do not access the mutable cache.

A history read (`blame_range`, bisect, `first_build`, a lesson's code check) on a host
without the mirror clones it once in the background
(`server/code/app/index/mirrors.py`, `history_dir`). A read that names its op waits up
to 10 s for the clone it started, or what is left of the op's latency budget, whichever
is less; the others answer `no_git_mirror` until it lands. After the clone, the ledger's merge
commits the clone lacks are fetched by sha and pinned: a merge made on a staging branch
upstream has since deleted is in the worker's mirror (never pruned) but not in a fresh
clone. A present mirror answers as it is; one that lacks the indexed head fetches the
branch in the background. A head that is not the branch's (a PR head) is not fetched.

This puts a full copy of every mirror on every serving host asked about it, which is
the point (any host answers history reads after a move or a scale-out) and the cost
(disk per host: a repository's size each). `LOOM_CODE_HISTORY_CLONE_ON_READ=false`
turns it off: only the worker's host clones, and a history read anywhere else answers
`no_git_mirror`.

Repository entries come from two sources, merged:

| Source            | Read by                           | Notes                                                                                                      |
| ----------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| Environment       | `code/domain/index/repos.py`      | `LOOM_CODE_REPOS_JSON`, or the scalar `LOOM_CODE_*` settings.                                              |
| `loom.code_repos` | `code/app/index/repo_registry.py` | Self-service rows, by `row_kind` (below). A private remote's token is stored encrypted and never returned. |

A `loom.code_repos` row's `row_kind` says what it is:

- `page`: a branch added from the page. It keeps an operator entry off its namespace,
  removed or not.
- `access`: an operator entry's classification and join policy.
- `''`: a row written before the column, read as the access row of an operator entry's
  namespace and as a branch added from the page elsewhere.

`configured_repos()` reads an in-process snapshot refreshed at boot, on every ingest
pass and after an add. Until the snapshot's first read it raises `RegistryUnread`
(self-service on), since the entries a page namespace skips are not known yet; the
modules that decide access read `config_entries()`, which lists the entries before that
read with none org-readable (`tests/unit/test_repo_snapshot_contract.py`). An op that
needs the full list answers 503 in that window; memory reads, search and
`memory.for_file` answer without code links. A code call naming no namespace defaults to
`LOOM_CODE_NAMESPACE` only when no member added that namespace from the page. Retiring
an entry (`code/app/index/retire.py`) deactivates its rows, runs an erasure saga over
every `code_*` table for the namespace, and removes the mirror when no other entry uses
it on the host that served the call; every other host's sweep removes its own copy.

## Git mirrors on every replica

Every serving process can answer a history read (blame, bisect, citations, PR
overlays, commit coverage), so every host keeps its own bare mirrors
(`code/app/index/mirrors.py`). A mirror is a cache of its remote: ClickHouse names the
remote, and any host can rebuild the mirror from it.

- **Warm-up.** At boot each process clones the mirrors of the indexed entries it lacks,
  `LOOM_CODE_MIRROR_WARMUP_CONCURRENCY` at a time, each after a random wait of up to
  30 s, so N replicas starting together do not all clone from GitHub at once. Clones
  run in the background: readiness does not wait for them.
- **The cost of a new disk.** A host with an empty `LOOM_CODE_REPOS_ROOT` makes a full
  bare clone of every indexed repository (several GB for a large one) before its
  history reads answer. Warm-up stays on by default because a new replica must build
  its caches without an operator; put `LOOM_CODE_REPOS_ROOT` on a volume that outlives
  a rollout to pay it once per volume, not once per pod. The clones are full, not
  `--filter=blob:none`: a partial clone fetches each missing blob from the remote while
  `git blame` runs, which makes a history read a network read and would reach the
  remote outside the repository-job sandbox.
- **The gate.** Every history read goes through `mirrors.history_dir`, which returns
  the mirror or why there is none. Until the mirror
  is there the read answers `no_git_mirror: cloning <entry>` (or why it will not be
  cloned here) instead of a git error, and starts the clone if none is running.
  `LOOM_GIT_HISTORY=none` turns history off on a host: those reads answer
  `no_git_history`.
- **The host loop.** Only the leader asks the remote what changed (`ls-remote` of the
  extra branches and the PR heads). What its pass fetched is in ClickHouse: each
  entry's branch tip (`clone_head`), the open PRs' heads (`code_gh_items.head_sha`) and
  the ledger's merges. Every `LOOM_CODE_MIRROR_FETCH_INTERVAL_S` each host reads those
  and fetches, by name, only the branches and PR heads its mirror holds at another sha,
  plus a page of ledger merges it lacks; a host that is current makes no network call.
  Extra branches are not followed on other hosts: a fresh clone carries every branch
  the remote had, and the merges on them come through the ledger. One process per host
  does each mirror's round, and every fetch into a mirror (the pass's, the host loop's,
  a read's) holds the mirror's `.fetch-lock`; the pass's fetch also counts as the host's
  round for the interval. The same loop runs `git gc --no-prune` when due and sweeps
  `LOOM_CODE_REPOS_ROOT`: mirrors, `checkout-*` trees and mirror lock files no active
  entry names (restricted entries included) and half-done clones. It sweeps nothing
  when the registry cannot be read.
- **Sandbox.** A host without the repository-job sandbox clones or fetches a
  self-registered entry with a network remote only where
  `LOOM_CODE_SELF_SERVICE_GIT_UNSANDBOXED` is set, on the read path as in the worker
  (`compiler_tier.unsandboxed_skip`). The entry's compiler tiers are skipped there
  either way.
- **A forward proxy.** With `LOOM_CODE_GIT_PROXY_URL`, every clone and fetch above
  (the pass's, the host loop's, a read's), the `ls-remote` before an add and a
  checkout's submodule update connect through the operator's proxy as the entry's
  `git_proxy_identity`, else the deployment's default (`code/app/index/git_proxy.py`).
  The proxy and its password are added where a repository job starts as a plain
  process (`sandbox.run_job`), to the environment of that one git process: not to
  `auth_env`, whose git settings a build harness copies, and not to a sandboxed job,
  where repository code runs. A job that cannot go through the proxy is refused with a
  fixed reason, so git never connects directly; a host that runs the sandbox, whose
  egress proxy is not chained through this one, refuses network git while the setting
  is set. A host round fetches a shared mirror as its first entry
  ([git through a forward proxy](/docs/operations/code-index-operations#git-through-a-forward-proxy)).
- **Merges the remote lost.** A ledger merge the remote no longer serves ("not our
  ref" in two calls, so one transient refusal does not count) is recorded in the
  mirror (`loom-unpinned-merges`), never asked for again, and
  counted in `/v1/health?include=mirrors` (`mirrors.unpinned_merges`) and `loom doctor`.
- **The leader** clones a missing mirror in the background too, so one long clone
  does not hold up the other entries of its pass; an indexed entry keeps its
  Repositories-card stage while its mirror is cloned again on a new host.
- **Erasure.** Mirrors and checkouts hold repository content, not memory content: the
  erasure census does not count them. A removed repository's copies go with the sweep
  on each host.

`/v1/health?include=mirrors` carries `mirrors`: how many of this host's mirrors are `ready`
and `cloning`, and `failed` and `absent` counted by reason. It answers without a token, so
it names no entry. Disk use is the size of every mirror on every host: N replicas hold N copies.

## Components

```mermaid
flowchart LR
  GH["Git remote"] -- fetch --> BC[("bare mirror")]
  BC --> CI["code_ingest<br/>(fast tier)"]
  CI --> P["parse: treesitter.py,<br/>lang_* lanes"]
  P --> CH["chunker.py"]
  P --> ED["edges_treesitter.py,<br/>dependents.py"]
  CH --> CC[(code_chunks)]
  P --> CS[(code_symbols)]
  ED --> CE[(code_edges)]
  CI --> CF[(code_files)]
  CI --> ST[(code_index_state)]
  BC --> SD["code_scip_*_delta<br/>(compiler tier)"]
  SD --> AP["scip_delta apply"]
  UP["code.scip_ingest"] --> AP
  AP --> CS
  AP --> CE
  CC -. "stub dim=0" .-> ER[code_embed_recovery]
  ER --> CC
  API["GitHub API"] --> PH[code_pr_history]
  PH --> PRT[(code_pr_history<br/>code_pr_reviews<br/>code_gh_items)]
```

## Fast tier: `code_ingest`

`server/code/workers/ingest.py` polls every `LOOM_CODE_INGEST_INTERVAL_SECONDS`;
`code.refresh` triggers a pass from CI. Per entry, each pass:

1. **Fetches** the mirror and walks first-parent commits from the `git_head` watermark
   in `code_index_state` to the tip, oldest first, at most
   `LOOM_CODE_INGEST_MAX_COMMITS_PER_PASS`.
2. **Re-indexes exactly the changed files** of each commit (`ingest_file` in
   `code/app/index/ingest.py`): parse, chunk, symbols, edges, call guards, the file
   row, and a context pack and review brief for the merged PR the commit names. Then it
   advances `git_head`. A crash re-runs from the last complete commit. Across entries
   the pass takes one commit per entry per round, so a long backlog never holds another
   entry's new commits; a round the budget ends resumes next pass at the entry (org and namespace) it missed.
3. **Walks** with the share `LOOM_CODE_INGEST_WALK_BUDGET_SHARE` leaves: reconciliation
   heals and extractor re-chunks (below).

| Bound                                   | Effect                                                                                        |
| --------------------------------------- | --------------------------------------------------------------------------------------------- |
| `LOOM_CODE_INGEST_MAX_PASS_SECONDS`     | Pass length.                                                                                  |
| `LOOM_CODE_INGEST_PASS_BUDGET_FRACTION` | After this share the pass starts no new units, saves cursors and returns `partial: true`.     |
| `LOOM_CODE_INGEST_SECONDS_PER_FILE`     | Predicts a commit's cost; a commit predicted to overrun starts only as the pass's first.      |
| `LOOM_CODE_INGEST_SLICE_SHARE`          | The most of the commit phase one oversized commit may take before it is sliced across passes. |
| `LOOM_CODE_INGEST_LANES`                | Entries ingested side by side (default 1, up to 8). One entry's commits stay sequential.      |
| `LOOM_CODE_INGEST_ROUND_FILES`          | Files per round inside a commit; reads prefetched in two statements, writes batched.          |

Lanes help because a lane waits on ClickHouse round trips, not CPU.

**Admission.** A file is refused before parsing when it matches the denylist
(`code/app/index/denylist.py`, `LOOM_CODE_INGEST_EXCLUDE`,
`LOOM_CODE_INGEST_IGNORE_FILE`), is binary, or exceeds `LOOM_CODE_INGEST_MAX_FILE_BYTES`.
So `coverage_floor: true` on a grep means every admitted chunk, not every byte.
A path the entry's `embed_exclude` globs name (`LOOM_CODE_EMBED_EXCLUDE` for the scalar
entry) is admitted, chunked and mapped, but its chunks are neither described nor embedded:
they carry the `unembedded by design` marker, which every writer of a vector or a
description honours and the coverage counts skip, the `code_summary` pass writes no card
for them, and code.search reaches them through the lexical leg only. A changed glob
applies to chunks written after it, in both directions (the operations guide's
`embed_exclude` notes name the repair).

### Choosing a parser

`ingest_parse.parse_for_ingest` tries these in order. The order keeps new file kinds out of
the extractor stamp:

1. `treesitter.lang_for_path`: the stamped core (C/C++ with `.h` through the C++ grammar,
   Python, shell, SQL, doc, config). `ingest_parse._lane_language` then re-files CMake
   files and TLC configs.
2. Helm and Kubernetes manifests among config files (`lang_gotemplate`, `lang_k8s`).
3. `lang_detect.detect_by_extension` (`LANG_BY_EXTENSION`).
4. A shebang, then shell detection by Linguist names and ShellCheck directives
   (`lang_detect.detect_shell`).
5. Host files (Dockerfile, Makefile, Jenkinsfile, CI YAML) with `LOOM_CODE_HOST_ISLANDS`
   (`lang_hosts`).
6. Expected-output fixtures, one unembedded chunk per file (`lang_reference`).
7. Any other text, chunked without symbols (`lang_text`).

The parser comes from `ingest_parse._PARSERS`. A failure of that parse, including a missing
grammar or a tree-sitter parse past `code_parse_timeout_s` or `code_parse_memory_mb`
(`bounded_parse`, one parse at a time), degrades to a chunk-only file with
`code_files.index_error` set; `code.index_errors` reports it; a TLA+ spec instead falls
back to its regex reader. A parse past its limits anywhere else takes its caller's
fallback and records no error.
Tree-sitter modules import lazily, so a server with the code workers off boots without the
`code` extras.

### Chunks

`server/code/domain/extract/chunker.py` cuts semantic units, never fixed windows:

| Chunk            | Contents                                                                                                    |
| ---------------- | ----------------------------------------------------------------------------------------------------------- |
| `function`       | One function body. An oversized one splits at top-level statements, each piece prefixed with the signature. |
| `class_skeleton` | A class with method bodies elided.                                                                          |
| `file_header`    | Leading comments and includes.                                                                              |
| `other`          | The rest, grouped.                                                                                          |

Python search responses omit a prefixed class docstring when the skeleton already contains its text.

Files without a tree fall back to whole-line windows; lanes without a grammar cut on
their symbol spans (`lane_units.span_chunks`). A chunk id is
`uuid5("loom://code/{namespace}/{path}#{scope}@{sha16}")`. It is content-addressed, so
an unchanged chunk keeps its id and hash and the embed step skips it without a lookup.
Identical chunks in one file get an ordinal suffix.

Class skeletons carry compacted presentation text, not physical source coordinates.
The chunker retains class source outside method chunks as `other` chunks, including
documentation, declarations, data members and blank separators. These source runs
keep their original line spans even when they are shorter than the general
leftover-chunk threshold. Body reconstruction requires every source line; missing
separators cause an incomplete read even when all member bodies are present.
Skeletons remain available for class summaries, and unmappable chunks still disclose
partial grep coverage. Retaining source adds chunk rows and can add embedding work.
The shared chunker's stamp moves only the chunk stage, across language families;
existing indexes need that stage re-derived before missing source becomes readable.

### Symbols and edges

A symbol id is `treesitter.symbol_id(qualified_name, signature)`: the first 128 bits of
SHA-256 over the name and a normalized signature (whitespace collapsed, defaults
stripped, so overloads differ). The fast tier, the SCIP converter and the read path all
call it, so both tiers land a shared symbol under one id. Python and shell qualify names
by module path, so the many `main()` functions in a test tree stay distinct.

Fast-tier edges (`edges_treesitter.py`, `tier='treesitter'`) are resolved by name and
graded:

| Confidence | Rule                                                                    |
| ---------- | ----------------------------------------------------------------------- |
| 1.0        | Unique definition in the same file                                      |
| 0.8        | Method of the enclosing class                                           |
| 0.6        | Unique match in the repository-wide symbol name table                   |
| none       | Ambiguous or unknown: no edge; recorded in `code_call_sites_unresolved` |

A wrong edge is worse than a missing one, so `code.callers` reports how many sites its
count leaves out. Constructor calls (`T x(...)`, `new T`, `make_unique<T>`) are calls to
`T::T`. Receiver-type modules (`cpp_receivers.py`, `py_receivers.py`, `ts_receivers.py`,
`go_receivers.py`) bind member calls. Edge kinds are `calls`, `includes`, `inherits`,
`overrides`, `uses_type`, `fixture_use`, `reads` and `writes`.

`code.callers` and `code.impact` expand a method to its base declarations through
indexed `overrides` edges or a bounded `inherits` walk from its class. A matching
method name or signature on an unrelated class does not establish virtual dispatch.
Missing relationships leave the graph answer a lower bound, with the missing-dispatch
cause disclosed when the compiler tier cannot rule it out.

**Dependents.** Edges resolve against a repository-wide name table, so a commit that
adds, removes or re-signs a symbol changes the edges of untouched files that name it.
`code/app/index/dependents.py` re-extracts only those files' edges at the same
commit, up to `LOOM_CODE_INGEST_DEPENDENTS_MAX_FILES`. The overflow waits in
`code_index_state` (`dependents_pending`) and drains through reconciliation.

### Embeddings and vector tables

`code_ingest` embeds new chunks inline, memoized by content hash (`embed_reuse.py`),
with bounded text (`embed_text.py`). With `LOOM_CODE_CONTEXT_DESCRIPTION_ENABLED` (on by
default) a chunk gets a one-line LLM description prepended to its embedded text,
best-effort and budget-gated. A provider failure leaves an `embedding_dim = 0` stub that
`code_embed_recovery` fills, with per-text fallback and poisoning after
`LOOM_CODE_EMBED_MAX_ATTEMPTS`. Until `LOOM_CODE_READY_EMBED_COVERAGE` of a namespace's
chunks have vectors, `code.search` answers from its lexical legs and says so.

| Table                                     | Filled by                                          | Use                                                                                                   |
| ----------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `code_summaries`                          | `code_summary` (weekly, off by default)            | File and module cards for `code.map`, gated by an inputs hash, with PageRank from `code_graph_stats`. |
| second-model tables, `code_chunks_prefix` | `LOOM_CODE_VECTOR_TABLES`; `loom code vector-twin` | The vector leg shortlists on the smaller twin and rescores on served vectors (`prefix_twin.py`).      |
| `code_answers`                            | `code.ask`                                         | Answer cache keyed by question embedding; served only if every cited file's hash is current.          |

The answer-cache policy also keys synthesis prompts, output budget and the prose and
chunk-kind ranking settings. Failed retrieval legs, interrupted or refused synthesis,
and unavailable synthesis never produce positive or negative cache entries. A returned
answer discloses these limits with `partial`, `partial_reason` and `note`; `coverage`
is a model self-assessment rather than verified correctness. See
[repository questions](/docs/guides/repository-questions) for calibration and mixed
source/documentation retrieval.

Bulk passes leave extra copies per key until a merge. `code/app/index/compaction.py`
runs `OPTIMIZE … FINAL` on the twin tables after a bulk pass. `code_chunks` is compacted
only by `loom code compact --table code_chunks --apply`.

## Compiler tier: SCIP

The compiler tier holds `tier='scip'` symbols and edges. The server never parses
protobuf: a producer converts SCIP output to a versioned JSON delta
(`scripts/scip_harness/scip_to_delta.py`) and `code/app/index/scip_delta.py`
applies it. Per touched file the apply upserts what the delta emits and tombstones the
file's `scip` rows it no longer emits; a deleted file is tombstoned whole. Re-applying a
delta gives the same live set.

| Producer          | Language                | Watermark        | Workers                                                | How it runs                                                                                                                                                                                                                                                                                                                                              |
| ----------------- | ----------------------- | ---------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scip-clang`      | C++                     | `scip_commit`    | `code_scip_full`, `code_scip_delta`, `code_scip_apply` | Changed TUs (and TUs including changed headers, capped) via `run_delta.sh`; `code_scip_full` seeds the tier and re-indexes it weekly.                                                                                                                                                                                                                    |
| `scip-typescript` | TypeScript / JavaScript | `scip_commit_ts` | `code_scip_ts_delta`                                   | Indexes named projects, or the members of an umbrella root tsconfig (including explicit tsconfig file references); a delta indexes only the projects that contain the window's files unless a shared config or lockfile changed, or a changed TypeScript path sits outside every member. The converter still bounds the output to the TypeScript window. |
| `scip-go`         | Go                      | `scip_commit_go` | `code_scip_go_delta`                                   | One build per module (`run_go_monorepo_delta.sh`).                                                                                                                                                                                                                                                                                                       |
| `scip-python`     | Python                  | `scip_commit_py` | `code_scip_py_delta`, `code_scip_apply`                | Per-merge delta (`run_python_delta.sh`); a first run indexes the tree.                                                                                                                                                                                                                                                                                   |

`code/domain/index/compiler_tiers.py` (`TIERS`) is the one table of watermark, label
and workers per producer; status handlers and the dashboard read it. A delta worker
compares its watermark with `git_head`, moves the checkout (fetching from the local
mirror, not the network), runs the producer in a subprocess and applies the delta
through the same path `code.scip_ingest` uses. One pass covers every merge since the
watermark.

An external producer such as a CI job can upload a delta in parts with
`code.scip_ingest`; parts are staged in `code_scip_batches` / `code_scip_parts` and
applied by `code_scip_apply`. Every compiler-tier pass takes a per-entry lock file in
`LOOM_CODE_SCIP_LOCK_DIR` and a ClickHouse lease, so a full re-index and a delta never
run on one entry at once. `loom code scip-full` rebuilds
the C++ tier; `loom code scip-delta` runs one delta pass.

Where both tiers hold the same row, reads prefer the compiler row, and every answer
names the tier it read (`scip` or `treesitter`).

Exact code grep answers can carry the caller's readable code-linked lessons for
the matched files. Lessons are read after cached match data, within the request's
remaining deadline. Presence queries and uncovered paths carry none;
`include_lessons=false` skips the read.

`code.enclosing` carries the same file lessons for resolved locations. Repeated
locations share one file read; unresolved locations bring no lessons. The caller's
readable memory namespaces, narrowed-token refusal, timeout and token cap apply
through the shared result enrichment. Resolved symbol names rank matching lessons
after constraints and pins; unresolved names contribute no query terms. Empty
lesson fields stay off the wire.

When several grep hits need implementation source, pass their `path:line`
locations to `code.enclosing` with `include_body=true`. It returns complete
enclosing definitions together. `code.symbol` resolves a named definition or
one location; the batch avoids a separate lookup for every located definition.

`code.read` reads several known line ranges in one request. It uses a local
Git mirror and checks the blob's hash against each indexed file record.
Only files indexed for text search qualify. Projected notebook cells and
reference fixtures with omitted text are unavailable. The response gives
inclusive line numbers for each window and marks unavailable ranges, including
ranges that exceed the request’s source byte limit.

Python SCIP identities use the same placeholder for callables of every
arity. Definition and enclosing-body responses recover the parameter list
from a retained declaration with the matching name. Metadata-only responses
leave the signature empty when the index provides only the placeholder.
The stored identity and call edges keep their existing keys.

Search and grep rank candidate lessons across all selected files by query-term
overlap after constraints and pinned rows. English inflections share stems; equal
matches keep path order, then the listing's confidence and recency order.
The remaining file-lesson reads retain path and listing order.
The ranking uses the existing namespace-scoped candidates. On trunk, uncapped
grep responses focus lessons on the definitions their matches name. Search
focuses a file's lessons when a returned definition has an exact linked lesson.
Whole-file search hits use file-level selection. Grep omits a candidate by scope
only if its link was checked at the same revision as the matched chunks. Matches
outside a named definition also keep candidates with overlapping or unverified
link ranges. Read the broader file history with `memory.for_file`. Before
omitting a lesson by scope, the enrichment checks its live link set for pending
and uncertain links within the request's enrichment deadline. Ranking and
focusing add no model calls.

File and symbol lessons carry complete memory text, including source references.
The internal file listing reads complete values; the pre-edit block keeps its own
read and render limits. A configured `code_result_lessons_tokens` budget leaves out
whole lessons rather than cutting their conditions. Its default of zero is
unlimited. With an explicit symbol request budget, source definitions take precedence;
whole linked lessons fit in the remainder and `lessons_left_out` counts omissions.

`bench/replay_code_lessons.py` compares recorded lesson order with query-aware order
from an evaluation's native memory certificates and grep answers. It retains every
timestamp-tie order that reproduces the recorded answer. Cases whose reads cannot be
reconstructed remain unknown. This offline replay measures lesson order, not solver success.

Python compiler conversion keeps callable and class descriptors distinct from
parameters, type parameters and fields. Call edges require a containing function
span; a reference at module or class scope does not belong to the preceding function.

## The extractor stamp

Content-addressed chunks and hashed symbol ids key on the input, not on the code that
produced the rows, so a chunker fix would never reach an existing row.
`server/code/domain/extract/extractor_stamp.py` closes the gap. It hashes the code tokens of
every extractor module (`logic_tokens`: no comments, blank lines or docstrings, and an
import reduced to the names it binds, so moving a module between packages moves no
stamp) plus the installed versions of the stamped grammars (`STAMPED_GRAMMARS`: the base library, C++,
Python, bash).

The stamp is split two ways so a change re-derives as little as possible:

- **By stage** (`STAGES`: `chunk`, `symbol`, `edge`, `guard`; `STAGE_MODULES`). A
  stage's stamp covers its modules and those of the stages it reads (`STAGE_INPUTS`).

  | Module changed                    | Stages moved                  |
  | --------------------------------- | ----------------------------- |
  | `chunker.py`                      | `chunk`                       |
  | `edges_treesitter.py`             | `edge`, `chunk`, `guard`      |
  | `treesitter.py`, `lang_python.py` | all (`symbol` feeds the rest) |
  | `call_guards.py`                  | `guard`                       |

- **By language family** (`LANGUAGE_FAMILIES`: `python`, `shell`, `typescript`, `cpp`,
  `other`; `MODULE_LANGUAGES`). A Python-only change heals `.py` files and leaves C++
  alone. The TypeScript edge modules (`ts_receivers.py`, `ts_reexports.py`,
  `ts_config.py`, `ts_workspace.py`) move only `typescript`. A stamped module missing
  from `MODULE_LANGUAGES` moves every family.

Each pass compares the running stamps with those in `code_index_state`. A moved stage is
re-derived for every file of that family in every indexed namespace, in paced batches
(`LOOM_CODE_EXTRACTOR_RECHUNK_PER_PASS`, switch `LOOM_CODE_EXTRACTOR_RECHUNK_ENABLED`).
An empty recorded stamp is recorded, never acted on. So:

- a code change to a module in `EXTRACTOR_MODULES` re-indexes every repository in the
  affected families, which takes hours on a large deployment; comments and docstrings
  can be edited freely;
- those files are excluded from the formatters (`pyproject.toml`), and
  `tests/unit/test_code_extractor_stamp.py` keeps the exclusion list and the module
  inventory in step: a module in `server/code/domain/extract/` in no stage must be
  listed in the test's `NON_EXTRACTOR_MODULES` with its reason;
- change them only when the extraction changes, and expect the re-derive after deploy.

**Lane modules are outside the stamp.** The lane parsers (`lang_typescript.py`,
`lang_rust.py`, `lang_go.py`, `lane_units.py`, …), their grammars and the file-selection
modules (`lang_detect.py`, `denylist.py`) do not move it; the TypeScript edge modules
above are the exception. A lane fix is applied with `loom code backfill --paths-file`
over that language's files.

## Reconciliation

Watermarks say which commits were walked, not whether every row is current.
`code/app/index/reconcile.py` measures drift. A `code_files` row carries `blob_sha`
and `indexed_commit`. One `git ls-tree -r <head>` marks a path stale when its blob
differs and gone when it is absent. Rows without a blob fall back to one
`git diff --name-only` per distinct commit, up to `LOOM_CODE_RECONCILE_MAX_COMMITS`.

The hourly check in `code_ingest` (`LOOM_CODE_RECONCILE_ENABLED`,
`LOOM_CODE_RECONCILE_INTERVAL_SECONDS`) re-ingests up to
`LOOM_CODE_RECONCILE_HEAL_PER_PASS` stale paths through `ingest_file`; only new content
is embedded. By hand: `loom code reconcile --heal`. The `loom.code.stale_files` gauge
reports the count.

## Watermarks and coverage

`code_index_state` (`ReplacingMergeTree(version)`, keyed `(org, namespace, state_key)`)
holds `git_head`, the per-producer SCIP watermarks, the extractor stamps, cursors,
`dependents_pending` and `history_until`, where `git_head` sits in the merged-PR
ledger's clock ([the bound](/docs/features/code-index/history-and-prs#history-stays-inside-the-indexed-head)).
A read that names a change stays inside `git_head`: a ledger read compares `merged_at`
with `history_until` (`_head_bound` in `code/store/index/sql.py`), and a read of the
mirror asks whether the head contains the commit (`history_bound.contains`). The issue
and PR mirror leaves out a PR merged after `history_until`, and the head of an unmerged
change (a PR's `refs/pull/N/head`, or a `head_sha` a caller names) is read only while it
is not of a change merged after the head (`history_bound.placed`).
The `as_of` block on every answer and
`loom.code.tier_lag_seconds{tier}` are computed from these rows and the mirror, not from
a producer's log. Per-commit coverage (`code/app/index/commit_coverage.py`) is one
`git merge-base --is-ancestor` per tier on the mirror, never a watermark comparison.
What callers see is in [freshness](/docs/features/code-index/freshness).

## PR history, backports and tracker links

| Table                                                  | Writer                                                      | Holds                                                                                              |
| ------------------------------------------------------ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `code_pr_history`, `code_pr_reviews`, `code_gh_items`  | `code_pr_history` (GitHub REST, cursor on `updated_at`)     | Merged PRs with files, review comments, issues. A rate limit or 5xx leaves the cursor unmoved.     |
| `code_context_packs`, `code_review_briefs`             | `code_ingest` at the merge commit, or on demand             | Per-PR context pack and reviewer's brief.                                                          |
| `code_backport_gaps`                                   | `code_backport_gaps` (nightly; needs `code_pr_history`)     | Per backport-labelled trunk PR, one row per release-branch namespace: covered, owed, not affected. |
| `code_test_map`, `code_symbol_stats`, `code_unit_risk` | `code_graph_stats` (weekly), `loom code crossref`           | Test↔source map, symbol fan-in, per-unit risk.                                                     |
| `code_coverage_files`                                  | `code_coverage_import` (daily), `loom code coverage-import` | Per source file, the line ranges a per-test coverage run executed.                                 |
| `qa_link_candidates`                                   | `tracker_links` (daily)                                     | Top merged PRs per recent issue, ranked by BM25F, stack frames in the diff and closing mentions.   |
| `qa_item_embeddings`                                   | `tracker_embed`                                             | Vectors of tracker issues and PRs in the embedding window; keys and filter facts, no text.         |

`code.repo.set_source` links a repository to its trackers, in order; the first is the
primary, whose numbers are the repository's issue and PR numbers. The links are the
`qa_binding` row of `code_index_state` and are read by `(org, namespace)`: a code namespace
name is derived from the repository and branch, so two orgs can hold the same one. The
operator's `LOOM_TRACKER_CODE_NAMESPACE_BINDINGS_JSON` applies only to the operator's own
repositories (`LOOM_CODE_REPOS_JSON` or `LOOM_CODE_REPO`), never to a self-service one
whose name matches a glob. Tracker workers read each namespace through its own source, so
a restricted namespace's rows never land under a standard one. The record contract is in
[tracker record contract](/docs/features/tracker/record-contract).

`code.repo.add_branch` writes the new branch's `qa_branch_of` row naming the root
repository (the source, or the source's own root when the source is a branch) when that
root is an operator repository, so a self-service root's branch never starts reading the
map if the operator later configures the root's name. A
registered branch whose root is an operator repository follows that repository's links at
read time, the glob included; a `qa_branch_of` row with no self-service entry beside it is
not followed. A source that is not an operator repository has its own `qa_binding` row
copied to the branch, a cleared one included. An operator source is its own root. Both
rows are written with the source's rows read first and `qa_branch_of` last, so a failure
leaves the branch following nothing.

`code.repo.remove` empties whichever of the two rows holds a value before the namespace's
detached purge. Registering a namespace empties any row a removed one of the same name
left and drops the name from its own process's snapshot, so the new namespace follows
neither. An emptied `qa_binding` reads as cleared until an admin of the tracker links it.
A namespace that had no `qa_binding` row gets none, so the operator's map still reaches an
operator entry configured under the same name. An operator entry configured under a
removed name gets no such cleanup: until the purge runs, it reads the removed namespace's
`qa_binding` row when there is one, the old links after a removal on build N-1 and none
after one on N. Other processes keep the rows they read for up to
`LOOM_CODE_REPOS_REFRESH_SECONDS`.

## Storage

| Table                                                          | Engine and key                                                                                         | Notes                                                                                         |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| `code_files`                                                   | RMT(`version`), `(org, namespace, path)`                                                               | Last parse per path: language, `blob_sha`, `indexed_commit`, `index_error`.                   |
| `code_chunks`                                                  | RMT(`version`), `(org, namespace, embedding_model, path, chunk_id)`, partitioned by `(org, namespace)` | Content, `lexemes`, vector. Text indexes: 3-gram on `lower(content)`, tokens on `lexemes`.    |
| `code_symbols`                                                 | RMT(`version`), `(org, namespace, tier, qualified_name, symbol_id)`                                    | Definitions with signature, span, doc comment, `scip_symbol`; ngram skip indexes on the name. |
| `code_symbol_names`, `code_symbol_ids`                         | RMT, filled by `code_symbol_names_mv` / `code_symbol_ids_mv`                                           | The symbols re-keyed by short name and by id.                                                 |
| `code_edges`                                                   | RMT(`version`), `(org, namespace, tier, to_symbol_id, edge_kind, from_symbol_id, path, line)`          | Callers are a key range; projections `by_from` (callees) and `by_path`.                       |
| `code_call_sites_unresolved`, `code_caller_guards`             | RMT(`version`)                                                                                         | Declined call sites by callee name; guards around each caller's call sites.                   |
| `code_term_freq`, `code_doc_stats`                             | AMT, RMT; filled by `code_term_freq_mv`, `code_doc_stats_mv`                                           | BM25 statistics for the lexical leg.                                                          |
| `code_term_df`                                                 | MT, `(org, namespace, term)`; replaced whole by `code_term_df_refresh`                                 | The same statistics as plain numbers; rebuilt within an hour of a change to those tables.     |
| `code_unit_signal`                                             | `SummingMergeTree((positive, negative))`                                                               | Outcome counters per unit from `code.outcome`.                                                |
| `code_search_trace`, `code_search_outcome`, `code_search_memo` | MT with 180-day TTL; RMT with 60-minute TTL                                                            | Per-query traces and outcomes; a short-lived memo of served `code.search` responses.          |

Every column is in the generated [schema reference](/docs/reference/schema).

## Query patterns

A file-qualified symbol request (`src/module.py:Type.method` or
`src/Type.cpp:Namespace::Type::method`) keeps the filename as a hard constraint.
The exact indexed path takes precedence even when it lacks the requested symbol.
If it is absent, an unanchored relative path with two or more components can match
the complete suffix of one live indexed file in the namespace. A `./` or absolute
path keeps the lookup exact. Both symbol reads use the selected path before ranking
and limiting. The response includes `resolved_by: file_symbol`, the canonical
indexed path, and the stored symbol name and id. The shared resolver applies this
spelling to structural code operations.

Python import spellings use the bounded short-name candidate read after an exact
symbol miss. Read-side matching preserves dotted module scopes and treats a package's
`__init__.py` as implicit. Only Python source rows participate; ambiguous or incomplete
candidate sets decline. The response discloses `resolved_by: python_module` while
retaining stored names and ids. Extraction and its stamp do not change.

Memory code links use the same Python import spellings when resolving named
definitions. A package-level name such as `pkg.json.dumps` can anchor the definition
in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor
names remain explicit, and ambiguous matches stay unlinked unless the memory's
file scope selects one definition.

| Op                               | Path                          | How                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| -------------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code.search`                    | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; a traceback whose frames name nothing in the index adds no name of its own; the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. |
| `code.grep`                      | `code/store/index/grep.py`    | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `code.symbol`                    | `code/app/symbol/`            | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `code.callers`, `code.impact`    | `code/store/index/edges.py`   | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `code.outline`, `code.enclosing` | —                             | Per-path reads of `code_symbols` and `code_chunks` spans.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `code.trace`                     | `code/app/symbol/trace.py`    | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last.                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the
index tokenizer. The score counts only whole app lexemes and rejects partial matches
from the gate. Underscore-only lexemes use the exact score within the same tenant,
model and path scope because the text index has no token for them.

ClickHouse returns rows that are equal in a sort in the order it read them, which
changes with the parts of the table and the threads of the read. So that the same
request gets the same answer, every ranked read of the search ends its order in keys
that identify the row:

- **Chunks:** the path, the start line and the chunk id, so the earlier lines of a file
  come first. The lexical leg, the definition leg, the chunks a history or card vote
  brings, the exact rescore of a shortlist and `track_path` close their order this way.
- **Pull requests:** the newer merge, then the higher number.
- **Symbols:** the path, the start line and the symbol id after the ranking keys.
- **The vector leg and the card leg:** the statement sorts on the distance alone, the
  one sort the codes-first read takes, and the rows it returns are put in the chunk
  order (the path, for a card) afterwards. Chunks with one text have one vector, so
  equal distances are common. Which of the rows at the read's last distance come back
  is still ClickHouse's choice, as is the shortlist the codes-first read rescores.

Fusion and the stages after it sort stably, so they keep the legs' order among equal
scores.

`retrieval_confidence` says whether the index holds an answer at all. It is the vector
leg's best cosine, read on the embedder's calibrated scale before any prior reorders
the rows (`code/domain/index/search_confidence.py`, `code/app/search/calibrate.py`):

- **The scale.** 0 at the midpoint between the abstain threshold and the cosine of a
  confident hit (`rerank_skip_above` in the namespace's calibration, else in the
  embedder's boot calibration, else `LOOM_LLM_RERANK_SKIP_ABOVE`), 1 at that cosine.
  An absolute cosine is not comparable across embedding models: one scores unrelated
  text 0.2, another 0.7. The boot calibration's probes are prose, so a namespace
  `code.calibrate` has not seeded reads its code on a prose scale: where the model
  scores a right code hit lower than a right prose answer, an answerable search reads
  `medium` or `high`
  ([seed each code namespace](/docs/operations/code-index-operations#first-index)).
- **What it separates.** A question the index can answer usually scores near 1, and
  one about another repository or another subject usually scores lower. It is a
  tendency, not a rule: measured on issue prompts with one embedding model, the median
  prompt sent to another repository's index scored 0.30 and about one in five still
  read `low`.
- **What it does not separate.** Among questions the index can answer, a result that
  holds the file to change and one that does not score alike. A high confidence is
  not evidence that the first result is the right one.
- **No cosine.** A search with no vector leg (no embedder, a lexical-only request, a
  failed leg), or one whose vector leg returned no row, reads 0.5, which never bands
  `low`.
- **No scale.** A confident-hit cosine that is not above the abstain threshold leaves
  no range to read a cosine on: a calibration whose question-to-answer cosines fall
  into its distractor range, or, with no calibration,
  `LOOM_MEMORY_SEARCH_ABSTAIN_THRESHOLD` set at or over `LOOM_LLM_RERANK_SKIP_ABOVE`.
  The search reads 0.5 then too, and `calibration_explanation` says so.
- **No results.** An abstain that returns no result reads 0.0.
- **A second vector model.** The scale is the served embedder's. A request's
  `vector_model` with no shortlist ranks on its own cosines, which are read on that
  scale all the same, as its abstention is.
- **No vector leg to read.** An exact symbol match reads a fixed 0.95 and the history
  route 0.5.
- **Not abstention.** Abstention is decided apart from the confidence, on the fused
  list: its top cosine under the abstain threshold (`below_threshold`), or a
  route-aware score (that cosine, its margin over the second hit, route agreement and
  the pool size) under `LOOM_CODE_SEARCH_ABSTAIN_CONFIDENCE_BELOW`
  (`low_calibrated_confidence`).

`retrieval_risk` bands the confidence of a result the search does not abstain on:
`high` below `LOOM_CODE_SEARCH_MEDIUM_RISK_FROM` (0.35), `medium` from it, `low` from
`LOOM_CODE_SEARCH_LOW_RISK_FROM` (0.70). It reads `abstain` when the search abstains.
`route_agreement` is reported beside the confidence and is not part of it.

After relevance ranking, per-file saturation spreads broad search results across
files. It is skipped for an explicit path, a symbol route, test intent, or a
code-shaped identifier named in the query that matches a qualified symbol
component in the relevance window. This keeps related definitions together for
questions about a named identifier. An unmatched identifier does not disable
saturation. Per-symbol deduplication still removes repeated chunks of one definition,
and continuation pages retain the final served order.

A reranker (`rerank` in the request, or `LOOM_CODE_SEARCH_RERANK_DEFAULT`) orders the
units it reads and leaves their scores as they were, so the scores of a reranked page
do not descend. The reply serves those units in the reranker's order, apart from the
named definitions:

- **The personal tie-break** runs before the reranker, on the fused order, and stands
  only for the units the reranker did not order. A swap it made on a reranked page
  reads `user_tiebreak=before_rerank` in `score_explanation`.
- **Named definitions** are served directly after the reranker's first unit, as they
  are after the first unit without a reranker, whether or not the reranker read them.
- **Per-file saturation** spreads only the units after the last one the reranker
  ordered, and counts the files of the units before them. `score_explanation` then
  reads `saturation=<decay>(below_reranked)`, or `saturation=skipped(reranked)` when no
  unit is after it.

History anchors and `sort_by: "fan_in"` apply after the reranker, as they do after
every relevance stage, and saturation leaves every unit up to the last one the
reranker ordered where they put it.

`rerank: "builtin:pick"` is the listwise pick, a reranker for a query that reads as a
bug report: twelve words or more, or the vocabulary of a failure. One call of the
deployment's pick model reads the report, cut at 4,000 characters, against one line for
each of the first 100 distinct units of the ranking (`path:lines symbol — declaration`,
no body), and answers with at most 8 of them, the most likely to change first, and one
word for how sure it is:

- **The picks are served first**, in the model's order. The named definitions are
  placed before the call, so the model reads them as candidates, and the picks go ahead
  of them. Saturation spreads the units after the last pick.
- **`pick_confidence`** in the reply is the model's word: `high` when it is confident
  its first pick is a definition the fix changes, `medium` when one of its picks
  probably is, `low` when probably none is. A caller that sends the results on only
  when the word is `high` sends fewer lists and fewer wrong ones. The word is of the
  ranking the pick handed on, its first pick first: a reply whose first result is
  another unit (a history anchor, or a request's `exclude_unit_ids`, `min_fan_in` or
  `sort_by: "fan_in"`) carries none, with or without a pick, and neither does a later
  page of a cursor.
- **It is off unless the deployment names a model.** `LOOM_CODE_SEARCH_PICK_MODEL` is
  empty by default, and the request then gets the ranking as it is, as does a query
  that does not read as a bug report and an LLM-free read. The deployment's default
  reranker never names the pick, and a search of several namespaces makes no pick call:
  each namespace is searched as with `rerank: "none"`.
- **A failed call keeps the ranking.** `retrieval_work.pick_failed` is `1` when the call
  failed or its reply was not the object asked for, and that answer is not memoized. A
  reply whose word has no candidate to be about is such a reply: `high` when its first
  number is not on the list, `high` or `medium` when none of its numbers is.
- **It costs a model call**: about 7,000 input and 250 output tokens for 100 lines, and
  two to three seconds on a provider's smallest model. Under `deadline_ms` it is skipped
  when less than 2.5 seconds are left, the floor of the search's other model calls, and
  cut at the deadline otherwise. A namespace over its LLM cost cap makes no pick call
  and gets the answer of `rerank: "none"`. A cursor whose stored ranking is gone is
  searched again, with a second pick call.

The pick was measured on bug reports of public repositories that a model may know.
About three quarters of its gain was on reports where the model could name the changed
function with no index at all, so the gain on private code is unconfirmed.

For a question about the implementation, ranking multiplies the score of a test,
example, fuzzer or benchmark path by 0.35 and the score of a prose file by
`LOOM_CODE_SEARCH_PROSE_PENALTY`: such a file is ranked lower, never dropped. The prose
penalty is off for a search constrained to paths and for a symbol lookup.

A question asks for tests when it holds a test word (`test`, `pytest`, `fixture`,
`ci`), and for documentation when it holds a documentation word (`docs`, `changelog`,
`tutorial`). Test intent turns off the test-path penalty, the fan-in prior, the kind
prior and per-file saturation, and lets the definition leg return a definition on a
test path; documentation intent turns off the prose penalty. A
question with more lexemes than `LOOM_CODE_SEARCH_QUERY_MAX_TOKENS` is an issue body,
where such a word names where a fault showed: a traceback path, a version listing, a
link. Only its first 16 lexemes are read for intent, which hold the title of a report
or the request a long prompt opens with. They are counted in the question as sent, so a
template's headings before the title are among them. A long prompt that states its
request after that opening is ranked as a report.

Under the `functions_first` kind prior (`LOOM_CODE_SEARCH_KIND_PRIOR`, or `kind_prior`
on a request) a question that long is ranked functions first: the fix of a report most
often edits a function, and a class skeleton or a module-level chunk that repeats the
report's words otherwise outscores it by more than a bounded factor takes back. Only
the length is read, so a design question or a task prompt past the cap is ranked the
same way. The default stays `flat`, which ranks every question by its bounded table:
functions first gains places on the first page for a changed function and gives up
reach for a changed class or module-level chunk (see Cost).

- **Order.** Every unit takes the table's score; the factors are those of `flat`. The
  other kinds of a file that holds function chunks (its class skeletons, module-level
  chunks, comment blocks and header) are then moved behind the functions among the
  first 25 units: one factor puts the best of them level with the lowest of those
  functions, never above it. They follow those functions and are served among the
  functions that score below. When the first 25 units hold no function, nothing is
  moved: a first page without one says the answer is not a function. 25 is the largest
  page a request can ask for, so the anchor is the same for every `top_k`.
  `score_explanation` reads `kind_prior=functions_first:moved` when a unit was moved,
  and `kind_prior=functions_first` when none was. Three later stages read those
  scores:
  - The outcome signal. A function it scales down is served after the moved units it
    then scores below. A moved unit that it scales up, by at most 35%, is served ahead
    of the functions it then outscores, the last ones of those 25 units.
  - The personal tie-break. It serves the best moved unit ahead of the function it is
    level with when, of the two, only that unit is in a directory of the caller's
    recent work.
  - Per-file saturation, which sorts by score. It keeps a file's best function ahead
    of the moved units; a file's later function that the decay takes below their score
    is served after them. A moved unit that follows a function of its own file takes
    the decay too.
- **These files keep the table's order.** SQL, a config file (YAML, JSON, TOML, XML,
  INI), a document (Markdown, reStructuredText, MDX, HTML), a style sheet, a Prisma
  schema, a FlatBuffers schema, an Angular component template, a file of Terraform
  values (`.tfvars`), a file with no extension, and a language with no parser (Kotlin,
  Swift, C#, Ruby, PHP). A unit of such a file has no function of its own file to
  follow, so it stays where the table scores it, among the functions. A namespace
  whose main language has no parser is therefore ranked as for a shorter question. A
  CMake file is among them as a config file, although its functions and macros are
  function chunks: its target outlines are not moved. The path's extension is all that
  is read.
- **Named definitions keep their places.** A class the report names is what it asks
  about: its skeleton is served directly after the first unit, as on every page.
- **A kind word or the name of a file does not change it.** In a pasted report they
  say where the fault showed, so they neither skip the prior nor boost a kind.
- **Unchanged.** These are not ranked functions first:
  - a long question whose opening asks for tests, which skips the prior, or for
    documentation, which keeps the bounded table. Under that table a kind word boosts
    its kind only when the opening holds it;
  - a search with a reranker to call, which orders the first units itself, the
    skeletons among them. The listwise pick is one where it has a call to make: it
    reads the bounded order. The path of a shorter question stays when that call is
    then skipped under a request budget, cut at the deadline or fails open;
  - every question under `flat`, `default` or `structural`, where the name of a file
    skips the prior and a kind word boosts its kind wherever the question holds it.
- **Cost.** A changed class skeleton or module-level chunk of a file that holds
  function chunks, when it scores among the first 25 units, is served after the
  functions among them, unless a definition place holds it. It can leave the first
  page for a later one, which the `cursor` of a continuation serves up to the 100th
  unit, or leave those 100 units. A unit that keeps the table's order and scored
  between the best moved unit and the lowest of those functions is served ahead of
  the moved units it scored below: a config or document window can pass a class
  skeleton that outscored it. The definition places hold at most three chunks: the
  frames of a pasted traceback first, then the names spelled as code outside it that
  have a definition, those written with their owner and then the first other one. A
  module-level chunk has no name to spell. Another table
  serves such a unit where the fusion scored it. Through MCP, whose compact tool
  schema omits `kind_prior`, a deployment set to `functions_first` serves it at that
  place for a shorter question; the `cursor` of a continuation reaches it at its
  moved place on a later page.

### Symbol bodies

Literal hits, rendered-message matches and symbol mentions use the same retained-source
line mapping as definition bodies. Copied doc comments and continuation headers do not
become file lines. Compacted class skeletons cannot establish exact hit coordinates.
Grep and symbol mentions recover their retained raw chunks under the same tenant,
model and path. A summary is replaced only when those chunks cover its span without
gaps or disagreements with already-read source. Recovery shares the grep scan's
character bound and any caller-supplied deadline. Incomplete or failed recovery leaves
grep partial and symbol mentions truncated. A missing hit in that response is not
evidence that the file lacks the text.

Grep continuation pools retain source-mapping and partial-coverage metadata. A
pool with another mapping triggers a disclosed rerun; restart pagination for
complete results because its offset can count synthetic hits. Signed cursor
formats and stored match shapes are unchanged across rolling builds. Readers
that do not use the additive pool metadata can still consume its matches.

A definition body covers every declared source line without conflicting overlaps,
missing lines or skeleton substitutions. Doc-comment copies and continuation headers
are removed from chunk prefixes when placing the retained lines. The read uses live
rows under one served embedding label, scoped to one organization, namespace, path and
line span, with a bounded row count. An unchanged chunk's introduction commit may
differ from its neighbors; it does not establish the current file revision. This read
follows live-row publication and does not provide a snapshot across an indexing pass.
A compiler declaration alone does not establish a larger function body.
Parser coordinates, source chunking and oversized-piece boundaries count LF lines;
other Unicode separators inside a string remain source text. A retained prefix ending
in an ambiguous non-LF separator cannot establish a complete physical line.
Hydration and indexing share provider-free label canonicalization, including explicit
local and fake provider overrides. Hydration constructs no embedder, and missing
provider credentials do not select a fake label's source chunks.

If the retained span cannot be established, exceeds 12,000 characters or needs more
than 400 chunk rows, the definition carries `elided: true`, `granularity: card` and a
ranged `next` read. HTTP and MCP preserve that omission. Enclosing-body lookups omit
unavailable text, and verification cannot use an unread body as negative evidence.
No source text is fetched from a network or fabricated to fill a gap.

## Invariants

- A code namespace is one branch; every `code_*` row is keyed by `(org, namespace)`.
- `git_head` advances only after every file of the commit is written.
- `treesitter.symbol_id` is the only symbol-id function, used by both tiers and the read
  path.
- Chunk ids are content-addressed; an unchanged chunk is not re-embedded.
- A stamped module's code change re-derives its stages for its language family in every
  namespace; comments and docstrings never do.
- A delta apply is idempotent and tombstones what the producer stopped emitting.
- The server never parses SCIP protobuf.
- Per-commit coverage is an ancestry check on the mirror, never a watermark.
- Retrieval filters `embedding_dim > 0`; a stub chunk is searchable lexically only.
- With `LOOM_CODE_GIT_PROXY_URL` set, git reaches a network remote through that proxy
  or not at all, and the proxy's password is in the environment of that git process only.

## Source entry points

| Path                                                                                                                               | What                                                                                          |
| ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `server/code/app/index/ingest_pass.py`                                                                                             | The fast-tier pass.                                                                           |
| `server/code/app/index/ingest.py`                                                                                                  | `ingest_file`, the per-file stages.                                                           |
| `server/code/app/index/ingest_parse.py`, `ingest_chunks.py`, `ingest_edges.py`, `ingest_resolve.py`, `ingest_reconcile.py`         | `parse_for_ingest` and `_PARSERS`, chunks, edges, edge-resolution reads, the key-diff writes. |
| `server/code/domain/extract/treesitter.py`, `lang_detect.py`, `lang_*.py`, `lane_units.py`                                         | Languages.                                                                                    |
| `server/code/domain/extract/chunker.py`, `edges_treesitter.py`, `call_guards.py`; `server/code/app/index/dependents.py`            | Chunks and edges.                                                                             |
| `server/code/domain/extract/extractor_stamp.py`                                                                                    | The stamp.                                                                                    |
| `server/code/app/index/reconcile.py`, `commit_coverage.py`, `scip_delta.py`; `server/code/domain/index/compiler_tiers.py`          | Drift, coverage, tiers.                                                                       |
| `server/code/workers/scip_*.py`, `scripts/scip_harness/`                                                                           | Compiler tier.                                                                                |
| `server/code/workers/embed_recovery.py`, `summary.py`, `graph_stats.py`, `pr_history.py`, `backport_gaps.py`, `coverage_notify.py` | Background workers.                                                                           |
| `server/code/domain/index/repos.py`; `server/code/app/index/repo_registry.py`, `registry.py`, `retire.py`, `gitrepo.py`            | Entries, mirrors, namespaces.                                                                 |
| `server/code/app/index/sandbox.py`, `egress.py`, `git_proxy.py`                                                                    | Repository jobs and how they reach the network.                                               |
| `server/code/app/search/`, `server/code/store/index/`                                                                              | Reads and writes.                                                                             |

## Related

- [Code index overview](/docs/features/code-index/overview) (languages and tiers),
  [freshness](/docs/features/code-index/freshness),
  [history and PRs](/docs/features/code-index/history-and-prs).
- [Code index operations](/docs/operations/code-index-operations).
- [Adding language support](/docs/development/adding-language-support).
- [ClickHouse](/docs/architecture/clickhouse), [operations reference](/docs/reference/operations#code).
