# gbrain — full corpus # LLM Wiki An open-source template for building LLM-powered knowledge bases, following [Andrej Karpathy's "LLM Wiki" pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). You provide raw sources. The LLM reads them, writes structured wiki pages, cross-links everything, and maintains it over time. You never edit the wiki directly — you curate sources and ask questions. ## How It Works The system has three layers: ``` raw/ Sources you collect (articles, transcripts, notes, PDFs) wiki/ LLM-written & maintained pages (summaries, concepts, entities, syntheses) CLAUDE.md Schema that tells the LLM how to structure everything ``` Three operations drive the workflow: | Operation | Trigger | What happens | |-----------|---------|--------------| | **Ingest** | "ingest raw/my-source.txt" | LLM reads the source, creates a summary page, creates/updates concept and entity pages, adds cross-links, updates the index and log | | **Query** | Ask any question | LLM searches the wiki, synthesizes an answer with citations, optionally creates a synthesis page for novel insights | | **Lint** | "lint" or "health check" | LLM audits all pages for orphans, contradictions, missing links, incomplete sections, and low-confidence claims — fixes what it can, reports the rest | ## Quick Start 1. **Clone this repo** ```bash git clone https://github.com/YOUR_USERNAME/llm-wiki.git my-knowledge-base cd my-knowledge-base ``` 2. **Customize CLAUDE.md** for your domain - Update the Purpose section with your topic - Replace the placeholder tagging taxonomy with your own categories - Adjust confidence level descriptions if needed - Everything else (workflows, page formats, linking rules) works as-is 3. **Drop sources into `raw/`** - Text files, transcripts, articles, notes — any plain text - These are immutable once added; the LLM never modifies them 4. **Tell the LLM to ingest** ``` ingest raw/my-first-source.txt ``` The LLM will create summary pages, concept pages, entity pages, cross-links, and update the index. 5. **Ask questions** ``` What are the key differences between X and Y? ``` The LLM answers from the wiki, citing specific pages. 6. **Run health checks** ``` lint ``` The LLM audits the wiki and fixes issues. ## Directory Structure ``` . ├── CLAUDE.md # Schema — the LLM's instructions ├── raw/ # Your source documents (immutable) └── wiki/ ├── index.md # Master catalog of all pages ├── log.md # Append-only activity log ├── dashboard.md # Dataview dashboard (Obsidian) ├── analytics.md # Charts View analytics (Obsidian) ├── flashcards.md # Spaced repetition cards ├── summaries/ # One page per source document ├── concepts/ # Concept and framework pages ├── entities/ # People, tools, organizations, etc. ├── syntheses/ # Cross-cutting analyses and comparisons ├── journal/ # Research/session journal entries │ └── template.md # Journal entry template └── presentations/ # Marp slide decks ``` ## Enhancements This template includes several extras beyond the core wiki pattern: ### Dataview Dashboard (`wiki/dashboard.md`) Live queries that surface low-confidence pages, recent updates, concepts by tag, and pages with the most sources. Requires the [Dataview](https://github.com/blacksmithgu/obsidian-dataview) Obsidian plugin. ### Charts View Analytics (`wiki/analytics.md`) Visual analytics with pie charts, bar charts, and word clouds. Requires the [Charts View](https://github.com/caronchen/obsidian-chartsview-plugin) Obsidian plugin. ### Mermaid Diagrams Use Mermaid code blocks in any wiki page to create flowcharts, sequence diagrams, or concept maps. Native support in Obsidian and GitHub. ### Marp Slides (`wiki/presentations/`) Create slide decks from markdown using [Marp](https://marp.app/). Drop presentation files in this directory. ### Research Journal (`wiki/journal/`) Track your research sessions, experiments, or applied work with the included template. The LLM can reference journal entries when answering queries. ### Spaced Repetition (`wiki/flashcards.md`) Flashcards in the format used by the [Spaced Repetition](https://github.com/st3v3nmw/obsidian-spaced-repetition) Obsidian plugin. Ask the LLM to generate flashcards from any wiki page. ### MCP Server This repo works with Claude Code's MCP server capabilities. Point an MCP-compatible client at this repo and the LLM can read/write the wiki programmatically. ## Customizing for Your Domain The schema in `CLAUDE.md` is domain-agnostic. To adapt it: 1. **Purpose** — Describe your knowledge domain in one paragraph 2. **Tagging taxonomy** — Replace placeholder categories with your own (e.g., for a cooking KB: `cuisine`, `technique`, `ingredient`, `equipment`) 3. **Confidence levels** — Adjust the descriptions to match your domain's evidence standards 4. **Entity types** — Update the entity page description to match what entities mean in your domain (people, tools, companies, etc.) 5. **Journal template** — Customize `wiki/journal/template.md` for your workflow Everything else — page format, linking conventions, workflows, rules — is universal and works across domains. ## Example Domains This template works for any knowledge-intensive topic: - **Research notes** — papers, experiments, methodologies - **Book analysis** — themes, characters, author techniques - **Competitive analysis** — companies, products, market trends - **Course notes** — lectures, readings, key concepts - **Personal development** — frameworks, habits, book summaries - **Technical documentation** — APIs, architectures, design patterns - **Hobby deep-dives** — any subject you want to master ## License MIT --- title: "Knowledge Base Index" type: index updated: 2026-07-02 --- # Knowledge Base Index Master catalog of all wiki pages. Every page in the wiki must have an entry here. ## Concepts | Page | Tags | Confidence | Updated | |------|------|------------|---------| | [[concepts/brains-and-sources]] | brains, foundational, operator | high | 2026-07-02 | | [[concepts/ingestion-pipeline]] | ingestion, brains, foundational, well-established | high | 2026-07-02 | | [[concepts/install-and-setup]] | operations, user, foundational | high | 2026-07-02 | | [[concepts/mcp-integration]] | mcp, user, developer, foundational, well-established | high | 2026-07-02 | | [[concepts/minions-orchestration]] | minions, operator, foundational, well-established | high | 2026-07-02 | | [[concepts/operations-and-cost]] | operations, operator, foundational, well-established | high | 2026-07-02 | | [[concepts/overview]] | brains, foundational, user | high | 2026-07-02 | | [[concepts/retrieval-and-search]] | retrieval, foundational, user | high | 2026-07-02 | | [[concepts/schema-packs]] | schema, foundational, operator | high | 2026-07-02 | | [[concepts/skillpacks-and-skills]] | skillpacks, foundational, developer | high | 2026-07-02 | | [[concepts/verification-and-quality]] | eval, operator, developer, foundational, well-established | high | 2026-07-02 | ## Entities | Page | Tags | Updated | |------|------|---------| | [[entities/ai-provider-integrations]] | operations, retrieval, mcp | 2026-07-02 | | [[entities/recipes-catalog]] | ingestion, operations, developer | 2026-07-02 | | [[entities/skills-catalog]] | skillpacks, operations, developer | 2026-07-02 | ## Summaries | Page | Source | Key Topics | Created | |------|--------|------------|---------| | [[summaries/version-digest]] | `raw/github_doc-changelog-md.md` | Version Digest | 2026-07-02 | ## Syntheses | Page | Pages Compared | Created | |------|----------------|---------| | [[syntheses/brain-vs-memory]] | brains, mcp, foundational, operator | 2026-07-02 | | [[syntheses/topology-picker]] | brains, operations, foundational | 2026-07-02 | | [[syntheses/troubleshooting-casebook]] | operations, retrieval, ingestion, mcp, verification | 2026-07-02 | ## Statistics - **Total pages**: 18 - **Concepts**: 11 - **Entities**: 3 - **Summaries**: 1 - **Syntheses**: 3 - **Sources ingested**: 0 - **High confidence**: 18 - **Medium confidence**: 0 - **Low confidence**: 0 --- title: "Brains and Sources" type: concept tags: [brains, foundational, operator] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-architecture-brains-and-sources-md.md", "raw/github_doc-docs-architecture-system-of-record-md.md", "raw/github_doc-docs-guides-originals-folder-md.md", "raw/github_doc-docs-guides-multi-source-brains-md.md", "raw/github_doc-docs-guides-source-attribution-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition GBrain organizes knowledge along two orthogonal axes. A **brain** is a database (PGLite file, self-hosted Postgres, or Supabase) — you can have many, and each has its own tables, OAuth surface, and lifecycle. A **source** is a named content repo *inside* one brain — a wiki, a `gstack` checkout, an essay collection — and one brain can hold several. `--brain ` picks which database; `--source ` picks which repo within it. Underneath both axes sits the **system-of-record** contract: the git repo of markdown files is canonical, and the Postgres/PGLite database is a derived, disposable cache that gets rebuilt from the repo, never backed up directly. ## How It Works **Resolution precedence** is identical in shape for both axes — highest-priority match wins: ``` WHICH BRAIN (DB)? WHICH SOURCE (repo in DB)? 1. --brain 1. --source 2. GBRAIN_BRAIN_ID env 2. GBRAIN_SOURCE env 3. .gbrain-mount dotfile 3. .gbrain-source dotfile 4. longest-prefix mount path match 4. longest-prefix source path match 5. (reserved: brains.default v2) 5. sources.default config 6. fallback: 'host' 6. fallback: 'default' ``` Sources are managed with `gbrain sources add --path

