Enforced, persistent decision memory for AI code agent teams — that survives context compaction. Agents log decisions and outcomes, learn from past rejections, and resume their pending roadmap after a /compact instead of re-researching it. Hooks make it mandatory (not "stored and hoped for"). And code reads route through SAN compression (~80% fewer tokens, tokenizer-measured) so the context window fills slower in the first place.
Persistent decision memory for AI coding agents. MCP server for Claude Code, Cursor, Cline.
Estrelas
12
Ferramentas
—
Disponibilidade
—
Portable across agent runtimes — your knowledge isn't trapped in one tool. Agent Brain is an MCP server, so Claude Code and Codex can both drive the same brain with MCP tools, standing protocol, and lifecycle hooks — switch agents for price or capability without resetting your project's accumulated decisions and SAN. Any MCP host works (Cursor, Cline, Continue, …). See docs/adapters.md; run ./setup.sh for the easiest install.
AI coding agents start fresh every session: no memory of past decisions, no learning from rejections, no cross-agent knowledge sharing — and they burn tokens re-reading the same source files task after task. Agent Brain fixes both:
Memory — decisions, outcomes, and review feedback persist across sessions and agents:
Agent → pre_check() → "WARNING: similar approach was rejected last week"
Agent → log_decision() → records what you decided and why
Agent → does work → PR created
Reviewer → log_outcome() → "rejected: violates DIP (dependency inversion)"
Next time, any agent → pre_check() → sees that rejection → avoids the mistake
Cheap code reading — the optional SAN protocol compresses source files to ~17-27% of their original tokens (81% saved, tokenizer-measured), and token_savings shows you exactly how much it saved, per session, in numbers and %.
Features
Feature
What it does
Decision Memory
Log decisions, outcomes, feedback. Persists across sessions.
Pre-Check Warnings
Before starting work, see past failures in the same area.
Fuzzy Matching
"Rate limiting on signup" finds "rate limiting on login" rejection.
Code Bridge
Link decisions to code symbols: "Show me all decisions that touched AuthService." (Richer with the optional code-review-graph MCP server; works standalone too.)
Agent Scorecards
Acceptance rate, trends, top rejection categories per agent.
Adaptive Warnings
Agents with high rejection rates get stricter pre-check warnings.
Team Dashboard
All agents at a glance — for project managers.
SAN Protocol
Compress code to ~20% of original tokens (81% saved, measured). Full codebase fits in context.
Token Savings Tracker
token_savings reports tokens saved this session / today / all-time, with %.
Enforcement Hook
Code edits are blocked until the agent logs a decision — memory actually gets populated.
Survives compaction
SessionStart hook re-injects the pending roadmap after /compact so the agent resumes instead of re-researching. Details
Relevance search
query_decisions(query="…") ranks by topic relevance, not just recency; get_roadmap returns open work in one call.
SAN as default read path
Hooks on both Read and Bash route raw code reads/dumps to get_san (per-file nudge, optional hard-block), so agents actually use SAN instead of cat/Read. A tool ladder (find→read→grep-literal→edit) is auto-installed to CLAUDE.md. Details
Records & pruning
Browse every decision as dated markdown; prune old/resolved ones (dry-run first, archived not deleted). Keeps the brain lean without losing the lessons. Details
Live decisions web view
A /decisions browser that streams decisions in real time as agents log them — filter by repo/area/agent/outcome, search, color-coded. Details
SAN search trace
A /san view that shows how a query finds code through SAN — index → content → block → src: line range, live. Details
Quick Start
Recommended:
git clone https://github.com/sandeep84397/agent-brain.git
cd agent-brain
chmod +x setup.sh
./setup.sh
./setup.sh installs Agent Brain for every supported runtime it detects on your
machine: Claude Code, Codex, or both. If you want to force one runtime:
Prompt for your repo paths (or use the template config)
Register the MCP server globally with Claude Code and/or Codex
Install the brain hooks (decision-gate, amnesia re-inject, Read/Bash→SAN routing)
Add the SAN tool-ladder to ~/.claude/CLAUDE.md for Claude Code or ~/.codex/hooks.json guidance for Codex — no manual edit needed (idempotent; safe to re-run)
Offer to customize agent names interactively
Run verification checks
No setup.sh? The server works standalone. Just pip install mcp networkx and register manually:
claude mcp add --transport stdio --scope user agent-brain -- python3 /path/to/server.py
The server gracefully handles a missing config.json — it starts with an empty brain.
Where things land:setup.sh installs a copy of the server and hooks to ~/.agent-brain/ with its own venv — that installed copy is what Claude Code and Codex run. The repo checkout keeps the source. CLI examples in this README use python3 brain/server.py <cmd> from the repo root after installing dependencies; against the installed copy, the equivalent is ~/.agent-brain/.venv/bin/python ~/.agent-brain/server.py <cmd>. If you edit the repo copy, re-run setup.sh and restart your agent runtime.
Existing users: upgrade to Claude + Codex
If you already installed Agent Brain before Codex support, update the checkout
and re-run the same command:
git pull
./setup.sh
The installer is idempotent. It preserves ~/.agent-brain/config.json,
decisions.json, decisions.journal, records, metrics, and existing Claude
agent files unless you explicitly choose to overwrite templates. It refreshes
the installed server and hooks under ~/.agent-brain/, keeps Claude Code wired,
and adds Codex config when Codex is detected.
The only manual step Codex may still require is hook trust: after setup,
restart Codex, run /hooks, and trust the Agent Brain hooks. That trust step is
intentional Codex safety behavior for non-managed command hooks.
Codex setup
When Codex is installed, ./setup.sh writes:
~/.codex/config.toml — [mcp_servers.agent-brain] using the installed brain venv
~/.codex/hooks.json — decision gate, roadmap injection, brain-before-research nudge, and SAN Read/Bash routing
After install, restart Codex. In Codex, run /mcp to confirm agent-brain is
enabled, then run /hooks and trust the Agent Brain hooks when prompted. Codex
requires explicit trust for non-managed command hooks.
This writes Claude project MCP files and appends an idempotent Agent Brain
protocol block to <project>/AGENTS.md for Codex. Restart your agent runtime in
that project so the instructions and MCP config reload.
Linking a project (so subagents can use brain)
./setup.sh registers brain at the user level. For project-local guidance and
subagent/project wiring, run:
Subagents not seeing brain tools? See the 4-layer model under Verification.
How To Use It
Once set up, you don't call brain tools yourself — your agents do, automatically, as part of their normal work. Your job is just to give agents tasks and (optionally) review the memory that builds up.
The loop every agent runs
For any non-trivial task, an agent follows this cycle (enforced by the hook — see Enforcement Hook):
1. pre_check(agent, area, action) ← "has anyone tried this before? did it fail?"
2. log_decision(agent, repo, area, ← records the plan; unlocks code edits
action, reasoning,
handoff_summary?, validation?, git metadata?)
3. … writes the code …
4. log_outcome(decision_id, outcome, ← records accepted / rejected / failed + why
outcome_by, reason)
You just say "add rate limiting to the signup endpoint". The agent does the rest.
Worked example — across two sessions
Monday — a decision gets rejected:
You: "Add rate limiting to /login"
Agent: pre_check(agent="karan", area="auth", action="rate limit login")
→ "No past failures in 'auth'. Proceed."
Agent: log_decision(... action="in-memory counter per IP", reasoning="simplest")
→ dec_20260609_..._a1b2c3
Agent: …writes code, opens PR…
PE: log_outcome(dec_..._a1b2c3, outcome="rejected", outcome_by="marcus",
reason="in-memory won't survive multi-instance deploy; use Redis")
Friday — a different agent, a related task, a different machine/session:
You: "Add rate limiting to the signup endpoint"
Agent: pre_check(agent="dev", area="auth", action="rate limit signup")
→ "SIMILAR REJECTIONS (1, 78% match):
[2026-06-09] karan tried: in-memory counter per IP
REJECTED by marcus: in-memory won't survive multi-instance deploy; use Redis"
Agent: …goes straight to a Redis-backed limiter, skips the mistake…
No human re-explained the Redis constraint. The brain carried it forward.
How it behaves
When an agent calls…
What happens
What you see
pre_check
Searches task-scoped decisions and similar failures; optional provider routing advice
Agent sees relevant context before coding
log_decision
Appends the decision and records scoped activity
Protected workflow actions can continue in that repo/session
Protected workflow action without scoped activity
PreToolUse guardrail requests a decision first
Agent logs context, then retries
log_outcome (rejected)
Records the rejection; raises that agent's rejection rate
Future pre_checks surface it; repeat offenders get stricter warnings
Any tool with a repo/status
Updates the live office dashboard
Agent appears working/reviewing/blocked at localhost:3333
What you get out of it (outcomes)
Outcome
How it helps
Mistakes aren't repeated
A rejection logged once warns every agent, every future session — even on a different machine.
No re-explaining context
Constraints ("use Redis", "don't bypass the auth middleware") live in the brain, not in your head.
Cross-agent learning
What backend-engineer learns, frontend-engineer and QA see. Knowledge is team-wide, not per-agent.
Accountability & trends
Scorecards show each agent's acceptance rate and recurring failure patterns — agent_scorecard("karan", detail=True).
Auditable history
"Why did we build it this way?" → decisions_for("AuthService.login") returns every decision that touched it, with reasoning and outcome.
Enforced discipline
The hook means the memory actually gets populated — agents can't silently skip logging and edit code anyway.
Inspecting the memory yourself
You rarely need to, but from the repo root (where you cloned agent-brain):
python3 brain/server.py stats # overall health: how many decisions/agents/repos
python3 brain/server.py office # who's working on what right now
python3 brain/server.py savings # tokens SAN saved (last session / today / all-time)
From any agent/MCP client you can also ask in plain language — "show me the team dashboard", "what decisions touched the payment service?", "what's karan's scorecard?", "how many tokens did SAN save this session?" — and the agent picks the right tool (team_dashboard, decisions_for, agent_scorecard, token_savings).
The brain is built to stay fast as the decision history grows into thousands of entries:
Concern
How it's handled
Reading the graph
decisions.json is parsed once and held in an in-memory cache keyed on file mtime+size — repeat tool calls in a session reuse it (~0.03ms vs ~140ms re-parse). The cache self-invalidates if another session writes the file.
Writing a decision
Writes are O(delta), not O(graph). decisions.json is a periodic full snapshot; decisions.journal is an append-only log of mutations. Logging an outcome on a ~4MB brain appends ~800 bytes instead of rewriting 4MB. The journal auto-compacts back into the snapshot once it passes 256KB.
SAN freshness
The freshness sweep (stat every indexed file + scan the .san/ tree) is debounced to once per 60s per repo, so bursts of get_san/query_san calls don't each pay for it.
Bounded responses
Every list/detail tool caps its output (row limits, per-field truncation) so one giant decision can't blow up a response. Stored text fields are capped at write time too.
Multi-session safety
Each Claude Code session runs its own server process sharing ~/.agent-brain/. Writes use os.replace with pid-unique temp files to avoid cross-process rename collisions.
Files in ~/.agent-brain/:decisions.json (snapshot) + decisions.journal (deltas) are the decision memory — both are needed; don't delete one without the other. office-state.json is live dashboard state (self-pruning), san_savings.jsonl is the token-savings log. All are per-machine and git-ignored.
MCP Tools (22)
Core (every agent uses these)
Tool
Purpose
pre_check
Past failures before starting work + plan pointers, escalation hints, model routing, SAN coverage (pass repo=)
log_decision
Record what you decided and why; optional plan_file, handoff summary, git metadata, validation, blockers, deferred work, and do-not-touch notes make future resume cheaper
log_outcome
Record accepted/rejected/failed after review
log_feedback
Reviewers log feedback on decisions
Query
Tool
Purpose
query_decisions
Filter by area/agent/repo/outcome and rank by free-text relevance (query="...") — finds decisions about a topic without knowing the exact area
get_decision
Full detail + feedback for one decision
get_roadmap
What's left to do — pending/revised work, ranked. Use after a fresh session or compaction
get_resume_context
Compact repo/area digest: latest handoff, open work, validation, hygiene nudges, SAN visibility, and next action
Records & pruning (keep the brain lean)
Tool
Purpose
export_records
Write a human-readable audit trail to ~/.agent-brain/records/ — one markdown file per day, browsable via INDEX.md
prune_decisions
Forget old, resolved decisions: archives to decisions.archive.jsonl (recoverable) and removes from the live graph. Dry-run by default; keeps rejections + roadmap (the learning)
resolve_stale_pending
Mark long-abandoned pending decisions as superseded so they stop polluting get_roadmap. Dry-run by default
Code Bridge
Tool
Purpose
decisions_for
Decisions touching a code symbol or file (auto-detected)
code_impact
Blast radius: code symbols + callers
Patterns
Tool
Purpose
get_patterns
Cluster recurring rejections; pass action to find similar past failures
Scorecards
Tool
Purpose
agent_scorecard
Stats for one/all agents; detail=True for trends + advice
team_dashboard
All agents at a glance (limit caps rows)
Office Dashboard
Tool
Purpose
heartbeat
Report agent status (working/idle/discussing/blocked) for live dashboard
detect_stalls
Find agents with open decisions but no activity for N minutes (default 5)
SAN (Structured Associative Notation)
Tool
Purpose
recompile_san
Refresh SAN metadata: rebuild index, clean orphans, update hashes. dry_run=True for a freshness report only. Does NOT generate content.
query_san
Find code instead of grepping raw source — keyword search over index + content, far fewer tokens
get_san
Read code instead of raw Read — same structure, ~5x fewer tokens (detail="full") / ~11x (detail="sig"). file_path may be relative or absolute (repo auto-detected); max_chars caps output
token_savings
Tokens saved by SAN this session / today / all-time — number + %
Admin (CLI only — not exposed via MCP)
Run from the repo root. These live on the CLI (not MCP) to keep the agent-facing tool surface lean:
python3 brain/server.py validate # full brain self-tests (117 checks)
python3 brain/server.py validate-san # SAN subsystem self-tests
python3 brain/server.py san-index <repo> # rebuild _index.json from .san/
python3 brain/server.py stats # overall brain health
python3 brain/server.py office [repo] # current office state (debug)
python3 brain/server.py savings # SAN token savings (last session / today / all-time)
python3 brain/server.py roadmap [repo] # open-work digest (same as get_roadmap)
python3 brain/server.py records [repo] # export the dated records dir
python3 brain/server.py prune [repo] [--before-days=N] [--apply] # forget old decisions (dry-run default)
python3 brain/server.py resolve-stale [repo] [--apply] # mark abandoned pending as superseded
Managing what the brain remembers
The brain only grows — it learns, it never forgets on its own. That's good for the valuable memory (what failed and why) but old, resolved decisions eventually add noise to pre_check and inflate get_roadmap. Two safe ways to keep it lean:
1. Browse the records. Every decision is exportable as dated, human-readable markdown:
python3 brain/server.py records # writes ~/.agent-brain/records/YYYY-MM-DD.md + INDEX.md
open ~/.agent-brain/records/INDEX.md # browse by date
Each entry shows the date, repo, area, agent, action, and outcome. The records are regenerated from the graph — deleting a day file just re-renders on the next export, so the graph stays the source of truth. To actually forget something, prune it.
2. Prune (or let the AI do it).prune_decisions is dry-run by default — it shows what would go without touching anything:
python3 brain/server.py prune --before-days=90 # preview: old, resolved decisions
python3 brain/server.py prune --before-days=90 --apply # archive + remove for real
What it does on --apply:
Archives each pruned decision to ~/.agent-brain/decisions.archive.jsonl (recoverable — nothing is hard-deleted).
Removes it from the live graph, so pre_check/get_roadmap stop surfacing it.
Keeps the learning: rejections/failures and roadmap/blocker-tagged decisions are never pruned.
Re-exports the records dir to reflect the change.
You can also just ask an agent: "prune decisions older than 3 months, dry run first" — it calls prune_decisions(before_days=90, dry_run=True), shows you the list, and only applies after you confirm.
Is unbounded growth a problem? Disk is trivial (~28 MB/year) and reads stay sub-millisecond (mtime-cached). The real cost is relevance noise — a 2-year-old rejected approach surfacing as a "similar failure". Prune resolved/old decisions periodically; keep the rejections, which are the cheapest lesson you'll ever get.
Agent Team
The repo includes 6 agent templates. Each has the Brain Protocol baked in:
Role
File
Responsibility
Pinned model
Project Manager
project-manager.md
Coordination, tracking, blockers
Haiku (cheap coordination)
Product Owner
product-owner.md
PRDs, acceptance criteria
Sonnet
Principal Engineer
principal-engineer.md
Architecture, SOLID, reviews
Opus (review is high-leverage)
Backend Engineer
backend-engineer.md
API, services, data layer
Sonnet
Frontend Engineer
frontend-engineer.md
UI, app logic, integration
Sonnet
QA Engineer
qa-engineer.md
Test plans, validation, quality gates
Sonnet
Model pins live in each template's model: frontmatter — change them to fit your budget. See Model Routing for the full strategy.
Scale by duplicating templates (e.g., backend-engineer-2.md).
Placeholders
Each template has {{ROLE_NAME}} / {{ROLE_NAME_LOWER}} placeholders:
File
Placeholders
project-manager.md
{{PM_NAME}}, {{PM_NAME_LOWER}}
product-owner.md
{{PO_NAME}}, {{PO_NAME_LOWER}}
principal-engineer.md
{{PE_NAME}}, {{PE_NAME_LOWER}}
backend-engineer.md
{{BE_NAME}}, {{BE_NAME_LOWER}}
frontend-engineer.md
{{FE_NAME}}, {{FE_NAME_LOWER}}
qa-engineer.md
{{QA_NAME}}, {{QA_NAME_LOWER}}
setup.sh offers to replace these interactively. Or do it manually:
sed -i 's/{{BE_NAME}}/Arjun/g; s/{{BE_NAME_LOWER}}/arjun/g' ~/.claude/agents/backend-engineer.md
Already have custom agents?
If you already have agent .md files, don't overwrite them. Instead, add the Brain Protocol block to each:
# Brain Protocol
Before starting any task:
1. Call `pre_check(agent="<name>", area="<area>", action_description="<plan>")`
2. If warnings exist, adjust approach
3. Call `log_decision(agent="<name>", repo="<repo>", area="<area>", action="<plan>", reasoning="<why>", files_touched=["<paths>"])`
After feedback:
4. Call `log_outcome(decision_id="<id>", outcome="<result>", outcome_by="<who>", reason="<why>")`
NON-NEGOTIABLE.
Critical: do NOT set the frontmatter tools: field. Claude Code subagents inherit ALL tools from the parent session — including every mcp__agent-brain__* tool — only when tools: is omitted. Setting it (even with ToolSearch included) turns it into a literal allowlist that silently strips MCP tools, because mcp__* is not a valid wildcard. Reference: Claude Code subagents — Available tools.
---
name: my-agent
description: ...
model: claude-sonnet-4-6
# No `tools:` — inherits everything from the parent session, including MCP.
# To restrict tools, use `disallowedTools:` instead.
---
What if I really must restrict tools? Add ToolSearch to your tools: allowlist
and bootstrap brain tools at the top of every task with
ToolSearch(query="agent-brain", max_results=25). This is a fallback for the rare
case where you genuinely need a tool denylist; for normal use, omit tools: entirely.
setup.sh shows this snippet if it detects existing agents (choose [m] for manual).
Model Routing (quality per cost)
Routing is advice, never model execution. Choose a route from task risk and the host's configured capabilities; the server does not spawn, switch, or fall back between providers.
OpenAI defaults keep bounded exploration on Luna, planning and implementation on Terra/medium, consequential review on Sol/high, and the hardest architecture work on Astra/high. Configure a provider explicitly:
pre_check(provider="openai"|"claude") reports compact routing advice. Claude receives only configured entries; legacy flat maps are labeled LEGACY/UNVERIFIED. A recommendation does not prove a model can run on the current host.
Escalation is narrow: two recent, unresolved reasoning failures by the same agent in the same repo and area, since its latest accepted decision. Environment and information failures require diagnosis; old unclassified failures do not mandate a stronger model. There is no percentage allocation, fixed escalation ladder, or cross-provider fallback.
Plan files as handoff artifacts
Pay for deep thinking once, reuse it across many cheap executions. The planner writes the plan to a file and logs it:
PLAN AVAILABLE: docs/plans/payments-plan.md (by marcus, 2026-06-12).
Read it before re-deriving the approach — execute against it, don't re-plan.
The pointer stays active while the decision is pending or accepted; a rejected plan stops being advertised.
Brain Protocol
Every agent reuses relevant context before starting a new approach:
1. After a fresh session or resume, call get_roadmap(repo). Before a new approach,
call pre_check(agent, area, action_description, repo).
→ See scoped failures and plan pointers. Adjust approach if warnings.
2. log_decision(agent, repo, area, action, reasoning)
→ Record your plan before implementing.
3. [do the work]
4. log_outcome(decision_id, outcome, outcome_by, reason)
→ Record what happened after review.
This is enforced in every agent's .md file as NON-NEGOTIABLE.
log_outcome can also accept optional caller-reported execution metadata:
source, model, effort, input_tokens, output_tokens, reasoning_tokens,
retries, and elapsed_seconds. Missing values remain unknown; this records a
caller report and does not claim server-side model telemetry.
The hooks (6)
setup.sh installs six hooks idempotently. They are workflow guardrails, not shell-edit security controls.
Requires a scoped decision before protected workflow actions
inject_brain_context.py
SessionStart startup/resume/compact
Re-injects the open-work digest after compaction — the amnesia fix
remind_brain_before_research.py
PreToolUse Workflow|Agent|Task|spawn_agent
Nudges a brain check before fan-out research
route_read_to_san.py
PreToolUse Read
Routes raw Read of SAN-covered code → get_san (per-file, escalating)
route_bash_to_san.py
PreToolUse Bash / Codex exec_command
Routes raw source dumps to SAN while leaving discovery searches alone
record_brain_activity.py
PostToolUse
Records canonical repo + host-session activity for the other hooks
All fail-open (any error → allow, never break a session) and respect BRAIN_SKIP_ENFORCE=1.
Enforcement Hook
The enforcement hook is a workflow guardrail. It checks canonical repository +
host-session activity before protected aliases (apply_patch, Workflow,
Agent, Task, spawn_agent); parent and subagent work shares that scope.
It does not secure shell edits or replace code review.
Fail-open: If scoped activity cannot be read or a hook errors, it allows the action (exit 0).
Bypass: Set BRAIN_SKIP_ENFORCE=1 before launching the host to skip guardrails:
{ "env": { "BRAIN_SKIP_ENFORCE": "1" } }
Parent and subagent activity shares the same host-session scope.
Surviving compaction (the amnesia fix)
A long session eventually hits /compact, and the summarizer can drop the pending work and roadmap you discussed earlier — the agent then re-researches things the brain already knows. Two hooks close that gap by pushing the brain's open-work digest back into context at the exact moments memory is born or lost:
Hook
Event
What it does
inject_brain_context.py
SessionStart (startup/resume/compact)
Injects current-repo open work via additionalContext.
Soft, non-blocking nudge to check relevant context before fan-out work.
This is the same digest get_roadmap returns, so push and pull never diverge. Startup is bounded to the current repo (top 5); compact/resume context is bounded to 8. Terminal decisions are excluded from open work, and stale pending entries are surfaced for verification rather than treated as proven unfinished.
Tagging durable work: put roadmap or blocker in a decision's area (e.g. area="kmp-foundation/roadmap") and it floats to the top of the digest above transient pending edits. Untagged pending decisions still appear, newest first — so the fix works on an existing brain with no migration.
Optional hard research gate: the reminder is soft by default. To block fan-out work until a brain read happened in the canonical repository + host session, set "research_gate": "hard" in ~/.agent-brain/config.json. pre_check, query_decisions, or get_roadmap satisfies that scoped activity record. Parent and subagent activity shares the host session; BRAIN_SKIP_ENFORCE=1 bypasses it.
Install (setup.sh wires every brain hook idempotently, backing up settings.json.bak):
SAN is far cheaper for reading code (see Is SAN worth it?) — but agents kept defaulting to raw reads because nothing routed them to SAN, and a tool ladder isn't obvious. These changes close the gap (none touch the SAN format or quality):
The tool ladder (the standing rule agents are taught + nudged toward):
Step
Goal
Use
Not
Find
which file/symbol has X
query_san / semantic_search_nodes
grep -r raw source
Read/understand
what a file/class does
get_san(file_path="<abs>") (sig/full)
cat/head/sed the file
Exact literal
a precise string/line
grep/rg on the file
get_san (SAN drops literals)
Edit
change exact bytes
raw Read then Edit
—
How it's enforced:
Mechanism
What it does
get_san accepts absolute paths
Pass the exact path you got from a discovery hit — repo auto-detected, no repo-name lookup. Removes the friction tax.
route_read_to_san.py (PreToolUse Read)
Raw Read of a fresh-.san code file → nudge toward get_san. Per-file dedupe (every file's first read is nudged, not just the session's first). Escalates: 1st read soft-allow; a 2nd+ raw read of the same file gets a stronger nudge, or a block under hard mode.
route_bash_to_san.py (PreToolUse Bash)
Closes the shell bypass: cat/head/sed/taildumping a fresh-.san source file → same nudge/escalation. Leaves grep/rg/awk (literal search) and discovery-grep-across-files alone — those are the right tools, not bypasses.
pre_check(repo=...) surfaces coverage
Appends SAN AVAILABLE: repo 'X' has N files compiled… so the read path is in view at check-before-work time.
Standing directive, auto-installed
setup.sh writes the tool-ladder block into ~/.claude/CLAUDE.md (idempotent, marked block) and the SessionStart digest re-injects it — so agents get the habit by default, no manual edit.
Soft vs. hard — set read_enforcement in config.json:
"soft" (default): all of the above nudge, never block. Raw reads always proceed.
"hard": a 2nd+ raw read/dump of the same fresh-.san file is blocked (exit 2) with an actionable message — forcing real SAN use (real, not-ignorable savings). First reads are never blocked; escape any block with BRAIN_SKIP_READ_BLOCK=1 when you genuinely need raw bytes.
When raw reads stay correct (every mechanism stays silent for these): files you're about to edit, non-code files, files with no/stale .san, anything outside a configured repo, literal grep on a file, and discovery grep across files. SAN is for understanding; raw read is for editing; grep is for exact literals.
SAN Protocol
Structured Associative Notation compresses code to ~17-27% of its original tokens (81% saved blended, tokenizer-measured) while preserving all facts. See san/README.md for the full spec.
Agents never load the whole compressed repo — they climb four levels, paying more only when needed:
Level
What
Avg cost/file
When
1. Catalog
_index.json — every file + its blocks
~0 (one lookup)
"Where does X live?"
2. Signatures
get_san(detail="sig") — public API surface only
~110 tokens
"What exists here?"
3. SAN brief
get_san — full compressed facts
~220 tokens
"How does this work?"
4. Raw source
Read the real lines via src: anchors
~1,170 tokens
"I'm about to edit this"
The signatures tier is also the most staleness-resistant: public surfaces churn far slower than function bodies.
Is SAN worth it? (measured numbers)
Measured with real tokenizers (tiktoken o200k_base and cl100k_base — both agree within 0.1%) across 3 production repos: 954 source/SAN file pairs, Kotlin/Java/TS/JS, ~1.12M source tokens. Compression varies by code style — boilerplate-heavy Android code compresses to ~17%, dense backend logic to ~27%; 18.9% blended (81% saved):
Scenario
Raw source
Via SAN
Saved
Agent reads 1 file (avg)
~1,170 tokens
~220 tokens
~950 (81%)
One task (agent explores ~10 files)
~11,700 tokens
~2,200 tokens
~9.5k per task
Whole codebase in context (954 files)
~1.12M tokens — doesn't fit
~211k tokens — fits in one window
~905k (81%)
Repo (style)
Files
Raw tokens
SAN tokens
Ratio
Android app (Kotlin, boilerplate-heavy)
651
853k
142k
16.6%
Backend (Kotlin, dense logic)
299
247k
67k
27.0%
Web (TS/JS)
4
15k
2.4k
15.7%
Do SAN's unicode operators (→ ⇒ ×) waste tokens? Not on modern tokenizers — measured: → = 1 token on both, and a typical SAN line costs exactly the same in unicode and ASCII form (19 vs 19 tokens). One caveat: standalone ⇒ is 1 token on o200k but 3 on the older cl100k — if you target older models, prefer the ASCII equivalents (->, =>, xN), which the spec allows everywhere.
Savings recur on every read by every agent; generation cost is one-time per file (plus regeneration when the file changes):
Cost side
Amount
Generate 1 file (Sonnet)
~1 read of the source (~1,170 input tokens) + ~220 output tokens
Break-even (token count)
After ~1-2 reads of that file via get_san instead of raw
Break-even (dollars)
~2-3 reads if reader = generator price (output tokens cost ~5× input); faster when generation runs on cheap Sonnet and reads are saved on expensive models
Use SAN when:
Agents repeatedly explore the same codebase (every task re-reads files)
The repo is too big to fit in context raw — SAN makes whole-repo reasoning possible
Multiple agents work the same repo (generation cost amortizes across the team)
Skip SAN when:
The repo is small enough to fit in context anyway (< ~50 files)
Files churn rapidly — stale SANs need regeneration, eroding the one-time-cost advantage
Numbers above are tokenizer-measured (tiktoken). The live token_savings tracker uses tiktoken too when it's installed in the brain venv (pip install tiktoken) — exact counts, same methodology as the table. Without tiktoken it falls back to a ~4 chars/token estimate (measured ~1.4 points optimistic: 17.5% vs 18.9% ratio). Measure your own repos:
pip install tiktoken
python3 -c "
import tiktoken; from pathlib import Path
enc = tiktoken.get_encoding('o200k_base')
raw = sum(len(enc.encode(f.read_text(errors='replace'))) for f in Path('.').rglob('*.kt'))
san = sum(len(enc.encode(f.read_text(errors='replace'))) for f in Path('.san').rglob('*.san'))
print(f'raw={raw:,} san={san:,} ratio={san/raw:.1%}')"
Measuring your savings (token_savings)
You don't have to estimate — the brain measures it live. Every get_san call records what the raw source read would have cost vs the SAN tokens actually served. Ask any agent:
"how many tokens did SAN save this session?" → agent calls token_savings()
=== SAN TOKEN SAVINGS ===
This session:
SAN reads: 14
Raw source cost avoided: 16,380 tokens
SAN tokens served: 3,080 tokens
SAVED: 13,300 tokens (81%)
Today (2026-06-11): ...
All time: ...
Or from the shell (reports the last recorded session instead of a live one):
python3 brain/server.py savings
How it counts — a partial proxy, not a savings guarantee:
Only get_san reads count (a read that replaced opening the raw file)
query_san searches and decision-memory benefits are not included
Reads where SAN wouldn't have saved anything are skipped
Events persist in ~/.agent-brain/san_savings.jsonl; raw reads the host actually made are not observable.
Use it to decide whether SAN is paying off: if "All time" savings stay near zero after a week, your agents aren't reading via SAN — check coverage with recompile_san(dry_run=True).
SAN Setup
SAN (Structured Associative Notation) compresses source code to ~17-27% of its original tokens for LLM context. This is optional — the decision memory works without it.
Supported languages: the brain-compiler is language-agnostic, and the server's housekeeping (freshness, indexing, orphan cleanup) recognizes these extensions: .kt .java .py .ts .tsx .js .jsx .swift .go .rs .rb .c .cpp .h .cs .php .scala .m .mm. Files in other languages can still be compiled by hand, but won't be tracked by the freshness sweep until their extension is added to SOURCE_EXTS in brain/server.py.
Create .san/ in your repo:
mkdir -p your-repo/.san
Install the managed compiler adapter for your host (once):
./setup.sh --claude # or --codex, or --all
This installs a managed brain-compiler agent/skill rendered from the
provider-neutral contract san/compiler-contract.md, pinned to the
configured model (see docs/adapters.md).
Generate SAN files by invoking that adapter on your host:
# e.g. "Convert src/services/AuthService.kt to SAN"
The adapter reads the source, then calls the server's publish_san tool,
which validates the content and atomically writes
your-repo/.san/src/services/AuthService.kt.san (the source path with
.san appended — mirrors the source tree). The server itself never invokes
a model.
Build the index:
python3 brain/server.py san-index my-backend # admin CLI; recompile_san also rebuilds it
Query SAN:
query_san("my-backend", "Auth") # search by keyword
get_san("my-backend", "src/services/AuthService.kt") # get specific file
plan_san_refresh("my-backend") # read-only: what needs (re)generation
recompile_san("my-backend", dry_run=True) # human-readable freshness report
SAN Commands
Command
What it does
plan_san_refresh("repo")
Read-only structured plan: source digests + which SANs are missing/stale/fresh/orphaned/unsupported/malformed. Zero filesystem or metrics mutation.
The host adapter's write path: validate + atomically publish one SAN, bound to the source digest. Rejects config drift, traversal, stale digests, invalid content; rolls back on any failure.
recompile_san("repo", dry_run=True)
Human-readable freshness report (read-only; delegates to plan_san_refresh)
recompile_san("repo")
Refresh metadata: rebuild index, clean orphans, update hashes. Does NOT generate SAN content.
query_san("repo", "keyword")
Search SAN index + file contents by keyword
get_san("repo", "src/path/File.kt")
Get SAN content for a source file. file_path may be relative or absolute (repo auto-detected); detail="sig" for the API surface only
python3 brain/server.py san-index <repo>
(CLI) Rebuild _index.json from all .san files
python3 brain/server.py validate-san
(CLI) 24 self-tests: hashing, orphan cleanup, staleness, index building. Isolated temp dir.
How SAN Generation Works
SAN content is generated by the host (an LLM — Claude Code or Codex), never by the agent-brain server. The server plans, validates, and publishes; it never invokes a model or a provider CLI. The division:
plan_san_refresh("repo") reports missing/stale files with their source SHA-256.
The active host's brain-compiler adapter generates SAN for each and calls publish_san(...) with the source digest.
publish_san validates the candidate structurally, verifies the source hasn't changed (digest compare-and-swap), then atomically replaces the SAN and updates the hash + index. On any failure it rolls back all prior state.
query_san / get_san read the published SAN; plan_san_refresh re-reports what's still stale.
See docs/adapters.md for the full provider-aware flow, managed paths, config, and the no-fallback policy.
Which model runs the compiler
The compiler model is configured, not chosen at call time, and there is no automatic fallback — if the configured model is unavailable the adapter stops rather than silently downgrading. Defaults (override in config.json under san_compiler):
Provider
Default model
Reasoning effort
Claude
claude-sonnet-4-6
—
Codex
gpt-5.4-mini
medium
SAN conversion is mechanical (read source → emit facts), so a cheap tier is the right default; your engineering agents consuming SAN can run on bigger models since SAN cuts their input cost to ~20% of raw anyway. To change the compiler model, edit config.json and re-run ./setup.sh for that provider (managed adapters re-render; an unmarked hand-edited adapter is preserved and reported, never overwritten).
Other hosts
The MCP server is host-agnostic — any MCP client can call plan_san_refresh / publish_san / query_san / get_san / recompile_san. The SAN grammar itself is defined once in the provider-neutral contract san/compiler-contract.md; each host gets a managed adapter rendered from it. To wire a host that setup.sh doesn't yet manage, point it at that contract and have it call publish_san (mirror the source tree, append .san). The server's digest-based staleness tracking works identically regardless of which host wrote the file.
Content Hashing
SAN staleness detection uses sha256 content hashing to avoid false positives:
Source file hashes are stored in .san/.san_hashes.json
When checking freshness, if the source content hash matches the stored hash, the file is skipped (even if mtime changed)
This catches false positives from git checkout, git stash pop, touch, or editor save-without-change
Hashes are updated when recompile_san runs
Orphan Cleanup
When a source file is deleted, its SAN file becomes an orphan. Orphans are detected and cleaned up automatically:
Every source tracked in .san_hashes.json is checked for existence
If the source is gone, the corresponding .san file and hash entry are removed
.san files with no matching source (even if not in hash tracker) are also cleaned up
Stats report orphans_removed so you can see what was cleaned up
Important: SAN refresh is NOT automatic. Staleness checks run when you call plan_san_refresh, query_san, get_san, or recompile_san(dry_run=True) — they report stale SANs but do NOT regenerate them. To force a full metadata refresh (e.g., after a large merge or branch switch), call recompile_san("repo"). To regenerate stale SAN content, invoke your host's brain-compiler adapter on the reported files (it calls publish_san).
.san/ is local generated output. SAN files are regenerated from source by the host adapter and published transactionally, so ./setup.sh --link-project adds .san/ to your project's .gitignore (an existing anchored /.san/ is accepted). Keep them out of version control; regenerate them per checkout.
Adaptive Warnings
Agents with high rejection rates get progressively stricter warnings:
Rejection Rate
Warning Level
Behavior
< 30%
NORMAL
Standard pre_check
30-49%
ELEVATED
"Pay close attention to past failures"
≥ 50%
STRICT
Shows top rejection patterns, demands extra scrutiny
Agents with fewer than 3 logged decisions always get NORMAL — no judgment on a tiny sample.
Old rejections age out gracefully. Warnings older than ~3 months are tagged
[6mo old — verify the reason still applies] — the codebase may have moved on
since the rejection, so the agent is told to re-check the reasoning instead of
treating it as current. The reason is always shown so the agent judges applicability;
nothing is silently filtered or silently blocked.
Web Dashboard (Live Visualization)
One local server, three views — a 3D office, a decisions browser with a real-time feed, and a SAN search trace.
python dashboard/server.py
# Opens http://localhost:3333 in your browser
# / 3D office (live agent activity)
# /decisions browse + live-stream decisions as they're logged
# /san trace how a query finds data through SAN
Decisions view (/decisions)
A searchable, filterable view of every decision the brain holds — and it updates in real time as agents log decisions, with no refresh:
Live feed — a Server-Sent Events stream watches decisions.json/decisions.journal; the moment a log_decision / log_outcome lands, the new card appears (with a brief highlight pulse). A "live" indicator shows the connection.
Filter by repo, area, agent, and outcome; search across action, reasoning, and outcome reason.
Color-coded outcomes — green accepted, red rejected/failed, amber pending, purple revised, grey superseded — with at-a-glance counts (total / accepted / rejected / pending).
Roadmap markers (★) on decisions tagged roadmap/blocker, so durable work stands out.
It reads the decision graph the same way the MCP server persists it (snapshot + journal replay), as a standalone process — no extra setup, just open the page while agents work.
SAN search trace (/san)
See how the AI finds code through SAN — type a symbol or keyword and watch the same traversal get_san/query_san runs:
resolve — the repo's .san directory
index — qualified-name lookup over _index.json (N symbols → name matches)
content — scan of .san bodies for matches the name didn't catch
block — each landing point shown with its kind, file, and src: line range (where to jump in the raw source)
Pick a repo, type, and the pipeline + result tree update live. It's the read-only view of the index → file → block → source-line path that makes SAN ~5-11x cheaper than raw reads.
3D office
A 3D virtual office that shows your agents working in real-time. Agents sit at desks, gather at the meeting table, show speech bubbles during discussions, and display status pips.
Features:
Orbitable 3D office (drag to orbit, scroll to zoom)
Activity feed sidebar — messages auto-expire after 12h so stale chatter clears itself (run python brain/server.py clear-activity to wipe it now)
Team panel with live agent list
How it works:
Brain tools (pre_check, log_decision, etc.) auto-update agent status — zero changes to your agents needed
For richer state (idle, messages, discussing), agents can call heartbeat() explicitly
Dashboard reads ~/.agent-brain/office-state.json via SSE (polls every 500ms)
Auto-heartbeat (free, no agent changes):
Brain Tool
Dashboard Status
pre_check
Agent shows as "planning"
log_decision
Agent shows as "working"
log_outcome
Reviewer shows as "reviewing"
log_feedback
Reviewer shows as "reviewing", linked to target agent
Explicit heartbeat (richer state):
heartbeat(agent="arjun", status="discussing", talking_to="marcus", message="DIP violation in AuthService?")
→ Both agents walk to meeting table, speech bubbles appear, message shows in chat log.
Tip: Add heartbeat(agent="<name>", status="idle") to agent templates for when they finish a task. Otherwise agents stay at their last status until the 2-minute timeout.
Verification
After setup, run the full validation from the repo root:
Runs a standalone health check from the shell — no Claude session required.
Always verifies:
MCP tools are registered in the server
config.json is valid JSON (or absent — empty brain is OK)
~/.agent-brain/ is writable (decision marker round-trip)
decisions.json is readable if present
agent-brain is registered as an MCP server in Claude config and/or ~/.codex/config.toml
Codex hooks exist when configured (~/.codex/hooks.json)
Every ~/.claude/agents/*.md is subagent-MCP-safe: omits the tools: frontmatter field (preferred — inherits MCP) or lists ToolSearch in tools: (fallback bootstrap)
Per-repo team resolution: which agents the brain considers in-team for each configured repo
With --project=<path>, also verifies:
Claude project MCP files when present (.mcp.json, .claude/settings.local.json)
Plus the agent frontmatter rule (see Already have custom agents? below): omit the tools: field so MCP tools are inherited. Setting tools: [Read, Write, ...] makes it an allowlist that silently strips every mcp__* tool, and mcp__agent-brain__* is not a valid wildcard.
After any config change, restart Claude Code (/exit then claude) — MCP and agent definitions are loaded at session start. Then run server.py diagnose --project=<path> to confirm all four layers are wired up.
Requirements
Any MCP-compatible AI code agent (Claude Code, Cursor, Windsurf, Cline, etc.)
Python 3.10+
Optional: CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS for multi-agent orchestration
A flat team list applies to every repo — fine when one team owns everything. When you run multiple repos with different staffing, scope members per repo so heartbeats from arjun on my-backend don't pollute the my-frontend office state.
Two ways to scope:
Per-entry repos filter (simplest — extends the flat list):
When teams_per_repo[repo] is present, the flat team list is ignored for that repo.
Backwards compatible: configs without teams_per_repo and no repos field on entries behave exactly like before.
How it's used: brain tools that take a repo arg (heartbeat, log_decision, etc.) feed it through _get_team_for_repo() for role resolution and dashboard filtering. The office CLI command (python3 brain/server.py office my-backend) shows only that repo's agents.
Ainda não há lista de ferramentas. Servidores remotos recebem uma após a primeira verificação de saúde.
Perguntas frequentes
Perguntas
Como instalo Agent Brain?
Copie nesta página a configuração stdio para Cursor, Claude Desktop, Claude Code ou VS Code. Ela usa a instalação do publicador, não um proxy do PlugMCP.
Agent Brain precisa de uma chave de API?
Este registro não lista nenhuma variável de ambiente obrigatória.
Qual transporte Agent Brain usa?
Agent Brain roda localmente via stdio.
Quando Agent Brain foi verificado pela última vez?
Última verificação: 2026-10-28. Persistent decision memory for AI coding agents. MCP server for Claude Code, Cursor, Cline.