Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: operating lessons for harness installs

garrytan4b26a98605db
diff --git a/AGENTS.md b/AGENTS.md
index d878104033..9ef80d1827 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -65,7 +65,7 @@ on `query`, `--source <id>`, `--limit`, `--json`; `gbrain backlinks <slug>` and
`gbrain timeline <slug>` for links and dated events. Copyable examples:
[brain-first](skills/conventions/brain-first.md#retrieval-gbrain-first).
-Recall relevant saved context before answering. Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.
+Recall relevant saved context before answering. Resolve a person (an email sender, an attendee) only by an exact frontmatter email or an exact title match, never a search's top hit ([identity rule](skills/conventions/brain-first.md#identity-exact-match)). Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.
Durable preferences and facts belong in shared memory when the user wants them
recalled later. Transient task state, credentials, local configuration, and harness
@@ -124,7 +124,10 @@ machine contract. The quick version:
4. Treat `[gbrain notice …]` blocks and `[AGENT]` blocks the same way. A degraded result is not proof of "no notes".
<!-- END GENERATED agent-protocol:quick-contract -->
-Exit 3 always means "stop and ask the user". Full contract, transcripts, effects,
+Exit 3 always means "stop and ask the user". Exit 10 means the write was
+accepted and is still pending: never "not found" or "failed", so poll the
+receipt (`gbrain write-request <id>`) before retrying, reporting or moving on.
+Full contract, transcripts, effects,
exit codes and marker grammar: [`docs/protocol/AGENT_OPERATOR_v1.md`](./docs/protocol/AGENT_OPERATOR_v1.md).
## Read this order
@@ -158,6 +161,23 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
[`docs/guides/live-sync.md`](./docs/guides/live-sync.md),
[`docs/mcp/DEPLOY.md`](./docs/mcp/DEPLOY.md),
[`docs/guides/remote-mcp.md`](./docs/guides/remote-mcp.md) (`gbrain mcp expose`).
+- **Run gbrain from cron, workspace scripts and hooks:** every caller goes
+ through one wrapper that sets `GBRAIN_HOME` (never `HOME`), loads the
+ brain's env file and runs the installed binary, never `bun run src/cli.ts`
+ with an inherited environment. Log stderr (never `2>/dev/null`: a
+ `no_brain` refusal then reads as "no results"), check the exit code, keep
+ hook output off stdout, allow at least 10 s per call, and never print the
+ process environment into a transcript. On a managed brain, schedule
+ `gbrain sources refresh <id>` and never commit files into the checkout from a
+ script. Wrapper and rules:
+ [cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),
+ [scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).
+- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour soft
+ delete, cascades to chunks, versions, links and facts, and `gbrain restore`
+ cannot undo it. Purge only on the user's explicit go for that purge ("scrub
+ the repo" is not one), one page at a time, verifying each; a stopped batch
+ stays stopped until the user says again
+ ([data-loss gate](skills/data-loss-gate/SKILL.md)).
- **Bring in your chat history:** `gbrain transcripts ingest` imports a
downloaded ChatGPT / Claude export (or agent session logs); `gbrain connectors`
connects the account and syncs new conversations live, incrementally and on an
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 658f41c3f4..53c73249a9 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -277,6 +277,7 @@ placeholder). Trust the CLI's detection over your own guesses.
| Hook reports "brain context unavailable" | serve not running or degraded | `gbrain doctor` names it; hooks fail open by design. | agent | none | `gbrain doctor --only bootstrap_hooks_heartbeat --json` |
| gh answers 403 "not enabled for this session" | Cloud proxy scoping — the repo is not attached to the session | Expected in cloud; the visibility ladder falls back to git protocol. NEVER shim gh. | agent (nothing to fix) | none | none needed |
| "crontab: command not found" / cron skipped | Containers and cloud sandboxes ship without a scheduler | Expected; event-driven pushes cover it — the skip message says exactly this. | agent (nothing to fix) | none | none needed |
+| A scheduled job, workspace script or hook finds nothing in the brain, or refuses `refresh_not_owner`, while the same command works in the session | The job runs with another `HOME`, so it reads another gbrain home (no database, or a second host identity) | Call gbrain from every job through one wrapper that sets `GBRAIN_HOME` (never `HOME`) and keeps stderr ([the wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended)). | agent | none | the job's log shows results and no refusal |
| A turn shows "workspace push is FAILING" | The background push is refusing (visibility, secret-scan, or network reasons) | Run `gbrain doctor`; the banner repeats every 30 min until fixed. | agent | none | `gbrain doctor --only bootstrap_push_health --json` |
## Hand off
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 897da9257a..b3ec4cb450 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -207,6 +207,25 @@ environment-dependent, so a re-run during an outage could silently repoint a
healthy Postgres brain at the PGLite floor. Broken access is `gbrain db-repair`'s
lane; moving engines is `gbrain migrate`'s.
+**Put the database next to the agent.** A warm search makes dozens of
+sequential round trips to Postgres, so the distance between the agent host and
+the database dominates its latency: in one deployment, moving Postgres into the
+agent host's region took warm search from 3.0 s to 1.2 s at p50. Create the
+database (and use the pooler) in the region of the machine that runs the agent
+and its `gbrain serve`.
+
+<a id="switching-a-database"></a>
+**Switching a brain's database** (a region move, a new server): stop gbrain's
+writers, then change every URL the tooling reads, not just the main one:
+`GBRAIN_DATABASE_URL`, `DATABASE_URL`, `GBRAIN_DIRECT_DATABASE_URL`, the
+`database_url` in `config.json`, and each env file, wrapper and service
+definition that sets them (`gbrain engine status --json` shows which source
+wins, with the password redacted). Restart every gbrain process, since a
+running process keeps the environment it started with. Prove the switch from
+the database side: a row written after the restart (a job, a test page)
+appears on the new server and no gbrain session remains on the old one. A
+shell's `echo $DATABASE_URL` proves only that shell.
+
`--json` emits `{status, engine, ladder_rung, url_source}` as the ONLY stdout
content so a scripted install can `| jq` it. The access token is never
persisted, logged, or echoed.
@@ -534,6 +553,17 @@ Read skills/soul-audit/SKILL.md and follow it.
This generates SOUL.md (agent identity), USER.md (user profile), ACCESS_POLICY.md
(who sees what), and HEARTBEAT.md (operational cadence) from the user's answers.
+**On OpenClaw 2026.10.6 and later,** `openclaw doctor --fix` imports a
+workspace `HEARTBEAT.md` into its own monitor, archives the file under the
+state directory's `backups/heartbeat-migration/` and removes it, while the
+rendered `AGENTS.md` still tells the agent to read it at session start. Until
+the render adapts to OpenClaw ([#7470](https://github.com/garrytan/gbrain/issues/7470)),
+put gbrain's file back after each doctor fix: `gbrain bootstrap render --only HEARTBEAT.md`
+re-renders it from the confirmed answers, or copy the archived file back when
+the user edited it. Jobs that must run on time belong in the host scheduler
+through the [one wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended),
+not only in `HEARTBEAT.md`, which runs only when a session starts.
+
If skipped, minimal defaults are installed automatically.
## Step 7: Recurring Jobs
@@ -543,7 +573,30 @@ capture, enrichment, maintenance or a service; do not infer consent from a
successful install or from a health recommendation.
Set up using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip the
-platform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon):
+platform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon).
+
+Every cron job, workspace script and hook calls gbrain through **one wrapper**
+that sets `GBRAIN_HOME` (never `HOME`), loads the brain's env file and runs
+the installed binary, never `bun run src/cli.ts` with an inherited
+environment. A scheduled job has another `HOME` than your shell, so a bare
+call finds no database (every lookup silently empty) or acts as a second host
+(`refresh_not_owner`). Log the wrapper's stderr instead of sending it to
+`/dev/null`, check exit codes against the [operator protocol](docs/protocol/AGENT_OPERATOR_v1.md),
+keep hook output off stdout so `--json` stays parseable, and give each call a
+timeout of at least 10 s. The wrapper and its rules:
+[call gbrain through one wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended).
+
+- **Managed brain checkout** (every 15 min, on the owner host):
+ `gbrain sources refresh <id>` is the only sanctioned fast-forward; it drains
+ writes, fast-forwards and re-syncs. Scripts save pages through
+ `put_page`/`capture`, never by writing and committing files in the
+ checkout: an unpushed local commit makes the checkout diverge and every
+ refresh refuse `refresh_diverged`
+ ([scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
+- **Workers**: start `gbrain jobs supervisor` with `--max-rss <MB>`; with
+ `--job-isolation process` the cap also covers each job child's process tree
+ (v0.60.426.0). Size the host for (concurrency + 1) × the cap
+ ([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:
@@ -648,6 +701,12 @@ 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, upgrade
+every install, restart every gbrain process and verify that each reports the
+new version, then `gbrain autopilot resume`
+([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume)).
+
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:
diff --git a/docs/GBRAIN_SKILLPACK.md b/docs/GBRAIN_SKILLPACK.md
index 9e0c79de10..4bc1cf1199 100644
--- a/docs/GBRAIN_SKILLPACK.md
+++ b/docs/GBRAIN_SKILLPACK.md
@@ -50,6 +50,8 @@ Running a production brain.
| Guide | What It Covers |
|-------|---------------|
| [Reference Cron Schedule](guides/cron-schedule.md) | 20+ recurring jobs, quiet hours, dream cycle |
+| [Call gbrain through one wrapper](guides/cron-schedule.md#calling-gbrain-unattended) | Cron, workspace scripts and hooks: `GBRAIN_HOME`, logged stderr, exit codes, clean stdout, timeouts, env files |
+| [Scripts and the managed checkout](guides/shared-checkout-git.md#scripts-and-the-managed-checkout) | Write through gbrain, scheduled `sources refresh`, history rewrites, gitignored paths |
| [Cron via Minions](../skills/conventions/cron-via-minions.md) | Why scheduled work runs as Minion jobs, not `agentTurn`. Built-in handlers are rewritten by the `v0_11_0` migration orchestrator (`gbrain apply-migrations`); host-specific handlers use the plugin contract below. |
| [Plugin Handlers](guides/plugin-handlers.md) | Registering host-specific Minion handlers via code (no data-file exec surface). |
| [Minions fix](guides/minions-fix.md) | Repairing a half-migrated Minions install. |
diff --git a/docs/guides/cli-socket.md b/docs/guides/cli-socket.md
index 980d56bb98..eabe5e97b9 100644
--- a/docs/guides/cli-socket.md
+++ b/docs/guides/cli-socket.md
@@ -133,6 +133,17 @@ whenever a call falls back, including when no socket exists (`no socket at
answered by the serve socket at <path>` line when the serve answers. `GBRAIN_CLI_SOCKET=0` makes a CLI call skip the
socket entirely, for comparisons and benchmarks.
+<a id="caller-timeouts"></a>
+## Caller timeouts
+
+A call that falls back to the cold path pays the full start (3–6 s on a
+pooled Postgres brain) before it reads anything. Give gbrain calls from scripts
+and agent runtimes a timeout of at least 10 s, and set it in every layer that
+has one: a language runtime's exec timeout (Node's `child_process`, Python's
+`subprocess`, a harness tool timeout) can end the call before a longer shell
+`timeout` ever applies, and the kill reads as an empty result. Scheduled
+callers go through one wrapper ([cron-schedule.md](cron-schedule.md#calling-gbrain-unattended)).
+
## Security
- **Unix domain socket only**, at `$GBRAIN_HOME/.gbrain/run/cli.sock`; never TCP.
diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.md
index 8e607d40ea..713cae990e 100644
--- a/docs/guides/cron-schedule.md
+++ b/docs/guides/cron-schedule.md
@@ -70,8 +70,9 @@ those (`maintenance_lock_busy`) and the holder runs them.
# Calendar sync — Sundays at 10 AM
0 10 * * 0 cd /path/to/calendar-sync && node calendar-sync.mjs --start $(date -v-7d +%Y-%m-%d) --end $(date +%Y-%m-%d)
-# Brain health — weekly Mondays at 6 AM
-0 6 * * 1 gbrain doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain embed --stale
+# Brain health — weekly Mondays at 6 AM. Every gbrain call goes through the
+# wrapper below (gbrain-run), never a bare `gbrain` or `bun run src/cli.ts`.
+0 6 * * 1 gbrain-run doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain-run embed --stale
# Autopilot health gate — daily at 7 AM. The exit code is the signal:
# 0 fresh (or nothing installed), 1 needs attention (stale heartbeat,
@@ -82,12 +83,85 @@ those (`maintenance_lock_busy`) and the holder runs them.
# daemon writes the maintenance verdict each tick), so it works even during
# a DB outage. On a stall: gbrain doctor --only global_maintenance_stalled
# names the phase and the command to run.
-0 7 * * * gbrain autopilot --status >> /tmp/gbrain-autopilot-health.log 2>&1 || your-notify "gbrain autopilot needs attention"
+0 7 * * * gbrain-run autopilot --status >> /tmp/gbrain-autopilot-health.log 2>&1 || your-notify "gbrain autopilot needs attention"
# Dream cycle — nightly at 2 AM
0 2 * * * /path/to/dream-cycle.sh
```
+<a id="calling-gbrain-unattended"></a>
+### Call gbrain through one wrapper
+
+A scheduled job does not run in the shell you tested it in. Cron, a harness's
+workspace scripts and git hooks start with another `HOME`, a bare `PATH` and
+whatever environment their parent had, so a call that works by hand can do
+something else on a schedule:
+
+- **No database.** The job finds no brain config or URL, gbrain refuses
+ (`no_brain`, or `GBRAIN_DB_ACCESS no_url`) on stderr, and a caller that
+ drops stderr reads every lookup as "nothing found".
+- **A second host.** gbrain keeps its host identity under the brain home, so a
+ job that resolves another home is another host: `gbrain sources refresh`
+ refuses `refresh_not_owner` (since v0.60.427.0 it names the identity file it
+ read and the `HOME` and `GBRAIN_HOME` it resolved), and owner-only
+ maintenance reports `owner_unavailable` with reason `host_mismatch`.
+- **A stale database.** A variable the caller already exported wins over the
+ brain's `config.json` and `.gbrain/.env`, so a job started from an old
+ environment keeps using the old `DATABASE_URL`.
+
+Give every cron line, workspace script and hook one entry point, a wrapper that
+sets `GBRAIN_HOME`, loads the brain's env file if the harness keeps one, and
+runs the installed binary:
+
+```bash
+#!/usr/bin/env bash
+# gbrain-run: the only way scheduled work calls gbrain
+set -euo pipefail
+export GBRAIN_HOME=/srv/gbrain # parent of .gbrain; the value serve, workers and autopilot use
+if [ -f /srv/gbrain/brain.env ]; then # only if the harness keeps the brain's settings in its own file
+ set -a; . /srv/gbrain/brain.env; set +a
+fi
+exec /srv/gbrain/.bun/bin/gbrain "$@" # the installed binary, by absolute path
+```
+
+Rules for the wrapper and everything that calls it:
+
+1. **Set `GBRAIN_HOME`, never `HOME`.** `GBRAIN_HOME` moves only gbrain's
+ state. Changing `HOME` also changes the git identity, SSH keys and push
+ credentials the job runs with. Use the same value as the serve, the workers
+ and autopilot; doctor `host_identity_mismatch` names a process that differs.
+2. **Run the installed binary.** Never `bun run src/cli.ts` from a checkout with
+ the caller's inherited environment: it skips the wrapper's settings and can
+ run another build than the serve.
+3. **Keep stderr and the exit code.** Never send gbrain's stderr to
+ `/dev/null`. Append it to a log and branch on the exit code
+ ([exit codes](exit-codes.md)): `10` means the write was accepted and is
+ still pending, not "not found" or "failed"; `3` means stop and ask the
+ user. A refusal fails the job; it is never an empty result.
+4. **Keep stdout clean.** A `--json` caller parses stdout as one document, so
+ the wrapper and any hook it runs log to a file or stderr, never stdout.
+5. **Allow time.** A cold CLI start takes 3–6 s on a pooled Postgres brain.
+ Set caller timeouts of at least 10 s in the shell and in the language
+ runtime that runs it (a runtime's exec timeout can override the shell's
+ without saying so), and turn on the [warm CLI socket](cli-socket.md) so
+ reads skip the cold start.
+6. **Quote the env file.** A file a shell sources is shell syntax. An unquoted
+ `&` in a URL ends the assignment and backgrounds the rest, so the variable
+ silently keeps its old value. Quote every value, keep Postgres URLs to
+ `?sslmode=require` (set driver options such as `GBRAIN_PREPARE=false` as
+ variables instead of extra `&` parameters), and restart every running
+ gbrain process after an edit: a process keeps the environment it started
+ with.
+7. **Never print the environment.** `env`, `printenv` or a process's
+ `environ` holds the database URL and API keys, and a transcript keeps them.
+ To debug, print variable names only, or run `gbrain engine status --json`,
+ which redacts the URL.
+
+On a managed brain the same wrapper runs `gbrain-run sources refresh <id>` on
+a schedule ([the managed cron line](../../skills/cron-scheduler/SKILL.md#managed-brain)).
+Scripts never write files and `git commit` straight into the managed checkout;
+see [shared-checkout git](shared-checkout-git.md#scripts-and-the-managed-checkout).
+
### Quiet Hours Gate (MANDATORY)
Every cron job that sends notifications MUST check quiet hours first. The
diff --git a/docs/guides/executive-assistant.md b/docs/guides/executive-assistant.md
index a622d20a5a..e73e45f87a 100644
--- a/docs/guides/executive-assistant.md
+++ b/docs/guides/executive-assistant.md
@@ -30,9 +30,14 @@ on email_batch(emails):
# Refuses on stale google sources by design — run the sync it names first
for email in emails:
- # Step 1: Search sender BEFORE reading the email body
- # Brain context makes triage 10x better
- sender_page = gbrain search "{email.sender_name}"
+ # Step 1: Resolve the sender BEFORE reading the email body
+ # Brain context makes triage 10x better. Identity is an exact match:
+ # the address in a person page's email frontmatter, else a person
+ # page whose title equals the display name. A search's top hit is
+ # NOT the sender; no exact match = unknown sender.
+ sender_page = gbrain list --type person --where email={email.sender_address} --source-id __all__ --json
+ if not sender_page:
+ sender_page = exact_title_match(gbrain search "{email.sender_name}" --types '["person"]' --json)
if sender_page:
context = gbrain get <sender_slug>
# Now you know: who they are, relationship history,
@@ -67,8 +72,8 @@ on email_batch(emails):
on upcoming_meeting(meeting):
briefing = {}
for attendee in meeting.attendees:
- # Search brain for each attendee
- results = gbrain search "{attendee.name}"
+ # Resolve each attendee by exact email, else exact title (as above)
+ results = gbrain list --type person --where email={attendee.email} --source-id __all__ --json
if results:
page = gbrain get <attendee_slug>
briefing[attendee] = {
@@ -123,10 +128,11 @@ on schedule_request(meeting):
## Tricky Spots
1. **Search sender BEFORE reading the email.** This is counterintuitive but critical. Loading brain context first means you know who they are, what you're working on together, and what they care about -- before you even see the subject line. The triage is informed, not mechanical.
-2. **Unknown senders with no brain page are almost always noise.** If `gbrain search` returns nothing for a sender, they're probably not important. Classify as low priority unless the email content signals otherwise.
-3. **Meeting prep is the highest-leverage EA workflow.** The user walks into every meeting already briefed on each attendee: last interaction, open threads, relationship history. This is the difference between "you have a meeting at 3" and "you have a meeting at 3 with alice-example -- last time you discussed the Series B, she was concerned about burn rate."
-4. **Post-inbox brain updates are where the brain compounds.** Every email is signal. If you clear the inbox without updating brain pages, the information is lost. This is the step most agents skip.
-5. **Scheduling nudges require timeline data.** "You haven't met with charlie-example in 6 weeks" only works if meeting pages have been ingested with proper entity propagation (see meeting-ingestion guide).
+2. **Identity is an exact match, never a top hit.** Accept a person page for a sender or attendee only when its `email` frontmatter holds the address, or its title equals the name exactly ([identity rule](../../skills/conventions/brain-first.md#identity-exact-match)). A semantic search always returns something, so taking the first hit files strangers as known contacts and loads the wrong relationship into the reply.
+3. **Unknown senders with no brain page are almost always noise.** If no person page matches a sender exactly, they're probably not important. Classify as low priority unless the email content signals otherwise.
+4. **Meeting prep is the highest-leverage EA workflow.** The user walks into every meeting already briefed on each attendee: last interaction, open threads, relationship history. This is the difference between "you have a meeting at 3" and "you have a meeting at 3 with alice-example -- last time you discussed the Series B, she was concerned about burn rate."
+5. **Post-inbox brain updates are where the brain compounds.** Every email is signal. If you clear the inbox without updating brain pages, the information is lost. This is the step most agents skip.
+6. **Scheduling nudges require timeline data.** "You haven't met with charlie-example in 6 weeks" only works if meeting pages have been ingested with proper entity propagation (see meeting-ingestion guide).
## How to Verify
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index b1f0693269..6887d48892 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -655,7 +655,12 @@ vars — incident-time escape hatches, not everyday knobs.
`sources.refresh_fetch_timeout_ms`, `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`).
A refresh interrupted by a crash is finished by the restarted owner or by
`gbrain sources refresh <source-id> --resume`. A cron that keeps a managed
- brain current runs the refresh instead of `git pull`.
+ brain current runs the refresh instead of `git pull`, through the same
+ [wrapper](cron-schedule.md#calling-gbrain-unattended) as every other
+ scheduled gbrain call (so it runs as the owner host). `refresh_diverged`
+ means something commits into the checkout outside gbrain: fix that writer
+ instead of forcing the checkout
+ ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).
**Say to your agent:** *"Bring my notes source up to date with its remote."*
diff --git a/docs/guides/minions-deployment.md b/docs/guides/minions-deployment.md
index fc08d2cc6e..de6f51d07c 100644
--- a/docs/guides/minions-deployment.md
+++ b/docs/guides/minions-deployment.md
@@ -45,8 +45,10 @@ gbrain jobs supervisor status --json
# Graceful stop (SIGTERM + drain wait + SIGKILL fallback).
gbrain jobs supervisor stop
-# Optional: cap worker memory in MB (--max-rss). Without the flag the RSS
-# watchdog is still on, at a RAM-relative auto-sized cap.
+# Cap worker memory in MB (--max-rss). Without the flag the RSS watchdog is
+# still on, at a RAM-relative auto-sized cap. With --job-isolation process the
+# cap also covers each job child's process tree; size the host for
+# (concurrency + 1) × the cap.
gbrain jobs supervisor --concurrency 4 --max-rss 4096
```
diff --git a/docs/guides/shared-checkout-git.md b/docs/guides/shared-checkout-git.md
index ddabf5284c..8f63cc5873 100644
--- a/docs/guides/shared-checkout-git.md
+++ b/docs/guides/shared-checkout-git.md
@@ -216,6 +216,47 @@ write that gets the lock commits the pending files with its own, and
`gbrain git commit-push --pending` commits and pushes them on demand.
`gbrain doctor` reports pending files older than 30 minutes as `dirty_age`.
+<a id="scripts-and-the-managed-checkout"></a>
+## Scripts and the managed checkout
+
+On a managed brain the persistence owner is the only Git writer in the
+canonical checkout, and `gbrain sources refresh` is the only way upstream
+commits come in. Four rules keep that checkout able to move:
+
+1. **Scripts write through gbrain, never with `git commit`.** A cron job or
+ hook that writes files into the checkout and commits them without pushing
+ leaves commits the upstream lacks. The checkout diverges, and every later
+ refresh refuses `refresh_diverged` and changes nothing. Save pages with
+ `put_page`, `edit_page`, `remember` or `capture` (CLI calls go through
+ the [one wrapper](cron-schedule.md#calling-gbrain-unattended)). On a classic
+ shared checkout, commit with `gbrain git commit-push -- <paths>`.
+2. **Refresh on a schedule.** `gbrain sources refresh <id>` drains queued
+ writes, refuses new ones until it finishes, fast-forwards with
+ `git merge --ff-only` and re-syncs every source on the checkout; run it
+ from cron on the owner host
+ ([cron line](../../skills/cron-scheduler/SKILL.md#managed-brain)).
+ `refresh_diverged` means something commits outside gbrain:
+ `git log --format='%h %an %ad %s' @{upstream}..HEAD` lists the stray
+ commits, so find and fix that writer, then reconcile as the
+ [refusal](write-refusals.md#refresh_diverged) says. Never force the
+ checkout.
+3. **Stop syncing a source before rewriting its history.** Before a
+ force-push or `git filter-repo`, take the source out of automatic sync
+ (`syncEnabled: false` in its config, with the user's agreement; there is
+ no CLI verb for it yet) and run `gbrain sources mirror-readonly <id>` so
+ no managed write touches its checkout. A sync whose recorded base commit no
+ longer exists makes sync and the maintenance cycle re-read the whole tree.
+ After the rewrite, move the checkout onto the new history
+ ([upstream rewritten](troubleshooting.md#upstream-rewritten)), then
+ `gbrain sources mirror-writable <id>` and turn sync back on.
+4. **Decide what a gitignored path is.** A page whose file a `.gitignore`
+ rule excludes cannot be committed, so its Git effect parks at once as
+ `git_target_ignored` naming the rule (since v0.60.427.0). Either un-ignore
+ it (remove or narrow the rule, commit that, then
+ `gbrain sources writer retry-effects <source> --parked-code git_target_ignored`)
+ or keep those pages database-only and leave the effects parked. Ask the
+ user which; it decides whether those pages are in the Git backup.
+
<a id="conflicts"></a>
## Conflicts
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index c3e62d89eb..99c9829201 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -29,6 +29,14 @@
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
+| A scheduled job, workspace script or hook finds nothing in the brain (every lookup empty), or its log shows `no_brain` or `GBRAIN_DB_ACCESS no_url`, while the same command works by hand | the job runs without the brain's config: call gbrain through one wrapper that sets `GBRAIN_HOME` and loads the brain's env file, and stop discarding its stderr ([the wrapper](cron-schedule.md#calling-gbrain-unattended)) | agent | none | the job's log shows results, and `gbrain engine status --json` run through the wrapper names the expected `db_url_source` |
+| `gbrain sources refresh` refuses `refresh_not_owner` from cron or a script but works by hand | the caller resolves another gbrain home, so it is another host; the refusal names the identity file, `HOME` and `GBRAIN_HOME` it read. Set the owner's `GBRAIN_HOME` in the wrapper (not `HOME`, which also swaps git credentials); never copy or delete a `host.json` | agent | none | `gbrain sources refresh <id> --dry-run` through the wrapper |
+| `gbrain sources refresh` refuses `refresh_diverged` on every run | something commits into the managed checkout outside gbrain, usually a script that writes files and runs `git commit` without pushing. `git log @{upstream}..HEAD` names the commits; move that writer to `put_page` or `capture`, then reconcile as the [refusal](write-refusals.md#refresh_diverged) says; never force ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)) | agent; reconciling after the user agrees | `destructive` when reconciling drops local commits | `gbrain sources refresh <id> --dry-run` |
+| A `--json` caller fails to parse gbrain's output | something other than gbrain wrote to stdout, usually a wrapper or a hook it runs; send that output to a log file or stderr (gbrain's own notices already go to stderr) | agent | none | the same call piped to `jq .` parses |
+| gbrain calls time out from a script or language runtime but finish by hand, or each search takes several seconds | a cold CLI start takes 3–6 s on a pooled Postgres brain: set caller timeouts of at least 10 s in both the shell and the runtime (a runtime exec timeout can override the shell's), and turn on the [warm CLI socket](cli-socket.md). If warm searches stay slow, measure the round trip to the database; one in another region dominates search time | agent; moving the database after the user agrees | none | `GBRAIN_DEBUG=1 gbrain search <query>` prints a `[cli-socket] warm:` line |
+| After a database change some processes still use the old server, or a URL variable silently keeps its old value | a shell-sourced env file has an unquoted `&` (the assignment ends there), or a process kept the environment it started with. Quote every value, keep Postgres URLs to `?sslmode=require` (driver options as variables, such as `GBRAIN_PREPARE=false`), update every URL variable the tooling reads, restart every gbrain process, and prove the switch from the database side ([switching a database](../../INSTALL_FOR_AGENTS.md#switching-a-database)). Never paste `env` output into a transcript while debugging | agent, after the user agrees | none | a row written after the restart appears on the new server |
+| Doctor `parked_effects` lists `git_target_ignored` effects | a `.gitignore` rule excludes those pages' files, so their Git effects cannot commit. The user decides: un-ignore (narrow the rule, commit it, then `gbrain sources writer retry-effects <source> --parked-code git_target_ignored`) or keep the pages database-only and leave the effects parked ([gitignored paths](shared-checkout-git.md#scripts-and-the-managed-checkout)) | agent, after the user decides | none | `gbrain sources writer status --source <id> --json` |
+| Sync and the maintenance cycle re-read a whole source on every run after its Git history was rewritten (force-push, `git filter-repo`) | the recorded base commit no longer exists. Move the checkout onto the new history ([upstream rewritten](#upstream-rewritten)); before the next rewrite, take the source out of automatic sync and run `gbrain sources mirror-readonly <id>` first | agent; the reset after the user agrees | `destructive` (the reset keeps a backup ref) | `gbrain doctor --only sync_failures --json` |
| [Database unreachable or `GBRAIN_DB_ACCESS <reason>`](#database-unreachable) | `gbrain engine status --probe`, then `gbrain db-repair` (diagnose); `gbrain db-repair --yes` applies safe fixes | agent; `--yes` after the user agrees | none to diagnose; `--apply-rewrites` rewrites the config URL (undoable) | `gbrain engine status --probe --json` |
| [PGLite `RuntimeError: Aborted()` at startup](#pglite-aborted) | automatic repair on the next command; else `gbrain pglite-repair --dry-run`, then `gbrain pglite-repair --yes` | agent; `--yes` after the user agrees | `destructive` (a WAL backup is kept and the restore command printed) | `gbrain doctor --only connection --json` |
| [`expected N dimensions, not M` on import](#embedding-dimensions) | `gbrain doctor` prints the exact `gbrain config set …` or `gbrain migrate embeddings --to <provider:model>` command | agent, after the user agrees | `migrate embeddings`: `paid`, needs the brain's writer lock | `gbrain doctor --only embeddings,embedding_width_consistency --json` |
diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.md
index 034d2ca5c3..13b0389150 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -71,6 +71,18 @@ Leave `GBRAIN_SOURCE` unset in the MCP env unless you deliberately want
single-source retrieval: a pin scopes every tool (search, `get_brain_identity`
counts, …) to that one source, and nothing warns on reads.
+## Scheduled jobs and workspace scripts
+
+OpenClaw cron jobs, workspace scripts and hooks run with another `HOME` and
+environment than the gateway's MCP server. Route every one of them through a
+single wrapper that sets `GBRAIN_HOME`, loads the brain's env file and runs the
+installed `gbrain` by absolute path; log its stderr and check its exit code
+([the wrapper and its rules](../guides/cron-schedule.md#calling-gbrain-unattended)).
+On a managed brain, scripts save pages through `put_page` or `capture` and
+never commit into the checkout; a scheduled `gbrain sources refresh <id>`
+keeps it current
+([scripts and the managed checkout](../guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
+
## Verify
`openclaw mcp list` should show `gbrain`. Then start an agent turn and ask it
diff --git a/llms-full.txt b/llms-full.txt
index a53cb518d9..6f628b7c02 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1824,7 +1824,7 @@ on `query`, `--source <id>`, `--limit`, `--json`; `gbrain backlinks <slug>` and
`gbrain timeline <slug>` for links and dated events. Copyable examples:
[brain-first](skills/conventions/brain-first.md#retrieval-gbrain-first).
-Recall relevant saved context before answering. Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.
+Recall relevant saved context before answering. Resolve a person (an email sender, an attendee) only by an exact frontmatter email or an exact title match, never a search's top hit ([identity rule](skills/conventions/brain-first.md#identity-exact-match)). Save explicit requests to remember with provenance; confirm corrections against the stored record. Automatic capture requires opt-in. Withdrawal (`forget`) removes a fact from active memory; history, source material, and private backups may remain. Never promise physical erasure. Verify changes with actual GBrain calls and distinguish a local test from a new-conversation test in the harness.
Durable preferences and facts belong in shared memory when the user wants them
recalled later. Transient task state, credentials, local configuration, and harness
@@ -1883,7 +1883,10 @@ machine contract. The quick version:
4. Treat `[gbrain notice …]` blocks and `[AGENT]` blocks the same way. A degraded result is not proof of "no notes".
<!-- END GENERATED agent-protocol:quick-contract -->
-Exit 3 always means "stop and ask the user". Full contract, transcripts, effects,
+Exit 3 always means "stop and ask the user". Exit 10 means the write was
+accepted and is still pending: never "not found" or "failed", so poll the
+receipt (`gbrain write-request <id>`) before retrying, reporting or moving on.
+Full contract, transcripts, effects,
exit codes and marker grammar: [`docs/protocol/AGENT_OPERATOR_v1.md`](./docs/protocol/AGENT_OPERATOR_v1.md).
## Read this order
@@ -1917,6 +1920,23 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
[`docs/guides/live-sync.md`](./docs/guides/live-sync.md),
[`docs/mcp/DEPLOY.md`](./docs/mcp/DEPLOY.md),
[`docs/guides/remote-mcp.md`](./docs/guides/remote-mcp.md) (`gbrain mcp expose`).
+- **Run gbrain from cron, workspace scripts and hooks:** every caller goes
+ through one wrapper that sets `GBRAIN_HOME` (never `HOME`), loads the
+ brain's env file and runs the installed binary, never `bun run src/cli.ts`
+ with an inherited environment. Log stderr (never `2>/dev/null`: a
+ `no_brain` refusal then reads as "no results"), check the exit code, keep
+ hook output off stdout, allow at least 10 s per call, and never print the
+ process environment into a transcript. On a managed brain, schedule
+ `gbrain sources refresh <id>` and never commit files into the checkout from a
+ script. Wrapper and rules:
+ [cron-schedule.md](docs/guides/cron-schedule.md#calling-gbrain-unattended),
+ [scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout).
+- **Delete or purge pages:** `gbrain delete --purge` skips the 72-hour soft
+ delete, cascades to chunks, versions, links and facts, and `gbrain restore`
+ cannot undo it. Purge only on the user's explicit go for that purge ("scrub
+ the repo" is not one), one page at a time, verifying each; a stopped batch
+ stays stopped until the user says again
+ ([data-loss gate](skills/data-loss-gate/SKILL.md)).
- **Bring in your chat history:** `gbrain transcripts ingest` imports a
downloaded ChatGPT / Claude export (or agent session logs); `gbrain connectors`
connects the account and syncs new conversations live, incrementally and on an
@@ -2837,6 +2857,25 @@ environment-dependent, so a re-run during an outage could silently repoint a
healthy Postgres brain at the PGLite floor. Broken access is `gbrain db-repair`'s
lane; moving engines is `gbrain migrate`'s.
+**Put the database next to the agent.** A warm search makes dozens of
+sequential round trips to Postgres, so the distance between the agent host and
+the database dominates its latency: in one deployment, moving Postgres into the
+agent host's region took warm search from 3.0 s to 1.2 s at p50. Create the
+database (and use the pooler) in the region of the machine that runs the agent
+and its `gbrain serve`.
+
+<a id="switching-a-database"></a>
+**Switching a brain's database** (a region move, a new server): stop gbrain's
+writers, then change every URL the tooling reads, not just the main one:
+`GBRAIN_DATABASE_URL`, `DATABASE_URL`, `GBRAIN_DIRECT_DATABASE_URL`, the
+`database_url` in `config.json`, and each env file, wrapper and service
+definition that sets them (`gbrain engine status --json` shows which source
+wins, with the password redacted). Restart every gbrain process, since a
+running process keeps the environment it started with. Prove the switch from
+the database side: a row written after the restart (a job, a test page)
+appears on the new server and no gbrain session remains on the old one. A
+shell's `echo $DATABASE_URL` proves only that shell.
+
`--json` emits `{status, engine, ladder_rung, url_source}` as the ONLY stdout
content so a scripted install can `| jq` it. The access token is never
persisted, logged, or echoed.
@@ -3164,6 +3203,17 @@ Read skills/soul-audit/SKILL.md and follow it.
This generates SOUL.md (agent identity), USER.md (user profile), ACCESS_POLICY.md
(who sees what), and HEARTBEAT.md (operational cadence) from the user's answers.
+**On OpenClaw 2026.10.6 and later,** `openclaw doctor --fix` imports a
+workspace `HEARTBEAT.md` into its own monitor, archives the file under the
+state directory's `backups/heartbeat-migration/` and removes it, while the
+rendered `AGENTS.md` still tells the agent to read it at session start. Until
+the render adapts to OpenClaw ([#7470](https://github.com/garrytan/gbrain/issues/7470)),
+put gbrain's file back after each doctor fix: `gbrain bootstrap render --only HEARTBEAT.md`
+re-renders it from the confirmed answers, or copy the archived file back when
+the user edited it. Jobs that must run on time belong in the host scheduler
+through the [one wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended),
+not only in `HEARTBEAT.md`, which runs only when a session starts.
+
If skipped, minimal defaults are installed automatically.
## Step 7: Recurring Jobs
@@ -3173,7 +3223,30 @@ capture, enrichment, maintenance or a service; do not infer consent from a
successful install or from a health recommendation.
Set up using your platform's scheduler (OpenClaw cron, Railway cron, crontab), or skip the
-platform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon):
+platform glue entirely with `gbrain autopilot --install` (built-in self-maintaining daemon).
+
+Every cron job, workspace script and hook calls gbrain through **one wrapper**
+that sets `GBRAIN_HOME` (never `HOME`), loads the brain's env file and runs
+the installed binary, never `bun run src/cli.ts` with an inherited
+environment. A scheduled job has another `HOME` than your shell, so a bare
+call finds no database (every lookup silently empty) or acts as a second host
+(`refresh_not_owner`). Log the wrapper's stderr instead of sending it to
+`/dev/null`, check exit codes against the [operator protocol](docs/protocol/AGENT_OPERATOR_v1.md),
+keep hook output off stdout so `--json` stays parseable, and give each call a
+timeout of at least 10 s. The wrapper and its rules:
+[call gbrain through one wrapper](docs/guides/cron-schedule.md#calling-gbrain-unattended).
+
+- **Managed brain checkout** (every 15 min, on the owner host):
+ `gbrain sources refresh <id>` is the only sanctioned fast-forward; it drains
+ writes, fast-forwards and re-syncs. Scripts save pages through
+ `put_page`/`capture`, never by writing and committing files in the
+ checkout: an unpushed local commit makes the checkout diverge and every
+ refresh refuse `refresh_diverged`
+ ([scripts and the managed checkout](docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
+- **Workers**: start `gbrain jobs supervisor` with `--max-rss <MB>`; with
+ `--job-isolation process` the cap also covers each job child's process tree
+ (v0.60.426.0). Size the host for (concurrency + 1) × the cap
+ ([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:
@@ -3278,6 +3351,12 @@ 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, upgrade
+every install, restart every gbrain process and verify that each reports the
+new version, then `gbrain autopilot resume`
+([the order](skills/gbrain-upgrade/SKILL.md#always-on-hosts-pause-drain-upgrade-verify-resume)).
+
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:
@@ -7505,7 +7584,12 @@ vars — incident-time escape hatches, not everyday knobs.
`sources.refresh_fetch_timeout_ms`, `GBRAIN_REFRESH_FETCH_TIMEOUT_MS`).
A refresh interrupted by a crash is finished by the restarted owner or by
`gbrain sources refresh <source-id> --resume`. A cron that keeps a managed
- brain current runs the refresh instead of `git pull`.
+ brain current runs the refresh instead of `git pull`, through the same
+ [wrapper](cron-schedule.md#calling-gbrain-unattended) as every other
+ scheduled gbrain call (so it runs as the owner host). `refresh_diverged`
+ means something commits into the checkout outside gbrain: fix that writer
+ instead of forcing the checkout
+ ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)).
**Say to your agent:** *"Bring my notes source up to date with its remote."*
@@ -7676,8 +7760,9 @@ those (`maintenance_lock_busy`) and the holder runs them.
# Calendar sync — Sundays at 10 AM
0 10 * * 0 cd /path/to/calendar-sync && node calendar-sync.mjs --start $(date -v-7d +%Y-%m-%d) --end $(date +%Y-%m-%d)
-# Brain health — weekly Mondays at 6 AM
-0 6 * * 1 gbrain doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain embed --stale
+# Brain health — weekly Mondays at 6 AM. Every gbrain call goes through the
+# wrapper below (gbrain-run), never a bare `gbrain` or `bun run src/cli.ts`.
+0 6 * * 1 gbrain-run doctor --json >> /tmp/gbrain-health.log 2>&1 && gbrain-run embed --stale
# Autopilot health gate — daily at 7 AM. The exit code is the signal:
# 0 fresh (or nothing installed), 1 needs attention (stale heartbeat,
@@ -7688,12 +7773,85 @@ those (`maintenance_lock_busy`) and the holder runs them.
# daemon writes the maintenance verdict each tick), so it works even during
# a DB outage. On a stall: gbrain doctor --only global_maintenance_stalled
# names the phase and the command to run.
-0 7 * * * gbrain autopilot --status >> /tmp/gbrain-autopilot-health.log 2>&1 || your-notify "gbrain autopilot needs attention"
+0 7 * * * gbrain-run autopilot --status >> /tmp/gbrain-autopilot-health.log 2>&1 || your-notify "gbrain autopilot needs attention"
# Dream cycle — nightly at 2 AM
0 2 * * * /path/to/dream-cycle.sh
```
+<a id="calling-gbrain-unattended"></a>
+### Call gbrain through one wrapper
+
+A scheduled job does not run in the shell you tested it in. Cron, a harness's
+workspace scripts and git hooks start with another `HOME`, a bare `PATH` and
+whatever environment their parent had, so a call that works by hand can do
+something else on a schedule:
+
+- **No database.** The job finds no brain config or URL, gbrain refuses
+ (`no_brain`, or `GBRAIN_DB_ACCESS no_url`) on stderr, and a caller that
+ drops stderr reads every lookup as "nothing found".
+- **A second host.** gbrain keeps its host identity under the brain home, so a
+ job that resolves another home is another host: `gbrain sources refresh`
+ refuses `refresh_not_owner` (since v0.60.427.0 it names the identity file it
+ read and the `HOME` and `GBRAIN_HOME` it resolved), and owner-only
+ maintenance reports `owner_unavailable` with reason `host_mismatch`.
+- **A stale database.** A variable the caller already exported wins over the
+ brain's `config.json` and `.gbrain/.env`, so a job started from an old
+ environment keeps using the old `DATABASE_URL`.
+
+Give every cron line, workspace script and hook one entry point, a wrapper that
+sets `GBRAIN_HOME`, loads the brain's env file if the harness keeps one, and
+runs the installed binary:
+
+```bash
+#!/usr/bin/env bash
+# gbrain-run: the only way scheduled work calls gbrain
+set -euo pipefail
+export GBRAIN_HOME=/srv/gbrain # parent of .gbrain; the value serve, workers and autopilot use
+if [ -f /srv/gbrain/brain.env ]; then # only if the harness keeps the brain's settings in its own file
+ set -a; . /srv/gbrain/brain.env; set +a
+fi
+exec /srv/gbrain/.bun/bin/gbrain "$@" # the installed binary, by absolute path
+```
+
+Rules for the wrapper and everything that calls it:
+
+1. **Set `GBRAIN_HOME`, never `HOME`.** `GBRAIN_HOME` moves only gbrain's
+ state. Changing `HOME` also changes the git identity, SSH keys and push
+ credentials the job runs with. Use the same value as the serve, the workers
+ and autopilot; doctor `host_identity_mismatch` names a process that differs.
+2. **Run the installed binary.** Never `bun run src/cli.ts` from a checkout with
+ the caller's inherited environment: it skips the wrapper's settings and can
+ run another build than the serve.
+3. **Keep stderr and the exit code.** Never send gbrain's stderr to
+ `/dev/null`. Append it to a log and branch on the exit code
+ ([exit codes](exit-codes.md)): `10` means the write was accepted and is
+ still pending, not "not found" or "failed"; `3` means stop and ask the
+ user. A refusal fails the job; it is never an empty result.
+4. **Keep stdout clean.** A `--json` caller parses stdout as one document, so
+ the wrapper and any hook it runs log to a file or stderr, never stdout.
+5. **Allow time.** A cold CLI start takes 3–6 s on a pooled Postgres brain.
+ Set caller timeouts of at least 10 s in the shell and in the language
+ runtime that runs it (a runtime's exec timeout can override the shell's
+ without saying so), and turn on the [warm CLI socket](cli-socket.md) so
+ reads skip the cold start.
+6. **Quote the env file.** A file a shell sources is shell syntax. An unquoted
+ `&` in a URL ends the assignment and backgrounds the rest, so the variable
+ silently keeps its old value. Quote every value, keep Postgres URLs to
+ `?sslmode=require` (set driver options such as `GBRAIN_PREPARE=false` as
+ variables instead of extra `&` parameters), and restart every running
+ gbrain process after an edit: a process keeps the environment it started
+ with.
+7. **Never print the environment.** `env`, `printenv` or a process's
+ `environ` holds the database URL and API keys, and a transcript keeps them.
+ To debug, print variable names only, or run `gbrain engine status --json`,
+ which redacts the URL.
+
+On a managed brain the same wrapper runs `gbrain-run sources refresh <id>` on
+a schedule ([the managed cron line](../../skills/cron-scheduler/SKILL.md#managed-brain)).
+Scripts never write files and `git commit` straight into the managed checkout;
+see [shared-checkout git](shared-checkout-git.md#scripts-and-the-managed-checkout).
+
### Quiet Hours Gate (MANDATORY)
Every cron job that sends notifications MUST check quiet hours first. The
@@ -8044,597 +8202,6 @@ echo "Dream cycle complete at $(date)"
---
-## docs/guides/scaling-skills.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/scaling-skills.md
-
-# Scaling skills past 300 without drowning the context window
-
-When an agent grows past 100 skills, a wall starts forming. Sessions take
-longer to start. The model gets a little dumber about which skill to pick.
-Tokens that should be powering reasoning are powering a skill catalog the
-model reads on every turn whether it needs to or not.
-
-This guide is the recipe for breaking through that wall without deleting
-capabilities. Three tiers, one resolver, one safety net. Production-tested
-on a 306-skill agent (Garry's OpenClaw, the agent behind Y Combinator's
-president). The pattern works whether you run OpenClaw, Hermes, Claude Code,
-Cursor, or your own MCP-aware agent.
-
-## The problem
-
-OpenClaw scans every skill file on disk at session start and injects them
-into the system prompt as `<available_skills>` entries. The model sees a
-name, description, and file path for each one. When a request matches, the
-model reads the full SKILL.md and follows it.
-
-This is great architecture at 50 skills. At 100, it's fine. At 200, it
-starts to drag. At 300, the system prompt eats more than 25,000 tokens on
-skill descriptions alone. Tokens that aren't going to reasoning, context,
-or actual work.
-
-The symptoms compound:
-
-- Sessions take noticeably longer to start.
-- The model has less room for conversation history.
-- Skill routing gets fuzzier. With 300 descriptions competing for attention,
- the model occasionally picks the wrong one.
-- Cost goes up because every turn carries the full skill manifest.
-
-The naive fix is to delete skills you don't use often. Don't do this. The
-whole point of skills is that capabilities compound. A gift pipeline that
-fires twice a month saves 30 minutes each time it does. A flight tracker
-fires once per trip and prevents a missed Uber. Deleting low-frequency
-skills optimizes for prompt size at the cost of capability. You wouldn't
-delete apps from your phone because the home screen is too crowded. You'd
-organize them.
-
-## The three tiers
-
-Not all skills need to be visible to the model at all times. Some are core.
-Some are specialized. Some are dormant.
-
-### Tier A: always loaded (~35 skills)
-
-The skills the model needs on every single turn. Brain search, email triage,
-calendar, meeting ingestion, content creation, the executive assistant.
-They stay in the system prompt's `<available_skills>` manifest. The model
-sees them natively and routes to them without any lookup.
-
-### Tier B: resolver-routed (~85 skills)
-
-Real, active skills that fire regularly but don't need to pollute every
-turn. Gift pipeline, flight tracker, investor update ingestion, adversary
-tracking, book mirror, civic intelligence. They live on disk. They have
-full SKILL.md files. But OpenClaw doesn't inject them into the prompt.
-
-Instead, a compact RESOLVER.md handles routing. One line per skill with
-trigger phrases:
-
-```markdown
-- **gift-advisor**: gift idea | what should I bring | birthday gift | housewarming
-- **flight-tracker**: track my flight | flight status | when does my flight land
-- **investor-update-ingest**: investor update | portfolio update | company metrics
-```
-
-When the model sees "what should I bring to Jessica's dinner," it checks
-the resolver, finds `gift-advisor`, reads the SKILL.md, and executes. Same
-result. Zero wasted tokens on the other 84 turns where gifts aren't relevant.
-
-### Tier C: dormant (~180 skills)
-
-Built-in OpenClaw skills that aren't in active rotation (1Password, Discord,
-Notion, Trello, integrations you haven't wired up yet) plus specialized
-skills that almost never fire. They're explicitly disabled in the config
-with `enabled: false`. They exist on disk as documentation and potential.
-Flip one boolean to wake them up. Zero tokens contributed to every prompt
-until then.
-
-### The numbers
-
-Before tiering, on Garry's 306-skill OpenClaw:
-
-| Metric | Before |
-|---|---|
-| Skills in system prompt | 306 |
-| Skill-description tokens per turn | ~25,000 |
-| Skill routing accuracy | degrading |
-| Session startup | slow |
-
-After tiering:
-
-| Metric | After |
-|---|---|
-| Skills in system prompt (Tier A) | 35 |
-| Skill-description tokens per turn | ~4,000 |
-| Skills still accessible (A + B + C) | 301 |
-| Capability loss | zero |
-| **Tokens freed per turn** | **~21,000** |
-
-21K tokens per turn is not a small optimization. It's the difference between
-the model having room to think and the model being squeezed. It's the
-difference between carrying 3 pages of conversation history and carrying 15.
-
-## What the resolver actually does
-
-The resolver is cheaper than the manifest. That's the load-bearing insight.
-
-OpenClaw's native skill manifest puts ~80 tokens per skill into the system
-prompt (name + description + location). At 300 skills that's 24,000 tokens
-spent every turn whether the model needs the catalog or not.
-
-The resolver puts ~15 tokens per skill into a compact markdown list. At
-300 skills that's 4,500 tokens. But it only fires when the model checks
-it, which is only when the request doesn't match a Tier A skill. Most
-turns, the resolver costs zero tokens because the Tier A match handles it.
-
-This is the routing-table pattern but applied to the skill manifest itself.
-The resolver routes to skills, but it also routes around skills, keeping
-them out of the context window until they're needed.
-
-GBrain ships with a [bundled `skills/RESOLVER.md`](../../skills/RESOLVER.md)
-you can use as a reference shape. The skillpack story for distributing
-your own resolvers across machines is covered in
-[skillpacks as scaffolding](skillpacks-as-scaffolding.md).
-
-## The compact list format
-
-GBrain's resolver parser reads two dialects. Markdown tables:
-
-```markdown
-| Trigger | Skill |
-|---------|-------|
-| "gift idea" | `skills/gift-advisor/SKILL.md` |
-```
-
-Tables are fine at 20 entries, unwieldy at 200, unreadable at 300. The
-compact list format scales better:
-
-```markdown
-- **gift-advisor**: gift idea | what should I bring | birthday gift
-- **flight-tracker**: track my flight | flight status | when does my flight land
-```
-
-The same `parseResolverEntries` function reads table rows and list rows
-in the same file, with the multi-resolver merge (skillpack
-`skills/RESOLVER.md` + workspace `../AGENTS.md`) folding everything into
-one unified view, so a compact-format resolver is fully visible to
-`gbrain doctor`.
-
-### The list-format contract
-
-A few rules to keep the parser unambiguous:
-
-- **Skill names must be kebab-lowercase.** `gift-advisor`, `flight-tracker`,
- `email-triage`. Names that start with an uppercase letter (`MyTool`,
- `Note`, `Convention`) are deliberately ignored. This is what stops prose
- bullets like `- **Note**: see [link]` from being mis-parsed as skill
- rows in real-world AGENTS.md files.
-- **The path always resolves to `skills/<name>/SKILL.md`.** An optional
- `→ \`skills/path\`` (or ASCII `->`) suffix is allowed for readability,
- but the parser strips it. For non-conventional paths (skills under
- nested directories, references into `conventions/`, anything that
- isn't `skills/<name>/SKILL.md`), use the table format.
-- **Triggers separate with `|`.** Empty pieces and the literal `...`
- placeholder are dropped. Each trigger becomes its own resolver entry,
- all pointing at the same skill.
-- **Bold or plain.** `- **name**: triggers` is preferred. `- name: triggers`
- works as a fallback.
-
-You can mix table and list rows in the same file. Useful when a brain
-inherits a table-format `RESOLVER.md` from gbrain and a list-format
-`../AGENTS.md` from OpenClaw.
-
-## The doctor safety net
-
-The danger with tiering is invisible skill loss. You disable a skill from
-native scanning, forget to add it to the resolver, and now the agent can't
-do something it used to do. You won't notice until the moment you need it.
-
-`gbrain doctor` walks every skill on disk and verifies it's reachable,
-either through native scanning (Tier A) or through the resolver (Tier B
-and C). On Garry's setup, the first run after tiering found 63 unreachable
-skills. Sixty-three capabilities that existed on disk but had no routing
-path. Fixed in an hour by adding resolver entries.
-
-Run it after every skill change:
-
-```bash
-gbrain doctor
-```
-
-For CI gates, use the JSON-emitting variant:
-
-```bash
-gbrain check-resolvable --json
-gbrain check-resolvable --strict # warnings fail too
-```
-
-If a skill is unreachable, the output tells you which one and suggests
-the fix. The resolver is a document. Documents are cheap to fix.
-
-## Implementation walkthrough
-
-Three changes. Total time about 45 minutes once you've decided which
-skills go in which tier.
-
-### 1. Audit and tier your skills
-
-Walk through every skill. Ask: does this need to fire on every turn?
-
-- If yes → Tier A.
-- If it fires weekly or less but is real → Tier B.
-- If you don't use it → Tier C.
-
-### 2. Disable Tier B and C in your agent's config
-
-For OpenClaw, the file is `openclaw.json`. Add an entry per disabled skill:
-
-```json
-{
- "skills": {
- "entries": {
- "gift-advisor": { "enabled": false },
- "flight-tracker": { "enabled": false },
- "1password": { "enabled": false }
- }
- }
-}
-```
-
-The exact config shape depends on which agent runtime you use. The point
-is the same in all of them: tell the runtime not to inject this skill into
-the system prompt. The file stays on disk; only the prompt injection stops.
-
-### 3. Write the resolver
-
-One line per Tier B and Tier C skill. Trigger phrases that match how you
-actually ask for things:
-
-```markdown
-- **gift-advisor**: gift idea | what should I bring | birthday gift
-- **flight-tracker**: track my flight | flight status | when do I land
-- **investor-update-ingest**: investor update | portfolio update | company metrics
-```
-
-That's it. The model handles the rest. When a request doesn't match Tier A,
-it checks the resolver, reads the matching SKILL.md, and executes.
-
-### 4. Run `gbrain doctor` and fix any unreachable skills
-
-The doctor sweep tells you which skills don't have a routing path. Add a
-resolver entry for each one, re-run, repeat until the count is zero.
-
-## Fix the tool, not the data
-
-When a tool fails against valid data, the right move is to fix the tool,
-not reshape the data. A clean list-format resolver is correct, compact,
-readable, and easy to maintain; a validator that only understands one
-shape is the bug, and the parser accepts both shapes for that reason.
-
-The same principle applies everywhere in agent systems. Your SKILL.md is
-the source of truth. Your AGENTS.md is the source of truth. Your resolver
-is the source of truth. When tooling disagrees with your configuration,
-the tooling is wrong. Fix the tooling.
-
-## The scaling curve
-
-At 50 skills, you don't need any of this. Just load everything.
-
-At 100, you start feeling the drag but can push through.
-
-At 200, routing accuracy drops and sessions get noticeably slower. This
-is where most people stop adding skills, which means their agent stops
-getting more capable. Bad trade.
-
-At 300+, tiering is mandatory. But with tiering, there's no ceiling.
-1,000 skills with 35 in the hot path and 965 in the resolver is the same
-per-turn cost as 35 skills with no resolver. The cost stays flat.
-Capabilities compound.
-
-The architecture that gets you from 50 to 300 is different from the
-architecture that gets you from 10 to 50. That's normal. Systems that
-scale change shape. The important thing is that each tier preserves full
-capability. You're organizing, not deleting.
-
-## Plugin bundling is a curation decision
-
-Not every skill in `skills/` reaches downstream installs. The plugin
-manifest (`openclaw.plugin.json`) is the bundled set; everything else is a
-recorded exclusion in `skills/plugin-exclusions.json`, each with a reason.
-The two are test-pinned in both directions: every manifest skill is either
-bundled or a recorded exclusion, and no skill is both. Adding a skill to
-the tree does NOT ship it — bundling is an explicit decision, and an
-unbundled skill never reaches a downstream install. When you write a new
-skill, decide (and record) which side of that line it lives on.
-
-`bun run gate:skills` (`scripts/skills-commit-gate.sh`) is the per-commit gate
-for any change under `skills/`. It runs the conformance + resolver +
-plugin-manifest tests, `check-resolvable --strict`, the `skills.lock.json`
-regen + freshness check, and `check-skill-refs` in seconds — run it before
-committing a skills change so the membership/closure and `plugin.version`
-assertions fail locally instead of in CI.
-
-`check-skill-refs` fails on two things:
-
-- **A `gbrain` command that cannot run.** Every `gbrain <cmd>` in a code block
- or inline span must be real (`gbrain embed refresh` fails with its
- replacement). Paid commands go preview, user approval, then `--yes --max-usd <cap>`.
-- **A relative link that leaves `skills/`**, which dangles in every copied
- skill. Link the protocol through `skills/conventions/agent-operator-protocol.md`
- and other docs by absolute URL; `bun scripts/portable-skill-links.ts` rewrites
- both (honoring `LLMS_REPO_BASE`). `skills/migrations/**` is exempt.
-
-## When a skill misroutes
-
-Treat a misroute like a failing test, because it becomes one. First
-reproduce it as a fixture in the skill's `routing-eval.jsonl` — the utterance
-that misrouted, with the expected skill (or `null`). Rewrite the misrouted
-utterance onto placeholder entities (`alice-example`, `acme-example`) before
-committing the fixture — same rule as skill-autobench; a routing fixture is a
-public artifact and must not carry a real contact or company name. Only then
-fix the cause:
-usually a trigger in the skill's frontmatter or its row in
-`skills/RESOLVER.md`. Regenerate the lock (`bun run
-scripts/generate-skills-manifest.ts`) and the llms bundles (`bun run
-build:llms`), verify with `gbrain check-resolvable --strict`, and ship it as
-a MICRO release. Downstream installs heal on their next upgrade — the fix
-travels with the skillpack, not with a support thread.
-
-## Related
-
-- [Skill development cycle](skill-development.md) — the 5-step loop for
- turning a repeated task into a real skill.
-- [Skillpacks as scaffolding](skillpacks-as-scaffolding.md) — how to
- distribute a coherent set of skills across machines and agents.
-- [Sub-agent routing](sub-agent-routing.md) — when to delegate to a
- sub-agent vs handle in-line, and the model routing table for each path.
-
-GBrain: [github.com/garrytan/gbrain](https://github.com/garrytan/gbrain).
-The `parseResolverEntries` parser lives at
-[`src/core/check-resolvable.ts`](../../src/core/check-resolvable.ts);
-the bundled resolver lives at [`skills/RESOLVER.md`](../../skills/RESOLVER.md).
-
----
-
-## docs/guides/push-context.md
-
-Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/push-context.md
-
-# Push-based context
-
-Pull retrieval needs the agent to *know to ask* before the brain contributes
-anything. Push-based context adds the other direction: the brain volunteers
-relevant pages from the recent conversation, confidence-gated so push noise
-never becomes worse than pull silence.
-
-The push channels share one zero-LLM core (`src/core/context/volunteer.ts`):
-
-| Channel | Surface | When to use |
-|---|---|---|
-| `reflex` | automatic, inside the context engine | default-on for plugin hosts; nothing to call |
-| `op` | `gbrain volunteer-context` / MCP `volunteer_context` | agents without the plugin; one call per turn |
-| `watch` | `gbrain watch` | stream a transcript in, volunteered pages stream out |
-| `claude-code` / `codex` / `opencode` | `gbrain hook user-prompt` (registered by `gbrain bootstrap`) | per-prompt injection inside a harness; see "Harness hooks" below |
-
-Push context is READ-side. Its WRITE-side sibling — the opt-in ambient
-memory writeback channel (`gbrain hook stop` banking gated user turns for
-serve-side extraction, `memory.auto_writeback`) — is documented in
-[ambient-writeback.md](./ambient-writeback.md).
-
-## How it decides
-
-1. **Extract** entities across the last N turns (capitalized runs, `@handles`),
- merged with recency / frequency / user-role salience. Assistant-introduced
- entities and "what did she invest in?" follow-ups whose antecedent was named
- in the window resolve.
-2. **Resolve** through the alias table, exact titles, surnames, and slug
- suffixes — each arm carries an honest confidence: alias 0.9, exact title
- 0.8, surname 0.72, slug-suffix 0.6, +0.05 when mentioned in ≥2 turns or the
- newest turn. Lowercase mentions ("remind me what alice said") probe the
- alias table only, and only when the alias is unique across every source in
- play; a surname-only reference ("Did Galewright follow up?") resolves when
- exactly one person page carries that surname. Ambiguity in either arm
- injects nothing — silence beats a wrong pointer. Kill switch for both:
- `retrieval_reflex_lexical_arms` (default on).
-3. **Gate** at `min_confidence` (default 0.7 — slug-suffix matches need an
- explicit lower gate), suppress pages already surfaced (slug-presence only),
- cap at 3 pages (hard cap 5).
-
-## CLI
-
-```bash
-# one-shot: pipe recent turns (oldest → newest)
-printf 'user: ask alice-example about the deal\nassistant: noted\nuser: what did she say?\n' \
- | gbrain volunteer-context
-
-# streaming: volunteered pages print as the transcript flows
-some-transcript-feed | gbrain watch --json
-
-# the feedback loop: how often were volunteered pages actually opened?
-gbrain volunteer-context --stats
-```
-
-Stats are **approximate** by design: "used" means the page's last retrieval
-(`page_retrievals.last_retrieved_at`, or the legacy `pages.last_retrieved_at`) >
-`volunteered_at` — the 5-minute last-retrieved throttle causes false negatives
-and unrelated reads of the same page cause false positives. Use the per-arm
-precision to tune `min_confidence`, not as an exact metric.
-
-**PGLite + `gbrain watch`:** PGLite is single-connection, and watch holds its
-connection for the whole session — a concurrent `gbrain serve` or any write
-path blocks until watch exits. On a PGLite brain, run watch in bursts (piped
-input exits at EOF) or use the ambient reflex channel instead, which routes
-through a running serve's resolve socket rather than taking the lock. Routing
-watch through that same socket is a filed follow-up (TODOS.md). Postgres
-brains are unaffected.
-
-## Harness hooks (the prompt-time channel)
-
-`gbrain bootstrap` registers `gbrain hook user-prompt` as a Claude Code
-`UserPromptSubmit` hook: every prompt is assembled into a per-turn context
-block (reflex pointers + volunteered pages + hot facts) through a running
-serve's IPC socket and injected as `additionalContext`. Two properties make
-this channel production-grade rather than spammy-and-invisible:
-
-- **Cross-turn dedupe.** The hook reads its OWN previous injections back out
- of the session transcript (Claude Code records them as structured
- `hook_additional_context` attachments; only gbrain-marked blocks count) and
- passes them as prior context — so a page is volunteered once per session,
- not once per mention. The dedupe horizon is bounded (the recent transcript
- window, byte-capped), so a marathon session can eventually re-volunteer its
- oldest injections. The extraction is structural, never substring matching
- over raw turn text, so a short slug appearing in a tool payload can't
- over-suppress.
-- **The feedback loop.** The serve logs each DELIVERED block's volunteered
- pages and pointers to `context_volunteer_events` under the hook's channel
- (`claude-code` by default; a codex hook registration passes
- `--harness codex` / `--harness opencode`). `gbrain volunteer-context --stats` then shows
- per-harness precision, and `gbrain doctor`'s `volunteer_channels` check
- shows which channels actually fire, with guidance for the two quiet cases:
- "hook installed but never registered (restart the session)" and "registered
- but quiet". Logging happens at the delivery point only — a block abandoned
- before the serve responded is never counted — and because a delivered
- response still isn't proof of injection (the hook can trim or drop it
- client-side), the doctor check reconciles the counts against the hook's own
- heartbeat and cautions when they diverge.
-
-The hook lane rides the running serve's IPC socket on PGLite and Postgres alike
-(the listener is engine-uniform and keys its socket off the connection URL), so
-the hook stays quiet only while no `gbrain serve` for the brain is running, and
-on a thin-client install, where pull-mode retrieval covers it.
-
-Kill switch: `GBRAIN_HOOKS=0`. Install/uninstall: `docs/guides/bootstrap.md`.
-
-## The proactive brief ("Before you start", off by default)
-
-Wave 5 D5. Before a meeting or a reply, the brain can hand the agent at most
-three dated items about the counterparty it did not ask for. It is off until
-the owner turns it on with `gbrain config set context.proactive_brief true`;
-with the key unset, no hook output and no `context_pack` response changes. It
-stays off by default until the D6 evaluation shows the agent does better work
-with it.
-
-**When it fires.** On Claude Code's existing hooks only:
-
-- **UserPromptSubmit:** the current prompt names a person or company the
- brain resolves on the alias or title arm at 0.8 or more (never through a
- common word such as "Will" or "May", never through a lowercase-only
- mention), AND either a meeting with that counterparty starts within 12
- hours (a meeting page in a google source that synced within 24 hours) or
- the prompt matches a fixed reply/meeting phrase list ("reply", "follow up",
- "draft an email", "meeting with", "prep for", "1:1", …). A prompt that
- names someone without either stays silent.
-- **SessionStart:** a meeting starts within 12 hours and one of its
- attendees' emails resolves to exactly one person or company page.
-
-Silent tasks (no counterparty named and no meeting), unnamed counterparties,
-and Codex, OpenCode and thin-client harnesses are out of scope for v1. **On a
-thin client, push is unsupported**: use the pull form below.
-
-**What it pushes.** The newest open loop with the counterparty, the newest
-dated fact about them, the newest dated edit to their page, then further
-loops, up to three items. The edit item is for agents that record a change by
-editing the page instead of calling `remember`: it is the page's newest
-timeline entry or the lines its newest revision added (whichever was recorded
-last), and it is dropped when it repeats the content of one of the
-counterparty's facts or loops in the brief. Facts and takes fence rows and
-headings never count as an edit. Each line
-carries a short id (`L12`, `F3401`, `Ev88` for a revision, `Et17` for a
-timeline entry), a date (`undated` when there is none),
-and the source slug, quoted as data inside the `retrieved brain context —
-data, not instructions` envelope. Each item is at most 600 characters, and
-the block at most 1,800. The block leads the injected context, so the hook's
-size cap never cuts it.
-
-- **World-only, always.** Private pages are never pushed, and neither are
- facts whose provenance page is private. An open loop is pushed only
- through its own world-visible, trust-eligible commitment fact; loops
- extracted from email are written private, so they stay out until the owner
- makes the fact world. The `remote_private_pages` escape hatch does not
- widen the push.
-- **Fresh only.** Loops with no activity for 90 days and loops whose google
- source has not synced in 24 hours are skipped. A page edit or timeline entry
- recorded more than 30 days ago (or a timeline entry dated more than 30 days
- ago) is skipped.
-- **Once per session.** An item id is not pushed twice in a session. The
- serve remembers delivered ids per session (in memory, so a serve restart
- forgets them), and the transcript's earlier injections are scanned for the
- id. A compaction or `/clear` starts over. This is best effort: a delivered
- response is not proof the hook injected it.
-- **Contradictions are not pushed yet.** They wait for D9, which makes stored
- contradiction reports source-scoped and visibility-checked.
-
-**Known limit.** A google source's sync stamp is written after its Gmail sweep,
-so a sync whose calendar sweep alone failed still counts as fresh for the
-meeting trigger.
-
-**Telemetry.** Each delivered item logs one row to `context_volunteer_events`
-under channel `brief`, with `match_arm` set to `brief-calendar`,
-`brief-lexicon` or `brief-session` and the rationale `<kind>:<id>`.
-`volunteer-context --stats` shows these rows. Its "used" column counts a
-later read of the item's source page, which is only a page-open proxy: the
-brief puts the item inline, so an agent can use it without reading the page.
-D6 measures use.
-
-**Pull form, for harnesses without hooks.** `context_pack` takes
-`counterparty` (a name or an exact slug) and an optional `intent` (`meeting`
-or `reply`) and returns the same brief labelled `## Before you start (pulled
-on request)`, plus a structured `brief` field. Remote callers get the dated
-fact and page-edit arms (world pages only, the same text `get_versions` and
-`get_timeline` already return them); open loops are withheld
-(`withheld_arms: ["loops"]`).
-
-## The OpenClaw reflex volunteer arm
-
-The OpenClaw context-engine lane's ambient reflex runs TWO arms per
-windowed turn: Arm 1 resolves entity pointers (the classic 3-pointer block),
-then Arm 2 runs the same `volunteerStage` gate the Claude Code turn-context
-lane ships — up to 3 additional confidence-gated pages (0.7 gate), deduped
-against the turn's pointers, rendered in the same wire idiom. Volunteer
-events from this lane log to `context_volunteer_events` under the `openclaw`
-channel (in-process only — the wire-claimable harness channel allowlist
-deliberately excludes it, so a hook client cannot spoof production
-attribution; on the PGLite/IPC rung these events are not logged; extending the
-log to that rung is a filed follow-up in TODOS.md).
-
-**Say to your agent:** *"Turn off the brain's volunteered context for now"* —
-your agent sets `retrieval_reflex_volunteer` to `false` (or exports
-`GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER=off` when config is unreachable — env wins
-over config as the incident lever). *"How often are volunteered pages actually
-used?"* — your agent runs `gbrain volunteer-context --stats`.
-
-## Config
-
-| Key | Default | What it does |
-|---|---|---|
-| `retrieval_reflex_window_turns` | 4 | turns the ambient reflex extracts from; 1 = current turn only (file/env plane: `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`) |
-| `retrieval_reflex` | true | the ambient channel's master switch (env: `GBRAIN_RETRIEVAL_REFLEX`; negatives `false/0/off/no`, case-insensitive) |
-| `retrieval_reflex_volunteer` | true | the reflex volunteer arm (Arm 2) — the incident kill switch for volunteered pages on the OpenClaw lane (env: `GBRAIN_RETRIEVAL_REFLEX_VOLUNTEER`, env above config) |
-| `retrieval_reflex_max_pointers` | 3 | pointer cap per turn |
-| `retrieval_reflex_lexical_arms` | true | the lowercase-alias + surname recall arms (env: `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`); off = disables both arms |
-| `context.hot_memory.session_only` | off | hot facts on the turn and session-start hooks come from the current session only, with no fallback to other sessions' recent facts (DB-plane; see [ambient writeback](ambient-writeback.md#hot-memory-and-other-sessions)) |
-| `context.proactive_brief` | off | the proactive brief ("Before you start") on the SessionStart and UserPromptSubmit hooks (DB-plane: `gbrain config set context.proactive_brief true`) |
-
-Per-call knobs: `max_pages` + `min_confidence` on both the op and `gbrain watch`
-(`--max-pages` / `--min-confidence`, plus `--window-turns` / `--source` on watch);
-on the op only: `prior_context` (text whose already-surfaced slugs are suppressed),
-`session_id` / `turn` attribution params (watch stamps its own per-session id and
-turn numbers in the feedback log), and `days` to size the `--stats` window.
-
-## Storage + privacy
-
-Volunteered pages log to `context_volunteer_events` (migration v117): slug,
-arm, confidence, channel, optional session/turn — the rationale is a
-deterministic template string, never raw conversation text. Event writes are
-best-effort (fire-and-forget, drained at CLI exit) — the log is a tuning signal,
-not an audit trail. Rows are pruned after 90 days by the dream cycle's purge
-phase. Synopses always strip the takes/facts fences — the same strip `get_page`
-applies to untrusted callers, applied unconditionally here so private fence rows
-never reach a prompt regardless of caller trust.
-
----
-
## docs/guides/github-source.md
Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/github-source.md
@@ -10533,6 +10100,14 @@ Source: https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/tro
| A gbrain call failed with a code you don't recognize | follow `fix.next` ([protocol](../protocol/AGENT_OPERATOR_v1.md)); `gbrain errors <code>` | agent | as the fix's `consent` | the fix's `verify` |
| A graph read omits a relationship you know existed, or says someone still works somewhere they left | the default read returns relationships true today: repeat with `status: "all"` or `as_of`; to record an end, add a dated timeline line (`Ended works_at [[companies/x]]`) or `add_link ... valid_until` ([temporal edges](temporal-edges.md)) | agent | none | `gbrain doctor --only edge_validity --json` |
| A command exited 3 (`confirmation_required`) | relay `user_message`; run `fix.command` only after the user agrees | agent, after the user agrees | the payload's `effects` | the fix's `verify` |
+| A scheduled job, workspace script or hook finds nothing in the brain (every lookup empty), or its log shows `no_brain` or `GBRAIN_DB_ACCESS no_url`, while the same command works by hand | the job runs without the brain's config: call gbrain through one wrapper that sets `GBRAIN_HOME` and loads the brain's env file, and stop discarding its stderr ([the wrapper](cron-schedule.md#calling-gbrain-unattended)) | agent | none | the job's log shows results, and `gbrain engine status --json` run through the wrapper names the expected `db_url_source` |
+| `gbrain sources refresh` refuses `refresh_not_owner` from cron or a script but works by hand | the caller resolves another gbrain home, so it is another host; the refusal names the identity file, `HOME` and `GBRAIN_HOME` it read. Set the owner's `GBRAIN_HOME` in the wrapper (not `HOME`, which also swaps git credentials); never copy or delete a `host.json` | agent | none | `gbrain sources refresh <id> --dry-run` through the wrapper |
+| `gbrain sources refresh` refuses `refresh_diverged` on every run | something commits into the managed checkout outside gbrain, usually a script that writes files and runs `git commit` without pushing. `git log @{upstream}..HEAD` names the commits; move that writer to `put_page` or `capture`, then reconcile as the [refusal](write-refusals.md#refresh_diverged) says; never force ([scripts and the managed checkout](shared-checkout-git.md#scripts-and-the-managed-checkout)) | agent; reconciling after the user agrees | `destructive` when reconciling drops local commits | `gbrain sources refresh <id> --dry-run` |
+| A `--json` caller fails to parse gbrain's output | something other than gbrain wrote to stdout, usually a wrapper or a hook it runs; send that output to a log file or stderr (gbrain's own notices already go to stderr) | agent | none | the same call piped to `jq .` parses |
+| gbrain calls time out from a script or language runtime but finish by hand, or each search takes several seconds | a cold CLI start takes 3–6 s on a pooled Postgres brain: set caller timeouts of at least 10 s in both the shell and the runtime (a runtime exec timeout can override the shell's), and turn on the [warm CLI socket](cli-socket.md). If warm searches stay slow, measure the round trip to the database; one in another region dominates search time | agent; moving the database after the user agrees | none | `GBRAIN_DEBUG=1 gbrain search <query>` prints a `[cli-socket] warm:` line |
+| After a database change some processes still use the old server, or a URL variable silently keeps its old value | a shell-sourced env file has an unquoted `&` (the assignment ends there), or a process kept the environment it started with. Quote every value, keep Postgres URLs to `?sslmode=require` (driver options as variables, such as `GBRAIN_PREPARE=false`), update every URL variable the tooling reads, restart every gbrain process, and prove the switch from the database side ([switching a database](../../INSTALL_FOR_AGENTS.md#switching-a-database)). Never paste `env` output into a transcript while debugging | agent, after the user agrees | none | a row written after the restart appears on the new server |
+| Doctor `parked_effects` lists `git_target_ignored` effects | a `.gitignore` rule excludes those pages' files, so their Git effects cannot commit. The user decides: un-ignore (narrow the rule, commit it, then `gbrain sources writer retry-effects <source> --parked-code git_target_ignored`) or keep the pages database-only and leave the effects parked ([gitignored paths](shared-checkout-git.md#scripts-and-the-managed-checkout)) | agent, after the user decides | none | `gbrain sources writer status --source <id> --json` |
+| Sync and the maintenance cycle re-read a whole source on every run after its Git history was rewritten (force-push, `git filter-repo`) | the recorded base commit no longer exists. Move the checkout onto the new history ([upstream rewritten](#upstream-rewritten)); before the next rewrite, take the source out of automatic sync and run `gbrain sources mirror-readonly <id>` first | agent; the reset after the user agrees | `destructive` (the reset keeps a backup ref) | `gbrain doctor --only sync_failures --json` |
| [Database unreachable or `GBRAIN_DB_ACCESS <reason>`](#database-unreachable) | `gbrain engine status --probe`, then `gbrain db-repair` (diagnose); `gbrain db-repair --yes` applies safe fixes | agent; `--yes` after the user agrees | none to diagnose; `--apply-rewrites` rewrites the config URL (undoable) | `gbrain engine status --probe --json` |
| [PGLite `RuntimeError: Aborted()` at startup](#pglite-aborted) | automatic repair on the next command; else `gbrain pglite-repair --dry-run`, then `gbrain pglite-repair --yes` | agent; `--yes` after the user agrees | `destructive` (a WAL backup is kept and the restore command printed) | `gbrain doctor --only connection --json` |
| [`expected N dimensions, not M` on import](#embedding-dimensions) | `gbrain doctor` prints the exact `gbrain config set …` or `gbrain migrate embeddings --to <provider:model>` command | agent, after the user agrees | `migrate embeddings`: `paid`, needs the brain's writer lock | `gbrain doctor --only embeddings,embedding_width_consistency --json` |
diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
index 75d50db52e..dbde1ed803 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
@@ -24,7 +24,7 @@ gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page wit
gbrain query "why did the launch move" # questions and concepts
gbrain search "launch" --types '["meeting","person"]' # only these page types
gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)
-gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'
+gbrain search "launch" --source source-a --limit 5 --json | jq -r '.[].slug'
gbrain get companies/acme-example # read the page a hit points to
gbrain recall "Alice Example" # facts saved with remember
gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)
@@ -40,7 +40,29 @@ gbrain list --type meeting --limit 50 # enumerate by t
- Without `--source`, a search reads the resolved source (a notice names it
when it routes); `--source __all__` searches every source.
- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.
- Read a degraded notice before concluding the brain has nothing.
+ Read a degraded notice before concluding the brain has nothing. Never send
+ stderr to `/dev/null`: a refusal there (`no_brain`, `GBRAIN_DB_ACCESS`)
+ then reads as "no results". Check the exit code too.
+
+<a id="identity-exact-match"></a>
+## Identity needs an exact match
+
+Resolving an email sender, a calendar attendee or a contact to a person page is
+an identity decision, and a search's top hit is not one: ranking always returns
+something, so taking it files strangers onto known contacts. Accept a page only
+on one of these:
+
+1. **An exact email match.** `gbrain list --type person --where email=<address> --source-id __all__ --json`
+ returns the person pages whose `email` frontmatter equals the address or
+ lists it. The match is case-sensitive, so pass the address as written and
+ lowercased (`--where [email protected],[email protected]`),
+ and use the field your person pages use (`email`, or `emails` for a list).
+2. **An exact title match.** `gbrain search "<display name>" --types '["person"]' --json`,
+ then accept only a hit whose `title` equals the name exactly.
+
+Exactly one page is the person. No page, or more than one, means unknown: treat
+the sender as new or ask the user. Never take the top hit, a partial name or a
+similar address, and never merge a stranger into a known contact's page.
## Available GBrain Tools
diff --git a/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md b/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md
index 1c4a36d739..5ad89d16d2 100644
--- a/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/data-loss-gate/SKILL.md
@@ -77,6 +77,16 @@ Brain / database level (gbrain-specific):
sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via
`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:
a sweep that's wrong in bulk is expensive to un-wrong in bulk.
+- **`gbrain delete --purge`** — skips the 72-hour soft delete and removes the
+ page at once with its chunks, versions, takes, timeline, links, raw data and
+ the facts filed on it. `gbrain restore` cannot undo it. Every purge needs the
+ user's explicit go for that purge: a request to "scrub the repo", "clean up
+ the files" or "remove it from Git" is not a go to purge database pages. After
+ the go, purge one page at a time (never a parallel `xargs` or a background
+ loop), confirm each one is gone (`gbrain get <slug> --include-deleted` reports
+ `page_not_found`) before the next, and stop the batch at the first refusal. A purge batch that was
+ stopped (SIGTERM, a write freeze, a timeout) stays stopped: report what
+ finished and ask again before relaunching it.
- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages
from every source of the brain. This is the point of no return for the
soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`
@@ -185,7 +195,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.
- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.
-- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.
+- A delete or forget returns `write_pending` (exit 10): it was accepted and is still pending, so it may still commit. It is not "not found" or "failed": poll the receipt (`gbrain write-request <request_id>`) before writing the deletion log entry, and never re-run the deletion or move to a wider one because of it.
## Anti-Patterns
@@ -196,6 +206,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- ❌ "I'll clean up and tell the user after" — the confirmation must come BEFORE the deletion
- ❌ "It's only a soft delete" — a wrong sweep is still expensive to un-wrong in bulk, and purge makes it permanent
- ❌ "The command already has --confirm-destructive" — the flag confirms the agent's intent, not the user's consent
+- ❌ "They asked me to scrub it from the repo, so I purged the pages" — a repository cleanup is not consent to delete database rows
+- ❌ Running purges in parallel, or reading a non-zero exit as "nothing happened" — exit 10 means the delete was accepted
- ❌ Presenting deletion as the only option without listing alternatives
## Dedup (sharp boundaries)
diff --git a/plugin-variants/gbrain-daily/skills/briefing/SKILL.md b/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
index 9d29096465..a6cac1cac3 100644
--- a/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
@@ -137,14 +137,19 @@ Before generating any briefing, load context from gbrain systematically.
### Before a meeting
For every attendee on the calendar invite:
-- `gbrain search "<attendee name>"` -- find their brain page
+- Find their brain page by an exact match only: their email in the page's
+ `email` frontmatter, or a person page whose title equals their name
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)). A
+ search's top hit is not the attendee.
- `gbrain get <slug>` -- load compiled truth, recent timeline, relationship context
- If no page exists, note the gap ("No brain page for alice-example -- consider enrichment")
### Before an email reply
Before drafting or triaging any email:
-- `gbrain search "<sender name>"` -- load sender context
+- Resolve the sender by exact email or exact title match
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)); no
+ exact match means an unknown sender, not the nearest known contact
- Read their compiled truth to understand who they are, what they care about, and
your relationship history. This turns a cold reply into an informed one.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
index 75d50db52e..dbde1ed803 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
@@ -24,7 +24,7 @@ gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page wit
gbrain query "why did the launch move" # questions and concepts
gbrain search "launch" --types '["meeting","person"]' # only these page types
gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)
-gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'
+gbrain search "launch" --source source-a --limit 5 --json | jq -r '.[].slug'
gbrain get companies/acme-example # read the page a hit points to
gbrain recall "Alice Example" # facts saved with remember
gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)
@@ -40,7 +40,29 @@ gbrain list --type meeting --limit 50 # enumerate by t
- Without `--source`, a search reads the resolved source (a notice names it
when it routes); `--source __all__` searches every source.
- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.
- Read a degraded notice before concluding the brain has nothing.
+ Read a degraded notice before concluding the brain has nothing. Never send
+ stderr to `/dev/null`: a refusal there (`no_brain`, `GBRAIN_DB_ACCESS`)
+ then reads as "no results". Check the exit code too.
+
+<a id="identity-exact-match"></a>
+## Identity needs an exact match
+
+Resolving an email sender, a calendar attendee or a contact to a person page is
+an identity decision, and a search's top hit is not one: ranking always returns
+something, so taking it files strangers onto known contacts. Accept a page only
+on one of these:
+
+1. **An exact email match.** `gbrain list --type person --where email=<address> --source-id __all__ --json`
+ returns the person pages whose `email` frontmatter equals the address or
+ lists it. The match is case-sensitive, so pass the address as written and
+ lowercased (`--where [email protected],[email protected]`),
+ and use the field your person pages use (`email`, or `emails` for a list).
+2. **An exact title match.** `gbrain search "<display name>" --types '["person"]' --json`,
+ then accept only a hit whose `title` equals the name exactly.
+
+Exactly one page is the person. No page, or more than one, means unknown: treat
+the sender as new or ask the user. Never take the top hit, a partial name or a
+similar address, and never merge a stranger into a known contact's page.
## Available GBrain Tools
diff --git a/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md b/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
index 594523bd86..e62a6df218 100644
--- a/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
@@ -350,7 +350,10 @@ five pages costs five corrections.
### Phase 7: Attendee enrichment (MANDATORY)
For EACH attendee:
-1. `gbrain search "{name}"` — does a people page exist?
+1. Does a people page exist? Only an exact match counts: the attendee's email
+ in a page's `email` frontmatter, or a person page whose title equals the
+ name ([identity rule](../conventions/brain-first.md#identity-exact-match)).
+ A search's top hit is a candidate to check, never the attendee.
2. If NO → create via the enrich skill (`skills/enrich/SKILL.md`). Every
person who was actually IN the meeting gets a page, even a thin one. Skip
only ephemeral third-party mentions (a name invoked about someone not
diff --git a/plugin/skills/briefing/SKILL.md b/plugin/skills/briefing/SKILL.md
index 9d29096465..a6cac1cac3 100644
--- a/plugin/skills/briefing/SKILL.md
+++ b/plugin/skills/briefing/SKILL.md
@@ -137,14 +137,19 @@ Before generating any briefing, load context from gbrain systematically.
### Before a meeting
For every attendee on the calendar invite:
-- `gbrain search "<attendee name>"` -- find their brain page
+- Find their brain page by an exact match only: their email in the page's
+ `email` frontmatter, or a person page whose title equals their name
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)). A
+ search's top hit is not the attendee.
- `gbrain get <slug>` -- load compiled truth, recent timeline, relationship context
- If no page exists, note the gap ("No brain page for alice-example -- consider enrichment")
### Before an email reply
Before drafting or triaging any email:
-- `gbrain search "<sender name>"` -- load sender context
+- Resolve the sender by exact email or exact title match
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)); no
+ exact match means an unknown sender, not the nearest known contact
- Read their compiled truth to understand who they are, what they care about, and
your relationship history. This turns a cold reply into an informed one.
diff --git a/plugin/skills/cold-start/SKILL.md b/plugin/skills/cold-start/SKILL.md
index 051de77f7d..6443b915ec 100644
--- a/plugin/skills/cold-start/SKILL.md
+++ b/plugin/skills/cold-start/SKILL.md
@@ -317,7 +317,9 @@ brain/daily/calendar/
### Entity enrichment
For each event with attendees:
-1. Look up each attendee in the brain (they should exist from Phase 2)
+1. Look up each attendee in the brain (they should exist from Phase 2), by
+ exact email or exact title match only
+ ([identity rule](../conventions/brain-first.md#identity-exact-match))
2. Add a timeline entry to their page: met at [event title] on [date]
3. If an attendee has no brain page and appears in 3+ events, create one
4. Link attendees who appear in the same meeting
diff --git a/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.md
index 75d50db52e..dbde1ed803 100644
--- a/plugin/skills/conventions/brain-first.md
+++ b/plugin/skills/conventions/brain-first.md
@@ -24,7 +24,7 @@ gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page wit
gbrain query "why did the launch move" # questions and concepts
gbrain search "launch" --types '["meeting","person"]' # only these page types
gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)
-gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'
+gbrain search "launch" --source source-a --limit 5 --json | jq -r '.[].slug'
gbrain get companies/acme-example # read the page a hit points to
gbrain recall "Alice Example" # facts saved with remember
gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)
@@ -40,7 +40,29 @@ gbrain list --type meeting --limit 50 # enumerate by t
- Without `--source`, a search reads the resolved source (a notice names it
when it routes); `--source __all__` searches every source.
- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.
- Read a degraded notice before concluding the brain has nothing.
+ Read a degraded notice before concluding the brain has nothing. Never send
+ stderr to `/dev/null`: a refusal there (`no_brain`, `GBRAIN_DB_ACCESS`)
+ then reads as "no results". Check the exit code too.
+
+<a id="identity-exact-match"></a>
+## Identity needs an exact match
+
+Resolving an email sender, a calendar attendee or a contact to a person page is
+an identity decision, and a search's top hit is not one: ranking always returns
+something, so taking it files strangers onto known contacts. Accept a page only
+on one of these:
+
+1. **An exact email match.** `gbrain list --type person --where email=<address> --source-id __all__ --json`
+ returns the person pages whose `email` frontmatter equals the address or
+ lists it. The match is case-sensitive, so pass the address as written and
+ lowercased (`--where [email protected],[email protected]`),
+ and use the field your person pages use (`email`, or `emails` for a list).
+2. **An exact title match.** `gbrain search "<display name>" --types '["person"]' --json`,
+ then accept only a hit whose `title` equals the name exactly.
+
+Exactly one page is the person. No page, or more than one, means unknown: treat
+the sender as new or ask the user. Never take the top hit, a partial name or a
+similar address, and never merge a stranger into a known contact's page.
## Available GBrain Tools
diff --git a/plugin/skills/cron-scheduler/SKILL.md b/plugin/skills/cron-scheduler/SKILL.md
index 6411917432..ffc1632833 100644
--- a/plugin/skills/cron-scheduler/SKILL.md
+++ b/plugin/skills/cron-scheduler/SKILL.md
@@ -29,6 +29,9 @@ This skill guarantees:
- Thin job prompts: jobs say "Read skills/X/SKILL.md and run it" (no inline 3000-word prompts)
- Idempotency: jobs can run twice without duplicate side effects
- Results saved as reports: `reports/{job-name}/{YYYY-MM-DD-HHMM}.md`
+- One entry point: every job, workspace script and hook calls gbrain through
+ one wrapper that sets `GBRAIN_HOME` and keeps stderr and the exit code
+ ([the wrapper](https://github.com/garrytan/gbrain/blob/master/docs/guides/cron-schedule.md#calling-gbrain-unattended))
## Phases
@@ -42,6 +45,15 @@ This skill guarantees:
- Morning contact releases the backlog
4. **Register with host scheduler.** OpenClaw cron, Railway cron, crontab, or process manager. **Each registered entry should execute via Minions, not `agentTurn`.** See `skills/conventions/cron-via-minions.md` for the rewrite pattern (PGLite uses `--follow`, Postgres uses fire-and-forget + `--idempotency-key` on the cycle slot). GBrain's v0.11.0 migration auto-rewrites entries for built-in handlers; host-specific handlers need a code-level registration per `docs/guides/plugin-handlers.md`.
5. **Write thin prompt.** Job prompt is one line: "Read skills/{name}/SKILL.md and run it."
+6. **Call gbrain through the wrapper.** Cron runs with another `HOME` and
+ environment than your shell, so a bare `gbrain` (or `bun run src/cli.ts`)
+ can find no database (every lookup silently empty) or act as a second host
+ (`refresh_not_owner`). Register `gbrain-run <args>`, the wrapper in
+ [cron-schedule.md](https://github.com/garrytan/gbrain/blob/master/docs/guides/cron-schedule.md#calling-gbrain-unattended):
+ it sets `GBRAIN_HOME` (never `HOME`), loads the brain's env file and runs
+ the installed binary. Log stderr to a file, check the exit code, keep hook
+ output off stdout, and give each call a timeout of at least 10 s.
+ The lines below write `gbrain-run`; doctor prints the bare command.
## Idempotency Requirement
@@ -63,7 +75,7 @@ cron line instead of N per-source entries.
**Preferred (multi-source)**:
```cron
-*/5 * * * * gbrain sync --all --parallel 4 --workers 4 --skip-failed
+*/5 * * * * gbrain-run sync --all --parallel 4 --workers 4 --skip-failed >> /tmp/gbrain-cron.log 2>&1
```
This replaces N per-source lines AND auto-picks-up future sources without
@@ -93,7 +105,7 @@ On a managed brain, install this line instead, on the host that owns the
sources:
```cron
-*/15 * * * * gbrain sources refresh <id>; gbrain sync --all --no-pull --hard-deadline 13m
+*/15 * * * * gbrain-run sources refresh <id> >> /tmp/gbrain-cron.log 2>&1; gbrain-run sync --all --no-pull --hard-deadline 13m >> /tmp/gbrain-cron.log 2>&1
```
- `gbrain sources refresh <id>` is the only way a managed checkout takes
@@ -101,6 +113,11 @@ sources:
the sources on that checkout). Add one refresh per checkout that tracks a
remote, with its real source id; drop it for checkouts with no remote. The
`;` is deliberate: the sync still runs when a refresh refuses.
+- `refresh_diverged`: the checkout has commits its upstream lacks, so
+ something commits outside gbrain (usually a script that writes files and
+ runs `git commit` in the checkout). Fix that writer so it saves pages
+ through `put_page` or `capture`; never force the checkout
+ ([scripts and the managed checkout](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
- `--hard-deadline 13m` stays under the 15-minute interval. Managed sync takes
no per-source lock, so a run that outlives the interval would overlap the
next tick. A run stopped at its deadline ends `resumable` and the next tick
@@ -129,6 +146,11 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `writer_coordinator_required` from a scheduled sync: the brain is managed. Replace the line with the [managed brain](#managed-brain) recipe; never retry with `--skip-failed` or without `--no-pull`.
- `sync_in_progress` from `gbrain sources refresh`: a managed sync cursor is unfinished, and the refresh never waits on it. Run the `gbrain sync --source <id> --no-pull …` command the refusal prints; the next tick's refresh then runs.
- `worktree_refreshing` from a sync: a refresh is draining or merging that checkout. Leave it; the next tick syncs it.
+- A job's lookups all come back empty, or its log shows `no_brain` or `GBRAIN_DB_ACCESS no_url`: the job runs without the brain's config. Call gbrain through the wrapper; an empty result from a job whose stderr went to `/dev/null` is not evidence of "no notes".
+- `refresh_not_owner` from cron while the same refresh works by hand: the job resolves another gbrain home, so it is another host. The refusal names the identity file, `HOME` and `GBRAIN_HOME` it read; set the owner's `GBRAIN_HOME` in the wrapper. Never copy or delete a `host.json`.
+- A `--json` caller fails to parse gbrain's output: something the wrapper runs prints to stdout. Send that hook's output to a log file.
+- Calls time out in the job but finish by hand: a cold start takes seconds. Raise the timeout to at least 10 s in both the shell and the runtime that spawns it, and use the [warm CLI socket](https://github.com/garrytan/gbrain/blob/master/docs/guides/cli-socket.md).
+- Exit 10 from a scheduled write: it was accepted and is still pending, not lost or "not found". Poll `gbrain write-request <request_id>` before retrying or reporting it.
## Anti-Patterns
@@ -137,6 +159,12 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Running cron jobs without testing on 3-5 items first
- Jobs that produce different output on re-run (not idempotent)
- Sending notifications during quiet hours (save to held queue instead)
+- A bare `gbrain` or `bun run src/cli.ts` in a cron line, script or hook
+ instead of the wrapper; a wrapper that sets `HOME` instead of `GBRAIN_HOME`
+- `2>/dev/null` on a gbrain call, or ignoring its exit code
+- A script that writes files and `git commit`s them in a managed checkout
+- Printing `env` or a process environment into a log or transcript while
+ debugging (it holds the database URL and keys)
- Separate per-source `gbrain sync --source <id>` cron entries when
`gbrain sync --all --parallel N --workers N` would replace them with
one line that auto-picks-up future sources.
diff --git a/plugin/skills/data-loss-gate/SKILL.md b/plugin/skills/data-loss-gate/SKILL.md
index 1c4a36d739..5ad89d16d2 100644
--- a/plugin/skills/data-loss-gate/SKILL.md
+++ b/plugin/skills/data-loss-gate/SKILL.md
@@ -77,6 +77,16 @@ Brain / database level (gbrain-specific):
sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via
`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:
a sweep that's wrong in bulk is expensive to un-wrong in bulk.
+- **`gbrain delete --purge`** — skips the 72-hour soft delete and removes the
+ page at once with its chunks, versions, takes, timeline, links, raw data and
+ the facts filed on it. `gbrain restore` cannot undo it. Every purge needs the
+ user's explicit go for that purge: a request to "scrub the repo", "clean up
+ the files" or "remove it from Git" is not a go to purge database pages. After
+ the go, purge one page at a time (never a parallel `xargs` or a background
+ loop), confirm each one is gone (`gbrain get <slug> --include-deleted` reports
+ `page_not_found`) before the next, and stop the batch at the first refusal. A purge batch that was
+ stopped (SIGTERM, a write freeze, a timeout) stays stopped: report what
+ finished and ask again before relaunching it.
- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages
from every source of the brain. This is the point of no return for the
soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`
@@ -185,7 +195,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.
- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.
-- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.
+- A delete or forget returns `write_pending` (exit 10): it was accepted and is still pending, so it may still commit. It is not "not found" or "failed": poll the receipt (`gbrain write-request <request_id>`) before writing the deletion log entry, and never re-run the deletion or move to a wider one because of it.
## Anti-Patterns
@@ -196,6 +206,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- ❌ "I'll clean up and tell the user after" — the confirmation must come BEFORE the deletion
- ❌ "It's only a soft delete" — a wrong sweep is still expensive to un-wrong in bulk, and purge makes it permanent
- ❌ "The command already has --confirm-destructive" — the flag confirms the agent's intent, not the user's consent
+- ❌ "They asked me to scrub it from the repo, so I purged the pages" — a repository cleanup is not consent to delete database rows
+- ❌ Running purges in parallel, or reading a non-zero exit as "nothing happened" — exit 10 means the delete was accepted
- ❌ Presenting deletion as the only option without listing alternatives
## Dedup (sharp boundaries)
diff --git a/plugin/skills/gbrain-upgrade/SKILL.md b/plugin/skills/gbrain-upgrade/SKILL.md
index 98e86763fc..c369531864 100644
--- a/plugin/skills/gbrain-upgrade/SKILL.md
+++ b/plugin/skills/gbrain-upgrade/SKILL.md
@@ -119,6 +119,30 @@ rather than blocking — the version numbers alone are enough to decide.
stops nagging for this version until it expires or a newer version ships.
- **Never** → `gbrain config set self_upgrade.mode off`
+## Always-on hosts: pause, drain, upgrade, verify, resume
+
+A host that runs autopilot, a jobs worker or a serve keeps the old build
+running after the binary swaps, and a job that starts mid-swap can run half on
+each. With the operator's go-ahead, upgrade in this order:
+
+1. `gbrain autopilot pause --reason "upgrade"` so no new cycle starts.
+2. Wait for a quiet queue: `gbrain jobs list --status active --json` returns
+ no jobs (`gbrain jobs stats --json` for the totals). Let running jobs
+ finish; don't cancel them to hurry.
+3. `gbrain upgrade` on every install that touches the brain. `which -a gbrain`
+ lists the installs on PATH; a harness, cron wrapper or service may run
+ another one by absolute path.
+4. Restart every resident gbrain process (serve, jobs supervisor, autopilot,
+ MCP servers), then verify that each install and each process reports the
+ new version: `gbrain --version` per install, and
+ `gbrain doctor --only runtime_build_skew,serve_build_drift --json` ok.
+ On a managed brain, `gbrain sources writer movement` must exit 0
+ ([restart and verify](https://github.com/garrytan/gbrain/blob/master/docs/guides/upgrades-auto-update.md#restart-and-verify)).
+5. `gbrain autopilot resume`.
+
+Report the version every process runs, not just the version the upgrade
+printed.
+
## When it fails
Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:
diff --git a/plugin/skills/meeting-ingestion/SKILL.md b/plugin/skills/meeting-ingestion/SKILL.md
index 594523bd86..e62a6df218 100644
--- a/plugin/skills/meeting-ingestion/SKILL.md
+++ b/plugin/skills/meeting-ingestion/SKILL.md
@@ -350,7 +350,10 @@ five pages costs five corrections.
### Phase 7: Attendee enrichment (MANDATORY)
For EACH attendee:
-1. `gbrain search "{name}"` — does a people page exist?
+1. Does a people page exist? Only an exact match counts: the attendee's email
+ in a page's `email` frontmatter, or a person page whose title equals the
+ name ([identity rule](../conventions/brain-first.md#identity-exact-match)).
+ A search's top hit is a candidate to check, never the attendee.
2. If NO → create via the enrich skill (`skills/enrich/SKILL.md`). Every
person who was actually IN the meeting gets a page, even a thin one. Skip
only ephemeral third-party mentions (a name invoked about someone not
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index a25f07898d..e0118e417e 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -221,6 +221,8 @@ export const SECTIONS: DocSection[] = [
description:
"Three-tier architecture for agents with 300+ skills: always-loaded, resolver-routed, and dormant. Per-turn token math, the compact list-format resolver, and the `gbrain doctor` safety net. 306 skills, ~21K tokens freed per turn, zero capability loss.",
path: "docs/guides/scaling-skills.md",
+ // Linked, not inlined: the operator-lessons wave (cron wrapper, managed checkout, identity) put llms-full.txt over FULL_SIZE_BUDGET.
+ includeInFull: false,
},
{
title: "docs/guides/life-chronicle.md",
@@ -248,6 +250,8 @@ export const SECTIONS: DocSection[] = [
description:
"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.",
path: "docs/guides/push-context.md",
+ // Linked, not inlined: same budget trim as scaling-skills.md.
+ includeInFull: false,
},
{
title: "docs/guides/time-aware-recall.md",
diff --git a/skills/briefing/SKILL.md b/skills/briefing/SKILL.md
index 71983bcbd5..a18e66b148 100644
--- a/skills/briefing/SKILL.md
+++ b/skills/briefing/SKILL.md
@@ -136,14 +136,19 @@ Before generating any briefing, load context from gbrain systematically.
### Before a meeting
For every attendee on the calendar invite:
-- `gbrain search "<attendee name>"` -- find their brain page
+- Find their brain page by an exact match only: their email in the page's
+ `email` frontmatter, or a person page whose title equals their name
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)). A
+ search's top hit is not the attendee.
- `gbrain get <slug>` -- load compiled truth, recent timeline, relationship context
- If no page exists, note the gap ("No brain page for alice-example -- consider enrichment")
### Before an email reply
Before drafting or triaging any email:
-- `gbrain search "<sender name>"` -- load sender context
+- Resolve the sender by exact email or exact title match
+ ([identity rule](../conventions/brain-first.md#identity-exact-match)); no
+ exact match means an unknown sender, not the nearest known contact
- Read their compiled truth to understand who they are, what they care about, and
your relationship history. This turns a cold reply into an informed one.
diff --git a/skills/cold-start/SKILL.md b/skills/cold-start/SKILL.md
index e764c40a01..cd97b656b0 100644
--- a/skills/cold-start/SKILL.md
+++ b/skills/cold-start/SKILL.md
@@ -316,7 +316,9 @@ brain/daily/calendar/
### Entity enrichment
For each event with attendees:
-1. Look up each attendee in the brain (they should exist from Phase 2)
+1. Look up each attendee in the brain (they should exist from Phase 2), by
+ exact email or exact title match only
+ ([identity rule](../conventions/brain-first.md#identity-exact-match))
2. Add a timeline entry to their page: met at [event title] on [date]
3. If an attendee has no brain page and appears in 3+ events, create one
4. Link attendees who appear in the same meeting
diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.md
index 75d50db52e..dbde1ed803 100644
--- a/skills/conventions/brain-first.md
+++ b/skills/conventions/brain-first.md
@@ -24,7 +24,7 @@ gbrain search '"ZEBRA-42" OR "inventory sync"' --match keyword # every page wit
gbrain query "why did the launch move" # questions and concepts
gbrain search "launch" --types '["meeting","person"]' # only these page types
gbrain query "launch" --since 2026-09-01 --until 2026-09-30 # date window (also --since 30d)
-gbrain search "launch" --source source-a --limit 5 --json 2>/dev/null | jq -r '.[].slug'
+gbrain search "launch" --source source-a --limit 5 --json | jq -r '.[].slug'
gbrain get companies/acme-example # read the page a hit points to
gbrain recall "Alice Example" # facts saved with remember
gbrain backlinks companies/acme-example --type meeting # pages that link here (instead of grepping a slug)
@@ -40,7 +40,29 @@ gbrain list --type meeting --limit 50 # enumerate by t
- Without `--source`, a search reads the resolved source (a notice names it
when it routes); `--source __all__` searches every source.
- Notices and `[AGENT]` blocks go to stderr, so `--json` stdout is clean JSON.
- Read a degraded notice before concluding the brain has nothing.
+ Read a degraded notice before concluding the brain has nothing. Never send
+ stderr to `/dev/null`: a refusal there (`no_brain`, `GBRAIN_DB_ACCESS`)
+ then reads as "no results". Check the exit code too.
+
+<a id="identity-exact-match"></a>
+## Identity needs an exact match
+
+Resolving an email sender, a calendar attendee or a contact to a person page is
+an identity decision, and a search's top hit is not one: ranking always returns
+something, so taking it files strangers onto known contacts. Accept a page only
+on one of these:
+
+1. **An exact email match.** `gbrain list --type person --where email=<address> --source-id __all__ --json`
+ returns the person pages whose `email` frontmatter equals the address or
+ lists it. The match is case-sensitive, so pass the address as written and
+ lowercased (`--where [email protected],[email protected]`),
+ and use the field your person pages use (`email`, or `emails` for a list).
+2. **An exact title match.** `gbrain search "<display name>" --types '["person"]' --json`,
+ then accept only a hit whose `title` equals the name exactly.
+
+Exactly one page is the person. No page, or more than one, means unknown: treat
+the sender as new or ask the user. Never take the top hit, a partial name or a
+similar address, and never merge a stranger into a known contact's page.
## Available GBrain Tools
diff --git a/skills/cron-scheduler/SKILL.md b/skills/cron-scheduler/SKILL.md
index 36a50c3a54..dd2239abc5 100644
--- a/skills/cron-scheduler/SKILL.md
+++ b/skills/cron-scheduler/SKILL.md
@@ -28,6 +28,9 @@ This skill guarantees:
- Thin job prompts: jobs say "Read skills/X/SKILL.md and run it" (no inline 3000-word prompts)
- Idempotency: jobs can run twice without duplicate side effects
- Results saved as reports: `reports/{job-name}/{YYYY-MM-DD-HHMM}.md`
+- One entry point: every job, workspace script and hook calls gbrain through
+ one wrapper that sets `GBRAIN_HOME` and keeps stderr and the exit code
+ ([the wrapper](https://github.com/garrytan/gbrain/blob/master/docs/guides/cron-schedule.md#calling-gbrain-unattended))
## Phases
@@ -41,6 +44,15 @@ This skill guarantees:
- Morning contact releases the backlog
4. **Register with host scheduler.** OpenClaw cron, Railway cron, crontab, or process manager. **Each registered entry should execute via Minions, not `agentTurn`.** See `skills/conventions/cron-via-minions.md` for the rewrite pattern (PGLite uses `--follow`, Postgres uses fire-and-forget + `--idempotency-key` on the cycle slot). GBrain's v0.11.0 migration auto-rewrites entries for built-in handlers; host-specific handlers need a code-level registration per `docs/guides/plugin-handlers.md`.
5. **Write thin prompt.** Job prompt is one line: "Read skills/{name}/SKILL.md and run it."
+6. **Call gbrain through the wrapper.** Cron runs with another `HOME` and
+ environment than your shell, so a bare `gbrain` (or `bun run src/cli.ts`)
+ can find no database (every lookup silently empty) or act as a second host
+ (`refresh_not_owner`). Register `gbrain-run <args>`, the wrapper in
+ [cron-schedule.md](https://github.com/garrytan/gbrain/blob/master/docs/guides/cron-schedule.md#calling-gbrain-unattended):
+ it sets `GBRAIN_HOME` (never `HOME`), loads the brain's env file and runs
+ the installed binary. Log stderr to a file, check the exit code, keep hook
+ output off stdout, and give each call a timeout of at least 10 s.
+ The lines below write `gbrain-run`; doctor prints the bare command.
## Idempotency Requirement
@@ -62,7 +74,7 @@ cron line instead of N per-source entries.
**Preferred (multi-source)**:
```cron
-*/5 * * * * gbrain sync --all --parallel 4 --workers 4 --skip-failed
+*/5 * * * * gbrain-run sync --all --parallel 4 --workers 4 --skip-failed >> /tmp/gbrain-cron.log 2>&1
```
This replaces N per-source lines AND auto-picks-up future sources without
@@ -92,7 +104,7 @@ On a managed brain, install this line instead, on the host that owns the
sources:
```cron
-*/15 * * * * gbrain sources refresh <id>; gbrain sync --all --no-pull --hard-deadline 13m
+*/15 * * * * gbrain-run sources refresh <id> >> /tmp/gbrain-cron.log 2>&1; gbrain-run sync --all --no-pull --hard-deadline 13m >> /tmp/gbrain-cron.log 2>&1
```
- `gbrain sources refresh <id>` is the only way a managed checkout takes
@@ -100,6 +112,11 @@ sources:
the sources on that checkout). Add one refresh per checkout that tracks a
remote, with its real source id; drop it for checkouts with no remote. The
`;` is deliberate: the sync still runs when a refresh refuses.
+- `refresh_diverged`: the checkout has commits its upstream lacks, so
+ something commits outside gbrain (usually a script that writes files and
+ runs `git commit` in the checkout). Fix that writer so it saves pages
+ through `put_page` or `capture`; never force the checkout
+ ([scripts and the managed checkout](https://github.com/garrytan/gbrain/blob/master/docs/guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
- `--hard-deadline 13m` stays under the 15-minute interval. Managed sync takes
no per-source lock, so a run that outlives the interval would overlap the
next tick. A run stopped at its deadline ends `resumable` and the next tick
@@ -128,6 +145,11 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `writer_coordinator_required` from a scheduled sync: the brain is managed. Replace the line with the [managed brain](#managed-brain) recipe; never retry with `--skip-failed` or without `--no-pull`.
- `sync_in_progress` from `gbrain sources refresh`: a managed sync cursor is unfinished, and the refresh never waits on it. Run the `gbrain sync --source <id> --no-pull …` command the refusal prints; the next tick's refresh then runs.
- `worktree_refreshing` from a sync: a refresh is draining or merging that checkout. Leave it; the next tick syncs it.
+- A job's lookups all come back empty, or its log shows `no_brain` or `GBRAIN_DB_ACCESS no_url`: the job runs without the brain's config. Call gbrain through the wrapper; an empty result from a job whose stderr went to `/dev/null` is not evidence of "no notes".
+- `refresh_not_owner` from cron while the same refresh works by hand: the job resolves another gbrain home, so it is another host. The refusal names the identity file, `HOME` and `GBRAIN_HOME` it read; set the owner's `GBRAIN_HOME` in the wrapper. Never copy or delete a `host.json`.
+- A `--json` caller fails to parse gbrain's output: something the wrapper runs prints to stdout. Send that hook's output to a log file.
+- Calls time out in the job but finish by hand: a cold start takes seconds. Raise the timeout to at least 10 s in both the shell and the runtime that spawns it, and use the [warm CLI socket](https://github.com/garrytan/gbrain/blob/master/docs/guides/cli-socket.md).
+- Exit 10 from a scheduled write: it was accepted and is still pending, not lost or "not found". Poll `gbrain write-request <request_id>` before retrying or reporting it.
## Anti-Patterns
@@ -136,6 +158,12 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Running cron jobs without testing on 3-5 items first
- Jobs that produce different output on re-run (not idempotent)
- Sending notifications during quiet hours (save to held queue instead)
+- A bare `gbrain` or `bun run src/cli.ts` in a cron line, script or hook
+ instead of the wrapper; a wrapper that sets `HOME` instead of `GBRAIN_HOME`
+- `2>/dev/null` on a gbrain call, or ignoring its exit code
+- A script that writes files and `git commit`s them in a managed checkout
+- Printing `env` or a process environment into a log or transcript while
+ debugging (it holds the database URL and keys)
- Separate per-source `gbrain sync --source <id>` cron entries when
`gbrain sync --all --parallel N --workers N` would replace them with
one line that auto-picks-up future sources.
diff --git a/skills/data-loss-gate/SKILL.md b/skills/data-loss-gate/SKILL.md
index 81f1451aa4..59805d6047 100644
--- a/skills/data-loss-gate/SKILL.md
+++ b/skills/data-loss-gate/SKILL.md
@@ -76,6 +76,16 @@ Brain / database level (gbrain-specific):
sweeps `delete_page` across a set of slugs. Deletes are soft (recoverable via
`gbrain restore <slug>`) until purged — say so on the card, then gate anyway:
a sweep that's wrong in bulk is expensive to un-wrong in bulk.
+- **`gbrain delete --purge`** — skips the 72-hour soft delete and removes the
+ page at once with its chunks, versions, takes, timeline, links, raw data and
+ the facts filed on it. `gbrain restore` cannot undo it. Every purge needs the
+ user's explicit go for that purge: a request to "scrub the repo", "clean up
+ the files" or "remove it from Git" is not a go to purge database pages. After
+ the go, purge one page at a time (never a parallel `xargs` or a background
+ loop), confirm each one is gone (`gbrain get <slug> --include-deleted` reports
+ `page_not_found`) before the next, and stop the batch at the first refusal. A purge batch that was
+ stopped (SIGTERM, a write freeze, a timeout) stays stopped: report what
+ finished and ask again before relaunching it.
- **`gbrain pages purge-deleted`** — permanently removes soft-deleted pages
from every source of the brain. This is the point of no return for the
soft-delete safety net. Show the user `gbrain pages purge-deleted --dry-run --json`
@@ -184,7 +194,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- A destructive command exits 3 (`confirmation_required`) or asks for `--confirm-destructive`: that flag confirms the agent is sure, not the user. Show the recoverability card and wait for the user's explicit yes.
- `gbrain pages purge-deleted` removes soft-deleted pages for good, so `gbrain restore` cannot bring them back afterwards: say so on the card. Never promise physical erasure or a recovery you cannot verify.
-- A delete or forget returns `write_pending` (exit 10): poll the receipt before writing the deletion log entry.
+- A delete or forget returns `write_pending` (exit 10): it was accepted and is still pending, so it may still commit. It is not "not found" or "failed": poll the receipt (`gbrain write-request <request_id>`) before writing the deletion log entry, and never re-run the deletion or move to a wider one because of it.
## Anti-Patterns
@@ -195,6 +205,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- ❌ "I'll clean up and tell the user after" — the confirmation must come BEFORE the deletion
- ❌ "It's only a soft delete" — a wrong sweep is still expensive to un-wrong in bulk, and purge makes it permanent
- ❌ "The command already has --confirm-destructive" — the flag confirms the agent's intent, not the user's consent
+- ❌ "They asked me to scrub it from the repo, so I purged the pages" — a repository cleanup is not consent to delete database rows
+- ❌ Running purges in parallel, or reading a non-zero exit as "nothing happened" — exit 10 means the delete was accepted
- ❌ Presenting deletion as the only option without listing alternatives
## Dedup (sharp boundaries)
diff --git a/skills/gbrain-upgrade/SKILL.md b/skills/gbrain-upgrade/SKILL.md
index 813e8ffcd7..b7c16ef7d2 100644
--- a/skills/gbrain-upgrade/SKILL.md
+++ b/skills/gbrain-upgrade/SKILL.md
@@ -118,6 +118,30 @@ rather than blocking — the version numbers alone are enough to decide.
stops nagging for this version until it expires or a newer version ships.
- **Never** → `gbrain config set self_upgrade.mode off`
+## Always-on hosts: pause, drain, upgrade, verify, resume
+
+A host that runs autopilot, a jobs worker or a serve keeps the old build
+running after the binary swaps, and a job that starts mid-swap can run half on
+each. With the operator's go-ahead, upgrade in this order:
+
+1. `gbrain autopilot pause --reason "upgrade"` so no new cycle starts.
+2. Wait for a quiet queue: `gbrain jobs list --status active --json` returns
+ no jobs (`gbrain jobs stats --json` for the totals). Let running jobs
+ finish; don't cancel them to hurry.
+3. `gbrain upgrade` on every install that touches the brain. `which -a gbrain`
+ lists the installs on PATH; a harness, cron wrapper or service may run
+ another one by absolute path.
+4. Restart every resident gbrain process (serve, jobs supervisor, autopilot,
+ MCP servers), then verify that each install and each process reports the
+ new version: `gbrain --version` per install, and
+ `gbrain doctor --only runtime_build_skew,serve_build_drift --json` ok.
+ On a managed brain, `gbrain sources writer movement` must exit 0
+ ([restart and verify](https://github.com/garrytan/gbrain/blob/master/docs/guides/upgrades-auto-update.md#restart-and-verify)).
+5. `gbrain autopilot resume`.
+
+Report the version every process runs, not just the version the upgrade
+printed.
+
## When it fails
Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:
diff --git a/skills/meeting-ingestion/SKILL.md b/skills/meeting-ingestion/SKILL.md
index 7119c13dd4..90d9fd18a2 100644
--- a/skills/meeting-ingestion/SKILL.md
+++ b/skills/meeting-ingestion/SKILL.md
@@ -349,7 +349,10 @@ five pages costs five corrections.
### Phase 7: Attendee enrichment (MANDATORY)
For EACH attendee:
-1. `gbrain search "{name}"` — does a people page exist?
+1. Does a people page exist? Only an exact match counts: the attendee's email
+ in a page's `email` frontmatter, or a person page whose title equals the
+ name ([identity rule](../conventions/brain-first.md#identity-exact-match)).
+ A search's top hit is a candidate to check, never the attendee.
2. If NO → create via the enrich skill (`skills/enrich/SKILL.md`). Every
person who was actually IN the meeting gets a page, even a thin one. Skip
only ephemeral third-party mentions (a name invoked about someone not
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7b1a2864ba..5a517da68a 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -25,7 +25,7 @@
"brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734",
"brain-taxonomist/SKILL.md": "418fd4cdac3355551c42a70fea4d76e3d9255fe04698358b2c1e89dc666bf11d",
"brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae",
- "briefing/SKILL.md": "9c99cee1e3e6177bfcbaabdc84aab0d9d786db4075b4875ec2e70b80570608bb",
+ "briefing/SKILL.md": "9402c9b9abdd743b1dfcfb9b6c59312e1ecbb92770385025ad89f36fe3330b57",
"briefing/routing-eval.jsonl": "c056fea88f673e324d6a72cb70438cd6fcdbd09ec2cd036d44eb31a9ea6bf33d",
"bulk-ingestion/MANIFEST-PATTERN.md": "deb3abad5d8026822a663810abb1f39d60df8bb797a42587ffa6d44eefa15a0b",
"bulk-ingestion/SKILL.md": "48c10ec94fc23cd6f1ecfa4ec7254cc1cb3f5ea8cc43daf2fbe109c59ce1cda4",
@@ -37,7 +37,7 @@
"citation-fixer/routing-eval.jsonl": "52b23b71e66fdc18aee67d0576099b0c83997d648cf4ecf8fe7753b91b6c9c53",
"citation-graph-ingest/SKILL.md": "3c8c4abea96769458e9781ce2f5f305c75118fcb5f68cc62b5e1ed7774259035",
"citation-graph-ingest/routing-eval.jsonl": "a1ba605d35e736b741b9e8aac1e7d50b61a7cbcada893d67099b55bf5a0d2635",
- "cold-start/SKILL.md": "57d09cff758c48965cb25b2ec2cf317dcf014c22d9610bee83cfe581cf1a9f76",
+ "cold-start/SKILL.md": "b92647ca477e27e923d8cc2d93749845a5e232429f19f6bfde2b0d86f28b6518",
"company-brainify/SKILL.md": "89e8cae702d468628d110119e325cece897cd15066c7cc7d27e990021904fc04",
"company-brainify/routing-eval.jsonl": "6f27f835eda9ae77a2b694534c78a043a871349820e8c638c3d8bbba6d3aa17b",
"concept-synthesis/SKILL.md": "a5c67f981c5d0a0ef4f13134ed8602e08b0bfbe289456213b8cd465a7a009220",
@@ -45,7 +45,7 @@
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/agent-operator-protocol.md": "b42b19223aa9dffbe783ce7c5c681d762377c740f3c609cbc555b9a60a035235",
- "conventions/brain-first.md": "b98dc24e086a35f136f74ca4abd856949d8b282e1298a47a250b2d18f69e0927",
+ "conventions/brain-first.md": "211885909210be4f278f7ff1b592a705b71b8a97499a7d2f1bede210d07179d0",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
@@ -66,12 +66,12 @@
"conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca",
"correction-pipeline/SKILL.md": "04b4aee06d7fcdd75db314da432ed7c08b5fbc20f117f18062c64aaf795bc564",
"correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",
- "cron-scheduler/SKILL.md": "a89bfeb058034d5033c42d56b35297e5f33e28a6dac01860d5e033a10262b3a5",
+ "cron-scheduler/SKILL.md": "65615bf63cca791eb43b42e338246a697a526fd81653f735d2b9f5d5601882c4",
"cross-modal-review/SKILL.md": "fc00a04e2ff9f498bee9b0b636bceba9dcfdc869c35d9a983109f408170f0807",
"daily-task-manager/SKILL.md": "e93264a83b5fd0a19b2f06a322b3a4ad92d418f6a968c1cd51f4bea79cbca4d9",
"daily-task-manager/routing-eval.jsonl": "e98b2592e65c26952242436a960d8b2061e375b269004a18c230cbcf1d692ff9",
"daily-task-prep/SKILL.md": "5ea839012b48761ed8d7a9bab056a2566587d6f7fe044e3907d77b20f8eec5ac",
- "data-loss-gate/SKILL.md": "6cddc796a128ddeea8c622de79dde1ec1e6c214203bce51ea5e751719e291d46",
+ "data-loss-gate/SKILL.md": "c1736e0985121e60ffeba993b68b5c722c9285220057b5ef72059f111aabcb18",
"data-loss-gate/routing-eval.jsonl": "825358a5600641061a02b25097cd84c1c28bb0359a7608a10b9f25f661bd88f9",
"data-research/SKILL.md": "39f9648a21a7074d6ad7db789e93e6d7085449a6cdaffacf8b1660eb68636b9d",
"db-repair/SKILL.md": "87a34fe18812f3b6ec37381ae69c205e30747300098ebe3fe41f8460d0ba8346",
@@ -88,7 +88,7 @@
"functional-area-resolver/SKILL.md": "fe6e35fbb34dffec7af9ce4a6cc9c0b0eaa8345f97f33262a2abe0983431b421",
"functional-area-resolver/routing-eval.jsonl": "f80674d915acdfe229046737a5b171da834be15ac6524b5a3fd18048e9b37028",
"gbrain-advisor/SKILL.md": "976b3c5c3798f9fec764fa5bacd1567f751875bd837fe188a0c6df041805ed51",
- "gbrain-upgrade/SKILL.md": "3acd674fd78af095b3a40fb4b437475552c166b6dd57014d7db6ce6ea94ce9c0",
+ "gbrain-upgrade/SKILL.md": "b4a637605234fd748b0501a244ffad491a9d8f16e537fbfdbf2d9de41f0aaaab",
"google-loops/SKILL.md": "20955fac0a94bbe9298a8aa7416e851cac86eb145bc551ed0fc556d2f583fa5e",
"idea-ingest/SKILL.md": "863be3660ead12a45d3b86309d73df0ffda6c5db6ca69873cce1810680df79b4",
"idea-lineage/SKILL.md": "8cb36179dbf94abc17065613b8e773b1bb2b22670742aa77347b91ac885a05c5",
@@ -100,7 +100,7 @@
"measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
"media-ingest/SKILL.md": "d70374d3df21397380203f541ebdcc90c0bc6bc7207234349594a081e98f2719",
- "meeting-ingestion/SKILL.md": "ee30ec5813080d6bb3b5d487389ba2887dd119e7dde28feda65db149568ffb7d",
+ "meeting-ingestion/SKILL.md": "8eebe641404da245da446cc651de44d479beaf879c52db7ce3d2432baca93ed6",
"meeting-ingestion/routing-eval.jsonl": "1995dc75eff09fd2e5fb403a10c81dc71b4c12035d48c77e57da0134c81f731a",
"migrate/SKILL.md": "ab7d7874bdd6cf1ef34538c2888b93b0a416f49bf04bd608dc5eccf9af9a5936",
"migrations/.gitkeep": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",