GBrain: Why Markdown & Knowledge Graphs Beat Databases for Agent Brains
This article dissects GBrain, an open-source AI agent brain that stores knowledge as Markdown in Git, builds a zero-LLM-cost knowledge graph via regex, and achieves 49.1% P@5 retrieval precision — 31 points higher than vector search alone — through hybrid retrieval, a nightly Dream Cycle for knowledge maintenance, and a clear separation between durable world knowledge (Brain) and operational state (Memory).
1 Markdown as the Single Source of Truth
GBrain's core design decision: knowledge lives in plain Markdown files inside a user-owned Git repository (the "Brain Repo"). A downstream PostgreSQL index is derived from Git; deletions in Git become soft deletes in the database. The Markdown files remain the authoritative source.
This design yields capabilities traditional databases struggle to provide:
Memory is Diffable : Review what the agent learned like a pull request.
Version Control : Revert erroneous writes with git revert.
Human-Readable : Knowledge stored as Markdown can be read and edited directly.
User-Controlled : Data resides on the user's disk, controlled by their keys, not a third-party vendor.
GBrain defines a contract-first BrainEngine interface (~47 operations) with two storage engines implementing it:
PGLite (default): PostgreSQL 17 compiled to WebAssembly, runs in-process, zero-config, starts in ~2 seconds, suitable for personal knowledge bases up to ~50,000 pages.
PostgreSQL + pgvector : For shared, large-scale, or multi-machine deployments (e.g., on Supabase or self-hosted).
CLI and MCP Server are generated from the same interface definition, allowing storage swaps without changing upper-layer logic.
2 Zero-Cost, Self-Connecting Knowledge Graph
On every put_page write, GBrain extracts entity references from Markdown using Obsidian-style Wikilinks ( [[wiki/people/bob]]) and Typed Link syntax. The entire process uses regex and string matching — zero LLM calls .
Extracted edges have explicit types: attended, works_at, invested_in, founded, advises, mentions. They are written to a links table with columns from_page_id, to_page_id, link_type, context.
Recursive SQL traverses the graph; the CLI command gbrain graph-query exposes multi-hop query capability.
3 How Much Does the Knowledge Graph Improve Retrieval?
GBrain's own BrainBench evaluation reveals a striking result:
Retrieval Method P@5
Full GBrain system 49.1%
Without knowledge graph (vector + keyword fusion only) 17.8%
Pure vector search 10.8%Recall@5 reaches 97.9%. Removing the knowledge graph drops P@5 from 49.1% to 17.8% — a 31-percentage-point contribution. The evaluation concludes: "The knowledge graph layer contributed 31 percentage points of P@5 improvement." Counter-intuitively, the free regex-based graph outperforms the expensive vector search.
4 Why Is the Knowledge Graph So Critical?
Many real-world agent queries are relational (multi-hop) , e.g., "Which people at companies I invested in work on AI Agents?" This requires traversing: You → invested_in → Company → works_at → Person → mentions → AI Agents.
Vector similarity only measures semantic closeness; it cannot natively follow typed edges. The knowledge graph explicitly represents this structure, enabling direct answers to relational queries.
Person --works_at--> Company --invested_in--> You
Person --mentions--> AI AgentsNote: "Zero LLM calls" applies only to graph construction at write time; retrieval and answer synthesis still consume tokens.
5 Hybrid Retrieval & Answer Synthesis
5.1 gbrain search — Raw Page Retrieval
Uses Hybrid Retrieval :
Vector search: HNSW, cosine similarity, 1,536-dim embeddings from OpenAI text-embedding-3-large (original 3,072 dims reduced via Dimensions API).
PostgreSQL tsvector full-text keyword search.
pg_trgm fuzzy title matching.
Results fused via Reciprocal Rank Fusion (RRF) with formula 1 / (60 + rank), plus Source Tier Boost and a Reranker.
Query Expansion
Claude Haiku expands the query into multiple variants.
Each variant embedded and run through vector search in parallel.
Keyword search run in parallel.
RRF fusion applied.
Four-layer deduplication: by source, cosine similarity > 0.85, per-type cap at 60%, per-page max occurrences.
5.2 gbrain think — Synthesized Answer Layer
Generates a consolidated answer with explicit source citations and honestly states what the Brain does not know : outdated pages, missing citations, contradictory information, knowledge gaps.
Clear separation: search returns raw pages; think returns a synthesized answer with uncertainty disclosure.
6 Dream Cycle: Nightly Knowledge Maintenance
A purely user-driven write model leads to drift: duplicate pages, stale references, conflicts, accumulating dirty data. GBrain's solution: Dream Cycle — a Cron-driven background process that runs during idle time:
Merge duplicate person pages.
Fix broken references.
Assess information importance.
Detect contradictions.
Prepare for next day's tasks.
"Agent works by day, sleeps at night; Brain organizes itself while the agent sleeps."
Reference deployment includes 20+ periodic tasks; Garry Tan's production runs 66 Cron Jobs .
https://github.com/garrytan/gbrain/blob/master/docs/GBRAIN_SKILLPACK.md
7 Automatic Contradiction Detection
Implemented via gbrain eval suspected-contradictions:
Sample retrieval-result pairs.
Pre-filter by date.
Use a query-conditioned LLM Judge.
Surface conflicting information written at different times.
Feed findings into the daily Dream Cycle.
Thus the Brain actively maintains consistency, not just accumulation.
8 Cost Control: Move Deterministic Work Off the LLM Gateway
Since v0.14.0, deterministic Cron work (API fetch, token refresh, scrape & write) runs as Shell Jobs that bypass the LLM Gateway entirely — 0 tokens per execution . This frees ~60% of Gateway headroom. Principle: "Only work that truly requires judgment goes to expensive models."
9 Closed-Loop Operation
Signal arrives
↓
Agent queries Brain
↓
Gains full context
↓
Agent produces response
↓
Result written back to Brain
↓
Auto-build knowledge graph edges
↓
Cron sync
↓
Dream Cycle nightly cleanup
↓
Knowledge continuously updated & cleaned
↓
Next day Agent gets better contextAgent capability grows over time — not because the model improves, but because the Brain continuously accumulates, connects, cleans, and integrates knowledge during downtime.
10 Brain ≠ Memory
10.1 Brain: World Knowledge
Durable facts about the external world: people, companies, deals, meetings, concepts, ideas.
10.2 Memory: Agent Operational State
How the agent works, not what the world is: user preferences, past decisions, tool configs, session continuity, operational state.
"Persist world knowledge in Brain; persist runtime state in Agent Memory; never put information in the wrong layer."
11 Why the Separation?
Core reason: Durability . Some platforms' Agent Memory may not survive resets. GBrain's data ultimately resolves to Markdown → Git — as long as the repo exists, knowledge persists. GBrain explicitly does not aim to be a "remember preferences, maintain cross-session state" system; it is a knowledge base, not working memory.
12 Benchmark Reality Check
BrainBench uses 240 fictional pages (80 people, 80 companies, 50 meetings, 30 concepts) generated by Opus, seeded for reproducibility, with 145 relational questions. Vectorize independently reviewed the methodology: internally consistent, documented, reproducible. Confirmed: Typed-Edge KG boost > pure hybrid search.
Two key limitations:
Covers only 2 of 12 retrieval categories — not representative of full GBrain capability.
Cannot be used for direct head-to-head comparison with other systems (Mem0, Zep, Letta) because the corpus is GBrain-specific, not a shared benchmark like BEAM or LOCOMO.
The cited 146,646 pages and 66 Cron Jobs are Garry Tan's self-reported production numbers, not independently verified.
13 GBrain's Limitations
13.1 Filesystem + Git Isn't for Everyone
Pros: user ownership, diff, version control, human-editable. Cons: Cloudflare's 2026 Agent Memory argues a tighter ingestion-retrieval pipeline may beat raw filesystem access, citing cost, performance, temporal logic, and supersession.
13.2 Free KG Depends on Link Discipline
Regex graph requires proper Wikilinks and Typed Links. Unstructured text like "Bob works at Acme." without explicit links yields poor edges. Graph quality = link discipline at write time.
13.3 PGLite Is Single-Writer
PGLite uses a single-writer model; concurrent MCP Server + Cron writes risk write-lock contention. Hence scale-out moves to full PostgreSQL.
14 Where Does the Memory Layer Belong?
GBrain explicitly identifies the gap: it is a Brain, not Memory . Operational and preference state belong in a separate layer — exactly what Mem0 addresses. The two are complementary.
15 Division of Responsibilities
GBrain — Durable World Knowledge
People
Companies
Deals
Meetings
ConceptsStored as user-owned files, enhanced by relational graph.
Memory Layer — Agent Operational Knowledge
How the user likes to work
What the user has corrected
What the agent has tried
Cross-session continuity
Cross-machine runtime contextThese rarely map to a single entity page. Memory Layer enables semantic retrieval without manual links, identity-scoped isolation, sharing across Cursor/Terminal/CLI, long-running agents, and evaluation at million-to-ten-million token context scales.
Combined Agent Context Architecture
Agent
│
┌───────┴───────┐
↓ ↓
GBrain Memory Layer
│ │
World Knowledge Operational State
│ │
People/Company Preferences
Deals/Meetings Decisions
Concepts/Ideas Session State
│ │
└───────┬───────┘
↓
Agent ContextA mature Agent Harness will likely run both Brain + Memory simultaneously.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaEdge
First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
