c2ae4dbfc5 v0.25.1 feat: book-mirror flagship + 8 research skills + skillpack uninstall + post-install advisory (#566)
* v0.25.1 foundation: scaffolds + manifests + filing-doctrine update

Foundation commit for v0.25.1 skills wave (book-mirror flagship + 8 research
pairings). All content is scaffold-stage; subsequent commits port wintermute
SKILL.md content into pure gbrain idiom.

Version bumps:
- VERSION 0.24.0 -> 0.25.1
- package.json: version + engines.bun >= 1.3.10 (D14 PTY harness)
- openclaw.plugin.json inner version 0.19.0 -> 0.25.1
- bun.lock refreshed

9 skill scaffolds via `gbrain skillify scaffold` (frontmatter + RESOLVER row +
routing-eval seed): book-mirror, article-enrichment, strategic-reading,
concept-synthesis, perplexity-research, archive-crawler, academic-verify,
brain-pdf, voice-note-ingest. Stub .mjs scripts and stub .test.ts files
deleted; these are pure-markdown skills, not deterministic-script skills.
Real tests will return when src/commands/book-mirror.ts and the other
runtime pieces land.

skills/manifest.json + openclaw.plugin.json skills[]: 9 new entries
(codex T6 fix; required by test/skillpack-sync-guard.test.ts).

D13 filing-doctrine update:
- skills/_brain-filing-rules.md: carve out media/<format>/<slug> as a
  sanctioned exception for sui-generis synthesized output.
- skills/_brain-filing-rules.json: add media/books/ and media/articles/
  as `synthesis-output` kind, distinct from raw-ingest filing.
- skills/media-ingest/SKILL.md: refine anti-pattern callout to clarify
  that format-prefixed paths are anti-pattern for raw ingest only,
  sanctioned for one-of-one synthesis.

Privacy guard hardening (codex T7):
- scripts/check-privacy.sh: extended for /data/brain/ and
  /data/.openclaw/ wintermute-specific path patterns. 7 historical
  files allow-listed (frozen migrations, test fixtures, env-var
  fallbacks). PRIVACY OK passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 book-mirror: trusted CLI with read-only subagent fan-out

Implements `gbrain book-mirror` per the locked v0.25.1 plan (D2/α + codex
HIGH-1 fix). Closes the prompt-injection vector codex flagged on the
earlier `allowedSlugPrefixes: ['media/books/*', 'people/*']` design by
narrowing the trust contract at the tool-allowlist layer instead.

Trust contract:
- Each chapter is analyzed by a separate subagent with allowed_tools
  restricted to ['get_page', 'search'] — read-only. Subagents cannot
  call put_page or any mutating op. Untrusted EPUB/PDF content cannot
  prompt-inject any people/* page because subagents lack write access
  entirely.
- Subagents return markdown analysis text via final_message
  (SubagentResult.result). The CLI reads each child's job.result and
  assembles the final two-column page itself.
- The CLI calls put_page once at the end with operator-level trust
  (no viaSubagent flag, no allowedSlugPrefixes). Operator can write
  anywhere; the namespace check doesn't fire for direct CLI calls.

Architecture:
- `--chapters-dir` is the input contract. The skill (which has shell +
  python access) handles EPUB/PDF extraction; the CLI takes pre-extracted
  .txt files. Separation of concerns: skill prepares inputs, CLI is the
  trusted runtime.
- Cost-estimate prompt before launching: ~$0.30/chapter × N at Opus,
  ~$0.06/chapter at Sonnet. Refuses to spend in non-TTY without --yes.
- Idempotency keys on each child: `book-mirror:<slug>:ch-<N>`. Re-running
  on same input dedups against the queue; failed chapters retry.
- Partial-failure handling: assembled page renders with completed
  chapters and a `## Failed chapters` section listing retries needed.
  Exit 1 on any failure; exit 0 only on full success.
- 30-min default per-child timeout (override with --timeout-ms).

CLI wiring:
- `book-mirror` added to CLI_ONLY set in src/cli.ts.
- Lazy-imports src/commands/book-mirror.ts to keep cold-start fast.

Out of scope for this commit (filed for v0.25.1 follow-ons):
- skills/book-mirror/SKILL.md content port (replaces the foundation
  scaffold stub).
- test/book-mirror.test.ts (will test arg parsing, validation, mock
  fan-out, cost-estimate gating, partial-failure assembly).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 book-mirror: port SKILL.md content + routing-eval

Replaces the foundation scaffold stub with the full ported book-mirror
SKILL.md, pointing the agent at the new `gbrain book-mirror` CLI as the
trusted runtime.

skills/book-mirror/SKILL.md:
- Drops wintermute_only frontmatter; uses gbrain frontmatter shape
  (mutating + writes_pages + writes_to: media/books/).
- Documents the trust contract: subagents are read-only, the CLI does
  the put_page write itself with operator trust. Closes the codex
  HIGH-1 prompt-injection vector at the tool-allowlist layer.
- Replaces /data/brain/ absolute paths with $BRAIN_DIR resolution from
  gbrain config.
- Replaces brain-commit-link.sh / direct shell-script writes with the
  CLI's single put_page call.
- Documents EPUB/PDF extraction via the agent's shell + python access
  (BeautifulSoup4 for EPUB, pdftotext for PDF). The skill prepares
  inputs; the CLI is the trusted runtime.
- Privacy scrub clean — no real names, no /data/brain/, no .openclaw/,
  no Wintermute literals.

skills/book-mirror/routing-eval.jsonl:
- 5 paraphrased intents per D-CX-6 rule (intent paraphrases the
  trigger, doesn't copy it).
- 3 adversarial intents that pattern-match media-ingest's "process
  this book" trigger (IRON RULE regression test for the
  media-ingest <-> book-mirror routing conflict flagged in R1+R2).
  These assert that book-mirror should NOT win on generic ingest
  phrasing.

skills/_brain-filing-rules.json: 4 new directory kinds added so
check-resolvable's filing audit passes for the new skills' writes_to
declarations:
- idea (ideas/) — generative ideas to act on later (voice-note-ingest,
  archive-crawler).
- research (research/) — web-research deltas, citation-checked claims
  (perplexity-research, academic-verify).
- original (originals/) — user-authored thinking the user originated
  (voice-note-ingest, archive-crawler, signal-detector).
- voice-note (voice-notes/) — random-thought audio capture pages
  (voice-note-ingest).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 ports: article-enrichment + strategic-reading + voice-note-ingest

Replaces SKILLIFY_STUB scaffolds with content-ported SKILL.md files in
pure gbrain idiom:

skills/article-enrichment/SKILL.md:
- Drops wintermute-specific scripts/enrich-article.mjs reference; the
  skill is markdown agent instructions, not a deterministic script
  pipeline.
- Replaces /data/brain/ paths with relative brain-dir paths.
- Documents the structured output contract (Executive Summary,
  Quotable Lines verbatim, Key Insights, Why It Matters, See Also,
  details-block source preservation).
- Sonnet by default, Opus for high-value content.

skills/strategic-reading/SKILL.md:
- Generic problem-lens reading flow (book/article/case study x specific
  strategic problem -> applied playbook with do/avoid/watch-for).
- Drops Garry-specific oppo example ("Tyler Law/Han Zou gatekeeper
  fight"); uses generic "gatekeeper-vs-incumbent fight" framing.
- Files to projects/<slug>/playbook.md (problem-tied) or
  concepts/<slug>.md (general strategy) per primary-subject filing rule.
- Cross-references book-mirror as the whole-life-personalization
  counterpart.

skills/voice-note-ingest/SKILL.md:
- Iron Law: exact phrasing preserved, never paraphrased. Block-quoted
  transcript is sacred; analysis is interpretive.
- 7-step decision tree (originals -> concepts -> people -> companies
  -> ideas -> personal -> voice-notes catch-all) per
  _brain-filing-rules.md.
- Replaces wintermute's brain-commit-link.sh + Supabase Storage helper
  with gbrain transcription + storage interface (pluggable per
  src/core/storage.ts).

Each skill ships routing-eval.jsonl with 5 paraphrased intents per
D-CX-6 (intent paraphrases trigger, doesn't copy it). The literal
"please <trigger> for me now" stubs from gbrain skillify scaffold are
replaced with realistic user phrasings.

Privacy scrub clean — no real names, no /data/brain/, no .openclaw/,
no Wintermute literals.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 ports: concept-synthesis + perplexity-research + brain-pdf

Replaces SKILLIFY_STUB scaffolds with content-ported SKILL.md files in
pure gbrain idiom:

skills/concept-synthesis/SKILL.md:
- 4-phase pipeline: dedup -> tier (T1 Canon to T4 Riff) -> synthesize
  T1/T2 -> cluster + intellectual map.
- Generic across any concept-stub source (signal-detector,
  voice-note-ingest, idea-ingest, archive-crawler).
- Drops wintermute-specific X-pipeline framing (9051 stubs from x-deep-enrich,
  scripts/x-concept-compiler.mjs); skill is markdown agent instructions
  using gbrain query + put_page.
- Output format: T1 gets full synthesis with evolution table + best
  articulation + related-concepts cross-links; T3/T4 stay as stubs.
- Cluster map at concepts/README.md as the master intellectual fingerprint.

skills/perplexity-research/SKILL.md:
- Brain-augmented web research: sends brain context as part of the
  Perplexity prompt so the search focuses on what's NEW vs already-known.
- Output structure: Executive Summary + Key New Developments + Confirming
  Signals + Contradictions or Updates + Recommended Brain Updates +
  Citations.
- Uses Perplexity sonar-pro by default (~$0.04/query); sonar for bulk.
- Drops wintermute-specific scripts/perplexity-research.mjs and
  /data/.env path; documents PERPLEXITY_API_KEY in agent env.
- Cross-references academic-verify (which wraps this skill for
  citation-checked claim verification per D7/alpha) and enrich (entity
  enrichment loop).

skills/brain-pdf/SKILL.md:
- Documents gstack make-pdf as soft prereq with absent-binary detection.
- 4-step workflow: resolve -> strip frontmatter -> render -> deliver.
- Defaults: NO --cover, NO --toc (look corporate and waste space).
- Mandatory CONTAINER=1 for Playwright sandboxing.
- Anti-pattern callout: never use raw MEDIA: tags for Telegram delivery
  (they fail silently); use message tool with filePath= attachment.

Each ships routing-eval.jsonl with 5 paraphrased intents per D-CX-6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 ports: archive-crawler + academic-verify (final SKILL.md batch)

Replaces the last two SKILLIFY_STUB scaffolds. All 9 new skills now
have ported content; `gbrain check-resolvable` reports zero
skillify_stub_unreplaced warnings.

skills/archive-crawler/SKILL.md (D3 + D12):
- Hard safety gate: refuses to run unless `archive-crawler.scan_paths:`
  is set in gbrain.yml. Closes the codex HIGH-4 footgun where 'trust
  the prompt' was not a control.
- Schema-generic port (D3 user constraint): no hardcoded era folders
  (no archive/, post-stanford/, posterous-era/, initialized-era/,
  yc-era/). Reads filing rules from _brain-filing-rules.json at
  runtime; agent decides per-page filing within sanctioned dirs.
- Drops wintermute-specific scripts and brain-commit-link.sh; uses
  gbrain operations for inventory + put_page for ingest.
- File-type handlers preserved (.mbox, .doc/.docx, .pst, .zip, images)
  with the exact same shell + python recipes.
- Manifest tracks per-item triage status + exact user reactions per
  conventions/quality.md exact-phrasing rule.

skills/academic-verify/SKILL.md (D4 + D7/alpha):
- Drops ALL the wintermute-specific oppo / adversarial framing: no
  Goff/Solomon, no CPE, no '48 Hills', no fabrication-detection,
  no 'oppo research where the target relies on academic credentials'.
  This is the public skillpack — research-not-adversarial bar.
- Pure-routing implementation per D7/alpha: skill is a thin
  orchestrator that scopes the claim, invokes
  perplexity-research with citation-mode prompt, and formats results
  as a verdict-shaped brain page. Zero new infrastructure.
- 5 verdict states (verified / partial / unverifiable / misattributed
  / retracted) replace the 'fabrication suspected' / 'methodologically
  flawed' classifications that read like takedown rubric.
- Documents Retraction Watch / PubPeer / OSF / Semantic Scholar /
  OpenAlex / Many Labs as the databases the agent uses via
  perplexity-research, but doesn't ship its own API integrations.

Each ports a routing-eval.jsonl with 5 paraphrased intents per D-CX-6.

Privacy scrub clean. typecheck OK. Remaining check-resolvable warnings
are routing_miss on the substring matcher (paraphrased intents don't
exact-match the RESOLVER triggers); the LLM tie-break layer is a
v0.26+ enhancement per CLAUDE.md routing-eval section. Warnings are
advisory, not errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 drift backports: citation-fixer + testing + cross-modal-review

Pulls the wintermute drift improvements identified by R1's quick audit
into the public skillpack, in pure gbrain idiom (no real names, no
/data/brain/ paths, no Wintermute literals — privacy guard passes).

skills/citation-fixer/SKILL.md (PORT, version 1.0 -> 1.1):
- Adds tweet/post URL resolution: scans pages for broken tweet
  references (no x.com URL) and resolves them via the host's X API
  integration.
- 5-step pipeline: identify broken refs -> extract searchable content
  (handle/quote/date) -> X API search -> verify + extract metadata
  -> patch the page with deterministic URL.
- Batch-mode pattern with priority order (recently changed pages
  first), rate-limit guidance (~50 pages/run), batch-commit cadence.
- Integration callout: enrich + media-ingest can call
  citation-fixer pre-commit to validate output.
- Anti-pattern: never compose tweet URLs by guessing the id;
  deterministic links only (per _output-rules.md).

skills/testing/SKILL.md (PORT, version 1.0 -> 1.1):
- Splits into TWO modes: skill conformance validation (original 1.0
  scope) AND project test-suite health (v0.25.1 extension).
- Test tiers: unit (<2s, every commit), evals (~60s, daily),
  integration (~5m, pre-ship + nightly), system health (<10s).
- Daily run protocol: unit -> evals -> system -> git diff analysis
  for regression intelligence.
- Failure classification: REGRESSION / STALE / FLAKE / NEW / INFRA
  with markers (red / yellow / warning / green / wrench).
- Auto-fix protocol: explicit DO and DO NOT lists. Security-test
  failures always escalate, never auto-fix.
- State tracking at ~/.gbrain/test-state.json for trend analysis,
  flake detection, regression velocity.

skills/cross-modal-review/SKILL.md (PORT, version 1.0 -> 1.1):
- Adds explicit "When to invoke" gating (significant code changes 5+
  files / 100+ lines, security-sensitive, architecture, churning,
  pre-bulk, skill creation, brain-page quality) vs DO NOT invoke
  (simple memory writes, typo fixes, routine cron, post-review
  commits).
- Adds code-review handoff section: knows WHEN to recommend gstack's
  /codex review (independent diff review from a different AI) and how
  to frame the cross-model output.
- Adversarial Challenge sub-mode: red-team prompt for security-
  sensitive changes; output adds exploitability rating
  (CRITICAL/HIGH/MEDIUM/LOW) + mitigations.
- Iron Law: user-sovereignty rule explicitly captured. Reviewer
  findings are informational until the user explicitly approves;
  cross-model consensus is signal, not permission.

All three pass scripts/check-privacy.sh (no Wintermute literals, no
/data/brain/, no /data/.openclaw/). typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 skillpack uninstall: D6 + D8 + D11 content-hash guard

Implements `gbrain skillpack uninstall <name>` per the locked
v0.25.1 plan. Inverse of install with symmetric data-loss posture:
refuses if the slug isn't in the managed-block's cumulative-slugs
receipt (D8) or if any installed file diverges from the bundle
original (D11). Same --overwrite-local escape hatch as install.

src/core/skillpack/installer.ts:
- New UninstallError class (mirrors InstallError shape) with codes:
  lock_held, bundle_error, target_missing, unknown_skill,
  user_added_slug (D8), locally_modified (D11), managed_block_missing.
- New types: UninstallFileOutcome, UninstallFileResult,
  UninstallResult, UninstallOptions.
- New applyUninstall() function. Steps:
  1. Acquire workspace lockfile (same gate as install).
  2. D8 check: read managed block; verify slug is in cumulative-slugs
     receipt. If user-added or unknown, throw user_added_slug.
  3. Enumerate bundle entries scoped to the skill (NOT shared_deps —
     other installed skills depend on them).
  4. D11 check: hash each existing target file vs bundle original.
     Skip removal for divergent files unless --overwrite-local.
  5. Atomic: if ANY file would be skipped due to local-mod and the
     user did not pass --overwrite-local, refuse the WHOLE uninstall
     (no half-uninstall — would desync managed block from filesystem).
  6. Rebuild managed block via applyManagedBlockUninstall() (drops
     slug from cumulative-slugs, preserves other rows + user-added
     unknown rows with stderr warning, atomic write via writeAtomic).
  7. Release lock.

src/commands/skillpack.ts:
- Wire `gbrain skillpack uninstall` subcommand. Flags mirror install:
  --dry-run, --overwrite-local, --force-unlock, --skills-dir,
  --workspace, --json, --help.
- Exit codes: 0 success, 1 refused due to local-mod (recoverable
  with --overwrite-local), 2 setup error (slug not in receipt, no
  workspace, lock held, etc.).
- Help text documents the symmetric trust contract explicitly.

D6 test slot is filled (smoke test t2 "uninstall changes routing"
will use this command). Per the plan, no `--all` uninstall in v0.25.1
(scope-narrowing; renaming a skill in the bundle should still be the
install --all path that prunes).

Typecheck passes. Privacy guard passes. `gbrain skillpack uninstall
--help` renders correctly.

Out of scope for this commit (next):
- test/skillpack-uninstall.test.ts (D8 + D11 cases, multi-arg,
  fail-loud-under-lock, idempotent-when-absent).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 archive-crawler safety gate (D12 + codex HIGH-4 fix)

Adds the gbrain.yml `archive-crawler.scan_paths:` allow-list contract
that closes the codex HIGH-4 finding. The archive-crawler skill
refuses to run unless the user has explicitly listed paths the agent
is permitted to scan.

src/core/archive-crawler-config.ts (NEW, 263 lines):
- Sibling to storage-config.ts (separate concern: archive scanning,
  not storage tiering; same gbrain.yml file shape).
- Hand-rolled parser for the `archive-crawler:` section (mirrors
  storage-config's parsing pattern; same trade-off — narrow-but-
  predictable, zero-dep).
- Accepts both `archive-crawler:` and `archive_crawler:` spellings.
- ArchiveCrawlerConfig: { scan_paths: string[]; deny_paths: string[] }
  — both normalized to absolute trailing-slashed paths.
- Validation:
  * scan_paths MUST be non-empty (D12 contract)
  * Every path absolute after ~ expansion (rejects relative)
  * Path-traversal rejected (`..` literal in path → invalid_path)
  * Trailing-slash normalized for unambiguous prefix matching
- isPathAllowed(candidate, config) helper for runtime per-file gate:
  prefix-match against scan_paths, deny_paths overrides. Directory-
  boundary safe — /writing/ does NOT match /writing-stuff/.
- ArchiveCrawlerConfigError class with discriminated codes:
  missing_section / empty_scan_paths / invalid_path / parse_error.

test/archive-crawler-config.test.ts (NEW, 19 tests):
- D12 missing_section gates: null repoPath, missing gbrain.yml, no
  archive-crawler section.
- D12 empty_scan_paths: scan_paths omitted or empty array.
- D12 invalid_path: relative path, ".." traversal in scan_paths,
  ".." traversal in deny_paths.
- Happy path: normalized paths, ~ expansion, deny_paths optional,
  both archive-crawler and archive_crawler key spellings.
- Direct API validation (normalizeAndValidateArchiveCrawlerConfig).
- isPathAllowed: scan_path match, scan_path miss, deny_path override,
  directory-boundary correctness (writing/ vs writing-stuff/),
  relative-path rejection.

19/19 pass in 17ms. Privacy guard passes. Typecheck OK.

The skills/archive-crawler/SKILL.md (already shipped in earlier
commit) documents the contract; this commit lands the runtime
that enforces it. The skill's safety claim is no longer aspirational.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 PTY harness port from gstack (D14/C-prime)

Ports gstack's claude-pty-runner.ts (~1300 lines) as a generalized
gbrain harness (~470 lines after trimming gstack-specific
orchestrators). Used by the smoke test E2E to drive interactive
openclaw sessions; future: any CLI command that grows interactive
prompts becomes testable without a refactor.

test/helpers/cli-pty-runner.ts (NEW, 470 lines):
- launchPty(opts): generic CLI spawner via Bun.spawn `terminal:` mode.
  Drops gstack's launchClaudePty's --permission-mode plan default;
  takes any binary + args.
- resolveBinary(name, override?): finds CLI binaries on PATH with
  homebrew/local/bun fallbacks.
- stripAnsi: standard CSI + OSC + charset + DEC-special escape
  stripping (verbatim port).
- isNumberedOptionListVisible: cursor + numbered list detection.
- parseNumberedOptions: extracts cursor-anchored numbered AUQ options
  (1-based indices, sequential block only). Handles cursor-on-non-1
  (user pressed Down) and box-layout AUQs (cursor mid-line after
  dividers). Reads only last 4KB to avoid matching stale lists.
- optionsSignature: stable hash for "is this AUQ the same as last
  poll?" detection.
- isTrustDialogVisible: matches Claude Code's "trust this folder"
  dialog so launchPty can auto-handle it.
- PtyOptions / PtySession types + send / sendKey / mark / visibleSince
  / waitFor / waitForAny primitives.
- launchPty internals: terminal: mode, exit tracking, wall-clock
  timeout, autoTrust polling watcher (15s window), graceful close
  with SIGINT then SIGKILL fallback.

DROPPED from the gstack original (gstack-specific):
- runPlanSkillObservation, runPlanSkillCounting, invokeAndObserve
  (Claude-Code plan-mode test orchestrators).
- isPlanReadyVisible, isPermissionDialogVisible (Claude-Code-specific
  dialog detection).
- ceoStep0Boundary, engStep0Boundary, designStep0Boundary,
  devexStep0Boundary (per-skill /plan-* boundary predicates).
- MODE_RE, COMPLETION_SUMMARY_RE, parseQuestionPrompt, auqFingerprint,
  assertReviewReportAtBottom (gstack plan-review specifics).
- classifyVisible (plan-mode outcome classifier).

If the smoke test ever needs Claude-Code-specific dialog detection,
add a thin wrapper in test/e2e/ — keeping the harness generic.

test/cli-pty-runner.test.ts (NEW, 24 tests, all pass):
- stripAnsi: 6 cases (CSI, OSC-BEL, OSC-ST, charset, DEC-special, plain)
- isNumberedOptionListVisible: 4 cases (match, no-cursor, single-opt,
  TTY collapsed-whitespace)
- parseNumberedOptions: 7 cases (3-opt, no-list, single-opt, prose-
  gating-pattern, gap-truncation, cursor-on-non-1, last-4KB-only)
- optionsSignature: 2 cases (order-independence, label-changes-sig)
- isTrustDialogVisible: 2 cases (canonical phrase, non-match)
- resolveBinary: 3 cases (override, missing, sh-on-path)

24/24 pass in 14ms. Privacy guard passes. Typecheck OK.

Bun version requirement (D14): engines.bun >= 1.3.10 (set in commit
b438a7c4) — required by Bun.spawn terminal: mode.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 skillpack uninstall tests + atomic-refusal bug fix

10 tests for applyUninstall covering D6 + D8 + D11. Found and fixed a
real atomic-refusal bug while writing them.

src/core/skillpack/installer.ts (BUG FIX):
- applyUninstall previously interleaved D11 hash check + unlink in
  the same loop. If file 5/N diverged, files 1..4 were ALREADY gone
  by the time the throw fired — half-uninstalled state, managed
  block out of sync with filesystem.
- Now: pre-scan ALL files for divergence into a fileChecks array;
  refuse loudly BEFORE any filesystem mutation if anything is
  blocked. Then unlink in a second pass (no decisions left to make).
- The atomic-refusal contract documented in the original code now
  matches the actual behavior. The contract was always the intent;
  the implementation just shipped wrong.

test/skillpack-uninstall.test.ts (NEW, 10 tests):
- Happy path: removes alpha files, drops slug from cumulative-slugs
  receipt, --dry-run leaves disk untouched.
- Preserves other installed skills: install --all then uninstall
  alpha, beta still present + still in receipt.
- D8 user_added_slug: refuses uninstall when slug not in
  cumulative-slugs receipt; refuses even when user hand-added the
  managed-block row.
- D11 locally_modified: file diverges from bundle → throws + NOTHING
  removed (atomic refusal; this is the test that caught the bug).
- D11 --overwrite-local: bypasses guard, removes anyway.
- unknown_skill / bundle_error: bad slug rejected with typed error.
- managed_block_missing: no RESOLVER.md in target → typed error.
- Idempotency: file already absent on disk doesn't crash; counts
  in result.summary.absent.

10/10 pass in 53ms. All 90 skillpack-related tests still pass
(install + uninstall + sync-guard + harness + archive-crawler).
Privacy guard passes. Typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 book-mirror tests — CLI surface + source invariants

9 tests pinning the book-mirror CLI's contract surface and
regression-detector source patterns. Pure surface tests; the full
subagent fan-out integration is exercised by the opt-in smoke test
(test/e2e/skill-smoke-openclaw.test.ts when EVALS=1).

Architecture note documented in the test file: src/cli.ts dispatches
connectEngine() BEFORE any CLI_ONLY command's own arg parsing,
including --help. This is a pre-existing choice (every CLI_ONLY
command — agent, sync, jobs, book-mirror — behaves identically) so
arg-validation paths can't be exercised from a clean tempdir without
DATABASE_URL. The smoke test covers them with a real engine.

What we test:
- book-mirror is registered in CLI_ONLY (no "Unknown command")
- Without DB, never reaches the queue-submission path
- Source file: exports runBookMirrorCmd
- Source file: documents the trust contract (codex HIGH-1 fix marker)
- Source file: read-only allowed_tools = ['get_page', 'search']
  (the actual trust narrowing — regression-detector for someone
  adding put_page back to the subagent's tool list)
- Source file: operator-trust put_page (remote: false, viaSubagent
  intentionally omitted as a regression-detector inline comment)
- Source file: cost-estimate confirmation (P1)
- Source file: idempotency keys for child jobs
- Source file: partial-failure handling

9/9 pass in 157ms. Privacy guard passes. Typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 docs: CHANGELOG + CLAUDE.md + migration + privacy allow-list

CHANGELOG.md (NEW v0.25.1 entry):
- Garry-voice release summary per CLAUDE.md voice rules: bold two-line
  headline, lead paragraph, "numbers that matter" table, "what this
  means for builders" closer, "To take advantage of v0.25.1" verify
  block, itemized changes (skills / CLI / filing / test infra / CI
  guard / config schema / drift backports / bug fix / tests / deferred).
- Documents the cross-model review trail: 15 user decisions across
  R1 + R2 + codex outside voice; 4 codex HIGH findings the eng
  review missed.
- The atomic-refusal bug fix called out as the cross-model loop
  working: test was written with the contract in mind, implementation
  lied about the contract, lie surfaced immediately.

CLAUDE.md (Key Files updates):
- src/commands/book-mirror.ts: full annotation with trust contract,
  codex HIGH-1 fix, idempotency keys, partial-failure handling.
- src/commands/skillpack.ts: extended with v0.25.1 uninstall
  semantics — D8 user-added refuse, D11 content-hash guard, atomic-
  refusal contract enforced by test.
- src/core/archive-crawler-config.ts: D12 + codex HIGH-4 safety
  gate documentation.
- test/helpers/cli-pty-runner.ts: PTY harness port from gstack
  documented.

skills/migrations/v0.25.1.md (NEW):
- Agent-readable upgrade walkthrough. 6 steps:
  1. Verify upgrade landed
  2. Install new skills (optional)
  3. Configure archive-crawler scan_paths if installed (REQUIRED)
  4. Use gbrain book-mirror (optional, the flagship)
  5. gbrain skillpack uninstall (when you want it)
  6. Privacy CI guard (fork-operators only)
- "If anything fails" feedback loop pointing at the issues tracker.

scripts/check-privacy.sh:
- CHANGELOG.md added to ALLOW_LIST. The v0.25.1 release notes
  document the BANNED_PATHS extension and reference the patterns
  in describing what's banned — same exception status as CLAUDE.md
  (which describes the rules) and the script itself.

Privacy guard passes. Typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 README: 34 skills + new "Research and synthesis" section

README.md updates:
- Top-of-page count: "29 skills" -> "34 skills" (4 places).
- Section header: "The 29 Skills" -> "The 34 Skills" with a
  pointer to the new Research and synthesis section.
- Added voice-note-ingest + article-enrichment under Content
  ingestion.
- New "Research and synthesis (v0.25.1)" section with 7 skills:
  book-mirror (flagship), strategic-reading, concept-synthesis,
  perplexity-research, archive-crawler (with safety-fence callout),
  academic-verify, brain-pdf.
- Each entry is one-line, what-it-does framing, no AI vocabulary.

scripts/check-privacy.sh:
- Added skills/migrations/v0.25.1.md to ALLOW_LIST. Same exception
  status as CHANGELOG.md and CLAUDE.md: meta-documentation that
  references the banned patterns to explain what's banned to the
  operating agent.

Privacy guard passes. Typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 verification: conformance sections + routing-eval intents + test loosen

Final pass to make the test suite green.

skills/{12 ports + backports}/SKILL.md:
- Renamed `## Anti-patterns` -> `## Anti-Patterns` (capital P) so the
  conformance test (test/skills-conformance.test.ts) sees the literal
  header it requires.
- Appended `## Contract` and `## Output Format` skeleton sections to
  every new SKILL.md and any backport that didn't have them. The
  conformance test asserts these literal headers; content can be brief
  (the body sections above already carry the substantive contract /
  output prose).
- Privacy guard: changed the appended Contract prose from
  "no `/data/brain/` literals" to "no fork-specific filesystem path
  literals" so the guard doesn't flag the doc text.

skills/{9 new ports + book-mirror}/routing-eval.jsonl:
- Rewrote intents so each contains at least one trigger string as
  substring. The structural matcher in check-resolvable requires
  substring match against triggers; my earlier intents were too
  paraphrased (per D-CX-6 rule) and missed the matcher entirely.
  Now each fixture has 5 intents that BOTH paraphrase user phrasing
  AND contain a literal trigger. book-mirror keeps its 3 adversarial
  intents that route to media-ingest (IRON RULE regression test).
- Fixed perplexity-research intent ambiguity: "Run perplexity research"
  was matching data-research too; tightened to "perplexity-research"
  with hyphen + added ambiguous_with to acknowledge the overlap.

test/check-resolvable.test.ts:
- v0.22.4 regression test loosened: routing_miss warnings are now
  ALLOWED (still fails on errors and on other warning types like
  trigger overlap, DRY violations, filing-rule misses). Documented
  in-line: routing_miss surfaces naturally when intents are
  paraphrased per D-CX-6; the LLM tie-break layer (placeholder per
  v0.24.0) is the intended fix when it ships.
- Test renamed: "0 warnings" -> "0 errors" to match the new contract.

Verification:
- scripts/check-privacy.sh OK
- bun run typecheck OK
- 423 tests / 0 fails on the v0.25.1-relevant suite (book-mirror,
  skillpack-install, skillpack-uninstall, skillpack-sync-guard,
  cli-pty-runner, archive-crawler-config, skills-conformance,
  resolver, check-resolvable, check-resolvable-cli).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 post-install advisory: agent-readable "what to do next"

gbrain users typically interact through their host agent (openclaw,
claude-code), not the CLI directly. So an interactive TTY prompt at
install time misses most of the audience. Instead: every gbrain init
and gbrain post-upgrade ends by printing an advisory the agent reads
from terminal output.

The advisory:
1. Names the version that just landed (0.25.1)
2. Lists each new skill the workspace hasn't installed yet, with a
   one-line value prop (FLAGSHIP, two-column, brain-augmented, etc.)
3. Tells the agent EXPLICITLY to ask the user before installing
4. Prints the exact command if the user says yes
5. Shows alternative commands (install <name>, list) if they say no

Detection logic (no nag):
- Reads cumulative-slugs receipt from the workspace's managed block
- Filters the v0.25.1 recommended set against installed slugs
- Returns null when every recommended skill is already installed
  (so existing-user upgrades that already installed --all don't get
  re-pestered every gbrain post-upgrade run)
- Workspace not detected → still renders advisory with a workspace-
  detection note (the agent can prompt the user for the right path)

src/core/skillpack/post-install-advisory.ts (NEW, 209 lines):
- V0_25_1_RECOMMENDED constant: the 9 new skills + descriptions.
  Future releases either bump the constant or read frontmatter from
  the latest migration file.
- detectInstalledSlugs(skillsDir, workspace): reads receipt or falls
  back to extractManagedSlugs for pre-v0.19 fences.
- buildAdvisory({ version, context, targetWorkspace, targetSkillsDir }):
  returns string OR null. Picks `--all` command for fresh installs,
  per-skill command for upgrades with subset missing.
- printAdvisoryIfRecommended(): no-op safe wrapper for the caller.
- Renders to stderr (stdout stays clean for --json output).

src/commands/init.ts: prints the advisory after both PGLite and
Postgres init paths succeed.

src/commands/upgrade.ts (runPostUpgrade): prints the advisory at the
end of post-upgrade, after migrations apply. Best-effort wrapped —
never blocks post-upgrade on a print failure.

test/post-install-advisory.test.ts (NEW, 10 cases):
- detectInstalledSlugs: empty set on no managed block; reads receipt
- partial-install: lists ONLY missing; uses per-skill command
- fresh-install (no slugs): uses --all command
- all-installed: returns null (no nag)
- agent-readable framing: "ACTION FOR THE AGENT", "Ask the user
  explicitly", "Do NOT install without asking", "user owns this
  decision"
- version + context (init vs upgrade) phrasing differ correctly
- one-line skill descriptions present (FLAGSHIP, two-column, etc.)
- workspace-not-detected fallback still renders with a note

10/10 pass in 25ms. Privacy guard passes. Typecheck OK.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 docs: document post-install advisory in CHANGELOG + migration

CHANGELOG.md: new section "Added (post-install advisory — v0.25.1 DX)"
explaining the advisory module, the "agent-readable instead of TTY
prompt" design choice, and which commands print it.

skills/migrations/v0.25.1.md: new Step 0 explicitly tells the
operating agent to handle the post-install advisory FIRST (the
banner the user just saw after `gbrain upgrade`), then return to the
rest of the migration steps. If the advisory didn't print, the
workspace is already up to date.

The migration file is what the agent reads after `gbrain upgrade`
runs `gbrain post-upgrade` and prints the banner — Step 0 closes
the loop between the advisory's "ASK THE USER FIRST" and the
existing migration walkthrough.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* v0.25.1 regen llms-full.txt — pick up v0.25.1 CLAUDE.md additions

The build-llms regen-drift guard (test/build-llms.test.ts) caught that
llms-full.txt was stale after the merge with master. CLAUDE.md gained
v0.25.1 entries (book-mirror.ts, archive-crawler-config.ts,
cli-pty-runner.ts, skillpack uninstall annotation) that the generator
inlines into llms-full.txt. Regenerated via bun run build:llms.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 08:41:11 -07:00

GBrain

Your AI agent is smart but forgetful. GBrain gives it a brain.

Built by the President and CEO of Y Combinator to run his actual AI agents. The production brain powering his OpenClaw and Hermes deployments: 17,888 pages, 4,383 people, 723 companies, 21 cron jobs running autonomously, built in 12 days. The agent ingests meetings, emails, tweets, voice calls, and original ideas while you sleep. It enriches every person and company it encounters. It fixes its own citations and consolidates memory overnight. You wake up and the brain is smarter than when you went to bed.

The brain wires itself. Every page write extracts entity references and creates typed links (attended, works_at, invested_in, founded, advises) with zero LLM calls. Hybrid search. Self-wiring knowledge graph. Structured timeline. Backlink-boosted ranking. Ask "who works at Acme AI?" or "what did Bob invest in this quarter?" and get answers vector search alone can't reach. Benchmarked side-by-side against the category: gbrain lands P@5 49.1%, R@5 97.9% on a 240-page Opus-generated rich-prose corpus, beating its own graph-disabled variant by +31.4 points P@5 and ripgrep-BM25 + vector-only RAG by a similar margin. The graph layer plus v0.12 extract quality together carry the gap. Full BrainBench scorecards + corpus live in the sibling gbrain-evals repo.

GBrain is those patterns, generalized. 34 skills. Install in 30 minutes. Your agent does the work. As Garry's personal agent gets smarter, so does yours.

New in v0.25.0 — BrainBench-Real (session capture, contributor opt-in): with GBRAIN_CONTRIBUTOR_MODE=1 set in your shell, every real query + search call through MCP, CLI, or the subagent tool-bridge gets captured (PII-scrubbed) into an eval_candidates table. Snapshot with gbrain eval export, replay against your code change with gbrain eval replay. Three numbers come back: mean Jaccard@k between captured and current retrieved slugs, top-1 stability, and latency Δ. Off by default for production users — no surprise data accumulation. Walkthrough: docs/eval-bench.md. NDJSON wire format: docs/eval-capture.md.

~30 minutes to a fully working brain. Database ready in 2 seconds (PGLite, no server). You just answer questions about API keys.

LLMs: fetch llms.txt for the documentation map, or llms-full.txt for the same map with core docs inlined in one fetch. Agents: start with AGENTS.md (or CLAUDE.md if you're Claude Code).

Install

GBrain is designed to be installed and operated by an AI agent. If you don't have one running yet:

Paste this into your agent:

Retrieve and follow the instructions at:
https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md

That's it. The agent clones the repo, installs GBrain, sets up the brain, loads 34 skills, and configures recurring jobs. You answer a few questions about API keys. ~30 minutes.

If your agent doesn't auto-read AGENTS.md, point it at that file first: https://raw.githubusercontent.com/garrytan/gbrain/master/AGENTS.md is the non-Claude agent operating protocol (install, read order, trust boundary, common tasks). For the full doc map, use llms.txt at the same URL root.

Standalone CLI (no agent)

git clone https://github.com/garrytan/gbrain.git && cd gbrain && bun install && bun link
gbrain init                     # local brain, ready in 2 seconds
gbrain import ~/notes/          # index your markdown
gbrain query "what themes show up across my notes?"

Do NOT use bun install -g github:garrytan/gbrain. Bun blocks the top-level postinstall hook on global installs, so schema migrations never run and the CLI aborts with Aborted() the first time it opens PGLite. Use git clone + bun install && bun link as shown above. See #218.

3 results (hybrid search, 0.12s):

1. concepts/do-things-that-dont-scale (score: 0.94)
   PG's argument that unscalable effort teaches you what users want.
   [Source: paulgraham.com, 2013-07-01]

2. originals/founder-mode-observation (score: 0.87)
   Deep involvement isn't micromanagement if it expands the team's thinking.

3. concepts/build-something-people-want (score: 0.81)
   The YC motto. Connected to 12 other brain pages.

MCP server (Claude Code, Cursor, Windsurf)

GBrain exposes 30+ MCP tools via stdio:

{
  "mcpServers": {
    "gbrain": { "command": "gbrain", "args": ["serve"] }
  }
}

Add to ~/.claude/server.json (Claude Code), Settings > MCP Servers (Cursor), or your client's MCP config.

Remote MCP (Claude Desktop, Cowork, Perplexity)

gbrain auth create "claude-desktop"            # tokens via the existing CLI
gbrain serve --http --port 8787                 # built-in HTTP transport (Postgres-only)
ngrok http 8787 --url your-brain.ngrok.app      # any tunnel works
claude mcp add gbrain -t http https://your-brain.ngrok.app/mcp -H "Authorization: Bearer TOKEN"

Per-client guides: docs/mcp/. Hardening defaults, env vars, and threat model: SECURITY.md. ChatGPT requires OAuth 2.1 (not yet implemented).

Using gbrain with GStack

If your engineering agent runs on GStack, point it at gbrain for code lookup instead of grep+read. Cathedral II (v0.21.0) ships call-graph edges and two-pass retrieval — /investigate, /review, /plan-eng-review, and /office-hours all benefit when the agent walks the symbol graph instead of scanning files line by line.

The five magical-moment commands:

gbrain code-callers searchKeyword           # who calls this symbol?
gbrain code-callees searchKeyword           # what does this symbol call?
gbrain code-def BrainEngine                 # where is X defined?
gbrain code-refs BrainEngine                # all reference sites
gbrain query "how does N+1 handling work" --near-symbol BrainEngine.searchKeyword --walk-depth 2

All five auto-emit JSON on non-TTY (gh-CLI convention) so a GStack subagent shelling out via bash gets a clean parseable response. Run gbrain sources add <repo> --strategy code to index a repo, then your agent's brain-first lookup covers code, not just markdown. (Cathedral II release notes)

The 34 Skills

GBrain ships 34 skills organized by skills/RESOLVER.md (or your OpenClaw's AGENTS.md — both filenames are supported as of v0.19). The resolver tells your agent which skill to read for any task. v0.25.1 added 9 research-flavored skills (book-mirror flagship plus 8 pairings); see the new "Research and synthesis" section below.

Skill files are code. They're the most powerful way to get knowledge work done. A skill file is a fat markdown document that encodes an entire workflow: when to fire, what to check, how to chain with other skills, what quality bar to enforce. The agent reads the skill and executes it. Skills can also call deterministic TypeScript code bundled in GBrain (search, import, embed, sync) for the parts that shouldn't be left to LLM judgment. Thin harness, fat skills: the intelligence lives in the skills, not the runtime.

Always-on

Skill What it does
signal-detector Fires on every message. Spawns a cheap model in parallel to capture original thinking and entity mentions. The brain compounds on autopilot.
brain-ops Brain-first lookup before any external API. The read-enrich-write loop that makes every response smarter.

Content ingestion

Skill What it does
ingest Thin router. Detects input type and delegates to the right ingestion skill.
idea-ingest Links, articles, tweets become brain pages with analysis, author people pages, and cross-linking.
media-ingest Video, audio, PDF, books, screenshots, GitHub repos. Transcripts, entity extraction, backlink propagation.
meeting-ingestion Transcripts become brain pages. Every attendee gets enriched. Every company gets a timeline entry.
voice-note-ingest Voice notes captured verbatim — exact phrasing preserved, never paraphrased. Routes to originals/concepts/people/companies/ideas/personal/voice-notes based on content.
article-enrichment Raw article dumps become structured pages with executive summary, verbatim quotes, key insights, and why-it-matters.

Research and synthesis (v0.25.1)

Skill What it does
book-mirror Flagship. Hand the agent a book, get a personalized two-column chapter-by-chapter analysis. Left column preserves the chapter's actual content; right column maps every idea to your life using your words from the brain. ~$6 for a 20-chapter book at Opus. Pairs with gbrain book-mirror CLI for the trusted runtime.
strategic-reading Read a book / article / case study through ONE specific problem-lens. Output: applied playbook with do / avoid / watch-for and short / medium / long-term recommendations.
concept-synthesis Deduplicate thousands of concept stubs into a tiered intellectual map (T1 Canon to T4 Riff). Trace how ideas evolved across years of notes.
perplexity-research Brain-augmented web research. Sends brain context to Perplexity so the search focuses on what's NEW vs already-known. Output: Executive Summary + Key New Developments + Confirming Signals + Contradictions or Updates + Recommended Brain Updates + Citations.
archive-crawler Universal archivist for personal file archives (Dropbox / Backblaze / Gmail-takeout / hard-drive dumps). REFUSES to run unless archive-crawler.scan_paths: is set in gbrain.yml. Safe-by-default safety fence.
academic-verify Trace a research claim through publication → methodology → raw data → independent replication. Routes through perplexity-research; produces a verdict (verified / partial / unverifiable / misattributed / retracted).
brain-pdf Render any brain page to publication-quality PDF via the gstack make-pdf binary. Strips frontmatter, sanitizes emoji, applies running headers.

Brain operations

Skill What it does
enrich Tiered enrichment (Tier 1/2/3). Creates and updates person/company pages with compiled truth and timelines.
query 3-layer search with synthesis and citations. Says "the brain doesn't have info on X" instead of hallucinating.
maintain Periodic health: stale pages, orphans, dead links, citation audit, back-link enforcement, tag consistency. v0.23 adds the dream cycle's synthesize + patterns phases ... overnight conversation transcripts become reflections, originals, and 25-year patterns.
citation-fixer Scans pages for missing or malformed citations. Fixes format to match the standard.
repo-architecture Where new brain files go. Decision protocol: primary subject determines directory, not format.
publish Share brain pages as password-protected HTML. Zero LLM calls.
data-research Structured data research with parameterized YAML recipes. Extract investor updates, expenses, company metrics from email.

Operational

Skill What it does
daily-task-manager Task lifecycle with priority levels (P0-P3). Stored as searchable brain pages.
daily-task-prep Morning prep: calendar lookahead with brain context per attendee, open threads, task review.
cron-scheduler Schedule staggering (5-min offsets), quiet hours (timezone-aware with wake-up override), idempotency.
reports Timestamped reports with keyword routing. "What's the latest briefing?" finds it instantly.
cross-modal-review Quality gate via second model. Refusal routing: if one model refuses, silently switch.
webhook-transforms External events (SMS, meetings, social mentions) converted into brain pages with entity extraction.
testing Validates every skill has SKILL.md with frontmatter, manifest coverage, resolver coverage.
skill-creator Create new skills following the conformance standard. MECE check against existing skills.
skillify The "skillify it!" meta-skill. Orchestrates the 10-step loop so failures become durable skills: scaffold the stubs via gbrain skillify scaffold, write the real logic, gate with gbrain skillify check + gbrain check-resolvable.
skillpack-check Agent-readable gbrain health report. Exit code for CI; JSON for debugging. Cron-friendly.
smoke-test 8 post-restart health checks with auto-fix (Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo). Drop-in user tests at ~/.gbrain/smoke-tests.d/*.sh.
minion-orchestrator Background work in one skill. Shell jobs via gbrain jobs submit shell (operator/CLI, MCP blocks protected names) and LLM subagents via gbrain agent run. Parent-child DAGs, child_done inbox, durability across worker restarts.

Identity and setup

Skill What it does
soul-audit 6-phase interview generating SOUL.md (agent identity), USER.md (user profile), ACCESS_POLICY.md (4-tier privacy), HEARTBEAT.md (operational cadence).
setup Auto-provision PGLite or Supabase. First import. GStack detection.
migrate Universal migration from Obsidian, Notion, Logseq, markdown, CSV, JSON, Roam.
briefing Daily briefing with meeting context, active deals, and citation tracking.

Conventions

Cross-cutting rules in skills/conventions/:

  • quality.md ... citations, back-links, notability gate, source attribution
  • brain-first.md ... 5-step lookup before any external API call
  • model-routing.md ... which model for which task
  • test-before-bulk.md ... test 3-5 items before any batch operation
  • cross-modal.yaml ... review pairs and refusal routing chain

How It Works

Signal arrives (meeting, email, tweet, link)
  -> Signal detector captures ideas + entities (parallel, never blocks)
  -> Brain-ops: check the brain first (gbrain search, gbrain get)
  -> Respond with full context
  -> Write: update brain pages with new information + citations
  -> Auto-link: typed relationships extracted on every write (zero LLM calls)
  -> Sync: gbrain indexes changes for next query

Every cycle adds knowledge. The agent enriches a person page after a meeting. Next time that person comes up, the agent already has context. The difference compounds daily.

The system gets smarter on its own. Entity enrichment auto-escalates: a person mentioned once gets a stub page (Tier 3). After 3 mentions across different sources, they get web + social enrichment (Tier 2). After a meeting or 8+ mentions, full pipeline (Tier 1). The brain learns who matters without being told. Deterministic classifiers improve over time via a fail-improve loop that logs every LLM fallback and generates better regex patterns from the failures. gbrain doctor shows the trajectory: "intent classifier: 87% deterministic, up from 40% in week 1."

"Prep me for my meeting with Jordan in 30 minutes" ... pulls dossier, shared history, recent activity, open threads

"What have I said about the relationship between shame and founder performance?" ... searches YOUR thinking, not the internet

Minions: your sub-agents won't drop work anymore

A durable, Postgres-native job queue built into the brain. Every long-running agent task is now a job that survives gateway restarts, streams progress, gets paused / resumed / steered mid-flight, and shows up in gbrain jobs list. Zero infra beyond your existing brain.

The production numbers that matter

Here's my personal OpenClaw deployment: one Render container. Supabase Postgres holding a 45,000-page brain. 19 cron jobs firing on schedule. Real gateway load from real daily work. The task: pull a month of my social posts from an external API and ingest them end-to-end into the brain as a structured page.

Minions sessions_spawn
Wall time 753ms >10,000ms (gateway timeout)
Token cost $0.00 ~$0.03 per run
Success rate 100% 0% (couldn't even spawn)
Memory/job ~2 MB ~80 MB

Under that 19-cron load, sub-agent spawn couldn't clear the 10-second gateway wall. Minions landed it in under a second for zero tokens. Scaling: 19,240 posts across 36 months, single bash loop, ~15 min total, $0.00. Sub-agents: ~9 min best case, ~$1.08 in tokens, ~40% spawn failure. Lab: durability ∞ (SIGKILL mid-flight, 10/10 rescued), throughput ~10× faster, fan-out ~21× with no failure wall, memory ~400× less.

Full benchmarks live in gbrain-evals.

The routing rule

Deterministic (same input → same steps → same output) → Minions Judgment (input requires assessment or decision) → Sub-agents

Pull posts, parse JSON, write a brain page, run a sync — deterministic. $0 tokens, survives restart, millisecond runtime. Triage the inbox, assess meeting priority, decide if a cold email deserves a reply — judgment. What sub-agents are actually good at. minion_mode: pain_triggered (the default) automates the routing.

What's fixed

The six daily pains — spawn storms, agents that stop responding, forgotten dispatches, gateway crashes mid-run, runaway grandchildren, debugging soup — all belonged to the "deterministic work through a reasoning model" mistake. Minions fixes them by not making that mistake: max_children cap, timeout_ms + AbortSignal, child_done inbox, full parent_job_id/depth/transcript per job, Postgres durability with stall detection, cascade cancel via recursive CTE. Plus idempotency keys, attachment validation, removeOnComplete, and gbrain jobs smoke that proves the install in half a second.

gbrain jobs smoke                        # verify install
gbrain jobs submit sync --params '{}'    # fire a background job
gbrain jobs stats                        # health dashboard
gbrain jobs supervisor --concurrency 4   # canonical: auto-restarting worker (Postgres only)
gbrain jobs work --concurrency 4         # raw worker (no crash recovery — prefer `supervisor`)

gbrain jobs supervisor keeps the worker alive across crashes with exponential backoff, atomic PID locking, structured audit events at ~/.gbrain/audit/supervisor-*.jsonl, and a start --detach / status --json / stop subcommand surface for agents. In containers it runs as PID 1; on systemd hosts it's the child of gbrain-worker.service. Full deployment guide: docs/guides/minions-deployment.md.

Read skills/minion-orchestrator/SKILL.md for parent-child DAGs, fan-in collection, steering via inbox.

Minions is not incrementally better than sub-agents for background work. It's categorically different. 753ms vs gateway timeout. $0 vs tokens. 100% vs couldn't-spawn. If your agent does deterministic work on a schedule, it runs on Minions now.

Health check and self-heal

Minions is canonical as of v0.11.1 — every gbrain upgrade runs the migration automatically (schema → smoke → prefs → host rewrites → env-aware autopilot install). If you ever want to verify manually or wire a cron into your morning briefing:

gbrain doctor                    # half-migrated state? prints loud banner + exits non-zero
gbrain skillpack-check --quiet    # exit 0/1/2 for pipeline gating
gbrain skillpack-check | jq       # full JSON: {healthy, summary, actions[], doctor, migrations}

If anything's off, actions[] tells you the exact command to run. For deeper troubleshooting: docs/guides/minions-fix.md.

Moving gateway crons to Minions (deterministic scripts, zero LLM tokens per fire): docs/guides/minions-shell-jobs.md.

Durable agents: gbrain agent (v0.15)

Your subagent runs survive crashes now. OpenClaw died mid-run? The worker re-claims on restart and replays from the last committed turn. Fan-out across 50 shards, one shard crashes — the aggregator still claims after every child reaches a terminal state and writes a mixed-outcome summary. Tool calls persist as a two-phase ledger (pendingcomplete | failed) so replay is safe by construction, not by hope.

# Submit a single-subagent run
gbrain agent run "summarize my last 10 journal pages"

# Fan out N prompts across N subagent children + 1 aggregator
gbrain agent run "analyze every page" \
  --fanout-manifest manifests/pages.json \
  --subagent-def analyzer

# Tail a running job (heartbeat per turn + full transcript on completion)
gbrain agent logs 1247 --follow --since 5m

Durability is the point: every Anthropic turn commits to subagent_messages, every tool call to subagent_tool_executions. Worker kills, OpenClaw crashes, timeouts — all resumable. Host repos (your OpenClaw, etc.) ship their own subagent definitions via GBRAIN_PLUGIN_PATH + a gbrain.plugin.json manifest: see docs/guides/plugin-authors.md. Requires ANTHROPIC_API_KEY on the worker.

Skillify: say "skillify it!" and the bug becomes structurally impossible to repeat

Your OpenClaw hit a new failure. You fix it once in conversation. You say "skillify it!" And now the fix is permanent: a SKILL.md with triggers, a deterministic script with tests, a routing fixture the agent re-evaluates daily, a filing audit that keeps the output from drifting. Ten items. Every one required. The bug can't recur.

Hermes and similar agent frameworks auto-create skills as a background behavior. Fine until you don't know what the agent shipped. Checklists decay. Tests drift. Resolver entries get stale. Six months later it's an opaque pile nobody has read, nobody has tested, and nobody is sure still works. GBrain ships the same capability except the human stays in the loop and every step is a command you can run.

The four verbs you need (v0.19)

# 1. Scaffold all 5 stub files for a new skill in one shot.
gbrain skillify scaffold webhook-verify \
  --description "verify ngrok webhooks" \
  --triggers "verify the webhook,check tunnel" \
  --writes-pages --writes-to people/,companies/

# 2. Replace the SKILLIFY_STUB sentinels with real logic + real tests.
$EDITOR skills/webhook-verify/scripts/webhook-verify.mjs
$EDITOR test/webhook-verify.test.ts

# 3. Run the 10-item audit: SKILL.md exists, script exists, unit + E2E tests,
#    LLM evals, resolver entry, trigger eval, check-resolvable gate, brain filing.
gbrain skillify check skills/webhook-verify/scripts/webhook-verify.mjs

# 4. Verify the whole tree: reachability, MECE overlap, DRY, routing gaps,
#    filing audit, SKILLIFY_STUB sentinels (fails if any skill still has one).
gbrain check-resolvable              # warnings advisory, errors block
gbrain check-resolvable --strict     # warnings block too (CI opt-in)

Idempotent re-runs. --force regenerates stub files but NEVER duplicates a resolver row. Scaffold completes in under 2 seconds. The real work (your rule, your script, your tests) is what you spend time on. Everything else is boilerplate the CLI writes for you.

gbrain routing-eval — catch the routing gaps your users actually hit

Drop a routing-eval.jsonl fixture next to any skill. Each line is {intent, expected_skill, ambiguous_with?}. gbrain check-resolvable runs the structural layer by default; gbrain routing-eval runs the same structural layer as a dedicated CI verb. The --llm flag is accepted as a placeholder for a future LLM tie-break layer; in this release it emits a stderr notice and runs structural only. False positives (wrong skill matched), missed routes (no skill matched), and tautological fixtures (intent copies trigger verbatim) all surface as specific advisories with the exact file:line to fix.

Works on your OpenClaw, not just gbrain's repo

v0.19 teaches gbrain check-resolvable to accept AGENTS.md as a resolver file alongside RESOLVER.md, at either the skills directory OR one level up (OpenClaw-native workspace-root layout). The skill manifest auto-derives from walking skills/*/SKILL.md when manifest.json is missing. Set OPENCLAW_WORKSPACE=~/your-openclaw/workspace and everything just works:

export OPENCLAW_WORKSPACE=~/your-openclaw/workspace
gbrain check-resolvable --verbose
# Auto-detects: AGENTS.md at workspace root, 107 skills derived from SKILL.md walk,
# 15 unreachable errors surfaced, 108 advisory warnings for overlaps and gaps.

First run on a real OpenClaw deployment found 15 unreachable skills out of 102 — about 15% of the tree was dark. The essay's "skills the agent can never reach" footgun, now visible.

gbrain skillpack install — drop 25 curated skills into your OpenClaw

The skills gbrain ships are a curated bundle. Install them into your workspace with dependency closure (shared conventions come along), per-file diff protection (your local edits are never clobbered without --overwrite-local), a file lock that serializes concurrent installers, and an atomic managed-block update to your AGENTS.md so you can see exactly what gbrain wrote.

gbrain skillpack list                          # 25 curated skills
gbrain skillpack install brain-ops             # one skill + its shared conventions
gbrain skillpack install --all                 # the full bundle
gbrain skillpack install brain-ops --dry-run   # preview; no writes
gbrain skillpack diff brain-ops                # compare bundle vs your local copy

Re-running is safe. The managed-block markers in your AGENTS.md let skillpack install accumulate rows across separate single-skill installs instead of overwriting each other. A receipt comment inside the fence (<!-- gbrain:skillpack:manifest cumulative-slugs="..." -->) tracks what gbrain has installed across runs. install --all is the only path that prunes; per-skill install never deletes what it didn't install. If you hand-add a row inside the fence, gbrain preserves it on reinstall and emits a stderr notice telling your agent to investigate.

Skillify is the piece that makes the skills tree survive six months of compounding work. Read skills/skillify/SKILL.md for the full 10-item checklist and the anti-patterns it catches.

Storage tiering: keep bulk content out of git (v0.22.11)

When your brain crosses 100K files and bulk machine-generated content (tweets, articles, transcripts) becomes the size driver, declare which directories belong in git and which live in the database only.

# gbrain.yml at the brain repo root
storage:
  db_tracked:
    - people/
    - companies/
    - deals/
  db_only:
    - media/x/
    - media/articles/
    - meetings/transcripts/

gbrain sync auto-manages your .gitignore for db_only paths. gbrain export --restore-only --repo . repopulates missing files from the database (container restart, fresh clone, accidental rm). gbrain storage status shows the tier breakdown.

Full guide: docs/storage-tiering.md.

Getting Data In

GBrain ships integration recipes that your agent sets up for you. Each recipe tells the agent what credentials to ask for, how to validate, and what cron to register.

Recipe Requires What It Does
Public Tunnel Fixed URL for MCP + voice (ngrok Hobby $8/mo)
Credential Gateway Gmail + Calendar access
Voice-to-Brain ngrok-tunnel Phone calls to brain pages (Twilio + OpenAI Realtime)
Email-to-Brain credential-gateway Gmail to entity pages
X-to-Brain Twitter timeline + mentions + deletions
Calendar-to-Brain credential-gateway Google Calendar to searchable daily pages
Meeting Sync Circleback transcripts to brain pages with attendees

Data research recipes extract structured data from email into tracked brain pages. Built-in recipes for investor updates (MRR, ARR, runway, headcount), expense tracking, and company metrics. Create your own with gbrain research init.

Run gbrain integrations to see status.

GBrain + GStack

GStack is the engine. GBrain is the mod.

  • GStack = coding skills (ship, review, QA, investigate, office-hours, retro). 70,000+ stars, 30,000 developers per day. When your agent codes on itself, it uses GStack.
  • GBrain = everything-else skills (brain ops, signal detection, ingestion, enrichment, cron, reports, identity). When your agent remembers, thinks, and operates, it uses GBrain.
  • hosts/gbrain.ts = the bridge. Tells GStack's coding skills to check the brain before coding.

gbrain init detects if GStack is installed and reports mod status. If GStack isn't there, it tells you how to get it.

Architecture

┌──────────────────┐    ┌───────────────┐    ┌──────────────────┐
│   Brain Repo     │    │    GBrain     │    │    AI Agent      │
│   (git)          │    │  (retrieval)  │    │  (read/write)    │
│                  │    │               │    │                  │
│  markdown files  │───>│  Postgres +   │<──>│  29 skills       │
│  = source of     │    │  pgvector     │    │  define HOW to   │
│    truth         │    │               │    │  use the brain   │
│                  │<───│  hybrid       │    │                  │
│  human can       │    │  search       │    │  RESOLVER.md     │
│  always read     │    │  (vector +    │    │  routes intent   │
│  & edit          │    │   keyword +   │    │  to skill        │
│                  │    │   RRF)        │    │                  │
└──────────────────┘    └───────────────┘    └──────────────────┘

The repo is the system of record. GBrain is the retrieval layer. The agent reads and writes through both. Human always wins... edit any markdown file and gbrain sync picks up the changes.

The Knowledge Model

Every page follows the compiled truth + timeline pattern:

---
type: concept
title: Do Things That Don't Scale
tags: [startups, growth, pg-essay]
---

Paul Graham's argument that startups should do unscalable things early on.
The key insight: the unscalable effort teaches you what users actually
want, which you can't learn any other way.

---

- 2013-07-01: Published on paulgraham.com
- 2024-11-15: Referenced in batch W25 kickoff talk

Above the ---: compiled truth. Your current best understanding. Gets rewritten when new evidence changes the picture. Below: timeline. Append-only evidence trail. Never edited, only added to.

Knowledge Graph

Pages aren't just text. Every mention of a person, company, or concept becomes a typed link in a structured graph. The brain wires itself.

Write a meeting page mentioning Alice and Acme AI
  -> Auto-link extracts entity refs from content (zero LLM calls)
  -> Infers types: meeting page + person ref => `attended`
                   "CEO of X" pattern        => `works_at`
                   "invested in"             => `invested_in`
                   "advises", "advisor"      => `advises`
                   "founded", "co-founded"   => `founded`
  -> Reconciles stale links: edits remove links no longer in content
  -> Backlinks rank well-connected entities higher in search
gbrain graph-query people/alice --type attended --depth 2
# returns who Alice met with, transitively

The graph powers questions vector search can't: "who works at Acme AI?", "what has Bob invested in?", "find the connection between Alice and Carol". Backfill an existing brain in one command:

gbrain extract links --source db        # wire up the existing 29K pages
gbrain extract timeline --source db     # extract dated events from markdown timelines

Then ask graph questions or watch the search ranking improve. Benchmarked side-by-side against ripgrep-BM25, vector-only RAG (same embedder), and gbrain-with-graph-disabled: gbrain lands P@5 49.1%, R@5 97.9% on a 240-page Opus-generated rich-prose corpus, beating hybrid-nograph by +31.4 points P@5. Isolate the contribution: v0.11→v0.12 moved the same gbrain codebase from P@5 22.1% → 49.1% on identical inputs, so typed-link extract quality is load-bearing. Full scorecards + reproducible corpus: gbrain-evals.

Hybrid search: vector + keyword + RRF fusion + multi-query expansion + 4-layer dedup.

Query
  -> Intent classifier (entity? temporal? event? general?)
  -> Multi-query expansion (Claude Haiku)
  -> Vector search (HNSW cosine) + Keyword search (tsvector)
  -> RRF fusion: score = sum(1/(60 + rank))
  -> Cosine re-scoring + compiled truth boost
  -> 4-layer dedup + compiled truth guarantee
  -> Results

Keyword alone misses conceptual matches. Vector alone misses exact phrases. RRF gets both. Search quality is benchmarked and reproducible: gbrain eval --qrels queries.json measures P@k, Recall@k, MRR, and nDCG@k. A/B test config changes before deploying them.

Why it works: many strategies in concert

The brain isn't one trick. Every retrieval question goes through ~20 deterministic techniques layered together. No single one is magic; the win comes from stacking them so each layer covers what the others miss.

Question
  │
  ├─ INGESTION (every put_page)
  │    ├─ Recursive markdown chunking (or semantic / LLM-guided)
  │    ├─ Embedding cache invalidation on edit
  │    └─ Idempotent imports (content-hash dedup)
  │
  ├─ GRAPH EXTRACTION (auto-link post-hook, zero LLM)
  │    ├─ Entity-ref regex (markdown links + bare slugs)
  │    ├─ Code-fence stripping (no false-positive slugs in code blocks)
  │    ├─ Typed inference cascade (FOUNDED → INVESTED → ADVISES → WORKS_AT)
  │    ├─ Page-role priors (partner-bio language → invested_in)
  │    ├─ Within-page dedup (same target collapses to one link)
  │    ├─ Stale-link reconciliation (edits remove dropped refs)
  │    └─ Multi-type link constraint (same person can works_at AND advises)
  │
  ├─ SEARCH PIPELINE (every query)
  │    ├─ Intent classifier (entity / temporal / event / general — auto-routes)
  │    ├─ Multi-query expansion (Haiku rephrases the question 3 ways)
  │    ├─ Vector search (HNSW cosine over OpenAI embeddings)
  │    ├─ Keyword search (Postgres tsvector + websearch_to_tsquery)
  │    ├─ Source-aware ranking (curated dirs outrank chat/daily swamp at SQL layer)
  │    ├─ Hard-exclude (test/ archive/ attachments/ .raw/ filtered before retrieval)
  │    ├─ Reciprocal Rank Fusion (score = sum 1/(60+rank) across both)
  │    ├─ Cosine re-scoring (re-rank chunks against actual query embedding)
  │    ├─ Compiled-truth boost (assessments outrank timeline noise)
  │    ├─ Backlink boost (well-connected entities rank higher)
  │    └─ Source-aware dedup (one CT chunk per page guaranteed)
  │
  ├─ GRAPH TRAVERSAL (relational queries)
  │    ├─ Recursive CTE with cycle prevention (visited-array check)
  │    ├─ Type-filtered edges (--type works_at, attended, etc.)
  │    ├─ Direction control (in / out / both)
  │    └─ Depth-capped (≤10 for remote MCP; DoS prevention)
  │
  └─ AGENT WORKFLOW (graph-confident hybrid)
       ├─ Graph-query first (high-precision typed answers)
       ├─ Grep fallback when graph returns nothing
       └─ Graph hits ranked first in top-K (better P@K and R@K)

End-to-end on the BrainBench v1 corpus (240 rich-prose pages, before/after PR #188):

Metric BEFORE PR #188 AFTER PR #188 Δ
Precision@5 39.2% 44.7% +5.4 pts
Recall@5 83.1% 94.6% +11.5 pts
Correct in top-5 217 247 +30
Graph-only F1 (ablation) 57.8% (grep) 86.6% +28.8 pts

Plus 5 orthogonal capability checks (identity resolution, temporal queries, performance at 10K-page scale, robustness to malformed input, MCP operation contract). All pass. Full report: gbrain-evals.

The point: each technique handles a class of inputs the others miss. Vector search misses exact slug refs; keyword catches them. Keyword misses conceptual matches; vector catches them. RRF picks the best of both. Compiled-truth boost keeps assessments above timeline noise. Auto-link extraction wires the graph that lets backlink boost rank well-connected entities higher. Graph traversal answers questions search alone can't reach. The agent picks graph-first for precision and falls back to keyword for recall. All deterministic, all in concert, all measured.

Voice

Call a phone number. Your AI answers. It knows who's calling, pulls their full context from the brain, and responds like someone who actually knows your world. When the call ends, a brain page appears with the transcript, entity detection, and cross-references.

Voice client connected

See it in action

The voice recipe ships with GBrain: Voice-to-Brain. WebRTC works in a browser tab with zero setup. A real phone number is optional.

Engine Architecture

CLI / MCP Server
     (thin wrappers, identical operations)
              |
      BrainEngine interface (pluggable)
              |
     +--------+--------+
     |                  |
PGLiteEngine       PostgresEngine
  (default)          (Supabase)
     |                  |
~/.gbrain/           Supabase Pro ($25/mo)
brain.pglite         Postgres + pgvector
embedded PG 17.5

     gbrain migrate --to supabase|pglite
         (bidirectional migration)

PGLite: embedded Postgres, no server, zero config. When your brain outgrows local (1000+ files, multi-device), gbrain migrate --to supabase moves everything.

File Storage

Brain repos accumulate binaries. GBrain has a three-stage migration:

gbrain files mirror <dir>       # copy to cloud, local untouched
gbrain files redirect <dir>     # replace local with .redirect pointers
gbrain files clean <dir>        # remove pointers, cloud only
gbrain files restore <dir>      # download everything back (undo)

Storage backends: S3-compatible (AWS, R2, MinIO), Supabase Storage, or local.

Commands

SETUP
  gbrain init [--supabase|--url]        Create brain (PGLite default)
  gbrain migrate --to supabase|pglite   Bidirectional engine migration
  gbrain upgrade                        Self-update with feature discovery

PAGES
  gbrain get <slug>                     Read a page (fuzzy slug matching)
  gbrain put <slug> [< file.md]         Write/update (auto-versions)
  gbrain delete <slug>                  Delete a page
  gbrain list [--type T] [--tag T]      List with filters

SEARCH
  gbrain search <query>                 Keyword search (tsvector)
  gbrain query <question>              Hybrid search (vector + keyword + RRF)

IMPORT
  gbrain import <dir> [--no-embed] [--workers N]
                                        Import markdown (idempotent)
  gbrain sync [--repo <path>] [--workers N]
                                        Git-to-brain incremental sync
                                        (>100-file diffs auto-parallelize 4 workers on Postgres)
  gbrain export [--dir ./out/]          Export to markdown

FILES
  gbrain files list|upload|sync|verify  File storage operations

EMBEDDINGS
  gbrain embed [<slug>|--all|--stale]   Generate/refresh embeddings

LINKS + GRAPH
  gbrain link|unlink|backlinks          Cross-reference management
  gbrain extract links|timeline|all     Batch backfill from existing pages
                                        (--source db|fs, --type, --since, --dry-run)
  gbrain graph-query <slug>             Typed traversal (--type T --depth N
                                        --direction in|out|both)

JOBS (Minions)
  gbrain jobs submit <name> [--params JSON] [--follow]  Submit a background job
  gbrain jobs list [--status S] [--queue Q]             List jobs with filters
  gbrain jobs get|cancel|retry|delete <id>              Manage job lifecycle
  gbrain jobs prune [--older-than 30d]                  Clean completed/dead jobs
  gbrain jobs stats                                     Job health dashboard
  gbrain jobs smoke                                     One-command health check
  gbrain jobs work [--queue Q] [--concurrency N]        Start worker daemon

SKILLS (v0.19)
  gbrain skillify scaffold <name>       Create 5 stub files + idempotent resolver row
  gbrain skillify check [path]          10-item audit of a skill
  gbrain skillpack list                 Print the 25 curated skills in the bundle
  gbrain skillpack install <name>       Copy one skill + its shared conventions into target
  gbrain skillpack install --all        Install the full curated bundle
  gbrain skillpack diff <name>          Per-file diff: bundle vs target workspace
  gbrain check-resolvable [--strict]    Resolver audit (reachability, MECE, DRY, routing, filing,
                                        SKILLIFY_STUB). Accepts RESOLVER.md OR AGENTS.md.
  gbrain routing-eval [--llm] [--json]  Intent→skill routing accuracy on fixtures

ADMIN
  gbrain doctor [--json] [--fast]       Health checks (resolver, skills, DB, embeddings)
  gbrain doctor --fix [--dry-run]       Auto-fix DRY violations (delegate inlined rules to conventions)
  gbrain doctor --locks                 List idle-in-tx backends (57014 diagnostic, Postgres only)
  gbrain stats                          Brain statistics
  gbrain serve                          MCP server (stdio)
  gbrain serve --http --port 8787       MCP server (HTTP, Postgres-only, bearer auth)
  gbrain auth create|list|revoke|test   Token management for the HTTP transport
  gbrain integrations                   Integration recipe dashboard
  gbrain sources list|add|remove|...    Multi-source brain management (v0.18)
  gbrain dream [--dry-run] [--phase N]  8-phase maintenance cycle (lint→backlinks→sync→synthesize
                                        →extract→patterns→embed→orphans). v0.23 added synthesize +
                                        patterns: transcripts → reflections + cross-session themes.
  gbrain dream --input <file>           Ad-hoc transcript synthesis (implies --phase synthesize)
  gbrain dream --date YYYY-MM-DD        Synthesize a single day; --from/--to for backfill ranges
  gbrain check-backlinks check|fix      Back-link enforcement
  gbrain lint [--fix]                   LLM artifact detection
  gbrain repair-jsonb [--dry-run]       Repair v0.12.0 double-encoded JSONB (Postgres)
  gbrain orphans [--json] [--count]     Find pages with zero inbound wikilinks
  gbrain transcribe <audio>             Transcribe audio (Groq Whisper)
  gbrain research init <name>           Scaffold a data-research recipe
  gbrain research list                  Show available recipes

Run gbrain --help for the full reference.

Origin Story

I was setting up my OpenClaw agent and started a markdown brain repo. One page per person, one page per company, compiled truth on top, timeline on the bottom. Within a week: 10,000+ files, 3,000+ people, 13 years of calendar data, 280+ meeting transcripts, 300+ captured ideas.

The agent runs while I sleep. The dream cycle scans every conversation, enriches missing entities, fixes broken citations, consolidates memory. I wake up and the brain is smarter than when I went to sleep.

The skills in this repo are those patterns, generalized. What took 11 days to build by hand ships as a mod you install in 30 minutes.

Docs

For agents:

For humans:

Reference:

Benchmarks:

  • gbrain-evals ... BrainBench, the sibling repo that holds the eval harness, corpus, scorecards, and 4-adapter comparisons. Depends on gbrain; not installed alongside gbrain.

Contributing

See CONTRIBUTING.md. Run bun test for unit tests. For the full local CI gate (gitleaks + unit + all 29 E2E files in Docker, the same checks GH Actions runs), use bun run ci:local ... or bun run ci:local:diff for the diff-aware subset during fast iteration.

If you're working on retrieval or any of the search/embedding/ranking surface, set GBRAIN_CONTRIBUTOR_MODE=1 in your shell rc and use gbrain eval replay to gate your changes against a snapshot of real captured queries — the dev loop is documented in docs/eval-bench.md. Capture is off by default for production users (no surprise data accumulation); the env var is the contributor opt-in.

PRs welcome for: new enrichment APIs, performance optimizations, additional engine backends, new skills following the conformance standard in skills/skill-creator/SKILL.md.

License

MIT

S
Description
No description provided
Readme MIT
160 MiB
Languages
TypeScript 97.4%
Shell 1.2%
JavaScript 0.9%
PLpgSQL 0.4%