Files
gbrain/docs/UPGRADING_DOWNSTREAM_AGENTS.md
Garry Tan 668b9bac30 v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins

Closes the critical- and high-severity items from six privately reported
advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv,
GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a
single commit so no intermediate revision carries a test-fixture credential
shape through the gitleaks range gate.

Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0
owner-approval flow is pinned end to end against a real `serve --http
--enable-dcr` process and in-process: anonymous /authorize mints no code, a
forged code is rejected at /token, revoked clients are refused at grants.begin,
and OAuthGrants.begin() now caps awaiting-decision requests per client_id.

Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2).
registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via
scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only.
Remote sources_remove is source-fenced like sources_status. doctor's
oauth_client_scope_health flags privileged self-registered clients.

Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains
jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus
bearer and db_url_credentials catch-alls; the transcripts lane opts into the
digit-gated high-entropy rule; getRawData follows the page soft-delete on both
engines; delete_page --purge (local-CLI only) hard-removes a leaked page.

Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts
drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_*
variables when a working-directory .env assigns them (key-presence, since Bun
expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs.

Release artifacts: VERSION/package.json/three plugin manifests bumped to
0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md,
CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin
trees, skills.lock, flag registry and llms bundle regenerated; module-size
ceilings adjusted with per-row reasons; TODOS follow-ups filed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: pre-landing review fixes (v0.50.2.0 security wave)

Review cycle 1 of the ship: 6 specialists + red team + coverage audit.

Security / red team:
- env-trust: parse .env with Bun's line grammar (bare CR terminates a line;
  BOM/U+2028 cannot hide an assignment); protect the loader / git / node /
  proxy / AI-CLI variable families a checkout could plant for the programs
  gbrain spawns; cli-preflight re-execs gbrain once with the sanitized
  environment so git, the agent CLI and workers inherit the clean view;
  cwd == ~/.gbrain no longer quarantines the operator's own .env.
- guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths
  (a package name resolves from the cwd's node_modules).
- secret-scan: bounded db_url_credentials quantifiers + per-pattern
  prechecks (linear on long lines), windowed previews that redact every
  sibling span, single-pass longest-first replacement.
- TODOS: follow-up entries reworded to the functional level.

API contract / maintainability:
- delete_page purge: remote callers get permission_denied; a purged
  response always carries write_through; get_raw_data description states
  the soft-delete follow; includeDeleted narrowed to the getRawData
  signature; client_credentials gate evaluated before the DCR ceiling;
  doctor privileged set derived from the scope registry; sources_remove /
  sources_status share assertSourceInCallerScope; shell-job opt-in reaches
  --job-isolation process children as --allow-shell-jobs; stale help copy.
- transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key
  order made every healthy re-run rewrite unchanged rows).

Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified
pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms
bundle, flag registry, tool catalog, structural suites regenerated;
module-size rows adjusted with reasons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave)

Re-exec redesign (security + red team + adversarial findings):
- cli-preflight re-runs gbrain from an empty temporary directory so the
  sanitized child never reloads the hostile .env: dropped keys are absent,
  never carried as '' (git and the dynamic loader presence-check
  GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident).
- The re-run marker is JSON {cwd, neutral} honoured only when the process
  provably started in that empty directory — a marker planted via a cwd
  .env is ignored (the ppid-keyed marker was forgeable under systemd/docker).
- SIGINT is delivered by the tty once (wrapper no longer forwards it);
  SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime.
