Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(docs): restore doc tails a truncated rewrite dropped in the previous commit; reapply the doc edits in full (GBRA-202)
garrytan7f2d1130177e
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 5f7b767c2f..9b06ef30bb 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -617,4 +617,225 @@ timeout of at least 10 s. The wrapper and its rules:([deployment](docs/guides/minions-deployment.md#per-job-process-isolation---job-isolation-process)).- **Live sync** (every 15 min): `gbrain sync --repo ~/brain && gbrain embed --stale`- — or `gbrain sync --watch` for a continuous loop. Safe on keyless brains:\ No newline at end of file+ — or `gbrain sync --watch` for a continuous loop. Safe on keyless brains:+ a bare `gbrain embed --stale` exits 0 with a stderr note when embeddings+ are disabled, so the chain doesn't break.+- **Health gate** (daily): `gbrain autopilot --status` — exit 0 fresh (or+ nothing installed), 1 needs attention (stale heartbeat, never ran, or+ paused), 2 the daemon took itself out of rotation. Filesystem-only, so it+ works during DB outages.+- **Auto-update** (daily): `gbrain check-update --json` (tell user, never auto-install).+- **Dream cycle** (nightly): `gbrain dream` runs the 8-phase overnight maintenance cycle.+ Entity sweep, citation fixes, memory consolidation, plus overnight conversation+ synthesis and cross-session pattern detection. One cron-friendly command. This is what+ is an opt-in maintenance capability. See `docs/guides/cron-schedule.md` for the+ full protocol.+- **Weekly**: `gbrain doctor --json && gbrain embed --stale`++## Step 8: Integrations++Run `gbrain integrations list`, then `gbrain integrations show <id>` for one recipe.+Each recipe is a self-contained installer. It tells you what credentials to ask for, how to validate, and what cron+to register. Ask the user which integrations they want (email, calendar, voice, Twitter).++Verify: `gbrain integrations doctor` (after at least one is configured)++## Step 9: Verify++For memory-only installs, run the install check from the+[first-run protocol](docs/protocol/AGENT_OPERATOR_v1.md#first-run): the read-only+smoke check `gbrain doctor --only harness_wiring --json` (it reads the+registration and runs initialize, tools/list and one `recall` against it), then+`remember` an install-check marker with+provenance `install-check`, ask the user to restart the harness, `recall` it in+the new session and `forget` it. Never save a made-up fact about the user.+Also save one user-approved generic test note or fact with+provenance, retrieve it, exit the CLI, and retrieve it again in a new process.+Check exact keyword retrieval as well as `remember`/`recall`. A process reopen+proves local persistence, not a new conversation in the native harness; verify+that separately after the user authorizes harness setup.++Read `docs/GBRAIN_VERIFY.md` for the checks covering capabilities the user enabled.+Run live-sync checks only when sync was configured; do not install services or+enable paid providers to make optional checks pass.++Once verification passes and the brain has content, run the activation probe:++```bash+gbrain onboard --check --json+```++See "The onboard surface" below for what the recommendations mean and the+consent gates around unattended remediation.++<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->+## Multi-agent rules for a shared brain checkout++Several agents, crons and hooks often commit to one brain checkout on the same+machine. In such a checkout:++1. **Commit and push with one command, naming your files:**+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.+ It takes the checkout's writer lock, commits only those paths, merges remote+ commits without touching anyone else's files, and fails loudly if the push+ does not land.+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.+ Stop and relay to the user on `integrate_conflict` (they choose which+ version wins) and on `writer_coordinator_required` (a managed brain: save+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,+ `git commit -a`, `git reset --hard` or `git push --force` there, and never+ fall back to them when the command fails. Never delete `.git/rebase-merge`+ before saving its autostash with `git stash store`.+<!-- gbrain-allow-shared-tree-git-end -->++Outcomes, conflict recovery, a stuck rebase and the lock contract for host+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).+<!-- END multi-agent-rules -->++## Upgrade++When an upgrade crosses v0.60.5.0, confirm a database backup exists before+upgrading, upgrade every process that writes to the brain, then follow the+[v0.60.5.0 steps](skills/migrations/v0.60.5.0.md): one full `gbrain doctor`,+then preview `gbrain repair` and apply only after the user agrees+([repair guide](docs/guides/repair.md)). Across v0.60.6.0, also follow the+[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md). Across v0.60.11.0, preview+`gbrain repair contextual-mode` and rebuild PGLite vector indexes after a crash+repair ([steps](skills/migrations/v0.60.11.0.md)).++When an upgrade crosses v0.53.0.0, follow the+[mechanical shared-skills migration](skills/migrations/v0.53.0.0.md) on the host,+starting with `gbrain apply-migrations --dry-run --json`. Stop/exclude old writers,+review writer status, and use the checklist's action-specific `--admin-intent`+and reviewed `--expected-state` when activating shared skills. Quiescence flags+are attestations, not process shutdown or administration authority. Preserve+operational DB and content backups, consent, edited files, and grant fences.+DB-only export, explicit regrants, parent/client reconnection, and native+verification are separate stages; report pending stages rather than claiming+the whole migration completed.++On a host with resident processes (autopilot, a jobs worker, a serve), pause+autopilot (`gbrain autopilot pause`), wait until no job is active, run+`gbrain upgrade` on every install (it restarts every gbrain process onto the+new build and verifies one build runs, or refuses `restart_refused` naming the+process it cannot restart), check that each process reports the new version,+then `gbrain autopilot resume`. A production brain follows the stable channel+(`gbrain config set self_upgrade.channel stable`)+([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume),+[stable channel](docs/guides/upgrades-auto-update.md#stable-channel)).++For memory-only upgrades, keep services and paid reindexing opt-in. The same+command works for `bun install -g` and `git clone + bun link` installs:++```bash+GBRAIN_NO_AUTOPILOT_INSTALL=1 GBRAIN_NO_REEMBED=1 gbrain upgrade --no-autopilot-install+```++On a clone it fetches, checks the new release's Bun floor, fast-forwards to+exactly the checked commit and runs `bun install`; a bare `git pull` skips the+check and can leave a release the host's Bun cannot start. When the floor is+above the host's Bun, the upgrade refuses with `requires Bun >=<floor>` and+changes nothing (exit 78): run `bun upgrade`, then the same upgrade command+again. Pass `--no-bun-floor-check` only after checking the target yourself+when the floor cannot be read (offline). See+[Bun floor](docs/guides/upgrades-auto-update.md#bun-floor).++The autopilot opt-out skips installation and service rewrites, including package+postinstall hooks; it does not skip other migrations. Keep the environment form+on the package-manager command because hooks run before `post-upgrade`.+`GBRAIN_NO_REEMBED=1` separately skips the potentially paid reindex step.+For an existing service deployment, review its migration guide instead of+assuming memory-only options are the desired maintenance policy. Verify a known+keyword query after upgrading, not just the version string.++Then read `skills/migrations/v<NEW_VERSION>.md` (published at+`https://github.com/garrytan/gbrain/blob/master/skills/migrations/v<NEW_VERSION>.md`;+also read any intermediate versions you skipped) and run any backfill or verification steps it lists. Skipping+this is how features ship in the binary but stay dormant in the user's brain.++**v0.32.3 search modes (one-time upgrade prompt):** if the user's brain was+created before v0.32.3, `gbrain post-upgrade` prints a banner including the+9-cell cost matrix (mode × downstream model) preceded by `[AGENT]` markers.+**Do NOT silently move past the banner.** Present the matrix to the operator+verbatim, ask which mode they want (recommended default: `tokenmax` to preserve+v0.31.x retrieval shape), then run `gbrain config set search.mode <mode>`. See+Step 3.5 above for the full ask-the-user protocol — the upgrade path uses the+same matrix and same default.++If the brain was created before v0.12.0, run+`gbrain extract links --source db && gbrain extract timeline --source db` to+backfill the graph layer (see Step 4.5 above).++If the brain is Postgres- or Supabase-backed and was created before v0.12.2,+the `v0_12_2` migration runs `gbrain repair-jsonb` automatically during+`gbrain post-upgrade` to fix double-encoded JSONB columns (PGLite brains+no-op). If wiki-style imports from before v0.12.2 were truncated by a+`splitBody` bug, run `gbrain sync --full` after upgrading to rebuild+`compiled_truth` from source markdown.++## The onboard surface++`gbrain onboard` is gbrain's activation surface.+Once your brain has any content, run `gbrain onboard --check --json` to+see structured recommendations across 5 brain-health axes (orphans,+stale embeddings, entity link coverage, timeline coverage, takes count).++**On first connect (after `gbrain init`):**+```bash+gbrain onboard --check --json+```+The JSON envelope (`schema_version: 1`) carries `recommendations[]` with+`apply_policy` per item: `auto_apply` (safe to run unattended),+`prompt_required` (needs explicit user consent), or `manual_only`+(pack upgrade, paid takes bootstrap: the user runs it).++**After every `gbrain upgrade`:**+```bash+gbrain onboard --check --json+```+New versions may surface new opportunities. The post-upgrade banner+nudges the user when it runs, but agents should re-probe as a hygiene+step regardless.++**Unattended remediation (cron / autopilot):**+```bash+gbrain onboard --auto --max-usd 5+```+Refuses without `--max-usd N`. Never runs `manual_only` items; it+lists them in `manual_only_skipped`. The autopilot daemon also consults+onboard recommendations on its tick — no explicit agent action needed+for the autonomous path.++**Remote / federated brain installs (MCP):**+The `run_onboard` MCP op (admin scope) lets thin-client agents probe+brain health + drive remediation over OAuth-authenticated MCP. Protected+LLM-bearing handlers (synthesize, patterns, consolidate, takes-bootstrap,+contextual_reindex_per_chunk) require the additional `run_protected_onboard`+scope — admin alone is insufficient. The MCP op returns+`skipped_missing_scope[]` listing what would have run with the right+grants.++**Privacy + consent gates:**+- `gbrain takes extract --from-pages` sends concept/atom/lore/briefing/+ writing/originals page content to your configured chat model (default+ Anthropic Haiku). Refuses to run unless `takes.bootstrap_enabled=true`+ is set in config AND `--yes` is passed. Two-gate opt-in by design.+- Autopilot's auto-apply tier for takes-bootstrap is `manual_only`+ (do not bypass).++**Suppress nudges in CI / scripted environments:**+```bash+export GBRAIN_NO_ONBOARD_NUDGE=1+```+Init and upgrade notices do not skip themselves when there is no terminal:+non-interactive callers get the onboarding nudge, the init decision bundle and+the post-upgrade summary as `[AGENT]` blocks (or the `notices` key under+`--json`), and stdio MCP sessions get the post-upgrade summary once as a notice+block. `GBRAIN_NO_ONBOARD_NUDGE=1` silences the onboarding nudges and the+post-upgrade summary everywhere. Only the remote-brain identity banner stays+TTY-only (`GBRAIN_BANNER=1` forces it, `GBRAIN_NO_BANNER=1` hides it).diff --git a/README.md b/README.mdindex c4b53b3ed2..753bc60bf1 100644--- a/README.md+++ b/README.md@@ -380,4 +380,79 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup h### Memorable — remember how, not just what (optional)Memorable stores replayable procedures from coding sessions. Its relay is off by-default and requires an explicit disclosure/consent step; it can send redacted\ No newline at end of file+default and requires an explicit disclosure/consent step; it can send redacted+traces and query text off-machine. Read the [Memorable integration guide](docs/memorable-agents.md)+for installation, data flow, per-harness limitations, and removal.++**Say to your agent:** *"Explain Memorable's data sharing before enabling it."*++## Architecture++```mermaid+flowchart LR+ Repo[Markdown brain repos] --> Sync[Sync and parse]+ Sync --> Engine{Brain engine}+ Engine -->|default| PGLite[(PGLite)]+ Engine -->|shared or large| Postgres[(Postgres and pgvector)]+ Agent[AI agent or operator] --> Surface[CLI or MCP]+ Surface --> Ops[Contract-first operations]+ Ops --> Search[Hybrid retrieval]+ Ops --> Graph[Typed graph traversal]+ PGLite --> Search+ Postgres --> Search+ PGLite --> Graph+ Postgres --> Graph+ Search --> Synthesis[Synthesis and gap analysis]+ Graph --> Synthesis+ Synthesis --> Answer[Cited answer]+```++**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines the 140+ methods both engines implement; CLI and MCP server are generated from one source.++**Canonical files preserve file-backed knowledge.** Your brain repo holds Markdown that GBrain indexes for retrieval; deletes in git become soft-deletes in the database. DB-only pages, unresolved facts, revision history, and operational state need a separate database backup. See the [system-of-record contract](docs/architecture/system-of-record.md). You can publish public subsets, share team mounts, and run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).++**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).++**Why the graph matters.** Vector search finds similar text; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md); [entity recall](docs/guides/entity-recall.md).++## Troubleshooting++Start with `gbrain doctor`. For database access failures, use `gbrain engine status --probe` and `gbrain db-repair` before changing configuration.++**Say to your agent:** *"Check my brain health and show me the repair plan before changing anything."*++[Troubleshooting reference](docs/guides/troubleshooting.md) covers installation recovery, PGLite startup, embedding dimensions, locks, import failures, and sync.++## Docs++- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end+- [`docs/guides/bootstrap.md`](docs/guides/bootstrap.md) — the persistent-personal-agent bootstrap contract (interview, identity files, hooks, private repo, security posture, uninstall), plus local harness mode (`gbrain bootstrap harness`) for wiring framework-spawned Claude Code/Codex sessions to a running serve+- [`docs/what-schemas-unlock.md`](docs/what-schemas-unlock.md) — why schemas matter: 7 killer use cases, the structural argument for typed page kinds, the agent-co-curates pattern+- [`docs/schema-author-tutorial.md`](docs/schema-author-tutorial.md) — 5-minute walkthrough: fork the bundled pack, add a custom type, backfill existing pages, prove the wiring via `gbrain whoknows`+- [`docs/architecture/`](docs/architecture/) — system design, topologies, retrieval theory+- [`docs/guides/`](docs/guides/) — how-to runbooks (google connect, open loops, sub-agent routing, minion deployment, skill development, brain-first lookup, idea capture, diligence ingestion)+- [`docs/integrations/`](docs/integrations/) — connecting external data sources (voice, email, calendar, embedding providers)+- [MCP task guide](docs/mcp/README.md) — deployment and per-client setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)+- [MCP administration](docs/mcp/ADMIN.md) — owner dashboard access, client registration, OAuth, permissions, and token recovery+- [Evals](docs/eval/) and [research](docs/research/) — methods and results+- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)+- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents+- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)+- [`CONTRIBUTING.md`](CONTRIBUTING.md) — contributor guide, test discipline, eval-capture mode+- [`SECURITY.md`](SECURITY.md) — install-path trust model, self-update integrity, automated scanning, OAuth threat model, hardening defaults++## Contributing++Run `bun run test` for the fast loop, `bun run verify` for the pre-push gate, `bun run ci:local` to run the full Docker-backed CI stack locally. Detailed test discipline in [`CONTRIBUTING.md`](CONTRIBUTING.md).++Community PRs are batched into release waves rather than merged one-by-one — see the community-PR-wave process in [`docs/RELEASING.md`](docs/RELEASING.md). Contributor attribution stays attached via `Co-Authored-By:` trailers. We credit every accepted contribution in [`CHANGELOG.md`](CHANGELOG.md).++If you find a bug or want a feature: open an issue first. Quick fixes (typo, doc bug, obvious regression) can go straight to a PR. Anything touching schema, retrieval ranking, MCP protocol, or the security boundary needs a design discussion in the issue first.++## License + credit++MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production brain behind my AI agents.++Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).++Community PR contributors are credited in `CHANGELOG.md` per release. Attribution for the retired provider's historical embedding and reranker integration remains in Git at `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.mdindex edac7f146c..6bbb280413 100644--- a/docs/architecture/RETRIEVAL.md+++ b/docs/architecture/RETRIEVAL.md@@ -528,4 +528,155 @@ distinct sessions) is a filed follow-up. `applyAutocut`cross-encoder rerank-score cliff, before the limit slice, first page only.Never-empty failsafe (`minKeep`), no-op when fewer than 2 results carry afinite rerank score (covers the fail-open reranker path), and alias-hop exact-matches are preserved through the cut. Weak-top floor: when the top rerank\ No newline at end of file+matches are preserved through the cut. Weak-top floor: when the top rerank+score is below `minTopScore` (default 0.35, config `search.autocut_min_top`),+cliff trimming is skipped entirely — a low-confidence list returns the full+cluster for the caller to judge instead of collapsing to one result. Knobs:+per-call `SearchOpts.autocut` → `search.autocut` / `search.autocut_jump` /+`search.autocut_min_top` config → mode bundle. The pre-autocut pool can be+captured for offline floor replay: `hybridSearch` exposes an eval-only+`onRerankPool` hook that fires with the exact pool `applyAutocut` is about to+cut (post-rerank, post alias-hop / exact-lookup, unscored injections included),+`gbrain eval longmemeval --capture-pool` records it per row as `rerank_pool`,+and `scripts/replay-autocut-floor.ts` replays every floor — including `off` —+from that single capture, validating byte-for-byte against the live decisions+before any other cell is read.++Each stage is testable in isolation. Each stage is replaceable. The whole pipeline is < 1ms of orchestration cost; the latency budget goes to the upstream HTTP calls (embedding, rerank) and the index scans.++## Evidence delivery: whole evidence after ranking++Ranking decides which pages matter; the reader still needs enough of each page+to answer. `return_unit` (`chunk`, `window`, `section`, `page`, `auto`; default `auto`)+adds a stage after ranking, cache and capture, and before output+redaction and snippet capping, shared by `search`, `query`, `recall` and+`think` (via `think.return_unit`). It groups the ranked hits by page, reads+every needed neighbor chunk in ONE batched, page_id-keyed query that+re-authorizes each page under the caller's current scope, sanitizes each+page's complete body before slicing, locates the hit chunks in it (so chunk+overlap never duplicates text), cuts the requested unit around the hits,+and packs blocks by rank into the token budget with a per-page floor so lower+ranked sessions keep their matching span. The strict protected-body sanitizer+runs on the whole body first, so delivered evidence never contains more than+`get_page` returns to the same caller. The default `auto` expands only+conversation pages (by page type or `chat/` / `conversations/` slug) to the+whole page and leaves every other hit its ranked chunk; with no conversation+hit, or with `chunk`, the stage does not run and responses are byte-identical. The measured motivation: on 400 held-out+LongMemEval questions whole sessions answered 361 against 253 for top-5+chunks, while neighbor windows reached only 285–292, so `auto` gives+conversations exactly the `page` unit. `auto` itself answered 445 of 500+LongMemEval-S questions against 312 for chunks (development data), and the+preregistered sealed check was inconclusive at a ceiling (149 against 147 of+150); see `docs/evidence-delivery.md` for the numbers and the token cost. A lexical+excerpt selector that failed its evaluation is recorded in+`docs/eval/ANSWER_PACKET_RESULTS.md`. Contract, algorithms and latency:+[`docs/evidence-delivery.md`](../evidence-delivery.md).++## How to verify on your own brain++```bash+# Reproduce the public LongMemEval receipt (cleaned S split, k=5) like-for-like:+# --by-type prints strict recall_all@5 (headline) and recall_any@5 (diagnostic);+# the like-for-like row pins the reranker and autocut off.+gbrain eval longmemeval ~/datasets/longmemeval/longmemeval_s_cleaned.json \+ --retrieval-only --top-k 5 --by-type --no-trajectory --mode balanced --reranker off --autocut off+# The shipped default path (what balanced/tokenmax run): --reranker on --autocut off++# Capture your own queries and replay against retrieval changes+export GBRAIN_CONTRIBUTOR_MODE=1+# ... use gbrain normally ...+gbrain eval export > before.ndjson+# ... change something ...+gbrain eval replay --against before.ndjson++# A/B retrieval strategies on a labeled fixture+gbrain eval --qrels qrels.json --config-a baseline.json --config-b balanced.json+```++The current measured LongMemEval result (95.53% session-level `recall_all@5` on the release default path, 449/470, and 93.40% with the reranker off, 439/470; cleaned S split, 470 scored questions, k=5, measured 2026-09-06 by the in-repo harness), its per-type table, every measured ranker arm and the judged answer-accuracy row live in [`docs/eval-bench.md`](../eval-bench.md#public-benchmarks-longmemeval).++Methodology + metric glossary in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md).++## Restricted salience++Remote reads default to the `world` take holder when no grant is supplied; an+explicit empty grant permits no takes. Counts and average weights use only+permitted active takes. Stored emotional weight contributes zero because it+combines all holders. Recent-salience inclusion uses `updated_at` with the+same recency formula as unrestricted local reads, which use their full+formulas. Deleted, quarantined and archived contributors are excluded+before ranking, limits and anomaly-baseline aggregation. Default remote page+privacy also excludes private pages; its documented opt-outs do not widen+take-holder permissions.+++## Chunk rebuilds after upgrading++**Say to your agent:** *"Check whether my search index is ready, and repair+code metadata without spending on embeddings."* Search and query report+`projection_readiness` for empty and nonempty results. `projection_pending`+means visible pages lack a current revision seal; `projection_status_unknown`+means the diagnostic could not establish readiness. Neither is a clean miss.+`projection_by_design` means the only unsealed pages in scope are+protected-OCR images (or pages of an archived source), which stay out of the+index by design: nothing is pending and no repair applies.+The CLI names these states; `--json` retains its result-array format and sends+incompleteness notices to stderr. MCP carries them in `_meta.retrieval`.++A resident `gbrain serve` drains queued Markdown and code rebuilds+without provider calls. Code repair can also run through the current owner:+`gbrain reindex-code --force --no-embed`. Rebuilds preserve only exact,+provenance-compatible vectors: each vector records the embedding input it was+built from (`content_chunks.embedding_input_hash`: column, model, dimensions,+wrapping tier and wrapped text), and a rebuild keeps it only when the current+page would produce the same input, so an unchanged contextual page keeps its+vectors and a synopsis-mode body edit nulls every synopsis-tier chunk. Vectors+written before that record existed are grandfathered on pages whose mode+is still NULL; contextual-mode repair and reindex stamp compatible raw inputs+when moving those pages to explicit `none`. An explicit `none` page may have+inherited a title-wrapped vector, so a rebuild clears unstamped vectors there,+and switching from title or synopsis to `none` clears active text vectors+immediately. Genuine old raw vectors on explicit `none` pages may need a+one-time re-embed; it never starts automatically. Remaining NULL vectors+still need an explicitly authorized `gbrain embed --stale` run. A text-ready+index is not a promise that every page has a vector. Diagnostics do not+disclose private or foreign-source pending pages and never start repair+themselves.++Markdown chunk creation applies the strict protected-body sanitizer before+splitting text. For remote reads, all existing chunks of every page kind are+withheld until a successful rebuild records the current chunker version. Public+pages require this rebuild too; trusted local chunk reads remain available. Body or+chunk changes invalidate that record until the next successful rebuild. Re-importing+unchanged content (`gbrain sync --full`, `gbrain import`) re-seals such a page+without a page write or journal admission. While pages are withheld, remote+`search` / `query` report `degraded: [safe_index_pending]` on empty and partial+results alike (the MCP empty-result block names it) instead of a clean or complete+answer, and `gbrain doctor` counts the withheld markdown and code pages and points+at `gbrain repair safe-chunks`, which re-seals them on any brain, managed included.+Direct page reads continue to use current source and visibility policy plus body+sanitization.++Run rebuild commands from a local installation on the brain host; thin clients+cannot rebuild the host's indexes.+`gbrain reindex --markdown --dry-run --no-embed` previews the existing rebuild.+`gbrain reindex --markdown --no-embed` rebuilds without embedding calls, replacing+previous vectors; use `gbrain embed --stale` later to restore semantic retrieval+when provider usage is authorized. The regular reindex path rebuilds and embeds.+Code pages use `gbrain reindex-code --force --no-embed`. Existing image indexes+require reimporting the source files; images whose OCR contains protected+sections remain unavailable to remote chunk retrieval. Schema migrations 160+and 161 install projection statistics and the pending-projection lookup index;+they do not rebuild vector indexes or call an embedding provider.++`query --since` includes its exact lower boundary. An exact `--until` timestamp+is inclusive without losing fractional precision; a date-only upper bound+includes the entire day, implemented as an exclusive next-midnight boundary.+Legacy direct engine `afterDate` and `beforeDate` bounds remain strict unless+their explicit inclusivity flags are set.+++Optional code-graph expansion is omitted from remote search. The six dedicated+code-inspection operations are also temporarily local-only; see the+[MCP surface runbook](../operations/mcp-surface-runbook.md#temporary-code-inspection-availability).+These restrictions are separate from the chunk rebuild requirement.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 0a69d5136c..91211a4ea0 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/bun-floor.ts` — the Bun floor of an upgrade target (#5855): `readBunLinkTarget` (`git fetch`, the fetched upstream SHA, `package.json` at that SHA; the swap fast-forwards to that SHA), `readPackageTarget` (`package.json` at the ref a global install's `github:` spec names, default branch when unpinned; ClawHub reads the canonical default branch), `parseReleasePackage` (only a `>=X.Y.Z` `engines.bun` is a floor; any other shape is unreadable), `readHostBun` (the lower of the `bun` on PATH and the Bun at `process.execPath`) and `evaluateBunFloor` (the refusal text with path, and a path-free copy for the self-upgrade audit). `BUN_FLOOR_EXIT_CODE` (78) marks a `gbrain upgrade` refused for the floor, which the autopilot channel treats as a hold. Tests: `bun-floor.test.ts`, `autopilot-bun-floor.test.ts`, `upgrade-bun-link-arc.serial.test.ts`.- `src/core/orphan-policy.ts` — the shared orphan-reporting policy (`gbrain orphans`, doctor's orphan ratio, `get_health`): convention constants plus per-brain `orphans.exclude_prefixes` / `orphans.exclude_slugs` overrides. Two renderers over the same constants: `shouldExcludeFromOrphanReporting(slug, overrides, meta)` (TypeScript) and `orphanExclusionSql(alias, overrides)` (a never-NULL SQL predicate; every list value is a bound parameter, only the identifier-checked alias is spliced; regexes are spelled for Postgres's engine: ASCII digits, `.` stops at line terminators). Quarantine stays outside the SQL predicate. Parity pinned on a generated slug/type corpus by `test/orphan-policy-sql-parity.test.ts` and its Postgres arm in `test/e2e/engine-sql-health-parity.test.ts`.-- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables` plus absent `missingSearchStatistics`) and repair kind `planner-stats` keep working. `readExpressionIndexesWithoutStats` (both engines; lhf wave 2 item 6) lists expression indexes on the hot tables with entries (index `reltuples > 0`) but no `pg_stats` row under their own name, skipping indexes whose statistics the role cannot see; every `maybeRefreshPlannerStats` reason except `first_read` analyzes their tables (a search never pays the probe), doctor names each with its own reason, and the repair plans their tables (on Postgres the opera... (line truncated to 2000 chars)+- `src/core/planner-stats.ts` + `src/core/planner-stats-schema.ts` — F4b row-delta ANALYZE for PGLite (no autovacuum). Migration f4_planner_stats (`sqlFor.pglite` only; a Postgres no-op) adds `planner_stats_deltas` / `planner_stats_state` and AFTER STATEMENT transition-table triggers on pages, links, facts, takes, content_chunks and timeline_entries, so modification counts commit or roll back with the data and survive restarts. `maybeRefreshPlannerStats(engine, reason)` ANALYZEs tables whose pending count exceeds max(500, 10% of reltuples) (or that have rows but no pg_stats) and publishes a watermark read before the ANALYZE, so a concurrent modification stays pending; checks are throttled to one per 2 s per engine. Call sites: PGLite planner-sensitive reads (`beforePlannerRead`, deferring a table whose last ANALYZE exceeded `planner.first_read_budget_ms`), import and managed sync every `import.analyze_every_pages`, stale link drains and the `extract --source db` links walk of at least `LINK_DRAIN_ANALYZE_MIN_STALE` (500) pages through `plannerStatsForLinkDrain` (first page, then the same cadence; `link_transitions`/`link_relationships`, no deltas, with `links`), the cycle after extract_facts, the consumer idle tick, and `refreshProjectionStatistics` (full ANALYZE publishes every watermark). `planner.auto_analyze=false` / `GBRAIN_PLANNER_AUTO_ANALYZE=0` disables them all. Doctor `planner_stats_stale` (Postgres: `pg_stat_user_tables` plus absent `missingSearchStatistics`) and repair kind `planner-stats` keep working. `readExpressionIndexesWithoutStats` (both engines; lhf wave 2 item 6) lists expression indexes on the hot tables with entries (index `reltuples > 0`) but no `pg_stats` row under their own name, skipping indexes whose statistics the role cannot see; every `maybeRefreshPlannerStats` reason except `first_read` analyzes their tables (a search never pays the probe), doctor names each with its own reason, and the repair plans their tables (on Postgres the operator-run recovery). Guide: `docs/guides/planner-stats.md`. Tests: `test/planner-stats*.test.ts` (`planner-stats-link-drain.test.ts` EXPLAINs the drain's snapshot read), `test/e2e/planner-stats-postgres.test.ts`.- `src/core/timeline-grading.ts` — `loadTimelineGradedPredicate(engine)`: which pages the 15-point brain_score timeline component grades (#5828). `engine-sql/health.ts` applies the predicate per page type to the linkable groups; `gradeTimelinePages` (re-exported by `orphan-policy.ts`) keeps the linkable (orphan-policy) pages whose active-pack primitive is `entity` or `temporal` (aliases resolve to the canonical type); undeclared and untyped types, and every page when no pack resolves, stay graded. Labelled "timeline density (entity and event pages)" in doctor and `get_health` output. Pinned by `test/brain-score-timeline-grading.test.ts`.- `src/core/cjk.ts` — Single source of truth for CJK detection. Exports `CJK_RANGES_REGEX`, `CJK_SLUG_CHARS` (character-class fragment for embedding inside other regexes), `SLUG_WORD_CHARS` + `PAGE_SLUG_SEG` (the shared slug-grammar fragments) and `SLUG_VARIATION_SELECTORS_RE` (the Mn-invisible emoji-VS16 / ideographic-IVS strip that BOTH `sync.ts:slugifySegment` and its twin `link-extraction.ts:normalizeBasename` apply, so the two grammars cannot drift on selectors), `CJK_SENTENCE_DELIMITERS` (`。!?`), `CJK_CLAUSE_DELIMITERS` (`;:,、`), `CJK_DENSITY_THRESHOLD = 0.30`, `hasCJK(s)`, `isCJKDominant(s)` (the ONE density test: CJK chars ≥ 30% of non-whitespace chars), `countCJKAwareWords(s)` (routes through `isCJKDominant` — English docs with one Japanese term stay whitespace-tokenized; Chinese-dominant docs get char-counted), `escapeLikePattern(s)` (escapes `%`, `_`, `\\` for `ILIKE ... ESCAPE '\\'`), and `cjkMatchTerms(query)` (whitespace terms with a trailing Korean particle stripped by `stripKoreanParticle`, longest particle first, stem kept only at 2+ characters; the one term list every CJK keyword builder matches, so the count, the keyword pages and the chunk search agree). BMP-only ranges (Han / Hiragana / Katakana / Hangul Syllables). Consumers: `expansion.ts`, `sync.ts:slugifySegment`, `operations.ts:validatePageSlug + validateFilename`, `chunkers/recursive.ts:countWords + DELIMITERS + extractTrailingContext` (the overlap extractor branches on `isCJKDominant` so it counts the same unit `countWords` does), `pglite-engine.ts:searchKeyword + searchKeywordChunks`.@@ -40,7 +40,7 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. `largePageBodyFilter(alias)` is its SQL twin (`body_bytes` of a segmented page, else the body columns' `octet_length`) and `pageBudgetLimitedFilter(alias)` the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying (PR 2 fix lane J2; test `test/large-pages/held-budget-shrink.test.ts`). The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.-- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation) while they are large (`pageBudgetLimitedFilter`); a page edited down to 1 MiB or under is unmetered and its row is ignored there, in `listBudgetLimitedPages` and in `pageSizeState`, and applies again if the page grows back. `listBudgetLimitedPages` (no row cap with `limit: null`) feeds `gbrain embed --held`; the hold and cap lines `meterPageBatch` prints name a per-page approve with a concrete N (held-embedding-action.ts), and `sizeStateLines` names `gbrain embed --held --dry-run --source <id>`. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines... (line truncated to 2000 chars)+- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation) while they are large (`pageBudgetLimitedFilter`); a page edited down to 1 MiB or under is unmetered and its row is ignored there, in `listBudgetLimitedPages` and in `pageSizeState`, and applies again if the page grows back. `listBudgetLimitedPages` (no row cap with `limit: null`) feeds `gbrain embed --held`; the hold and cap lines `meterPageBatch` prints name a per-page approve with a concrete N (held-embedding-action.ts), and `sizeStateLines` names `gbrain embed --held --dry-run --source <id>`. Its ledger prices a free local recipe at $0 (#6847). #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). A segmented page is sized by `body_bytes` and re-indexed from its materialized snapshot (`materializedSnapshot`, Wave B PR 2; `test/large-pages/oversized-backfill-segmented.test.ts`). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview commands; after a run that held pages, `approvals` carries one approve per source with a concrete N (`budgetLimitedReport`).- `src/core/held-embedding.ts` — held embedding budgets surfaced (#6803 part 3) and approvable on every provider (#6847). `readBudgetLimited` counts held and capped large pages with chunks still waiting (active vector column, `embedded_at`, signature drift; no row cap), by source; `budgetLimitedReport` renders the one phrase plus one approve Action per source (most pending chunks first). Consumers: `gbrain embed --stale` (`noteBudgetLimited`, a `budget_limited` field and one line), the embed-backfill job (`budgetLimitedField`; never a failure or stall input), doctor `partial_embedding` (`budgetLimitedFinding`, its own registry entry), the oversized backfill receipt. `heldEmbedArgv`: `--held --dry-run` lists every source (exit 0); `--max-usd` across several sources without `--source` refuses `invalid_params`. `heldApprovalUsd`: an explicit `--max-usd N` on `--slugs`/`--held` is the hold approval on any provider, refused before release with `embedding_unavailable` or `no_pricing`; `--yes` never approves. Tests: `test/held-embedding-budgets.test.ts` (+ Postgres wrapper), `test/held-embedding-approval.test.ts`, `test/held-embedding-printed-commands.serial.test.ts`.- `src/core/held-embedding-action.ts` — leaf module for the held-embedding approval: `approvalAmount` (N = `derivedCapUsd` of the higher of the run-meter and per-page ledger estimates, so x1.5 with a $0.25 floor; $0.01 and no paid/egress consent on a free recipe), `ledgerPricePerMTok`, `heldApproveAction` (argv, source-scoped dry-run preview and verify, `ask_user`), `heldPreviewCommand` (the every-source listing opts out of routing's source pin) and `budgetLimitedPhrase`.@@ -67,3 +67,16 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/npm-squat-check.ts` — classifies `gbrain` PATH entries as real, foreign npm package, broken, or unknown for doctor's `npm_squat` check, plus the `gbrain` package directories under the global roots the caller passes (`<npm root -g>/gbrain`, `$BUN_INSTALL/install/global/node_modules/gbrain`): an unrelated global package no PATH entry reaches is appended after the PATH entries, so it warns when no real gbrain is on PATH and is noted when one wins. A warn caused by an unrelated package carries a structured `fix`: remove it (`npm uninstall -g gbrain`, or `bun remove -g gbrain` for Bun's global dir; always `ask_user`), then, only when no real gbrain remains on PATH, `bun install -g github:garrytan/gbrain#latest-stable` and the #218 schema recovery `gbrain apply-migrations --yes --no-autopilot-install`. On Windows it normalizes Git Bash/MSYS drive paths (`/c/...` → `C:/...`) and tries the native `.exe` suffix before reporting a broken entry; non-Windows classification keeps the original single-candidate behavior. Pinned by `test/npm-squat-check.test.ts` and, through the CLI, `test/doctor-npm-squat.test.ts`.- `src/core/operations-descriptions.ts` — Constants module for tool descriptions. Pinned via `test/operations-descriptions.test.ts`. Houses `GET_RECENT_SALIENCE_DESCRIPTION`, `FIND_ANOMALIES_DESCRIPTION`, `GET_RECENT_TRANSCRIPTS_DESCRIPTION` plus `LIST_PAGES_DESCRIPTION`, `QUERY_DESCRIPTION`, `SEARCH_DESCRIPTION`. Stable surface for the Tier-2 LLM routing eval — keeping them here keeps the test from binding to whatever is in `operations.ts` at test-run time. Description-edit checklist for `QUERY_DESCRIPTION` / `SEARCH_DESCRIPTION` (and any other text a starter tool serves): no pre-merge lane carries a provider key, so run the routing eval yourself with `GBRAIN_TEST_KEEP_PROVIDER_KEYS=1 bun test test/e2e/salience-llm-routing.test.ts` (Haiku 4.5 at temperature 0, ≈ $0.04; a `search`/`query` rewrite can move concept phrasings such as "all the people that work on X" from `query` to `search` without any unit test noticing), then `bun test test/mcp-schema-budget.test.ts` (per-tool budget, 25,000-character served starter ceiling and its 200-character headroom floor, `MINIMUM_GUIDANCE` pins), `test/operations-descriptions.test.ts`, `test/mcp-instructions-batching.test.ts`, and regenerate with `bun run build:operation-manifest`, `bun run scripts/generate-tool-catalog.ts` and `GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-goldens.test.ts`. Both descriptions say that people/companies/projects by topic are `query` work: Haiku 4.5 otherwise reads "all the X that do Y" as a `search` list lookup (measured at temperature 1: 28/80 concept phrasings misrouted without the clause, 1/80 with it).++- `src/core/operations.ts` — Contract-first operation contract, served through a ~300-line assembly façade: the op definitions live in the domain modules under `src/core/ops/` (next entry) and are spread into the single exported `operations` array here; the registration loop replaces each handler with `withOutputRedaction(op)`, so a `'retrieval'` op's output is redacted on every dispatch path (see `src/core/ops/contract.ts`); the shared contract types (`src/core/ops/contract.ts`) and the security/scope layer (`src/core/ops/context.ts`) are re-exported through this file, so every import path below resolves through the façade unchanged. The rest of this entry describes the surface as consumers see it. Fresh same-source graph mutations (`add_link`, `add_timeline_entry`) preflight each endpoint against the scalar write source via `requireWritablePage` (`ops/context.ts`); `add_timeline_entry` resolves an authorized stored request before that fresh-write preflight so exact replay retains its outcome after page purge or recreation: a page readable only from another granted source returns endpoint-specific `permission_denied` naming the boundary, pages outside the caller's `get_page` visibility scope stay `page_not_found` (a soft-deleted foreign page is indistinguishable from absence), and a mutation-time engine miss — the typed `PageMissingError` from `src/core/engine-errors.ts`, thrown by both engines' single-statement endpoint resolution — is reclassified into the same envelope by `instanceof`, never message matching. Exports upload validators `validateUploadPath`, `validatePageSlug`, `validateFilename`, plus `matchesSlugAllowList(slug, prefixes)` (glob matcher: `<prefix>/*` matches recursive children; bare `<prefix>` matches exact only). `OperationContext.remote` is a REQUIRED field flagging untrusted callers; `OperationContext.allowedSlugPrefixes` is the trusted-workspace allow-list set by the dream cycle; `OperationContext.auth?: AuthInfo` is threaded through HTTP dispatch for scope enforcement in `serve-http.ts` before the op runs. OAuth `whoami` exposes the authenticated `AuthInfo.sourceId` and `AuthInfo.allowedSources` grants as `source_id` and `federated_read`; absent grants serialize fail-closed as `null` and `[]`, while local, legacy, and stdio response shapes stay unchanged. `enforceSubagentSlugFence(ctx, slug, opName)` is the shared fail-closed subagent write fence: when `viaSubagent` and `allowedSlugPrefixes` is set, the slug must match the allow-list; else the legacy `wiki/agents/<id>/...` namespace check applies. Both `put_page` and `add_timeline_entry` (subagent-allowlisted) route through it. Auto-link/timeline hooks are skipped for remote-owned subagents even with explicit prefixes; only local subagents qualify as trusted workspaces. `enforceClientSlugFence(ctx, slug, opName)` is the OAuth-client write fence: when `ctx.auth.boundSlugPrefixes` is present (threaded from `oauth_clients.bound_slug_prefixes` at token-verification time), every direct slug-mutating write op — `put_page`, `delete_page`, `restore_page`, `add_tag`, `remove_tag`, `add_link`/`remove_link` (`from` endpoint only; linking TO a readable page is a reference), `add_timeline_entry`, `revert_version`, `put_raw_data` — rejects out-of-prefix slugs with `permission_denied`, BEFORE each op's dry-run short-circuit. Direct writes use the shared boundary-aware prefix rules; empty-array binding is deny-all (fail-closed); no auth / no binding = no fence. The match rule itself lives in the exported `slugUnderBoundPrefixes(prefixes, slug)` so non-op write surfaces reuse it verbatim. It is BOUNDARY-AWARE (a prefix matches whole segments, so `emp-alice` does not admit `emp-alice-2/…`), lowercases both sides (stored slugs are lowercased by `validateSlug`, so comparing the caller's raw string would let a mixed-case slug commit and only then trip the resolved-slug re-check), accepts BOTH the trailing-slash and the `<prefix>/*` glob spelling via `normalizeSlugPrefix` (direct and delegated fences share normalization while storing independently reviewed spans), and ignores empty-string prefixes. `assertValidSlugPrefixes` (`oauth-provider.ts`) rejects empty, whitespace-bearing, non-lowercase, and boundary-less entries at registration and rescope. `submit_agent` validates tools and namespaces against the independently stored `bound_tools`, `delegated_slug_prefixes`, and `delegated_namespace` grants. It normalizes accepted prefixes for `matchesSlugAllowList` and rejects explicit empty remote tool or prefix overrides. Workers interpret explicit empty tool lists as no tools, with defaults reserved for absent trusted-local bindings. `put_page` deduplication may resolve another slug by content hash or `frontmatter.id`, but returns an authorized read-only `duplicate` outcome. The original target's revision never authorizes publication to that other page. Preparation and guarded validation recheck the duplicate's current authority, readability, concrete page identity and revision; neither its canonical fields nor its file are written. OAuth and delegated subagent fences still apply, and denials do not name an inaccessible duplicate. Pinned by `test/put-page-dedup-fence.test.ts`. `CLIENT_FENCED_WRITE_OPS` + `enforceBoundClientOpAllowList(auth, op)` are the fail-closed companion, applied once in `src/mcp/dispatch.ts` (the choke point both MCP transports share): a slug-bound client calling ANY `write`/`admin` op not on the allow-list gets `permission_denied`. This covers the ops that write by a key other than a slug and therefore cannot be fenced — `extract_entities`/`extract_facts` (mutate `people/*`, `companies/*`), `forget_fact` (numeric fact id, crosses sources), `ontology_propose` — and makes a write op added later denied-by-default instead of silently unfenced. `think` is on the allow-list because remote callers cannot persist from it. Pinned by `test/client-slug-fence.test.ts` and over-the-wire by `test/qm-provisioning.test.ts`. Every `Operation` carries `scope?: 'read' | 'write' | 'admin'` + `localOnly?: boolean`; `think` is read-scoped for OAuth/MCP because remote callers have `save`/`take` forced off before persistence, while local CLI can still persist via `remote:false`; `sync_brain`, `file_upload`, `file_list`, `file_url` are `admin + localOnly` (rejected over HTTP). Four trust-boundary call sites (`put_page` allowlist, file_upload trust-narrowing, submit_job protected-name guard, auto-link skip) use FAIL-CLOSED semantics: `ctx.remote === false` for trusted-only sites, `ctx.remote !== false` for "untrust unless explicit-false" — anything not strictly `false` is treated as remote (so a read+write OAuth token over HTTP MCP cannot submit `shell` jobs). `sourceScopeOpts(ctx)` encodes the source-scoped read precedence ladder — federated array (`ctx.auth.allowedSources`) wins over scalar (`ctx.sourceId`/`ctx.auth.sourceId`) over nothing; every read-side op handler routes through it so a source-bound OAuth client can't see neighboring sources via `search`/`query`/`list_pages`/`get_page`/`find_experts`/query's image path, plus the by-slug reads `get_tags`/`get_links`/`get_backlinks`/`get_timeline`/`get_chunks` (chunks follow the same ladder as `get_page`, so a federated grant that can open a page can read its chunks — and the chunk payload never carries embedding vectors) (and `get_page`'s tag fetch, which resolves against the concrete page's own `source_id`). `get_tags` resolves `readPolicyOpts`, so an untrusted caller gets no tags for a `visibility: private` page (unless the operator's private-pages opt-out is on) or a soft-deleted page. `assertExplicitSourceLive(ctx, sourceIdParam)` is the async companion for the ops that accept a per-call `source_id` (`get_page`, `list_pages`, `search`, `query`): called right after `federatedSearchScope` (so the grant check has already run and it can only name a granted source), an explicit id with no live unarchived `sources` row throws `unknown_source` instead of silently scoping the read to an empty source — the CLI's `--source` existence rule applied to the op path; `__all__` and an omitted param skip it. `linkReadScopeOpts(ctx, scope?)` is the link-read sibling for `get_links`/`get_backlinks`/`traverse_graph` (`scope` defaults to `sourceScopeOpts(ctx)`; the link ops pass their resolved per-call `federatedSearchScope`): a link row references three pages (from/to/origin), and the engine's federated (`sourceIds[]`) branch scopes ALL THREE while its scalar (`sourceId`) branch scopes only the near endpoint (by design — trusted internal callers like `reconcileLinks` and back-link validators call the engine with a scalar scope and need the cross-source view). For an UNTRUSTED remote caller (`ctx.remote !== false`) carrying only a scalar scope it promotes that scope to a single-element `sourceIds:[id]`, routing them through the all-endpoint branch so a far/origin slug from outside the grant isn't disclosed; a federated array passes through unchanged and trusted local CLI (`ctx.remote === false`) keeps the scalar cross-source view. `thinkSourceScopeOpts(ctx)` maps the same precedence ladder onto `runThink`'s public options (`allowedSources`/`sourceId`) so the `think` op's gather and trajectory stages inherit the caller's source grant. `put_page` submits through `submitPageMutation` to the durable journal. Existing-page replacements require `expected_revision` or explicit `force`; omission is create-only. The designated owner publishes under native root and database guards, with recoverable file replacement and a terminal receipt committed with canonical state. Accepted contention returns `write_pending` after the synchronous wait; admission failure does not fabricate a queued receipt. Git and embeddings report separate effect outcomes. Trusted-local `delete_page` with `purge: true` uses the same journal, revision and recovery protocol: artifact-removal failure preserves the prior row, and exact replay retains the original terminal outcome after deletion. Link provenance surface: `add_link` (`gbrain link`/`link-add`) + `remove_link` (`gbrain unlink`/`link-rm`) expose `link_source`/`link_type`; `add_link` rejects the reconciliation-managed built-ins via `MANAGED_LINK_SOURCES` (`markdown`/`frontmatter`/`mentions`/`wikilink-resolved`) and defaults omitted provenance to `'manual'` (the engine's own default stays `'markdown'` for internal callers); `list_link_sources` (`gbrain link-sources`, read) lists provenances via `sourceScopeOpts`. CLI aliases register through `cliHints.aliases` (collision-guarded in `src/cli.ts`).+- `src/core/ops/contract.ts` — the shared operation types (`Operation`, `OperationContext`, `ParamDef`, `OperationError`). `Operation.outputRedaction: OutputRedactionPolicy` is REQUIRED, so typecheck forces every op to say how its response treats stored text: `'retrieval'` (the whole response passes `redactRetrievalOutput`, uncapped, assignment rule on), `{ retrieval: { localVerbatim: [...] } }` (same, but the named top-level keys stay raw for the trusted local CLI, `ctx.remote === false`; the memory verbs' `facts`), `{ exempt: reason }` (deliberately raw with a one-line reason: page reads `get_page`/`fetch`/`get_chunks`/`get_raw_data`/`get_versions`, skill-catalog files, admin job ops) or `'no_stored_text'` (returns no page, chunk, fact, take or transcript text). `operations.ts` applies the policy at registration (`withOutputRedaction` in `src/core/search/output-redaction.ts`); `test/retrieval-op-redaction.test.ts` sweeps every classified op with a planted secret. `whoami` and the HTTP `gbrain://capabilities` resource choose `oauth` vs `legacy` through `authTransport`, which trusts the verifier-set `AuthInfo.principal` and falls back to the `gbrain_cl_` id prefix only when no principal is present.+- `src/core/ops/write-inference.ts` — the write-inference contract: what model work a write may do and when. `WriteInference` = `none` (no model call before commit) | `embedding` (may embed before commit, never generative) | `async_derived` (none/embedding before commit; may queue generative work after commit, e.g. facts extraction) | `opt_in_media` (generative before commit only under a user opt-in, image OCR) | `explicit_llm` (the op is a model call: think, extract_facts, submit_agent) | `non_content` (admin state). `writeInferenceOf(op)` resolves the inline `Operation.writeInference`, then `OP_WRITE_INFERENCE`, then `none`, so an unclassified op is held to the strictest promise and never breaks the build. `CLI_WRITE_INFERENCE` lists CLI writers that are not ops. `ZERO_GENERATIVE_BEFORE_COMMIT` = none/embedding/async_derived. Pinned by `test/op-write-inference.test.ts` and checked at runtime by `test/write-path-zero-llm.serial.test.ts` + `test/write-path-no-egress.serial.test.ts` (docs/TESTING.md#write-inference-tests).++- `src/core/pg-access-classify.ts` — Postgres ACCESS-error classifier, the reason/remediation layer of the db-availability loop (detect → `GBRAIN_DB_ACCESS` marker → skills/db-repair → `gbrain db-repair`). `RESIDENT_POOL_FLOOR` (6) is the documented minimum `GBRAIN_POOL_SIZE` for a long-running process; `pool_exhausted` recommends it plus fewer processes (docs/ENGINES.md#pool-sizing), and `serve`'s boot-deadline line uses it. Two entry points, one diagnosis type: `classifyPgAccessError(err, ctx?)` for thrown errors (data-driven ordered `REASON_ROWS` table, first match wins — specific rows before general ones) and `diagnoseDbConfig(ctx)` for errorless config-plane reasons (`no_url`, `env_shadowed` — there is no error object at connectEngine's no-config exit or under an env shadow; never fake one). The `PgAccessReason` union (16 reasons) is APPEND-ONLY — a compatibility surface once the bundled skills are in the wild, like progress phase names; consumers switch exhaustively with a `never` sentinel. Invariants: `message`/`remediation` are ALWAYS pre-redacted (safe for transcripts/receipts/issues); every `fix` descriptor is hardcoded or derived from the CURRENT config URL (`deriveSessionPoolerUrl`/`deriveDirectUrl`), never from anything parsed out of error text, and `run_command` argv[0] is always `gbrain`; **remediation copy has exactly ONE home: this module** — db-repair, doctor, and MCP dispatch all render `diagnosis.remediation`, skills reference the command and never duplicate recipe text. TWO-AXIS design note (mirrored in `retry-matcher.ts`'s header — do not "fix" one side to match the other): retry-matcher answers "should I retry?" and deliberately treats `password authentication failed` as retryable (auth race during DNS failover); this module answers "what went wrong?" and reports the same error `auth_failed` + `transient: false` — both correct on their own axis; unknown reasons defer `transient` to `isRetryableConnError`. Also exports `DB_ACCESS_MARKER_PREFIX`/`formatDbAccessMarker` (the single source of the marker literal that skills/db-repair pins in both `description:` and `triggers:`; the action a reader takes is ALWAYS the hardcoded `gbrain db-repair`, never a command parsed from the marker), `isDbAccessFailure` (the ACCESS-class subset fail-open recall arms use to tell "one arm degraded" from "the DB is down"), and Supabase enrichment `{pooler, projectRef, pausedSuspect}` (paused projects aren't a distinct wire error — modeled as a suspicion flag on dns/timeout/tenant reasons). Pinned by `test/pg-access-classify.test.ts`.++- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.++- `src/core/reindex-consent.ts` — W4.5 paid-consent gate for `reindex --markdown`: `estimateReindexSpend` (pages after `--limit`, estimate over pending pages' text via `countPending`; null when unpriced) and `requireReindexConsent` (null when `embedWouldSpend` is false; else `requireConsent` with effect `paid`, page count and estimate in `user_message`/`est_usd`, `--yes` command and `--dry-run` preview; `interactive: false` never prompts; a user cap below the estimate throws `cost_cap_exceeded`). Called by `runReindex` (CLI, `upgrade`, job handler) and `jobs submit reindex` (stores `jobSpendAuthorization`; so does the search-mode switch prompt's TTY yes). `minions/handlers/reindex.ts` runs paid work only with `job.spend.record`; a refusal is a terminal `confirmation_required`. Tests: `test/reindex-consent.test.ts`.++- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI: `brain_id` (a resume against another brain refuses), `max_usd` (reused by `--resume` without `--max-usd`), `include_repairs`, cumulative `spent_usd` and the original step `manifest` (`job_ids`, `repair_kinds`); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus `test/recovery-layer.test.ts`.+- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; a `spends: 'llm'` kind's step is `paid` and adds `llm_usd` (its paid-model estimate) to `est_usd_cost`, which is null when either part is unpriced; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. A `spends: 'llm'` step never reserves its model estimate: it runs under the caller's tracker (never a nested `stepBudget` tracker) with what is left of the cap as `maxLlmUsd`, then `charge`s the part of its actual `cost.llm_usd` that `spentUsd()` did not already rise by during the step, so model spend counts once; a step its allowance stopped is `budget_exhausted`. `planRepairSteps`, `runRepairSteps` and `runRemediation`'s `repairs.registry` take stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. `manual-only.ts`: `isManualOnlyStep` (by job name: `unify-types`, `extract-takes-from-pages`; fail-closed without `protected`) is the one predicate the onboard renderer's `manual_only` label, `runRemediation` and autopilot's targeted dispatch share; the runner never submits such a step, initially or after a recheck, keeps its cost out of the `--max-usd` estimate and returns `manual_only_skipped` entries (`code`, `why`, rendered `fix`: `gbrain jobs submit <job> [--params <json>] --follow`, actor `user`, `consent: ['paid']` when paid; `queued_jobs` names rows of that job still waiting or active). Plan and run preview through `planRepairStepsReport` (the strict `planRepairSteps` still propagates the first error), so a kind whose preview throws is reported as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted, then capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.diff --git a/docs/guides/capabilities.md b/docs/guides/capabilities.mdindex c8de136452..c31c5dee7e 100644--- a/docs/guides/capabilities.md+++ b/docs/guides/capabilities.md@@ -1,6 +1,6 @@# Capabilities-**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The cross-encoder reranker is on in `balanced` and `tokenmax`, off in `conservative` — the default is Voyage `rerank-2.5` on `VOYAGE_API_KEY`; without the key search fails open in fusion order and `gbrain search modes` / `gbrain doctor` say so (ask your agent *"check whether my brain's reranker is actually running"*). Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page. **Say to your agent... (line truncated to 2000 chars)+**Hybrid search.** Vector (HNSW on pgvector) + BM25 keyword + reciprocal-rank fusion + source-tier boost + intent-aware query rewriting. Three named search modes (`conservative`, `balanced`, `tokenmax`) bundle the cost/quality knobs into a single config key. Live cost/recall comparisons in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). The install picker default-applies `tokenmax` (it recommends `conservative` for Haiku-class subagent tiers or keyless setups); a brain with `search.mode` unset resolves to `balanced` at query time. The cross-encoder reranker is on in `balanced` and `tokenmax`, off in `conservative` — the default is Voyage `rerank-2.5` on `VOYAGE_API_KEY`; without the key search fails open in fusion order and `gbrain search modes` / `gbrain doctor` say so (ask your agent *"check whether my brain's reranker is actually running"*). Per-query graph signals notice when a top result is a hub for THAT query (adjacency boost), is corroborated across team brains (cross-source boost), or is being crowded out by weak chunks from a chatty session (session demote). Run `gbrain search "<query>" --explain` to see per-stage attribution: base score, every boost that fired, what it multiplied. `gbrain doctor` ships a `graph_signals_coverage` check; `gbrain search stats` shows fire counts and failure breakdowns. Vector retrieval pools the best chunk per page, so a page surfaces on its strongest evidence instead of losing to a neighbor on one weak chunk. Queries that match a page's title phrase or a declared free-text alias (`gbrain reindex --aliases` backfills existing pages) get boosted to the page they name. Every result carries an `evidence` tag (why it matched) and a `create_safety` hint (`exists` / `probable` / `unknown`) so an agent decides whether a page already exists instead of guessing from a raw score. `gbrain search diagnose "<query>" --target <slug>` traces which retrieval layer surfaces (or misses) a page. **Say to your agent:** *"Tune my retrieval"* — *"What search mode am I running?"* — *"Why did this page rank first?"* (your agent runs `gbrain search --explain`).**Self-wiring knowledge graph.** Trusted local `put_page` extracts supported references without LLM calls when auto-linking is enabled. Remote MCP writes save references as text without inline graph extraction; a post-commit `links` effect adds plain mention edges to existing pages the writer can see, and typed edges rely on stdio's best-effort startup/idle sweeps, explicit host maintenance or authorized `add_link`. See [memory boundaries](memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Typed edges (`attended`, `works_at`, `invested_in`, `founded`, `advises`, `mentions`, …). Multi-hop traversal via `gbrain graph-query`. On the 145 synthetic BrainBench relationship questions, turning on relationship retrieval in the production search pipeline raised mean R@5 from 0.6626 to 0.7241, better on 45 of 435 question runs and worse on none ([September 9, 2026 refresh](https://github.com/garrytan/gbrain-evals/blob/main/docs/benchmarks/2026-09-09-retrieval-refresh.md#production-relationship-retrieval-one-switch)). The R@5 0.9791 in the same report is `graph-oracle-parse`, an adapter that knows the four question templates in advance: an upper bound, not a product score or a universal retrieval guarantee. **Say to your agent:** *"Who works at acme-example?"* — *"What's the relationship between fund-a and widget-co?"* — *"What connections does alice-example have?"* **Obsidian-style vaults:** bare `[[note-name]]` wikilinks that point across folders — you wrote `[[struktura]]` but the page lives at `projects/struktura.md` — resolve by basename once you opt in with `gbrain config set link_resolution.global_basename true`. Off by default; `gbrain doctor` tells you how many edges you'd gain before you flip it. See [migrating an Obsidian vault](../../INSTALL_FOR_AGENTS.md#step-45-wire-the-knowledge-graph).@@ -28,9 +28,9 @@ The command is idempotent (re-running with the same language is a no-op for vect**Say to your agent — the phrasebook.** You never invoke a skill by name; you say what you want and your agent routes it. Every skill declares its trigger phrases in its frontmatter, and [`skills/RESOLVER.md`](../../skills/RESOLVER.md) is the full human-readable phrasebook — one table of "when you say this, this skill fires." A taste: *"Ingest this PDF"* (media-ingest) — *"What's happening today?"* (briefing) — *"Fill my brain"* (cold-start) — *"Brain health"* / *"check backlinks"* (maintain — either phrase routes there) — *"Is my brain set up right?"* (gbrain-advisor) — *"Did the restart break anything?"* (smoke-test) — *"Run this as a background task"* (minion-orchestrator). If you're ever unsure what to say, ask your agent: *"What can my brain do?"* and have it read the resolver back to you.-**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. Measured 2026-09-06 at gbrain v0.48.4.0 by this command on LongMemEval-S (cleaned Sept-2025 revision, 500 questions, 470 scored after the 30 abstention questions are dropped as the official scorer does), k=5, single run: on the release default path (`balanced`: `voyage:rerank-2.5` on, autocut off) strict session-level `recall_all@5` of **95.53%** (449/470), meaning every gold session landed inside the top-5 distinct retrieved sessions, retrieval only, no reader model; with the reranker off, the like-for-like row against systems that run no reranker, **93.40%** (439/470). The looser any-hit `recall_any@5` was 99.79% / 98.72% and is reported as a diagnostic, not a headline. The reranker-off row reproduces the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) runner's 2026-09-02 receipt (438/470; 469 of 470 rows agree per question), where the per-row receipts live. Paired against reranker-off hybrid the reranker gains 18 questions and loses 8; the default that shipped before v0.48.4.0 (reranker on with autocut) scored 379/470, because autocut kept the best session and dropped the rest on multi-part questions, which is why autocut is now off. One warning that the ranker wave re-measured rather than removed: an explicit LLM multi-query expansion experiment performed worse at k=5 — 255/470 `recall_all@5` (paired +3 / −187 vs hybrid) at the legacy weighting, 394/470 with the new `search.expansion_variant_budget` knob at its smallest pre-registered value, still 43 questions behind plain hybrid on the held-out decision set — so the bundles keep the legacy weighting, these results describe the expanded experiment rather than every call in a named mode. `gbrain query` does not expand by default in any mode (`search.expansion true` turns it on; `--expand` / `--no-expand` win), while `search` a... (line truncated to 2000 chars)+**Eval framework.** `gbrain eval longmemeval` runs the public [LongMemEval](https://huggingface.co/datasets/xiaowu0162/longmemeval) benchmark against your hybrid retrieval. Measured 2026-09-06 at gbrain v0.48.4.0 by this command on LongMemEval-S (cleaned Sept-2025 revision, 500 questions, 470 scored after the 30 abstention questions are dropped as the official scorer does), k=5, single run: on the release default path (`balanced`: `voyage:rerank-2.5` on, autocut off) strict session-level `recall_all@5` of **95.53%** (449/470), meaning every gold session landed inside the top-5 distinct retrieved sessions, retrieval only, no reader model; with the reranker off, the like-for-like row against systems that run no reranker, **93.40%** (439/470). The looser any-hit `recall_any@5` was 99.79% / 98.72% and is reported as a diagnostic, not a headline. The reranker-off row reproduces the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) runner's 2026-09-02 receipt (438/470; 469 of 470 rows agree per question), where the per-row receipts live. Paired against reranker-off hybrid the reranker gains 18 questions and loses 8; the default that shipped before v0.48.4.0 (reranker on with autocut) scored 379/470, because autocut kept the best session and dropped the rest on multi-part questions, which is why autocut is now off. One warning that the ranker wave re-measured rather than removed: an explicit LLM multi-query expansion experiment performed worse at k=5 — 255/470 `recall_all@5` (paired +3 / −187 vs hybrid) at the legacy weighting, 394/470 with the new `search.expansion_variant_budget` knob at its smallest pre-registered value, still 43 questions behind plain hybrid on the held-out decision set — so the bundles keep the legacy weighting, these results describe the expanded experiment rather than every call in a named mode. `gbrain query` does not expand by default in any mode (`search.expansion true` turns it on; `--expand` / `--no-expand` win), while `search` and memory verbs never expand; see [search modes](search-modes.md). `gbrain eval export` + `gbrain eval replay` capture real queries and replay them against code changes (set `GBRAIN_CONTRIBUTOR_MODE=1`). `gbrain eval cross-modal` cross-checks an output against the task using three different-provider frontier models. `gbrain eval retrieval-quality` runs NamedThingBench, which hard-gates the named-thing retrieval families (title-substring, alias-synonym, generic-to-named, multi-chunk-dilution) so a regression in "find the page this query names" fails CI loudly. `gbrain eval brainbench` runs the cross-harness memory conformance suite: know-to-ask, push precision/recall, write-back fidelity, and cross-session continuity, scored per harness seam (your OpenClaw's production pipeline plus Claude Code and Codex injection contracts) against a committed 141-fixture synthetic corpus — hermetic by default (in-memory PGLite, no keys, seconds), and CI gates every PR against master's committed baseline. Methodology in [`docs/eval/BRAINBENCH.md`](../eval/BRAINBENCH.md); search-mode methodology in [`docs/eval/SEARCH_MODE_METHODOLOGY.md`](../eval/SEARCH_MODE_METHODOLOGY.md). **Say to your agent:** *"Run a regression check on retrieval"* (your agent runs `gbrain eval brainbench`); *"Run the public LongMemEval benchmark like-for-like"* (no skill backs this one; your agent runs `gbrain eval longmemeval <longmemeval_s_cleaned.json> --retrieval-only --top-k 5 --by-type --no-trajectory --mode balanced --reranker off --autocut off`. That in-repo command is the reproduction path for the 93.40% row (and the 2026-09-02 receipt's 93.19%): its `--by-type` summary reports strict `recall_all@5` with any-hit as the diagnostic, joins on the dataset's raw session ids, and drops the 30 abstention questions as the official scorer does; `--reranker on --autocut off` runs the shipped default path instead — autocut is off in every mode since rule R2 — and `--reranker on --autocut on --capture-pool` reproduces the capture the autocut replay was scored from).-**How it measures up.** One distinction decides every memory-benchmark comparison: strict `recall_all@5` counts a question only when every gold session lands in the top 5, while loose any-hit counts it when a single one does, and 300 of LongMemEval-S's 470 scored questions need two or more sessions. On the strict metric, on this dataset, gbrain scores 93.40% with the reranker off (v0.48.4.0, 2026-09-06, 470 scored; 93.19% on the 2026-09-02 sibling receipt) and 95.53% on the release default path with `voyage:rerank-2.5` on (same run, same 470); the k=5 ceiling is 99.4% because 3 questions carry 6 gold sessions. The closest strict comparisons we could find: MemPalace publishes only any-hit (96.6% / 98.4%), but rescoring its committed per-question rankings against the official gold labels gives 85.7% for its raw vector setup and 90.0% with an LLM reranker in the loop (our recomputation, their data); ContextFit publishes an All@5 of 87.45% (411/470) whose rerank layer reads gold labels during the run, so we mark it loosely comparable. The 94 to 96% figures quoted for Mastra, Mem0, MemCog, Supermemory and others are LLM-judged answer accuracy, a different race that scores the reader and judge as much as the memory. gbrain's first judged number, published with v0.48.4.0: 86.6% (433/500; 95% CI 83.6–89.6) with the default `anthropic:claude-sonnet-4-6` reader over the full text of the retrieved sessions and a gpt-4o judge running the official prompts; 449 of the 470 non-abstention questions had every gold session retrieved and the reader converted 396 of them, so the gap to those vendor numbers is in the answering layer and the protocols differ, so no comparison is claimed in either direction. Pure vector on the same corpus scored 93.8% (v0.48.0.0 receipt), so the hybrid layer is roughly neutral on this benchmark and earns its keep elsewhere. Full table with sources and our read of each: [gbrain-evals `docs/comparison-systems.md`](https://github.com/garrytan/gbrain-evals/bl... (line truncated to 2000 chars)+**How it measures up.** One distinction decides every memory-benchmark comparison: strict `recall_all@5` counts a question only when every gold session lands in the top 5, while loose any-hit counts it when a single one does, and 300 of LongMemEval-S's 470 scored questions need two or more sessions. On the strict metric, on this dataset, gbrain scores 93.40% with the reranker off (v0.48.4.0, 2026-09-06, 470 scored; 93.19% on the 2026-09-02 sibling receipt) and 95.53% on the release default path with `voyage:rerank-2.5` on (same run, same 470); the k=5 ceiling is 99.4% because 3 questions carry 6 gold sessions. The closest strict comparisons we could find: MemPalace publishes only any-hit (96.6% / 98.4%), but rescoring its committed per-question rankings against the official gold labels gives 85.7% for its raw vector setup and 90.0% with an LLM reranker in the loop (our recomputation, their data); ContextFit publishes an All@5 of 87.45% (411/470) whose rerank layer reads gold labels during the run, so we mark it loosely comparable. The 94 to 96% figures quoted for Mastra, Mem0, MemCog, Supermemory and others are LLM-judged answer accuracy, a different race that scores the reader and judge as much as the memory. gbrain's first judged number, published with v0.48.4.0: 86.6% (433/500; 95% CI 83.6–89.6) with the default `anthropic:claude-sonnet-4-6` reader over the full text of the retrieved sessions and a gpt-4o judge running the official prompts; 449 of the 470 non-abstention questions had every gold session retrieved and the reader converted 396 of them, so the gap to those vendor numbers is in the answering layer and the protocols differ, so no comparison is claimed in either direction. Pure vector on the same corpus scored 93.8% (v0.48.0.0 receipt), so the hybrid layer is roughly neutral on this benchmark and earns its keep elsewhere. Full table with sources and our read of each: [gbrain-evals `docs/comparison-systems.md`](https://github.com/garrytan/gbrain-evals/blob/main/docs/comparison-systems.md).**Brain consistency.** `gbrain eval suspected-contradictions` samples retrieval pairs, layered date pre-filter, query-conditioned LLM judge, persistent cache. Surfaces conflicts between takes + facts the agent has written. It is paid, opt-in LLM work with its own schedule: the dream cycle only reads the latest probe run, it never starts one (see the [recommended nightly cadence](../eval-bench.md#recommended-nightly-cadence)). **Say to your agent:** *"What did the last contradiction probe surface?"* — *"Fact-check what we have on acme-example"* (claim-by-claim live-source verification) — or have your agent run `gbrain eval suspected-contradictions` directly.diff --git a/llms-full.txt b/llms-full.txtindex 815b520f5c..89f2d060ce 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3270,6 +3270,227 @@ timeout of at least 10 s. The wrapper and its rules:- **Live sync** (every 15 min): `gbrain sync --repo ~/brain && gbrain embed --stale`— or `gbrain sync --watch` for a continuous loop. Safe on keyless brains:+ a bare `gbrain embed --stale` exits 0 with a stderr note when embeddings+ are disabled, so the chain doesn't break.+- **Health gate** (daily): `gbrain autopilot --status` — exit 0 fresh (or+ nothing installed), 1 needs attention (stale heartbeat, never ran, or+ paused), 2 the daemon took itself out of rotation. Filesystem-only, so it+ works during DB outages.+- **Auto-update** (daily): `gbrain check-update --json` (tell user, never auto-install).+- **Dream cycle** (nightly): `gbrain dream` runs the 8-phase overnight maintenance cycle.+ Entity sweep, citation fixes, memory consolidation, plus overnight conversation+ synthesis and cross-session pattern detection. One cron-friendly command. This is what+ is an opt-in maintenance capability. See `docs/guides/cron-schedule.md` for the+ full protocol.+- **Weekly**: `gbrain doctor --json && gbrain embed --stale`++## Step 8: Integrations++Run `gbrain integrations list`, then `gbrain integrations show <id>` for one recipe.+Each recipe is a self-contained installer. It tells you what credentials to ask for, how to validate, and what cron+to register. Ask the user which integrations they want (email, calendar, voice, Twitter).++Verify: `gbrain integrations doctor` (after at least one is configured)++## Step 9: Verify++For memory-only installs, run the install check from the+[first-run protocol](docs/protocol/AGENT_OPERATOR_v1.md#first-run): the read-only+smoke check `gbrain doctor --only harness_wiring --json` (it reads the+registration and runs initialize, tools/list and one `recall` against it), then+`remember` an install-check marker with+provenance `install-check`, ask the user to restart the harness, `recall` it in+the new session and `forget` it. Never save a made-up fact about the user.+Also save one user-approved generic test note or fact with+provenance, retrieve it, exit the CLI, and retrieve it again in a new process.+Check exact keyword retrieval as well as `remember`/`recall`. A process reopen+proves local persistence, not a new conversation in the native harness; verify+that separately after the user authorizes harness setup.++Read `docs/GBRAIN_VERIFY.md` for the checks covering capabilities the user enabled.+Run live-sync checks only when sync was configured; do not install services or+enable paid providers to make optional checks pass.++Once verification passes and the brain has content, run the activation probe:++```bash+gbrain onboard --check --json+```++See "The onboard surface" below for what the recommendations mean and the+consent gates around unattended remediation.++<!-- BEGIN multi-agent-rules (identical in AGENTS.md, BOOTSTRAP_FOR_AGENTS.md and INSTALL_FOR_AGENTS.md; bun run check:shared-tree-git) -->+## Multi-agent rules for a shared brain checkout++Several agents, crons and hooks often commit to one brain checkout on the same+machine. In such a checkout:++1. **Commit and push with one command, naming your files:**+ `scripts/brain-commit-push.sh "<msg>" <paths>`, or+ `gbrain git commit-push -m "<msg>" -- <paths>` when the brain has no helper.+ It takes the checkout's writer lock, commits only those paths, merges remote+ commits without touching anyone else's files, and fails loudly if the push+ does not land.+2. **Bring remote commits in with `--pull`** (`scripts/brain-commit-push.sh --pull`+ or `gbrain git commit-push --pull`) at session start and before a batch of writes.+3. **On a non-zero exit, read the code.** Retry once on `commit_lock_busy`.+ Stop and relay to the user on `integrate_conflict` (they choose which+ version wins) and on `writer_coordinator_required` (a managed brain: save+ pages with `put_page` instead). `pushed_checkout_lagging` is a success.+<!-- gbrain-allow-shared-tree-git-begin: the forbidden commands, named so agents avoid them -->+4. **Never run** `git pull --rebase`, `git stash`, `--autostash`, `git add -A`,+ `git commit -a`, `git reset --hard` or `git push --force` there, and never+ fall back to them when the command fails. Never delete `.git/rebase-merge`+ before saving its autostash with `git stash store`.+<!-- gbrain-allow-shared-tree-git-end -->++Outcomes, conflict recovery, a stuck rebase and the lock contract for host+daemons: [docs/guides/shared-checkout-git.md](docs/guides/shared-checkout-git.md).+<!-- END multi-agent-rules -->++## Upgrade++When an upgrade crosses v0.60.5.0, confirm a database backup exists before+upgrading, upgrade every process that writes to the brain, then follow the+[v0.60.5.0 steps](skills/migrations/v0.60.5.0.md): one full `gbrain doctor`,+then preview `gbrain repair` and apply only after the user agrees+([repair guide](docs/guides/repair.md)). Across v0.60.6.0, also follow the+[one-time timeline prune and slug-collision steps](skills/migrations/v0.60.6.0.md). Across v0.60.11.0, preview+`gbrain repair contextual-mode` and rebuild PGLite vector indexes after a crash+repair ([steps](skills/migrations/v0.60.11.0.md)).++When an upgrade crosses v0.53.0.0, follow the+[mechanical shared-skills migration](skills/migrations/v0.53.0.0.md) on the host,+starting with `gbrain apply-migrations --dry-run --json`. Stop/exclude old writers,+review writer status, and use the checklist's action-specific `--admin-intent`+and reviewed `--expected-state` when activating shared skills. Quiescence flags+are attestations, not process shutdown or administration authority. Preserve+operational DB and content backups, consent, edited files, and grant fences.+DB-only export, explicit regrants, parent/client reconnection, and native+verification are separate stages; report pending stages rather than claiming+the whole migration completed.++On a host with resident processes (autopilot, a jobs worker, a serve), pause+autopilot (`gbrain autopilot pause`), wait until no job is active, run+`gbrain upgrade` on every install (it restarts every gbrain process onto the+new build and verifies one build runs, or refuses `restart_refused` naming the+process it cannot restart), check that each process reports the new version,+then `gbrain autopilot resume`. A production brain follows the stable channel+(`gbrain config set self_upgrade.channel stable`)+([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume),+[stable channel](docs/guides/upgrades-auto-update.md#stable-channel)).++For memory-only upgrades, keep services and paid reindexing opt-in. The same+command works for `bun install -g` and `git clone + bun link` installs:++```bash+GBRAIN_NO_AUTOPILOT_INSTALL=1 GBRAIN_NO_REEMBED=1 gbrain upgrade --no-autopilot-install+```++On a clone it fetches, checks the new release's Bun floor, fast-forwards to+exactly the checked commit and runs `bun install`; a bare `git pull` skips the+check and can leave a release the host's Bun cannot start. When the floor is+above the host's Bun, the upgrade refuses with `requires Bun >=<floor>` and+changes nothing (exit 78): run `bun upgrade`, then the same upgrade command+again. Pass `--no-bun-floor-check` only after checking the target yourself+when the floor cannot be read (offline). See+[Bun floor](docs/guides/upgrades-auto-update.md#bun-floor).++The autopilot opt-out skips installation and service rewrites, including package+postinstall hooks; it does not skip other migrations. Keep the environment form+on the package-manager command because hooks run before `post-upgrade`.+`GBRAIN_NO_REEMBED=1` separately skips the potentially paid reindex step.+For an existing service deployment, review its migration guide instead of+assuming memory-only options are the desired maintenance policy. Verify a known+keyword query after upgrading, not just the version string.++Then read `skills/migrations/v<NEW_VERSION>.md` (published at+`https://github.com/garrytan/gbrain/blob/master/skills/migrations/v<NEW_VERSION>.md`;+also read any intermediate versions you skipped) and run any backfill or verification steps it lists. Skipping+this is how features ship in the binary but stay dormant in the user's brain.++**v0.32.3 search modes (one-time upgrade prompt):** if the user's brain was+created before v0.32.3, `gbrain post-upgrade` prints a banner including the+9-cell cost matrix (mode × downstream model) preceded by `[AGENT]` markers.+**Do NOT silently move past the banner.** Present the matrix to the operator+verbatim, ask which mode they want (recommended default: `tokenmax` to preserve+v0.31.x retrieval shape), then run `gbrain config set search.mode <mode>`. See+Step 3.5 above for the full ask-the-user protocol — the upgrade path uses the+same matrix and same default.++If the brain was created before v0.12.0, run+`gbrain extract links --source db && gbrain extract timeline --source db` to+backfill the graph layer (see Step 4.5 above).++If the brain is Postgres- or Supabase-backed and was created before v0.12.2,+the `v0_12_2` migration runs `gbrain repair-jsonb` automatically during+`gbrain post-upgrade` to fix double-encoded JSONB columns (PGLite brains+no-op). If wiki-style imports from before v0.12.2 were truncated by a+`splitBody` bug, run `gbrain sync --full` after upgrading to rebuild+`compiled_truth` from source markdown.++## The onboard surface++`gbrain onboard` is gbrain's activation surface.+Once your brain has any content, run `gbrain onboard --check --json` to+see structured recommendations across 5 brain-health axes (orphans,+stale embeddings, entity link coverage, timeline coverage, takes count).++**On first connect (after `gbrain init`):**+```bash+gbrain onboard --check --json+```+The JSON envelope (`schema_version: 1`) carries `recommendations[]` with+`apply_policy` per item: `auto_apply` (safe to run unattended),+`prompt_required` (needs explicit user consent), or `manual_only`+(pack upgrade, paid takes bootstrap: the user runs it).++**After every `gbrain upgrade`:**+```bash+gbrain onboard --check --json+```+New versions may surface new opportunities. The post-upgrade banner+nudges the user when it runs, but agents should re-probe as a hygiene+step regardless.++**Unattended remediation (cron / autopilot):**+```bash+gbrain onboard --auto --max-usd 5+```+Refuses without `--max-usd N`. Never runs `manual_only` items; it+lists them in `manual_only_skipped`. The autopilot daemon also consults+onboard recommendations on its tick — no explicit agent action needed+for the autonomous path.++**Remote / federated brain installs (MCP):**+The `run_onboard` MCP op (admin scope) lets thin-client agents probe+brain health + drive remediation over OAuth-authenticated MCP. Protected+LLM-bearing handlers (synthesize, patterns, consolidate, takes-bootstrap,+contextual_reindex_per_chunk) require the additional `run_protected_onboard`+scope — admin alone is insufficient. The MCP op returns+`skipped_missing_scope[]` listing what would have run with the right+grants.++**Privacy + consent gates:**+- `gbrain takes extract --from-pages` sends concept/atom/lore/briefing/+ writing/originals page content to your configured chat model (default+ Anthropic Haiku). Refuses to run unless `takes.bootstrap_enabled=true`+ is set in config AND `--yes` is passed. Two-gate opt-in by design.+- Autopilot's auto-apply tier for takes-bootstrap is `manual_only`+ (do not bypass).++**Suppress nudges in CI / scripted environments:**+```bash+export GBRAIN_NO_ONBOARD_NUDGE=1+```+Init and upgrade notices do not skip themselves when there is no terminal:+non-interactive callers get the onboarding nudge, the init decision bundle and+the post-upgrade summary as `[AGENT]` blocks (or the `notices` key under+`--json`), and stdio MCP sessions get the post-upgrade summary once as a notice+block. `GBRAIN_NO_ONBOARD_NUDGE=1` silences the onboarding nudges and the+post-upgrade summary everywhere. Only the remote-brain identity banner stays+TTY-only (`GBRAIN_BANNER=1` forces it, `GBRAIN_NO_BANNER=1` hides it).---@@ -5141,6 +5362,81 @@ Data flowing into the brain. Each integration is a recipe — markdown + setup hMemorable stores replayable procedures from coding sessions. Its relay is off bydefault and requires an explicit disclosure/consent step; it can send redacted+traces and query text off-machine. Read the [Memorable integration guide](docs/memorable-agents.md)+for installation, data flow, per-harness limitations, and removal.++**Say to your agent:** *"Explain Memorable's data sharing before enabling it."*++## Architecture++```mermaid+flowchart LR+ Repo[Markdown brain repos] --> Sync[Sync and parse]+ Sync --> Engine{Brain engine}+ Engine -->|default| PGLite[(PGLite)]+ Engine -->|shared or large| Postgres[(Postgres and pgvector)]+ Agent[AI agent or operator] --> Surface[CLI or MCP]+ Surface --> Ops[Contract-first operations]+ Ops --> Search[Hybrid retrieval]+ Ops --> Graph[Typed graph traversal]+ PGLite --> Search+ Postgres --> Search+ PGLite --> Graph+ Postgres --> Graph+ Search --> Synthesis[Synthesis and gap analysis]+ Graph --> Synthesis+ Synthesis --> Answer[Cited answer]+```++**Two engines, one contract.** PGLite (Postgres 17 via WASM, zero-config, default) for personal brains up to ~50K pages. Postgres + pgvector (Supabase or self-hosted) for shared / large / multi-machine deployments. The contract-first `BrainEngine` interface in [`src/core/engine.ts`](src/core/engine.ts) defines the 140+ methods both engines implement; CLI and MCP server are generated from one source.++**Canonical files preserve file-backed knowledge.** Your brain repo holds Markdown that GBrain indexes for retrieval; deletes in git become soft-deletes in the database. DB-only pages, unresolved facts, revision history, and operational state need a separate database backup. See the [system-of-record contract](docs/architecture/system-of-record.md). You can publish public subsets, share team mounts, and run thin-client setups pointing at a colleague's brain server. Topologies in [`docs/architecture/topologies.md`](docs/architecture/topologies.md).++**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).++**Why the graph matters.** Vector search finds similar text; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md); [entity recall](docs/guides/entity-recall.md).++## Troubleshooting++Start with `gbrain doctor`. For database access failures, use `gbrain engine status --probe` and `gbrain db-repair` before changing configuration.++**Say to your agent:** *"Check my brain health and show me the repair plan before changing anything."*++[Troubleshooting reference](docs/guides/troubleshooting.md) covers installation recovery, PGLite startup, embedding dimensions, locks, import failures, and sync.++## Docs++- [`docs/INSTALL.md`](docs/INSTALL.md) — every install path, end to end+- [`docs/guides/bootstrap.md`](docs/guides/bootstrap.md) — the persistent-personal-agent bootstrap contract (interview, identity files, hooks, private repo, security posture, uninstall), plus local harness mode (`gbrain bootstrap harness`) for wiring framework-spawned Claude Code/Codex sessions to a running serve+- [`docs/what-schemas-unlock.md`](docs/what-schemas-unlock.md) — why schemas matter: 7 killer use cases, the structural argument for typed page kinds, the agent-co-curates pattern+- [`docs/schema-author-tutorial.md`](docs/schema-author-tutorial.md) — 5-minute walkthrough: fork the bundled pack, add a custom type, backfill existing pages, prove the wiring via `gbrain whoknows`+- [`docs/architecture/`](docs/architecture/) — system design, topologies, retrieval theory+- [`docs/guides/`](docs/guides/) — how-to runbooks (google connect, open loops, sub-agent routing, minion deployment, skill development, brain-first lookup, idea capture, diligence ingestion)+- [`docs/integrations/`](docs/integrations/) — connecting external data sources (voice, email, calendar, embedding providers)+- [MCP task guide](docs/mcp/README.md) — deployment and per-client setup (Claude Desktop, Code, Cursor, ChatGPT, Perplexity, Cowork)+- [MCP administration](docs/mcp/ADMIN.md) — owner dashboard access, client registration, OAuth, permissions, and token recovery+- [Evals](docs/eval/) and [research](docs/research/) — methods and results+- [`docs/ethos/`](docs/ethos/) — philosophy (thin harness, fat skills, markdown as recipes, origin story)+- [`AGENTS.md`](AGENTS.md) — entry point for non-Claude agents+- [`CLAUDE.md`](CLAUDE.md) — entry point for Claude Code (deep operating context)+- [`CONTRIBUTING.md`](CONTRIBUTING.md) — contributor guide, test discipline, eval-capture mode+- [`SECURITY.md`](SECURITY.md) — install-path trust model, self-update integrity, automated scanning, OAuth threat model, hardening defaults++## Contributing++Run `bun run test` for the fast loop, `bun run verify` for the pre-push gate, `bun run ci:local` to run the full Docker-backed CI stack locally. Detailed test discipline in [`CONTRIBUTING.md`](CONTRIBUTING.md).++Community PRs are batched into release waves rather than merged one-by-one — see the community-PR-wave process in [`docs/RELEASING.md`](docs/RELEASING.md). Contributor attribution stays attached via `Co-Authored-By:` trailers. We credit every accepted contribution in [`CHANGELOG.md`](CHANGELOG.md).++If you find a bug or want a feature: open an issue first. Quick fixes (typo, doc bug, obvious regression) can go straight to a PR. Anything touching schema, retrieval ranking, MCP protocol, or the security boundary needs a design discussion in the issue first.++## License + credit++MIT. I built GBrain to run my OpenClaw and Hermes deployments — the production brain behind my AI agents.++Origin story: [`docs/ethos/ORIGIN.md`](docs/ethos/ORIGIN.md).++Community PR contributors are credited in `CHANGELOG.md` per release. Attribution for the retired provider's historical embedding and reranker integration remains in Git at `6040075c6cb95be5881cc2e1b76ef7d71f4e5d29`. Voyage AI for the asymmetric-encoding recipe template. Ramp Labs for the search quality improvements lineage.---