Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

docs: reference pages for the second brain, scripting, snapshots and the security model (#165)

xerj-org2e6fccde2269
diff --git a/README.md b/README.md
index 986c74ece..70daa5a46 100644
--- a/README.md
+++ b/README.md
@@ -154,6 +154,19 @@ cargo run --release -p es-yaml-runner -- --dir tests/es-compat-yaml/yaml
- [Roadmap and project layout](./ROADMAP.md)
- [Changelog](./CHANGELOG.md)
+Reference pages for individual subsystems, written against the source and
+including the limits each one does not lift:
+
+- [Second brain](./docs/SECOND_BRAIN.md) for the relationship layer over
+ indexed documents: the `/_graph` routes, evidence on links, the seven
+ detectors and the two-hop cap.
+- [Scripting](./docs/SCRIPTING.md) for the Painless subset, where scripts run,
+ and the resource limits that bound them.
+- [Snapshot and restore](./docs/SNAPSHOT_AND_RESTORE.md) for the supported
+ subset of the snapshot API, and what restore replaces.
+- [Security model](./docs/SECURITY_MODEL.md) for authentication, the reserved
+ `.xerj-memory-*` namespace, API keys and what is not enforced.
+
## Contributing
Pull requests are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) for the
diff --git a/docs/SCRIPTING.md b/docs/SCRIPTING.md
new file mode 100644
index 000000000..3a121bab3
--- /dev/null
+++ b/docs/SCRIPTING.md
@@ -0,0 +1,430 @@
+# Painless scripting in XERJ
+
+XERJ ships a small Painless interpreter. It is not a port of Elasticsearch's
+Painless and it is not a general scripting runtime. It is a purpose-built
+interpreter that covers the script shapes the ES-compat suite and real
+dashboards send: predicates, scoring expressions, runtime-field `emit()`
+scripts, and `ctx._source` update statements.
+
+Everything below is read out of the implementation:
+
+- interpreter: `engine/crates/xerj-engine/src/painless.rs`
+- HTTP entry points: `engine/crates/xerj-api/src/es_compat.rs`
+- query parsing: `engine/crates/xerj-query/src/parser.rs`
+
+If a construct is not listed here, assume it is not implemented. The
+interpreter rejects what it does not understand rather than guessing.
+
+## Where scripts run
+
+Each row was traced from the request body to the call into the interpreter.
+
+| Surface | Request shape | Evaluated at |
+|---|---|---|
+| `script` query | `{"query": {"script": {"script": {"source": "...", "params": {}}}}}` | `xerj-engine/src/index.rs:26502` |
+| `script_score` query | `{"query": {"script_score": {"query": ..., "script": {"source": "..."}}}}` | `xerj-engine/src/index.rs:33162` |
+| `function_score` with a `script_score` function | `functions: [{"script_score": {"script": {...}}}]` | `xerj-engine/src/index.rs:33162` |
+| `script_fields` | `{"script_fields": {"name": {"script": {"source": "..."}}}}` | `xerj-api/src/es_compat.rs:11051` |
+| Runtime fields | `{"runtime_mappings": {"name": {"type": "...", "script": {"source": "emit(...)"}}}, "fields": ["name"]}` | `xerj-api/src/es_compat.rs:10263`, and inside `top_hits` at `xerj-engine/src/aggs.rs:9395` |
+| Script rescore | `{"rescore": {"script": {"script": {"source": "..."}}}}` | `xerj-engine/src/index.rs:28362` |
+| Script-bucketed `terms` agg | `{"aggs": {"a": {"terms": {"script": {"source": "..."}}}}}` | `xerj-engine/src/aggs.rs:3292` |
+| `terms_set.minimum_should_match_script` | `{"terms_set": {"f": {"terms": [...], "minimum_should_match_script": {"source": "params.num_terms"}}}}` | `xerj-engine/src/index.rs:26575` |
+| Scripted update | `POST /{index}/_update/{id}` with a `script` | `xerj-api/src/es_compat.rs:15160` |
+| Scripted update by query | `POST /{index}/_update_by_query` with a `script` | `xerj-api/src/es_compat.rs:15160` |
+| Standalone execute | `POST /_scripts/painless/_execute` | `xerj-api/src/es_compat.rs:24974` |
+
+Two things that look like script surfaces and are not:
+
+- **Sorting by script is not implemented.** `parse_sort_field_spec`
+ (`xerj-query/src/parser.rs:2833`) reads field names, order, mode, missing and
+ format. There is no `_script` sort branch, so a `_script` sort entry is
+ treated as a field named `_script` and no script runs.
+- **Stored Painless scripts are not supported.** `PUT /_scripts/{id}`
+ (`xerj-api/src/es_compat.rs:24804`) stores mustache **search templates**, and
+ `GET` returns them with `"lang": "mustache"`. A query that references a script
+ by `id` instead of `source` is rejected by the parser, which requires
+ `script.script.source` (`xerj-query/src/parser.rs:1146`).
+
+## The implemented subset
+
+### Context values
+
+| Expression | Meaning |
+|---|---|
+| `doc['field'].value`, `doc.field.value` | first value of the field. Errors when the field is missing, with the same message ES 7.0+ uses |
+| `doc['field'].size()`, `.length`, `.empty` | defined on a missing field, so `doc['x'].size() == 0 ? 0 : doc['x'].value` is the way to guard |
+| `params.name`, `params['name']` | value from the script's `params` object |
+| `params['_source']` | the document as an object |
+| `_score` | the document's current score |
+| `emit(value)` | records a runtime-field value. Call it more than once for a multi-valued field |
+
+`doc[...]` returns null in `POST /_scripts/painless/_execute`, because there is
+no document in standalone execution.
+
+### Literals, operators, statements
+
+- Literals: integer, float, string, `true`, `false`, `null`. There are no array
+ or map literals; a list has to arrive through `params`.
+- Arithmetic `+ - * / %`, comparison `< <= > >= == !=`, logical `&& || !`,
+ ternary `? :`, unary `-` and `!`. `+` concatenates when either side is a
+ string.
+- Declarations `double x = ...`, `int`, `long`, `float`, `boolean`, `String`,
+ `def`, `var`. Types are parsed and discarded; the interpreter is dynamically
+ typed.
+- `if (...) { ... } else { ... }`, blocks, `;` separators, explicit
+ `return x;`, and implicit return of the last statement's value.
+- `Math.max`, `min`, `abs`, `log`, `log10`, `sqrt`, `pow`, `exp`, `floor`,
+ `ceil`, `round`, `Math.PI`, `Math.E` (`painless.rs:2490`).
+- `dotProduct(params.q, 'field')` over a numeric vector field, or over a
+ literal array supplied in `params`.
+- On strings: `.length`, `.toString()`, `.toLowerCase()`, `.toUpperCase()`, and
+ the date accessors `getHour`, `getMinute`, `getSecond`, `getDayOfMonth`,
+ `getMonthValue`, `getYear`, `getDayOfWeek`, `getDayOfWeekEnum`,
+ `getDisplayName`. On objects: `.toString()`, `.size()`, `.isEmpty()`, and
+ member lookup. On arrays: `.size()`, `.length`, `.isEmpty()`
+ (`painless.rs:2122-2165`).
+
+### Local functions and lambdas
+
+Both shipped and are exercised by the limit tests. They are not described
+anywhere else in the docs, so in detail:
+
+- A top-level declaration `<type> name(<type> arg, ...) { ... }` becomes a
+ callable value. Parameter and return types are parsed and discarded
+ (`painless.rs:1379`).
+- A lambda literal is `(a, b) -> expr` or `(a, b) -> { ... }`
+ (`painless.rs:1414`). It evaluates to a closure value that can be stored in a
+ variable or passed as an argument.
+- A closure is invoked either by calling its name directly, `compare(a, b)`, or
+ through **any** `.method(args)` call on the value: `s.get()`, `fn.apply(x)`,
+ `pred.test(x)`. The method name is ignored and only the positional arguments
+ matter (`painless.rs:2113`). That covers `Supplier`, `Function`,
+ `BiFunction` and `Predicate` shapes without the interpreter knowing about any
+ of them, which is what OpenSearch's UBI dashboard scripts need.
+- A closure body runs in a fresh scope containing only its bound parameters. It
+ cannot read the caller's locals; `doc`, `params` and `_score` still resolve,
+ because they come from the evaluation context rather than the enclosing scope
+ (`painless.rs:1764`).
+
+### Not implemented
+
+`for`, `while`, `break`, `continue`, `new` and `instanceof` are recognised by
+the tokenizer (`painless.rs:469`) but no statement or expression parser accepts
+them, so a script using any of them fails to parse. There are no loops of any
+kind. There are no array or map literals, no field assignment through
+`doc[...]`, no regular expressions, no `Debug`/`Logger`, and no Java standard
+library beyond the methods listed above. Any unsupported construct is an
+evaluation error, and what happens next depends on the surface (see
+"Error handling" below).
+
+## Resource limits
+
+These are the constants in `painless.rs`. They are enforced, not advisory.
+
+| Limit | Constant | Value | Scope |
+|---|---|---|---|
+| Script source length | `MAX_SCRIPT_LEN` (`:643`) | 65,536 bytes (64 KiB) | per script |
+| Parser nesting depth | `MAX_PARSE_DEPTH` (`:631`) | 100 | per script |
+| Expression evaluation depth | `MAX_EVAL_DEPTH` (`:638`) | 500 | per script |
+| Closure call nesting depth | `MAX_CALL_DEPTH` (`:724`) | 32 | per evaluation |
+| Closure invocations | `MAX_CALL_COUNT` (`:734`) | 10,000 | per evaluation |
+| Work-unit budget | `MAX_SCRIPT_OPS` (`:824`) | 5,000,000 | per evaluation |
+| Wall-clock slice, ceiling | `MAX_EVAL_SLICE` (`:857`) | 500 ms | per evaluation |
+| Wall-clock slice, floor | `MIN_EVAL_SLICE` (`:873`) | 100 ms | per evaluation |
+| Single string value | `MAX_PAINLESS_STRING_LEN` (`:653`) | 1,048,576 bytes (1 MiB) | per evaluation |
+| Compiled-script cache | `MAX_SCRIPT_CACHE_ENTRIES` / `MAX_SCRIPT_CACHE_SRC_BYTES` (`:1571`, `:1577`) | 128 entries, 512 KiB of source | per thread |
+
+An **evaluation** is one script run against one document. A search evaluates
+its scripts once per document, per clause, per aggregation bucket, so read
+"per evaluation" literally.
+
+The **work-unit budget** is the one that bounds cost rather than shape. A unit
+is one interpreter step, plus one unit per 64 bytes (`BYTES_PER_OP`,
+`painless.rs:804`) of any value a step produces or copies. That pricing exists
+because `params.x`, `params['_source']` and `doc['x'].value` each materialise a
+copy behind an expression that looks like constant work. The counter is
+deterministic, with no clock in it, so a trip is reproducible on any machine.
+
+The **wall-clock slice** is the backstop for work the counter prices too
+cheaply. Each evaluation's slice is the enclosing request's remaining time,
+clamped into the 100 ms to 500 ms range above, and it is fixed before any work
+is charged (`PainlessCtx::new`, `painless.rs:158`). The clock is read once per
+1,024 work units (`OPS_PER_CLOCK_CHECK`, `painless.rs:849`), so an evaluation
+can overshoot its deadline by one sampling window plus the step in flight.
+
+Two figures recorded next to those constants and pinned by tests in
+`engine/crates/xerj-engine/tests/painless_cpu_budget.rs`: the largest benign
+script the 64 KiB source cap admits costs 34,407 work units, which leaves the
+5,000,000 ceiling a 145x margin; and the four adversarial shapes that motivated
+the budget cost 9.03 s, 37.35 s, 17.17 s and 1.13 s **per document** without it,
+and 97 ms, 109 ms, 168 ms and 155 ms with it.
+
+## What a caller sees when a limit trips
+
+Source length, parse depth and evaluation depth are checked before anything
+runs. `check_script_limits` (`painless.rs:1665`) compiles a script without
+evaluating it and reports only those three, and every search entry point walks
+the request body for scripts
+under `script` and `*_script` keys before executing
+(`es_compat.rs:5221`). The walked fields are exactly `query`, `rescore`,
+`sort`, `script_fields`, `runtime_mappings` and `aggs`/`aggregations`
+(`GuardedField::ALL`, `es_compat.rs:5326`), and the same set is applied on
+`_search`, scroll and async search (through `build_search_request`,
+`es_compat.rs:5451`) and on `_msearch`, `_search/template` and
+`_msearch/template` (through the raw-body resolver, `es_compat.rs:18231`,
+`:24476`, `:24668`).
+
+A violation caught by that guard is a 400 before any document is touched. The
+exception type is not the same on every entry point, so check the status rather
+than the type:
+
+- `_search`, scroll, async search and `_search/template` raise
+ `XerjError::invalid_query`, which the error layer renders as HTTP 400 with
+ `"type": "search_phase_execution_exception"` and the limit message as
+ `reason` (`es_compat.rs:5452`, `:24477`; mapping table in
+ `xerj-api/src/error.rs:269`).
+- `_msearch` and `_msearch/template` fail only the offending sub-request, with
+ `{"error": {"type": "illegal_argument_exception", "reason": "..."},
+ "status": 400}` in that item's slot and the rest of the batch still running
+ (`es_compat.rs:18231`, `:24668`).
+
+The remaining limits depend on the data and can only trip mid-evaluation. Those
+faults are recorded into a task-local sink installed for the whole request
+(`with_script_fault_capture`, `painless.rs:977`), and the handler turns the
+first one into an error response instead of serving a substituted value. That
+response is HTTP 400 with this body (`script_limit_response`,
+`es_compat.rs:5257`):
+
+```json
+{
+ "error": {
+ "root_cause": [{ "type": "script_exception", "reason": "<reason>" }],
+ "type": "script_exception",
+ "reason": "<reason>"
+ },
+ "status": 400
+}
+```
+
+`_msearch` embeds that same object as one sub-response inside its 200 envelope
+(`script_limit_error_value`, `es_compat.rs:5268`).
+
+Endpoints that run a search internally do not carry the up-front guard, but
+they do refuse rather than report a truncated result when a limit trips during
+matching: `_count` (`es_compat.rs:15390`), `_reindex` (`:17738`),
+`_delete_by_query` (`:20257`) and `_update_by_query` (`:20377`) all return the
+`script_exception` body instead of a count, a copy or a delete count taken over
+a fail-closed subset.
+
+The `reason` is one of these exact strings (`is_resource_limit_error`,
+`painless.rs:896`):
+
+| Limit | `reason` |
+|---|---|
+| Source too long, up front | `compile error: script source is N bytes, exceeds the 65536-byte limit` |
+| Source too long, at evaluation | `script source is N bytes, exceeds the 65536-byte limit` |
+| Parse depth | `compile error: script exceeds maximum nesting depth` |
+| Evaluation depth | `script evaluation exceeded maximum depth; split the expression into smaller statements` |
+| Closure call depth | `script evaluation exceeded maximum closure call depth; reduce the recursion depth` |
+| Closure invocation count | `script evaluation exceeded the maximum closure invocation count` |
+| Work budget | `script evaluation exceeded its per-document work budget; simplify the script` |
+| Time budget | `script evaluation exceeded its per-document time budget; simplify the script` |
+
+Once one evaluation has tripped a limit, every later evaluation inside the same
+fault-capture scope returns that error immediately without running
+(`eval_painless`, `painless.rs:1701`). That is what makes one budget the bound
+for the whole request rather than one budget multiplied by the document count.
+The scope is installed by `_search` (`es_compat.rs:6438`), by the engine's
+`Index::search` (`index.rs:12534`), and by `_update` and `_update_by_query`
+(`es_compat.rs:14924`, `:20394`). `POST /_scripts/painless/_execute` installs
+no scope; it runs one script and returns any error from it, including a limit
+message, as a 400 `script_exception` whose reason is prefixed with
+`cannot evaluate script: ` (`es_compat.rs:24993`).
+
+`POST /_scripts/painless/_execute` is stricter and answers differently: its
+source cap is 4,096 bytes and an oversize script gets HTTP 413 with
+`action_request_validation_exception` (`es_compat.rs:24911`).
+
+### Errors that are not limits
+
+A script that XERJ cannot parse or evaluate, including one that uses real
+Painless features outside this subset, is **not** a 400. It degrades, per
+surface:
+
+- `script` query: the document does not match. A script that returns anything
+ other than boolean `true` also does not match (`index.rs:26502`).
+- `script_score` and script rescore: the score contribution becomes `0.0`
+ (`index.rs:33162`, `index.rs:28362`).
+- `script_fields`: the field is absent from the hit (`es_compat.rs:11051`).
+- Script-bucketed `terms` agg: no buckets from that document
+ (`aggs.rs:3292`).
+- `terms_set.minimum_should_match_script`: the document cannot match
+ (`index.rs:26575`).
+
+This split is deliberate. A script outside the subset has to keep degrading so
+that an otherwise-working request does not start failing; a resource-limit trip
+is a script that was understood and refused, where a substituted `0.0` or `[]`
+would be a plausible wrong answer. The contract is covered by
+`engine/crates/xerj-api/tests/script_limits_http.rs`, including the
+"unsupported syntax still degrades quietly" case.
+
+## Scripted updates
+
+`POST /{index}/_update/{id}` and `POST /{index}/_update_by_query` accept a
+`script`, but they do not run the general interpreter over the whole script.
+`apply_painless_update` (`es_compat.rs:15167`) splits the source on top-level
+`;`, and each statement must target `ctx._source`:
+
+| Form | Example |
+|---|---|
+| Assignment | `ctx._source.status = 'done'` |
+| Compound assignment | `ctx._source.count += params.n` |
+| Increment and decrement | `ctx._source.views++` |
+| Remove a field | `ctx._source.remove('tmp')` |
+
+Right-hand sides go through the interpreter, with `ctx._source.x` rewritten to
+`doc['x'].value` first (`es_compat.rs:15087`), so `params`, `Math.*` and the
+operators above all work there.
+
+Real limitations of this path, from the same function:
+
+- There is no control flow. Because statements are split on `;`, an `if` block
+ in an update script produces fragments that do not start with `ctx._source`
+ and the request fails with
+ `unsupported update script statement: <statement>` as a 400.
+- Other `ctx.*` statements are accepted and ignored. `ctx.op = 'noop'` and
+ `ctx.op = 'delete'` parse without error and do nothing, so the document is
+ still rewritten (`es_compat.rs:15216`). This differs from Elasticsearch.
+- An unrecognised statement is an error rather than a quiet no-op, which is the
+ opposite of the search-path behaviour described above.
+
+### The request-level budget, and what it does not cover
+
+Before rc.10 these two endpoints reached the interpreter through
+`transform_document_serialized`, which established neither a request deadline
+nor a fault sink, so every statement of every document got its own full slice.
+As of rc.10 (#153) both wrap the work in one deadline and one fault sink:
+
+- `SCRIPTED_UPDATE_BUDGET_MS = 30_000` (`es_compat.rs:20362`), the same 30 s
+ `_search` falls back to when a request names no timeout.
+- `_update` sets that deadline around the transform (`es_compat.rs:14923`).
+- `_update_by_query` sets it around the whole hit loop, and the loop itself
+ checks it per hit and breaks (`es_compat.rs:20409`). When it breaks early the
+ response reports `"timed_out": true` instead of the hardcoded `false` it used
+ to return.
+- A limit trip is reported once for the request rather than once per document
+ (`es_compat.rs:20463`).
+
+The honest residual, which is a property of the search path rather than of the
+update path: **the work budget and the time slice are per evaluation, meaning
+per document.** `PainlessCtx::new` builds a fresh counter and a fresh deadline
+for every document (`painless.rs:158`), so a script tuned to stay just under
+5,000,000 work units costs that much on every matched document and never trips.
+What bounds a search as a whole is the request deadline, `timeout` in the
+request or 30,000 ms by default (`index.rs:12508`), plus the fail-fast on the
+first fault described above.
+
+The per-evaluation slice also has a floor. Once the request deadline has
+passed, each evaluation still gets `MIN_EVAL_SLICE` (100 ms) rather than being
+cut off instantly, because the document scan only notices an expired deadline
+at a document boundary and cutting evaluations off immediately would turn
+ordinary slow searches into `script_exception` 400s
+(`painless.rs:859-873`). So an expensive-but-legal script can continue to
+consume up to 100 ms per document past the deadline until the scan stops.
+
+## Examples
+
+Against a server started with `xerj --data-dir ./data --insecure`, listening on
+`localhost:9200`.
+
+A `script` query as a filter:
+
+```sh
+curl localhost:9200/orders/_search -H 'content-type: application/json' -d '{
+ "query": {
+ "script": {
+ "script": {
+ "source": "doc[\"total\"].size() == 0 ? false : doc[\"total\"].value > params.floor",
+ "params": { "floor": 100 }
+ }
+ }
+ }
+}'
+```
+
+`script_score`, combining the query score with a field:
+
+```sh
+curl localhost:9200/orders/_search -H 'content-type: application/json' -d '{
+ "query": {
+ "script_score": {
+ "query": { "match": { "title": "laptop" } },
+ "script": { "source": "_score * Math.log(2 + doc[\"views\"].value)" }
+ }
+ }
+}'
+```
+
+A runtime field, using a lambda as the predicate:
+
+```sh
+curl localhost:9200/orders/_search -H 'content-type: application/json' -d '{
+ "runtime_mappings": {
+ "big_order": {
+ "type": "boolean",
+ "script": {
+ "source": "def over = (n) -> n > 100; emit(over.test(doc[\"total\"].value))"
+ }
+ }
+ },
+ "fields": ["big_order"],
+ "_source": false
+}'
+```
+
+A scripted update:
+
+```sh
+curl -X POST localhost:9200/orders/_update/order-1 \
+ -H 'content-type: application/json' -d '{
+ "script": {
+ "source": "ctx._source.views++; ctx._source.status = params.next",
+ "params": { "next": "shipped" }
+ }
+}'
+```
+
+An update by query:
+
+```sh
+curl -X POST localhost:9200/orders/_update_by_query \
+ -H 'content-type: application/json' -d '{
+ "query": { "term": { "status": "new" } },
+ "script": { "source": "ctx._source.priority = 1" }
+}'
+```
+
+Standalone evaluation, which has params but no document:
+
+```sh
+curl -X POST localhost:9200/_scripts/painless/_execute \
+ -H 'content-type: application/json' -d '{
+ "script": { "source": "params.a * params.b", "params": { "a": 6, "b": 7 } }
+}'
+```
+
+The response is `{"result": "42.0"}`. Results are stringified, and whole
+numbers keep one decimal place, matching Elasticsearch
+(`es_compat.rs:24976`).
+
+## Performance notes
+
+Compiled ASTs are cached per thread and keyed by source text, including parse
+failures, because an invalid script is also re-evaluated once per document
+(`painless.rs:1643`). The cache is bounded by both entry count and total source
+bytes, since the key is caller-supplied text.
+
+There are no published latency numbers for script execution in this repo, so
+this document does not give any. The two measured figures quoted above are the
+work-budget calibration numbers recorded in `painless.rs` and pinned by
+`engine/crates/xerj-engine/tests/painless_cpu_budget.rs`.
diff --git a/docs/SECOND_BRAIN.md b/docs/SECOND_BRAIN.md
new file mode 100644
index 000000000..9f12c79f0
--- /dev/null
+++ b/docs/SECOND_BRAIN.md
@@ -0,0 +1,572 @@
+# The XERJ second brain
+
+A second brain is a relationship layer over documents that already exist in
+XERJ. It is not a graph database. There is no query language, no shortest-path,
+no PageRank and no unbounded traversal. Edges are ordinary XERJ documents, and
+traversal is a bounded, batched, columnar read of at most two hops per call.
+
+The implementation contract is
+[`docs/design/SECOND_BRAIN_SPEC.md`](./design/SECOND_BRAIN_SPEC.md); the source
+is authoritative. A worked end-to-end run against this repository's own `docs/`
+folder is in [`docs/usecases/second-brain/`](./usecases/second-brain/README.md).
+
+## What a brain is
+
+A brain is a name, plus two reserved indices derived from that name.
+
+| Role | Index | Source |
+|---|---|---|
+| Edges | `.xerj-memory-{brain}-edges` | `authz::brain_edges_index` (`engine/crates/xerj-api/src/authz.rs:153`) |
+| Nodes (default) | `.xerj-memory-{brain}` | `authz::memory_namespace_index` (`engine/crates/xerj-api/src/authz.rs:159`) |
+
+The reserved prefix is `.xerj-memory-`
+(`engine/crates/xerj-common/src/types.rs:190`), which is the same namespace the
+agent-memory API uses. A brain's default nodes index is therefore the
+agent-memory namespace of the same name.
+
+Nodes are just documents. The graph layer never interprets them, it only stores
+their ids as `src` and `dst` strings. Anything with a document id can be a node,
+including agent-memory entries and autoindex section documents.
+
+Edges are ordinary documents too. They live in the edges index with an explicit
+mapping and ride the normal write path (WAL, memtable, segment, doc values), so
+replay, flush, merge and snapshots work on them because they are documents. The
+mapping is written identically by both writers, the HTTP handler
+(`graph_api::edge_index_mapping`, `engine/crates/xerj-api/src/graph_api.rs:205`)
+and the autoindex detector pipeline
+(`detect::edge_index_mapping`, `engine/crates/xerj-autoindex/src/detect/mod.rs:101`):
+
+| Field | Type |
+|---|---|
+| `edge_id`, `src`, `dst`, `type`, `detector`, `src_file`, `src_format`, `dst_format` | `keyword` |
+| `weight`, `confidence` | `float` |
+| `valid_at`, `invalid_at`, `created_at`, `expired_at` | `date`, format `epoch_millis` |
+| `schema_version` | `integer` |
+| `evidence.quote` | `text` |
+| `evidence.source` | `keyword` |
+| `evidence.offset` | `long` |
+
+Timestamps are stored as epoch-millisecond numbers, never as ISO strings.
+
+The `_id` of an edge document is derived, not random:
+
+```
+edge_id = xxh3_128("xg1\0" src "\0" type "\0" dst "\0" decimal(valid_at_ms))
+```
+
+rendered as 32 lowercase hex characters. Both writers pin the same function
+(`graph_api.rs:185`, `detect/mod.rs:45`). The consequence is that the same
+`(src, type, dst, valid_at)` produces the same document id, so re-asserting an
+edge overwrites instead of duplicating, and a re-run of the detectors over an
+unchanged corpus converges instead of growing.
+
+Each edges index also holds one reserved meta document with `_id`
+`__xerj-brain-meta` (`graph_api.rs:110`). It carries `meta_version`, `brain`,
+`nodes_index` and `created_at`. It has no `src` or `dst`, and every count and
+traversal filters on `exists: src`, so the meta document never appears as an
+edge.
+
+Brain names are validated the same way in both crates (`graph_api.rs:150`,
+`detect/mod.rs:69`): non-empty, at most 200 characters, first character a
+lowercase letter or digit, remaining characters from `a-z 0-9 _ - .`, no `..`,
+and the name must not end in `-edges` (that suffix is reserved for the edge
+index of the brain without it).
+
+## Creating one
+
+Two commands build a brain from a folder. Both take `--brain <NAME>`.
+
+```
+xerj autoindex <folder> --brain <NAME>
+xerj brain <folder> [--brain <NAME>]
+```
+
+`xerj autoindex` is the discovery and indexing pipeline. Its help text
+(`engine/crates/xerj-autoindex/src/cli.rs:82`) documents the flag as:
+
+```
+--brain <NAME> second-brain name; relationship edges land in
+ .xerj-memory-<NAME>-edges (default: folder name slug)
+--no-graph skip relationship detection (wikilinks, local links,
+ section order, directory chains) — no edges are written
+```
+
+When `--brain` is omitted the name is derived from the root folder's basename
+(`xerj_autoindex::derive_brain_name`, `engine/crates/xerj-autoindex/src/lib.rs:429`),
+falling back to `brain` when the basename sanitizes to nothing. The name is
+validated at argument-parse time, so a bad name fails before the indexing work
+starts (`cli.rs:211`).
+
+`xerj brain <folder>` is the one-command form: it boots or attaches to a server,
+runs the same pipeline with graph detection on, and opens the console
+(`engine/crates/xerj-server/src/brain.rs:61`, dispatched at
+`engine/crates/xerj-server/src/main.rs:1560`). Its own `--brain <NAME>` defaults
+to the folder's name.
+
+You can also build a brain with no folder at all, by asserting edges through the
+HTTP API. The edges index is created lazily on the first `link` call.
+
+## The endpoints
+
+All four graph routes are mounted on the ES-compatible router, alongside the
+agent-memory routes (`engine/crates/xerj-api/src/router.rs:769`):
+
+```
+POST /_memory/{namespace} store
+GET /_memory/{namespace} list
+DELETE /_memory/{namespace} drop the namespace
+POST /_memory/{namespace}/_recall recall
+DELETE /_memory/{namespace}/{id} forget one
+
+POST /_graph/{brain}/link assert an edge
+DELETE /_graph/{brain}/link/{edge_id} retire an edge
+GET /_graph/{brain}/ego bounded neighbourhood
+GET /_graph/{brain}/overview brain-level stats
+```
+
+Graph errors use one shape (`graph_api.rs:238`):
+
+```json
+{"error": {"type": "graph_error", "reason": "<message>"}, "status": 400}
+```
+
+The examples below assume a server started with `--insecure`, which is open
+mode: one user, no configuration, no credential needed. On a secured server add
+`-H "Authorization: ApiKey <key>"`; see the authorization section.
+
+### POST /_graph/{brain}/link
+
+Asserts an edge. Creates the edges index and its meta document on first use.
+Returns 201 when the derived id is new and 200 when the same
+`(src, type, dst, valid_at)` is re-asserted.
+
+```bash
+curl -s -X POST 'http://localhost:9200/_graph/notes/link' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "src": "note-fermentation",
+ "dst": "note-sourdough",
+ "type": "relates_to",
+ "evidence": {"quote": "sourdough is a wild fermentation", "source": "notes/bread.md", "offset": 412}
+ }'
+```
+
+Body fields (`LinkBody`, `graph_api.rs:377`). Unknown fields are rejected with a
+400, so a typo cannot silently drop part of an assertion.
+
+| Field | Required | Default | Notes |
+|---|---|---|---|
+| `src` | yes | | non-empty; `src == dst` is a 400 |
+| `dst` | yes | | non-empty |
+| `type` | yes | | non-empty |
+| `weight` | no | `1.0` | must be finite, clamped to `[0, 1]` |
+| `confidence` | no | `1.0` | must be finite, clamped to `[0, 1]` |
+| `valid_at` | no | server now | epoch-ms number or RFC3339 string |
+| `created_at` | no | server now | epoch-ms number or RFC3339 string |
+| `detector` | no | `"manual@1"` | free string |
+| `evidence` | no | omitted | must be an object; `{quote, source, offset}` is the shape the readers expect |
+
+When `evidence.source` is a string it is mirrored to the top-level `src_file`
+field (`graph_api.rs:514`), which is what makes replacement-style invalidation a
+doc-values term query rather than an object scan.
+
+The response echoes the stored document:
+
+```json
+{"brain": "notes", "edge_id": "<32 hex chars>", "created": true, "edge": { ... }}
+```
+
+### DELETE /_graph/{brain}/link/{edge_id}
+
+Retires an edge. It never removes the document. The same document is re-indexed
+under the same `_id` with `invalid_at` and `expired_at` added
+(`graph_api.rs:567`).
+
+```bash
+curl -s -X DELETE 'http://localhost:9200/_graph/notes/link/<edge_id>?invalid_at=2026-07-01T00:00:00Z'
+```
+
+`invalid_at` accepts an epoch-ms number or an RFC3339 string and defaults to
+server now. `expired_at` is always server now and is not caller-settable.
+
+Retiring an already-retired edge is a no-op that reports the standing fact:
+
+```json
+{"brain": "notes", "edge_id": "...", "invalidated": false, "already_invalid_at": 1751328000000}
+```
+
+An unknown edge id, or an unknown brain, is a 404 with
+`"edge '<id>' does not exist in brain '<brain>'"`.
+
+### GET /_graph/{brain}/ego
+
+The bounded neighbourhood of one node, or of several seeds.
+
+```bash
+curl -s 'http://localhost:9200/_graph/notes/ego?node=note-sourdough&hops=2&include_nodes=true'
+```
+
+Query parameters (`EgoParams`, `graph_api.rs:665`):
+
+| Parameter | Default | Notes |
+|---|---|---|
+| `node` | | the node id to expand from; mutually exclusive with `nodes` |
+| `nodes` | | comma-separated seed ids; deduped, capped at 64, the clip counted in `not_shown.frontier_clipped` |
+| `hops` | `1` | `1` or `2` only; anything else is a 400 |
+| `direction` | `both` | `out`, `in` or `both` |
+| `types` | all types | comma-separated edge-type allowlist |
+| `limit` | `100` | clamped to `1..=1000` |
+| `as_of` | now | epoch-ms number or RFC3339 string |
+| `include_expired` | `false` | also return retired edges |
+| `include_nodes` | `false` | hydrate node summaries from the nodes index |
+| `nodes_index` | brain meta, else `.xerj-memory-{brain}` | authorized separately, see below |
+| `include_evidence` | `true` | hydrate `evidence`, `detector`, `confidence`, `created_at`, `expired_at` on returned edges |
+
+Omitting both `node` and `nodes` is a 400. Supplying both is a 400. A brain with
+no edges index is a 404.
+
+The response carries `brain`, `contract` (`"xerj-second-brain/1"`), `seeds`
+(plus `node` when there is exactly one seed), `as_of`, `hops`, `direction`,
+`edges`, `neighbors`, `not_shown`, and `nodes` when `include_nodes=true`.
+Each edge carries `edge_id`, `src`, `dst`, `type`, `weight`, `hop`, `direction`,
+`valid_at` and `invalid_at` (JSON null when the edge is live), plus the
+hydrated fields when `include_evidence` is on.
+
+`not_shown` is filled on every response and counts what was withheld:
+`edges_clipped`, `frontier_clipped`, `expired_excluded`, `type_filtered`,
+`segments_without_columns`, `memtable_docs_scanned`, `dangling_nodes` and
+`dangling_ids` (up to 50 ids listed verbatim). A node id that resolves to no
+document in the nodes index is reported as dangling; the edge is kept and
+nothing is invented for the missing node.
+
+Node hydration reads `title`, `text` or `body` (first 160 characters, as
+`preview`), and `ax_path` (as `path`). `path` is null for nodes that carry no
+`ax_path`, such as hand-written ones. It is not guessed.
+
+### GET /_graph/{brain}/overview
+
+Brain-level totals and breakdowns, built from three searches on the edges index
+plus one count on the nodes index.
+
+```bash
+curl -s 'http://localhost:9200/_graph/notes/overview?top=10&histogram_interval=day'
+```
+
+Query parameters (`OverviewParams`, `graph_api.rs:1081`): `as_of` (default now),
+`top` (default 10, clamped `1..=50`), `histogram_interval` (`day` by default,
+`hour` accepted, anything else is a 400).
+
+The response carries `brain`, `contract`, `exists`, `as_of`, `nodes_index`,
+`nodes.total`, `embedder`, `edges` (`total`, `live`, `invalidated`), `types`,
+`detectors`, `hubs.out`, `hubs.in`, `created_over_time`, and a `not_shown`
+object reporting each aggregation's unlisted tail
+(`types_not_listed`, `detectors_not_listed`, `hubs_out_not_listed`,
+`hubs_in_not_listed`).
+
+`total` counts every edge ever asserted; `live` counts the edges visible at
+`as_of`; `invalidated` is the difference. `created_over_time` is a
+`date_histogram` over `created_at` across all asserted edges, so retiring an
+edge does not erase it from the timeline.
+
+`embedder` reports the node store's configured embedder id, and reports
+`lexical-feature-hash` for the built-in default (`graph_api.rs:1149`). The
+built-in embedder is lexical feature hashing, not a neural model.
+
+A brain that does not exist returns 404 with a short body rather than an error
+envelope:
+
+```json
+{"brain": "notes", "contract": "xerj-second-brain/1", "exists": false}
+```
+
+### Recall coupled to the graph
+
+`POST /_memory/{namespace}/_recall` takes an optional `graph` object
+(`GraphRecallOpts`, `engine/crates/xerj-api/src/memory_api.rs:454`). The brain
+of a namespace is the namespace itself: recall expands over
+`.xerj-memory-{namespace}-edges`. When `graph` is absent, recall behaves exactly
+as it did before the graph existed.
+
+```bash
+curl -s -X POST 'http://localhost:9200/_memory/notes/_recall' \
+ -H 'Content-Type: application/json' \
+ -d '{"query": "fermentation", "k": 10,
+ "graph": {"mode": "blend", "hops": 2, "weight": 0.3}}'
+```
+
+| Field | Required | Default | Notes |
+|---|---|---|---|
+| `mode` | yes | | `restrict` or `blend`; anything else is a 400 |
+| `seeds` | for `restrict` | for `blend`, the ids of the top 5 base-recall hits | `restrict` with absent or empty seeds is a 400 |
+| `hops` | no | `1` | `1` or `2` |
+| `types` | no | all | edge-type allowlist |
+| `weight` | no | `0.3` | blend weight, clamped to `[0, 1]`; ignored for `restrict` |
+| `as_of` | no | now | epoch-ms number or RFC3339 string |
+
+`restrict` narrows recall to the documents reachable from the seeds. `blend`
+leaves the candidate set alone and re-ranks it by
+`(1 - w) * normalized_score + w * proximity`, where proximity is `1.0` for a
+seed and `0.5^hop * clamp(weight, 0, 1)` for a node reached at that hop, taking
+the maximum over paths (`memory_api.rs:916`). Blended hits carry a
+`graph_proximity` field.
+
+The response gains a `graph` object with `mode`, `seeds`, `hops`, `as_of`,
+`reachable` (a count) and its own `not_shown`. If the brain has no edges index,
+recall proceeds ungated and `not_shown.no_edges_index` is `true` rather than the
+request failing quietly (`memory_api.rs:957`). The reachable set folded into a
+`restrict` filter is capped at 10,000 ids (`memory_api.rs:478`).
+
+Note that `/_memory/{namespace}/_recall` requires exactly one of `query` or
+`vector`, and rejects unknown fields with a 400.
+
+## Evidence on links
+
+Every edge the detectors emit carries the text that taught it. The assembled
+document sets `evidence.quote`, `evidence.source` and `evidence.offset` for
+every detected edge (`detect/mod.rs:570`), where `source` is the root-relative
+path of the file the edge was read from and `offset` is the byte offset within
+the section text. The quote is the full trimmed line containing that offset,
+clipped to 240 characters (`detect::line_at`, `detect/mod.rs:416`). The same
+path is mirrored into the top-level `src_file` field.
+
+Two of the seven detectors do not have an author's sentence to quote, because
+they fire on file layout rather than on text. They record a generated rationale
+in the same field instead, with offset 0:
+
+- `samedir` writes `"<a> and <b> share directory <dir>"` (`detect/samedir.rs:54`)
+- `sequence` writes `"<label> precedes <label> of <file>"`, or
+ `"<label> opens <file>"` for the first section (`detect/sequence.rs:40`)
+
+The console reads that distinction back out and renders it differently: a quote
+is shown in quotation marks, a structural rationale is shown prefixed with
+`WHY —` and never wearing quotation marks, and an edge with no evidence at all
+is shown as `no evidence recorded — asserted, not detected`
+(`xerj-ux/src/ux/ego-ledger.js:111`, `xerj-ux/src/ux/brain-map.js:1452`).
+
+That last case is the one that matters for hand-asserted links. `POST
+/_graph/{brain}/link` stores `evidence` only when the caller supplies it. When
+you assert a link by hand or from an agent without a quote, the stored document
+simply has no `evidence` field, and the reader says so. Nothing is fabricated to
+fill the gap.
+
+The honest claim is "every link shows its evidence", not "every link has a
+quote".
+
+## The seven detectors, and what they do not do
+
+Seven detectors ship. They are the complete contents of
+`engine/crates/xerj-autoindex/src/detect/`, registered in
+`detect::default_detectors` (`detect/mod.rs:383`):
+
+| Detector | Edge `type` | `detector` tag | Weight | Confidence | Fires on |
+|---|---|---|---|---|---|
+| `wikilink` | `wikilink` | `wikilink@2` | 1.0 | 0.95 | `[[Target]]` or `[[Target\|alias]]` resolving to a corpus file |
+| `mdlink` | `mdlink` | `mdlink@2` | 0.9 | 0.9 | `[text](relative/path.md)` resolving to a corpus file |
+| `href` | `href` | `href@2` | 0.7 | 0.85 | `<a href="...">` to a corpus file, html-sniffed files only |
+| `pathcite` | `pathcite` | `pathcite@1` | 0.6 | 0.7 | a bare file path in prose that resolves to a corpus file |
+| `cratecite` | `cratecite` | `cratecite@1` | 0.5 | 0.6 | a crate directory name in prose, linking to that directory's `Cargo.toml` |
+| `sequence` | `sequence` | `sequence@2` | 0.8 | 0.99 | the file card, then each section preceding the next within one file |
+| `samedir` | `same_dir` | `samedir@2` | 0.3 | 0.4 | files sharing a directory, chained in path order, never a clique |
+
+The `@N` suffix on the tag is the detector version. It is bumped on any
+behaviour change, so old edges stay attributable to the rules that produced
+them.
+
+Detectors are deterministic and versioned. There is no LLM in this path. The
+same corpus produces a byte-identical edge set on every run, given unchanged
+file mtimes, because edge identity is a hash of `(src, type, dst, valid_at)` and
+`valid_at` is the source file's mtime rather than the wall clock
+(`detect/mod.rs:316`).
+
+**All seven detectors are structural. They find explicit citations and file
+layout. None of them looks at what a document is about.** If two documents cover
+the same topic but neither links to nor names the other, no detector will
+connect them. Point XERJ at a folder of recipes and sourdough will not connect
+to kimchi, even though both are fermentation. A corpus of plain-text notes that
+do not cross-reference each other produces a graph whose only edges are
+`sequence` within each file and `same_dir` between neighbouring files.
+
+This is a known gap, not a bug, and it is tracked as
+[issue #164](https://github.com/xerj-org/xerj/issues/164), "Second brain cannot
+connect documents by topic, only by explicit citation". A shared-term detector
+is proposed there. Until it lands, do not expect topic linking, and read
+`same_dir` for what it is: directory co-location, weighted 0.3, the floor of the
+detector set, standing in for a topic signal that does not exist yet.
+
+## The hop cap
+
+`hops` is `1` or `2`. Anything else is a 400 whose body carries this exact
+sentence (`GRAPH_HOPS_CAP_REASON`, `engine/crates/xerj-engine/src/graph.rs:69`):
+
+```
+hops is capped at 2: XERJ's second brain is a relationship layer over documents,
+not a graph database (no Cypher, no shortest-path, no variable-depth traversal).
+Iterate: expand again from this response's 'reachable' ids.
+```
+
+(That is one line in the source and in the response; it is wrapped here to fit.)
+
+`hops=0` is refused by the same check. Called directly on the engine rather
+than through HTTP, `hops=0` gets `hops must be at least 1.` prepended to that
+same sentence (`graph.rs:242`).
+
+The same string is used by `/_graph/{brain}/ego` (`graph_api.rs:774`) and by the
+`graph` block of `/_memory/{namespace}/_recall` (`memory_api.rs:843`), so the
+wording does not vary by surface.
+
+Depth beyond two hops composes on the client: take ids from the previous
+response and expand again from them. `ego` accepts up to 64 seeds per call
+through `nodes=` for exactly this.
+
+Other bounds in the engine, all reported rather than silent
+(`graph.rs:55`-`63`, `graph.rs:120`):
+
+| Bound | Value | Reported as |
+|---|---|---|
+| Hops | 2 | 400 with the sentence above |
+| Frontier ids per hop | 4096 | `not_shown.frontier_clipped` |
+| Result edges per request | 100,000 | `not_shown.edges_clipped` |
+| `ego` seeds per call | 64 | `not_shown.frontier_clipped` |
+| `ego` returned edges | `limit`, clamped to 1000 | `not_shown.edges_clipped` |
+| `restrict` reachable ids | 10,000 | `graph.not_shown.reachable_clipped` |
+
+A segment that lacks the doc-values columns the hop needs is skipped and counted
+in `segments_without_columns`. The hop never falls back to reading `_source`, so
+a skipped segment is always reported.
+
+## Bi-temporal behaviour
+
+Links are retired, not deleted. `DELETE /_graph/{brain}/link/{edge_id}`
+re-indexes the same document under the same `_id`, adding two timestamps:
+
+- `invalid_at` is when the fact stopped being true. It is caller-settable and
+ defaults to server now.
+- `expired_at` is when the system recorded that. It is always server now.
+
+Those are the two clocks. `valid_at` and `created_at` are their counterparts on
+the assertion side: `valid_at` is when the fact became true, `created_at` is when
+the system recorded it.
+
+Visibility at a given instant is decided by `bitemporal_visible`
+(`graph.rs:198`):
+
+```
+visible(as_of) = valid_at <= as_of AND (invalid_at is absent OR invalid_at > as_of)
+```
+
+`include_expired=true` disables only the second half. An edge asserted after
+`as_of` stays invisible either way, because it did not exist in the world being
+asked about. Edges excluded by this rule are counted in
+`not_shown.expired_excluded`.
+
+Passing `as_of` to `ego` or `overview` therefore answers "what did this brain
+believe at that moment", including edges that have since been retired. Since a
+different `valid_at` yields a different derived `edge_id`, re-asserting a fact at
+a new `valid_at` creates a distinct edge rather than mutating the old one, which
+is what keeps the history intact.
+
+One consequence to be aware of: because retirement is a re-index of the same
+document rather than a delete, an edges index never shrinks through the graph
+API. Reclaiming space means deleting documents through the ordinary index APIs,
+which discards the history.
+
+## The reserved namespace is a tenant boundary
+
+The `.xerj-memory-*` namespace, which holds every agent-memory namespace and
+every second brain, is reserved. Reaching an index in it requires a principal
+that holds the matching privilege on that specific index
+(`engine/crates/xerj-api/src/authz.rs`, module documentation).
+
+The resource a brain authorizes against is its edges index,
+`.xerj-memory-{brain}-edges`. Who can read a brain:
+
+| Principal | Reach |
+|---|---|
+| open mode (`--insecure`, or no admin key configured) | every brain; one user, no configuration |
+| the configured admin key | every brain |
+| a key minted with `role_descriptors` naming the edges index | that brain, at the granted privilege |
+| a key minted without `role_descriptors` | no brain |
+| no or invalid credential | nothing |
+
+`ego` and `overview` need `read`; `link` and `unlink` need `write`. Creating the
+edges index lazily counts as writing the brain, not as a separate `manage` step.
+
+To grant brain `alice` to a key, name both of its indices at mint time. The
+second name is the nodes index, needed for `ego`'s node hydration and
+`overview`'s note count:
+
+Unlike the examples above, this one needs a secured server. Only a superuser can
+mint a scoped key (`es_compat.rs:25507-25522`), so present the admin key XERJ
+wrote to `<data_dir>/admin.key`:
+
+```bash
+curl -s -X POST 'http://localhost:9200/_security/api_key' \
+ -H "Authorization: ApiKey $(cat ./data/admin.key)" \
+ -H 'Content-Type: application/json' \
+ -d '{"name": "alice-agent",
+ "role_descriptors": {"alice": {"indices": [
+ {"names": [".xerj-memory-alice-edges", ".xerj-memory-alice"],
+ "privileges": ["read", "write"]}]}}}'
+```
+
+Minting against an `--insecure` server does return a key, but the key grants
+nothing narrower than everything: open mode resolves every caller to a superuser
+before any credential is examined (`auth.rs:220-222`), so the grant above is
+never consulted. Brain isolation only exists on a server with `auth.enabled` and
+an admin key configured.
+
+A denial is an ES-shaped 403 with `error.type` `security_exception`
+(`authz.rs:242`), naming the resource, the action and the grant that would fix
+it.
+
+Two properties are worth calling out because they are deliberate:
+
+- **Authorization runs before the existence check.** Every graph handler
+ authorizes the caller for the brain before it looks at whether the brain
+ exists, so a brain that is not yours and a brain that does not exist return
+ the same 403 and the status code cannot be used to enumerate brains.
+- **`ego?nodes_index=` is authorized separately.** The nodes index can be
+ redirected by the caller, and the brain's meta document (writable by anyone
+ with `write` on the brain) can point it anywhere, so hydration is authorized
+ against the resolved index in its own right. Without that, `write` on one
+ brain would be a read primitive for every index on the node.
+
+Enforcement is not limited to these four routes. A brain's edges live in an
+ordinary index whose name merely starts with a dot, so it is nameable through
+the generic ES-compatible and native index routes. Those doors are closed at two
+layers that a handler cannot route around: the authorization middleware, which
+resolves targets from the request path and from request bodies (`_bulk`,
+`_msearch`, `_mget`, `_aliases`, `_reindex`, index templates and others), and
+the engine's index guard, which is inside the only funnel to index data. The
+second layer answers "not found" rather than "forbidden", which is what lets
+fan-out verbs such as `POST /_search` and `_cat/indices` filter instead of
+failing.
+
+Two limits stated plainly in the source:
+
+- This makes the reserved namespace a real boundary and confines a scoped key to
+ its grants. It does not turn XERJ into a general multi-tenant authorization
+ system. A key minted without `role_descriptors` keeps its historical reach over
+ ordinary, non-reserved indices.
+- An explicit grant is not second-guessed. A scoped key minted with
+ `names: ["*"]` can reach the reserved namespace, because `*` matches every
+ index and that is what the operator asked for. Only a superuser can mint one.
+ Operators who want brain isolation must grant concrete names, or a prefix that
+ excludes `.xerj-memory-`.
+
+The module documentation at the top of `memory_api.rs` still describes the
+pre-#79 model in which `/_memory/*` had no per-namespace authorization. The
+handlers do call `authz::authorize_memory_namespace` (for example
+`memory_api.rs:318` and `memory_api.rs:490`); the comment is stale, the code is
+not.
+
+## What is not covered here
+
+- Console and MCP surfaces for the second brain exist but are not documented in
+ this file.
+- Edge fields `src_format` and `dst_format` are written by the detectors and are
+ in the mapping, but no endpoint documented above returns them in a shaped
+ response field of their own; they arrive as part of an edge's `_source` when
+ read through the ordinary search API.
+- There are no published performance figures for graph expansion in this
+ repository, so none are quoted here.
diff --git a/docs/SECURITY_MODEL.md b/docs/SECURITY_MODEL.md
new file mode 100644
index 000000000..85bd2e810
--- /dev/null
+++ b/docs/SECURITY_MODEL.md
@@ -0,0 +1,530 @@
+# XERJ Security Model
+
+This document describes the authorization boundaries XERJ actually enforces, as
+implemented in the source. It is written for operators deciding how to deploy a
+node and for contributors adding a handler that touches index data.
+
+Every statement below points at the code that makes it true. Where a control is
+partial, unenforced, or absent, that is stated in the same place rather than in
+a footnote. The source is authoritative; if this document and the code disagree,
+the code is right and this document is a bug.
+
+Primary sources:
+
+| Area | File |
+|---|---|
+| Authentication, `Principal` | `engine/crates/xerj-api/src/auth.rs` |
+| Authorization decision, enforcement points | `engine/crates/xerj-api/src/authz.rs` |
+| Engine-side visibility funnel | `engine/crates/xerj-engine/src/index_guard.rs` |
+| Privileges, roles, `role_descriptors` parsing | `engine/crates/xerj-engine/src/rbac.rs` |
+| Console client identity and rate limiting | `engine/crates/xerj-console-api/src/client_ip.rs`, `.../auth/rate_limit.rs` |
+| Cluster control-frame authentication | `engine/crates/xerj-cluster/src/auth.rs` |
+
+## The two layers
+
+Authorization is decided twice, in two different places, for two different
+reasons.
+
+### Layer 1: the authz middleware
+
+`authz_middleware` (`xerj-api/src/authz.rs:1224`) runs on both HTTP routers. It
+is added to the router before `auth_middleware`, so it runs after it
+(`xerj-api/src/router.rs:786-789`): authentication has already resolved the
+caller to a `Principal`, and this layer decides what that principal may reach.
+
+It does four things:
+
+1. Classifies the path (`classify`, `authz.rs:444`) into a brain, a memory
+ namespace, one or more index expressions, a cluster endpoint, or exempt.
+ Path segments are percent-decoded first (`percent_decode`, `authz.rs:421`),
+ so `%2Exerj-memory-alice` cannot slip past a check that
+ `.xerj-memory-alice` would fail.
+2. Works out the privilege the request needs (`required_privilege`,
+ `authz.rs:505`). `GET`/`HEAD` need read. A `POST` whose operation segment is
+ in `POST_READ_OPS` (`_search`, `_count`, `_msearch`, `_mget`, `_sql` and
+ others, `authz.rs:349`) needs read. Operations in `ADMIN_OPS` (`_settings`,
+ `_mapping`, `_close`, `_alias`, `_forcemerge` and others, `authz.rs:388`)
+ need manage, as does a request with no operation segment at all, because that
+ creates or destroys the index. Everything else is treated as a write.
+3. Extracts the indices the request body names (`body_targets`, `authz.rs:730`)
+ and authorizes each one. The shapes it parses are enumerated in `BodyShape`
+ (`authz.rs:578`): `_bulk` action lines, `_msearch` header lines, `_mget`
+ `docs[]._index`, `_aliases` actions, `_reindex` `source`/`dest`, snapshot
+ `indices`, `PUT /{index}` `aliases`, index-template `index_patterns`, ML job
+ and datafeed configs, the native `POST /v1/indices` body, and a `terms`
+ lookup or `lookup` runtime field at any depth inside a search body. Aliases
+ are resolved to their backing indices before the decision
+ (`authorize_expression`, `authz.rs:1168`).
+4. Installs the principal as the engine's visibility rule for the rest of the
+ request and prunes reserved index names out of metadata responses
+ (`prune_response`, `authz.rs:1431`).
+
+A superuser short-circuits on the first line of the middleware
+(`authz.rs:1237`): no body buffering, no visibility guard, no response pruning.
+For every other principal, the body is buffered only on routes that can name an
+index in it, bounded by `limits.max_body_bytes`; a body over that limit is
+refused with `413` rather than being authorized unread (`authz.rs:1251-1262`).
+
+A denial at this layer is an ES-shaped `403` with `type: security_exception`
+(`forbidden`, `authz.rs:242`; body shape in `xerj-api/src/error.rs:52`). It is
+returned before any existence check, so `403` versus `404` cannot be used to
+enumerate what exists.
+
+A body that should have named its targets but cannot be parsed is refused, not
+ignored (`unresolvable`, `authz.rs:709`).
+
+### Layer 2: the index_guard visibility funnel
+
+The middleware can only check what it knows how to parse. The second layer sits
+where a name becomes an index, which every path must pass through.
+
+`authz_middleware` wraps the inner service in
+`xerj_engine::index_guard::scoped` (`authz.rs:1272-1273`), which sets a `tokio`
+task-local holding an `IndexVisibility` implementation for the principal.
+`PrincipalVisibility::visible` (`authz.rs:304`) answers true when the principal
+holds read, write, or manage on that index: this layer decides whether the
+index may be reached at all, and the middleware still decides which privilege
+the request needs on it.
+
+Six engine functions consult it:
+
+| Function | Line |
+|---|---|
+| `Engine::create_index` | `xerj-engine/src/engine.rs:786` |
+| `Engine::delete_index` | `engine.rs:1110` |
+| `Engine::get_index` (including the alias branch) | `engine.rs:1165`, `engine.rs:1179` |
+| `Engine::get_or_create_index` | `engine.rs:1199` |
+| `Engine::index_name_list` | `engine.rs:1254` |
+| `Engine::list_indices` | `engine.rs:1281` |
+
+A denied name is reported as `XerjError::index_not_found`, not as a refusal.
+That is deliberate (`index_guard.rs:87-99`): a brain you may not read is
+indistinguishable from a brain that does not exist, and fan-out verbs such as
+`GET /_cat/indices` or a `logs-*` wildcard filter to the visible set instead of
+failing wholesale.
+
+### Absent guard means allow, and what follows from that
+
+`index_guard::visible` returns `true` when no guard is installed
+(`index_guard.rs:125-127`, the `unwrap_or(true)`). This is not "permission
+granted": it means no request is in scope. Startup index discovery, WAL replay,
+background flush and merge timers, and snapshot restore all run with no
+task-local set and must not be restricted.
+
+Three consequences follow, and all three are load-bearing:
+
+- **Detached work loses the guard.** A `tokio::spawn` or `spawn_blocking` starts
+ a new task, which does not inherit the task-local. `index_guard::current()`
+ captures the rule on the request's task and `scoped_opt` re-installs it inside
+ the spawned future (`index_guard.rs:146`, `index_guard.rs:161`). This was a
+ live hole, not a hypothetical: the ML datafeed scorer started by
+ `POST /_ml/datafeeds/{id}/_start` re-read its source index on a timer with no
+ guard installed (`index_guard.rs:34-57`). `es_compat::spawn_datafeed_task` is
+ the worked example of carrying the rule across.
+- **rayon workers never see the guard.** A rayon worker is an ordinary OS thread
+ that `tokio` does not poll tasks on, so the thread-local backing the guard is
+ simply unset there. The test `absent_guard_on_a_rayon_worker`
+ (`index_guard.rs:247`) pins this. No rayon closure in the tree resolves an
+ index name; the bulk fan-out parallelises NDJSON parsing only.
+- **A surface outside the middleware must do its own checking.** The Console
+ router is merged onto the engine routers after their layers are applied, so
+ `authz_middleware` never runs for it and its in-process engine calls carry no
+ guard. The Console data-sources proxy therefore refuses the reserved namespace
+ itself, with the same `404` a Console system index gets
+ (`xerj-console-api/src/data_sources.rs:37-48`). The gRPC listener does the
+ same with `Principal::allows_index` (`xerj-server/src/grpc.rs:62-75`) and
+ refuses index patterns outright for non-superusers (`grpc.rs:81-88`).
+
+If you add a surface that reaches `Engine` outside `authz_middleware`, neither
+layer protects it. Check it explicitly.
+
+## The reserved `.xerj-memory-*` namespace
+
+`RESERVED_INDEX_PREFIX` is `.xerj-memory-` and `is_reserved_index` is a prefix
+test (`xerj-common/src/types.rs:190-195`). The definition lives in
+`xerj-common` because more than one crate has to refuse the same namespace.
+
+Indices under this prefix are not ordinary indices. They hold agent-memory
+namespaces and second brains:
+
+- `POST|GET|DELETE /_memory/{ns}` and `/_memory/{ns}/_recall`,
+ `/_memory/{ns}/{id}` operate on `.xerj-memory-{ns}`
+ (`memory_namespace_index`, `authz.rs:159`; routes at
+ `xerj-api/src/router.rs:768-775`).
+- `/_graph/{brain}/link`, `/link/{edge_id}`, `/ego`, `/overview` operate on
+ `.xerj-memory-{brain}-edges` (`brain_edges_index`, `authz.rs:153`; routes at
+ `router.rs:780-783`), and the graph read paths additionally authorize the
+ brain's nodes index (`graph_api.rs:729`, `graph_api.rs:906`).
+
+What makes the namespace special:
+
+- A key minted without usable `role_descriptors` (`Principal::Unscoped`) holds
+ **nothing** here, while keeping its historical reach over ordinary indices
+ (`Principal::allows_index`, `auth.rs:99-106`). That is the fail-closed half:
+ an unconfigured credential is denied the brain, not handed it.
+- A name a caller is about to *create* is checked against `may_reach_reserved`
+ (`authz.rs:177`), which judges a pattern by the literal text before its first
+ `*`. This is what stops an alias, a fresh index, or an index template pattern
+ from squatting the prefix and having a brain resolve through it later
+ (`authorize_template_patterns`, `authz.rs:989`).
+- Handlers under `/_memory` and `/_graph` call
+ `authorize_memory_namespace` / `authorize_brain` themselves as well as being
+ covered by the middleware (`memory_api.rs:319`, `:491`, `:568`, `:1148`,
+ `:1234`, `:1278`; `graph_api.rs:416`, `:578`, `:722`, `:1178`).
+
+One deliberate exception, worth reading before you hand out a key: a grant of
+`names: ["*"]` **does** reach the reserved namespace. `Role::applies_to` treats
+`*` as matching every index, brains included, and this is documented as an
+operator's explicit choice rather than an escalation, because only a superuser
+can mint a scoped key at all (`rbac.rs:72-111`). If you want brain isolation,
+grant concrete names or a prefix that cannot reach the namespace, such as
+`logs-*`.
+
+## Principals
+
+`Principal` (`auth.rs:55-90`) has four variants, in decreasing order of reach.
+
+| Principal | How you become one | Reach |
+|---|---|---|
+| `Superuser` | `auth.enabled = false` (which `--insecure` sets), or an empty `admin_api_key`, or presenting the configured admin key | Everything. Skips the whole authorization path |
+| `Scoped` | A key minted by `POST /_security/api_key` **with** usable `role_descriptors` | Only the indices its roles name, with the privileges those roles carry |
+| `Unscoped` | A key minted **without** usable `role_descriptors` | Ordinary indices as before; nothing in `.xerj-memory-*` |
+| `Denied` | No valid credential, or an expired, invalidated, or unknown one | Nothing |
+
+Accepted credential forms (`authenticate`, `auth.rs:214`):
+
+- `Authorization: ApiKey <key>` and `Authorization: Bearer <key>`, where `<key>`
+ is either the admin key or the `encoded` value of a minted key
+ (`base64("id:api_key")`).
+- `Authorization: Basic <base64(user:pass)>`, where the password half is the
+ admin key (any username), or the decoded `user:pass` is read as a minted
+ key's `id:secret` (`basic_principal`, `auth.rs:257`). Kibana's basic-realm
+ login sends this shape.
+
+All secret comparisons are constant-time after a length check
+(`constant_time_eq`, `auth.rs:364`), on both the admin-key and minted-key paths.
+
+Two paths are exempt from authentication: `/health/live` and `/health/ready`
+(`AUTH_EXEMPT_PATHS`, `auth.rs:41`), so a hardened deployment's probes do not
+crashloop. Neither handler touches index data. `/_security/_authenticate` and
+`/v1/metrics` are exempt from *authorization* classification only
+(`authz.rs:448-453`); `/v1/metrics` still needs the admin key unless
+`auth.metrics_token` is configured, in which case that token opens that one
+endpoint and nothing else (`auth.rs:290-301`).
+
+With `auth.enabled = true` (the default) and no configured key, the server
+generates a 64-character hex admin key on first run, prints it, and writes it to
+`<data_dir>/admin.key` with mode 0600, reusing it on later starts
+(`ensure_admin_key`, `xerj-server/src/main.rs:500-548`).
+
+## API keys and privileges
+
+### What a scoped key can and cannot do
+
+A minted key is **never** a superuser (`check_minted_key`, `auth.rs:330-360`).
+The strongest thing it can be is `Unscoped`.
+
+Minting is gated (`security_create_api_key`,
+`xerj-api/src/es_compat.rs:25507-25580`):
+
+- A `Scoped` caller may not mint at all, and gets a `403`.
+- An `Unscoped` caller may mint, but any `role_descriptors` it supplies are
+ ignored with a warning, so it can only produce more unscoped keys.
+- Only the superuser can mint a scoped key.
+
+`role_descriptors` are parsed by `roles_from_role_descriptors`
+(`rbac.rs:159`), one `Role` per `indices[]` entry. The ES privilege names map
+onto XERJ privileges as follows (`es_index_privilege`, `rbac.rs:123`):
+
+| ES privilege in `role_descriptors` | Granted |
+|---|---|
+| `all` | read + write + manage |
+| `read`, `read_cross_cluster`, `view_index_metadata`, `monitor` | read |
+| `write`, `index`, `create`, `create_doc`, `delete`, `maintenance` | write |
+| `manage`, `create_index`, `delete_index`, `manage_ilm`, `manage_follow_index` | manage |
+| anything else | nothing |
+
+Index-name matching (`Role::applies_to`, `rbac.rs:99`): `*` matches everything,
+a literal name matches exactly, and a **trailing** `*` matches by prefix. A `*`
+in the middle of a pattern matches nothing.
+
+Not honoured, and each one fails closed by granting nothing
+(`rbac.rs:150-158`):
+
+- `cluster` privileges inside a descriptor are ignored. XERJ has no
+ cluster-privilege enforcement.
+- `field_security` and `query` (field-level and document-level security) are
+ ignored. A descriptor that only makes sense with FLS or DLS therefore
+ over-grants at the field level within an index it was already granted. Do not
+ rely on this for field-level control.
+- A descriptor that names no index, or names indices but no recognised
+ privilege, produces no role at all, which makes the key `Unscoped`.
+
+A key also carries expiry and invalidation, both checked on every request before
+the secret comparison (`auth.rs:338-349`).
+
+### Privileges that exist but are not decided
+
+`Privilege` (`rbac.rs:34-49`) has seven variants. Only three of them are ever
+demanded of a principal: `ReadIndex`, `WriteIndex`, and `AdminIndex`.
+`SnapshotCreate`, `SnapshotRestore`, `SecurityAdmin`, and `AuditRead` appear
+only as labels in a `403` message and in a sort key
+(`authz.rs:242-251`, `authz.rs:972-982`, `es_compat.rs:25522`). Nothing checks
+whether a principal holds them, because `role_descriptors` cannot grant them.
+
+### The named role store is data only
+
+`PUT /_security/role/{name}` stores a role and enforces nothing. Every response
+from these handlers carries `"enforced": false` plus a warning string
+(`xerj-api/src/native.rs:900-949`; routes at `router.rs:127-133`), and the PUT
+logs a warning. `RoleStore`'s seeded roles (`admin`, `write`, `read`,
+`read_only_index`, `snapshot_admin`, `auditor`, `rbac.rs:238-278`) are likewise
+inert. The same is true of the application-privilege store behind
+`/_security/privilege` (`es_compat.rs:25628-25631`).
+
+Broad RBAC over the general ES-compatible surface is not implemented. What is
+enforced is the reserved namespace and the confinement of a `Scoped` key to its
+named indices (`authz.rs:94-101`).
+
+## Snapshot and restore
+
+Snapshot and restore are the one place where a wildcard is decided by the
+middleware instead of being expanded by the engine. `Engine::create_snapshot`
+walks the index map itself, and `Engine::restore_snapshot` expands against the
+snapshot's own manifest and then rewrites the index directory, so neither passes
+the `index_guard` funnel (`expansion_for` and its rationale,
+`authz.rs:1141-1153`).
+
+The rules, from `decide` (`authz.rs:1329-1361`):
+
+- A snapshot or restore that names **no** indices covers every index on the
+ node, brains included, so it is superuser-only. For a non-superuser it is a
+ `403` naming `<all indices>`.
+- A restore upgrades every named target's demand to write, because a restore
+ overwrites what it names.
+- A pattern that `may_reach_reserved` requires an explicit grant covering that
+ pattern; a superuser passes, a `Scoped` key must hold the pattern itself, and
+ anything else is refused (`authorize_expression`, `authz.rs:1175-1193`).
+ Narrower patterns such as `logs-*` are unaffected, so ordinary per-tenant
+ backups keep working.
+
+Routes: `PUT /_snapshot/{repo}/{snapshot}` and
+`POST /_snapshot/{repo}/{snapshot}/_restore` (`router.rs:485-496`).
+
+## The Console rate limiter keys on the socket peer
+
+The Console's auth endpoints charge a per-IP bucket before doing work
+(`xerj-console-api/src/auth/rate_limit.rs`):
+
+- 10 hits per minute and 100 per hour, per `(ip, endpoint)` pair
+ (`PER_MINUTE`, `PER_HOUR`, `rate_limit.rs:22-25`).
+- Over the limit returns `429` with no body, so a caller cannot learn whether
+ the email or token was valid (`rate_limit.rs:8-9`).
+- Charged on exactly three endpoints today:
+ `/_xerj-console/api/v1/auth/login/begin`, `.../login/finish`, and
+ `.../magic/redeem` (`auth/login.rs:54`, `auth/login.rs:126`,
+ `auth/magic.rs:203`).
+
+The `ip` in the key comes from the `ClientIp` extractor
+(`xerj-console-api/src/client_ip.rs`), which reads the TCP peer out of
+`ConnectInfo<SocketAddr>`. Forwarding headers are consulted only when the socket
+peer itself matches `server.trusted_proxies`, which is **empty by default**, so
+an unconfigured node believes nobody (`client_ip.rs:53-107`;
+`server.trusted_proxies` at `xerj-common/src/config.rs:294-311`, defaulting to
+an empty list at `config.rs:322`). When the peer is a declared proxy, the
+`X-Forwarded-For` chain is read right to left, skipping entries that are
+themselves declared proxies; a malformed element stops the walk and the peer is
+used instead. Failing that, a single-valued `X-Real-IP` is honoured.
+
+If no peer address is available at all, the key is the literal string
+`"unknown"` (`UNKNOWN_IP`, `client_ip.rs:45`), which throttles rather than
+exempts.
+
+**Operational consequence.** If you terminate TLS or load-balance in front of
+XERJ and do not list the proxy in `server.trusted_proxies`, the peer address is
+the proxy's for every request, so every one of your users shares a single bucket
+of 10 login attempts per minute. Set `server.trusted_proxies` to the addresses
+or CIDR blocks of proxies you operate, and only those: anything listed there can
+claim to be any client, and so can move its own bucket. Invalid entries fail
+startup rather than silently widening or narrowing trust
+(`config.rs:143-144`).
+
+Note that `ClientIp` is also used for audit fields on endpoints that are not
+rate limited, for example passkey enrolment (`auth/passkey.rs:168`). Only the
+three endpoints listed above charge a bucket.
+
+## Cluster control-frame authentication
+
+Cluster mode is off by default (`ClusterConfig::default`,
+`config.rs:1195-1205`). When it is on, the control transport on `cluster.port`
+(default 9300) authenticates every frame.
+
+### Fails closed without a secret
+
+Confirmed in two independent places:
+
+1. `ClusterConfig::validate` (`config.rs:1237-1260`) returns a configuration
+ error when `enabled = true` and neither `cluster.auth_secret` nor
+ `XERJ_CLUSTER_AUTH_SECRET` supplies a secret.
+2. Startup refuses again before the transport is built
+ (`xerj-server/src/main.rs:1621-1636`), with a comment stating that this must
+ abort startup and is deliberately not folded into the degraded single-node
+ fallback that covers bind failures.
+
+There is no unauthenticated cluster mode to fall back to: `ClusterSecret` is the
+only source of frame tags and has no "no secret" variant
+(`xerj-cluster/src/auth.rs:84-92`).
+
+### Minimum secret length: 16 characters
+
+Also confirmed in two places, which agree:
+
+- `xerj_cluster::auth::MIN_SECRET_LEN = 16`, enforced by `ClusterSecret::new`
+ after trimming surrounding whitespace (`auth.rs:55`, `auth.rs:108-121`).
+- `ClusterConfig::MIN_AUTH_SECRET_LEN = 16`, enforced by config validation
+ (`config.rs:1211-1215`, `config.rs:1250-1257`).
+
+The transport enforces the floor independently of the config, so a mismatch
+fails closed. Precedence: a non-empty `cluster.auth_secret` wins over the
+environment variable, so a stray env var cannot silently re-key a cluster
+(`resolve_auth_secret`, `config.rs:1228-1235`). Every node must be configured
+with the same secret. The config documentation suggests generating one with
+`openssl rand -hex 32`.
+
+### What the tags bind
+
+Each frame carries an HMAC-SHA256 tag over a domain-separated binding of the
+protocol context (`hello` versus `frame`), the wire version byte, a 32-byte
+random challenge the *receiver* generates per accepted connection, the sender's
+node id, the frame's zero-based position in the connection, and the payload
+(`auth.rs:125-154`). The sequence number is never transmitted: both ends count
+independently, so a replayed, dropped, or reordered frame lands on the wrong
+sequence and fails. Fields are length-prefixed so concatenations cannot collide.
+Tags are compared in constant time after a length check (`tags_match`,
+`auth.rs:178-183`). `ClusterSecret`'s `Debug` never renders key material
+(`auth.rs:94-99`).
+
+### What it does not give you
+
+Stated in the module's own words (`auth.rs:21-29`):
+
+- **No confidentiality.** Frames are plaintext JSON on the wire. The HMAC
+ authenticates, it does not encrypt. Cluster traffic still belongs on a trusted
+ network segment.
+- **No per-node identity.** The secret is cluster-wide, so it proves that the
+ peer knows the cluster secret, not that the peer is a particular node. A
+ compromised member can impersonate any other member. mTLS is not implemented.
+
+The wire format changed with this authentication work and does not interoperate
+with 1.0.0-rc.9 or earlier in either direction, so upgrading a cluster requires
+stopping every node rather than a rolling restart (`CHANGELOG.md`, 1.0.0-rc.10,
+"Breaking").
+
+## Worked example
+
+Start a node with auth enabled (the default) and take the admin key it writes to
+`<data_dir>/admin.key`. Mint a key scoped to one brain. Only the admin key can
+do this:
+
+```bash
+curl -s -X POST 'http://localhost:9200/_security/api_key' \
+ -H "Authorization: ApiKey $(cat ./data/admin.key)" \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "name": "alice-agent",
+ "role_descriptors": {
+ "alice-brain": {
+ "indices": [
+ {
+ "names": [".xerj-memory-alice", ".xerj-memory-alice-edges"],
+ "privileges": ["read", "write"]
+ }
+ ]
+ }
+ }
+ }'
+```
+
+The response carries `id`, `name`, `expiration`, `api_key` and `encoded`
+(`es_compat.rs:25600-25606`). `encoded` is `base64("id:api_key")` and is what
+you present:
+
+```bash
+KEY='<the encoded value from the response>'
+
+# Alice's own memory namespace: allowed by the grant above.
+curl -s -H "Authorization: ApiKey $KEY" 'http://localhost:9200/_memory/alice'
+
+# Another tenant's brain: refused, without revealing whether it exists.
+curl -s -H "Authorization: ApiKey $KEY" 'http://localhost:9200/_graph/bob/overview'
+```
+
+The second call is classified as a brain read, resolved to
+`.xerj-memory-bob-edges`, and denied with:
+
+```json
+{
+ "error": {
+ "root_cause": [
+ {
+ "type": "security_exception",
+ "reason": "action [read] is unauthorized for this credential on [.xerj-memory-bob-edges]: mint a key whose role_descriptors grant [read] on that index (POST /_security/api_key), or use the configured admin key"
+ }
+ ],
+ "type": "security_exception",
+ "reason": "action [read] is unauthorized for this credential on [.xerj-memory-bob-edges]: mint a key whose role_descriptors grant [read] on that index (POST /_security/api_key), or use the configured admin key"
+ },
+ "status": 403
+}
+```
+
+The reason string is built in `forbidden` (`authz.rs:242-264`) and the JSON
+shape in `error.rs:52-74`. Enumeration behaves the same way: `GET /_cat/indices`
+with this key lists only the indices it may see, because `Engine::list_indices`
+filters through the visibility guard.
+
+## Known limits
+
+Everything here is a limit of the current code, verified in the source. None of
+it is on a schedule this document can promise.
+
+- **No general RBAC.** An `Unscoped` key keeps superuser-equivalent reach over
+ ordinary (non-reserved) indices. The reserved namespace is a real boundary and
+ a `Scoped` key is confined to its grants; nothing else is
+ (`authz.rs:94-101`).
+- **No field-level or document-level security.** `field_security` and `query`
+ in a `role_descriptors` entry are parsed and discarded (`rbac.rs:152-155`).
+- **The named role store and application privileges are inert.**
+ `/_security/role*` and `/_security/privilege*` store data and gate nothing;
+ the role responses say so with `"enforced": false`
+ (`native.rs:900-949`, `es_compat.rs:25628-25631`).
+- **Four of the seven privileges are never checked.** `SnapshotCreate`,
+ `SnapshotRestore`, `SecurityAdmin` and `AuditRead` exist only as error labels
+ (`authz.rs:242-251`).
+- **The audit endpoints are not privilege-gated.** `/_audit/_search` and
+ `/_audit/_verify` (`router.rs:124-125`) are cluster-classified reads, so any
+ authenticated principal that reaches the router passes; `AuditRead` is not
+ consulted. The startup banner also states plainly that auditing today is
+ request tracing, not a tamper-evident log (`main.rs:317`).
+- **`names: ["*"]` reaches the reserved namespace.** This is intended and pinned
+ by a test, but it means one careless grant hands over every brain
+ (`rbac.rs:72-98`).
+- **A surface mounted outside `authz_middleware` is unprotected by default**,
+ because an absent guard allows. The Console proxy and the gRPC listener each
+ carry their own check; a new surface would need its own
+ (`data_sources.rs:37-48`, `grpc.rs:62-88`).
+- **Detached work must carry the rule by hand.** `tokio::spawn` and
+ `spawn_blocking` do not inherit the guard, and rayon workers never see it. The
+ audit of every spawn site in the workspace is in `index_guard.rs:59-85`; a new
+ spawn that can resolve an index name must use `current()` and `scoped_opt`.
+- **Cluster traffic is unencrypted and membership-authenticated only.** No
+ confidentiality, no per-node identity, no mTLS (`auth.rs:21-29`).
+- **TLS is off by default.** `TlsConfig` derives `Default`, so `tls.enabled` is
+ `false` (`config.rs:492-501`), and `--insecure` disables both TLS and auth
+ (`main.rs:345-349`). The startup banner prints the posture on every start
+ (`main.rs:302-319`).
+- **No encryption at rest at the engine level.** The startup banner says to use
+ OS full-disk encryption or bucket-side encryption instead (`main.rs:318`).
+- **Rate limiting covers three Console auth endpoints only.** There is no
+ general per-IP request throttle on the data plane (`rate_limit.rs`, and the
+ three call sites listed above).
diff --git a/docs/SNAPSHOT_AND_RESTORE.md b/docs/SNAPSHOT_AND_RESTORE.md
new file mode 100644
index 000000000..49c65f746
--- /dev/null
+++ b/docs/SNAPSHOT_AND_RESTORE.md
@@ -0,0 +1,427 @@
+# Snapshot and restore
+
+XERJ implements a subset of the Elasticsearch snapshot API. A snapshot is a
+recursive filesystem copy of one or more index directories into a repository
+directory, plus a `manifest.json` at the snapshot root. A restore copies those
+directories back and reopens the indices.
+
+Restore is destructive. It deletes the live index directory before copying the
+snapshot back. Read [Restore replaces index
+directories](#restore-replaces-index-directories) before you run one.
+
+Everything below was read out of the source. The handlers are in
+`engine/crates/xerj-api/src/es_compat.rs`, the engine work is
+`Engine::create_snapshot` and `Engine::restore_snapshot` in
+`engine/crates/xerj-engine/src/engine.rs`, the routes are in
+`engine/crates/xerj-api/src/router.rs`, and the authorization rules are in
+`engine/crates/xerj-api/src/authz.rs`.
+
+## Routes
+
+| Method | Path | Handler |
+|---|---|---|
+| `PUT` | `/_snapshot/{repo}` | register or replace a repository |
+| `GET` | `/_snapshot/{repo}` | read a repository config (`*` or `_all` returns all of them) |
+| `DELETE` | `/_snapshot/{repo}` | deregister a repository |
+| `PUT` | `/_snapshot/{repo}/{snapshot}` | take a snapshot |
+| `GET` | `/_snapshot/{repo}/{snapshot}` | read one snapshot's info |
+| `POST` | `/_snapshot/{repo}/{snapshot}/_restore` | restore |
+| `GET` | `/_cat/repositories` | plain-text `name type` lines, one per repository, no header row |
+
+Those are all the snapshot routes the router registers (`router.rs:485-497`,
+`router.rs:763`). There is no `DELETE /_snapshot/{repo}/{snapshot}`, no
+`_status`, no `_verify`, no `_cleanup`, and no snapshot lifecycle management.
+See [What is not supported](#what-is-not-supported).
+
+## Register a repository
+
+The body you send is stored verbatim under the repository name
+(`es_compat.rs:23138`). Only one field is ever read back out: the string at
+`settings.location`, which is the filesystem path the snapshot directory is
+created under (`es_compat.rs:23197-23201`).
+
+The repository name must not be empty and must not contain `..`, `/`, `\`, or a
+NUL byte. Violations return HTTP 400 with `"type":
+"mapper_parsing_exception"` (`es_compat.rs:23086-23098`).
+
+The location is bounded. `validate_snapshot_path` rejects any location that
+contains a `..` path component, and requires the location to canonicalize to a
+path inside `server.data_dir` or inside one of the base directories listed in
+`limits.snapshot_repo_allowlist` in the TOML config
+(`engine.rs:1971-1997`, `xerj-common/src/config.rs:960`). The allowlist defaults
+to empty, which means only `data_dir` is permitted. This is checked when a
+snapshot is created or restored, not when the repository is registered, so a
+bad location is accepted by `PUT /_snapshot/{repo}` and only fails later.
+
+If `settings.location` is absent the handler falls back to
+`/tmp/xerj-snapshots` (`es_compat.rs:23201`). That fallback is outside the
+default `data_dir` and will therefore be refused by the location check, so
+always set `settings.location` explicitly.
+
+```bash
+curl -sS -X PUT localhost:9200/_snapshot/backups \
+ -H "Authorization: ApiKey $XERJ_ADMIN_KEY" \
+ -H 'Content-Type: application/json' \
+ -d '{"type":"fs","settings":{"location":"./data/snapshots"}}'
+```
+
+Response:
+
+```json
+{"acknowledged": true}
+```
+
+The repository registry is an in-memory map built empty at engine start
+(`engine.rs:257`, `engine.rs:405`). Nothing reloads it from disk, so
+repositories have to be registered again after a restart.
+
+## Take a snapshot
+
+```bash
+curl -sS -X PUT localhost:9200/_snapshot/backups/2026-08-04 \
+ -H "Authorization: ApiKey $XERJ_ADMIN_KEY" \
+ -H 'Content-Type: application/json' \
+ -d '{"indices":"logs-*"}'
+```
+
+The body is optional. The only field read is `indices`
+(`es_compat.rs:23210-23217`).
+
+### Both spellings of `indices`
+
+Since rc.10 the create handler parses `indices` as an array of names or
+patterns, or as a single string that may itself be comma-separated:
+
+```json
+{"indices": ["logs-2026-08", "metrics-*"]}
+{"indices": "logs-2026-08,metrics-*"}
+```
+
+Before rc.10 only the array spelling was read. The string spelling fell through
+to "absent", which means "every index on the node", so `{"indices":"logs-*"}`
+captured everything. Both spellings now parse the same way.
+
+### Patterns resolve against what you can see
+
+`Engine::create_snapshot` takes concrete index names, so the handler expands
+patterns before calling it. It expands them over `Engine::index_name_list()`
+(`es_compat.rs:23225-23249`), which filters through
+`xerj_engine::index_guard::visible` (`engine.rs:1250-1256`). The middleware
+installs the request's principal as that visibility rule
+(`authz.rs:1272-1273`), so the set of indices captured is the set the caller is
+allowed to see. Before rc.10 the wildcard reached the engine verbatim, matched
+nothing, and produced an empty snapshot, so `{"indices":["*"]}` used to back up
+nothing at all.
+
+The matcher used on this path is `glob_match_simple`
+(`es_compat.rs:19590-19601`). It handles exactly three shapes: `*` on its own,
+a trailing wildcard (`logs-*`), and a leading wildcard (`*-2026`). Anything
+else is compared as an exact string, so a mid-pattern wildcard such as
+`logs-*-2026` matches nothing here. `_all` and `*` both expand to every visible
+index.
+
+### With no `indices` at all
+
+If `indices` is absent, the engine snapshots every open index except its own
+internal ones. "Internal" here means a name starting with `.xerj_`
+(`is_system_index`, `engine.rs:1925-1927`). The reserved agent-memory and
+second-brain namespace uses the prefix `.xerj-memory-` with a hyphen
+(`xerj-common/src/types.rs:190`), which is not `.xerj_`, so an unnamed snapshot
+does include every brain on the node. That is exactly why an unnamed snapshot
+is superuser-only; see [Authorization](#authorization).
+
+### What gets copied, and when
+
+For each selected index the engine flushes the memtable and then copies the
+index directory recursively: WAL files, segment files, and the schema, settings
+and `es_mapping.json` files (`engine.rs:1669-1690`). The flush happens
+immediately before that index's own copy, inside the per-index loop, so indices
+are captured at different instants. There is no cross-index point-in-time
+consistency, and no lock stops writes arriving during the copy.
+
+An index named in `indices` that does not exist on the node is skipped
+(`engine.rs:1670-1673`), but it is still listed in the manifest, because the
+manifest records the requested list rather than the copied list
+(`engine.rs:1657-1668`, `engine.rs:1692-1697`).
+
+### Response
+
+The operation is synchronous. There is no `wait_for_completion` on create. The
+response is `{"accepted": true, "snapshot": <manifest>}` where the manifest is
+the same JSON written to `manifest.json` (`es_compat.rs:23256-23260`,
+`engine.rs:1692-1712`):
+
+```json
+{
+ "accepted": true,
+ "snapshot": {
+ "snapshot": "2026-08-04",
+ "uuid": "…",
+ "version": "8.13.0",
+ "indices": ["logs-2026-08"],
+ "state": "SUCCESS",
+ "start_time_in_millis": 1754265600123,
+ "end_time_in_millis": 1754265601047,
+ "duration_in_millis": 924,
+ "failures": [],
+ "shards": {"total": 1, "failed": 0, "successful": 1}
+ }
+}
+```
+
+The timestamps are real. `start_time_in_millis` is sampled before the flush and
+copy work begins and `end_time_in_millis` after it finishes, so
+`duration_in_millis` is the elapsed wall-clock time of the copy
+(`engine.rs:1655`, `engine.rs:1692`, `engine.rs:1702`).
+
+The `shards` counts are index counts, not shard counts: all three are derived
+from the length of the index list (`engine.rs:1704-1707`). `version` is the
+hardcoded string `"8.13.0"`, which is the ES protocol version XERJ reports, not
+a XERJ version.
+
+The snapshot name is validated the same way the repository name is, and must
+also not be `.` or `..` (`es_compat.rs:23105-23123`).
+
+## Inspect
+
+```bash
+curl -sS localhost:9200/_snapshot/backups/2026-08-04 \
+ -H "Authorization: ApiKey $XERJ_ADMIN_KEY"
+```
+
+Returns `{"snapshots": [<manifest>]}`, or 404
+`index_not_found_exception` if either the repository or the snapshot is unknown
+(`es_compat.rs:23265-23283`).
+
+This handler reads an in-memory map keyed by `"{repo}/{snapshot}"`, populated
+when the snapshot was taken in this process (`es_compat.rs:23257-23258`). After
+a restart it returns 404 even though the files are still on disk. Restore does
+not use that map: it reads `manifest.json` from the repository directory, so
+restoring a snapshot taken before a restart still works.
+
+There is no `GET /_snapshot/{repo}/_all` and no wildcard listing of snapshots;
+the lookup is an exact key match.
+
+## Restore replaces index directories
+
+```bash
+curl -sS -X POST 'localhost:9200/_snapshot/backups/2026-08-04/_restore?wait_for_completion=true' \
+ -H "Authorization: ApiKey $XERJ_ADMIN_KEY" \
+ -H 'Content-Type: application/json' \
+ -d '{"indices":"logs-2026-08"}'
+```
+
+For every index it selects, the restore loop (`engine.rs:1857-1892`):
+
+1. removes the index from the live index map,
+2. calls `remove_dir_all` on `<data_dir>/<index>`,
+3. recreates the directory and copies the snapshot's copy back,
+4. reopens the index and reloads its persisted ES mapping.
+
+Every document written to that index after the snapshot was taken is gone. So
+is every mapping change. There is no merge mode, no dry run, and no way to
+restore under a different name (see the rejected options below). If the reopen
+in step 4 fails, the index is recorded in the engine's `failed_indices` map and
+the loop continues to the next index (`engine.rs:1895-1898`), so the old data
+is already deleted at that point.
+
+The list of index names in the response is the set the filter selected. An
+index whose snapshot directory was missing is skipped with a warning
+(`engine.rs:1836-1840`) and one whose reopen failed is also skipped, but both
+still appear in that list. Treat it as "what was attempted", not as proof of
+success.
+
+### Selecting indices to restore
+
+`indices` accepts the same two spellings as create: an array, or a single
+string that may be comma-separated (`es_compat.rs:23345-23356`). Each entry is
+split on commas again in the engine, and each resulting pattern is matched
+against the index list in the snapshot's own `manifest.json`
+(`engine.rs:1765-1806`).
+
+The matcher on the restore path is `glob_match` (`engine.rs:2066-2087`), a full
+wildcard matcher supporting `*` and `?` anywhere in the pattern. This is a
+different matcher from the one the create path uses, so a pattern that selects
+nothing when taking a snapshot may still select something when restoring one.
+
+- A pattern with no `*` that matches nothing in the snapshot is an error: HTTP
+ 400, `"type": "search_phase_execution_exception"`, reason
+ `[{snapshot}] no index matches [{pattern}] in snapshot` (`engine.rs:1795-1802`).
+ A wildcard that matches nothing is not an error.
+- A wildcard never selects a `.xerj_*` internal index unless the pattern itself
+ starts with `.` (`engine.rs:1786-1793`).
+- With no `indices` at all, every index in the manifest except `.xerj_*` ones is
+ restored (`engine.rs:1775-1782`).
+
+Index names coming out of the manifest are revalidated with `IndexName::new`
+before any filesystem operation, and the destination directory is checked to be
+inside `data_dir` both lexically and after canonicalization
+(`engine.rs:1822-1834`, `engine.rs:1844-1855`,
+`engine.rs:1866-1877`).
+
+### Restore options that are rejected
+
+These five options are refused with HTTP 400, `"type":
+"illegal_argument_exception"`, reason `restore option [{name}] is not supported
+by this XERJ version` (`es_compat.rs:23316-23343`):
+
+`rename_pattern`, `rename_replacement`, `feature_states`, `index_settings`,
+`ignore_index_settings`
+
+They fail loud rather than being ignored, because ignoring a rename would
+overwrite the source index instead of creating a copy.
+
+Any other field in the restore body is ignored. The handler reads only
+`indices` and the five names above, so `include_global_state`,
+`include_aliases`, `partial` and friends have no effect and produce no error.
+
+### `wait_for_completion`
+
+`wait_for_completion` is a query-string parameter and is compared to the exact
+string `"true"` (`es_compat.rs:23358-23361`). `wait_for_completion=1` and
+`wait_for_completion=TRUE` both read as false.
+
+The restore runs synchronously either way. The flag only picks the response
+shape (`es_compat.rs:23368-23386`):
+
+```json
+{"accepted": true}
+```
+
+or, with `wait_for_completion=true`:
+
+```json
+{
+ "snapshot": {
+ "snapshot": "2026-08-04",
+ "indices": ["logs-2026-08"],
+ "shards": {"total": 1, "failed": 0, "successful": 1}
+ }
+}
+```
+
+Again, those counts are index counts.
+
+## Authorization
+
+Snapshot and restore are the only two routes where an index pattern in a
+request body is decided by the authorization middleware itself rather than left
+to the engine's visibility guard (`authz.rs:1143-1152`). The reason is in the
+code: `create_snapshot` walks the index map and `restore_snapshot` expands
+against the snapshot manifest and then removes and rewrites index directories,
+so neither passes through `get_index` or `delete_index`, which is where every
+other body-named target meets the guard.
+
+The rules, as `decide` and `authorize_expression` apply them:
+
+- **Superuser skips all of it** (`authz.rs:1291-1293`). A principal is
+ superuser when it presents the configured admin key, and also when
+ `auth.enabled` is false or `auth.admin_api_key` is empty, which is the
+ point-at-a-folder local posture (`auth.rs:214-222`). A superuser can back up
+ and restore everything.
+
+- **Naming no indices at all is superuser-only.** For any non-GET, non-HEAD
+ request under `/_snapshot/` with three or more path segments, an empty set of
+ demanded indices is refused (`authz.rs:1333-1358`). That covers both `PUT
+ /_snapshot/{repo}/{snap}` with no body and `POST
+ /_snapshot/{repo}/{snap}/_restore` with no `indices`, because both cover
+ every index on the node, brains included. The 403 names the resource as
+ `<all indices>` and the action as `create_snapshot` or `restore_snapshot`.
+
+- **A pattern that may reach the reserved namespace needs an explicit grant.**
+ `may_reach_reserved` (`authz.rs:177-191`) judges a pattern by the literal
+ text before its first `*`: the expression qualifies if that prefix starts
+ with `.xerj-memory-` or is itself a prefix of `.xerj-memory-`. So `*`, `_all`,
+ `.*`, `.xerj-*` and `.xerj-memory-alice*` all qualify. For those, only a
+ superuser, or a scoped key whose `role_descriptors` grant that very pattern
+ with the required privilege, is allowed through (`authz.rs:1175-1193`). An
+ unscoped key is never allowed a reserved-reaching pattern on these two
+ routes.
+
+- **Narrower patterns work normally.** `logs-*` does not qualify under
+ `may_reach_reserved`, so it is not refused and is not subject to the extra
+ check. The ordinary per-tenant backup keeps working.
+
+- **Concrete names go through the normal per-index check**, resolving aliases
+ first (`authz.rs:1194-1202`).
+
+- **Restore demands write, not read.** `body_targets` records snapshot
+ `indices` as `ReadIndex`, and `decide` upgrades every demand to `WriteIndex`
+ when the last path segment is `_restore` (`authz.rs:895-905`,
+ `authz.rs:1342-1347`), because a restore overwrites what it names.
+
+A refusal is an ES-shaped 403 naming the resource and the action, with the
+grant that would fix it (`authz.rs:242-262`).
+
+Note that "unscoped" is a real category here: a key with no usable
+`role_descriptors` keeps its historical reach over ordinary indices but has no
+privilege at all on `.xerj-memory-*` (`auth.rs:99-106`). And an explicit grant
+is not second-guessed: a scoped key minted with `names: ["*"]` does satisfy the
+check above, because `*` matches every index and that is what the operator
+asked for. Only a superuser can mint such a key. To keep brains isolated, grant
+concrete names or a prefix that excludes `.xerj-memory-`.
+
+## The native backup route
+
+`POST /v1/admin/backup` calls the same `Engine::create_snapshot`
+(`native.rs:779-815`). Its body has three optional fields: `repo_path`, `name`
+and `indices` (`native.rs:770-777`). `repo_path` defaults to
+`<data_dir>/_backups` and `name` defaults to `backup-<uuid>`. It returns HTTP
+201 with the manifest under a `manifest` key.
+
+Two differences from the ES route are worth knowing:
+
+- It passes `indices` to the engine unchanged, with no pattern expansion. The
+ engine looks index names up exactly, so a wildcard here matches nothing.
+- The authorization middleware classifies `/v1/...` as a cluster route, not as
+ a snapshot route (`authz.rs:473-480`, `authz.rs:675-677`), so the
+ snapshot-specific pattern rule above does not apply to it. It falls through
+ to the general cluster-mutation rule: a scoped key is refused, an unscoped
+ key is allowed (`authz.rs:1386-1396`).
+
+The repository location check still applies, since it lives inside
+`Engine::create_snapshot`.
+
+## What is not supported
+
+Confirmed absent from the code, not merely undocumented:
+
+- **Deleting a snapshot.** The route table registers only `PUT` and `GET` on
+ `/_snapshot/{repo}/{snapshot}` (`router.rs:491-493`). Removing a snapshot
+ means deleting its directory yourself.
+- **`_status`, `_verify`, `_cleanup`, `_slm`.** No routes exist for any of
+ them.
+- **`GET /_snapshot`** with no repository. The route is `/_snapshot/:repo`; use
+ `GET /_snapshot/_all` or `GET /_snapshot/*` to list repositories.
+- **Listing snapshots in a repository.** `GET /_snapshot/{repo}/{snapshot}` is
+ an exact key lookup; `_all` and wildcards are not handled.
+- **Anything but a local filesystem repository.** The `type` field you send is
+ stored and echoed by `_cat/repositories` but is never acted on. There is no
+ S3, GCS, Azure or HDFS implementation; the engine always does a local
+ recursive directory copy.
+- **Incremental or deduplicated snapshots.** Every snapshot copies the full
+ index directory. There is no shared blob store and no reference counting
+ between snapshots.
+- **Global cluster state.** Only per-index directories and the manifest are
+ written. Index templates, ILM policies, cluster settings, enrich policies,
+ transform pipelines and security keys are not captured, and are not restored.
+- **Restore rename, per-index settings overrides, and feature states.**
+ Rejected with 400, as listed above.
+- **`ignore_unavailable`, `include_global_state`, `partial`,
+ `include_aliases`.** Not parsed on either verb.
+- **Persistent repository and snapshot metadata.** Both maps are in-memory and
+ are lost on restart.
+- **Cluster-wide coordination.** Both operations act on the local node's
+ `data_dir`.
+- **Compression or encryption of the copy.** Files are copied as they are on
+ disk.
+- **Point-in-time consistency across indices,** and any guard against
+ concurrent writes or a concurrent restore. See [What gets copied, and
+ when](#what-gets-copied-and-when).
+
+## Related
+
+- [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md) for where the engine, storage and
+ API layers sit.
+- `CHANGELOG.md` for the rc.10 entry describing the snapshot authorization fix
+ and the `indices` parsing fix.