- Protected families widened: XDG config roots (git reads
  $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust
  stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the
  GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker.
- cwd dotenv parsed once per start; jobs start uses the same '1' literal.

secret-scan (cycle-2 findings):
- db_url_credentials password class only stops at whitespace, '@' and
  string delimiters again (unescaped / { } < > | ^ ` \ passwords redact);
  BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body
  bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts
  were quadratic); incremental PEM line cursor; redactFindings rebuilds
  the text by span-splice in one pass (was O(unique values x text)).

Contract / docs:
- delete_page purge responses carry a residuals hint (git history, exports,
  compiled context, slug-keyed derived rows); CHANGELOG states a single
  truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under
  Changed with a migration note); SECURITY.md / KEY_FILES / docs guides /
  minion-orchestrator skill describe the new mechanism and the
  --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source
  marker on the hook spawn-shape test; new PEM fixtures fragmented.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave)

- Compiled binaries: every `bun build --compile` invocation passes
  `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh`
  guard (self-tested, in verify CHECKS) keeps it that way.
- cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`,
  OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE
  join the protected set; the neutral hop dir is realpath'd; signal
  handlers are installed before the spawn; non-tty wrappers forward SIGINT
  once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had
  a value.
- secret-scan: PEM header-line cursor is O(text) on newline-free tails;
  bounded bearer echo pass redacts bare re-occurrences of claimed tokens.
- transcripts ingest: raw-metadata probe reads active rows only.
- Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT,
  perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms +
  skills.lock + plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave)

Cross-model adversarial pass (Codex) + Claude verifier findings:
- env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS,
  PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH,
  BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded.
- cli-preflight: config-dir exemption refused when the cwd .env assigns
  GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal
  listeners so its exit is always the child's; SIGINT forwarded only
  without a controlling terminal (/dev/tty probe); a dropped planted HOME
  is restored from the passwd home; script-mode runs warn once when the
  cwd bunfig.toml declares a top-level preload.
- secret-scan: overlapping matches redact the UNION of matched spans;
  echo pass covers bearer + high-entropy values (64 unique, <=512 chars)
  via per-value sweeps over unclaimed gaps only; planRedaction/
  applyRedaction share a session-wide echo dictionary in transcripts
  render.
- sources_remove keys on write authority (assertSourceInCallerWriteScope);
  federated read grants confer no removal right.
- delete_page --purge retries the tombstone's file removal and fails
  closed (storage_error) while the file remains.
- Docs: SECURITY.md quarantine example no longer uses the one key that
  refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS
follow-up refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave)

- cli-preflight: hop marker carries the wrapper pid; a verified re-run arms
  an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the
  wrapper is force-killed, so supervisor restarts never orphan a worker;
  relative path-bearing runtime flags (--preload/-r/--require/--import,
  --config/-c, --env-file, --tsconfig-override) are resolved against the
  original cwd before the hop.
- secret-scan: echo pass is a streaming leftmost-longest merge with O(values)
  retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went
  from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now
  covered wall-to-wall.
- Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* docs: update project documentation for v0.50.3.0

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(ci): green the three failing checks on the v0.50.3.0 wave

- semgrep: six `nosemgrep` suppressions with justifications for the
  path-join/resolve and non-literal-RegExp taint heuristics on operator-
  controlled cwd/flag paths and compile-time pattern sources (no behaviour
  change).
- test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s
  intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the
  pty's SIGINT on itself after the child exits (130) instead of relaying
  the child's 42. The pty command now `exec`s the wrapper so no shell stays
  in the foreground group; documented in a `ptyCommand` helper.
- Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly
  the self-registration ceiling (`read write`) via
  `scopesSupportedForDiscovery`, so a connector that copies
  `scopes_supported` into /register succeeds (master's #5122 pin); without
  DCR the full operator list minus `agent` is unchanged. Sibling e2e
  assertions that expected privileged scopes on the DCR-enabled server
  updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES
  updated; llms regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131)

Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up
refs + bun.lock, template repo and plugin trees regenerated.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-15 21:40:59 -07:00

27 KiB

Upgrading Downstream Agents

Scope: this file covers skill-fork diffs through v0.36.5.0. The canonical upgrade channel is skills/migrations/v*.md (the agent-executed migration files that gbrain upgrade / gbrain post-upgrade route through), plus CHANGELOG.md for release history. Use this file to catch a long-diverged fork up through the versions it covers; for anything after v0.36.5.0, walk the migration files and CHANGELOG. Time-critical: the ZeroEntropy hosted-API shutdown (2026-09-04) — every fork still embedding or reranking through zeroentropyai:* must run skills/migrations/v0.46.3.0.md before that date.