[--federated|--no-federated]`, `gbrain sources list`, `remove`, `rename`, `default`, `attach` (writes `.gbrain-source` into the CWD, kubectl-context style), `detach`, `federate`/`unfederate`. Every `pages` row carries a `source_id`, and slugs are unique **per source**, not globally — the same slug can exist under two different sources as two different pages. The **federation** flag (`config.federated`, default `false` for new sources) controls whether a source joins unqualified `gbrain search "X"` results; the seeded `default` source is `federated=true` so pre-v0.17 brains behave unchanged. Multi-source citations use `[source-id:slug]` form, e.g. `[wiki:topics/ai]`. Brains are enumerated by a **host** (the default, in `~/.gbrain/config.json`) plus **mounts** registered via `gbrain mounts add --path --db-url `. Topologies range from a single-person/single-source setup, to one person with several federated sources inside one brain, to a personal brain plus one mounted team brain, up to a CEO-class user mounting several team brains — each internally organized as its own multi-source brain. Cross-brain queries are **not deterministic**: the agent sees the brain list (`gbrain mounts list`) and decides when to fan out, which keeps access control clean by design. **Durability ("harden")**: `gbrain sources add wiki --url --pat-file ` clones a brain repo and automatically installs pull-first rebase safety, an atomic commit+push helper (`scripts/brain-commit-push.sh`), a 30-minute DB-free background pull cron, and a repo-scoped credential — verified before declaring success. Re-run `gbrain sources harden ` any time to audit an existing source. **The system of record** classifies every table into three buckets: FS-canonical (takes, facts, links, timeline, tags — markdown is the source of truth, a reconciler like `extract links` or `extract_facts` rebuilds the DB row from the fence/section), derived-but-not-user-authored (`pages`, `content_chunks`, `page_versions` — rebuilt by the chunker/embedder on import), and DB-only-by-design (OAuth tokens, job queues, audit logs — infrastructure state that never belongs in git). Disaster recovery is one command: `gbrain rebuild --confirm-destructive` wipes derived tables and `gbrain sync && gbrain extract all` regenerates them from markdown. **Provenance and originals.** Every fact written to the brain — compiled truth or timeline — carries an inline `[Source: who, channel/context, date time tz]` citation; tweet citations must include the full URL, not just a handle. When sources conflict, both are noted rather than silently resolved, following a priority order (user direct statements > primary sources > enrichment APIs > web search > social media). A separate `originals/` directory captures the user's own thinking verbatim — not paraphrased — using the user's exact phrasing for the slug (`meatsuit-maintenance-tax`, not a sanitized description), cross-linked aggressively to the people, meetings, and media that shaped it. A user's *synthesis* of someone else's idea also counts as original and belongs in `originals/`, not `concepts/`. ## Key Parameters - `--brain ` / `GBRAIN_BRAIN_ID` / `.gbrain-mount` — which database. - `--source ` / `GBRAIN_SOURCE` / `.gbrain-source` — which repo within that database. - `federated: true|false` per source — whether it joins default cross-source search. - FS-canonical vs derived-but-not-authored vs DB-only-by-design — which category a new table falls into determines its rebuild story. ## When To Use Use `--source` when the data owner stays the same but the topic/repo changes (a second personal repo, an isolated essays draft folder). Use `--brain` when the data owner changes (a team-published brain, someone else's server). Isolate a topic from personal search with `federated=false`; keep cross-repo recall automatic with `federated=true`. ## Risks & Pitfalls - Treating a source boundary as a brain boundary (or vice versa) misroutes queries silently — the resolver never guesses on writes, but reads can quietly search the wrong scope. - A team's facts belong in the team's brain, not the personal brain — writing cross-brain without asking violates the ownership model. - Skipping citations on compiled-truth claims (not just timeline entries) is the most common attribution failure; compiled truth is not exempt just because it's synthesized. - Assuming the database is backed up: it isn't, by design — losing the markdown repo (not the DB) is the actual failure mode to guard against. ## Related Concepts - [[concepts/overview]] — compiled truth + timeline, the page-level pattern this architecture supports - [[concepts/schema-packs]] — what shape each source/brain takes - [[concepts/ingestion-pipeline]] — how content lands inside a source - [[concepts/verification-and-quality]] — citation and audit discipline ## Sources docs/architecture/brains-and-sources.md; docs/architecture/system-of-record.md; docs/guides/originals-folder.md; docs/guides/multi-source-brains.md; docs/guides/source-attribution.md. --- title: "Ingestion Pipeline" type: concept tags: [ingestion, brains, foundational, well-established] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-guides-enrichment-pipeline-md.md", "raw/github_doc-docs-guides-entity-detection-md.md", "raw/github_doc-docs-guides-deterministic-collectors-md.md", "raw/github_doc-docs-guides-live-sync-md.md", "raw/github_doc-docs-guides-meeting-ingestion-md.md", "raw/github_doc-docs-guides-diligence-ingestion-md.md", "raw/github_doc-docs-guides-idea-capture-md.md", "raw/github_doc-docs-guides-content-media-md.md", "raw/github_doc-docs-guides-push-context-md.md"] confidence: high gbrain_version: "0.42.56.0" --- ## Definition The ingestion pipeline is how raw signal — conversation, meeting transcripts, data-room documents, original ideas, YouTube videos, tweets, PDFs — becomes structured, cross-linked, searchable pages inside a gbrain brain. It is not one command; it is a family of patterns (entity detection, enrichment, deterministic collectors, and content-type-specific ingestors) that all converge on the same contract: extract entities, write or update pages, back-link bidirectionally, and sync so the write is searchable. ## How It Works **Entity detection** runs on every inbound message via a cheap async sub-agent (Sonnet-class, not Opus) that scans for two things in priority order: original thinking (captured verbatim into `brain/originals/{slug}.md` — the idea-capture flow covered below) and entity mentions (people, companies, media). Detection is deliberately non-blocking: the user's response is never held up by brain writes. A `gbrain search` dedup check runs before any page is created, since variant spellings and nicknames are the main source of duplicate pages. Every entity mention forces a back-link from the entity's page to the source — "the Iron Law of Back-Linking" — because an unlinked mention breaks graph traversal. **Enrichment** scales spend to importance via a three-tier system: Tier 1 (key people, 10-15 API calls: web, Twitter/X, LinkedIn via Crustdata, funding data, meeting-transcript search, contacts) down to Tier 3 (1-2 calls, brain cross-reference only). Raw API responses are stored via `gbrain put_raw_data ` for auditability and re-processing, overwritten (not appended) on re-enrichment, and gated to at most once per week per page. Enrichment writes to State/Contact/Timeline sections but never overwrites a human-written Assessment section — that stays sacrosanct. **Deterministic collectors** split mechanical work from judgment: a plain script (no LLM calls) fetches data, generates links/URLs, tags noise via regex, and tracks seen/new state atomically; a separate LLM pass reads the pre-formatted digest and adds classification, commentary, and brain enrichment. The principle: if output must be present and correctly formatted every time, generate it in code; if it needs judgment, generate it with the LLM — never both in the same pass. **Meeting ingestion** pulls the *complete* diarized transcript (never an AI summary, which hallucinates framing), writes the agent's own analysis above a full transcript below, then propagates a timeline entry to every attendee's page, every mentioned person's page, and every mentioned company's page — this propagation step is "the step most agents skip." Runs on a 3x/day cron (10 AM, 4 PM, 9 PM). **Diligence ingestion** is a 9-step pipeline that turns pitch decks and financial models into a diligence directory (`brain/diligence/{company}/`) with diarized documents, preserved raw files, and an `index.md` carrying Round Details, Document Inventory, Key Findings, Bull Case, Bear Case, and Open Questions. **Idea capture** applies an "authorship test" (user-generated → `originals/`; synthesis of others' ideas → still `originals/`, since the synthesis is itself original; world concept → `concepts/`; business idea → `ideas/`) and mandates exact phrasing — never paraphrase, since "the language IS the insight." **Content/media ingestion** covers YouTube (diarized transcript + agent analysis, never the auto-summary), social bundles (thread + linked articles + engagement, not just the tweet), and PDFs/documents (OCR if needed, chapter summaries, cross-references). **Live sync** and **push-based context** close the loop: `gbrain sync --repo && gbrain embed --stale` (always chained) makes new/edited pages searchable, while push-based context (`src/core/context/volunteer.ts`) volunteers relevant pages from recent conversation across three channels (`reflex`, `op`, `watch`) without the agent needing to ask. ## Key Parameters - Sub-agent model for detection: Sonnet-class (5-10x cheaper than Opus, sufficient for pattern matching) — see [[concepts/minions-orchestration]] and sub-agent routing. - Enrichment tiers: Tier 1 (10-15 calls) / Tier 2 (3-5 calls) / Tier 3 (1-2 calls), re-enrichment gated to weekly. - LinkedIn connection count < 20 flags a false-match discard. - `GBRAIN_SYNC_AUTOSKIP_AFTER` (default 3) auto-skips a file that fails the same way on consecutive syncs so the rest of the brain keeps indexing. - Push-context gate: `min_confidence` default 0.7, hard cap 5 pages, `retrieval_reflex_window_turns` default 4. - Meeting-sync cron: 10 AM, 4 PM, 9 PM weekdays. ## When To Use Use entity detection and the async signal-detector pattern on every conversational surface where people/companies/ideas come up in passing. Use deterministic collectors for any cron-driven data pull (email, X, calendar, GitHub) where link/format correctness must be 100%. Use the meeting/diligence/idea/media ingestors for their respective content types rather than a generic import — each has domain-specific propagation and quality-bar requirements. Always chain `gbrain sync` after any write. ## Risks & Pitfalls - Skipping entity propagation on meetings (updating only the meeting page, not attendee/company pages) is the most common half-ingestion failure. - Letting an LLM generate links or IDs in long outputs — it will silently drop formatting rules after ~10 items; bake links into the deterministic collector instead. - Creating stub pages (a name with no content) gives false confidence — worse than no page. - Running sync without `gbrain embed --stale` leaves new chunks unindexed for vector search even though `gbrain sync` "succeeded." - IPv4-only hosts silently fail the direct-connection leg of sync against Supabase's Transaction pooler — the #1 cause of "sync ran but nothing happened." ## Related Concepts [[concepts/minions-orchestration]], [[concepts/mcp-integration]], [[concepts/operations-and-cost]], [[concepts/verification-and-quality]] ## Sources raw/github_doc-docs-guides-enrichment-pipeline-md.md, raw/github_doc-docs-guides-entity-detection-md.md, raw/github_doc-docs-guides-deterministic-collectors-md.md, raw/github_doc-docs-guides-live-sync-md.md, raw/github_doc-docs-guides-meeting-ingestion-md.md, raw/github_doc-docs-guides-diligence-ingestion-md.md, raw/github_doc-docs-guides-idea-capture-md.md, raw/github_doc-docs-guides-content-media-md.md, raw/github_doc-docs-guides-push-context-md.md --- title: "Install and Setup" type: concept tags: [operations, user, foundational] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-install-md.md", "raw/github_doc-install-for-agents-md.md", "raw/github_doc-docs-operations-headless-install-md.md", "raw/github_doc-docs-guides-upgrades-auto-update-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition Installing GBrain means getting a Bun + TypeScript CLI onto a machine, initializing a local (PGLite) or shared (Postgres/Supabase) database, and wiring it into either an agent platform (OpenClaw, Hermes) or a coding agent (Claude Code, Codex) via MCP. GBrain is explicitly "designed to be installed and operated by an AI agent" — the canonical install path is handing an agent `INSTALL_FOR_AGENTS.md` and letting it execute the steps, asking the human only for API keys and yes/no decisions. ## How It Works **Three human-facing install paths** (`docs/INSTALL.md`), pick one and mix later: 1. **Run with an agent platform.** `bun install -g github:garrytan/gbrain`, then `gbrain init --pglite` (2 seconds, no server), then `gbrain skillpack scaffold --all` to drop 43 skills into the agent workspace, then `gbrain doctor` to confirm green checks. Upgrading later is `gbrain upgrade`. 2. **CLI standalone.** Same `bun install -g` + `gbrain init --pglite`, no agent platform. Init detects repo size and suggests Supabase above ~1000 markdown files (`gbrain migrate --to supabase` / `--to pglite` to move engines later). 3. **MCP server for any client.** `gbrain serve` (stdio, local subprocess) or `gbrain serve --http` (OAuth 2.1 + `/admin` dashboard). `gbrain connect https://your-host/mcp --token gbrain_xxx [--install]` wires a remote brain into Claude Code or Codex in one command and smoke-tests the token with `--install`. **Agent-driven install** (`INSTALL_FOR_AGENTS.md`, ~30 minutes end to end) walks a fresh agent through 9 numbered steps: install Bun + `bun install -g github:garrytan/gbrain`; collect API keys (`ZEROENTROPY_API_KEY` default embedding+reranker, `OPENAI_API_KEY` fallback, `ANTHROPIC_API_KEY` optional for query expansion); `gbrain init` + `gbrain doctor --json`; **confirm search mode with the operator before proceeding** (Step 3.5 — see below, this step must not be silently skipped); `gbrain import ~/brain/ --no-embed` then `gbrain embed --stale`; backfill the knowledge graph on existing content with `gbrain extract links --source db` + `gbrain extract timeline --source db`; scaffold skills with `gbrain skillpack scaffold --all` and read `skills/RESOLVER.md`; optionally run the soul-audit skill for identity (SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md); set up recurring jobs (or just run `gbrain autopilot --install`, a self-maintaining daemon); configure integrations via `gbrain integrations list`; and finally run the 7 checks in `docs/GBRAIN_VERIFY.md`. **Step 3.5 is a hard stop, not optional.** `gbrain init` auto-applies a default search mode. The agent must present the 9-cell cost matrix (mode × downstream model, $40–$1,000/mo at 10K queries/mo, a 25x spread corner to corner) verbatim and ask the operator to choose `conservative`, `balanced`, or `tokenmax` before running any real queries — silently accepting the default can rack up surprise spend. See [[concepts/operations-and-cost]] for the full cost model. **v0.42.0+ onboarding.** `gbrain onboard --check --json` surfaces structured, apply-policy-tagged recommendations (`auto_apply`, `prompt_required`, `manual_only`) across 5 brain-health axes. Run it after `gbrain init` and after every `gbrain upgrade`. Unattended remediation requires an explicit budget: `gbrain onboard --auto --max-usd 5` (refuses without `--max-usd`). ## Key Parameters - `gbrain init --pglite` — zero-config local brain, 2 seconds, no Docker. - `gbrain init --mcp-only` — thin-client mode: configures a remote MCP connection, skips a local engine entirely; most local commands refuse with a paste-ready hint. - `gbrain doctor --json` / `gbrain doctor` — health check; on failure it names the exact repair command. - API keys resolve from `~/.gbrain/config.json` (file plane) or env vars; `gbrain config set zeroentropy_api_key sk-...` writes them. - `self_upgrade.mode` (`notify` default / `auto` opt-in / `off`) — governs whether upgrades apply silently. `notify` always waits for explicit confirmation; `auto` only fires during quiet hours, when idle, doctor-gated, never retrying a known-bad version. - Headless/CI installs: pattern 1 (provider key at build time, `gbrain init --pglite` bakes in `embedding_model`) vs pattern 2 (`gbrain init --pglite --no-embedding` at build, real provider configured + `gbrain init --force` at container start). As of v0.37, `gbrain init --pglite` in a non-TTY context with no embedding key present exits 1 by deliberate fail-loud design — it will not silently pick a mismatched default. ## When To Use - **Fresh personal setup, no agent platform yet**: `gbrain init --pglite` + `claude mcp add gbrain -- gbrain serve` is the fastest path to a coding-agent memory, zero server/token/tunnel. - **Already have OpenClaw/Hermes**: paste `INSTALL_FOR_AGENTS.md`'s URL into the agent and let it run the full 9-step protocol, including 43 skills and the dream cycle. - **Docker/CI/postinstall**: use one of the two headless patterns in `docs/operations/headless-install.md` — never rely on `gbrain init --pglite` silently defaulting in a non-TTY context. - **Team/company brain**: follow the dedicated company-brain tutorial rather than the personal-brain path (multi-user, OAuth-scoped). ## Risks & Pitfalls - `bun install -g` can hit a postinstall error that blocks schema migrations (`gbrain doctor` reports `schema_version: 0`); recovery is `gbrain apply-migrations --yes`, or the deterministic fallback: `git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain && bun install && bun link`. - Never silently move past the Step 3.5 / post-upgrade search-mode banner — the cost spread across modes and models is large enough that an agent choosing without asking can surprise the user's bill. - In headless installs, `RUN gbrain init --pglite` with no provider key baked in is the one pattern that silently produces a dimension mismatch (`vector(1280)` vs a 1536d provider) — always use one of the two documented patterns instead. - Migration files under `skills/migrations/vX.Y.Z.md` are agent instructions to read and adapt, not scripts to execute blindly; skipping them is how a feature ships in the binary but stays dormant for an existing user. ## Related Concepts - [[concepts/overview]] — what gbrain is before you install it - [[concepts/mcp-integration]] — wiring an installed brain into Claude Code, Codex, and other MCP clients - [[concepts/operations-and-cost]] — the search-mode cost matrix referenced during install and upgrade - [[concepts/brains-and-sources]] — what `gbrain init` actually creates ## Sources docs/INSTALL.md; INSTALL_FOR_AGENTS.md; docs/operations/headless-install.md; docs/guides/upgrades-auto-update.md. --- title: "MCP Integration" type: concept tags: [mcp, user, developer, foundational, well-established] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-mcp-claude-code-md.md", "raw/github_doc-docs-mcp-claude-desktop-md.md", "raw/github_doc-docs-mcp-claude-cowork-md.md", "raw/github_doc-docs-mcp-codex-md.md", "raw/github_doc-docs-mcp-chatgpt-md.md", "raw/github_doc-docs-mcp-perplexity-md.md", "raw/github_doc-docs-mcp-deploy-md.md", "raw/github_doc-docs-architecture-thin-client-md.md", "raw/github_doc-docs-guides-sub-agent-routing-md.md", "raw/github_doc-docs-tutorials-connect-coding-agent-md.md"] confidence: high gbrain_version: "0.42.56.0" --- ## Definition MCP integration is how any AI agent — Claude Code, Claude Desktop, Claude Cowork, Codex, ChatGPT, Perplexity — connects to a gbrain brain as a tool server, either locally over stdio (`gbrain serve`) or remotely over HTTP with OAuth 2.1 or legacy bearer tokens (`gbrain serve --http`). Once connected, the agent gets brain-aware tools (`search`, `query`, `get_page`, `put_page`, `think`, `find_experts`, and more) instead of re-deriving context every session. ## How It Works **Local stdio** is the zero-setup path: `claude mcp add gbrain -- gbrain serve` (or `codex mcp add gbrain -- gbrain serve`) spawns `gbrain serve` as a subprocess. No server, tunnel, or token; works on both PGLite and Postgres engines. **Remote HTTP** (`gbrain serve --http --port 3131`) ships full OAuth 2.1 (client credentials, authorization code + PKCE, refresh rotation, optional DCR), an embedded `/admin` dashboard, scoped operations, and a live SSE activity feed. `--bind 0.0.0.0` is required to accept non-loopback connections (default is `127.0.0.1`); `--public-url` must match the tunnel/host so the OAuth issuer in discovery metadata is consistent. `gbrain connect --token [--agent ] [--install]` is the fast path: it prints (or, with `--install`, directly runs) the client-specific `mcp add` command and smoke-tests the token by calling `get_brain_identity` before handing off, so a bad token fails immediately rather than on first use. Per-client specifics: **Claude Code** — `claude mcp add gbrain -- gbrain serve` (local) or `claude mcp add gbrain -t http -H "Authorization: Bearer "` (remote). **Claude Desktop** — remote servers must be added via Settings > Integrations in the GUI; `claude_desktop_config.json` only supports local stdio servers and fails silently for remote. **Claude Cowork** — either a remote connector added by an org Owner, or automatic bridging through an already-configured Claude Desktop (no separate server needed). **Codex** — `codex mcp add gbrain --url --bearer-token-env-var GBRAIN_REMOTE_TOKEN`; Codex stores the env-var *name*, not the token, and reads it at launch. **ChatGPT** — the only client that hard-requires OAuth 2.1 + PKCE; register a client of grant type `authorization_code` from `/admin`, expose the server publicly (e.g. ngrok), and add the connector with the discovered `/.well-known/oauth-authorization-server` endpoint. **Perplexity** — remote-only; needs `--bind 0.0.0.0` and a matching `--public-url`, supports either OAuth client-credentials (recommended) or a legacy bearer token. Every scoped operation is tagged `read | write | admin`; four operations (`sync_brain`, `file_upload`, `file_list`, `file_url`) are `localOnly` and rejected over HTTP regardless of scope, so remote agents can never reach local filesystem surface area. **Thin-client architecture** (`gbrain init --mcp-only`, v0.29.2+) sets up an install with no local brain content — just an OAuth client pointing at a remote `gbrain serve --http`. As of v0.31.1 every CLI operation surface correctly routes to the remote brain instead of silently falling through to an empty local PGLite (the earlier "No results against a populated remote brain" bug class). Routing lives inline in `src/cli.ts` (`runThinClientRouted`), detects `isThinClient(cfg)` before ever opening a local engine, and normalizes every transport failure into a typed `RemoteMcpError`. **Sub-agent model routing** governs cost when an MCP-connected agent spawns sub-agents: route the main session to a strong model (Opus-class) and route cheap, high-volume work — entity detection on every message, research execution — to a cheaper model (Sonnet-class for detection, DeepSeek-class for research), typically cutting total cost 50-80%. **The connect-a-coding-agent workflow** has two paths: Path A connects a laptop agent to an existing populated brain (host serves HTTP, mint a token, one `gbrain connect ... --install` per agent); Path B starts from nothing (`gbrain init --pglite`, `gbrain capture` or `gbrain import`, then `claude mcp add gbrain -- gbrain serve`). Either way, the payoff is the **brain-first protocol**: search before answering, write back decisions/entities with `put_page`, and cite the page used — pasted into `CLAUDE.md` / `AGENTS.md`. ## Key Parameters - `gbrain auth create ` — mint a long-lived, full-access bearer token (Postgres only). - `gbrain auth register-client --grant-types client_credentials|authorization_code --scopes "read write"` — OAuth client registration; `--source` / `--federated-read` scope multi-source brains. - `mcp.publish_skills` — gates `list_skills`; default ON for new `gbrain init` brains, OFF for upgraded brains (`gbrain config set mcp.publish_skills true`). - `capture` is CLI-only, never an MCP tool — remote/MCP writers use `put_page`. ## When To Use Use local stdio for single-machine setups with zero infra. Use remote HTTP + OAuth whenever multiple devices, a team, or ChatGPT/Perplexity need access. Use thin-client mode when an agent should reach a shared remote brain with no local content at all. ## Risks & Pitfalls - Adding a remote MCP server to Claude Desktop via the JSON config file — it silently fails; must go through Settings > Integrations. - Forgetting `--bind 0.0.0.0` — the tunnel is up but every remote connection gets `ECONNREFUSED` (a stderr WARN fires when `--public-url` is set without `--bind`). - Treating a `gbrain auth create` bearer token as low-stakes — it is long-lived and full-access; prefer scoped OAuth clients for anything cloud-hosted. - Running entity detection or other high-volume sub-agent work on Opus instead of Sonnet — a 5-10x cost multiplier for no quality gain on pattern-matching tasks. ## Related Concepts [[concepts/ingestion-pipeline]], [[concepts/minions-orchestration]], [[concepts/operations-and-cost]] ## Sources raw/github_doc-docs-mcp-claude-code-md.md, raw/github_doc-docs-mcp-claude-desktop-md.md, raw/github_doc-docs-mcp-claude-cowork-md.md, raw/github_doc-docs-mcp-codex-md.md, raw/github_doc-docs-mcp-chatgpt-md.md, raw/github_doc-docs-mcp-perplexity-md.md, raw/github_doc-docs-mcp-deploy-md.md, raw/github_doc-docs-architecture-thin-client-md.md, raw/github_doc-docs-guides-sub-agent-routing-md.md, raw/github_doc-docs-tutorials-connect-coding-agent-md.md --- title: "Minions Orchestration" type: concept tags: [minions, operator, foundational, well-established] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-guides-minions-deployment-md.md", "raw/github_doc-docs-guides-minions-shell-jobs-md.md", "raw/github_doc-docs-guides-minions-fix-md.md", "raw/github_doc-docs-guides-cron-schedule-md.md", "raw/github_doc-docs-guides-quiet-hours-md.md", "raw/github_doc-docs-guides-queue-operations-runbook-md.md"] confidence: high gbrain_version: "0.42.56.0" --- ## Definition Minions is gbrain's background-job system: a Postgres-backed (or PGLite, with caveats) job queue that runs deterministic scripts and scheduled maintenance work — cron-driven collectors, the nightly dream cycle, shell scripts — without paying for a full LLM gateway session on every tick. "Minions orchestration" covers deploying a durable worker, submitting shell jobs safely, scheduling the recurring jobs a production brain needs, and diagnosing a stalled queue. ## How It Works The core primitive is `gbrain jobs work`, a worker that claims and executes jobs from the queue. Because a bare worker can die silently (DB connection drops, lock-renewal failures, Bun crashes), the canonical deployment wraps it in `gbrain jobs supervisor`, which auto-restarts the worker with exponential backoff (1s → 60s cap), writes a PID file, emits lifecycle events to `~/.gbrain/audit/supervisor-YYYY-Www.jsonl`, and drains gracefully on SIGTERM (35s window). Exit codes are documented so an agent can branch: `0` clean shutdown, `1` max crashes exceeded (page a human), `2` another supervisor holds the lock, `3` PID file unwritable. Deployment recommendations differ by host: containers run the supervisor as PID 1; Linux VMs with systemd layer systemd (host-level restart) over the supervisor (in-process crash recovery); dev laptops just run it in a terminal. `--nice N` lowers CPU scheduling priority without cutting concurrency, useful when the worker shares a machine with interactive use. **Shell jobs** move deterministic cron scripts (token refresh, API fetch/write) off the LLM gateway entirely — zero tokens per run, with retry/backoff/DLQ and `gbrain jobs list` visibility. Two independent gates protect the blast radius: MCP callers can never submit a `shell` job (rejected regardless of the env flag), and the worker only registers the shell handler when `GBRAIN_ALLOW_SHELL_JOBS=1` is set. Shell jobs run with a minimal env (`PATH, HOME, USER, LANG, TZ, NODE_ENV`); secrets are opted in per job via `inherit: ["database_url", ...]` (names only ever land in the row; values resolve at child-spawn) rather than baked into `env:`, and `redact_secrets: true` scrubs known-secret values out of stdout/stderr before persistence. PGLite installs can't run a persistent worker (exclusive file lock) — every crontab invocation must add `--follow` to run inline. **Migration/health**: `gbrain jobs supervisor` was preceded by a hand-rolled `minion-watchdog.sh`; `gbrain apply-migrations --yes` is the idempotent fix for a half-migrated Minions install (missing `~/.gbrain/preferences.json`, autopilot still inline). `gbrain doctor` and `gbrain skillpack-check` detect the half-installed state and print exact remediation commands. **Cron scheduling** is the backbone of a self-maintaining brain: email/X collection every 30 minutes, meeting sync 3x/day, calendar sync weekly, and the nightly **dream cycle** (2 AM) — entity sweep, broken-citation repair, memory consolidation, then sync. Every notification-producing cron job must pass through a **quiet hours gate** first (default 11 PM–8 AM local, held output goes to `/tmp/cron-held/` and is folded into the morning briefing) — travel-aware timezone inference reads calendar flight/hotel events so quiet hours follow the user, not the clock. **Queue operations**: `gbrain doctor`'s `queue_health` check flags `stalled-forever` (active job older than 1h) and `waiting-depth` (per-name queue deeper than 10). A nastier failure mode — the "dead pool" — is a worker process that's alive by `ps`/`kill -0` but whose DB connection died, so it claims nothing while jobs pile up at 0 active; as of v0.42.22.0 this self-heals (the worker self-exits on a dead-pool probe after ~3 minutes and the supervisor respawns it; the supervisor also restarts a worker that makes zero progress for 15 minutes despite claimable work). ## Key Parameters - `--concurrency N`, `--nice N` (POSIX -20 to 19) on `gbrain jobs supervisor`. - `lockDuration` 30s default, `max_stalled` 5 (schema default, tune per-job via `--max-stalled`), `stalledInterval` 30s. - `GBRAIN_ALLOW_SHELL_JOBS=1` — required on the worker for shell jobs; MCP callers are always refused regardless. - `inherit:` free-form config-key list (e.g. `database_url` → `GBRAIN_DATABASE_URL`); `redact_secrets: true` for output-side scrubbing. - Quiet hours default `QUIET_START=23`, `QUIET_END=8`; configurable, `enabled: false` disables entirely. - `GBRAIN_QUEUE_WAITING_THRESHOLD` overrides the default waiting-depth-10 alarm. - `--wedge-restart-minutes` / `--wedge-restart-checks` tune the dead-pool auto-restart (0 disables). ## When To Use Deploy `gbrain jobs supervisor` (not a bare `gbrain jobs work`) for any production brain that runs unattended crons. Use shell jobs to move deterministic, non-reasoning scripts off the LLM gateway. Use the quiet-hours gate on every job that can produce a user-facing notification. Reach for the queue-operations runbook the moment `gbrain doctor` or `gbrain jobs stats` reports a wedged or stalled queue. ## Risks & Pitfalls - Running `gbrain jobs work` bare in production with no supervisor: a crash leaves submitted jobs sitting in `waiting` forever with no auto-recovery. - Writing a secret directly into a shell job's `env:` (pre-v0.36.5.0 pattern) plants plaintext in the job row and the audit JSONL — use `inherit:` instead. - `redact_secrets` is a literal string-replace heuristic — it won't catch a base64-encoded or character-split secret; it defends against accidental echo, not exfiltration. - Skipping the quiet-hours gate on even one notification cron risks a 3 AM ping that gets the whole system disabled by the user. - `DO NOT` pass `maxStalledCount` to `MinionWorker` — it's a no-op; the stall detector reads the job row's `max_stalled` column set at submit time. - On PGLite, forgetting `--follow` on a crontab shell-job invocation means the job never runs (no persistent worker is possible). ## Related Concepts [[concepts/ingestion-pipeline]], [[concepts/operations-and-cost]], [[concepts/mcp-integration]] ## Sources raw/github_doc-docs-guides-minions-deployment-md.md, raw/github_doc-docs-guides-minions-shell-jobs-md.md, raw/github_doc-docs-guides-minions-fix-md.md, raw/github_doc-docs-guides-cron-schedule-md.md, raw/github_doc-docs-guides-quiet-hours-md.md, raw/github_doc-docs-guides-queue-operations-runbook-md.md --- title: "Operations and Cost" type: concept tags: [operations, operator, foundational, well-established] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-operations-spend-controls-md.md", "raw/github_doc-docs-guardrails-md.md", "raw/github_doc-docs-storage-tiering-md.md", "raw/github_doc-docs-embedding-migrations-md.md", "raw/github_doc-docs-guides-rls-and-you-md.md", "raw/github_doc-docs-incidents-2026-05-20-lsd-cost-explosion-md.md", "raw/github_doc-docs-guides-operational-disciplines-md.md"] confidence: high gbrain_version: "0.42.56.0" --- ## Definition Running gbrain responsibly means treating spend, security exposure, and disk footprint as first-class operational surfaces rather than defaults you hope stay reasonable: embedding-spend gates, content-guardrail seams, storage tiering, embedding-dimension migrations, Row Level Security, and the daily/nightly operational disciplines that keep a brain from silently rotting or silently draining a budget. ## How It Works **Spend controls** are organized under one master switch, `spend.posture`: `gated` (default) enforces every cost gate; `tokenmax` makes every gate informational (spend is still recorded to a ledger, only the ceiling is removed). An explicit per-call cap (`--max-usd N`) always wins over posture. The gates themselves: the sync inline-embed cost gate (`sync.cost_gate_min_usd`, default `$0.50`, prompts on TTY, auto-defers to capped backfill jobs on non-TTY so a cron never wedges), the backfill 24h per-source spend cap (`embed.backfill_max_usd_per_source_24h`, default `$25`), the backfill per-job budget (`embed.backfill_max_usd`, default `$10`), and per-call caps on `enrich`/`onboard --auto`. All USD-limit knobs accept `off` / `unlimited` / `none` to mean no limit — `0` is a real, distinct choice (block on any nonzero spend), not "off." **Guardrails** are vendor-neutral, observe-only seams at five boundaries (`file_storage.markdown`, `file_storage.code`, `ai_gateway.chat`, `ai_gateway.expand`, `ai_gateway.tool_input`) where an operator can register an external classifier (content firewall, prompt-injection detector, PII scrubber). The OSS distribution ships inert — zero guardrails registered by default. Hard invariants: `runGuardrails()` returns void so no provider verdict can ever block, rewrite, or reorder gbrain behavior; failures (timeout, throw, missing config) are swallowed (fail-open); no verdict is persisted by gbrain; and only the ingest/user-facing payload is passed, never system prompts, tool output, or embeddings. **Storage tiering** splits a brain repo into `db_tracked` (version-controlled, human-edited — people/, companies/, deals/) and `db_only` (bulk machine-generated content — media/x/, meetings/transcripts/) directories declared in `gbrain.yml`. `gbrain sync` auto-manages `.gitignore` for `db_only` paths; `gbrain export --restore-only` repopulates missing `db_only` files from the database (useful after a container restart or fresh clone); `gbrain storage status` gives a health dashboard of page counts and disk usage per tier. On PGLite, the "offload to DB" promise is technically vacuous since the DB *is* the local file — full tiering requires migrating to Postgres. **Embedding migrations**: switching to a same-dimension model is automatic as of v0.41.31.0 — gbrain stamps a `:` signature per page, and `gbrain embed --stale` re-embeds only signature-drifted pages (pages embedded pre-v0.41.31.0 carry a NULL signature and are never flagged, so upgrading doesn't trigger a whole-corpus re-embed). A **dimension** change is not automatic: it requires dropping the HNSW index, wiping every existing embedding (pgvector refuses to cast across dimensions), altering the column type (Postgres only — PGLite's WASM pgvector build rejects `ALTER COLUMN TYPE`), and re-embedding the entire corpus. PGLite's path is `gbrain reinit-pglite --embedding-model --embedding-dimensions ` (backs up, re-inits, re-syncs); Postgres uses a documented SQL recipe (`BEGIN; DROP INDEX; UPDATE ... SET embedding = NULL; ALTER COLUMN TYPE vector(N); CREATE INDEX ...; COMMIT;`, skipping the index step above 2000 dims). **RLS ("RLS and you")**: every table in a gbrain's `public` schema must have Row Level Security enabled — `gbrain doctor` fails (exit 1), not warns, if any doesn't. Since v0.26.7 (migration v35), an event trigger (`auto_rls_on_create_table`) auto-enables RLS on every newly created public table, plus a one-time backfill on upgrade. gbrain's service-role connection holds `BYPASSRLS`, so enabling RLS never breaks gbrain itself — it only blocks the anon key's default read, which is the point (Supabase exposes `public` schema tables to the anon key via PostgREST by default). A deliberate exemption requires a `COMMENT ON TABLE ... IS 'GBRAIN:RLS_EXEMPT reason=...'` — no CLI shortcut exists, by design, so opening a table to anon reads is visible in shell history and `pg_dump`. **The LSD cost-explosion incident (2026-05-20)** is the canonical cautionary tale: `gbrain lsd` estimated $0.96 but spent $50.71 (53x over) on a 13,690-page brain because the far-set sampler (`fetchFar()`) returned one page per unique directory prefix (~2,000) instead of respecting the configured `m=12`, producing 15,868 ideas instead of ~96 and blowing the judge's context window 5.5x over. Root causes: no cap on far-set cardinality, no cost circuit breaker, unbounded judge context, and unpaired UTF-16 surrogates crashing JSON serialization. The fix wave (P1-P7, shipped in v0.37.x) added a far-set cap (`max(m*4, 50)`), `--max-cost`/`--strict-budget`/`--max-far-set` flags, judge chunking at 100 ideas/call, Unicode sanitization at the serialization boundary, a gateway-layer `BudgetTracker` (`AsyncLocalStorage`-scoped, throws `BudgetExhausted` on overrun), and checkpoint/`--resume` support. The generalized lesson: **every LLM-calling function needs a budget**, and cost estimators must account for actual data cardinality, not just the parameters a user configured. **Operational disciplines** are five non-negotiable rules for a production brain: (1) signal detection on every inbound message, (2) brain-first lookup before reaching for external APIs, (3) `gbrain sync` after every write, (4) a daily `gbrain doctor` heartbeat, (5) the nightly dream cycle (entity sweep, citation audit, memory consolidation, sync). See [[concepts/ingestion-pipeline]] and [[concepts/minions-orchestration]] for the mechanics of each. ## Key Parameters - `spend.posture`: `gated` (default) | `tokenmax`. - `sync.cost_gate_min_usd` default `$0.50`; `embed.backfill_max_usd_per_source_24h` default `$25`; `embed.backfill_max_usd` default `$10`; `embed.backfill_cooldown_min` default `10`. - `GBRAIN:RLS_EXEMPT reason=...` — the only sanctioned RLS-exemption mechanism. - `--max-cost`, `--strict-budget`, `--max-far-set` on `brainstorm`/`lsd` post-incident. ## When To Use Apply spend gates and budgets to any command that makes a variable number of LLM calls scaled to brain size (`brainstorm`, `lsd`, `dream`, `enrich`, `extract all`). Use storage tiering once a brain repo crosses tens of thousands of files. Run the embedding-migration recipe only when deliberately switching models/dimensions — it's an expensive, non-automatic operation by design. Treat RLS failures in `gbrain doctor` as blocking, not advisory. ## Risks & Pitfalls - Assuming a cost estimator based on configured parameters (`m=12`) reflects actual behavior when the underlying data cardinality (2,000 prefixes) diverges — the LSD incident's root cause. - Passing `--yes` to skip a cost preview removes the last manual inspection opportunity before an expensive run. - Forgetting that `gbrain config set embedding_model` is a no-op for the embed pipeline pre-v0.37 — it wrote the DB plane while the embed gateway reads the file plane. - Treating RLS as Supabase-only: gbrain enforces it on self-hosted Postgres too, since the policy is a gbrain invariant, not a PostgREST workaround. - Forgetting the `GBRAIN:RLS_EXEMPT` comment before a v0.26.7 upgrade — the backfill silently flips RLS on for any public table lacking it. ## Related Concepts [[concepts/minions-orchestration]], [[concepts/ingestion-pipeline]], [[concepts/verification-and-quality]] ## Sources raw/github_doc-docs-operations-spend-controls-md.md, raw/github_doc-docs-guardrails-md.md, raw/github_doc-docs-storage-tiering-md.md, raw/github_doc-docs-embedding-migrations-md.md, raw/github_doc-docs-guides-rls-and-you-md.md, raw/github_doc-docs-incidents-2026-05-20-lsd-cost-explosion-md.md, raw/github_doc-docs-guides-operational-disciplines-md.md --- title: "GBrain Overview" type: concept tags: [brains, foundational, user] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-readme-md.md", "raw/github_doc-docs-ethos-thin-harness-fat-skills-md.md", "raw/github_doc-docs-ethos-origin-md.md", "raw/github_doc-docs-ethos-markdown-skills-as-recipes-md.md", "raw/github_doc-docs-guides-compiled-truth-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition GBrain (github.com/garrytan/gbrain) is Garry Tan's opinionated, self-hosted "brain layer" for AI agents: a compiled personal or company knowledge runtime that sits on top of a markdown brain repo and a Postgres/PGLite database. Where a typical personal-knowledge tool gives you back a list of matching pages, GBrain gives you back an actual synthesized answer with citations and an explicit note on what it doesn't know yet — the tagline is "Search gives you raw pages. GBrain gives you the answer." It is the production brain behind Tan's own OpenClaw and Hermes deployments (146,646 pages, 24,585 people, 5,339 companies, 66 autonomous cron jobs at time of writing). ## How It Works GBrain's engineering ethos comes from Tan's "thin harness, fat skills" thesis: intelligence should live in fat, markdown-encoded skills; the harness running the model should stay thin (read/write files, manage context, enforce safety — nothing more); and deterministic work (SQL, code, numbers) should be pushed down into code rather than left to the model's judgment. A **skill file** is a reusable markdown procedure — a method call that takes parameters and encodes judgment, not a hardcoded script. A **resolver** is a routing table that tells the model what to load when, so the harness doesn't need every capability loaded into context on every turn. See [[concepts/skillpacks-and-skills]] for how this plays out in GBrain's 43 bundled skills. The companion idea, "markdown is code," treats a skill file as documentation, specification, package, and source code all at once — a distribution mechanism where an agent reads a recipe (architecture, routing logic, integration points, judgment calls, failure modes) and builds a native implementation tailored to the user's setup, rather than installing someone else's binary. Underneath the skills sits GBrain's data model: the **compiled truth + timeline pattern**. Every brain page has two zones separated by a horizontal rule. Above the line is compiled truth — a current synthesis that gets REWRITTEN as new evidence arrives. Below the line is the timeline — an append-only, never-edited evidence trail. Every compiled-truth claim must trace back to timeline entries with citations. This is the mechanism behind GBrain's "compiled truth" idea: unlike RAG, which re-derives an answer from raw chunks on every query, GBrain pre-computes the synthesis once and keeps it current, so `gbrain think` can return a paragraph instead of ten links. ## Key Parameters - **Two query surfaces**: `gbrain search` (raw retrieval — top pages by hybrid score, fast, no LLM cost) vs `gbrain think` (synthesis — composes a cited answer plus gap analysis). See [[concepts/retrieval-and-search]]. - **Two engines, one contract**: PGLite (zero-config, WASM, personal brains up to ~50K pages) or Postgres + pgvector (shared/large deployments) — both implement the same `BrainEngine` interface. - **Brain repo is the system of record**: the git repo of markdown files is canonical; the database is a derived, rebuildable cache. See [[concepts/brains-and-sources]]. - **Self-wiring knowledge graph**: every page write extracts entity references and creates typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`) with zero LLM calls — this graph produces a benchmarked +31.4 point P@5 lift over vector-only RAG (BrainBench: P@5 49.1%, R@5 97.9%). - **The loop**: signal → search → respond → write → auto-link → sync. A signal detector runs on every message; brain-first lookup happens before any external API call; auto-link fires on every write; cron-driven enrichment runs overnight. ## When To Use GBrain is aimed at anyone who wants an AI agent that doesn't forget people, companies, decisions, and ideas between sessions — individuals running a personal agent (OpenClaw, Hermes) or wiring a coding agent (Claude Code, Codex) up with a persistent memory layer via MCP, and now also teams wanting a shared, access-scoped "company brain." It's the right fit when the value is in accumulating and re-synthesizing knowledge over months, not for one-off note storage. ## Risks & Pitfalls - **Context bloat is the enemy.** Tan's own confession: his CLAUDE.md grew to 20,000 lines before being cut back to ~200 lines of pointers — the resolver pattern exists specifically to avoid drowning the model in irrelevant context. - **A fat harness with thin skills is the anti-pattern.** Loading 40+ tool definitions or wrapping every REST endpoint as an MCP tool multiplies tokens, latency, and failure rate; GBrain's design deliberately pushes intelligence into markdown skills and keeps the harness (~200 lines) minimal. - **Compiled truth must stay honest.** Every claim above the line needs a timeline entry behind it, or the synthesis becomes unverifiable prose — see [[concepts/verification-and-quality]] for the citation discipline this depends on. ## Related Concepts - [[concepts/skillpacks-and-skills]] — the fat-skills half of the architecture - [[concepts/brains-and-sources]] — the system-of-record and database model - [[concepts/retrieval-and-search]] — how `search` and `think` differ - [[concepts/ingestion-pipeline]] — how signal becomes brain pages - [[syntheses/brain-vs-memory]] — how GBrain relates to other memory layers ## Sources README.md; docs/ethos/THIN_HARNESS_FAT_SKILLS.md; docs/ethos/ORIGIN.md; docs/ethos/MARKDOWN_SKILLS_AS_RECIPES.md; docs/guides/compiled-truth.md. (docs/DESIGN.md was reviewed but dropped — it's a UI style guide for the admin SPA, not relevant to what gbrain is.) --- title: "Retrieval and Search" type: concept tags: [retrieval, foundational, user] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-architecture-retrieval-md.md", "raw/github_doc-docs-guides-search-modes-md.md", "raw/github_doc-docs-architecture-lens-packs-md.md", "raw/github_doc-docs-guides-brain-first-lookup-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition GBrain's retrieval stack answers "does vector search alone work for a personal knowledge base?" with no, and layers four strategies together: vector similarity (HNSW on pgvector), BM25 keyword matching, reciprocal-rank fusion (RRF) to merge the two without weighting either globally, and knowledge-graph traversal over typed edges. On GBrain's BrainBench (a 240-page corpus), the full stack scores P@5 49.1% / R@5 97.9%, a **+31.4 point P@5 lift** over the graph-disabled hybrid variant and over vector-only RAG — the graph is described as "the load-bearing wall," not a marginal feature. ## How It Works **Why each strategy alone fails**: vector-only misses factual relationships not directly encoded in the embedding ("companies in Garry's portfolio" returns essays about portfolios, not company pages); keyword-only is brittle to phrasing/synonyms; graph-only is blind to anything not yet linked, so it's sparse on fresh pages. **Auto-link (zero LLM calls)**: every `put_page` runs `extractEntityRefs` against three regex families — standard markdown links, Obsidian wikilinks, and typed-link blockquotes — and writes edges via a single batched SQL upsert. Heuristic link-type inference (`attended`, `works_at`, `invested_in`, `founded`, `advises`) fires from surrounding sentence context, also without an LLM call. On a 17K-page brain, a full graph extract completes in seconds. **Reranking**: ZeroEntropy's `zerank-2` is the default cross-encoder reranker (on for `balanced` mode); on a 20-query benchmark it reshuffles 60% of top-1 results after the hybrid+RRF+graph stack, at a cost of +150ms p50 and ~$0.025/M tokens. Disable with `gbrain config set search.reranker.enabled false`. **Source-aware ranking**: a SQL-layer boost/demote table favors curated content (`originals/`, `concepts/`, `writing/`) over bulk content (chat logs, daily notes, social media); `archive/` is deliberately demoted (0.5x) rather than hard-excluded — high-signal historical pages can still surface, and a strong reranker match can still promote an archived page back up. Hard-excluded prefixes (`test/`, `attachments/`, `.raw/`) are filtered at retrieval, before ranking. **Named-thing retrieval**: four layers added after a documented incident where vector search under-surfaced pages organized around chosen proper names. Per-page max-pool (`DISTINCT ON (slug)`, best chunk per page) ensures N distinct pages surface rather than N chunks collapsing to fewer pages; a title-phrase boost fires when the query is a contiguous run inside the page title; an alias hop bridges free-text `aliases:` frontmatter to true synonyms with zero surface overlap; and every result carries an `evidence` tag (`alias_hit | exact_title_match | high_vector_match | keyword_exact | weak_semantic`) plus a `create_safety` hint (`exists | probable | unknown`) so an agent can decide whether to write a duplicate page. **Intent-aware rewriting**: queries classify deterministically (no LLM) into `entity`, `temporal`, `event`, or `general`, each routing through different ranking knobs — entity queries weight graph traversal higher, temporal queries bypass the source boost so chat/daily pages resurface, event queries engage the timeline index. **Multi-query expansion**: for `detail: 'high'` searches, a Haiku-class call produces 2-3 query variants merged via RRF, catching synonym misses; it's opt-in per mode bundle (on for `tokenmax`, off for `balanced`/`conservative`). **Two query surfaces**: `gbrain search "term"` (keyword, fast, no embeddings needed, returns chunks) and `gbrain query "question"` (hybrid vector+keyword+RRF, needs embeddings, also returns chunks). Both need a follow-up `gbrain get ` to load a confirmed-relevant chunk's full page. `gbrain get ` is the third mode — direct, instant, no search overhead — when the slug is already known. Progression is expected to run keyword (day one) → hybrid (once embeddings exist) → direct get (once slugs are known). **Brain-first lookup protocol** is the mandatory sequencing rule: try keyword search, then hybrid search, then a guessed direct slug, and only fall back to an external API (Brave Search, etc.) if the brain genuinely has nothing. The brain has context — relationship history, the user's own assessments, meeting transcripts, cross-references — that no external API can provide; skipping this order wastes money and returns worse answers even for "simple" lookups, since brain-first adds under 100ms. **Lens packs (v0.41.2.0)** stack additional schema-pack-driven dream-cycle phases on top of `gbrain-base`: `gbrain-creator` (atom extraction + concept synthesis from transcripts), `gbrain-investor` (thesis + bet-resolution tracking with Brier-scored calibration), `gbrain-engineer` (bridges `gstack` learnings into the brain), and `gbrain-everything` (a meta-pack stacking all three via `extends`+`borrow_from`). Each declares calibration domains scored by one of four closed aggregator algorithms (`scalar_brier`, `weighted_brier`, `count_based`, `cluster_summary`). ## Key Parameters - Named search modes bundle cost/quality knobs into one config key: `conservative`, `balanced` (default, reranker on), `tokenmax` (expansion on). See [[concepts/operations-and-cost]]. - `SearchOpts.exclude_slug_prefixes` / `GBRAIN_SOURCE_BOOST` env — tune the source-boost map. - `search.reranker.enabled` — toggle ZeroEntropy reranking. - `evidence` and `create_safety` fields on every search result. ## When To Use Use `gbrain search` for raw material to skim — citation lookups, finding a quote, agent context windows, known exact names. Use `gbrain query`/`gbrain think` for semantic or fuzzy questions where you want ranked relevance across vector+keyword+graph. Use `gbrain get ` the moment a slug is known, to skip search overhead entirely. Run `gbrain search "" --explain` or `gbrain search diagnose "" --target ` when a retrieval result looks wrong and you need per-stage attribution. ## Risks & Pitfalls - Don't run hybrid search (`gbrain query`) for a known exact name — it wastes embedding compute; use keyword search or a direct get instead. - Hybrid search silently returns nothing (while keyword search works) if embeddings haven't been generated yet — that's a signal to run the embedding pipeline, not that search is broken. - Search returns chunks, not full pages — answering from a chunk alone when full context matters is a common shortcut failure; always `gbrain get` the full page once relevance is confirmed. - Cross-pack federation (mounted brains with divergent active schema packs) can reject queries with `permission_denied` — a known, deferred gap, not a bug to chase. ## Related Concepts - [[concepts/schema-packs]] — `expert_routing`/`extractable` flags that retrieval consults - [[concepts/operations-and-cost]] — the search-mode cost matrix - [[concepts/overview]] — `search` vs `think` and the synthesis layer above raw retrieval - [[concepts/brains-and-sources]] — federation and source scoping that retrieval respects ## Sources docs/architecture/RETRIEVAL.md; docs/guides/search-modes.md; docs/architecture/lens-packs.md; docs/guides/brain-first-lookup.md. --- title: "Schema Packs" type: concept tags: [schema, foundational, operator] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-architecture-schema-packs-md.md", "raw/github_doc-docs-gbrain-recommended-schema-md.md", "raw/github_doc-docs-what-schemas-unlock-md.md", "raw/github_doc-docs-architecture-type-taxonomy-md.md", "raw/github_doc-docs-schema-author-tutorial-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition A **schema pack** is the artifact that tells GBrain what shape a brain takes: which directories exist, what page types live in them, how to infer a type from a file path, and which link verbs connect what to what. It's the single, dynamically-consulted source of truth for "what's in your brain" — every read and write path checks it. Without typed pages, GBrain is a pile of notes with text search; with a schema pack, `whoknows`/`find_experts` can route by expertise, `extract_facts` can pull typed claims, and `graph-query` can traverse typed edges. ## How It Works **Bundled packs**: `gbrain-base` (legacy, ~22-24 types, byte-for-byte pre-v0.38 behavior) and, as of v0.41.22, the default `gbrain-base-v2` — a 14-canonical-type DRY/MECE taxonomy plus a `note` catch-all (`person`, `company`, `media`, `tweet`, `social-digest`, `analysis`, `atom`, `concept`, `source`, `deal`, `email`, `slack`, `writing`, `project`, `note`). This taxonomy was a direct response to issue #1479, where a 186K-page production brain had accreted 94 distinct `pages.type` values across 9 redundant clusters, degrading search filtering, enrichment routing, and agent filing decisions. Subtypes (e.g. `media.subtype` = video/article/essay/book/podcast/blog) live in frontmatter rather than inflating the type count. `gbrain-recommended` extends `gbrain-base` with 13 additional directories from `docs/GBRAIN_RECOMMENDED_SCHEMA.md` (source, place, trip, conversation, personal, civic, project, etc.) — activate with `gbrain schema use gbrain-recommended`. **Resolution chain (7 tiers, first match wins)**: per-call `schema_pack` opt (CLI only) → `GBRAIN_SCHEMA_PACK` env → per-source DB config key → brain-wide DB config key → `gbrain.yml` `schema:` section → `~/.gbrain/config.json` `schema_pack` field → default `gbrain-base`. **CLI surface**: inspection verbs `gbrain schema active` / `list` / `show` / `validate` / `use `; authoring + discovery verbs `gbrain schema detect` (heuristic clustering on your actual filesystem shape), `suggest` (LLM-refined proposals), `review-candidates` (human-gated promotion), `review-orphans`, `init `, `fork `, `edit`, `diff`, `graph`, `lint` (flags duplicates + missing prefixes), `explain `, `downgrade --to

