Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: git-canonical guide, git-parent model in brains-and-sources, large-page writes, source_ids reference, llms map; drop the README byte cap

garrytanfe9154da1945
diff --git a/CLAUDE.md b/CLAUDE.md
index 8a32b155c0..7751dfc9e8 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -186,7 +186,7 @@ from recurring:
narration. When a file's behavior changes, UPDATE its entry to the new truth.
- **CI is the enforcement, not this prose.** `scripts/check-key-files-current-state.sh`
(in `bun run verify`) fails on the bolded-release-clause marker in the reference
- docs AND on size caps for CLAUDE, README, the index, and each subsystem. A written rule caused this disease; a guard
+ docs AND on size caps for CLAUDE, the index, and each subsystem. A written rule caused this disease; a guard
cures it.
- **After any CLAUDE.md or reference-doc edit, run `bun run build:llms`** — the
llms bundle inlines/links these (config in `scripts/llms-config.ts`); the
diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.md
index f21033bd69..a1a771753e 100644
--- a/docs/architecture/brains-and-sources.md
+++ b/docs/architecture/brains-and-sources.md
@@ -49,6 +49,27 @@ source name) and never picks the repo, on a local brain, through a running
`GBRAIN_SOURCE`, `.gbrain-source` or the defaults select, and the JSON result
names it in `source_id`.
+### Git is the parent of a source with a checkout
+
+Most sources are a Git checkout (`local_path`) plus the pages gbrain derived
+from it. The files are the record people read, review and clone; the
+database is an index that gbrain can rebuild from them. How tightly the
+database follows Git depends on the source:
+
+| Source | Where the record is | How the database follows |
+|---|---|---|
+| Checkout, mixed (the default) | The files in Git | Sync imports what is committed. A write publishes the file and its database row together (managed) or the row first (classic), and the Git commit follows later (a background Git effect once Git durability is on). When the two disagree, sync holds the page for review. |
+| Checkout, strict (`canonical: git`, opt-in per source) | Git commits | Every write is committed to Git before its row. Sync indexes committed blobs only, and Git wins. Private pages, `storage.db_only` directories and ignored paths are declared database-only. |
+| Read-only mirror (`gbrain sources mirror-readonly`) | The upstream repository | Sync imports; gbrain never writes into the checkout. |
+| No checkout (connector sources, database-only sources) | The database | Nothing to derive from; back up the database. |
+
+Scripts, crons and people that write files in a checkout commit them with
+`gbrain git commit-push -- <paths>`, which takes the same writer lock. To make
+a source strict, or to see how far its database is from Git, read
+[git-canonical sources](../guides/git-canonical.md); `gbrain sources git-gap <id>`
+is the read-only check, and doctor's `db_ahead_of_git` and `git_index_lag`
+report it brain-wide.
+
### When does each axis move?
| You want to | Adjust |
@@ -358,5 +379,10 @@ ungranted source when remote callers must have no access to that source.
- [`topologies.md`](./topologies.md) — where the DB lives (operator recipes
for each deployment shape).
+- [`git-canonical.md`](../guides/git-canonical.md) — strict sources: Git
+ first, the database derived from the commits, and how to convert or roll
+ back a source.
+- [`multi-source-brains.md`](../guides/multi-source-brains.md) — adding,
+ scoping and hosting sources, and narrowing one request with `source_ids`.
- `skills/conventions/brain-routing.md` — the agent-facing decision table.
- `CHANGELOG.md` — release history for the `sources` and `mounts` primitives.
diff --git a/docs/guides/git-canonical.md b/docs/guides/git-canonical.md
new file mode 100644
index 0000000000..0b7dcae2c5
--- /dev/null
+++ b/docs/guides/git-canonical.md
@@ -0,0 +1,170 @@
+# Git-canonical sources (strict mode)
+
+A source in git-canonical mode, also called strict mode, keeps its pages in Git
+first. Every page write is committed to the source's checkout before the
+database records it, and the database is an index that gbrain can rebuild from
+the commits. When Git and the database disagree, Git wins.
+
+Strict mode is chosen per source and is **off by default**. Nothing turns it on
+during an upgrade: a source becomes strict only when you convert it with
+`gbrain sources canonical` or host a new source with `gbrain sources host-repo`.
+The design, with the full reasoning and every edge case, is
+[GIT_CANONICAL_MEMORY.md](../designs/GIT_CANONICAL_MEMORY.md). This page is the
+operator's view.
+
+## What changes for a strict source
+
+| | A mixed source (the default) | A strict source (`canonical: git`) |
+|---|---|---|
+| A page write | The file and the database row are published first; a background Git effect commits and pushes the file later, once Git durability is on. | The file is written and committed under the checkout's writer lock, then the row commits. The receipt names the commit (`persistence.git_commit`, `git_state: committed`). The Git effect only pushes. |
+| A crash between the two | Recovery restores the file's previous bytes. | The committed file is kept, and the write's replay finishes the row against it. |
+| What sync reads | The working tree and the database; disagreements become holds such as `file_drift` or `worktree_dirty`. | Committed blobs at HEAD only. Each committed version is imported over what the database holds, and a committed removal deletes the page. |
+| An uncommitted edit in the checkout | Held as `worktree_dirty`. | Left on disk and not indexed until someone commits it. |
+| `gbrain sync --working-tree` | Reads the working tree. | Refused with `managed_sync_flag_refused`. |
+| A row write from an older gbrain that does not know the mode | Accepted. | Refused by the database guard (`git_protocol_required`). |
+
+Writes to a strict source pay for a local commit. The door commits with Git
+plumbing and updates the index only for the paths it wrote, so on a
+150,000-file checkout it adds about 230 ms per write (p50). A `put_pages` batch,
+a maintenance run (dream patterns, one `extract_entities` call, one atom
+generation) and other grouped writes share one commit.
+
+## When to turn it on
+
+Turn it on for a source when you want its Markdown in Git to be the record:
+people and other clones read, review and edit the files, and you want to be
+able to rebuild the index from them. It also removes the class of problems
+where the database and the checkout drift apart on a busy source (drift holds,
+held deletions, parked per-write commits), because the database is never ahead
+of Git.
+
+It needs:
+
+- **Managed persistence on the brain.** Only the managed writer commits through
+ the door. On an unmanaged brain, conversion and every direct import into a
+ strict source are refused with `strict_requires_managed`. Turning managed
+ persistence on is its own step (`gbrain sources writer activate`); see
+ [local registrations and canonical ownership](concurrent-writes.md#local-registrations-and-canonical-ownership).
+- **A Git checkout for the source, on a branch.** A source with no checkout
+ stays database-only as a whole and can't be strict. A strict write on a
+ detached HEAD or an unborn branch is refused (`git_detached_head`,
+ `git_branch_unborn`) and rolls back.
+- **The trusted local CLI on the brain host.** `sources canonical` and
+ `sources host-repo` are not MCP operations, and an agent runs either on a
+ production brain only with the user's yes, one source at a time.
+
+Leave a source mixed when it has no checkout, when you don't want a local
+commit on the write path, or while other writers on the host still run a gbrain
+older than the one that converted it.
+
+## Converting an existing source
+
+Look first. Both commands below are read-only:
+
+```bash
+gbrain sources git-gap <source-id> --json # how far the database is from HEAD, page by page
+gbrain sources canonical <source-id> --to git # the conversion plan (--dry-run is the default)
+```
+
+The plan puts every live page in one category and prints a preview hash:
+
+| Category | What the apply does |
+|---|---|
+| adopt | The database holds content Git lacks (`database_ahead`, `undeclared_database_only`, `worktree_only`). The page is written to its file and committed through the door, up to 200 pages per commit. No row changes. |
+| declared | The page belongs to a [database-only class](#what-stays-in-the-database-only). Nothing is written. |
+| git wins | Git moved and the database did not (or the hold already matches the committed file). The strict pass indexes the committed file. |
+| holds | Open sync holds are cleared so Git's verdict runs over them. |
+| parked effects | Retried once, or recorded as declared when Git ignores the target. |
+| discard | Database content that Git-wins would throw away. The apply refuses with `git_conversion_blocked` until this is 0, and there is no override. |
+
+When the plan is what you expect, apply exactly that plan:
+
+```bash
+gbrain sources canonical <source-id> --to git --apply --expect <hash> [--no-embed] [--no-extract]
+```
+
+A plan that changed since the preview refuses with `preview_changed`; preview
+again. The apply adopts group by group (a crash leaves the source mixed, and the
+next preview lists only what is left), runs a full strict pass, sets
+`canonical: git`, then runs one more strict pass. Writes that land during the
+conversion can leave work behind; the command then reports
+`git_conversion_incomplete` and the source stays strict. Wait until
+`gbrain sync status --source <id> --json` shows it idle, preview again and apply
+the new hash.
+
+**A new, empty source** can start strict instead:
+`gbrain sources host-repo <id> --dir <path> [--push-remote <url>]` creates a bare
+repository people clone, with a worktree gbrain owns, and makes the source
+strict. See [hosted repositories](multi-source-brains.md#hosted-repositories).
+
+## How writes reach a strict source
+
+Every write goes through the same door, whoever sends it:
+
+- **Local writers** (`put_page`, `capture`, `remember`, imports, dream,
+ connectors, maintenance) publish through the managed writer, which commits
+ before the row.
+- **Remote MCP callers and thin clients** send a write request that the
+ checkout owner's door commits. The reply carries the revision once it is
+ committed and indexed, or `write_pending` with a request id (exit 10 on the
+ CLI) while the owner is busy or offline. Poll it with
+ `gbrain write-request <id>`; it is never "failed" or "not found". The owner
+ re-checks the caller's grant before committing, so a grant revoked while the
+ request waits is refused with no commit and no row.
+- **Scripts, crons and people** that write files commit them, for example with
+ `gbrain git commit-push -m "<msg>" -- <paths>`
+ ([shared checkout rules](shared-checkout-git.md#scripts-and-the-managed-checkout)).
+ The next sync pass indexes the commit. An edit nobody commits is never
+ indexed.
+
+Pushing is off the write path. A push conflict on a page path parks only the
+push; local commits and writes keep going.
+
+## What stays in the database only
+
+Some content has no file on purpose. On a strict source each of these is a
+declared class, and anything else that would land in the database without a
+file is refused with [`git_home_required`](write-refusals.md#git_home_required).
+
+| Class | What happens |
+|---|---|
+| Private, alias-private and lineage-private pages | Never committed. A page turning private is published as the door commit that removes its file; turning world again writes the file back at the path it had. Commits made before it turned private still hold the old text, and gbrain never rewrites history. A write that would commit private bytes is refused with [`git_private_commit_refused`](write-refusals.md#git_private_commit_refused). |
+| Pages under a `storage.db_only` directory in `gbrain.yml` | The door never commits under them ([storage tiering](../storage-tiering.md)). |
+| Derive-phase pages that never had a file | Kept database-only. |
+| Paths the checkout's Git ignores | Never committed and never given a Git effect. |
+| Detached pages and origin twins | Kept database-only. |
+| Derived data: chunks, embeddings, links and rows parsed from pages, receipts | Rebuilt from Git, never content of record. |
+
+A file under a Git LFS rule is refused with `git_lfs_not_enabled` unless
+`storage.git_lfs` is on and the checkout configures the LFS filter; the door
+then commits the LFS pointer.
+
+Back up the database for the declared classes: Git holds everything else.
+
+## Turning it off
+
+```bash
+gbrain sources canonical <source-id> --to mixed # preview
+gbrain sources canonical <source-id> --to mixed --apply --expect <hash>
+```
+
+This removes `canonical: git` and changes nothing else. Git keeps every door
+commit and no row is rewritten; the source goes back to mixed behavior on its
+next write and sync pass.
+
+## What doctor and status show
+
+| Where | What it tells you |
+|---|---|
+| `gbrain doctor` → `git_index_lag` | Per strict source, how many commits and seconds the index trails HEAD. It warns once the oldest unindexed commit is older than 900 s (`GBRAIN_DOCTOR_GIT_INDEX_LAG_WARN_SECONDS`), and its fix is `gbrain sync --source <id> --no-pull`. Until then, search and reads show the older version. |
+| `gbrain doctor` → `db_ahead_of_git` | The git-gap totals for every source with a checkout, strict or not. Informational: always ok. Bounded by `GBRAIN_DOCTOR_GIT_GAP_TIMEOUT_MS` (10 s by default). |
+| `gbrain sources git-gap <id> [--sample n] [--json]` | Each page's state against HEAD: `equal`, `database_ahead`, `git_ahead`, declared or undeclared database-only, `worktree_only`, `unparseable`, `unsafe_path`, with a sample of paths. Read-only. |
+| `gbrain sources reindex <id> --from-git` | A preview of every database version Git would replace, bound to HEAD by a hash; `--apply --expect <hash>` runs that pass. Use it to re-derive a strict source's index on purpose. |
+| `gbrain sync status --source <id> --json` | The sync pass that indexes commits: state, reason and the last error. |
+| A write receipt | `persistence.git_commit` and `git_state: committed`. A door commit that landed before its row, on a write that then ended without committing, keeps `landed_before_row: true`: Git holds those bytes and the indexer imports them. |
+
+Explain any code offline with `gbrain errors <code>`. The ones specific to
+strict sources are `strict_requires_managed`, `git_home_required`,
+`git_private_commit_refused`, `git_lfs_not_enabled`, `git_protocol_required`,
+`git_detached_head`, `git_branch_unborn`, `git_conversion_blocked` and
+`git_conversion_incomplete`.
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index f7bbe88078..274c5f2abf 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -136,6 +136,27 @@ An ordinary page carries no field.
A body over the page ceiling, or `put_page` content over 24 MiB, has no
receipt: the write is refused as `request_too_large`.
+<a id="adding-to-a-large-page"></a>
+### Adding to or uploading a large page
+
+Don't send a growing page back whole to add a line. `append_page` (CLI
+`gbrain append <slug>`, text from `--file` or stdin) adds text to the end of a
+page in time proportional to the text. It takes a `request_id`, so a retry
+never appends twice, and `expected_tail_sha256` refuses `tail_changed` when
+another writer appended first. `edit_page` on a page stored in segments
+rewrites only the segments its match touches; `within` restricts the match to
+a range a window read returned.
+
+A page bigger than one request (see the limits below) goes in an upload
+session: `begin_page_upload`, then `upload_page_part` from part 0, then
+`commit_page_upload`, which returns `put_page`'s receipt. `get_page_upload`
+resumes after a lost reply and `abort_page_upload` discards the session.
+`gbrain put --file` and `gbrain capture --file` use a session on a remote
+brain, and `gbrain append` switches to one when the text is over the
+connection's request limit. A session belongs to the connection, source and
+page that began it, its staged bytes count against the `persistence.limits`
+upload quotas, and an idle session expires.
+
<a id="reading-part-of-a-page"></a>
### Reading part of a page
@@ -273,7 +294,7 @@ wrong with the page.
| Markdown import and sync (`gbrain import`, `gbrain sync`, the managed sync blob read) | the page ceiling: 256 MiB on Postgres, 128 MiB on PGLite (24 MiB while segmented storage is off); above 24 MiB on a source backed by files, only from the file's own place in the checkout | — |
| CLI stdin (`gbrain put`, `gbrain capture --stdin`) | 24 MiB (was 5 MB) | `gbrain import` the file |
| MCP stdio (local agents, `gbrain serve`) | 64 MiB per JSON-RPC message (the MCP SDK default of 10 MiB is raised), so a JSON-escaped page at the ceiling fits | — |
-| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default) | the same: sync or the CLI on the brain host (chunked uploads arrive in a later release) |
+| MCP over HTTP (`gbrain serve --http`) | 4 MiB request body (the MCP SDK default) | an [upload session](#adding-to-a-large-page), or sync or the CLI on the brain host |
| Legacy HTTP transport | 1 MiB (`GBRAIN_HTTP_MAX_BODY_BYTES`) | the same |
| `put_pages` batch | 8 MiB per batch | send large pages one per `put_page`, or by file |
| Persistence journal | 64 MiB of outstanding JSON-escaped write intent per principal (was 32 MiB), 256 MiB per brain | nothing: a second large write waits for the first |
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index b0b7d875bc..3a329efd7f 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -294,7 +294,7 @@ Pages whose writes keep ending in a `source_changed` conflict, grouped by slug (
## `put_page`
-Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences. For remote writes, `[[wikilinks]]` and markdown links in the body that point at pages already in the same source become plain `mentions` links after the commit (a journaled `links` effect; the receipt's `auto_links.mention_links` says it is queued; `mcp.remote_auto_links false` turns it off). Typed and frontmatter links are skipped for untrusted writes: a stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Pass `wait_ms` (up to 30000) to hold the reply until the commit instead of polling get_write_request. For more than 3 pages, use `put_pages` (full surface). Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG. A write the content-quality gate quarantined still commits but reports `quarantined: { reason, detail }` with a `page_quarantined` safety notice (put_pages marks each such page and emits one notice).
+Replace a complete canonical Markdown page. Read get_page with include_content:true and pass its revision as expected_revision; force explicitly overwrites the current revision. Omitting both permits creation only. Retain a UUID request_id and repeat identical arguments after transport failure or a pending receipt. Content, tags, sanitized text projections, versions and the committed receipt publish together; embedding and optional Git effects have separate status. Remote callers preserve protected facts/takes fences. For remote writes, `[[wikilinks]]` and markdown links in the body that point at pages already in the same source become plain `mentions` links after the commit (a journaled `links` effect; the receipt's `auto_links.mention_links` says it is queued; `mcp.remote_auto_links false` turns it off). Typed and frontmatter links are skipped for untrusted writes: a stdio `gbrain serve` sweeps them at startup + on idle; `gbrain serve --http` does not self-sweep — run `gbrain sweep --once` or use trusted local capture/put_page for inline link extraction. Pass `wait_ms` (up to 30000) to hold the reply until the commit instead of polling get_write_request. For more than 3 pages, use `put_pages` (full surface). To add to the end of a log or conversation, use `append_page` instead of re-sending the page, and send a page larger than one request through an upload session (`begin_page_upload`, `upload_page_part`, `commit_page_upload`); both are on the full surface ([adding to a large page](../guides/memory-boundaries.md#adding-to-a-large-page)). Remote callers receive write_through.warning when no repo is configured. For file input use gbrain capture --file PATH --slug SLUG. A write the content-quality gate quarantined still commits but reports `quarantined: { reason, detail }` with a `page_quarantined` safety notice (put_pages marks each such page and emits one notice).
| Parameter | Type | Guidance |
| --- | --- | --- |
@@ -339,6 +339,7 @@ Hybrid search with vector + keyword, plus multi-query expansion when the search
| `since` | string | Filter to pages whose effective_date is >= this. ISO-8601 (YYYY-MM-DD or full timestamp) OR relative ('7d', '2w', '1y'). |
| `until` | string | Filter to effective_date <= this. Same format as `since`. YYYY-MM-DD lands at end-of-day. |
| `source_id` | string | Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile). Pass '__all__' to span every source for trusted local callers. For remote callers, '__all__' uses the same scope as omission: an OAuth grant when present, otherwise the transport-computed federated sources for grantless local stdio. |
+| `source_ids` | array | Narrow the request to these sources (CLI: `--source-ids source-a,source-b`). Each id is authorized like an explicit `source_id`, so the list can narrow a request but never widen it: a source outside a remote caller's grant refuses the whole request with `permission_denied`, and a removed or archived one with `unknown_source`. Omitted, `[]` or a blank string reads every source you can read; `__all__` is refused. With `source_id` too, the request reads their intersection, and an empty intersection returns no rows with an `empty_retrieval` notice. See [narrowing one request](../guides/multi-source-brains.md#narrow-one-request-with-source_ids). |
| `cross_modal` | string (`text`, `image`, `both`, `auto`) | Cross-modal search routing.<br> 'text' (default for non-image-intent queries) — text-only path.<br> 'image' — route the query through Voyage multimodal-3 + the embedding_image column. Best for 'show me photos of...' phrasings.<br> 'both' — run text AND image searches in parallel; merge via weighted RRF.<br> 'auto' — same effect as omitting the field; intent classifier decides based on query phrasing. |
| `embedding_column` | string | Route vector search through a non-default embedding column. Defaults to 'embedding' (the brain's primary column) unless `search_embedding_column` config sets a different default. Per-call override for A/B benchmarking across providers (e.g. 'embedding_voyage', 'embedding_openai'). Column MUST be declared in the `embedding_columns` config registry — unknown names throw with a paste-ready hint listing valid columns. |
| `adaptive_return` | boolean | Return a TIGHT, intent-sized result set instead of the full top-K. YOU (the agent) set this per query to serve the user well:<br> TRUE when the user's question has a small, specific answer — a lookup ('what is X', 'who is Y', 'what's my <thing>', 'what did Z decide'), a single-fact recall, or when you'll route the result into a precise downstream step (a classifier, a decision, an exact citation). The user gets the answer, not a wall of loosely-related pages, and you spend fewer tokens reading noise.<br> Omit / FALSE for breadth — 'everything about X', 'list all', 'what do I know about Y', exploration, brainstorming, or any time you'd rather see more candidates and judge for yourself. Recall matters more there, so take the full top-K.<br>Safe by construction: it NEVER returns empty when there are matches (you always get at least the top hit), and it only applies to the first page (omit when paginating). Caps come from config (search.adaptive_return_entity_max / _other_max; default 2 / 6) — pass `limit` 1 alongside this for a hard single-answer cap. |
@@ -406,7 +407,7 @@ Fuzzy-resolve a partial slug to matching page slugs
## `search`
-Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (it can add multi-query expansion with `expand: true`); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.
+Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. Best for exact known tokens, names, and structured-field lookups. A populated result set is NOT proof of coverage — for concept / synonym / landscape questions use `query` (it can add multi-query expansion with `expand: true`); for exhaustive enumeration use list_pages pagination. Pass `return_unit` ('window' / 'section' / 'page') for whole evidence instead of chunks; conversation pages already come back whole by default (return_unit 'auto'; 'chunk' opts out). For personal/emotional questions, prefer get_recent_salience or find_anomalies — they surface activity bursts without needing a search term. To find every page that contains a literal phrase or identifier, where you would otherwise grep, use `search_exact` (CLI `gbrain search --exact "<phrase>"`): it is unranked and exhaustive and says whether it read the whole scope ([exact search](../guides/exact-search.md)). For code-symbol questions (callers, callees, definitions, blast radius), use code_callers / code_callees / code_def / code_refs instead — those return structural graph data, not text chunks. For agent memory reads (saved facts + budget-packed retrieval), prefer the `recall` verb.
Every call also reports how many pages match the query's keywords (`keyword_total`, `keyword_truncated`; "10000+" past 10,000) in one line after the rows. That count covers keyword (full-text) matches only, not the ranked rows. To list every one of those pages, pass `match: "keyword"`: rows come one per page in keyword-score order with `total`, `truncated` and `next`, a ready-to-send argument object; keep calling with `next` until it is absent. A page whose text did not fit `token_budget` still gets a row, with `evidence_omitted: true`. If the count times out, the line says it is unavailable (degraded stage `keyword_count_unavailable`), never zero.
@@ -421,6 +422,7 @@ On a large Postgres brain a broad keyword statement can hit the keyword time lim
| `cursor` | string | The keyset cursor inside a `match: "keyword"` response's `next`. Send `next` unchanged; a cursor without `match: "keyword"` is refused (`search_cursor_requires_keyword`). |
| `mode` | string | Search mode (conservative\|balanced\|tokenmax). Local callers only: an agent-facing caller that sets it is refused (`search_mode_local_only`) with a fix naming `match: "keyword"`. |
| `source_id` | string | Scope search to a single source. Defaults to OperationContext.sourceId (set from CLI --source / GBRAIN_SOURCE / .gbrain-source dotfile); when unset, an unqualified read spans every federated source. Pass '__all__' to span every source for trusted local callers; for remote callers '__all__' spans only your granted sources. |
+| `source_ids` | array | Narrow the request to these sources (CLI: `--source-ids source-a,source-b`). Each id is authorized like an explicit `source_id`, so the list can narrow a request but never widen it: a source outside a remote caller's grant refuses the whole request with `permission_denied`, and a removed or archived one with `unknown_source`. Omitted, `[]` or a blank string reads every source you can read; `__all__` is refused. With `source_id` too, the request reads their intersection, and an empty intersection returns no rows with an `empty_retrieval` notice. See [narrowing one request](../guides/multi-source-brains.md#narrow-one-request-with-source_ids). |
| `types` | array | Filter results to pages whose `type` is in this list (e.g. ['person','company']). CLI: --types person,company. Applied at SQL level on every retrieval leg — the same filter `whoknows` uses. Stacks with all other filters. |
| `snippet_chars` | number | Cap each result's chunk_text at N characters (a "… [truncated]" marker names the get_page recovery move). 0 forces full text. Unset: subagent tool loops default to the agent.search_snippet_chars config (300; 0=full); every other caller gets full text. A row widened by `search.long_page_unit` (`delivered: {unit, reason: "long_page"}`) is exempt and comes back whole; every other row is still cut. |
| `return_unit` | string (`chunk`, `window`, `section`, `page`, `auto`) | Evidence unit returned in each result's chunk_text (default: config search.return_unit, which defaults to 'auto').<br> 'chunk' — the ranked chunk only (~300-450 tokens per result).<br> 'window' — the hit chunk plus return_window neighbor chunks each side (local context, ~3x chunk).<br> 'section' — the enclosing markdown section, or the conversation rounds around the hit.<br> 'page' — the whole page/session, capped. Use for multi-session or temporal questions where the answer needs the whole conversation.<br> 'auto' — the whole page for conversation pages (conversation/transcript/chat/meeting/slack/imessage types, chat/ or conversations/ slugs), the ranked chunk unchanged for everything else. When no hit is a conversation the response is exactly the chunk response.<br>Non-chunk units return one result per page, packed into token_budget (default 6000, auto 24000; remote max 32000), with a `delivered` object (unit, chunk_ids, match_spans, tokens, truncated; reason under auto) per result and `delivery` in the response meta. |
diff --git a/llms-full.txt b/llms-full.txt
index 049c149726..8fd01b4ea5 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2314,7 +2314,7 @@ from recurring:
narration. When a file's behavior changes, UPDATE its entry to the new truth.
- **CI is the enforcement, not this prose.** `scripts/check-key-files-current-state.sh`
(in `bun run verify`) fails on the bolded-release-clause marker in the reference
- docs AND on size caps for CLAUDE, README, the index, and each subsystem. A written rule caused this disease; a guard
+ docs AND on size caps for CLAUDE, the index, and each subsystem. A written rule caused this disease; a guard
cures it.
- **After any CLAUDE.md or reference-doc edit, run `bun run build:llms`** — the
llms bundle inlines/links these (config in `scripts/llms-config.ts`); the
diff --git a/llms.txt b/llms.txt
index f2f8a208d7..0014e91340 100644
--- a/llms.txt
+++ b/llms.txt
@@ -10,7 +10,7 @@ Repo: https://github.com/garrytan/gbrain
- [Grok Bot](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/grok-bot.md): Recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a client and install the thin CLI; local in-Bot memory as the no-host alternative. Native skill activation, shared-computer trust and dated evidence.
- [Muse personal agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/muse.md): Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP.
- [Inside an existing agent](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/in-agent-setup.md): Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration.
-- [Memory boundaries](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/memory-boundaries.md): Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits.
+- [Memory boundaries](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/memory-boundaries.md): Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).
- [Brain versus session memory](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/brain-vs-memory.md): Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.
- [Connect a hosted brain](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/hosted-harness-access.md): Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification.
- [Harness adapter reference](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/harness-adapters.md): Registry-generated transport, authentication lifetime and configuration facts.
@@ -22,6 +22,7 @@ Repo: https://github.com/garrytan/gbrain
- [CLAUDE.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CLAUDE.md): Orientation + resolver. North Star, two axes, architecture + cross-cutting invariants, the reference map pointing at on-demand docs, and the inline ship IRON RULES.
- [docs/architecture/KEY_FILES.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/KEY_FILES.md): Bounded navigation index for subsystem references: find a source file's current behavior, invariants, and test evidence without loading the entire reference corpus.
- [docs/architecture/thin-client.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/thin-client.md): The thin-client / remote-MCP / cross-modal routing seam: isThinClient detection, callRemoteTool, SSRF-hardened URL validation, per-command routing.
+- [docs/architecture/brains-and-sources.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/brains-and-sources.md): The two axes: a brain is which database, a source is which repo inside it. Resolution precedence for --brain and --source, topologies, Git as the parent of a source with a checkout (mixed, strict, mirror, database-only), entity identity across sources, cross-source links and what confines remote callers.
- [INSTALL_FOR_AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md): Step-by-step agent installation (steps 0-9): install, keyless init, the first-run decision bundle, harness wiring, verification and upgrades.
- [docs/protocol/AGENT_OPERATOR_v1.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/protocol/AGENT_OPERATOR_v1.md): The agent operator contract: read `code`, follow `fix.next` (run / ask_user / tell_user_to_run / wait / report), run `fix.verify`. Error envelope, notices and mute, effects/actor/next table, consent and preapproval, exit codes, marker grammar, compatibility policy, first run, and how to make gbrain work better for your user.
- [skills/RESOLVER.md](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/RESOLVER.md): Skill dispatcher. Read first for any task.
@@ -42,6 +43,13 @@ Repo: https://github.com/garrytan/gbrain
- [docs/guides/on-commit-sync.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/on-commit-sync.md): Opt-in on-commit sync in gbrain serve (sync.on_commit) and the per-source commit→searchable/embedded latency.
- [docs/guides/shared-checkout-git.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/shared-checkout-git.md): Committing and pushing when several agents share one brain checkout: `gbrain git commit-push` / `scripts/brain-commit-push.sh` (writer lock, path-scoped commit, in-memory merge, fast-forward-only advance), the outcome table, conflict resolution with --resolve, recovering a stuck rebase, the lock contract for host daemons, and the git commands never to run there.
- [docs/guides/sync-unblock-runbook.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/sync-unblock-runbook.md): Operator-agent loop for a managed catch-up on a live checkout: gbrain sync status --json (cursor, committed_last_10m, each hold and the last error with class / safe_actions / needs_human), gbrain sync unblock --apply, and the decision table (page / connection / systemic) behind them.
+- [docs/guides/git-canonical.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/git-canonical.md): Git-canonical (strict) sources, opt-in per source: every write committed to Git through one door before the database row, the database derived from commits (Git wins), when to turn it on, `gbrain sources canonical <id> --to git|mixed` preview and apply, remote writes through the owner's door (write_pending), declared database-only classes, rollback, doctor git_index_lag / db_ahead_of_git, `sources git-gap` and `sources reindex --from-git`.
+- [docs/guides/multi-source-brains.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/multi-source-brains.md): Several repos in one brain: `gbrain sources add|list|federate`, per-request `source_ids` narrowing on search and query (never widens a grant), hosting an empty source in a bare repository (`gbrain sources host-repo`), read-only mirrors and the full `gbrain sources` verb list.
+- [docs/guides/exact-search.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/exact-search.md): `gbrain search --exact "<phrase>"` / MCP `search_exact`: unranked, exhaustive literal scan instead of grep, with a `complete` flag that says whether the whole scope was read; filters and limits.
+- [docs/guides/cli-socket.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/cli-socket.md): Opt-in warm CLI socket on Postgres (`gbrain serve --cli-socket`): one-shot `gbrain search`, `query`, `get` and `recall` answered by the running serve, identity matching, refusals and GBRAIN_DEBUG=1 diagnostics.
+- [docs/guides/upgrades-auto-update.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/upgrades-auto-update.md): `gbrain upgrade` and auto-update: the stable release channel, restarting every gbrain process onto the new build, doctor runtime_build_skew, known-bad releases and recovery.
+- [docs/mcp/TOOL_REFERENCE.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/mcp/TOOL_REFERENCE.md): Longer guidance for each starter-surface MCP tool: defaults and edge cases per parameter (search and query `source_ids`, return_unit, match: keyword), and pointers to full-surface tools such as search_exact and append_page.
+- [docs/TOOL_CATALOG.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/TOOL_CATALOG.md): Generated: every MCP tool by area with its scope, starter membership and config gate (upload sessions, append_page, search_exact and the rest).
- [docs/guides/cron-schedule.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/cron-schedule.md): Recurring job scheduling.
- [docs/guides/minions-deployment.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-deployment.md): Deploying the gbrain jobs worker: crontab + watchdog, inline --follow, systemd/Procfile/fly.toml, upgrade checklist.
- [docs/guides/quiet-hours.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/quiet-hours.md): Notification hold + timezone-aware delivery.
@@ -93,6 +101,7 @@ Repo: https://github.com/garrytan/gbrain
## Optional
- [docs/designs/](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/designs/): Forward-looking designs.
+- [docs/architecture/generations.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/generations.md): Derived-data safety: how atoms, chronicle events, synthesis, facts and takes publish through one generation primitive, held results, retirements versioned and restorable for 30 days by default (generations.restore_days), and release or undo.
- [docs/architecture/infra-layer.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/infra-layer.md): Shared infra patterns.
- [docs/memorable-agents.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/memorable-agents.md): Optional Memorable procedural-memory integration: the session-end receipt, the config gate and kill switch, the consent model, and exactly what leaves the machine.
@@ -104,3 +113,5 @@ Repo: https://github.com/garrytan/gbrain
- `gbrain repair [<kind>] [--apply]` - preview, then fix timeline, visibility and safe-chunk damage doctor reports.
- `gbrain upgrade` runs post-upgrade + apply-migrations.
- `gbrain errors <code> [--json]` - explain any error code offline; follow its `fix.next`.
+- `gbrain search --exact "<phrase>"` - every page containing a literal phrase, instead of grep.
+- `gbrain sources git-gap <id> [--json]` - read-only: how far a source's database is from what Git has committed.
diff --git a/scripts/check-key-files-current-state.sh b/scripts/check-key-files-current-state.sh
index 8b27e5a3cf..b1f1729b9d 100755
--- a/scripts/check-key-files-current-state.sh
+++ b/scripts/check-key-files-current-state.sh
@@ -13,7 +13,7 @@
# marker is the disease signature; it must not appear in those docs. Plain prose
# ("as of pgvector 0.7", "Postgres 11+") is fine — only the bolded release
# marker is banned, so this never false-fires on legitimate version mentions.
-# 2. Size caps for CLAUDE.md, README.md, the index, each subsystem and
+# 2. Size caps for CLAUDE.md, the index, each subsystem and
# docs/TESTING.md. The TESTING.md cap is a ratchet: lower it when the file
# shrinks, never raise it; detail moves next to its code instead.
# 3. One reference bullet per src file across the index and subsystems — a cherry-pick that keeps both sides
@@ -87,7 +87,7 @@ if [ -f "$claude" ]; then
fi
fi
-for spec in "README.md:45000" "docs/architecture/KEY_FILES.md:10000"; do
+for spec in "docs/architecture/KEY_FILES.md:10000"; do
rel="${spec%:*}"
cap="${spec##*:}"
[ -f "$ROOT/$rel" ] || continue
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index e0118e417e..840822c4e5 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -42,7 +42,7 @@ export const SECTIONS: DocSection[] = [
{ title: "Grok Bot", path: "docs/guides/grok-bot.md", description: "Recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a client and install the thin CLI; local in-Bot memory as the no-host alternative. Native skill activation, shared-computer trust and dated evidence." },
{ title: "Muse personal agent", path: "docs/guides/muse.md", description: "Verify durable storage first; connect Muse to your published brain (`gbrain mcp expose --funnel` + thin CLI) or add local explicit memory with provenance alongside Muse's native memory; distinguish Muse Code and unverified native MCP." },
{ title: "Inside an existing agent", path: "docs/guides/in-agent-setup.md", description: "Isolated setup, absolute launcher, receipts, keyless maintenance, complete private backup and safe restoration." },
- { title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits.", includeInFull: false },
+ { title: "Memory boundaries", path: "docs/guides/memory-boundaries.md", description: "Durable shared preferences versus harness state; remote graph maintenance, provider text disclosure, authorization and full-backup limits; large pages (segmented storage up to 256 MiB on Postgres, append_page / gbrain append, upload sessions, windowed reads, limits per entry point).", includeInFull: false },
{ title: "Brain versus session memory", path: "docs/guides/brain-vs-memory.md", description: "Route durable facts and preferences to shared memory, configuration to the harness, and temporary work to session state.", includeInFull: false },
{ title: "Connect a hosted brain", path: "docs/guides/hosted-harness-access.md", description: "Getting the HTTPS endpoint (`gbrain mcp expose`, admin token file), host-side grants, private credential handoff, harness installation, profile repair, delegation limits and honest verification." },
{ title: "Harness adapter reference", path: "docs/guides/harness-adapters.md", description: "Registry-generated transport, authentication lifetime and configuration facts.", includeInFull: false },
@@ -78,6 +78,13 @@ export const SECTIONS: DocSection[] = [
path: "docs/architecture/thin-client.md",
includeInFull: false,
},
+ {
+ title: "docs/architecture/brains-and-sources.md",
+ description:
+ "The two axes: a brain is which database, a source is which repo inside it. Resolution precedence for --brain and --source, topologies, Git as the parent of a source with a checkout (mixed, strict, mirror, database-only), entity identity across sources, cross-source links and what confines remote callers.",
+ path: "docs/architecture/brains-and-sources.md",
+ includeInFull: false,
+ },
{
title: "INSTALL_FOR_AGENTS.md",
description: "Step-by-step agent installation (steps 0-9): install, keyless init, the first-run decision bundle, harness wiring, verification and upgrades.",
@@ -192,6 +199,55 @@ export const SECTIONS: DocSection[] = [
path: "docs/guides/sync-unblock-runbook.md",
includeInFull: false,
},
+ {
+ title: "docs/guides/git-canonical.md",
+ description:
+ "Git-canonical (strict) sources, opt-in per source: every write committed to Git through one door before the database row, the database derived from commits (Git wins), when to turn it on, `gbrain sources canonical <id> --to git|mixed` preview and apply, remote writes through the owner's door (write_pending), declared database-only classes, rollback, doctor git_index_lag / db_ahead_of_git, `sources git-gap` and `sources reindex --from-git`.",
+ path: "docs/guides/git-canonical.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/guides/multi-source-brains.md",
+ description:
+ "Several repos in one brain: `gbrain sources add|list|federate`, per-request `source_ids` narrowing on search and query (never widens a grant), hosting an empty source in a bare repository (`gbrain sources host-repo`), read-only mirrors and the full `gbrain sources` verb list.",
+ path: "docs/guides/multi-source-brains.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/guides/exact-search.md",
+ description:
+ "`gbrain search --exact \"<phrase>\"` / MCP `search_exact`: unranked, exhaustive literal scan instead of grep, with a `complete` flag that says whether the whole scope was read; filters and limits.",
+ path: "docs/guides/exact-search.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/guides/cli-socket.md",
+ description:
+ "Opt-in warm CLI socket on Postgres (`gbrain serve --cli-socket`): one-shot `gbrain search`, `query`, `get` and `recall` answered by the running serve, identity matching, refusals and GBRAIN_DEBUG=1 diagnostics.",
+ path: "docs/guides/cli-socket.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/guides/upgrades-auto-update.md",
+ description:
+ "`gbrain upgrade` and auto-update: the stable release channel, restarting every gbrain process onto the new build, doctor runtime_build_skew, known-bad releases and recovery.",
+ path: "docs/guides/upgrades-auto-update.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/mcp/TOOL_REFERENCE.md",
+ description:
+ "Longer guidance for each starter-surface MCP tool: defaults and edge cases per parameter (search and query `source_ids`, return_unit, match: keyword), and pointers to full-surface tools such as search_exact and append_page.",
+ path: "docs/mcp/TOOL_REFERENCE.md",
+ includeInFull: false,
+ },
+ {
+ title: "docs/TOOL_CATALOG.md",
+ description:
+ "Generated: every MCP tool by area with its scope, starter membership and config gate (upload sessions, append_page, search_exact and the rest).",
+ path: "docs/TOOL_CATALOG.md",
+ includeInFull: false,
+ },
{
title: "docs/guides/cron-schedule.md",
description: "Recurring job scheduling.",
@@ -457,6 +513,13 @@ export const SECTIONS: DocSection[] = [
path: "docs/designs/",
includeInFull: false,
},
+ {
+ title: "docs/architecture/generations.md",
+ description:
+ "Derived-data safety: how atoms, chronicle events, synthesis, facts and takes publish through one generation primitive, held results, retirements versioned and restorable for 30 days by default (generations.restore_days), and release or undo.",
+ path: "docs/architecture/generations.md",
+ includeInFull: false,
+ },
{
title: "docs/architecture/infra-layer.md",
description: "Shared infra patterns.",
@@ -481,6 +544,8 @@ export const INLINE_TIPS = [
"`gbrain repair [<kind>] [--apply]` - preview, then fix timeline, visibility and safe-chunk damage doctor reports.",
"`gbrain upgrade` runs post-upgrade + apply-migrations.",
"`gbrain errors <code> [--json]` - explain any error code offline; follow its `fix.next`.",
+ "`gbrain search --exact \"<phrase>\"` - every page containing a literal phrase, instead of grep.",
+ "`gbrain sources git-gap <id> [--json]` - read-only: how far a source's database is from what Git has committed.",
];
// Target ~800KB so llms-full.txt fits in ~200k-token contexts with room to spare.
diff --git a/test/scripts/check-key-files-current-state.test.ts b/test/scripts/check-key-files-current-state.test.ts
index 99a1686080..98e20f1d1e 100644
--- a/test/scripts/check-key-files-current-state.test.ts
+++ b/test/scripts/check-key-files-current-state.test.ts
@@ -151,8 +151,15 @@ describe("check-key-files-current-state.sh", () => {
expect(result.stderr).toContain("src/core/example.ts");
});
+ it("leaves README.md uncapped", () => {
+ seedClean();
+ writeDoc("README.md", "x".repeat(60000));
+ const result = run();
+ expect(result.status).toBe(0);
+ expect(result.stderr).not.toContain("README.md is");
+ });
+
it.each([
- ["README.md", 45000],
["docs/architecture/KEY_FILES.md", 10000],
["docs/architecture/key-files/engines.md", 60000],
] as const)("bounds %s without rejecting the exact cap", (path, cap) => {