{"owner":"garrytan","repo":"gbrain","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["AGENTS.md","llms.txt","CLAUDE.md"],"files":{"AGENTS.md":"# Agents working on GBrain\n\nThis is your install + operating protocol. Claude Code reads `./CLAUDE.md` automatically.\nEveryone else (Codex, Cursor, OpenClaw, Aider, Continue, or an LLM fetching via URL):\nstart here.\n\n> **Becoming someone's persistent personal agent** (identity + memory + private repo)?\n> Follow [`BOOTSTRAP_FOR_AGENTS.md`](./BOOTSTRAP_FOR_AGENTS.md) — the `gbrain bootstrap`\n> flow — instead of the plain install below, then come back here for the operating\n> protocol. Connecting to an EXISTING remote brain from a laptop agent?\n> `gbrain connect https://your-host/mcp --token gbrain_xxx --install` (see the MCP\n> table in [`README.md`](./README.md)).\n\n## Install (5 min)\n\n<!-- npm-trap + #218 recovery: canonical copy lives in README.md (\"Install\" warning) — sync edits. -->\n1. Install gbrain via Bun (the canonical path):\n   ```bash\n   curl -fsSL https://bun.sh/install | bash\n   export PATH=\"$HOME/.bun/bin:$PATH\"\n   bun install -g github:garrytan/gbrain\n   ```\n   If `bun install -g` aborts or `gbrain doctor` reports `schema_version: 0`,\n   the CLI prints a recovery hint pointing at [#218](https://github.com/garrytan/gbrain/issues/218).\n   Run `gbrain apply-migrations --yes` to recover, or fall back to the\n   deterministic install: `git clone https://github.com/garrytan/gbrain.git ~/gbrain && cd ~/gbrain && bun install && bun link`.\n2. Init the brain: `gbrain init` (defaults to PGLite, zero-config). For 1000+ files or\n   multi-machine sync, init suggests Postgres + pgvector via Supabase.\n3. **STOP — ask the user about search mode.** `gbrain init` auto-applied a\n   default but printed a 9-cell cost matrix (mode × downstream model)\n   preceded by `[AGENT]` markers. You MUST relay the matrix to the operator\n   and confirm their choice before continuing. Cost spread between corners\n   is 25x — silent acceptance is the wrong default. See\n   [`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) Step 3.5 for the\n   exact ask-the-user protocol. Same banner fires on `gbrain post-upgrade`\n   for existing users (search modes were added in v0.32.3).\n4. Read [`./INSTALL_FOR_AGENTS.md`](./INSTALL_FOR_AGENTS.md) for the full step-by-step\n   flow (API keys, identity, cron, verification).\n\n## Read this order\n\n1. `./AGENTS.md` (this file) — install + operating protocol.\n2. [`./CLAUDE.md`](./CLAUDE.md) — orientation + resolver: architecture, cross-cutting\n   invariants, the reference map, inline ship rules. It routes to on-demand detail docs:\n   [`./docs/architecture/KEY_FILES.md`](./docs/architecture/KEY_FILES.md) (per-file index —\n   read a file's entry before editing it), [`./docs/TESTING.md`](./docs/TESTING.md) (test\n   tiers + isolation lint + E2E lifecycle), and\n   [`./docs/architecture/thin-client.md`](./docs/architecture/thin-client.md) (remote-MCP seam).\n3. [`./docs/architecture/brains-and-sources.md`](./docs/architecture/brains-and-sources.md)\n   — the two-axis mental model (brain = which DB, source = which repo in the DB). Every\n   query routes on both axes. Read before writing anything that touches brain ops.\n4. [`./skills/conventions/brain-routing.md`](./skills/conventions/brain-routing.md) —\n   agent-facing decision table: when to switch brain, when to switch source, how\n   cross-brain federation works (latent-space only; the agent decides).\n5. [`./skills/RESOLVER.md`](./skills/RESOLVER.md) — skill dispatcher. Read before any task.\n\n## Trust boundary (critical)\n\nGBrain distinguishes **trusted local CLI callers** (`OperationContext.remote = false`,\nset by `src/cli.ts`) from **untrusted agent-facing callers** (`remote = true`, set by\n`src/mcp/server.ts`). Security-sensitive operations like `file_upload` tighten filesystem\nconfinement when `remote = true` and default to strict behavior when unset. If you are\nwriting or reviewing an operation, consult `src/core/operations.ts` for the contract.\n\n## Common tasks\n\n- **Configure:** [`docs/ENGINES.md`](./docs/ENGINES.md),\n  [`docs/guides/live-sync.md`](./docs/guides/live-sync.md),\n  [`docs/mcp/DEPLOY.md`](./docs/mcp/DEPLOY.md).\n- **Debug:** [`docs/GBRAIN_VERIFY.md`](./docs/GBRAIN_VERIFY.md),\n  [`docs/guides/minions-fix.md`](./docs/guides/minions-fix.md), `gbrain doctor --fix`.\n- **Migrate / upgrade:** `gbrain upgrade` (binary self-update + schema migrations + post-upgrade prompts),\n  [`docs/UPGRADING_DOWNSTREAM_AGENTS.md`](./docs/UPGRADING_DOWNSTREAM_AGENTS.md),\n  [`skills/migrations/`](./skills/migrations/), `gbrain apply-migrations --yes` (manual schema-only).\n- **Eval retrieval changes:** capture is off by default. To benchmark a\n  retrieval change against real captured queries, set\n  `GBRAIN_CONTRIBUTOR_MODE=1`, then `gbrain eval export --since 7d > base.ndjson`\n  and `gbrain eval replay --against base.ndjson`. For public benchmark\n  coverage (LongMemEval, ground-truth scoring), `gbrain eval longmemeval\n  <dataset.jsonl>` runs against an isolated in-memory PGLite\n  per question — your `~/.gbrain` is never opened. Full guide:\n  [`docs/eval-bench.md`](./docs/eval-bench.md).\n- **Drive the brain to a target health score:** the one-command\n  loop. `gbrain doctor --remediation-plan --json` previews what would be\n  fixed; `gbrain doctor --remediate --yes --target-score 90 --max-usd 5`\n  walks a dependency-ordered plan (sync before extract, embed after\n  consolidate), re-checking score between every step, refusing to spend\n  past the cost cap. Empty brains (no entity pages) or unconfigured embedding\n  keys hit a `max_reachable_score` ceiling and bail with what's missing.\n  Three phase handlers (synthesize / patterns / consolidate) are\n  PROTECTED — only trusted local callers can submit them; MCP cannot.\n  Reference: [`docs/architecture/topologies.md`](./docs/architecture/topologies.md).\n- **Track a founder/company over time:** when an entity has\n  typed metric claims in its `## Facts` fence (`metric: mrr`, `value: 50000`,\n  `unit: USD`, `period: monthly` columns), run\n  `gbrain eval trajectory <entity-slug>` for the chronological history\n  with regressions auto-flagged, or `gbrain founder scorecard <entity-slug>`\n  for a four-signal JSON rollup (claim_accuracy / consistency /\n  growth_trajectory / red_flags). MCP op `find_trajectory` exposes the\n  same data — read scope, visibility-filtered for remote callers.\n  `gbrain think` uses this substrate automatically on temporal /\n  knowledge_update intent (default ON; flip `think.trajectory_enabled=false`\n  to opt out). Non-metric event rows (`meeting`, `job_change`,\n  `location_change`) ride through the same pipeline via `facts.event_type`;\n  pass `kind: 'event'` or `'all'` to `find_trajectory` to query them.\n- **Everything else:** [`./llms.txt`](./llms.txt) is the full documentation map.\n  [`./llms-full.txt`](./llms-full.txt) is the same map with core docs inlined for\n  single-fetch ingestion.\n\n## Before shipping\n\nEasiest path: `bun run ci:local` runs the full CI gate inside Docker (gitleaks,\nguards + typecheck, then 4-shard parallel unit + E2E against four pgvector\ncontainers plus a transaction-mode PgBouncer; unit phase keeps `DATABASE_URL`\nunset) and tears down. Use `bun run ci:local:diff` for the\ndiff-aware subset during fast iteration on a focused branch. Requires Docker\n(Docker Desktop / OrbStack / Colima) and `gitleaks` (`brew install gitleaks`).\n\nManual path: `bun test` plus the E2E lifecycle described in `./CLAUDE.md` (spin\nup the test Postgres container, run `bun run test:e2e`, tear it down).\n\nShip via the `/ship` skill, not by hand. The full release + contributor process\n(CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave) lives in\n[`./docs/RELEASING.md`](./docs/RELEASING.md); read it before shipping.\n\n## Privacy\n\nNever commit real names of people, companies, or funds into public artifacts. See the\nPrivacy rule in `./CLAUDE.md`. GBrain pages reference real contacts; public docs must\nuse generic placeholders (`alice-example`, `acme-example`, `fund-a`).\n\n## Forks\n\nIf you are a fork, regenerate `llms.txt` + `llms-full.txt` with your own URL base before\npublishing: `LLMS_REPO_BASE=https://raw.githubusercontent.com/your-org/your-fork/main bun run build:llms`.\n","llms.txt":"# GBrain\n\n> GBrain is a personal knowledge brain and GStack mod for agent platforms. Pluggable engines (PGLite default, Postgres+pgvector for scale), contract-first operations, 26 fat-markdown skills. Teaches agents brain ops, ingestion, enrichment, scheduling, identity, and access control.\n\nRepo: https://github.com/garrytan/gbrain\n\n## Core entry points\n\n- [AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/AGENTS.md): Start here if you are not Claude Code. Install order, trust boundary, skill resolver, config/debug/migration pointers.\n- [CLAUDE.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CLAUDE.md): Orientation + resolver. North Star, two axes, architecture + cross-cutting invariants, the reference map pointing at on-demand docs, and the inline ship IRON RULES.\n- [docs/architecture/KEY_FILES.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/KEY_FILES.md): Per-file index for the gbrain repo: what each src/ file does + its load-bearing invariants. The on-demand detail CLAUDE.md's reference map routes to.\n- [docs/architecture/thin-client.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/thin-client.md): The thin-client / remote-MCP / cross-modal routing seam: isThinClient detection, callRemoteTool, SSRF-hardened URL validation, per-command routing.\n- [INSTALL_FOR_AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md): 9-step agent installation.\n- [skills/RESOLVER.md](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/RESOLVER.md): Skill dispatcher. Read first for any task.\n- [README.md](https://raw.githubusercontent.com/garrytan/gbrain/master/README.md): Project overview, benchmarks, 30-minute setup.\n\n## Configuration\n\n- [docs/ENGINES.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ENGINES.md): PGLite vs Postgres trade-off and when to migrate.\n- [docs/GBRAIN_RECOMMENDED_SCHEMA.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/GBRAIN_RECOMMENDED_SCHEMA.md): MECE directory structure (people/, companies/, concepts/).\n- [docs/what-schemas-unlock.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/what-schemas-unlock.md): Why schemas matter: 7 killer use cases (4000 invisible meetings, founder ops brain, research brain, legal brain, team brain, agent-as-co-curator) + the structural argument for typed page kinds. Read this before pitching schema authoring (v0.40.7.0).\n- [docs/schema-author-tutorial.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/schema-author-tutorial.md): 5-minute walkthrough: fork the bundled pack, add a custom `researcher` type, backfill existing pages via `gbrain schema sync --apply`, prove the T1.5 wiring via `gbrain whoknows` (v0.40.7.0).\n- [docs/guides/live-sync.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/live-sync.md): Incremental markdown sync setup.\n- [docs/guides/cron-schedule.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/cron-schedule.md): Recurring job scheduling.\n- [docs/guides/minions-deployment.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-deployment.md): Deploying the gbrain jobs worker: crontab + watchdog, inline --follow, systemd/Procfile/fly.toml, upgrade checklist.\n- [docs/guides/quiet-hours.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/quiet-hours.md): Notification hold + timezone-aware delivery.\n- [docs/guides/scaling-skills.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/scaling-skills.md): Three-tier architecture for agents with 300+ skills: always-loaded, resolver-routed, and dormant. Per-turn token math, the v0.41.7.0 compact list-format resolver, and the `gbrain doctor` safety net. 306 skills, ~21K tokens freed per turn, zero capability loss.\n- [docs/guides/push-context.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/push-context.md): Push-based context: the brain volunteers confidence-gated pages from the rolling conversation window. Three channels (ambient reflex, volunteer_context op, gbrain watch), config knobs, and the volunteered-vs-used feedback loop.\n- [docs/mcp/DEPLOY.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/mcp/DEPLOY.md): MCP server deployment.\n- [docs/protocol/MEMORY_VERBS_v1.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/protocol/MEMORY_VERBS_v1.md): The frozen five-verb memory protocol (recall/remember/entity/synthesize/forget): response envelopes, error contract, additive-forever versioning, surface modes, conformance certification, per-harness installs.\n\n## AI providers\n\n- [docs/ai-providers/zeroentropy.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/zeroentropy.md): ZeroEntropy zembed-1 embedding + zerank-2 reranker (hosted): API key, embedding switch, reranker config.\n- [docs/ai-providers/llama-server-reranker.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ai-providers/llama-server-reranker.md): Local reranker via llama.cpp --reranking: Qwen3-Reranker or self-hosted ZE weights, --alias setup, gbrain config keys, cold-start timeout, budget-cap interaction.\n\n## Debugging\n\n- [docs/GBRAIN_VERIFY.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/GBRAIN_VERIFY.md): 7-check post-setup verification. Start here when something feels off.\n- [docs/guides/minions-fix.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/minions-fix.md): Troubleshooting the Minions job queue.\n- [docs/integrations/reliability-repair.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/integrations/reliability-repair.md): Data integrity recovery.\n\n## Migrations\n\n- [docs/UPGRADING_DOWNSTREAM_AGENTS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/UPGRADING_DOWNSTREAM_AGENTS.md): Patches for downstream agent skill forks. One section per release.\n- [skills/migrations/](https://raw.githubusercontent.com/garrytan/gbrain/master/skills/migrations/): Per-version (v0.5.0 - v0.14.1) agent-executable migration instructions.\n- [CHANGELOG.md](https://raw.githubusercontent.com/garrytan/gbrain/master/CHANGELOG.md): Release-summary voice + itemized changes + self-repair block per version.\n\n## Contributing\n\n- [docs/TESTING.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/TESTING.md): Test command tiers, the test-isolation lint (R1-R4), the canonical PGLite block, withEnv, the E2E DB lifecycle, and the file taxonomy. Maintainer-facing.\n- [docs/RELEASING.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/RELEASING.md): Full release + contributor process: pre-ship test requirements, the CHANGELOG voice + release-summary template, the 'To take advantage of vX' block, version migrations, GitHub Actions SHA refresh, PR conventions, community-PR-wave. (Ship IRON RULES stay inline in CLAUDE.md.)\n\n## Philosophy\n\n- [docs/ethos/THIN_HARNESS_FAT_SKILLS.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ethos/THIN_HARNESS_FAT_SKILLS.md): Why skills live in markdown.\n- [docs/ethos/MARKDOWN_SKILLS_AS_RECIPES.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/ethos/MARKDOWN_SKILLS_AS_RECIPES.md): Homebrew for Personal AI.\n\n## Optional\n\n- [docs/designs/](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/designs/): Forward-looking designs.\n- [docs/architecture/infra-layer.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/architecture/infra-layer.md): Shared infra patterns.\n\n## Operational tips\n\n- `gbrain doctor [--json] [--fast] [--fix]` - built-in health checks.\n- `gbrain orphans [--json]` - pages with zero inbound wikilinks.\n- `gbrain repair-jsonb [--dry-run]` - repair v0.12.0 double-encoded JSONB rows.\n- `gbrain upgrade` runs post-upgrade + apply-migrations.\n","CLAUDE.md":"# CLAUDE.md\n\nGBrain is a personal knowledge brain and GStack mod for agent platforms. Pluggable\nengines: PGLite (embedded Postgres via WASM, zero-config default) or Postgres + pgvector\n+ hybrid search in a managed Supabase instance. `gbrain init` defaults to PGLite;\nsuggests Supabase for 1000+ files. GStack teaches agents how to code. GBrain teaches\nagents everything else: brain ops, signal detection, content ingestion, enrichment,\ncron scheduling, reports, identity, and access control.\n\n## North Star\n\ngbrain aims to be the **next Postgres for memory**: the most well-tested, widest-coverage,\nbest-for-the-most-at-the-least retrieval + agent memory system for company brains and\npersonal AI, built to serve a billion people. Every feature and every eval is judged\nagainst this bar. \"gbrain is best\" is a WHOLE-SYSTEM claim — proven across the full\nBrainBench suite (retrieval, longmemeval, calibration, …) — not by any single feature.\nWhen scoping an eval, prove the FEATURE delivers value to gbrain users; do not waste it\nproving that gbrain's particular algorithm beats some other algorithm (a research\nbake-off, off-mission).\n\n## Two organizational axes (read this first)\n\nGBrain knowledge is organized along two orthogonal axes. Users AND agents must\nunderstand both, or queries misroute silently.\n\n- **Brain** — WHICH DATABASE. Your personal brain is `host`. You can mount\n  additional brains (team-published, each with their own DB and access policy)\n  via `gbrain mounts add` (v0.19+). Routing: `--brain`, `GBRAIN_BRAIN_ID`,\n  `.gbrain-mount` dotfile.\n- **Source** — WHICH REPO INSIDE THE DATABASE. A brain can hold many sources\n  (wiki, gstack, openclaw, essays). Slugs scope per source. Routing:\n  `--source`, `GBRAIN_SOURCE`, `.gbrain-source` dotfile.\n\nBoth axes follow the same 6-tier resolution pattern. Read\n`docs/architecture/brains-and-sources.md` for topology diagrams (personal, team\nmount, CEO-class with multiple team brains) and\n`skills/conventions/brain-routing.md` for the agent-facing decision table.\n\n## Architecture\n\nContract-first: `src/core/operations.ts` defines 100+ shared operations (including `volunteer_context` — push-based context, see `docs/guides/push-context.md` — and the seven frozen MEMORY_VERBS `recall`/`remember`/`entity`/`synthesize`/`forget`/`context_pack`/`delta` — the last two are v0.45.7 ambient-recall boundary verbs (budget-packed pack + \"what changed since\"), all seven stamp `protocol_version: 1`, servable alone via `gbrain serve --surface verbs`, see `docs/protocol/MEMORY_VERBS_v1.md` + `docs/guides/ambient-recall.md`). CLI and MCP\nserver are both generated from this single source. Engine factory (`src/core/engine-factory.ts`)\ndynamically imports the configured engine (`'pglite'` or `'postgres'`). Skills are fat\nmarkdown files (tool-agnostic, work with both CLI and plugin contexts).\n\n**Trust boundary:** `OperationContext.remote` distinguishes trusted local CLI callers\n(`remote: false` set by `src/cli.ts`) from untrusted agent-facing callers\n(`remote: true` set by `src/mcp/server.ts`). Security-sensitive operations like\n`file_upload` tighten filesystem confinement when `remote=true` and default to\nstrict behavior when unset.\n\n**Cross-cutting invariants (must-never-violate, regardless of which file you touch).**\nThese used to be buried across the per-file index; they live here so they always load.\nPer-file detail is in `docs/architecture/KEY_FILES.md`.\n\n- **Trust is fail-closed.** `OperationContext.remote` is REQUIRED on the type. Anything not\n  strictly `false` is treated as remote/untrusted (`ctx.remote === false` for trusted-only\n  sites; `ctx.remote !== false` for untrust-unless-explicit-false). Don't default it falsy.\n- **Source isolation.** Every read-side op routes through `sourceScopeOpts(ctx)`; precedence\n  is federated array (`ctx.auth.allowedSources`) > scalar (`ctx.sourceId`) > nothing. Don't\n  hand-roll source filtering — a missed thread is a cross-source data leak.\n- **JSONB: never `JSON.stringify` into a `::jsonb` cast.** postgres.js double-encodes it (a jsonb\n  string scalar); PGLite hides the bug. This bites BOTH spellings — the template form\n  (`${JSON.stringify(x)}::jsonb`) AND the positional form (`executeRaw(\\`…$N::jsonb\\`, [JSON.stringify(x)])`,\n  the #2339 class that aborted every sync). Fix: pass a raw object to `engine.executeRaw` / use\n  `executeRawJsonb` / `sql.json()`; or for the positional path bind through `$N::text::jsonb` (binds as\n  text, the cast parses it). Guarded by `scripts/check-jsonb-pattern.sh` (template grep) +\n  `scripts/check-jsonb-params.mjs` (positional AST scanner); the real backstop is the DATABASE_URL-gated\n  e2e parity tests, since PGLite can't surface the bug. Full rule in `docs/ENGINES.md`.\n- **Engine-live paths avoid runtime dynamic `import()` for helper dependencies.** In\n  `src/core/pglite-engine.ts`, `src/core/postgres-engine.ts`, and\n  `src/core/migrate.ts`, dependencies previously reached through runtime dynamic\n  imports use static top-level imports. The only current dynamic-`import()` exceptions\n  are the four `ai/gateway.ts` lookups in both engines'\n  `initSchema()` and `_upsertChunksOnce()` methods; each remains lazy inside a\n  local `try/catch` because the gateway has a large provider/config closure and,\n  more importantly, eager evaluation would occur before the catch and could\n  turn a recoverable default/config-row fallback into a module-load failure.\n  Every exception carries `engine-dynamic-import-ok` on the import line.\n  `scripts/check-engine-dynamic-import.sh` enforces the rule. For history, use\n  `git log -G'await[[:space:]]+import\\\\('`, not `git log -S`: a dynamic-to-static\n  rewrite can preserve the searched token while changing its context.\n- **Engine parity.** `src/core/postgres-engine.ts` and `src/core/pglite-engine.ts` move in\n  lockstep — a new method/SQL shape lands in BOTH, pinned by `test/e2e/engine-parity.test.ts`.\n  Forward-referenced columns/indexes go in the bootstrap probe set (guarded by\n  `test/schema-bootstrap-coverage.test.ts`).\n- **Contract-first.** `src/core/operations.ts` is the single source; CLI + MCP are generated\n  from it. Every op carries `scope: 'read'|'write'|'admin'` + optional `localOnly`. HTTP\n  dispatch enforces scope/localOnly before the handler runs.\n- **Migrations.** Schema DDL lives in the `MIGRATIONS` array in `src/core/migrate.ts`.\n  `CREATE INDEX CONCURRENTLY` needs `transaction: false` (pre-drop invalid remnants on\n  Postgres; plain `CREATE INDEX` on PGLite via `sqlFor.pglite`).\n- **Multi-source.** Slug uniqueness is `(source_id, slug)`, not slug. Key batch ops and\n  reverse-writes on the composite key; `validateSourceId` before any `source_id` path join.\n- **One canonical chat-pricing table.** All paid-cloud chat/completion prices live ONCE in\n  `src/core/model-pricing.ts` (`CANONICAL_PRICING` + `canonicalLookup`). Every other table\n  (`anthropic-pricing.ts`'s `ANTHROPIC_PRICING`, `takes-quality-eval/pricing.ts`'s\n  `MODEL_PRICING`, the contradictions/cross-modal/skillopt cost views) is a DERIVED view, never\n  a hand-copied duplicate — so cross-table price drift is structurally impossible. Update a\n  price in `model-pricing.ts` only; each consumer keeps its own key allowlist + miss policy\n  (fail-closed vs warn-only vs null), not its own numbers. Pinned by `test/model-pricing.test.ts`\n  (drift guard asserts each view equals canonical). Embeddings price separately in\n  `embedding-pricing.ts` (different unit).\n\n\n## Reference map (load on demand)\n\nCLAUDE.md is the always-loaded orientation + dispatcher. Detailed reference loads\non demand — read the linked doc before working in that area. (Same two-layer\npattern gbrain ships for its own skills: thin router in `skills/RESOLVER.md`, fat\ndetail on demand.)\n\n| When you're working on... | Read first |\n|---|---|\n| any file in `src/` (what it does + its invariants) | `docs/architecture/KEY_FILES.md` — find the file's entry |\n| search / ranking / hybrid / retrieval | `docs/architecture/RETRIEVAL.md` + the `search/*` entries in `KEY_FILES.md` |\n| search modes / cost knobs | `docs/guides/search-modes.md` |\n| embedding spend gates / cost gate / `spend.posture` / off switches | `docs/operations/spend-controls.md` |\n| push-based context (volunteer/watch/reflex window) | `docs/guides/push-context.md` |\n| schema packs / page types / extraction | `docs/architecture/schema-packs.md`, `type-taxonomy.md`, `lens-packs.md` |\n| thin-client / remote MCP / cross-modal | `docs/architecture/thin-client.md` |\n| memory verbs / MCP tool surface (`--surface`) / conformance | `docs/protocol/MEMORY_VERBS_v1.md` + the `verbs*`/`surface.ts`/`protocol.ts` entries in `KEY_FILES.md` |\n| the CLI surface (commands + flags) | `gbrain --help` / `gbrain --tools-json`, plus the relevant `KEY_FILES.md` entry |\n| running or writing tests | `docs/TESTING.md` |\n| bulk-command progress wiring | `docs/progress-events.md` |\n| eval methodology / metrics | `docs/eval/` |\n| brains vs sources / topology | `docs/architecture/brains-and-sources.md`, `topologies.md` |\n| skill routing | `skills/RESOLVER.md` |\n| agent bootstrap (paste-in install, hooks, `gbrain bootstrap`, sweep, keyless) | `docs/guides/bootstrap.md` + `docs/designs/AGENT_BOOTSTRAP_PLAN.md` + the KEY_FILES bootstrap cluster |\n| shipping a release / CHANGELOG / PR conventions | `docs/RELEASING.md` (ship IRON RULES stay inline below) |\n\nThe per-file index (`## Key files`), the thin-client routing seam, and the testing\ndiscipline used to live inline here. They moved to the docs above so this file\nstays small enough to load every session. Nothing was lost — the pre-move content\nis in git, and the docs carry every load-bearing invariant (compressed to\ncurrent-state).\n\n## Maintaining CLAUDE.md and the reference docs\n\nCLAUDE.md grew to ~592KB / ~147k tokens once the per-file index became append-only\n(one `**vX.Y.Z:**` clause per release per file). That is the exact anti-pattern\ngbrain exists to fix. The rules that keep it from recurring:\n\n- **CLAUDE.md is orientation, not the implementation spec.** It carries the North\n  Star, the two axes, architecture + cross-cutting invariants, the resolver, and\n  the inline IRON RULES. Per-file/per-command/per-test detail lives in the\n  reference docs and loads on demand.\n- **Reference docs (`KEY_FILES.md`, `thin-client.md`, `TESTING.md`) describe\n  CURRENT behavior only.** Release history goes in `CHANGELOG.md` + git. Do NOT\n  append `**vX.Y.Z (#NNN):**` clauses, codex/review tags, or \"pre-fix/then/was-now\"\n  narration. When a file's behavior changes, UPDATE its entry to the new truth.\n- **CI is the enforcement, not this prose.** `scripts/check-key-files-current-state.sh`\n  (in `bun run verify`) fails on the bolded-release-clause marker in the reference\n  docs AND on a CLAUDE.md size cap. A written rule caused this disease; a guard\n  cures it.\n- **After any CLAUDE.md or reference-doc edit, run `bun run build:llms`** — the\n  llms bundle inlines/links these (config in `scripts/llms-config.ts`); the\n  freshness + budget test (`bun test test/build-llms.test.ts`) fails CI otherwise.\n\n## Search Mode (v0.32.3)\n\nGBrain ships three named search modes that bundle the search-lite knobs from\nPR #897 into a single config key. Pick one at install time; the rest of the\nproject resolves through `src/core/search/mode.ts`.\n\n| Knob                          | `conservative` | `balanced` | `tokenmax`     |\n|-------------------------------|----------------|------------|----------------|\n| `cache.enabled`               | true           | true       | true           |\n| `cache.similarity_threshold`  | 0.92           | 0.92       | 0.92           |\n| `cache.ttl_seconds`           | 3600           | 3600       | 3600           |\n| `intentWeighting`             | true           | true       | true           |\n| `tokenBudget`                 | **4000**       | **12000**  | **off**        |\n| `expansion` (LLM multi-query) | false          | false      | **true**       |\n| `relationalRetrieval`         | false          | **true**   | **true**       |\n| `searchLimit` default         | 10             | 25         | 50             |\n\n**Cost anchors (downstream agent input cost — gbrain itself is rounding error).**\nThe corner-to-corner spread is 25x once you pair mode with downstream model.\nChunks ~400 tokens avg. Per-query cost @ 10K queries/month (typical\nsingle-user volume), full search payload, no cache savings:\n\n| Mode \\ Downstream | Haiku 4.5 (\\$1/M) | Sonnet 4.6 (\\$3/M) | Opus 4.7 (\\$5/M) |\n|---|---|---|---|\n| conservative (~4K) | **\\$40/mo** | \\$120/mo | \\$200/mo |\n| balanced (~10K) | \\$100/mo | \\$300/mo | \\$500/mo |\n| tokenmax (~20K) | \\$200/mo | \\$600/mo | **\\$1,000/mo** |\n\nScales linearly: multiply by 10 for 100K/mo (heavy power user / multi-user\nfleet); divide by 10 for 1K/mo (light usage). Natural pairings span ~4x.\nMismatches (tokenmax+Haiku, conservative+Opus) waste capacity differently\n— too-big payload overwhelms a cheap model; too-small payload starves an\nexpensive one.\n\ntokenmax adds ~\\$1.50 per 1K queries in Haiku expansion calls on top of\nthe matrix (\\$15/mo @ 10K). Cache hits cut all numbers ~50%. **The matrix\nhas three verbatim homes: this section, the `gbrain init` picker copy\n(`src/commands/init-mode-picker.ts`), and `INSTALL_FOR_AGENTS.md` Step\n3.5** — update all three when refreshing.\n\n**Per-query math vs real-world spend.** The matrix above is what an\nisolated benchmark would measure. Real agent loops with disciplined\nAnthropic prompt caching see 50-80% discount on top (cache hits skip\ndownstream entirely). The realistic-scale anchor in\n`docs/eval/SEARCH_MODE_METHODOLOGY.md` walks the natural pairings at\nsingle-power-user volume (~860 turns/mo): tokenmax+Opus ~\\$700/mo,\nbalanced+Sonnet ~\\$430/mo, conservative+Haiku ~\\$170/mo. Setups WITHOUT\ncache-aware prompt layout (frequent prefix churn) see the per-query\nmatrix dominate — mode + model choice matters more there.\n\n**Resolution chain** (matches the v0.31.12 model-tier pattern at\n`src/core/model-config.ts:resolveModel`):\n\n    per-call SearchOpts → per-key config (search.cache.enabled, …) →\n      MODE_BUNDLES[search.mode] → MODE_BUNDLES.balanced (fallback)\n\nMode resolution lives in **bare `hybridSearch`** (NOT just the cached wrapper)\nper `[CDX-5+6]` in `~/.claude/plans/lets-take-a-look-validated-parrot.md` — so\n`gbrain eval replay` and `gbrain eval longmemeval` test the same mode-affected\nbehavior as the production `query` op.\n\n**Cache-key contamination hotfix `[CDX-4]`:** migration v56 added a\n`knobs_hash` column to `query_cache`. The lookup filter is now\n`WHERE source_id = $ AND knobs_hash = $ AND embedding similarity < $` so a\ntokenmax write (expansion=on, limit=50) can't be served to a conservative\nread.\n\n**v0.36.3.0 knobs_hash v=2 → v=3.** The hash now folds the active\nembedding column name + provider into the cache key, so a query routed\nthrough `embedding_voyage` (1024d Voyage) can't be served a cache row\nwritten against `embedding` (1536d OpenAI). Existing v=2 rows become\nunreachable on first re-query (one-time miss spike on upgrade);\n`mode.ts:KNOBS_HASH_VERSION` is the single source of truth.\n\n**v0.42.34.0 knobs_hash v=9 → v=10.** Folds the `relationalRetrieval` knob +\ndepth into the cache key so a relational-on result set can't be served to a\nrelational-off lookup (same contamination class as graph_signals). One-time\nmiss spike on upgrade.\n\n**Relational retrieval (v0.42.34.0).** `relationalRetrieval` (on for\nbalanced/tokenmax) adds a fourth recall arm: a relational query (\"who invested\nin X\", \"what connects A and B\") resolves its seed entity and walks the typed-edge\ngraph (`src/core/search/relational-recall.ts` + `relational-intent.ts`,\n`engine.relationalFanout`), injecting edge-derived answers into RRF. Within-source,\ndeterministic, mentions-excluded by default, pure no-op for non-relational queries.\nThe `query` op's `relational` flag forces it on/off per call.\n\n**Three CLI surfaces:**\n\n    gbrain search modes              # what is running, with per-knob attribution\n    gbrain search modes --reset      # clear search.* overrides (mode bundle wins)\n    gbrain search stats [--days N]   # cache hit rate, intent mix, budget drops\n    gbrain search tune [--apply]     # data-driven recommendations\n\nThe install picker fires inside `gbrain init` AFTER `engine.initSchema()`\n(non-TTY auto-selects). The upgrade banner fires once via `runPostUpgrade`\nin `src/commands/upgrade.ts`, gated by `search.mode_upgrade_notice_shown`.\n\n## Eval discipline (v0.32.3)\n\nEvery metric printed by any `gbrain eval *` or `gbrain search stats` command\nresolves through `src/core/eval/metric-glossary.ts` so industry terms\n(`P@k`, `nDCG@k`, `MRR`, `Jaccard@k`) carry a plain-English line in human\noutput and a `_meta.metric_glossary` block in JSON output (one block per\nresponse per `[CDX-25]`, NOT sibling `_gloss` fields).\n\nThe full methodology — datasets, sample selection, pre-registered\nexpectations, threats to validity, paired-bootstrap + Bonferroni p-value\ndiscipline `[CDX-14]` — lives in `docs/eval/SEARCH_MODE_METHODOLOGY.md`.\nAuto-regenerated `docs/eval/METRIC_GLOSSARY.md` is CI-guarded against\ndrift (`scripts/check-eval-glossary-fresh.sh`).\n\nPer-run records land at `<repo>/.gbrain-evals/eval-results.jsonl` per\n`[CDX-23]`. The user's personal `~/.gbrain` brain is NEVER touched —\naudit trail lives in the source repo's git history.\n\n## Skills\n\nRead the skill files in `skills/` before doing brain operations. GBrain ships 50+ skills\n(the current list lives in `skills/manifest.json`) organized by `skills/RESOLVER.md`\n(`AGENTS.md` is also accepted as of v0.19):\n\n**Original 8 (conformance-migrated):** ingest (thin router), query, maintain, enrich,\nbriefing, migrate, setup, publish.\n\n**Brain skills (ported from an upstream agent fork):** signal-detector, brain-ops, idea-ingest, media-ingest,\nmeeting-ingestion, citation-fixer, repo-architecture, skill-creator, daily-task-manager.\n\n**Operational + identity:** daily-task-prep, cross-modal-review, cron-scheduler, reports,\ntesting, soul-audit, webhook-transforms, data-research, minion-orchestrator. As of\nv0.20.4, `minion-orchestrator` is the single unified skill for both lanes of background\nwork (shell jobs via `gbrain jobs submit shell`, LLM subagents via `gbrain agent run`) ...\nthe prior `gbrain-jobs` skill was merged in, Preconditions are shared, and trigger\nrouting is narrowed to what the skill actually covers.\n\n**Skillify loop (v0.19):** skillify (the markdown orchestration), skillpack-check\n(agent-readable health report).\n\n**Brain-resident skillpacks + advisor (v0.42.47.0, #2180):** A brain repo can carry its\nown publishable skillpack (`brain_resident: true` in `skillpack.json` + `schema_pack`);\n`gbrain skillpack init-brain-pack` scaffolds one with a 5-section machine-parseable README.\nConnecting harnesses discover it on `gbrain sources add` (Topology A advisory, bounded nag\nvia `nag-state.ts`) and over MCP via the source-scoped `list_brain_skillpack` op +\n`get_skill --source_id` (gated by `mcp.publish_skills`). The bundled `gbrain-advisor` skill\n+ `gbrain advisor` op compute a ranked, read-only list of high-leverage actions from brain\nstate (8 collectors in `src/core/advisor/`); `--json`+exit codes for CI/cron, local-only\n`--apply <id>` behind confirm, exposed over MCP behind `mcp.publish_advisor` (default off,\nread-only on remote). Thin-client binary install stays deferred to PR2 `build_skillpack`.\n\n**Routing-table compression (v0.32.3.0):** `skills/functional-area-resolver/` —\ntwo-layer dispatch pattern for shrinking large AGENTS.md / RESOLVER.md files\n(>=12KB) without losing routing accuracy. Replaces one row per skill with one\nentry per functional area, where each area declares its sub-skills in a\n`(dispatcher for: ...)` clause. The static-prompt analog of hierarchical agent\nrouting (AnyTool [arXiv:2402.04253](https://arxiv.org/abs/2402.04253), RAG-MCP\n[arXiv:2505.03275](https://arxiv.org/html/2505.03275v1), Anthropic Agent Skills\nprogressive disclosure). Empirically validated across Opus 4.7 / Sonnet 4.6 /\nHaiku 4.5: +13 to +17pp over the verbose baseline at 48% the size (25KB → 13KB\non a real fork). The `(dispatcher for: ...)` clause is the load-bearing signal\n— strip it and lenient accuracy collapses to 41.7% on Sonnet (the\n`resolver-of-resolvers` ablation case). A/B eval surface lives at\n`evals/functional-area-resolver/` (outside `skills/` deliberately so the\nskillpack bundler doesn't ship eval infrastructure to downstream installs):\ngateway-routed TypeScript harness, 20 training + 5 held-out fixtures, strict +\nlenient scoring, three committed cross-model receipts in `baseline-runs/`.\nReceipt header binds (model, prompt_template_hash, fixtures_hash, harness_sha,\nts) so future contributors can verify reproduction. Companion `rescore.mjs`\nre-scores existing JSONL with lenient tolerance for zero API cost. Reproduce\nwith `cd evals/functional-area-resolver && node harness.mjs --model\n{opus|sonnet|haiku}` (~$0.30–1.70 per model). Nine v0.33.x follow-up TODOs\nfiled for held-out corpus growth, cross-vendor verification, hierarchical\narea-of-areas, embedding-based pre-router, and the run-1 vs run-2\nprompt-design ablation methodology.\n\n**Operational health (v0.19.1):** smoke-test (8 post-restart health checks with auto-fix\nfor Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo; user-extensible via\n`~/.gbrain/smoke-tests.d/*.sh`).\n\n**Conventions:** `skills/conventions/` has cross-cutting rules (quality, brain-first,\nmodel-routing, test-before-bulk, cross-modal). `skills/_brain-filing-rules.md` and\n`skills/_output-rules.md` are shared references.\n\n## Bulk-action progress reporting\n\nAll bulk commands (doctor, embed, import, export, sync, extract, migrate,\nrepair-jsonb, orphans, check-backlinks, lint, integrity auto, eval, files\nsync, and apply-migrations) stream progress through the shared reporter\nat `src/core/progress.ts`. Agents get heartbeats within 1 second of every\niteration regardless of how slow the underlying work is.\n\nRules:\n- Progress always writes to **stderr**. Stdout stays clean for data output\n  (`--json` payloads, final summaries, JSON action events from `extract`).\n- Non-TTY default: plain one-line-per-event human text. JSON requires the\n  explicit `--progress-json` flag.\n- Global flags (`--quiet`, `--progress-json`, `--progress-interval=<ms>`)\n  are parsed by `src/core/cli-options.ts` BEFORE command dispatch.\n- Phase names are machine-stable `snake_case.dot.path` (e.g.\n  `doctor.db_checks`, `sync.imports`). Documented in\n  `docs/progress-events.md`; additive changes only.\n- `scripts/check-progress-to-stdout.sh` is a CI guard that fails the build\n  if any new code writes `\\r` progress to stdout. Wired into `bun run test`.\n- Minion handlers pass `job.updateProgress` as the `onProgress` callback\n  to core functions (DB-backed primary progress channel); stderr from\n  `jobs work` stays coarse for daemon liveness only.\n\nWhen wiring a new bulk command: `import { createProgress } from '../core/progress.ts'`\nand `import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts'`.\nCreate a reporter with `createProgress(cliOptsToProgressOptions(getCliOptions()))`,\n`start(phase, total?)` before the loop, `tick()` inside it, `finish()` after.\nFor single long-running queries, use `startHeartbeat(reporter, note)` with a\ntry/finally to guarantee cleanup. Never call `process.stdout.write('\\r...')`\nin bulk paths, the CI guard will fail the build.\n\n## Capturing test output (NEVER pipe through `tail` / `head`)\n\n**Iron rule:** when running `bun test`, `bun run test:e2e`, `bun run typecheck`,\nor any other test/check command, redirect to a file FIRST, then `tail` the file\nseparately:\n\n```bash\n# RIGHT — full output preserved, real exit code visible\nbun test > /tmp/ship_units.txt 2>&1\necho \"EXIT=$?\"\ntail -50 /tmp/ship_units.txt\ngrep -E '(fail\\)|✗|error:' /tmp/ship_units.txt | head -30\n```\n\n```bash\n# WRONG — exit code is `tail`'s (always 0), failures truncated, ship gates fail open\nbun test 2>&1 | tail -10\n```\n\nThe pipe form silently breaks /ship Step T1 (test failure ownership triage) and\nthe test verification gate (Step 16) because:\n- `$?` after a pipe is the LAST command's exit code (`tail` → 0), not bun's\n- bun prints failure details before the summary line, so `tail -N` drops them\n- Step T1 needs the full failure list to classify in-branch vs pre-existing\n\nThis bit us during v0.26.2 ship: `bun test 2>&1 | tail -10` reported \"3911 pass / 23 fail\"\nbut no failure details survived, forcing a 23-minute re-run to triage.\n\nApply the same pattern to any long-running command whose exit code matters:\n`bun run typecheck`, `bun run ci:local`, migration runs, eval suites, etc.\nFor background tasks (`run_in_background: true`), the harness captures the exit\nfile separately — use it via the bg task's `<id>.exit` file, not the streamed\noutput.\n\n## Sync resumability + lock tuning (v0.42.x, #1794)\n\n`gbrain sync` is resumable and converges under pool exhaustion + repeated kills.\nProgress banks into the append-only `op_checkpoint_paths` table (one row per drained\npath, written via the direct session pool so it survives `EMAXCONNSESSION`); a killed\nrun resumes from the checkpoint and `last_commit` only advances on true completion. The\nper-source lock heartbeats through the direct pool and refuses to steal a live,\nrecently-refreshed holder. Six env knobs tune it (all env-only, incident-time escape\nhatches — no config-dashboard surface by design):\n\n| Env var | Default | What it does |\n|---|---|---|\n| `GBRAIN_SYNC_CHECKPOINT_EVERY` | 1000 | Flush the checkpoint every N drained files. |\n| `GBRAIN_SYNC_CHECKPOINT_SECONDS` | 10 | Also flush every N seconds (whichever comes first) — bounds worst-case loss regardless of throughput. Flush also fires after the first file. |\n| `GBRAIN_SYNC_MAX_CHECKPOINT_FAILURES` | 3 | Consecutive failed flushes (each already retried ~12s) before the run aborts with `reason: 'checkpoint_unavailable'` instead of importing work it can never bank. |\n| `GBRAIN_SYNC_YIELD_EVERY` | 64 | Yield the event loop (`setTimeout(0)`, NOT `setImmediate` — Bun starves the timers phase under a tight setImmediate loop) every N files so the lock-refresh `setInterval` heartbeat fires mid-import. |\n| `GBRAIN_LOCK_STEAL_GRACE_SECONDS` | derived (~600 at 30min TTL) | A holder that refreshed within this window is NOT stolen even if its TTL lapsed (starved-but-alive). Dead holders stop refreshing, age past the grace, and become stealable; TTL stays the backstop. |\n| `GBRAIN_SYNC_STALL_ABORT_SECONDS` | 900 | Progress-aware stall watchdog (#1950): if the import drain makes no forward progress (keyed on file-import progress, NOT the lock heartbeat) for N seconds, abort the run and release the per-source lock so the next `gbrain sync` resumes from the checkpoint. Reports `reason: 'stall_timeout'`. Observed BETWEEN files; a hang inside one file's import isn't interrupted until it returns (the wall-clock hard deadline is that backstop). 0 disables. |\n\n## Pace Mode (DB-contention-aware backfill pacing)\n\nA naive `gbrain embed --stale` / large `sync` can saturate a PgBouncer\ntransaction-mode pooler and starve the minion supervisor's lock renewals\n(`lock-renewal-failed` → dead jobs). Pacing is the native, composable fix — it\nreplaces external SIGSTOP/SIGCONT wrapper scripts. **Opt-in: default mode `off`.**\n\nThe composable primitive is `src/core/db-pacer.ts` (`createDbPacer`):\n- **Concurrency cap is the real lever** (caps simultaneous in-flight DB writes =\n  pooler slots held). Embed paths set their worker count to `maxConcurrency`\n  (single pool, no permit); `sync` uses the shared `acquire()` **permit** because\n  each parallel worker owns a separate engine (one budget must span pools).\n- **In-band signal** (`observe(ms)` EWMA from the work's own queries — never\n  blind the way an out-of-band probe pool was). **No probe loop, no\n  `probeLatency` engine method.**\n- **Cooperative `pace()` sleep** on `setTimeout` (keeps the lock heartbeat\n  firing), jittered to avoid a thundering-herd resume. `acquire()`/`pace()` throw\n  `AbortError` on cancel; everything else is fail-open (a pacer bug never kills a\n  backfill, never throws an unhandledRejection).\n\nNamed bundles resolve through `src/core/pace-mode.ts` (`resolvePaceMode`), mirror\nof the search-mode pattern but with **env ABOVE config** (incident escape hatch):\n\n    per-call flag → GBRAIN_PACE_* env → config (pace.*) → PACE_BUNDLES[mode] → off\n\n| Knob | off | gentle | balanced | aggressive |\n|---|---|---|---|---|\n| `maxConcurrency` | (off) | 4 | 8 | 16 |\n| `paceAtMs` (EWMA → sleep) | — | 250 | 500 | 1000 |\n| `maxSleepMs` (jittered cap) | — | 2000 | 1500 | 1000 |\n\n**Surfaces.** `gbrain embed --stale --pace[=mode]` (bare `--pace` = balanced),\n`--pace-max-concurrency=N`. `--background` carries explicit pace OVERRIDES (not\nthe resolved bundle) into the `embed` job payload; the handler re-resolves\nenv>config>bundle at execution so `GBRAIN_PACE_*` still wins (CX5). Config-level\n`pace.mode` paces EVERY `runEmbedCore` caller (cycle embed, embed-catch-up,\nsync-auto-embed) and the prod `embed-backfill` job automatically. `sync` reads\nenv/config. PGLite / mode `off` → no-op pacer.\n\n**Correctness fixes pacing bundles** (longer paced runs widen these): CLI\n`embed --stale` single-flights via the SAME per-source lock key as the\n`embed-backfill` handler (`src/core/embed-backfill-lock.ts`; all-source runs lock\nevery source in sorted order) so a hand-run backfill and a queued job can't race\nthe NULL→non-NULL upsert (`TODOS:2299`); a **bounded** end-of-run keyset re-entry\n(max 3 + forward-progress, paced runs only) catches rows inserted behind the\ncursor (`TODOS:2301`); and the embed wall-clock budget timer is re-armed around\n`pace()` sleeps so paced time doesn't burn the work budget.\n\n`EmbedResult.pacing` carries the end-of-run telemetry (cap, samples, EWMA, slept\nms, max waiters) for `--json`; a one-line summary prints to stderr.\n\n## Build\n\n`bun build --compile --outfile bin/gbrain src/cli.ts`\n\n## Version locations (single source of truth: `VERSION` file)\n\nEvery release advances the version in **six files at once**. Keep these in\nsync. `/ship` enforces this via Step 12's idempotency check (VERSION vs\npackage.json drift), but the canonical list lives here so future runs and\nthe auto-update agent know where to look.\n\n**Version format is mandatory: `MAJOR.MINOR.PATCH.MICRO` (four numeric\nsegments, dot-separated, no leading `v`).** Every new release MUST use the\n4-segment form. The `.MICRO` slot is the dot-suffix follow-up channel: when\na release ships its commit subject ahead of its VERSION bump (e.g. PR #795\nlanding as `v0.31.4` without bumping the file), the corrective ship lands\nas `0.31.4.1` rather than churning the patch number to `0.31.5`. Suffixes\nlike `-fixwave` are still allowed as needed (`0.31.1.1-fixwave`), but the\nfour numeric segments are required first. Historical 3-segment versions\n(`0.31.3`, `0.22.1`) remain valid in `git log` and migration filenames\n(`skills/migrations/v0.21.0.md`); do NOT rewrite them. Going forward only.\n\n**Required (every release must update all six):**\n\n| File | What lives there | Format |\n|---|---|---|\n| `VERSION` | The single source of truth. Read first by `/ship`, the binary, and CI version-gate. | Bare 4-segment string `MAJOR.MINOR.PATCH.MICRO` (e.g. `0.31.4.1`), no leading `v`. |\n| `package.json` | Bun/npm package version. `gbrain --version` reads it via the compiled binary's bundled package metadata. CI version-gate cross-checks this against `VERSION` and fails if they drift. | `\"version\": \"0.31.4.1\"` |\n| `CHANGELOG.md` | Top entry header `## [0.31.4.1] - YYYY-MM-DD` plus the \"To take advantage of v0.31.4.1\" block. | Standard Keep-a-Changelog header. |\n| `TODOS.md` | Any TODO entries that mention \"follow-up from vX.Y.Z.W\" use the version of the release that filed them. Update only when filing NEW follow-up TODOs. | Inline `vX.Y.Z.W` references in TODO bodies. |\n| `CLAUDE.md` | The Key Files section's per-file annotations carry `vX.Y.Z.W (#NNN)` tags noting which release introduced a behavior. Update whenever a wave's annotations get folded in. | Inline `vX.Y.Z.W (#NNN, contributed by @user)` references. |\n| `openclaw.plugin.json` | OpenClaw plugin manifest (v0.45.6.0, #4033). Hand-maintained; `test/openclaw-plugin-manifest.test.ts` fails the suite if it drifts from `package.json`. Merges from master auto-resolve it to master's version — re-bump it with the trio. | `\"version\": \"0.45.12.0\"` |\n| `BOOTSTRAP_FOR_AGENTS.md` | Runbook stamp on line 1. `scripts/check-bootstrap-tag.sh` (in `bun run verify` + CI) fails when it drifts from `VERSION`; refresh it in the same commit as the bump. | `<!-- gbrain-runbook-stamp: X.Y.Z.W -->` |\n| `templates/bootstrap/template-repo/` | Vendored template tree with an embedded version stamp. Auto-derived, but NOT by `bun install`: run `bun run scripts/generate-template-repo.ts --out templates/bootstrap/template-repo` after the bump; `scripts/check-bootstrap-templates.sh` fails CI on drift. | `<!-- gbrain-template-stamp: X.Y.Z.W -->` in generated files. |\n\n**Auto-derived (no manual edit; refreshed by their own commands):**\n\n- `bun.lock` — root-package version is auto-pinned from `package.json`. After\n  bumping `package.json`, run `bun install` to refresh the lockfile.\n- `llms-full.txt` / `llms.txt` — auto-generated documentation bundles. **Any\n  CLAUDE.md edit MUST be followed by `bun run build:llms` in the same commit\n  (or a follow-up commit before push).** The committed bundles are checked\n  against fresh generator output by `test/build-llms.test.ts`, which runs in\n  CI shard 1. If you edited CLAUDE.md and didn't regenerate, CI will fail.\n  This has bitten the wave 3 times — every CLAUDE.md edit gets a `bun run\n  build:llms` chaser, no exceptions. (The `verify` gate doesn't run this\n  test; only the full unit suite does. So `bun run typecheck` clean is NOT\n  enough to know you can push after a CLAUDE.md edit.)\n\n**Historical (DO NOT bump on release):**\n\n- `skills/migrations/v0.21.0.md` — migration files use the version they\n  shipped FROM as their filename. v0.21.0's migration always says v0.21.0.\n- `src/commands/migrations/v0_21_0.ts` — same: migration code references\n  the schema version it migrates to.\n- `test/migrations-v0_21_0.test.ts`, `test/migration-orchestrator-v0_21_0.test.ts`,\n  `test/migrate.test.ts` — migration tests reference historical migration\n  versions; these are correct as-is and should not move.\n- `src/core/db.ts`, `src/core/migrate.ts`, `src/core/import-file.ts`,\n  `src/commands/reindex-code.ts` — code comments cite the release that\n  introduced a feature. Once written, these are historical record.\n- `README.md` — references the latest published feature names by version\n  (e.g. \"v0.21.0 Code Cathedral\"); update only when the README's marketing\n  copy is intentionally being refreshed, NOT on every micro/patch bump.\n\n**The /ship workflow's version idempotency check:** Step 12 reads\n`VERSION` and `package.json`, classifies as FRESH / ALREADY_BUMPED /\nDRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on\nDRIFT_UNEXPECTED. This is why the two must move together.\n\n**The CI version-gate** rejects pushes where `VERSION` and\n`package.json` disagree, OR where `VERSION` is not strictly greater\nthan master's VERSION. If a queue collision claims your version on\nmaster before yours lands, /ship's queue-aware allocator (Step 12)\nwill detect drift and re-bump on the next run.\n\n### Mandatory version-consistency audit (run after EVERY merge or commit that touches VERSION, package.json, or CHANGELOG)\n\n**The trio MUST agree.** Every merge from master will hit conflicts on\nVERSION + package.json + CHANGELOG.md because master ships its own\nversion bumps. Auto-merge sometimes resolves these silently in unexpected\nways. After any merge, branch update, or version-related edit, run this\naudit. It's three lines and never lies:\n\n```bash\necho \"VERSION:     $(cat VERSION)\"\necho \"package.json: $(node -e 'process.stdout.write(require(\"./package.json\").version)')\"\ngrep -E \"^## \\[\" CHANGELOG.md | head -1\n```\n\nAll three MUST show the same `MAJOR.MINOR.PATCH.MICRO`. If any one\ndisagrees, you have not finished the merge. Fix it before pushing or\nshipping. There is no situation in which \"I'll fix it next push\" is OK,\nbecause:\n\n- A green local test run with mismatched VERSION/package.json still\n  fails the CI version-gate.\n- A green CHANGELOG entry under the wrong version header silently lies\n  to release-notes consumers.\n- /ship's Step 12 idempotency check classifies a mismatch as\n  `DRIFT_UNEXPECTED` and HALTS — but only if you remember to run /ship\n  before pushing. Manual `git push` skips the check.\n\n### Merge-conflict recovery procedure (memorize this)\n\nWhen `git merge origin/master` reports conflicts on VERSION,\npackage.json, or CHANGELOG.md, resolve in this exact order:\n\n1. **VERSION** — overwrite with the wave's version (`echo -n \"X.Y.Z.W\"\n   > VERSION`). Highest semver wins; do NOT take master's lower version.\n2. **package.json** — strip the conflict markers, keep the wave's\n   version line. Sed pattern:\n   `sed -i.bak '/^<<<<<<< HEAD$/d; /^=======$/,/^>>>>>>> /d' package.json && rm package.json.bak`\n   (assumes ours is above the `=======`).\n3. **CHANGELOG.md** — strip ALL three conflict markers; both your entry\n   and master's entry stay. Sed pattern:\n   `sed -i.bak '/^<<<<<<< HEAD$/d; /^=======$/d; /^>>>>>>> origin\\/master$/d' CHANGELOG.md && rm CHANGELOG.md.bak`\n   Then verify your entry is the topmost `## [X.Y.Z.W]` and master's\n   newer-than-yours entries (if any) sit below.\n4. **Run the 3-line audit above.** If it doesn't show your version on\n   all three lines, you missed a marker.\n5. **Run `bun install`** to refresh `bun.lock` against the resolved\n   `package.json`. Stage and commit if it changed.\n6. **Run `bun run typecheck`** before committing the merge.\n7. Only THEN run `git commit` for the merge.\n\nIf the audit shows drift after step 4, do NOT proceed to step 5. Re-run\nsteps 1-3 against the actual file content; you missed a marker or\nresolved one in the wrong direction.\n\n**Anti-pattern to avoid:** Resolving via `git checkout --ours package.json`\nand `git checkout --theirs scripts/test-shard.sh` mixed in the same\ncommit. The selective directional resolution is fine, but on\nVERSION/package.json/CHANGELOG specifically, ALWAYS use the explicit\n`echo > VERSION` + sed-strip-markers pattern above. The directional\ncheckout flags have bitten us when the conflict shape was unexpected\n(e.g. master stripped a section we expected to keep).\n\n### Pre-push gate (manual; tighten when you remember to)\n\nBefore any `git push` of a merge commit, run the audit one more time:\n\n```bash\necho \"VERSION:     $(cat VERSION)\"\necho \"package.json: $(node -e 'process.stdout.write(require(\"./package.json\").version)')\"\ngrep -E \"^## \\[\" CHANGELOG.md | head -1\n```\n\nIf you've been editing the branch via `/ship` you can rely on Step 12's\nidempotency check. If you've been editing manually (merge resolution,\nconflict fix, version bump), the audit is the last line of defense\nbefore CI yells at you.\n\n## Conductor branch-name = workspace-name (IRON RULE)\n\nConductor workspaces expect the git branch name to match the workspace\ndirectory name. When they disagree, Conductor silently fails to render the\nPR view + show ship state, leading to \"did you actually push?\" confusion.\n\n**Check this FIRST on every ship and BEFORE creating any PR:**\n\n```bash\nWORKSPACE=$(basename \"$PWD\")              # e.g. puebla-v4\nBRANCH=$(git branch --show-current)        # e.g. garrytan/gstack-requests\ncase \"$BRANCH\" in\n  */\"$WORKSPACE\") echo \"OK: branch tail matches workspace\" ;;\n  \"$WORKSPACE\")   echo \"OK: branch == workspace\" ;;\n  *)              echo \"MISMATCH: branch=$BRANCH workspace=$WORKSPACE — RENAME BEFORE SHIPPING\" ;;\nesac\n```\n\nIf MISMATCH (branch is `garrytan/foo` but workspace is `puebla-v4`):\n\n```bash\n# Rename local, push under new name, delete old remote (and old PR if it\n# was already created — github auto-closes it when head ref dies).\ngit branch -m garrytan/<workspace-name>\ngit push -u origin garrytan/<workspace-name>\ngit push origin --delete <old-branch-name>\n# If a PR existed against the old branch:\n#   gh pr comment <old-pr> --body \"Superseded by #<new>: branch renamed to match Conductor workspace.\"\n#   gh pr create --base master --title \"...\" --body \"...\"  # recreate from renamed branch\n```\n\nCaught the hard way on v0.41.9.0 ship: workspace `puebla-v4` but branch\n`garrytan/gstack-requests` produced PR #1439 that Conductor wouldn't\ndisplay. Renamed to `garrytan/puebla-v4`; recreated as #1440.\n\nThe /ship workflow's Step 1 should be augmented to run the mismatch\ncheck; until that lands upstream, ALWAYS run the check above before\n`/ship` invokes its first push or PR-create step.\n\n\n## Releasing\n\nBefore any ship, read **[docs/RELEASING.md](docs/RELEASING.md)** in full. It carries the\nfull release + contributor process: pre-ship test requirements (`bun run ci:local` / the\nE2E lifecycle), the CHANGELOG voice + release-summary template, the \"To take advantage of\nvX\" self-repair block, version migrations, the GitHub Actions SHA refresh, PR conventions,\nand the community-PR-wave process. **Use `/ship` — never hand-roll a release.**\n\nThe ship-critical IRON RULES stay inline in this file (do NOT relocate them): the\nVersion-locations table above (the 5-file sync + the 3-line VERSION/package.json/CHANGELOG\naudit), the Conductor branch=workspace rule (above), Post-ship `/document-release` (below),\nthe Privacy + Responsible-disclosure rules (below), and the PR-title-version-first rule\n(below).\n\n## Post-ship requirements (MANDATORY)\n\nAfter EVERY /ship, you MUST run /document-release. This is NOT optional. Do NOT\nskip it. Do NOT say \"docs look fine\" without running it. The skill reads every .md\nfile in the project, cross-references the diff, and updates anything that drifted.\n\nIf /ship's Step 8.5 triggers document-release automatically, that counts. But if\nit gets skipped for ANY reason (timeout, error, oversight), you MUST run it manually\nbefore considering the ship complete.\n\nFiles that MUST be checked on every ship:\n- README.md — does it reflect new features, commands, or setup steps?\n- CLAUDE.md — does it reflect new files, test files, or architecture changes?\n- CHANGELOG.md — does it cover every commit?\n- TODOS.md — are completed items marked done?\n- docs/ — do any guides need updating?\n\nA ship without updated docs is an incomplete ship. Period.\n\n\n## Privacy rule: scrub real names from public docs\n\n**Never reference real people, companies, funds, or private agent names in any\npublic-facing artifact.** Public artifacts include: `CHANGELOG.md`, `README.md`,\n`docs/`, `skills/`, PR titles + bodies, commit messages, and comments in checked-in\ncode. Query examples, benchmark stories, and migration guides MUST use generic\nplaceholders.\n\nWhy: gbrain runs a personal knowledge brain containing notes on real people and\nreal companies (YC founders, portfolio companies, funds, investors, meeting\nattendees). When a doc copies a query like `gbrain graph diana-hu --depth 2` or\nnames a specific agent fork like `Wintermute`, that real name gets indexed by\nsearch engines, surfaced in cross-references, and distributed with every release.\n\n**Name mapping** to use in examples:\n- Agent forks → `your agent fork`, `a downstream agent`, or `agent-fork`\n- Example person → `alice-example`, `charlie-example`, or `a-founder`\n- Example company → `acme-example`, `widget-co`, or `a-company`\n- Example fund → `fund-a`, `fund-b`, `fund-c`\n- Example deal → `acme-seed`, `widget-series-a`\n- Example meeting → `meetings/2026-04-03` (generic date is fine)\n- Example user → `you` or `the user`, never a proper name\n\n**Specific rule: never say `Wintermute` in any CHANGELOG, README, doc, PR, or\ncommit message.** When the temptation is to illustrate with the real fork name:\n- Reader-facing copy → `your OpenClaw` (covers Wintermute, Hermes, AlphaClaw,\n  and any other downstream OpenClaw deployment in one term the reader already\n  recognizes).\n- First-person / origin-story copy → `Garry's OpenClaw` (honest that this is\n  the production deployment driving the feature, without exposing the private\n  agent's name).\n\n`Wintermute` may appear in private artifacts (scratch plans under\n`~/.gstack/projects/…`, memory files, conversation transcripts, CEO-review\nplans) — those aren't distributed. Anything checked into this repo or shipped\nin a release must use the OpenClaw phrasing above. Sweeping a stale reference\nis a small clean-up PR, not a debate.\n\n**When in doubt, ask yourself:** \"Would this query reveal private information\nabout the user's contacts, investments, or portfolio if it were read by a\nstranger?\" If yes, replace with generic placeholders.\n\n**Illustrative API examples with household-brand companies** (Stripe, Brex, OpenAI,\nGitHub, etc.) are fine — they're public entities, not contacts in anyone's brain.\nDo not confuse illustrative API examples with queries that reveal real\nrelationships.\n\n## Responsible-disclosure rule: don't broadcast attack surface in release notes\n\n**When a release fixes a security gap or a user-impacting bug, describe the fix\nfunctionally. Do not enumerate the attack surface, quantify the exposure window,\nor highlight the most sensitive records by name in public-facing artifacts.**\n\nPublic-facing artifacts include: `CHANGELOG.md`, `README.md`, `docs/`, PR titles\nand bodies, commit messages, GitHub issue titles and comments, release pages,\ntweets, blog posts.\n\n**Don't write:**\n- \"10 tables were publicly readable by the anon key for months, including X, Y, Z\"\n- \"X and Y are the most sensitive ones\"\n- \"N tables exposed. Fix: enable RLS on these specific tables: ...\"\n\n**Do write:**\n- \"Security hardening pass. Fresh installs secure by default. Existing brains\n  brought to the same bar automatically on upgrade.\"\n- \"If `gbrain doctor` still flags anything after upgrade, the message names each\n  table and gives the exact fix.\"\n\nWhy: anyone reading the release page before they've upgraded now has a directed\nprobe list for unpatched installs. The source code ships the specifics anyway\n(`src/schema.sql`, `src/core/migrate.ts`, test fixtures) — reverse engineers can\nget them. But the release page is a broadcast channel. Don't hand attackers a\ncurated list with a banner.\n\n**The test:** if a reader with no prior context could read the release note and\nwalk away knowing \"gbrain at version X has table Y readable by anon key until\nthey patch,\" the note is too specific. Rewrite until that's no longer possible.\n\n**What IS fine in public artifacts:**\n- The mechanism of the fix (\"the check now scans every public table instead of\n  a hardcoded allowlist\").\n- User-facing operator ergonomics (the escape-hatch SQL template, the upgrade\n  commands, the breaking-change flag).\n- Credit to contributors.\n- Generic framing of severity (\"security posture tightening pass\") without\n  quantification.\n\n**What stays in private artifacts (plan files, private memories, internal docs):**\n- Specific table names, record counts, exposure duration.\n- Which records stand out as highest-risk.\n- Detailed before/after tables in the \"numbers that matter\" format.\n\nIf the CEO/Eng review of a plan produces a detailed exposure table, keep it in\nthe plan file under `~/.claude/plans/` or `~/.gstack/projects/`. Don't copy it\ninto the CHANGELOG or PR body.\n\nApplies retroactively: if you see a prior CHANGELOG entry naming attack-surface\nspecifics, scrub it as a small cleanup commit, the same way a stale Wintermute\nreference gets swept.\n\n\n## PR title format — version FIRST (IRON RULE)\n\n**Every PR title MUST start with the version, then the conventional-commit subject:**\n\n```\nvMAJOR.MINOR.PATCH.MICRO <type>(<scope>): <summary> (#issue or wave ref)\n```\n\nExample (correct): `v0.42.3.0 feat(search): autocut — score-discontinuity result-sizing (#1663 wave 1)`\n\nThe version goes at the **BEGINNING**, never the end. This matches the repo's\ncommit-subject convention (`git log` shows `v0.41.38.0 fix: ...`,\n`v0.42.1.0 feat: ...`) so the PR list, the merge commit, and the changelog all\nread version-first. A title with the version parenthesized at the end\n(`feat(search): autocut ... (v0.42.3.0)`) is WRONG — fix it with\n`gh pr edit <N> --title \"vX.Y.Z.W <type>: <summary>\"`.\n\nThis applies to `gh pr create` and every `gh pr edit --title`. When `/ship`\n(or any flow) sets a PR title, the version is the first token. Same rule for the\nfinal commit subject that carries the version bump.\n\n\n## Skill routing\n\nWhen the user's request matches an available skill, ALWAYS invoke it using the Skill\ntool as your FIRST action. Do NOT answer directly, do NOT use other tools first.\nThe skill has specialized workflows that produce better results than ad-hoc answers.\n\n**NEVER hand-roll ship operations.** Do not manually run git commit + push + gh pr\ncreate when /ship is available. /ship handles VERSION bump, CHANGELOG, document-release,\npre-landing review, test coverage audit, and adversarial review. Manually creating a PR\nskips all of these. If the user says \"commit and ship\", \"push and ship\", \"bisect and\nship\", or any combination that ends with shipping — invoke /ship and let it handle\neverything including the commits. If the branch name contains a version (e.g.\n`v0.5-live-sync`), /ship should use that version for the bump.\n\nKey routing rules:\n- Product ideas, \"is this worth building\", brainstorming → invoke office-hours\n- Bugs, errors, \"why is this broken\", 500 errors → invoke investigate\n- Ship, deploy, push, create PR, \"commit and ship\", \"push and ship\" → invoke ship\n- QA, test the site, find bugs → invoke qa\n- Code review, check my diff → invoke review\n- Update docs after shipping → invoke document-release\n- Weekly retro → invoke retro\n- Design system, brand → invoke design-consultation\n- Visual audit, design polish → invoke design-review\n- Architecture review → invoke plan-eng-review\n- Save progress, checkpoint, resume → invoke checkpoint\n- Code quality, health check → invoke health\n"}}