` (recovery), `usage --since 30d`. **Migrating an existing brain to the new taxonomy**: `gbrain onboard --check --explain` gives a per-cluster narrative dry-run, then `gbrain jobs submit unify-types --allow-protected --params '{"target_pack":"gbrain-base-v2"}'` runs an 8-phase job (preflight+lock → retype explicit rules → retype catch-all to `note` with `legacy_type` preserved → page-to-link conversions → page-to-alias conversions → residual path-prefix typing → flip active pack → verify). Every retype preserves `frontmatter.legacy_type` so a single SQL UPDATE can roll it back; page-to-link/alias conversions soft-delete the source page with a 72-hour `gbrain pages restore` window. **Authoring your own pack**: `gbrain schema init my-pack` scaffolds `~/.gbrain/schema-packs/my-pack/pack.yaml`; edit it, `gbrain schema validate my-pack`, `gbrain schema use my-pack`, `gbrain schema active` to confirm. A minimal pack declares `api_version: gbrain-schema-pack-v1`, `extends: gbrain-base`, and a `page_types` list where each entry has `name`, `primitive`, `path_prefixes`, `extractable`, `expert_routing`. **The 5-minute tutorial flow** (`docs/schema-author-tutorial.md`): `gbrain schema fork gbrain-base mine` → `gbrain schema use mine` → `gbrain schema add-type researcher --primitive entity --prefix people/researchers/ --extractable --expert` → drop a few placeholder pages under `people/researchers/` and `gbrain sync` → `gbrain schema stats --json` shows them as `untyped_pages` → `gbrain schema sync --json` (dry-run) then `gbrain schema sync --apply` backfills `page.type` in chunked batches → `gbrain whoknows "machine learning"` now surfaces the researcher pages because `whoknows` reads `expert_routing: true` types from the active pack instead of a pre-v0.40.7.0 hardcoded `['person', 'company']` filter. ## Key Parameters - `primitive` — the structural kind (`entity`, `temporal`, `media`, `concept`, `annotation`). - `extractable: true` — page type is eligible for `extract_facts`. - `expert_routing: true` — page type surfaces in `whoknows`/`find_experts`. - `path_prefixes` — directory prefixes that map to this type at parse time. - `mutation_from` / `migration_from` — how a successor pack declares upgrade compatibility. - Decision rule for evolving a schema (`skills/conventions/schema-evolution.md`): <20 pages → don't pack-codify; 20-100 → alias onto an existing type; 100+ → first-class type. ## When To Use Reach for a custom schema pack once a corpus has real structural repetition the default catch-all obscures — 4,000 meetings typed as generic `note`, a founder's leads/investors/portcos/deals, a research brain's researchers/papers/grants, a legal brain's cases/motions/depositions. The signal is `gbrain schema review-orphans` showing many untyped pages sharing an obvious prefix, or a `whoknows` query returning noisy generic-type results instead of expert-routed ones. ## Risks & Pitfalls - **Untyped content is invisible content.** A page typed as the `note` catch-all is text-searchable but invisible to expert routing, fact extraction, and link inference — adding a type is structural promotion, not cosmetic. - Cross-pack search across federated sources with divergent active packs currently rejects with `permission_denied` (deferred to v0.40+ per-source closure work) — don't assume mounted brains with different packs compose silently. - `extends` chain semver compatibility isn't checked yet; a forked pack can silently drift from its parent. - A code revert of a schema-pack-cathedral PR is not sufficient recovery on its own — `gbrain schema downgrade --to gbrain-base` must also restore the config, and typed pages with no matching type in the restored pack may need `gbrain pages purge-deleted`. ## Related Concepts - [[concepts/brains-and-sources]] — the source a schema pack governs - [[concepts/retrieval-and-search]] — how `expert_routing` and `extractable` feed search - [[concepts/skillpacks-and-skills]] — the schema-author skill that automates detect→suggest→apply - [[entities/recipes-catalog]] — how bundled recipes interact with a brain's active pack ## Sources docs/architecture/schema-packs.md; docs/GBRAIN_RECOMMENDED_SCHEMA.md; docs/what-schemas-unlock.md; docs/architecture/type-taxonomy.md; docs/schema-author-tutorial.md. --- title: "Skillpacks and Skills" type: concept tags: [skillpacks, foundational, developer] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-gbrain-skillpack-md.md", "raw/github_doc-docs-skillpack-anatomy-md.md", "raw/github_doc-docs-guides-skillpacks-as-scaffolding-md.md", "raw/github_doc-docs-guides-skill-development-md.md", "raw/github_doc-docs-guides-skillopt-md.md", "raw/github_doc-docs-guides-scaling-skills-md.md"] confidence: high gbrain_version: 0.42.56.0 --- ## Definition A **skill** is a markdown procedure (`SKILL.md`) that teaches an agent how to do something — the operational unit of GBrain's "fat skills" philosophy (see [[concepts/overview]]). A **skillpack** is a distributable bundle of skills plus tests, evals, and a manifest; GBrain ships 40+ curated skills as its own reference bundle (`docs/GBRAIN_SKILLPACK.md`), covering signal capture, ingestion, enrichment, querying, brain ops, citation fixing, and cron scheduling. ## How It Works **Skillpacks are scaffolding, not amber (v0.33+).** Pre-v0.33, `gbrain skillpack install` copied skills into a workspace and wrote a managed-block fence into `RESOLVER.md`/`AGENTS.md`, hash-checking every file on subsequent installs. That model is retired. The current five-command model treats skills as first-class code the user owns and forks freely: - `gbrain skillpack scaffold ` — one-time additive copy into the workspace; refuses to overwrite existing files; `scaffold --all` copies every missing bundled skill. - `gbrain skillpack reference ` — read-only diff of gbrain's bundle vs. the local copy (`identical`/`differs`/`missing`); `--apply-clean-hunks` auto-applies hunks whose context matches uniquely. - `gbrain skillpack migrate-fence` — one-shot conversion for pre-v0.33 workspaces; strips the managed-block markers, preserves every fenced row verbatim. - `gbrain skillpack scrub-legacy-fence-rows` — opt-in cleanup once frontmatter-based routing is confirmed working. - `gbrain skillpack harvest --from ` — lifts a proven skill back into gbrain so others can scaffold it; runs a privacy linter against known-sensitive patterns before landing anything. `install`/`uninstall` are removed entirely in v0.33 with no deprecated alias. **Discovery is frontmatter-based, not a hand-maintained table.** Each `SKILL.md` declares a `triggers:` array; the agent walks `skills/*/SKILL.md` at startup, builds an in-memory routing table from triggers, and matches user intent against it. **Anatomy of a third-party skillpack** (`examples/skillpack-reference/`): `skillpack.json` manifest, `skills//SKILL.md` + `routing-eval.jsonl` (≥5 pinned trigger→skill intents), `runbooks/bootstrap.md` (displayed once after scaffold, never auto-executed — auto-walking a bootstrap runbook is exactly the npm-postinstall attack shape GBrain avoids by design), unit tests, e2e tests, LLM-judge eval configs, `CHANGELOG.md`, `LICENSE`. `gbrain skillpack doctor . --quick` scores a pack on 10 binary dimensions — 5 core (must all pass to publish at any tier: valid manifest, every skill has a well-formed `SKILL.md`, routing evals present, unique triggers across the pack, current changelog) and 5 quality badges (unit tests, e2e tests, LLM eval, bootstrap runbook, license) that determine tier: `endorsed` (all 10 + Garry's endorsement), `community` (5 core + ≥3 badges, default on PR merge), `experimental` (5 core + <3 badges), `blocked` (any core check fails). **The 5-step skill development cycle**: (1) concept the process in plain language; (2) run it manually on 3-10 real items — no `SKILL.md` yet; (3) show the user the output, get feedback, revise; (4) codify into a skill — new skill or a parameterized addition to an existing one, kept MECE (no two skills own the same entity-type/signal-source combination, or they'll produce duplicate/conflicting brain pages); (5) put it on a cron if it recurs, and monitor the first few automated runs. The governing rule: "if you have to ask twice, it should already be a skill running on a cron." **`gbrain skillopt`** treats a `SKILL.md` as a trainable parameter of an agent that itself never changes. Workflow: `gbrain skillopt my-skill --bootstrap-from-skill` generates a starter benchmark (≤50 tasks) directly from the skill; a human strengthens the generated judges and deletes the `# BOOTSTRAP_PENDING_REVIEW` sentinel line; `gbrain skillopt my-skill --bootstrap-reviewed --split 1:1:1` runs the optimizer. Internally: forward pass (run candidate against `D_train`) → backward pass (two reflect calls proposing edits) → rank+clip within an LR budget → apply as tagged-result patches (frontmatter mutation is forbidden) → validation gate (median-of-3 judge runs, only accepts if the median beats best by >0.05) → atomic commit. A typical 20-task run costs roughly $0.71-$0.90; safety guards include a bundled-skill gate (mutating a gbrain-shipped skill in place requires `--allow-mutate-bundled` plus a `--held-out` set of ≥5 disjoint tasks or it hard-refuses) and a read-only tool sandbox during optimization rollouts. **Scaling past ~100 skills** needs tiering, or the system prompt starts eating tokens on skill descriptions the model doesn't need that turn. Three tiers: Tier A (~35 skills, always loaded natively in ``), Tier B (~85 skills, resolver-routed — real skills that fire regularly but live only in `RESOLVER.md`'s compact list, not the prompt), Tier C (~180 skills, `enabled: false`, dormant until flipped on). On a production 306-skill OpenClaw this cut skill-description tokens from ~25,000/turn to ~4,000/turn with zero capability loss. The compact list format (`- **skill-name**: trigger | trigger | trigger`, v0.41.7.0) replaced the markdown-table-only resolver format once tables became unreadable past ~200 entries; `gbrain doctor` and `gbrain check-resolvable --json/--strict` sweep every skill on disk and flag any that are unreachable by either native scanning or the resolver. ## Key Parameters - `triggers:` frontmatter array — how a skill is discovered. - `sources:` frontmatter array — paired non-markdown source files a skill scaffold copies alongside it. - Skillpack doctor's 5 core + 5 badge dimensions — gate for publish tier. - SkillOpt flags: `--epochs`, `--batch-size`, `--lr`, `--split TRAIN:SEL:TEST`, `--max-cost-usd` (default $5.00 hard cap), `--held-out`. - Tiering thresholds: ~35 (Tier A ceiling before drag), ~100 (drag begins), ~200 (routing accuracy visibly drops), 300+ (tiering becomes mandatory). ## When To Use Scaffold a skill the first time a task needs to run again ("the test: if I have to ask you for something twice, you failed"). Use `skillopt` once a skill has a real benchmark and you want measurable, judge-gated improvement rather than vibes-based prompt tweaking. Start tiering skills once routing feels fuzzy or session startup drags — usually somewhere past 100-200 skills. ## Risks & Pitfalls - **MECE violations compound silently**: two skills creating pages in the same directory produce duplicate or conflicting brain content before anyone notices. - **Stubs are not skills**: a `SKILL.md` with "TODO: implement" should not exist — keep it manual work until it can be finished end-to-end. - **Auto-applying a `bootstrap.md` runbook** or auto-walking a scaffolded pack's setup steps is the exact supply-chain risk the "display but don't execute" rule exists to prevent. - **Invisible skill loss during tiering**: disabling native scanning for a skill without adding a resolver entry makes a capability silently unreachable; run `gbrain doctor` after every tiering change. - SkillOpt on write-heavy skills (`put_page`-flavored) isn't supported by the v1 read-only sandbox yet. ## Related Concepts - [[concepts/overview]] — the thin-harness-fat-skills thesis this pattern implements - [[concepts/schema-packs]] — the schema-author skill that co-curates a brain's ontology - [[entities/skills-catalog]] — the concrete bundled skills and their groupings - [[concepts/ingestion-pipeline]] — orchestration skills that call enrichment on every signal ## Sources docs/GBRAIN_SKILLPACK.md; docs/skillpack-anatomy.md; docs/guides/skillpacks-as-scaffolding.md; docs/guides/skill-development.md; docs/guides/skillopt.md; docs/guides/scaling-skills.md. --- title: "Verification and Quality" type: concept tags: [eval, operator, developer, foundational, well-established] created: 2026-07-02 updated: 2026-07-02 sources: ["raw/github_doc-docs-gbrain-verify-md.md", "raw/github_doc-docs-contradictions-md.md", "raw/github_doc-docs-takes-vs-facts-md.md", "raw/github_doc-docs-architecture-calibration-quality-gate-spec-md.md", "raw/github_doc-docs-eval-bench-md.md", "raw/github_doc-docs-eval-capture-md.md", "raw/github_doc-docs-eval-takes-quality-md.md"] confidence: high gbrain_version: "0.42.56.0" --- ## Definition Verification and quality is the set of runbooks and eval instruments gbrain ships to answer "is this brain actually working, and is what it knows actually true?" — spanning post-install verification, contradiction detection, the epistemological split between takes and facts, a falsifiability quality gate on extracted claims, and a full eval-bench/capture/replay loop for anyone changing retrieval. ## How It Works **Installation verification** (`GBRAIN_VERIFY.md`) is an 8-check runbook run after install: schema (`gbrain doctor --json`), skillpack loaded, auto-update configured, live sync (the most important check — "sync ran" ≠ "sync worked"; verified by comparing DB page count to syncable file count, then an end-to-end edit→push→search round-trip), embedding coverage, brain-first lookup, knowledge-graph wiring (`links`/`timeline_entries` non-zero, backfilled via `gbrain extract links`/`extract timeline`), and JSONB frontmatter integrity (`gbrain repair-jsonb --dry-run --json`, expecting `totalRepaired: 0`). **Contradiction detection** (`gbrain eval suspected-contradictions`, v0.32.6) samples retrieval results, asks an LLM judge whether any pair of chunks contradicts on a factual claim, and aggregates into a report with a Wilson 95% confidence interval on the headline rate. This measures what compiled-truth-plus-timeline and source-boost/recency-decay ranking *don't* catch: unmarked semantic contradictions that actually surface in retrieval. Findings carry a severity rubric (`low` naming differences, `medium` possibly-stale factual values, `high` identity/structural claims) and a paste-ready `resolution_command` (`gbrain takes supersede`, `gbrain dream --phase synthesize`, `gbrain takes mark-debate`, or manual review). Decision policy on the Wilson CI lower bound: below 5% the existing mechanisms are enough; 5-15% is an operator judgment call; above 15% justifies a bigger architectural swing. The probe never mutates the brain — it only writes to its own `eval_contradictions_runs`/`_cache` tables. A later temporal-aware upgrade (v0.35.3.1/v0.35.7) added a six-member verdict enum (including `temporal_supersession`/`temporal_evolution`) so legitimate change-over-time stops being flagged as a false contradiction. **Takes vs facts** is a hard architectural boundary never to conflate: *takes* (cold storage, `takes` table) are the epistemological layer — who believes what, multi-holder, extracted from brain pages by LLM analysis, kinds `take`/`fact`/`bet`/`hunch`; *facts* (hot memory, `facts` table, v0.31) are single-user, real-time, per-turn conversation capture (kinds `event`/`preference`/`commitment`/`belief`/`fact`). The nightly dream cycle's `consolidate` phase is the one-way bridge (hot facts → cold takes), grouping, deduplicating, and promoting durable facts with proper attribution. See [[concepts/ingestion-pipeline]] for the dream cycle mechanics. **The calibration quality gate** addresses noise in the `propose_takes` → `grade_takes` → `calibration_profile` pipeline: in production on a 96K-page brain, only 6.8% of high-weight takes passed a falsifiability filter, and half of those were unresolvable. The fix adds a `falsifiability` (0.0-1.0) and `falsifiability_category` column at extraction time, gates `grade_takes` to `falsifiability >= 0.7 AND category != 'not_prediction'` (cutting grading volume ~93%), adds `pg_trgm`-based near-duplicate detection at extraction, and groups resolved takes by category for per-domain calibration scorecards ("your technology calls are 60% accurate — you tend to be ~18 months early"). **Eval bench** is the human dev loop for anyone touching retrieval (search, ranking, embeddings, intent, expansion, source boost, hybrid fusion). The 4-command loop: capture (`GBRAIN_CONTRIBUTOR_MODE=1`, off by default for privacy), snapshot a baseline (`gbrain eval export --since 7d > baseline.ndjson`), make the code change, replay (`gbrain eval replay --against baseline.ndjson`) — reporting Mean Jaccard@k (≥0.85 healthy), Top-1 stability (≥85% healthy), and latency delta. `gbrain bench publish` + `gbrain eval gate` (v0.41) close the loop into two CI gates: a regression gate (replay against a captured baseline) and a correctness gate (`--qrels`, known-right queries scored via bare `hybridSearch` for CI determinism). `gbrain eval longmemeval` runs the public LongMemEval benchmark end-to-end in a hermetic per-question PGLite. `gbrain eval suspected-contradictions trend --days 30` tracks the contradiction rate over time. **Eval capture** is the underlying NDJSON wire format (`schema_version: 1`) that `gbrain eval export` emits: every row records `tool_name`, PII-scrubbed `query`, `retrieved_slugs`/`retrieved_chunk_ids`, `vector_enabled`, `latency_ms`, `remote`, and more, ordered `created_at DESC, id DESC` for safe windowed exports. Capture is off by default (privacy-positive); `GBRAIN_CONTRIBUTOR_MODE=1` or `eval.capture: true` in `~/.gbrain/config.json` turns it on (explicit config always wins over the env var). **Takes-quality eval** (`gbrain eval takes-quality`, v0.32+) runs a 3-model panel against a 5-dimension rubric (accuracy, attribution, weight calibration, kind classification, signal density) on a sample of takes, aggregating to PASS/FAIL/INCONCLUSIVE with a persisted, schema-versioned receipt (`eval_takes_quality_runs` + disk artifact). `regress --against ` gates CI on a per-dimension-mean drop past a threshold (default 0.5). ## Key Parameters - Wilson CI decision thresholds: <5% no action / 5-15% operator judgment / >15% plan the bigger swing. - Falsifiability grade gate: `falsifiability >= 0.7 AND category != 'not_prediction'`. - Eval-bench health: Mean Jaccard@k ≥ 0.85, Top-1 stability ≥ 85%, latency delta within ±50ms. - `eval.capture` resolution order: explicit config true/false > `GBRAIN_CONTRIBUTOR_MODE` > default off. - Takes-quality verdict: `pass` requires every dimension mean ≥7 AND every dimension min ≥5 across contributing models; `inconclusive` if fewer than 2/3 models contributed complete scores. ## When To Use Run the 8-check verification runbook immediately after any install or migration. Run the contradiction probe on a nightly cadence against top queries once a brain has meaningful curated content. Run eval-bench's replay loop before merging any change touching `src/core/search/`. Use takes-quality `regress` as a CI gate whenever the takes-extraction prompt changes. ## Risks & Pitfalls - Treating "sync ran" as equivalent to "sync worked" — an unreachable direct connection on an IPv4-only host silently skips most pages while reporting success. - Conflating takes and facts — dumping another person's attributed belief into the single-user facts table, or vice versa, is a category error that corrupts both layers. - Acting on a contradiction-probe headline rate when `n < 30` — the `small_sample_note` fires because the Wilson CI is too wide to be actionable at that scale. - Grading takes without the falsifiability filter — 93% of high-weight takes in production were philosophical beliefs, advice, or logistics, not falsifiable predictions, and grading them wastes LLM cost and pollutes calibration profiles. - Forgetting `GBRAIN_CONTRIBUTOR_MODE=1` before trying to capture eval traffic for a baseline — capture is off by default. ## Related Concepts [[concepts/operations-and-cost]], [[concepts/ingestion-pipeline]], [[concepts/mcp-integration]] ## Sources raw/github_doc-docs-gbrain-verify-md.md, raw/github_doc-docs-contradictions-md.md, raw/github_doc-docs-takes-vs-facts-md.md, raw/github_doc-docs-architecture-calibration-quality-gate-spec-md.md, raw/github_doc-docs-eval-bench-md.md, raw/github_doc-docs-eval-capture-md.md, raw/github_doc-docs-eval-takes-quality-md.md --- title: "AI Provider Integrations" type: entity tags: [operations, retrieval, mcp] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-docs-ai-providers-zeroentropy-md.md", "raw/github_doc-docs-ai-providers-llama-server-reranker-md.md", "raw/github_doc-docs-integrations-embedding-providers-md.md", "raw/github_doc-docs-integrations-credential-gateway-md.md", "raw/github_doc-docs-integrations-meeting-webhooks-md.md", "raw/github_doc-docs-integrations-readme-md.md", "raw/github_doc-docs-integrations-reliability-repair-md.md"] confidence: high --- # AI Provider Integrations ## Overview GBrain is a retrieval runtime, not a model vendor: it plugs into a wide set of external AI, credential, and webhook providers through a recipe abstraction, so the same core (chunking, embedding, search, sync) can run against very different vendor stacks. This page catalogs the provider-facing integration surface: embedding providers, the reranker stack (ZeroEntropy hosted + llama-server local), the credential gateway that mediates access to Gmail/Calendar/messaging, meeting/call webhook sources, and the write-time reliability hooks (pre-commit, JSONB repair) that keep provider-fed data honest. ## Characteristics **Embedding providers (16 recipes).** `gbrain providers list` shows the live registry; `gbrain providers explain --json` gives agents a machine-readable capability matrix. Coverage: `openai` (default, 1536d, $0.13/1M), `zeroentropyai` (zembed-1, Matryoshka to 2560/1280/640/320/160/80/40, $0.05/1M), `voyage` (voyage-4 family, 256-2048d, best quality/$, code-tuned `voyage-code-3`), `openrouter` (single key fan-out to dozens of hosted models, embedding + chat), `google` (gemini-embedding-001, 768d default), `azure-openai`, `minimax`, `dashscope`, `zhipu`, `ollama` (local, free), `llama-server` (local, free, user-set dims), `litellm` (universal proxy escape hatch), `together`. `anthropic`/`deepseek`/`groq` are chat-only (no embedding model). As of v0.37, `gbrain init --pglite` auto-detects the provider from whichever API key env var is set; an interactive picker fires if multiple keys are present, and a non-TTY context with no keys exits 1 with a paste-ready hint. **Reranking.** ZeroEntropy's `zerank-2` cross-encoder is the hosted default reranker in `tokenmax` search mode ($0.025/1M tokens, ~$0.0003/query at 30 candidates), opt-in on `conservative`/`balanced` via `gbrain config set search.reranker.enabled true`. `llama-server-reranker` (added v0.40.6.1) is the local/free alternative: point `gbrain` at a self-hosted `llama-server --reranking` instance running Qwen3-Reranker (0.6B/4B/8B) or a self-hosted GGUF conversion of ZE's `zerank-2`/`zerank-1-small` weights. Both speak the same `{results: [{index, relevance_score}]}` wire shape gbrain's `gateway.rerank()` already drives — the recipe is a base-URL override, and any other provider matching that wire shape (not Voyage, which uses `top_k`/`data[]`) can reuse it. Reranking is fail-open by construction across all providers: any error class (auth, network, timeout, payload-too-large) logs to `~/.gbrain/audit/rerank-failures-*.jsonl` and falls back to unmodified RRF order — search reliability beats reranker quality. **Credential gateway.** The agent never holds raw API keys. **ClawVisor** (OpenClaw) is a credential-vaulting/authorization gateway with task-scoped authorization: every request needs a `task_id` from an approved standing task declaring purpose, authorized actions, auto-execute flag, and lifetime. Services: Gmail, Google Calendar, Google Drive, Google Contacts, Apple iMessage, GitHub, Slack. Setup: create an agent in the ClawVisor dashboard, set `CLAWVISOR_URL`/`CLAWVISOR_AGENT_TOKEN`, activate services, create standing tasks with **expansive** purposes (narrow purposes cause the intent-verification model to reject legitimate requests). **Hermes Agent** offers a built-in alternative: multi-platform messaging (Telegram, Discord, Slack, WhatsApp, Signal, Email) plus tool access configured via `config.yaml`, with OAuth for Google services and scheduled automations reusing the same EA workflows through the gateway's tool system. **Meeting and call webhooks.** **Circleback** records meetings, transcribes with speaker diarization, and fires a webhook (`{gateway}/hooks/circleback-meetings`) on completion carrying the full transcript, attendees, notes, action items, and calendar context; signature verification is `HMAC-SHA256` over the body against a signing secret, header `X-Circleback-Signature: sha256=` — unverified webhooks must be rejected. API access uses OAuth dynamic client registration with ~24h access tokens. **Quo (OpenPhone)** provides SMS/call integration: webhooks for `message.received`, `call.completed`, `call.summary.completed`, `call.transcript.completed`; inbound calls over 30s trigger a transcript+summary fetch into a `meetings/` brain page; inbound texts get sender lookup against the brain and a drafted (never auto-sent) reply. Auth is a bare API key in the `Authorization` header, no `Bearer` prefix. **Write-time reliability.** `gbrain frontmatter install-hook` (v0.22.4+) installs a git pre-commit hook validating staged `.md`/`.mdx` frontmatter against eight failure classes (missing `---` delimiters, YAML parse errors, slug mismatch, null bytes, nested quotes, non-string scalar fields, empty frontmatter) — bypass with `git commit --no-verify`. Separately, `gbrain doctor` and `gbrain repair-jsonb` (v0.12.2) detect and fix a historical JSONB double-encoding corruption class that hit real Postgres/Supabase brains (not PGLite) across four columns (`pages.frontmatter`, `raw_data.data`, `ingest_log.pages_updated`, `files.metadata`); the repair is idempotent (`UPDATE ... WHERE jsonb_typeof(col) = 'string'`). **Trust boundary on integration recipes.** Only recipes shipped inside the gbrain package (`recipes/` in a source install or the global install copy) are trusted to run `command`/`http` health checks. Recipes discovered from `$GBRAIN_RECIPES_DIR` or a cwd-local `./recipes/` are untrusted and restricted to `env_exists`/`any_of` checks — an SSRF defense. ## How to Use Smoke-test and switch an embedding provider: ```bash gbrain providers list gbrain providers test --model openai:text-embedding-3-large gbrain init --pglite --model voyage ``` Enable ZeroEntropy embedding + reranker: ```bash export ZEROENTROPY_API_KEY= gbrain config set search.reranker.enabled true gbrain models doctor --json | jq '.probes[] | select(.touchpoint=="reranker_config")' ``` Wire a local llama-server reranker: ```bash ./build/bin/llama-server --model ./models/qwen3-reranker-4b-q4_k_m.gguf --alias qwen3-reranker-4b --reranking --port 8081 gbrain config set search.reranker.model llama-server-reranker:qwen3-reranker-4b gbrain config set search.reranker.enabled true ``` Fix a JSONB corruption after upgrading past v0.12.1: ```bash gbrain doctor gbrain repair-jsonb --dry-run gbrain repair-jsonb ``` Install the frontmatter pre-commit gate on a brain repo: ```bash gbrain frontmatter install-hook ``` ## Related Entities - [[entities/skills-catalog]] — the frontmatter-guard and other skills that share validation logic with the pre-commit hook - [[entities/recipes-catalog]] — self-installing recipes referenced here (credential-gateway, meeting-sync, twilio-voice-brain) - [[concepts/retrieval-and-search]] — how reranking fits into the hybrid search pipeline - [[concepts/ingestion-pipeline]] — the deterministic-collector pattern that meeting/call webhooks and email/calendar recipes rely on - [[concepts/operations-and-cost]] — reranker and embedding cost anchors, budget caps for local rerank - [[syntheses/topology-picker]] — which embedding provider (e.g. `voyage-code-3`) fits a code-brain topology --- title: "Recipes Catalog" type: entity tags: [ingestion, operations, developer] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-recipes-email-to-brain-md.md", "raw/github_doc-recipes-calendar-to-brain-md.md", "raw/github_doc-recipes-x-to-brain-md.md", "raw/github_doc-recipes-meeting-sync-md.md", "raw/github_doc-recipes-twilio-voice-brain-md.md", "raw/github_doc-recipes-agent-voice-md.md", "raw/github_doc-recipes-credential-gateway-md.md", "raw/github_doc-recipes-ngrok-tunnel-md.md", "raw/github_doc-recipes-restart-sweep-md.md", "raw/github_doc-recipes-retrieval-reflex-md.md"] confidence: high --- # Recipes Catalog ## Overview A gbrain recipe is a markdown file with YAML frontmatter (id, version, category, `requires:`, `secrets:`, `health_checks:`, `setup_time`, `cost_estimate`) that the host agent reads and executes as an installer — the recipe body is a step-by-step script the agent walks the user through, validating each credential before moving on. Only recipes shipped inside the gbrain package itself are trusted to run live `command`/`http` health checks (see [[entities/ai-provider-integrations]] for the trust-boundary detail). Recipes fall into three categories: **sense** (data flows into the brain), **infra** (foundational plumbing other recipes depend on), and **reflex** (automated response/behavior, not data ingestion). ## Characteristics ### email-to-brain (v0.7.0, sense, requires credential-gateway) Gmail messages become brain pages. A deterministic Node.js collector (never the LLM) pulls email via ClawVisor or direct Google OAuth, dedupes by message ID, bakes in Gmail deep-links (`https://mail.google.com/mail/u/?authuser=ACCOUNT#inbox/MESSAGE_ID` — the `authuser` param is critical and must be code-generated, never LLM-guessed), and filters noise (`noreply@`, `notifications@`, etc.) deterministically while flagging e-signature requests (DocuSign, HelloSign, PandaDoc). The agent's job is Step 4 onward: read the digest, detect entities, update brain pages, extract action items. Cron every 30 min; enrichment 3x/day. Cost: $0. ### calendar-to-brain (v0.7.0, sense, requires credential-gateway) Google Calendar events become one markdown file per day at `brain/daily/calendar/{YYYY}/{YYYY-MM-DD}.md`. Historical backfill uses monthly chunks for sparse years and weekly chunks for dense years (`dense_after` cutover) to minimize API calls. Attendee filtering strips conference rooms and mailing lists. Daily-file writes only touch the `## Calendar` section, preserving any manually added `## Notes`. Weekly sync cron. Cost: $0. ### x-to-brain (v0.8.1, sense, no dependencies) Twitter/X timeline, mentions, and keyword searches flow into the brain via a deterministic collector against X API v2 (Bearer token). Tracks deletions (compare tweet IDs run-over-run, verify via direct lookup, only for tweets <7 days old and not stale >48h), engagement velocity (alert at 2x on tweets with ≥50 likes, or +100 absolute), and — new in v0.8.1 — image OCR via a vision model, a real-time Filtered Stream option (Basic tier, $200/mo), and a 6-dimension tweet rating rubric (reach, relevance, sentiment, novelty, actionability, virality). Cron every 30 min, staggered against other collectors to avoid resource contention. Cost: $0 (free tier) to $200/mo (Basic, needed for search) to $5,000/mo (Pro, full archive). ### meeting-sync (v0.7.0, sense, no dependencies) Circleback meeting transcripts auto-import as `brain/meetings/{YYYY-MM-DD}-{slug}.md` with frontmatter (source_id, date, duration, attendees), key points, action items, and full speaker-labeled transcript. The Circleback API returns JSONRPC 2.0 wrapped in SSE wrapped in a double-JSON-encoded string — parsing requires stripping the `data:` prefix, parsing the SSE line, drilling into `result.content[0].text`, then parsing that string as JSON again. Idempotent by `source_id` (double-checked via grep + filename). Auto git-commits and pushes after each sync, which triggers gbrain's live sync. Cron 3x/day on weekdays. Cost: $0 (10 meetings/mo free) to $17/mo (Pro, unlimited). ### twilio-voice-brain (v0.8.2, sense, requires ngrok-tunnel) — **DEPRECATED in v0.40.0.0** Phone calls create brain pages via Twilio + OpenAI Realtime (or a DIY Deepgram+Claude+TTS pipeline). Deprecated in favor of **agent-voice**; scheduled for removal in v0.41. Migration path: `gbrain integrations install agent-voice --target `, which includes a Twilio bridge (`code/lib/twilio-bridge.mjs`) for operators who still want phone inbound. Retained here for reference on production-hardening patterns still relevant to voice generally: Unicode sanitization before sending text to Twilio (em-dashes/smart-quotes/arrows crash the WebSocket if left as non-ASCII), PII scrubbing from voice context before it's read aloud, identity-first system prompts, and a conversation-timing rule set (don't interrupt mid-thought; respond after a complete thought + 2-3s silence; never let silence exceed 5s after a complete thought) called out as the single highest-impact voice-quality fix. Cost: ~$20-22/mo for ~100 min of calls. ### agent-voice (v0.1.0, category: voice, install_kind: copy-into-host-repo, no dependencies) The current voice recipe, replacing twilio-voice-brain. Ships two personas (Mars — introspective thought partner, voice `Orus`; Venus — sharp executive assistant, voice `Aoede`), a WebRTC-first browser client at `/call?test=1`, a read-only-by-default tool router (search/query/get_page/list_pages/find_experts/get_recent_salience/get_recent_transcripts/read_article; writes denylisted), and an optional Twilio adapter. Uses the **skillpack-as-reference paradigm**: `gbrain integrations install agent-voice --target ` *copies* the code into the operator's own repo (not a runtime gbrain dependency), so local edits are the operator's to keep. `--refresh` re-diffs host files against gbrain's current reference and classifies each as unchanged-identical / unchanged-stale / locally-modified / source-deleted / source-renamed, offering keep-mine/take-theirs/merge per file. Cost: $0.06-0.24/min OpenAI Realtime, optional $1-2/mo Twilio number. ### credential-gateway (v0.7.0, infra, no dependencies) Foundational recipe that email-to-brain and calendar-to-brain both require. Two options: **ClawVisor** (handles OAuth/refresh/encryption; one setup covers Gmail, Calendar, and Contacts) or **direct Google OAuth2** (no extra service, but the operator manages token refresh). The single most emphasized rule across every ClawVisor-dependent recipe: standing-task purposes must be **expansive** — narrow purposes like "email triage" cause the intent-verification model to reject legitimate requests. Cost: $0. ### ngrok-tunnel (v0.7.0, infra, no dependencies) Provides the fixed public URL that voice-to-brain and remote-MCP recipes need for webhooks (Twilio) and client connections (Claude Desktop, Claude Code, Perplexity). Free tier URLs change on every restart, breaking Twilio and Claude Desktop configuration — the doc treats Hobby tier ($8/mo, fixed domain) as effectively required for anything beyond a demo, backed by a watchdog script (cron every 2 min) that restarts ngrok and re-points Twilio if using the free tier. Notable gotcha: Claude Desktop's remote-MCP config does **not** work via `claude_desktop_config.json` — it silently fails; must use Settings > Integrations in the GUI. Cost: $0 (free, ephemeral) to $8/mo (Hobby, fixed domain) to $20/mo (Pro, 2+ domains). ### restart-sweep (v0.1.0, reflex, no dependencies) Detects Telegram messages dropped when the OpenClaw gateway restarts mid-session (webhook-delivered messages can't be replayed via `getUpdates` the way long-poll bots can). Reads OpenClaw session state via `openclaw sessions --json`, flags sessions with `abortedLastRun: true` as the primary (reliable) signal, and optionally flags "active before restart, silent after" timing gaps behind `OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1` (off by default — false-positives during quiet periods). A 6-hour cooldown per sessionKey prevents alert storms when the bootstrap log is unreadable and the restart-time estimate is unstable. Ships as a copy-into-host-repo script wired to a 5-minute cron; the noted v2 upgrade path is a plugin Minion handler registered against `gbrain/minions` for built-in queue idempotency. Cost: $0. ### retrieval-reflex (v0.1.0, reflex, install_kind: copy-into-host-repo, no dependencies) Not a data-ingestion recipe — it teaches the host agent *when* to look something up in the brain and *what* to pull. Two halves: (1) a deterministic, zero-LLM, on-by-default pointer layer in the `gbrain-context` engine that scans each turn for salient resolvable entities and injects a compact pointer (name → slug → one-line summary) so the agent knows a page exists without opening it; (2) this recipe installs a policy skill fragment into the host resolver encoding the trigger policy for actually retrieving. Disable via `retrieval_reflex: false` in `~/.gbrain/config.json` or `GBRAIN_RETRIEVAL_REFLEX=false`. Cost: $0. Setup time: 2 min — the fastest recipe in the catalog. ## How to Use Discover and check recipe status: ```bash gbrain integrations ``` Typical install order for a full "sense" stack (each STOPs on the agent until the prior credential validates): ```bash # 1. Infra first gbrain integrations install credential-gateway # or run its setup flow directly gbrain integrations install ngrok-tunnel # 2. Sense recipes that depend on credential-gateway # (email-to-brain, calendar-to-brain — agent-driven setup flows) # 3. Voice (current) gbrain integrations install agent-voice --target $TARGET_REPO # 4. Reflex layer gbrain integrations install retrieval-reflex --target ``` Refresh a copy-into-host-repo recipe against the latest gbrain reference: ```bash gbrain integrations install agent-voice --target $TARGET_REPO --refresh ``` ## Related Entities - [[entities/ai-provider-integrations]] — credential-gateway and meeting-webhook manual guides overlap with this catalog's self-installing recipes of the same purpose - [[entities/skills-catalog]] — `webhook-transforms` and `minion-orchestrator` skills operate the reflex-category recipes - [[concepts/ingestion-pipeline]] — the deterministic-collector pattern ("code for data, LLMs for judgment") every sense recipe follows - [[concepts/operations-and-cost]] — cost estimates and cron staggering discipline shared across recipes - [[syntheses/troubleshooting-casebook]] — Twilio/ngrok/OAuth failure modes surfaced in these recipes' Troubleshooting sections --- title: "Skills Catalog" type: entity tags: [skillpacks, operations, developer] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-skills-agent-readme-md.md", "raw/github_doc-skills-resolver-md.md", "raw/github_doc-skills-brain-filing-rules-md.md", "raw/github_doc-skills-friction-protocol-md.md", "raw/github_doc-skills-output-rules-md.md", "raw/github_doc-skills-conventions-brain-first-md.md", "raw/github_doc-skills-conventions-brain-routing-md.md", "raw/github_doc-skills-conventions-calibration-md.md", "raw/github_doc-skills-conventions-cron-via-minions-md.md", "raw/github_doc-skills-conventions-model-routing-md.md", "raw/github_doc-skills-conventions-quality-md.md", "raw/github_doc-skills-conventions-salience-and-recency-md.md", "raw/github_doc-skills-conventions-schema-evolution-md.md", "raw/github_doc-skills-conventions-search-modes-md.md", "raw/github_doc-skills-conventions-subagent-routing-md.md", "raw/github_doc-skills-conventions-test-before-bulk-md.md"] confidence: high --- # Skills Catalog ## Overview A gbrain skillpack scaffolds a `skills/` directory into the host agent repo: one `SKILL.md` per skill (contract + workflow), plus a handful of underscore-prefixed cross-cutting files and a `conventions/` folder. `skills/RESOLVER.md` is the dispatcher — as of gbrain v0.36, routing lives in each skill's own YAML frontmatter `triggers:` array (not a managed table), and the agent walks every `skills//SKILL.md` at runtime to build its routing table. This page catalogs the skill *names and purposes* evidenced in the gathered sources — it is not a substitute for reading a skill's own `SKILL.md`, but it answers "does skill X exist and roughly what does it do." ## Characteristics ### Always-on skills (fire on every message) | Skill | Purpose | |---|---| | `signal-detector` | Runs on every inbound message (spawned in parallel, non-blocking) to catch signals worth acting on | | `brain-ops` | Handles any brain read/write/lookup/citation operation | ### Brain operations | Skill | Purpose | |---|---| | `query` | Answers "what do we know about / tell me about / who is / background on"; also handles graph queries ("who knows who", "relationship between") | | `enrich` | Creates/enriches a person or company page | | `repo-architecture` | Filing rules — where a new file goes | | `brain-taxonomist` | Decides which directory a brain page belongs in; taxonomy checks and refiling | | `eiirp` | "Everything in its right place" — stores research, files miscellaneous work into the brain, makes it re-doable | | `citation-fixer` | Fixes broken citations in brain pages (chain into `maintain` for broader brain health) | | `data-research` | Research/tracking tasks — extracting from email, investor updates, donations | | `publish` | Shares a brain page as a link | | `frontmatter-guard` | Validates/fixes page frontmatter; brain lint | ### Content & media ingestion | Skill | Purpose | |---|---| | `capture` | Quick capture — "save this thought", "drop this in the inbox" | | `idea-ingest` | User shares a link, article, tweet, or idea | | `media-ingest` | Video/YouTube, PDF, podcast, book, screenshot, or repo ingestion | | `meeting-ingestion` | Processes a received meeting transcript | | `ingest` | Generic "ingest this" — auto-routes to the above | ### Operational | Skill | Purpose | |---|---| | `daily-task-manager` | Task add/remove/complete/defer/review | | `daily-task-prep` | Morning prep, meeting context, day planning | | `briefing` | Daily briefing — "what's happening today" | | `cron-scheduler` | Cron scheduling, quiet hours, job staggering | | `gbrain-advisor` | "Is my brain set up right", weekly brain checkup | | `reports` | Save or load reports | | `skill-creator` | "Create a skill", "improve this skill" | | `skillify` | Turns ad hoc work into a proper skill | | `functional-area-resolver` | Compresses an oversized RESOLVER.md/AGENTS.md into a functional-area dispatcher | | `skillpack-check` | Morning health check — "is gbrain healthy" | | `skillpack-harvest` | Publishes/promotes a local skill upstream into gbrain for other clients | | `smoke-test` | Post-restart health check + auto-fix | | `cross-modal-review` | Cross-modal review / second opinion | | `testing` | Validates skills; skill health check | | `webhook-transforms` | Webhook setup and external event processing | | `minion-orchestrator` | Spawns background/parallel agent tasks; steer/pause/resume; `gbrain jobs submit` | | `ask-user` | Choice-gate pattern for presenting options / getting a user decision | ### Setup & migration | Skill | Purpose | |---|---| | `setup` | "Set up GBrain", first boot | | `cold-start` | Bootstrap — "fill my brain", "what should I import first" | | `migrate` | Migrate from Obsidian/Notion/Logseq | | `maintain` | Brain health check/maintenance run; also link extraction, timeline population, and the dream-cycle synthesis phases | | `gbrain-upgrade` | "Upgrade gbrain", checks for `UPGRADE_AVAILABLE` | | `soul-audit` | Agent identity — "who am I", customize agent | ### Schema | Skill | Purpose | |---|---| | `schema-author` | Dispatcher for all `gbrain schema` subcommands — add/remove types, aliases, prefixes, link types; propose new types from a corpus | | `schema-unify` | Consolidates page-type proliferation to the canonical taxonomy ("94 types to 14"); `gbrain onboard --check`, `gbrain jobs submit unify-types` | ### Uncategorized (single-purpose) | Skill | Purpose | |---|---| | `book-mirror` | Personalized two-column analysis of a book against the user's life | | `article-enrichment` | Batch-enriches brain pages from an article | | `strategic-reading` | Reads a source through a specific lens/problem; extracts a playbook | | `concept-synthesis` | Synthesizes concepts across notes; builds an intellectual map | | `idea-lineage` | Traces how the user's thinking on an idea evolved over time | | `perplexity-research` | Web research via Perplexity — "what's new about", "current state of" | | `archive-crawler` | Mines an old archive/dropbox for reusable content | | `academic-verify` | Verifies an academic claim or study | | `brain-pdf` | Exports a brain page as PDF | | `voice-note-ingest` | Transcribes and files a voice memo | ### Thinking skills (from GStack, not gbrain-native) | Skill | Purpose | |---|---| | `office-hours` | Brainstorming | | `ceo-review` | Plan review — "poke holes" | | `investigate` | Debug/fix/investigate | | `retro` | Retrospective — "what shipped" | These come from GStack, a sibling project; if GStack isn't installed, gbrain's brain-only skills still function without them. ### Identity & access files (not SKILL.md, but always-consulted) | File | Purpose | |---|---| | `ACCESS_POLICY.md` | Checked before responding to a non-owner message | | `SOUL.md` | Agent identity/vibe | | `USER.md` | User context | | `HEARTBEAT.md` | Operational cadence — what to check and when | ### Cross-cutting underscore files (apply to every brain-writing skill) | File | Purpose | |---|---| | `_AGENT_README.md` | Operating contract: routing via SKILL.md frontmatter `triggers:`, skillpack-reference diffing on upgrade, skill removal procedure | | `_brain-filing-rules.md` | Primary-subject filing rule, notability gate, mandatory back-linking, citation requirements, raw-source-preservation size routing, dream-cycle path allow-list, takes attribution (holder vs. subject) | | `_output-rules.md` | Deterministic links only (never guess a URL), no LLM slop, exact-phrasing preservation for quotes, title-quality bar | | `_friction-protocol.md` | `gbrain friction log --severity {confused,error,blocker,nit}` — logs tool/doc friction (and delight) for the claw-test feedback loop | ### `conventions/` (cross-cutting rules every skill defers to) | File | Purpose | |---|---| | `conventions/quality.md` | Citations, back-links, notability gate | | `conventions/brain-first.md` | Check the brain before calling external APIs | | `conventions/brain-routing.md` | Which brain (DB) and which source (repo) to target; cross-brain federation is latent-space only | | `conventions/schema-evolution.md` | When to add a new type vs. alias vs. prefix — read before `schema-author` | | `conventions/subagent-routing.md` | When to use Minions vs. inline work | | `conventions/search-modes.md` | Search-mode tuning reference for "what search mode/is my cache hot" queries | | `conventions/calibration.md`, `conventions/cron-via-minions.md`, `conventions/model-routing.md`, `conventions/salience-and-recency.md`, `conventions/test-before-bulk.md` | Additional cross-cutting conventions mirrored into `raw/`; each is referenced by name from skills that touch calibration scoring, cron-driven background jobs, model selection, salience/recency weighting, and pre-bulk-operation testing respectively | ## How to Use Check what's scaffolded vs. current, and pull in a newly added skill: ```bash gbrain skillpack reference --all gbrain skillpack reference # unified diff for one skill gbrain skillpack reference --apply-clean-hunks # two-way merge, use with care gbrain skillpack scaffold # bring in a skill gbrain added since scaffolding ``` Remove a scaffolded skill: ```bash rm -rf skills/ rm src/commands/.ts # if the skill declared paired source files ``` Log friction encountered while using a skill: ```bash gbrain friction log --severity error --phase --message "" ``` ## Related Entities - [[entities/recipes-catalog]] — recipes are self-installing integrations; skills are the agent-facing behavior contracts that often drive them - [[concepts/skillpacks-and-skills]] — the skillpack packaging/versioning model this catalog sits on top of - [[concepts/minions-orchestration]] — backs the `minion-orchestrator` skill - [[concepts/verification-and-quality]] — backs `frontmatter-guard`, `citation-fixer`, `testing`, `smoke-test` - [[syntheses/troubleshooting-casebook]] — issues that surface through `gbrain doctor` and `smoke-test` --- title: "Activity Log" type: log --- # Activity Log Append-only record of all wiki changes. ## 2026-07-02 — Initial build (medium rung) **Triggered by:** user request for a gbrain wiki (github.com/garrytan/gbrain, 25k stars). **Gathered:** 153 raw sources via source-pipeline (138 github_docs from master incl. docs/, skills conventions/catalog docs, recipes; 15 closed issues >=3 comments). Excluded by spec: skills/migrations per-version notes (CHANGELOG covers versions), docs/plans|proposals|designs (internal planning), examples/evals/tests. **Built (18 pages):** 11 concepts (overview, install-and-setup, brains-and-sources, schema-packs, skillpacks-and-skills, retrieval-and-search, ingestion-pipeline, minions-orchestration, mcp-integration, operations-and-cost, verification-and-quality), 3 entities (ai-provider-integrations, skills-catalog — maps the ~60-skill space without per-skill pages, recipes-catalog), 1 summary (version-digest, current 0.42.56.0 "Life Chronicle"), 3 syntheses (topology-picker, troubleshooting-casebook from 15 solved issues, brain-vs-memory). **Notes:** DESIGN.md judged irrelevant (admin SPA style guide) and dropped from overview sources. gbrain_version: "0.42.56.0" on all pages. --- ## Format Each entry follows this format: ``` ### YYYY-MM-DD HH:MM — [Action Type] - **Source/Trigger**: what initiated the action - **Pages created**: list of new pages - **Pages updated**: list of updated pages - **Notes**: any contradictions flagged, decisions made ``` --- ### 2026-04-08 00:00 — Setup - **Source/Trigger**: Repository initialized - **Pages created**: index.md, log.md, dashboard.md, analytics.md, flashcards.md - **Pages updated**: none - **Notes**: Empty knowledge base ready for first source ingestion --- title: "Version Digest" type: summary tags: [operations, foundational] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-changelog-md.md", "raw/github_doc-docs-migrations-v0-41-2-markdown-greenfield-md.md"] confidence: high --- # Version Digest ## Key Points - **Current version: 0.42.56.0** (released 2026-07-02), per the top entry of `CHANGELOG.md`. gbrain has no GitHub Releases — `CHANGELOG.md` plus the `VERSION` file are the only version record. - **Cadence:** near-daily to every-few-days shipping. The ~10 entries below this digest span 2026-06-11 to 2026-07-02 (0.42.41.0 through 0.42.56.0), roughly 15 releases in 3 weeks — a four-part dotted version (`major.minor.patch.build`) where the last segment increments almost every release. - **Every entry ends with a "To take advantage of vX" section** — a standing convention that tells the operator exactly what command(s) to run (`gbrain upgrade`, `gbrain apply-migrations --yes`, or nothing at all) to benefit from that release, and calls out what's on-by-default vs. opt-in. ### Last ~10 meaningful versions (newest first) | Version | Date | Headline | |---|---|---| | **0.42.56.0** | 2026-07-02 | **Life Chronicle** — bi-temporal entity ontology, timeline events (`gbrain day`, `gbrain since`, `gbrain last-seen`), diary capture, `gbrain orient`. Auto-emission off by default; diary content redacted from untrusted/remote readers. | | 0.42.55.0 | 2026-06-24 | Security-hardening pass: routing dotfiles trust-gated, skills directory confined to workspace, page slugs reject unsafe characters (control bytes, RTL overrides), large-file transcription no longer builds shell strings, dynamic OAuth client registration defaults to consent-bearing grant. | | 0.42.53.0 | 2026-06-23 | Fixed a JSONB double-encode bug that aborted every multi-source Postgres `gbrain sync` at the first checkpoint; swept the same bug class repo-wide; added a CI guard (`scripts/check-jsonb-params.mjs`). | | 0.42.52.0 | 2026-06-18 | Autopilot stops manufacturing dead jobs / wedging its queue; per-source failure cooldown + fan-out clamp; sync stall watchdog (`GBRAIN_SYNC_STALL_ABORT_SECONDS`, default 900); `gbrain status --deadline-ms`/`--fast`. | | 0.42.51.0 | 2026-06-17 | `gbrain sync` writes scale across cores (page-generation clock moved off a single locked counter row); `gbrain doctor` distinguishes in-progress sync from genuinely stale. | | 0.42.50.0 | 2026-06-17 | CI reliability hardening: concurrency-cancel superseded runs, `timeout-minutes` on every job, hermetic E2E env scrub, `actionlint` workflow linting. | | 0.42.49.0 | 2026-06-16 | Opt-in DB pacing for `gbrain embed`/`gbrain sync` (`--pace[=mode]`, `pace.mode` config) so large backfills can't starve the minion supervisor's lock renewals. | | 0.42.48.0 | 2026-06-16 | Brain-repo git hardening: `gbrain sources add --pat-file` and `gbrain sources harden` auto-install divergence-safe pull, auto-push safety net, and a 30-minute background pull. First push path / first credential storage in gbrain. | | 0.42.47.0 | 2026-06-16 | Brain-resident skillpacks (a brain repo can ship its own skills to any connecting harness) + `gbrain advisor` — read-only ranked "what to do next" list. | | 0.42.46.0 | 2026-06-16 | Federated read scope extended to every by-slug read (`get_page`, `get_tags`, `get_links`, `get_backlinks`, `get_timeline`), not just search/query. | | 0.42.45.0 | 2026-06-13 | Daily sync cron stops wedging on cost gates; embedding-spend estimate now prices only the actual sync delta, not the whole corpus; `spend.posture tokenmax` makes cost gates informational. | | 0.42.44.0 | 2026-06-13 | Fixed a broken link in the personal-brain tutorial (pointed at wrong AlphaClaw domain). | | 0.42.43.0 | 2026-06-12 | Push-based context: ambient retrieval reflex reads recent turns and volunteers relevant pages unprompted (`volunteer_context`, `gbrain watch`), confidence-gated (default 0.7). | | 0.42.42.0 | 2026-06-12 | Fixed a flat 10-second exit tax on `gbrain query` under transaction-mode Postgres poolers; fixed a long-standing bug where **every PGLite error exit reported success (exit 0)**. | | 0.42.41.0 | 2026-06-11 | Correctness wave: conversation facts no longer deleted by the `extract_facts` reconcile cycle; autopilot no longer crash-loops on transient DB errors; concurrent PGLite processes no longer corrupt each other's WAL via stolen locks. | ### Breaking-change and migration patterns - **Migrations are versioned and additive.** Numbered migrations (e.g. v120 schema-lint hardening, v121 event-projection column, v122 facts ontology columns, v94 take_domain_assignments) run via `gbrain apply-migrations --yes` or automatically on the next command that opens the brain. Legacy rows are consistently left unchanged ("additive; legacy rows unchanged"). - **New behavior defaults to off, existing behavior is preserved on upgrade.** Recurring phrase across entries: "Auto-emission is OFF by default," "Pacing is opt-in (default off)," "existing brains are untouched until you opt in." Security hardening is the exception — it's forced on for all brains (fresh and existing) since it closes real vulnerability classes. - **Deprecation has a one-release grace window with an explicit removal version.** Example: `twilio-voice-brain` recipe marked deprecated in v0.40.0.0, stays available for exactly one release, scheduled for removal in v0.41 (see [[entities/recipes-catalog]]). - **Config keys refuse silent schema-breaking changes.** `gbrain config set embedding_model` / `embedding_dimensions` are refused outright as of v0.37.11.0 because the schema column has to resize — the supported paths are `gbrain reinit-pglite` (PGLite) or a documented SQL migration recipe (Postgres), never a bare config write. - **A dedicated one-shot importer, not a schema migration, moves data across a paradigm shift.** `docs/migrations/v0.41.2-markdown-greenfield.md` describes migrating a legacy OpenClaw brain's flat markdown files (`atoms/`, `concepts/`, `ideas/`) into gbrain's ingestion pipeline: `gbrain capture --source markdown-greenfield --repo ` with a mandatory `--dry-run` pass first, `imported_from: markdown-greenfield` frontmatter stamped on every page so later `dream` cycles skip re-extracting them, and a fully reversible rollback (`gbrain pages delete`/`purge-deleted`) since the importer only reads from the original repo, never mutates it. Idempotent at the page-slug level — safe to re-run after partial failures. - **Exit-code correctness was treated as a first-class bug class.** Two releases in the same week (0.42.42.0, 0.42.43.0) fixed CLI exit-code lies (PGLite always reporting 0, `gbrain doctor`'s FAIL verdict reporting 0) and added a structural CI guard against the next raw exit-code write — evidence that gbrain treats "the CLI told a script the truth about success/failure" as a hard reliability requirement, not a nice-to-have. ## Relevant Concepts - [[concepts/operations-and-cost]] — spend-posture gates, sync stall watchdogs, and pacing knobs referenced across multiple digested versions - [[concepts/ingestion-pipeline]] — the markdown-greenfield importer's dry-run/audit/idempotency pattern - [[concepts/verification-and-quality]] — the exit-code correctness fixes and CI reliability hardening wave - [[entities/recipes-catalog]] — twilio-voice-brain's deprecation timeline as a concrete breaking-change example - [[entities/skills-catalog]] — the `gbrain-upgrade` skill that watches for `UPGRADE_AVAILABLE` ## Source Metadata - **Type:** GitHub-hosted markdown documentation (`CHANGELOG.md`, migration guide) - **Source:** `github.com/garrytan/gbrain`, `master` branch - **Fetched:** 2026-07-05 - **Identifiers:** `raw/github_doc-changelog-md.md` (path `CHANGELOG.md`), `raw/github_doc-docs-migrations-v0-41-2-markdown-greenfield-md.md` (path `docs/migrations/v0.41.2-markdown-greenfield.md`) --- title: "Brain vs Memory, and gbrain vs Alternatives" type: synthesis tags: [brains, mcp, foundational, operator] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-docs-guides-brain-vs-memory-md.md", "raw/github_doc-docs-mcp-alternatives-md.md", "raw/github_doc-docs-guides-brain-agent-loop-md.md", "raw/github_doc-docs-guides-agent-to-gbrain-md.md"] confidence: high --- # Brain vs Memory, and gbrain vs Alternatives ## Comparison ### Three information layers, three destinations | Layer | What goes here | Durability | Example | |---|---|---|---| | **gbrain (the brain)** | World knowledge — facts about entities external to the agent (people, companies, deals, meetings, concepts, original thinking) | Durable; survives agent resets | "Pedro is CEO of Brex" → person page; "Brex raised Series D at $12B" → company page | | **Agent memory** | Operational state — the agent's own preferences, decisions, tool config, session continuity | Not guaranteed durable ("doesn't survive agent resets on some platforms") | "User prefers concise formatting"; "Deploy to staging before prod"; "API key for X goes in .env" | | **Session context** | Current conversation — what was just said, immediate task state | Ephemeral, automatic (already in the conversation window) | "We were just discussing the board deck" | ### gbrain vs. the two localOnly/MCP surfaces (a distinct but related distinction) | Surface | Operations | Access path | Why | |---|---|---|---| | **MCP ops over HTTP** | `search`, `query`, `put_page`, `get_page`, `find_experts`, `find_orphans`, `find_anomalies`, `get_recent_salience`, `find_trajectory`, etc. | Thin-client + OAuth (`client_credentials` grant); secrets never leave the `gbrain serve` process | Preferred whenever an MCP-equivalent op exists — OAuth scoping (`read`/`write`/`admin`), source-scoped tokens, one audit surface (`mcp_request_log`) | | **localOnly admin ops** | `sync`, `embed`, `extract`, `dream`, `doctor`, `autopilot`, `init`, `secrets` | Shell job with `inherit: [...]` submitted to the Minions worker, or direct CLI on the host | These need local filesystem access or manage `~/.gbrain/`; refused outright in thin-client mode (`localOnly op refused in thin-client mode`) | ### Remote-access alternatives for exposing an MCP server (tunnel comparison) | | ngrok | Tailscale Funnel | Fly.io / Railway | |---|---|---|---| | Cost | $8/mo (Hobby, fixed domain) | Free | $5-10/mo | | Fixed URL | Yes (Hobby tier) | Yes | Yes | | Works when laptop is off | No | No | Yes | | Cold start | None | None | None | | All 30 operations | Yes | Yes | Yes | | Setup time | 5 min | 10 min | 15 min | ## Analysis **The brain-vs-memory boundary test is "is this about the world, or about how the agent operates?"** — and the source is explicit that this is the single decision rule to apply when in doubt. Two failure modes bracket the correct answer: storing a person's stated preference ("Pedro prefers email over Slack") in agent memory *feels* like a preference but is actually a fact about Pedro, so it belongs on his gbrain page — routing it to memory means it's lost the moment the agent's memory doesn't survive a reset. The mirror-image mistake is storing the *user's* preference ("likes bullet points over paragraphs") in gbrain — that's about agent behavior, not the world, and cluttering knowledge pages with it degrades gbrain's own search quality. **Synthesis of external ideas is explicitly routed to gbrain, not memory** — "the user's take on Peter Thiel's zero-to-one framework" is the user's original thinking, filed under `originals/`, because it's knowledge about the world (the user's own intellectual position) even though it originates in conversation. This is the same instinct captured in the `_brain-filing-rules.md` skill convention referenced in [[entities/skills-catalog]]. **The brain-agent loop treats gbrain as strictly prior to any external API call, not just prior to memory.** The stated invariant is "external APIs fill gaps, they don't start from scratch" — `gbrain search` runs before Brave Search, `gbrain get` before Crustdata. This positions gbrain not merely as one memory layer among several but as the default first move for any entity-shaped question, with the read happening *before* composing a response (not after) so the response itself benefits from context, and the write happening immediately after (not deferred, because "I'll update the brain later" means never in practice). **The MCP-surface distinction (Surface 1 vs Surface 2) is a separate axis from the brain-vs-memory question, but the two compound for downstream agent authors.** A hermes/openclaw/fork author calling into gbrain doesn't just decide "does this belong in the brain" — they also have to decide *which gbrain surface* reaches it. Getting this wrong has a real cost: pre-v0.36.5.0, agents that needed `localOnly` ops (like `sync`) but didn't know the shell-job pattern existed would pass secrets like `DATABASE_URL` via a job's plain `env:` field, landing the plaintext value in `minion_jobs.data` and the shell-audit JSONL — visible to anyone with brain-DB read access. The `inherit: ["database_url"]` mechanism (names in the row, values resolved at child-spawn from the worker's own config) is the corrected pattern, and the validator now rejects the old plaintext form outright. **"gbrain vs alternatives" in the gathered sources is narrower than a full memory-system comparison — it's specifically about tunnel/remote-access alternatives for MCP**, not a comparison against other memory or knowledge-graph products (mem0, Zep, etc. are not mentioned in the gathered source). Within that scope, the three options (ngrok, Tailscale Funnel, Fly.io/Railway) trade off cost, always-on availability, and setup time identically regardless of which is chosen — `gbrain serve --http` itself is Postgres-only by design (PGLite is local-only), which is the actual constraint that forces a topology decision once remote access is wanted (see [[syntheses/topology-picker]]). ## Recommendations - **Apply the world-vs-operations test to every new piece of information before storing it**, and default to gbrain when genuinely unsure — a missing brain page is recoverable, but agent memory that isn't durable on your platform means unrecoverable loss for world knowledge misfiled there. - **Always read gbrain before responding, not after**, and always write back immediately after a conversation surfaces new information about a known entity — both are stated as invariants, not suggestions, in the brain-agent loop. - **When building a downstream agent integration, consult `src/core/operations.ts`'s `localOnly` flag before deciding how to call an operation** — don't assume every gbrain capability is reachable over MCP. `sync`/`embed`/`extract`/`dream`/`doctor`/`autopilot`/`init`/`secrets` all require the shell-job + `inherit:` pattern or direct host CLI access. - **Never pass secrets through a shell job's plain `env:` field** — use `inherit: [...]` so only the config-key name (not the value) is ever persisted in job data or audit logs. - **For remote MCP access, pick the tunnel option by uptime requirement, not just cost**: ngrok/Tailscale are free-to-cheap but die when the host machine is off; Fly.io/Railway cost slightly more but run 24/7. ## Pages Compared - [[entities/skills-catalog]] — `_brain-filing-rules.md` and the notability gate that operationalize the world-vs-operations boundary at write time - [[syntheses/topology-picker]] — the Postgres-only constraint on `gbrain serve --http` and how it interacts with remote-access topology choices - [[entities/ai-provider-integrations]] — the credential gateway pattern (agent never holds raw API keys) that parallels the `inherit:` secrets pattern here - [[concepts/minions-orchestration]] — the shell-job worker mechanism that carries `localOnly` operations for a downstream agent - [[concepts/mcp-integration]] — the fuller MCP ops surface and OAuth scoping model referenced in Surface 1 --- title: "Topology Picker: Personal vs Company vs Multi-Brain" type: synthesis tags: [brains, operations, foundational] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_doc-docs-architecture-topologies-md.md", "raw/github_doc-docs-tutorials-personal-brain-md.md", "raw/github_doc-docs-tutorials-company-brain-md.md", "raw/github_doc-docs-architecture-infra-layer-md.md", "raw/github_doc-docs-guides-executive-assistant-md.md"] confidence: high --- # Topology Picker: Personal vs Company vs Multi-Brain ## Comparison gbrain's own architecture doc distinguishes **deployment topology** (WHERE the database lives) from **brain organization** (WHICH database, and how sources/scopes divide it — see `docs/architecture/brains-and-sources.md`). This page combines both axes into one picker, because the tutorials always bundle a deployment shape with an organizational pattern. | Dimension | Personal brain (Topology 1) | Company brain (Topology 1 + multi-source) | Cross-machine thin client (Topology 2) | Split-engine per-worktree (Topology 3) | |---|---|---|---|---| | **Who it's for** | Solo user, single machine, one agent | 10-50 person team sharing institutional memory | Agent runs on one machine, brain hosted on another (beefy host, thin edge) | Multiple Conductor/gstack worktrees on one machine touching the same code repo | | **Engine** | PGLite (small) or Supabase (1000+ files) | Real Postgres/Supabase required for multi-user (`gbrain migrate --to supabase` if starting on PGLite) | No local engine at all — thin client has a `remote_mcp` config, not a DB connection | One PGLite per worktree + a separate shared artifact brain (local or Topology 2) | | **Sources** | One (`default`) | Multiple, e.g. `shared`, `customers`, `internal` — each a separate git-backed source in the same DB | Whatever the host defines; thin client is transparent to source structure | Per-worktree code source (disposable) + shared artifact source (durable) | | **Access control** | None needed (single user) | Per-teammate OAuth clients with `--source` (write scope) + `--federated-read` (read scope); isolation enforced at the SQL layer, fuzz-tested for zero cross-source leaks | `gbrain auth register-client` with `client_credentials` grant; scope must include `admin` for `gbrain remote ping`/`doctor` | Alias-level only — no smart per-tool routing; a wrong alias silently reads/writes the wrong brain | | **Setup command** | `gbrain init` / `gbrain init --pglite` / `gbrain init --supabase` | `gbrain sources add --path

--name "..."` per source, then `gbrain auth register-client --source --federated-read ` | Host: `gbrain serve --http --port 3001 --bind 0.0.0.0`; client: `gbrain init --mcp-only --issuer-url ... --oauth-client-id ...` | `GBRAIN_HOME=/.conductor/gbrain gbrain init --pglite && gbrain serve --http --port ` per worktree | | **Cost (real numbers from source)** | ~$100-150/mo (Render Pro $85 + Supabase free-$25 + OpenAI $5-20 + Anthropic $50-500) | Under $100/mo AI-side for 25 people (ZeroEntropy embeddings ~$35, Anthropic ~$50) on top of the personal-brain hosting bill | N/A — cost is whatever the host brain already costs; thin clients add no DB cost | N/A — local PGLite per worktree is disposable/free; cost is whichever artifact-brain topology backs it | | **Embedding model recommendation** | ZeroEntropy default (2x faster, 2.6x cheaper than OpenAI per the company-brain benchmark) | Same — ZeroEntropy at $0.05/M tokens vs OpenAI $0.13/M, Voyage $0.18/M | Inherits host's provider | `voyage-code-3` (code-tuned) per worktree, set at `gbrain init` time since `config set embedding_model` is refused post-init | ## Analysis **The three deployment topologies compose rather than compete.** A single machine can run a Topology-2 thin client pointed at a remote artifact brain *and* Topology-3 per-worktree code engines simultaneously — `GBRAIN_HOME` picks which `~/.gbrain` config is active per invocation, and the agent's MCP client config picks the destination per tool call by alias. There is no global orchestrator; this is explicit by design. **Personal vs company brain is not a different install — it's the same stack with three additions.** The company-brain tutorial is explicit: the agent runtime, Supabase backend, gbrain CLI, and harness "stay exactly as you set them up" from the personal-brain tutorial. What's added is (1) multiple sources instead of one, (2) per-user OAuth scoping, (3) per-person folders/crons/skills layered on top of shared structure. Anyone reading the company-brain tutorial in isolation should first have completed the personal-brain path — the two docs form a strict progression. **Two distinct scoping models exist for the company case, and they solve different problems.** Model A (separate sources + OAuth scoping) gives database-enforced isolation and suits a company where every teammate runs their own AI client independently. Model B (one source + `partners//` convention) is what the source author actually runs in production for a fat-agent-serves-everyone pattern over a single interface (e.g. Telegram) — isolation there is convention-only, enforced by the agent, not the database. Choosing wrong means either over-engineering OAuth infrastructure for a single-agent deployment, or under-protecting sensitive content (legal, HR, performance reviews) in a multi-client deployment. **Adoption is a bigger risk than architecture.** The company-brain tutorial's most emphasized non-technical point is the "botmaster pattern": pre-populate each teammate's slice before they ever log in, walk them through 2-3 specific "wow" flows, and only then hand over open DM access. Skipping straight to "here's your credential, try it out" reliably produces a bounce — the teammate sends one generic query against their empty slice, gets a generic answer, and never returns. **Topology 3's biggest risk is silent misrouting, not performance.** Because alias routing is manual and there is no cross-checking, a wrong `mcp____put_page` call permanently writes code-shaped content into the artifact brain (or vice versa) with no error. The mitigation is naming discipline (`gbrain_code` vs `gbrain_artifacts`, never `gbrain` vs `gbrain_local`) plus explicit system-prompt rules — this is a documentation/convention fix, not a code fix, and gstack is called out as the layer that automates this wiring consistently across worktrees. **The infra layer (chunking → embedding → hybrid RRF search) is identical underneath every topology.** The same pipeline (`src/core/import-file.ts`, hybrid search with 4-layer dedup, `voyage-code-3` or `zembed-1` for embeddings) runs whether the brain is a solo PGLite install or a Supabase-backed 25-person company brain — the topology and organization choices only change *where* that pipeline runs and *who* can query which slice, never *how* retrieval works. **Executive-assistant-style workflows (email triage, meeting prep) are topology-agnostic but assume a populated brain.** The pattern of searching a sender/attendee *before* reading content, then writing back post-interaction, works identically whether the brain is personal or company-scoped — but its value is gated on entity pages already existing, which is itself gated on the ingestion recipes in [[entities/recipes-catalog]] being wired up. ## Recommendations - **Start with Topology 1 (personal brain) unless you already know you need multi-user.** It's the default (`gbrain init` with no flags) and every other topology is additive on top of it. - **Pick Topology 2 (thin client) only when the agent genuinely runs on a different machine than the brain**, or when spinning up a second local install would create source-ID contention. Don't use it for a same-machine agent+brain pair — a local stdio `gbrain serve` is simpler and faster. - **Pick Topology 3 (split-engine) only with multiple concurrent Conductor/gstack worktrees.** With one worktree at a time, there's no contention to prevent, so the extra per-worktree engine setup is pure overhead. - **For a company brain, default to Model A (separate sources + OAuth) if teammates use different AI clients**; use Model B (single source + `partners/` convention) only if one agent serves everyone through one shared interface. - **Budget the botmaster onboarding time (~45 min/teammate) into any company-brain rollout plan** — it is explicitly called out as the difference between adoption and an unused internal tool. - **Set the embedding model at `gbrain init` time, not after.** `gbrain config set embedding_model`/`embedding_dimensions` is refused post-init (schema resize requirement); use `gbrain reinit-pglite` or the Postgres migration recipe to change it later. See [[entities/ai-provider-integrations]]. - **For any code-indexing use case (gstack per-worktree brains), use `voyage-code-3`, not a general-purpose embedding model** — it's specifically tuned for code retrieval per Voyage's published benchmarks. ## Pages Compared - [[entities/ai-provider-integrations]] — embedding provider choice by topology - [[entities/recipes-catalog]] — ingestion recipes that populate a brain regardless of topology - [[concepts/brains-and-sources]] — the organizational axis (which DB) this page pairs with the deployment axis (where the DB lives) - [[concepts/operations-and-cost]] — autopilot, `gbrain doctor --remediate`, and cost controls referenced in the company-brain operating section - [[syntheses/brain-vs-memory]] — a related decision (brain vs. agent memory) that applies within any of these topologies --- title: "Troubleshooting Casebook" type: synthesis tags: [operations, retrieval, ingestion, mcp, verification] created: 2026-07-02 updated: 2026-07-02 gbrain_version: 0.42.56.0 sources: ["raw/github_issue-v0-13-0-migration-shells-out-via-process-execpath-breaks-on-.md", "raw/github_issue-autopilot-install-generates-broken-wrapper-execpath-resolves.md", "raw/github_issue-v0-14-x-initschema-fails-with-column-link-source-does-not-ex.md", "raw/github_issue-sync-aborts-on-every-change-writecompleted-double-encodes-op.md", "raw/github_issue-source-config-stored-as-double-encoded-json-string-breaks-co.md", "raw/github_issue-gbrain-get-query-spin-at-100-cpu-after-printing-output-never.md", "raw/github_issue-gbrain-embed-hangs-indefinitely-on-pglite-no-http-requests-s.md", "raw/github_issue-gbrain-search-can-hang-after-printing-results-and-search-mod.md", "raw/github_issue-mcp-extract-facts-entity-hints-array-schema-is-missing-items.md", "raw/github_issue-mcp-server-fails-to-connect-schema-is-missing-a-method-liter.md", "raw/github_issue-oauth-clientsstore-getclient-returns-client-secret-hash-wher.md", "raw/github_issue-make-embedding-provider-model-and-dimensions-configurable.md", "raw/github_issue-data-loss-recloneifmissing-rm-rfs-user-managed-source-path-u.md", "raw/github_issue-gbrain-extract-is-not-source-aware-silently-inserts-0-links-.md", "raw/github_issue-bug-conversation-parser-no-match-on-pages-with-78-pattern-ma.md", "raw/github_doc-docs-issues-doctor-auto-heal-and-scoring-md.md", "raw/github_doc-docs-issues-cross-modal-search-md.md", "raw/github_doc-docs-architecture-retrieval-maxpool-incident-md.md"] confidence: high --- # Troubleshooting Casebook ## Comparison Grouped by symptom area, each entry names the failure, root cause, fix version (where fixed), and the issue mirror(s) that document it. | Symptom area | Failure | Fixed in | Issues | |---|---|---|---| | Install/upgrade path resolution | Wrapper scripts resolve `process.execPath` to the Bun runtime instead of the gbrain CLI | Consolidated fix under #332 | #238 (migration shell-out), #136 (autopilot --install) | | Schema migration ordering | `initSchema` runs `CREATE INDEX` referencing columns a later migration adds | Consolidated under #695 | #266 | | JSONB double-encoding | `JSON.stringify(x)` bound through `$N::jsonb` stores a string scalar, not an object/array | v0.42.53.0 (#2375) + `gbrain repair-jsonb` for pre-fix rows | #2280 (sync checkpoints), #2307 (sources.config / webhook lookup) | | PGLite post-output CLI hang | Fire-and-forget writes (retrieval tracking, search cache) race CLI disconnect, spin the event loop at ~100% CPU after output prints | v0.36.3.0 (embed/query path), later consolidated under #1259 | #1247 (get/query), #1065 (embed), #1343 (search + search-modes routing) | | MCP schema validation | Array params missing `items`; handler registration using raw string literals instead of SDK Zod schemas | v0.35.3.0 (array items), v0.6.0 (method literals) | #806, #9 | | OAuth secret verification | `clientsStore.getClient()` returns the stored SHA-256 hash where the MCP SDK's middleware expects plaintext, so every authorization_code `/token`/`/revoke` fails | v0.37.7.0 (native pre-handler) | #1166 | | Embedding provider lock-in | Provider/model/dimensions hardcoded to OpenAI text-embedding-3-large/1536 | Landed via PR #172 (pluggable providers) + PR #450/#469 (schema-layer dimension support) | #133 | | Destructive source re-clone | `recloneIfMissing()` ran an ungated `rm -rf` on a source's `local_path`, capable of destroying a user-managed working tree | v0.42.33.0 (#1881) | #1526 | | Federated extraction blind spot | `gbrain extract` drops `source_id` on the filesystem path, so links/timeline silently fail to insert on non-default sources; `doctor` recommends a command that can't work; `--dry-run` overcounts | v0.37.7.0 (source-scoped extract SQL) | #1204 | | Conversation-parser false negatives | Pattern scorer only scans the first 10 non-blank lines, missing transcripts behind frontmatter/summary preambles; then a real transcript shape had no matching built-in pattern | v0.41.18.1 (threshold fallback) + `bold-paren-time` pattern (unreleased-version follow-up) | #1533 | | Doctor scoring false positives (proposal, unshipped) | `NESTED_QUOTES` cosmetic YAML noise dominates frontmatter warnings (6,900+ of ~7,100); contradiction probe flags temporal evolution as conflict; multi-source drift from a pre-v0.30.3 bug can't be acknowledged | Proposed, not confirmed shipped in gathered sources | `docs/issues/doctor-auto-heal-and-scoring.md` | | Cross-modal search gap (proposal, unshipped) | Image embeddings (Voyage multimodal-3, 11K chunks indexed) exist but no query path routes text queries to the `embedding_image` column; `modality` metadata itself has a backfill gap (10 of ~11,204 rows correctly tagged) | Proposed (Phase 1 design), not confirmed shipped | `docs/issues/cross-modal-search.md` | | Retrieval miss on a chosen-name page (resolved incident) | A canonical concept page didn't surface for its own title phrase because retrieval was literal-embedding-proximity on body chunks, `aliases:` frontmatter was dead to search, and the agent's dedup decision keyed off a fuzzy blended score | Resolved (retrieval-cathedral wave) | `docs/architecture/RETRIEVAL_MAXPOOL_INCIDENT.md` | ## Analysis **One root-cause pattern recurs across three separate symptom areas: binding a JS string through `$N::jsonb` double-encodes it.** The sync-checkpoint abort (#2280) and the webhook `unknown_repo` 404 (#2307) are the same bug class in different tables — both trace to `JSON.stringify(x)` passed into a parameterized `::jsonb` cast, which postgres.js serializes into a JSON *string scalar* rather than an object/array. PGLite's driver parses either shape, so the bug is invisible in local dev and only bites real Postgres — this is explicitly called out in both issues and in `docs/integrations/reliability-repair.md`'s v0.12.2 write-up (see [[entities/ai-provider-integrations]]). The eventual fix (v0.42.53.0, PR #2375) was a repo-wide sweep plus a static AST scanner (`scripts/check-jsonb-params.mjs`) specifically because the same mistake had already shipped independently at least twice. Pre-fix rows do not self-heal — `gbrain repair-jsonb` must be run once. **`process.execPath` unreliability is a second recurring pattern, specific to Bun-based installs.** Both the v0.13.0 migration shell-out (#238) and `autopilot --install`'s wrapper generation (#136) assumed `process.execPath` resolves to the gbrain binary; under a `bun install -g` or `bun link` install it resolves to the Bun runtime itself, so the generated command becomes `bun ` instead of `gbrain `, failing with `Script not found`. Both issues were consolidated under a canonical #332 tracking issue — evidence that gbrain triages by bug *class*, not by individual report, once a pattern is recognized (the same consolidation pattern appears for #266 → #695, and for the PGLite-hang reports → #1259). **PGLite's cooperative single-owner model produces a family of "prints output then hangs" bugs**, all traced to code that fires a background write (search-cache invalidation, `last_retrieved_at` tracking) without awaiting it before the short-lived CLI process disconnects. On Postgres these writes finish fast enough that the race never surfaces; on PGLite (especially with larger vectors going through the HNSW path) the write can take long enough that Bun's event loop notices pending work and spins at ~100% CPU. The general shape of the fix (v0.36.1.1's `pendingCacheWrites` + `awaitPendingSearchCacheWrites()`) is to track fire-and-forget writes in a Set the CLI drains before exit, rather than making every write synchronous. **Federated/multi-source brains are where source-ID plumbing bugs concentrate.** `gbrain extract`'s missing `source_id` stamp (#1204) and the OAuth read-scope gaps fixed in changelog entry 0.42.46.0 (see [[summaries/version-digest]]) are both instances of "a feature worked correctly on a single-source brain and silently degraded on a federated one." The `extract` bug is particularly dangerous because `gbrain doctor`'s own remediation advice pointed at the broken command, and `--dry-run` disagreed with the real run (253 "would create" vs. 0 actually created) — a diagnostic actively pointing the wrong way is worse than no diagnostic. **The data-loss issue (#1526) is the most severe entry in this casebook and illustrates a documented safety pattern gap.** `recloneIfMissing()` lacked the containment check that its sibling `removeSource()` already had (`isPathContained(src.local_path, ~/.gbrain/clones)`), so a source whose `local_path` pointed outside gbrain-managed storage could have its entire working tree `rm -rf`'d on a false-positive "missing/no-git/not-a-dir" state — which the reporter demonstrated could be triggered by a Windows file-handle race during concurrent autopilot/sync activity. The eventual fix (v0.42.33.0) added `isOwnedClone` gating with a TOCTOU re-check and a symlink-leaf guard. The lesson generalizes: any function that does destructive filesystem cleanup needs the same containment check as its sibling functions, not a per-function reimplementation. **The retrieval-maxpool incident is the deepest single case study and corrects a prior RFC's own diagnosis.** It documents four independent retrieval gaps (per-page max-pooling, title-phrase boost, alias-hop synonym matching, and an evidence contract replacing a fuzzy dedup threshold) that combined to make a fully-developed concept page invisible to its own chosen name. It's notable for explicitly stating that a prior internal RFC (closed PR #1616) was "directionally right about the disease but wrong on several mechanics" — including a mislabeled repro command and a `--mode` flag that was never actually wired to the CLI. The incident produced a permanent regression gate (NamedThingBench) precisely because a 97.9 R@5 benchmark score coexisted with a 0.64 production score on the same query shape. **Two entries are unshipped proposals, not confirmed fixes — treat them as known gaps, not resolved issues.** `docs/issues/doctor-auto-heal-and-scoring.md` and `docs/issues/cross-modal-search.md` read like internal engineering RFCs with problem/evidence/proposed-fix/test-case structure, but neither source confirms a shipping version. Cross-referencing against [[summaries/version-digest]]'s digested changelog range (0.42.41.0–0.42.56.0) shows neither auto-heal mode nor cross-modal query routing appearing — if a wiki reader needs current status on either, that's a live gap to flag rather than assume closed. ## Recommendations - **On any Postgres-backed brain exhibiting silent write failures (sync aborting, webhook lookups 404ing with correct-looking config), suspect JSONB double-encoding first.** Check `jsonb_typeof()` — if it reads `'string'` instead of `'object'`/`'array'`, run `gbrain repair-jsonb` (idempotent, `--dry-run` available). - **On a Bun-based install, if a generated wrapper script or migration phase fails with `Script not found ""`, suspect a `process.execPath` misresolution.** Confirm gbrain is on the current version (this class was consolidated and fixed under #332); if it recurs, the shell-out should resolve the CLI via PATH or the package's `bin` field, never `process.execPath`. - **On PGLite, if a read command (`get`, `query`, `search`) prints correct output and then hangs, suspect an unawaited fire-and-forget write** (retrieval tracking, cache invalidation) racing CLI disconnect. Confirm version is at least v0.36.3.0 / carries the #1259 fix. - **On a federated/multi-source brain, don't trust `gbrain doctor`'s literal command suggestions without checking source-awareness first** — the extraction bug (#1204) shows doctor can recommend a structurally broken remedy. Cross-check `--dry-run` output against the real run's result count; a mismatch is itself the tell. - **Any custom filesystem-destructive function (recloning, purging, resetting a source) must reuse the same containment/symlink-escape guard as `removeSource()`**, not a bespoke check — the data-loss issue shipped specifically because the guard wasn't reused. - **For a page that should be found by a chosen/informal name, add `aliases:` frontmatter explicitly** — frontmatter aliases were dead to search until the retrieval-maxpool fix landed; verify with `gbrain search diagnose "" --target ` and `gbrain reindex --aliases` for pages predating the fix. - **Treat `docs/issues/*.md` proposal documents as open design work, not shipped features**, unless independently confirmed against the changelog. ## Pages Compared - [[summaries/version-digest]] — changelog entries confirming the JSONB and exit-code fix classes - [[entities/ai-provider-integrations]] — the reliability-repair doc covering the same JSONB double-encode class from the v0.12.2 era - [[entities/recipes-catalog]] — ngrok/Twilio/OAuth troubleshooting sections that parallel the OAuth and MCP-schema issues here - [[concepts/retrieval-and-search]] — the retrieval-maxpool incident's four-layer fix in full mechanical detail - [[concepts/verification-and-quality]] — `gbrain doctor`'s scoring model and the unshipped auto-heal proposal