GBrain ships skills in skills/. Downstream agents (custom OpenClaw deployments, agent forks of any kind) often copy these skill files into their own workspace and diverge over time — adding agent-specific phases, removing irrelevant ones, tightening language. Once that happens, gbrain can't push updates to those forks. The agent has to apply the diffs by hand.

This doc lists the exact diffs each downstream agent needs to apply when upgrading. Cross-reference against your fork's local skill files.

Why this exists

gbrain upgrade ships the new binary. gbrain post-upgrade [--execute --yes] runs the schema migrations and backfills the data. But the skill files themselves that tell the agent how to behave — those are user-owned. If your ~/git/<your-agent>/workspace/skills/brain-ops/SKILL.md says # Based on gbrain v0.10.0 at the top, it doesn't know about v0.12.0 features.

The agent will keep manually calling gbrain link after every put_page (redundant — auto-link does it), miss out on gbrain graph-query for relationship questions, and not know to backfill the structured timeline.

How to apply

  1. Identify your forked skill files. Typically at ~/git/<your-agent>/workspace/skills/ or wherever your agent's skill directory lives.
  2. For each skill listed below, find the matching phase/section in your fork.
  3. Apply the diff (paste the new block in the indicated location).
  4. Update the version banner at the top of your fork (# Based on gbrain v0.12.0).
  5. Verify: ask the agent to write a test page and confirm the response includes auto_links: { created, removed, errors }. (Local CLI writes only — MCP writes, stdio included, return auto_links: { skipped: "remote" } and are reconciled later by the serve maintenance sweep or gbrain sweep --once.)

Total time: ~10 minutes for all four skills.


1. brain-ops/SKILL.md

Where: Insert a new ### Phase 2.5 section immediately after ### Phase 2: On Every Inbound Signal.

Why: Phase 2.5 declares that auto-link runs automatically. Without this, the agent's mental model says it must call gbrain link after every put_page, which is redundant and can cause double-add warnings.

### Phase 2.5: Structured Graph Updates (auto-link)

"Auto-link" reconciliation extracts entity references from a page and writes
them to the graph (`links` table) with inferred relationship types; stale
links (refs no longer in the page text) are removed. WHO runs it depends on
the write path:

- **Trusted local writes** (`gbrain put`, `gbrain capture`,
  `gbrain call put_page`) auto-link inline and return
  `auto_links: { created, removed, errors }`.
- **MCP callers (stdio AND HTTP)** return `auto_links: { skipped: "remote", hint }`
  and `auto_timeline: { skipped: "remote" }`. Body wikilinks are saved as text;
  edges are reconciled asynchronously by the serve's maintenance sweep
  (at startup and on 10-minute idle ticks), or on demand with
  `gbrain sweep --once` / `gbrain extract links --source db`. Use `add_link`
  for relationships you need immediately. Untrusted body text can plant
  ranking-boosting edges, which is why the inline path is local-only.
- Inferred link types: `attended` (meeting -> person), `works_at`, `invested_in`,
  `founded`, `advises`, `source` (frontmatter), `mentions` (default).
- To disable: `gbrain config set auto_link false`. Default is on.
- Timeline entries with specific dates still need explicit `gbrain timeline-add`
  (or batch via `gbrain extract timeline --source db`).

Also update the Iron Law section. If your fork still says "Back-links maintained on every brain write (Iron Law)" without qualification, append:

**v0.12.0 update:** Auto-link satisfies the Iron Law for entity-reference links
on every `put_page` (inline for trusted local writes; for MCP writes, once the
serve maintenance sweep runs). The agent's Iron Law obligation is now: include the
entity reference in the page content (e.g., `[Alice](people/alice)`); auto-link
handles the structured row. Manual `add_link` calls are reserved for
relationships you can't express in markdown content.

2. meeting-ingestion/SKILL.md

Where: Append to the end of ### Phase 3: Attendee enrichment.

Why: Eliminates redundant gbrain link calls per attendee (auto-link handles them when the meeting page references attendees as [Name](people/slug)).

**Note (v0.12.0):** Once the meeting page is written via `gbrain put`, the
auto-link post-hook automatically creates `attended` links from the meeting
to each attendee whose page is referenced as `[Name](people/slug)`. You don't
need to call `gbrain link` for attendees. You DO still need `gbrain timeline-add`
for dated events (auto-link only handles links, not timeline entries).

Where: In ### Phase 4: Entity propagation, the line "Back-link from entity page to meeting page" can be replaced with:

4. Entity references in the meeting page body auto-create the link via auto-link.
   For incoming references on the entity page (entity page → meeting page), edit
   the entity page to mention the meeting and `put_page` it — auto-link handles
   the rest.

3. signal-detector/SKILL.md

Where: Append to the end of ### Phase 2: Entity Detection.

Why: Same logic as brain-ops — eliminates manual gbrain link after writing originals/ideas pages that reference people or companies.

**Auto-link (v0.12.0):** When you write/update an originals or ideas page that
references a person or company, the auto-link post-hook on `put_page`
automatically creates the link from the new page to that entity. You don't
need to call `gbrain link` manually. Timeline entries still need explicit calls.

4. enrich/SKILL.md

Where: Replace ### Step 7: Cross-reference with the block below.

Why: With auto-link, link creation between related entity pages is automatic. Step 7 is about content updates, not link creation.

Old (delete):

### Step 7: Cross-reference

- Update company pages from person enrichment (and vice versa)
- Update related project/deal pages if relevant context surfaced
- Check index files if the brain uses them
- Add back-links manually via `gbrain link` for any new entity references

New (paste):

### Step 7: Cross-reference

- Update company pages from person enrichment (and vice versa)
- Update related project/deal pages if relevant context surfaced
- Check index files if the brain uses them

**Note (v0.12.0):** Links between brain pages are auto-created on every
`put_page` call (auto-link post-hook). Step 7 focuses on content
cross-references (updating related pages' compiled truth with new signal
from this enrichment), not on creating links. On a trusted local write the
put_page response carries `auto_links: { created, removed, errors }`; MCP
writes (stdio and HTTP) return `auto_links: { skipped: "remote", hint }`
instead — edges are reconciled by the serve maintenance sweep or
`gbrain sweep --once`, and `add_link` covers an edge you need immediately.
Timeline entries still need explicit `gbrain timeline-add` calls.

After all four diffs are applied

  1. Bump the version banner at the top of each forked file:

    # Based on gbrain v0.12.0 skills/<skill-name>, extended with <your-agent>-specific config
    
  2. Run the v0.12.0 backfill (this populates the graph for your existing brain):

    gbrain post-upgrade
    

    post-upgrade calls apply-migrations --yes automatically, which runs the v0_12_0 orchestrator (schema → config check → extract links --source db → extract timeline --source db → verify). Idempotent; cheap when nothing is pending.

  3. Verify auto-link works: ask the agent to write a test page that references [Some Person](people/some-person). Confirm the put_page response includes auto_links: { created: 1, removed: 0, errors: 0 }. (Local CLI write; an MCP write returns auto_links: { skipped: "remote" } — run gbrain sweep --once, then check the edge with gbrain graph-query.)

  4. Verify graph traversal works:

    gbrain graph-query people/some-well-connected-person --depth 2
    

    Should return an indented tree of typed edges.


v0.12.2 hotfix (data-correctness, no skill edits)

v0.12.2 is a Postgres data-correctness hotfix. No forked skill files need to change; the skill contracts are the same. You DO need to run the migration, and there is one markdown-parsing behavior to know about.

1. Run the migration (Postgres-backed brains)

gbrain upgrade

The v0_12_2 orchestrator runs gbrain repair-jsonb automatically. It rewrites rows where jsonb_typeof = 'string' across pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, and page_versions.frontmatter. Idempotent, safe to re-run. PGLite brains no-op cleanly.

Verify after upgrade:

gbrain repair-jsonb --dry-run --json    # expect totalRepaired: 0

2. Recover any truncated wiki articles

If your brain imported wiki-style markdown before v0.12.2, some pages were silently truncated (any standalone --- in body content was treated as a timeline separator). Re-import from source:

gbrain sync --full

splitBody rebuilds compiled_truth correctly.

3. The splitBody contract

splitBody requires an explicit timeline sentinel. Recognized markers (priority order):

  1. <!-- timeline --> (preferred — what serializeMarkdown emits)
  2. --- timeline --- (decorated separator)
  3. --- directly before ## Timeline or ## History heading (backward-compat)

A bare --- in body text is a markdown horizontal rule, not a timeline separator. If your agent writes pages with a bare --- delimiter, migrate to <!-- timeline --> — the serializeMarkdown helper emits it.

4. Wiki subtypes auto-typed

inferType detects five directory patterns as their own page types rather than concept:

Path pattern Type
/wiki/analysis/ analysis
/wiki/guides/ guide
/wiki/hardware/ hardware
/wiki/architecture/ architecture
/writing/ writing

If your skills or queries filter by type=concept and expect wiki content in that bucket, update them to include these types.


v0.13.0 — Frontmatter Relationship Indexing

Verdict: no action required for most skills. v0.13 projects YAML frontmatter fields into the graph as typed edges. The ingestion API is unchanged — keep calling put_page with frontmatter the way you do today; the graph auto-populates behind the scenes.

Three skills get an optional new phase if you want to consume the new auto_links.unresolved response field. Without this, unresolvable frontmatter names silently skip.

1. meeting-ingestion/SKILL.md (optional)

Where: Add a new section after "Phase 3: Write Meeting Page".

### Phase 3.5: Check for unresolved attendees (v0.13+)

After `put_page`, inspect `response.auto_links.unresolved` — an array of frontmatter
references that did not resolve to existing pages. For meetings, this usually means
attendees you haven't created a person page for yet.

If `unresolved.length > 0`:
- Option 1 (create pages now): trigger an enrichment pass to build the missing people pages.
- Option 2 (defer): log the unresolved names to the enrichment queue for later.
- Option 3 (accept the gap): the attendee edge will not be created until a page exists.
  Re-running `gbrain extract links --source db --include-frontmatter` after creating
  the page fills in the missing edges.

2. enrich/SKILL.md (optional)

Where: Add to the enrichment trigger list.

### Drain unresolved frontmatter names (v0.13+)

If any `put_page` response includes `auto_links.unresolved` entries, the enrichment
tier should pick up those (field, name) pairs and try to create the missing entity
pages. Example flow:

1. signal-detector captures a meeting with `attendees: [Alice Known, Unknown Person]`
2. put_page returns `auto_links.unresolved = [{field: 'attendees', name: 'Unknown Person'}]`
3. enrichment tier consumes `Unknown Person` → web search → creates `people/unknown-person.md`
4. The next put_page (or a backfill run) wires up the `attended` edge automatically

3. idea-ingest/SKILL.md (optional)

Where: Same pattern as meeting-ingestion — check auto_links.unresolved after put_page, route names to enrichment.

Unchanged skills (no diffs needed)

  • brain-ops/SKILL.md — auto-link mechanics are internal; the write path stays the same.
  • signal-detector/SKILL.md — signal capture path unchanged.
  • query/SKILL.md — traverse_graph returns the frontmatter-derived edges automatically.
  • daily-task-manager/SKILL.md, briefing/SKILL.md, citation-fixer/SKILL.md, media-ingest/SKILL.md — unchanged.

Edge types you can filter in graph queries

Frontmatter-derived edges carry these link_type values. If your fork has graph-query skills that filter by type, these are available:

  • works_at (person → company) — from company:, companies:, or key_people:
  • founded (person → company) — from founded:
  • invested_in (investor → deal/company) — from investors: or lead:
  • led_round (lead → deal) — from lead:
  • yc_partner (partner → company) — from partner:
  • attended (person → meeting) — from attendees:
  • discussed_in (source → page) — from sources:
  • source (page → source) — from source:
  • related_to (page → target) — from related: or see_also:

Migration timing

gbrain upgrade takes 2-5 min on a 46K-page brain (one-time). Runs out-of-process via gbrain post-upgrade. If your agent holds a DB connection during the upgrade, reconnect after; otherwise keep serving.

Type names

The extractor emits 'attended' and 'mentions'. If your fork's graph queries filter on the older spellings 'attendee' or 'mention', widen them to match both so rows written under either name are returned.


v0.14.0 shell jobs (optional adoption, no skill edits)

Adds a shell job type to Minions so deterministic cron scripts (API fetch, token refresh, scrape + write) move off the LLM gateway. Zero tokens per fire. ~60% gateway CPU headroom at typical scale. Feature is off by default; installs that do not opt in are unaffected.

To adopt, follow skills/migrations/v0.14.0.md. The short version:

  1. Start the worker with gbrain jobs work --allow-shell-jobs (equivalently, export GBRAIN_ALLOW_SHELL_JOBS=1 on the worker process; a .env in the worker's directory cannot set it) (Postgres). On PGLite, every crontab invocation uses --follow for inline execution; no persistent worker.
  2. Classify each of your host's cron entries: LLM-requiring (keep on gateway) vs deterministic (candidate for shell). Typical splits:
    • Deterministic → shell: ycli-token-refresh, x-oauth2-refresh, x-garrytan-unified, calendar-sync-to-brain, github-pulse, frameio-scan, flight-tracker, x-raw-json-backfill.
    • LLM-requiring → stay: social-radar, content-ideas, adversary-vacuum, ea-inbox-sweep, morning-briefing, brain-maintenance.
  3. For each deterministic cron, rewrite as:
    3 13,16,19,22,1,4,7,10 * * * \
      gbrain jobs submit shell \
        --params '{"cmd":"node scripts/your-script.mjs","cwd":"/data/.openclaw/workspace"}' \
        --max-attempts 3 --timeout-ms 300000
    
  4. Watch gbrain jobs get <id> for exit_code / stdout_tail / stderr_tail on each fire. Compare against pre-migration behavior before approving the next batch.

No skill edits required. The handler runs worker-side; skill files don't change. If your host exposes custom handlers via the plugin contract, they work unchanged.

Iron rule: never auto-rewrite the operator's crontab. Every rewrite is per-cron, human-approved, with a diff. gbrain ships no crontab-rewriting helper; every rewrite is manual.


v0.16.0: durable agent runtime

gbrain ships gbrain agent run / gbrain agent logs, a subagent handler type in Minions, and a plugin contract for host-repo subagent defs. None of the existing skills need surgery. The question for downstream agents is how to adopt the runtime, not how to patch around a breaking change.

1. Run a worker with an Anthropic key

The subagent handlers (subagent and subagent_aggregator) are always registered on the worker. No separate opt-in flag — ANTHROPIC_API_KEY is the natural cost gate (no key, the SDK call fails on the first turn), and who-can-submit is already protected (PROTECTED_JOB_NAMES + trusted-submit: MCP callers get permission_denied; only gbrain agent run can insert these rows).

ANTHROPIC_API_KEY=sk-ant-... gbrain jobs work

Worker startup prints:

[minion worker] subagent handlers enabled

2. Ship your subagents as a plugin (OpenClaw + similar)

Move your custom subagent definitions out of your gbrain fork and into your own repo as a plugin. Concretely:

~/<your-agent>/gbrain-plugin/
├── gbrain.plugin.json
└── subagents/
    ├── meeting-ingestion.md
    ├── signal-detector.md
    └── daily-task-prep.md

gbrain.plugin.json:

{
  "name": "your-openclaw",
  "version": "2026.4.20",
  "plugin_version": "gbrain-plugin-v1"
}

Each subagents/*.md is a plain-text agent definition — YAML frontmatter + body-as-system-prompt. Recognized frontmatter fields: name, model, max_turns, allowed_tools (must subset the derived brain-tool registry).

Turn it on:

export GBRAIN_PLUGIN_PATH="$HOME/<your-agent>/gbrain-plugin"

Worker startup prints [plugin-loader] loaded '<name>' v<ver> (N subagents) per plugin; any rejection (bad manifest, unknown tool in allowed_tools, version mismatch) shows up as a loud warning at startup, not a silent dispatch- time failure. See docs/guides/plugin-authors.md for the full contract.

3. Replace ephemeral subagent runs with durable ones

If your agent currently spawns ephemeral subagents (OpenClaw Agent(), ad-hoc Anthropic API calls, etc.) for work that should survive crashes, sleeps, or worker restarts, migrate those to gbrain agent run. The durability is free:

gbrain agent run "analyze my last 50 journal pages for recurring themes" \
  --subagent-def analyzer --fanout-manifest manifests/journal-pages.json

Every turn persists to subagent_messages, every tool call is a two-phase ledger, and gbrain agent logs <job> shows where it died + what the last successful call returned. No more "re-run from scratch because the session context evaporated."

4. put_page from subagents writes under an agent namespace

If you adopt the subagent runtime, note that put_page calls originating from a subagent's tool dispatch MUST target wiki/agents/<subagent_id>/.... The schema shown to the model enforces this on first try; a server-side fail-closed check rejects anything else. This does NOT affect your skill files, CLI put_page calls, or MCP put_page — only tool-dispatched writes from inside an LLM loop.

Aggregation output (the final "here's what all N children found" brain page) goes via a separate trusted CLI path, not through a subagent tool call, so it can write anywhere you want.

Iron rule: never grant an agent write access beyond its namespace. The server-side check exists because dispatcher bugs happen; treat it as defense in depth, not the primary boundary.


v0.22.4 — frontmatter-guard adoption

1. Stop hand-rolling frontmatter validators

If your fork has scripts that call js-yaml directly to validate brain page frontmatter, replace them with gbrain frontmatter validate calls. The CLI covers the seven canonical error classes and ships a --json envelope that's stable across releases.

- # Custom validator script
- node scripts/validate-frontmatter.mjs <path>
+ gbrain frontmatter validate <path> --json

For consumers that need the validator inside another script, import from gbrain's markdown export instead of duplicating logic:

import { parseMarkdown } from 'gbrain/markdown';

const parsed = parseMarkdown(content, filePath, { validate: true, expectedSlug });
for (const err of parsed.errors ?? []) {
  // err.code: MISSING_OPEN | MISSING_CLOSE | YAML_PARSE | SLUG_MISMATCH |
  //           NULL_BYTES | NESTED_QUOTES | EMPTY_FRONTMATTER
}

2. Drop any references to lib/brain-writer.mjs

If your fork's skills or scripts referenced an aspirational lib/brain-writer.mjs (gbrain does not ship it), replace those references with the gbrain CLI. The frontmatter-guard skill lives at skills/frontmatter-guard/SKILL.md and points at gbrain frontmatter validate / audit / install-hook.

3. Wire the doctor subcheck into your health pipeline

gbrain doctor reports frontmatter_integrity automatically. If your fork has a custom health pipeline (e.g. a daily Slack post about brain health), pull from gbrain doctor --json and surface the frontmatter_integrity row counts.

4. (Optional) Install the pre-commit hook on brain repos

For sources backed by git, gbrain frontmatter install-hook drops a pre-commit script that blocks commits with malformed frontmatter:

gbrain frontmatter install-hook

Skip this if your brain isn't a git repo or if your downstream agent already enforces validation at write time. See docs/integrations/pre-commit.md for the full recipe.

5. Migration ergonomics — read pending-host-work.jsonl

After gbrain apply-migrations --yes runs the v0.22.4 audit, your agent should read ~/.gbrain/migrations/pending-host-work.jsonl (filter to migration === "0.22.4") and walk each entry's command field. Each entry points to a per-source gbrain frontmatter validate <source_path> --fix command — surface counts to the user, get explicit consent, then run.

The migration is audit-only. It never mutates brain content during apply-migrations. Your agent runs the fix command with user consent.


Later versions

For versions after v0.36.5.0, the diffs live in skills/migrations/v*.md (one file per release that needs agent-side action) and CHANGELOG.md. The sections here stay so you can catch up multiple versions at once.

To check what your fork is missing:

diff <(grep -A3 "Based on gbrain" ~/<your-fork>/skills/brain-ops/SKILL.md) \
     <(grep "v[0-9]" ~/gbrain/skills/migrations/ | tail -3)

v0.36.5.0 — Free-form secret inheritance for shell jobs calling gbrain CLI

What it is. Shell-job params accept an inherit: field. Pass any snake_case config-key name on it; the worker resolves the value from its loadConfig() at child-spawn time and injects it into the child env. Names land in the row; values never persist from inherit:. Validation runs pre-enqueue in both submit paths (CLI + submit_job op), so a malformed payload never lands in minion_jobs.data.

Why. Without it, an agent that calls gbrain from shell jobs has to either write database_url to ~/.gbrain/config.json plaintext or pass env: { GBRAIN_DATABASE_URL: "..." } per-job. Both leave plaintext secrets somewhere — disk or DB row. inherit: keeps names in the row and resolves values at spawn time.

What your agent can do. inherit: is free-form. Pass any config-key:

{
  "cmd": "gbrain sync --skip-failed && gbrain embed --stale",
  "cwd": "/data/gbrain",
  "inherit": ["database_url", "anthropic_api_key", "voyage_api_key"]
}

The env-key name in the child is derived by uppercasing the config-key: database_url → GBRAIN_DATABASE_URL, anthropic_api_key → ANTHROPIC_API_KEY, voyage_api_key → VOYAGE_API_KEY, etc. The validator does NOT police which config keys you inherit — the agent is in the same uid as the worker, so it's the agent's call.

You can still use env:. inherit: does not forbid env:{ ANYTHING }. If you have a reason to put a value in the row plaintext (a non-secret correlation token, or a secret you know is OK to persist), pass it via env:. Prefer inherit: when you want the value out of the row.

Worker setup (one-time, per host):

  • gbrain config set database_url postgresql://... — file-plane routed (writes ~/.gbrain/config.json, which is where inherit's loadConfig() resolution looks; works even when the DB is unreachable). The vendor API keys (anthropic_api_key, voyage_api_key, ...) route to the file plane the same way; other config keys write the DB plane, which loadConfig() does not read — put those in the file or env directly
  • OR put the key in ~/.gbrain/config.json directly
  • OR set GBRAIN_DATABASE_URL / DATABASE_URL / per-provider env on the worker process

If the worker can't resolve a requested name, the validator fail-fasts at submit time with a gbrain config set <X> hint, instead of a silent "No database URL" failure in child stderr minutes after submission.

Related. A gbrain doctor check home_dir_in_worktree warns if ~/.gbrain/ lives inside a git worktree. A ~/.gbrain/.gitignore (single line *) is laid down by every saveConfig() call AND by gbrain post-upgrade, so existing installs get coverage without re-running gbrain init. Honest scope: the .gitignore covers casual git add but does NOT cover already-tracked files, screenshots, backups, or git add -f.

Strategy framing. For agent-to-gbrain calls, the canonical guide is docs/guides/agent-to-gbrain.md. Two distinct surfaces: HTTP MCP via OAuth for ops with MCP equivalents (search, query, put_page, etc.), and shell job + inherit: for localOnly admin ops (sync, embed, dream, doctor, etc.). Not a fallback hierarchy — pick by op.

Errors to handle (your agent submits shell jobs; surface these clearly):

Error What it means Agent action
shell: inherit must be an array of config-key names inherit wasn't an array. Pass "inherit": ["database_url", ...].
shell: inherit entries must be non-empty strings Element was empty, non-string, or null. Use snake_case config-key names.
shell: inherit name "<X>" must match [a-z][a-z0-9_]* Name failed snake_case regex (uppercase, leading underscore, etc.). Use the config-key verbatim — database_url, not DATABASE_URL.
shell: inherit requested "<X>" but worker has no <X> configured Worker can't resolve the name from its loadConfig(). Run gbrain config set <X> <value> on the worker host.