Your agent doesn't need a second brain app. It needs a folder and a map.
How I run a personal knowledge base on plain markdown that Claude Code, Codex, Gemini CLI, Cursor, Copilot and my own bot all read from the same source, plus the scripts and hooks that keep it current.
This page is also published as plain markdown at /insights/second-brain-markdown-map.md, with every table and script intact. Requesting this URL with Accept: text/markdown returns the same file, and /llms.txt indexes every article on the site. To have your agent build the setup, paste this:
Read https://anisri.dev/insights/second-brain-markdown-map.md and set up a second brain in this folder the way it describes: BRAIN.md, CORE.md, the content folders, the scripts and the hooks. Ask me before writing CORE.md.
00The short version
- A second brain for an agent is a folder of markdown files and one map file that tells the agent where things live and how to behave. No app, no database.
- The map matters most. Everything it loads costs tokens on every turn, so it routes to files instead of containing them.
- Write the map once as
BRAIN.mdand generate the tool-specific files (CLAUDE.md,AGENTS.md,GEMINI.md, your ownbot.md) from it. Hand-maintained copies drift apart. - Instructions in a markdown file are suggestions. Hooks, linters and pre-commit checks are what enforce them. Put your rules in both.
- Automate capture, filing, indexing and review. A brain you have to tend by hand is a brain you stop tending.
01Why plain files beat the app
"Second brain" sounds like something you buy. Most people who try it end up with an Obsidian vault full of plugins or a Notion workspace with seven linked databases, and then they bolt an AI on top and wonder why the answers are mush.
A coding agent's native skills are listing directories, reading files, grepping, and editing text. That's the whole interface. Every layer you put between your knowledge and those four moves is a layer the agent has to work around: proprietary link syntax, database exports, API pagination, rich-text blobs. Plain markdown on disk is the format the agent already handles best, and it gives the shortest path from question to answer.
It also gives you things apps charge for. Git is your version history and audit log. grep is your search. Any editor on any OS is your UI. And when the next agent ships next month, it reads your brain on day one, because it reads files.
The strongest case against doing this
Flat files don't win everywhere. The real counterargument: files don't do meaning, only text. If you ask "what did I decide about hosting costs" and the note says "moved off the big cloud because the bill doubled," a grep for "hosting" misses it. Vector search catches it. Graph tools catch relationships you never wrote down explicitly. And once you're past a few thousand files, an agent opening index after index burns real time and tokens.
My answer is that for a personal brain, you almost never hit that ceiling, and the fix when you do is to add a search layer on top of the same files, not to move them into a database (section 08). But if you're building team-wide knowledge for hundreds of people, start somewhere else.
- One person or a small team
- Hundreds to low thousands of notes
- You already live in a terminal or IDE agent
- You want the same knowledge in several agents
- Company-wide search across many authors
- Heavy permissions, who-can-see-what
- Mostly PDFs, images, and recordings
- Regulated data that can't sit in a git repo
02The shape of it
The common version of this layout is three content folders and a few root files. That part is right. What it leaves out is what keeps it working: generated entry files for each agent, per-folder indexes, and a place for automation. Here's the full tree I run, with what each piece is for.
@BRAIN.md. Claude Code's entry point.@BRAIN.md.My setup differs from the common one in two ways.
I call the core file CORE.md, not MEMORY.md. Claude Code's auto memory feature keeps its own notes in a file called MEMORY.md under your user folder. Different file, same name, and you will eventually confuse yourself or the agent. Name yours something nobody else uses.
The map doesn't list files. Indexes do. A map that lists every note grows with every note, and every line of it rides along on every single turn. So BRAIN.md names the folders, and a script writes an INDEX.md inside each folder from the files' own frontmatter. The agent pays for the index only when it opens that folder.
Paid on every turn
Keep it under ~200 lines combined. Rules, routing, identity. Never facts that change weekly.
Paid when a folder is relevant
One line per file, generated. This is how the agent picks the right file without opening ten.
Paid only when opened
The actual knowledge. Can be as big as you like, because it stays on disk until asked for.
Where does this fact go?
The folder layout only works if filing is boring and obvious. This is the table I use.
| You learned... | It goes in | Why there |
|---|---|---|
| How your backup job works | notes/backups.md | A topic. Name the file after the topic, not the date. |
| A client prefers written updates on Fridays | people/client-name.md | About a person or company. One card each. |
| The migration is blocked on a vendor ticket | projects/migration.md | Status that will change. Bump updated and next. |
| You picked Postgres over Mongo for the side project | DECISIONS.md | A choice with a reason. Future you will ask why. |
| The last outage happened because nobody owned the cert | LEARNINGS.md | A lesson. Repeated lessons become rules in the map. |
| You prefer short answers with sources | CORE.md | Stable, about you, needed on every turn. |
| A link you'll read later, a voice memo | inbox/ | Unprocessed. Filing it is a job for automation. |
| An API key or a patient record | nowhere | Store where the secret lives, never the secret. |
The rule underneath all of it: one subject, one file, named after the subject. tax-policy.md, not notes-march.md. Lowercase, hyphens, no spaces. When an agent searches for "tax," the file name is the cheapest hit it can get. When it's deciding whether to create a file, a predictable name is how it finds the one that already exists.
03The map, line by line
The folders are storage. The map is what turns storage into behavior. It answers four questions before the agent sees your first prompt: who is this for, where does stuff live, how do I answer, and how do I write. Here's mine, with the parts called out.
1# Brain Ani's personal knowledge base. You answer from these files, not your training data. If it is not written down here, it does not exist. 2## Always loaded @CORE.md 3## Where things live - notes/ one topic per file. Start at notes/INDEX.md - people/ one card per person. - projects/ status files. - DECISIONS.md what + why - inbox/ raw drops 4## How to answer 1. Read the folder INDEX.md, then open only what you need. 2. Cite every claim (path/file.md). 3. Nothing found: "not in the brain". 4. Files disagree: show both. 5## How to write - Search first. Append before create. - lowercase-with-hyphens.md - Frontmatter: description, updated. - Never delete. Mark superseded. - No secrets, ever.
- 1Purpose and scopeTwo sentences. The "if it's not here it doesn't exist" line is what pushes the model away from filling gaps with training data.
- 2ImportsOnly the files that must be in context on every turn. Each import is inlined at launch, so it costs the same as pasting it into the map.
- 3RoutingFolders and entry points, not file lists. The agent learns where to look, the indexes tell it what's there.
- 4Read protocolCheapest path first, citations always, an explicit way to say "I don't know," and a rule for conflicts. That last one is what most maps forget.
- 5Write protocolMost brains fail here. Without append-first and never-delete rules, an eager agent will happily create
vps-setup-2.mdand rewrite history.
The full file is short enough to paste in one go:
# Brain Ani's personal knowledge base. You answer from these files, not from your training data. If it is not written down here, it does not exist. ## Always loaded @CORE.md ## Where things live - notes/ one topic per file. Start at notes/INDEX.md - people/ one card per person or company. Start at people/INDEX.md - projects/ one file per project, with status. Start at projects/INDEX.md - DECISIONS.md what was decided and why, newest at the bottom - LEARNINGS.md lessons and post-mortems - inbox/ raw drops waiting to be filed ## How to answer 1. Read the INDEX.md of the folder that fits, then open only the files you need. 2. Cite every claim as (path/file.md). 3. If nothing covers it, say "not in the brain" and stop. Do not guess. 4. If two files disagree, show both and say which is newer. ## How to write - Append to an existing file before creating a new one. Search first. - New file names: lowercase-with-hyphens.md, named after the subject. - Every file starts with frontmatter: description, updated (YYYY-MM-DD). Projects also carry status (active, paused, done) and next. - Never delete a line. Mark it "(superseded YYYY-MM-DD)" and add the new one. - Decisions go in DECISIONS.md as "## YYYY-MM-DD title", then what, why, and what was rejected. - Never store passwords, keys, tokens, or regulated data. Store where they live instead.
You'll see advice to @-import DECISIONS.md and LEARNINGS.md into the map so they're "always in focus." Don't. Those files only grow. An import gets inlined in full at session start, so six months in you're paying for every decision you've ever made on every turn, and the useful instructions get buried under it. Import what's small and stable (CORE.md). Route to everything else.
04What happens when you ask a question
It helps to know what the harness does with these files, because it changes how you write them. Here's the path for a question like "how is the VPS backed up?" in Claude Code.
Session starts, map is already loaded
Claude Code reads CLAUDE.md from the working directory and every parent folder above it, expands its @ imports, and puts all of it in context before you type.
Hook adds today's briefing
A SessionStart hook prints active projects, recent decisions and the inbox count. Whatever it prints joins the context (section 07).
ring 1 / a few linesThe map routes it to a folder
"Backups" is a topic, so the protocol says start at notes/INDEX.md. One small read.
The index picks the file
The line vps-setup.md: How the Hetzner VPS is built, patched and backed up matches. If nothing matches, a grep across the folder is the fallback.
Read, answer, cite
The agent opens one file and answers with (notes/vps-setup.md) attached, so you can check it.
updated dates.The loading rules worth knowing
These are from Claude Code's memory docs. Other tools behave similarly but not identically, which is the whole reason for section 05.
- Ancestors load at launch, children load lazily.
CLAUDE.mdfiles in the current folder and every folder above it load at startup. Ones in subfolders only load when Claude reads files in that subfolder. That's a free way to scope rules:people/CLAUDE.mdcan hold "never store home addresses" and it only costs tokens when the agent is inpeople/. - Imports nest five hops deep and use relative, absolute or
~paths. They're ignored inside code spans and code blocks, so you can write about@something.mdwithout importing it. - There's a user level too.
~/.claude/CLAUDE.mdapplies to every project. Good place for "how I like answers," bad place for brain-specific rules. - Rules can be split. Every
.mdfile in.claude/rules/loads at the same priority as the projectCLAUDE.md. Handy for code repos. For a brain I prefer one map, because one map is easier to sync to other agents. - Keep it short. The docs recommend keeping each
CLAUDE.mdto around 200 lines. Past that, the model starts following some rules and quietly dropping others.
"Answer only from these files. If missing, say not found." is a request, not a guarantee. Models follow it most of the time and break it under pressure, usually when the question sounds like something they already know. Citations are your detector: an answer without a file path is an answer you should distrust. Anything you need enforced (naming, frontmatter, no duplicates) belongs in a hook or a linter that fails loudly, not in prose.
05One brain, every agent
Most second-brain guides stop here. They tell you to write a CLAUDE.md, and that's fine until you also use Codex at work, Gemini CLI for a side thing, and Cursor in your editor. Now you have three instruction files, and by Friday they disagree.
Every one of these tools does the same thing: look for a markdown file with a known name, read it into context. The only differences are the name they look for and whether they expand imports.
| Agent | Looks for | Expands @imports | How I point it at the brain |
|---|---|---|---|
| Claude Code | CLAUDE.md; AGENTS.md if no CLAUDE.md exists (v2.1.277+) | yes, 5 hops | Generated CLAUDE.md containing @BRAIN.md |
| Gemini CLI | GEMINI.md, or any names in context.fileName | yes | Generated GEMINI.md pointer |
| OpenAI Codex | AGENTS.md | not that I know of | Flattened AGENTS.md |
| Cursor | AGENTS.md, .cursor/rules/ | not that I know of | Flattened AGENTS.md |
| GitHub Copilot agent | AGENTS.md, .github/copilot-instructions.md | not that I know of | Flattened AGENTS.md |
| Your own bot | Whatever you tell it | whatever you build | bot.md plus a loader (section 06) |
The Claude Code row changed recently. As of v2.1.277 (September 18, 2026), Claude Code reads AGENTS.md when a project has no CLAUDE.md, and you can change that behavior under "Project instructions" in /config. If both files exist, CLAUDE.md wins. At launch the changelog said it wasn't on Bedrock, Vertex or Foundry yet, so if you run Claude Code through a cloud provider, don't count on it.
You could just commit an AGENTS.md and stop there. I don't, for two reasons. First, the flattened file can't use imports, so your CORE.md has to be pasted in. Second, the moment one tool gets a feature the others don't (Claude's lazy subfolder loading, say), you want the freedom to emit different files per tool. So I keep one source and generate the rest.
BRAIN.md+ CORE.md via importCLAUDE.mdpointerOne line, @BRAIN.md. Claude expands it.
GEMINI.mdpointerSame idea, Gemini's import syntax.
AGENTS.mdflattenedImports inlined. Codex, Cursor, Copilot.
bot.mdloaderYour persona plus @BRAIN.md, resolved by your code.
#!/usr/bin/env bash
# One source of truth (BRAIN.md), one entry file per tool.
# Run after editing BRAIN.md, or let the pre-commit hook do it.
set -euo pipefail
cd "$(dirname "$0")/.."
banner='<!-- Generated from BRAIN.md by scripts/sync_agents.sh. Edit BRAIN.md, not this file. -->'
# Claude Code and Gemini CLI resolve @imports themselves, so a pointer is enough.
printf '%s\n\n@BRAIN.md\n' "$banner" > CLAUDE.md
printf '%s\n\n@./BRAIN.md\n' "$banner" > GEMINI.md
# Codex, Cursor, Copilot and most others read AGENTS.md but do not expand
# @imports, so they get one flattened file with everything inlined.
{ echo "$banner"; echo; python3 scripts/brain_load.py BRAIN.md; } > AGENTS.md
echo "synced: CLAUDE.md GEMINI.md AGENTS.md"Why not symlinks? They're the classic trick (ln -s AGENTS.md CLAUDE.md) and they work on a Mac. They break on Windows checkouts without developer mode, some sync tools copy them as plain files, and they can't flatten imports. A short script has none of those problems.
If you only use Gemini CLI, there's a shortcut: set "context": {"fileName": ["AGENTS.md", "GEMINI.md"]} in .gemini/settings.json and it'll read the same AGENTS.md everybody else does.
06Wiring up your own bot.md
There's nothing magic about any of these file names. A harness that "supports CLAUDE.md" is doing three things: it finds a known file, expands its imports, and puts the result in the system prompt. Then it gives the model tools to read more. You can build the same thing for your own bot in about 150 lines, and once you do, the brain works in a Slack bot, a cron job, a home assistant, a WhatsApp responder, anything.
Step 1: the entry file
Your bot gets its own file for persona and tool rules, and imports the shared map. That way the bot can be terse and the coding agents can be chatty, while both use the same knowledge and protocols.
# Bot You are Ani's research assistant. You work only from the brain below. Short answers. Every claim gets a (path/file.md) citation. Tools: list_files, read_file, search, append_fact. There is no delete. When you append, say exactly what you added and where. @BRAIN.md
Step 2: a loader that resolves imports
This mirrors the Claude Code import rules: relative, absolute and ~ paths, five hops max, nothing inside code. I added cycle detection, because sooner or later two files will import each other. It's also what sync_agents.sh uses to flatten AGENTS.md, so there's exactly one implementation of "what the map says."
#!/usr/bin/env python3
"""Flatten a markdown map and its @imports into one prompt.
Follows the same rules Claude Code uses: relative, absolute or ~ paths,
at most 5 hops deep, and nothing inside code fences or `inline code`.
Only .md targets are expanded, so emails and @handles are left alone.
"""
import re
import sys
from pathlib import Path
MAX_DEPTH = 5
IMPORT = re.compile(r"(?<![\w`])@((?:~/|\.{1,2}/|/)?[\w./-]+\.md)\b")
def load(path, depth=0, seen=frozenset()):
path = Path(path).expanduser().resolve()
if path in seen:
return f"<!-- skipped {path.name}: import cycle -->"
if depth > MAX_DEPTH:
return f"<!-- skipped {path.name}: more than {MAX_DEPTH} hops -->"
seen = seen | {path}
out, in_fence = [], False
for line in path.read_text(encoding="utf-8").splitlines():
if line.lstrip().startswith(("```", "~~~")):
in_fence = not in_fence
if in_fence or "@" not in line:
out.append(line)
continue
parts = line.split("`") # odd indexes are inline code
for i in range(0, len(parts), 2):
parts[i] = IMPORT.sub(lambda m: _expand(m, path, depth, seen), parts[i])
out.append("`".join(parts))
return "\n".join(out)
def _expand(match, parent, depth, seen):
target = Path(match.group(1)).expanduser()
if not target.is_absolute():
target = parent.parent / target
if not target.exists():
return f"{match.group(0)} (missing)"
body = load(target, depth + 1, seen)
return f'\n<file path="{match.group(1)}">\n{body}\n</file>\n'
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: brain_load.py MAP.md > prompt.txt")
print(load(sys.argv[1]))Step 3: tools and a loop
Four tools are enough: list, read, search, append. Note what's missing. There's no delete and no overwrite, and every path is checked against the brain root so the model can't wander off into ~/.ssh. Your bot can only make the brain bigger, and git can undo anything it does. I'm using the Anthropic SDK here, but the shape is identical for any model with tool calling.
scripts/bot.py92 lines
#!/usr/bin/env python3
"""A small agent that runs on bot.md and nothing else.
pip install anthropic
export ANTHROPIC_API_KEY=...
python3 scripts/bot.py "what is the backup setup on the VPS?"
"""
import os
import sys
from pathlib import Path
import anthropic
sys.path.insert(0, str(Path(__file__).resolve().parent))
from brain_load import load # noqa: E402
ROOT = Path(__file__).resolve().parent.parent
MODEL = os.environ.get("BRAIN_MODEL", "claude-sonnet-5-5")
MAX_TURNS = 12
def safe(rel):
p = (ROOT / rel).resolve()
if ROOT not in p.parents and p != ROOT:
raise ValueError("path is outside the brain")
return p
def list_files(folder="."):
return "\n".join(str(p.relative_to(ROOT)) for p in sorted(safe(folder).rglob("*.md")))
def read_file(path):
return safe(path).read_text(encoding="utf-8")
def search(text):
hits = []
for p in sorted(ROOT.rglob("*.md")):
for n, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1):
if text.lower() in line.lower():
hits.append(f"{p.relative_to(ROOT)}:{n}: {line.strip()}")
return "\n".join(hits[:50]) or "no matches"
def append_fact(path, fact):
p = safe(path)
if p.suffix != ".md" or not p.exists():
return "refused: append only to an existing .md file (create files by hand or via /remember)"
with p.open("a", encoding="utf-8") as f:
f.write(f"\n- {fact.strip()}")
return f"appended to {path}"
HANDLERS = {f.__name__: f for f in (list_files, read_file, search, append_fact)}
TOOLS = [
{"name": "list_files", "description": "List .md files under a folder of the brain.",
"input_schema": {"type": "object", "properties": {"folder": {"type": "string"}}}},
{"name": "read_file", "description": "Read one file, path relative to the brain root.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
{"name": "search", "description": "Case-insensitive text search across every file.",
"input_schema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}},
{"name": "append_fact", "description": "Append one bullet to an existing file.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}, "fact": {"type": "string"}},
"required": ["path", "fact"]}},
]
def ask(question):
client = anthropic.Anthropic()
system = load(ROOT / "bot.md") # the map, with @imports inlined
messages = [{"role": "user", "content": question}]
for _ in range(MAX_TURNS):
resp = client.messages.create(model=MODEL, max_tokens=2000, system=system,
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
results = []
for block in resp.content:
if block.type == "tool_use":
try:
out = HANDLERS[block.name](**block.input)
except Exception as e: # hand the error back, let the model recover
out = f"error: {e}"
results.append({"type": "tool_result", "tool_use_id": block.id, "content": out})
messages.append({"role": "user", "content": results})
return "stopped: too many tool calls"
if __name__ == "__main__":
print(ask(" ".join(sys.argv[1:]) or "What is in the brain?"))Run it with python3 scripts/bot.py "what's blocking home-ops?". The model gets the flattened map as its system prompt, reads projects/INDEX.md, opens one file, and answers with a citation. Swap the model by setting BRAIN_MODEL.
If you'd rather expose the brain to Claude Desktop or any MCP client, those same four functions become four MCP tools with almost no changes, and the flattened map becomes a resource or a prompt. The loader doesn't change. That's the payoff of keeping the logic in plain functions over plain files.
07Automating the boring parts
Every second brain I've seen die died the same way. Capture is easy, filing is a chore, so the inbox grows, the indexes go stale, two files about the same thing appear, and one day the agent confidently quotes a project status from four months ago. More discipline won't fix that. Automation will, by taking the chores off your plate.
Capture
Drop raw stuff in inbox/, or say /remember.
File
Agent picks the right file, appends, never duplicates.
slash commandEnforce
Lint runs after every write. Failures go back to the agent.
PostToolUse hookIndex
INDEX.md and agent files regenerate on commit.
pre-commitReview
Weekly headless pass: file inbox, flag stale, merge dupes.
cron + claude -pCapture: an inbox and a /remember command
Capture has to be faster than forgetting. Two paths cover it. For anything on your phone, sync inbox/ with whatever you already use (Syncthing, iCloud Drive, Dropbox) and drop text files or voice memo transcripts in there. For anything mid-session, a slash command. In Claude Code, any markdown file in .claude/commands/ becomes a command, and $ARGUMENTS is whatever you type after it.
--- description: File a fact into the brain without creating duplicates argument-hint: the fact, in plain words allowed-tools: Read, Glob, Grep, Edit, Write --- File this into the brain: $ARGUMENTS 1. Pick the home. A topic goes in notes/, a person or company in people/, project status in projects/, a choice with a reason in DECISIONS.md, a lesson in LEARNINGS.md. 2. Grep for an existing file on the same subject. Append there if one exists. Create a new file only when nothing fits. 3. New files get a lowercase-with-hyphens name and frontmatter with description and updated. Bump updated on any file you touch. 4. Never rewrite old lines. If the new fact contradicts one, mark the old line "(superseded YYYY-MM-DD)" and add the new line under it. 5. Reply with one line: the path you touched and what you added.
Now /remember Acme wants the invoice split by cost center from November finds people/acme-corp.md, appends one line, bumps the date, and tells you where it went.
Context: a briefing on every session start
Claude Code hooks are shell commands that run on lifecycle events. For SessionStart, whatever the command prints gets added to the session's context. So instead of stuffing project status into the map, a script prints just what's live today.
scripts/brain_today.py26 lines
#!/usr/bin/env python3
"""SessionStart hook: print a short briefing. Claude Code adds
whatever this prints to the session's context."""
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_index import ROOT, frontmatter # noqa: E402
print("## Today's brain briefing")
for f in sorted((ROOT / "projects").glob("*.md")):
meta = frontmatter(f)
if meta.get("status") == "active":
print(f"- projects/{f.name}: next = {meta.get('next', 'not set')}")
log = ROOT / "DECISIONS.md"
if log.exists():
heads = [l for l in log.read_text(encoding="utf-8").splitlines() if l.startswith("## ")]
if heads:
print("\nLast decisions:")
for h in heads[-3:]:
print("-", h[3:])
inbox = [p.name for p in (ROOT / "inbox").glob("*") if p.is_file()]
if inbox:
print(f"\n{len(inbox)} item(s) waiting in inbox/. Offer to file them.")Enforcement: lint after every write
This is the hook that changed the most for me. After any Write or Edit, a script rebuilds the indexes and lints the brain. If something's wrong, it exits with code 2, and for a PostToolUse hook that sends stderr straight back to Claude. The agent sees "name must be lowercase-with-hyphens" and fixes its own file before moving on. Your naming rules stop being a polite request.
{
"hooks": {
"SessionStart": [
{
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/scripts/brain_today.py" }
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR\"/scripts/post_write_lint.py" }
]
}
]
}
}scripts/post_write_lint.py22 lines
#!/usr/bin/env python3
"""PostToolUse hook for Write|Edit. If Claude just touched a brain file,
rebuild the indexes and lint. Exit code 2 sends stderr back to Claude
so it fixes its own mess before moving on."""
import json
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
event = json.load(sys.stdin)
target = Path(event.get("tool_input", {}).get("file_path", ""))
if target.suffix != ".md" or ROOT not in target.resolve().parents:
sys.exit(0)
here = Path(__file__).resolve().parent
subprocess.run([sys.executable, str(here / "build_index.py")], check=False)
lint = subprocess.run([sys.executable, str(here / "brain_lint.py")], capture_output=True, text=True)
if lint.returncode != 0:
print("Brain lint failed after your edit. Fix these:\n" + lint.stderr, file=sys.stderr)
sys.exit(2)The linter checks the problems that degrade a brain over time: bad file names, missing descriptions (which break the index), likely duplicates by name similarity, active projects nobody touched in 30 days, a map over its line budget, and imports pointing at files that no longer exist.
scripts/brain_lint.py66 lines
#!/usr/bin/env python3
"""Keep the brain honest. Errors exit 1, warnings only print."""
import difflib
import re
import sys
from datetime import date, timedelta
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from build_index import FOLDERS, ROOT, frontmatter # noqa: E402
from brain_load import IMPORT # noqa: E402
NAME = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*\.md$")
MAP_LINE_BUDGET = 200
STALE_AFTER = timedelta(days=30)
def lint():
errors, warnings = [], []
for folder in FOLDERS:
files = [f for f in sorted((ROOT / folder).glob("*.md")) if f.name != "INDEX.md"]
stems = [f.stem for f in files]
for f in files:
rel = f.relative_to(ROOT)
meta = frontmatter(f)
if not NAME.match(f.name):
errors.append(f"{rel}: name must be lowercase-with-hyphens.md")
if "description" not in meta:
errors.append(f"{rel}: missing 'description' in frontmatter")
twins = difflib.get_close_matches(f.stem, [s for s in stems if s != f.stem], n=1, cutoff=0.88)
if twins and f.stem < twins[0]:
warnings.append(f"{rel}: looks like a duplicate of {folder}/{twins[0]}.md")
if folder == "projects" and meta.get("status") == "active":
try:
if date.today() - date.fromisoformat(meta.get("updated", "")) > STALE_AFTER:
warnings.append(f"{rel}: active but not updated in 30+ days")
except ValueError:
errors.append(f"{rel}: active project needs 'updated: YYYY-MM-DD'")
brain = ROOT / "BRAIN.md"
if brain.exists():
lines = brain.read_text(encoding="utf-8").splitlines()
if len(lines) > MAP_LINE_BUDGET:
warnings.append(f"BRAIN.md is {len(lines)} lines; budget is {MAP_LINE_BUDGET}")
in_fence = False
for n, line in enumerate(lines, 1):
if line.lstrip().startswith(("```", "~~~")):
in_fence = not in_fence
if in_fence:
continue
for part in line.split("`")[::2]:
for m in IMPORT.finditer(part):
if not (ROOT / m.group(1)).expanduser().exists():
errors.append(f"BRAIN.md:{n}: broken import @{m.group(1)}")
else:
errors.append("BRAIN.md is missing")
return errors, warnings
if __name__ == "__main__":
errors, warnings = lint()
for w in warnings:
print("warn ", w)
for e in errors:
print("error", e, file=sys.stderr)
sys.exit(1 if errors else 0)Indexing: generated, never hand-written
Each folder's INDEX.md is built from the frontmatter of the files in it. You never edit an index, so it can never drift from reality. The --check flag lets CI fail if someone forgot to rebuild.
scripts/build_index.py47 lines
#!/usr/bin/env python3
"""Rebuild notes/INDEX.md, people/INDEX.md and projects/INDEX.md
from each file's frontmatter. --check exits 1 if any index is stale."""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
FOLDERS = ["notes", "people", "projects"]
def frontmatter(path):
text = path.read_text(encoding="utf-8")
if not text.startswith("---\n"):
return {}
head = text[4:].split("\n---", 1)[0]
pairs = (line.split(":", 1) for line in head.splitlines() if ":" in line)
return {k.strip(): v.strip() for k, v in pairs}
def render(folder):
rows = []
for f in sorted((ROOT / folder).glob("*.md")):
if f.name == "INDEX.md":
continue
meta = frontmatter(f)
desc = meta.get("description", "(no description)")
extra = f" [{meta['status']}]" if "status" in meta else ""
rows.append(f"- {f.name}{extra}: {desc}")
head = f"# {folder}/ index\n\nGenerated by scripts/build_index.py. Do not edit by hand.\n\n"
return head + ("\n".join(rows) or "- (empty)") + "\n"
def main(check=False):
stale = []
for folder in FOLDERS:
(ROOT / folder).mkdir(exist_ok=True)
idx, new = ROOT / folder / "INDEX.md", render(folder)
if not idx.exists() or idx.read_text(encoding="utf-8") != new:
stale.append(str(idx.relative_to(ROOT)))
if not check:
idx.write_text(new, encoding="utf-8")
if check and stale:
sys.exit("stale index: " + ", ".join(stale) + " (run scripts/build_index.py)")
if __name__ == "__main__":
main(check="--check" in sys.argv)Then a git pre-commit hook ties the last three together, so nothing reaches history without fresh indexes, synced agent files, and a clean lint. This also covers edits you make by hand in your editor, which the Claude hook never sees.
#!/bin/sh # cp scripts/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit set -e python3 scripts/build_index.py bash scripts/sync_agents.sh >/dev/null python3 scripts/brain_lint.py git add notes/INDEX.md people/INDEX.md projects/INDEX.md CLAUDE.md GEMINI.md AGENTS.md
Review: a weekly headless pass
claude -p runs Claude Code non-interactively with a prompt and exits, and --allowedTools limits what it can touch. Once a week, a cron job runs a review on a fresh git branch, so what you get Monday morning is a diff you can read and merge, not a brain that changed behind your back.
Weekly review of this brain. Follow BRAIN.md. Do not invent facts. 1. File everything in inbox/ into the right place, then move the raw file to inbox/filed/. 2. For each project marked active with updated older than 30 days, set status to paused and add a line saying why it looks stalled. 3. Find files that cover the same subject. Merge the smaller into the larger, and leave a one-line pointer in the smaller. 4. Read LEARNINGS.md. If a lesson keeps repeating, propose a rule for BRAIN.md at the bottom of LEARNINGS.md under "## proposed rules". Do not edit BRAIN.md yourself. 5. Finish with a summary of every file you changed.
scripts/weekly_review.sh15 lines
#!/usr/bin/env bash # Headless weekly review. Works on a branch so you review a diff, not a surprise. set -euo pipefail cd "$(dirname "$0")/.." branch="review/$(date +%F)" git switch -c "$branch" claude -p "$(cat prompts/weekly-review.md)" \ --allowedTools "Read,Glob,Grep,Edit,Write,Bash(python3 scripts/build_index.py),Bash(python3 scripts/brain_lint.py)" python3 scripts/build_index.py python3 scripts/brain_lint.py git add -A && git commit -qm "weekly review $(date +%F)" || echo "nothing to commit" git switch - echo "review ready on $branch: git diff main...$branch"
# every Monday 07:00, review on a branch 0 7 * * 1 cd "$HOME/second-brain" && ./scripts/weekly_review.sh >> inbox/.review.log 2>&1
Note step 4 of the prompt: the review proposes rules but isn't allowed to edit BRAIN.md. The map is the one file where every change should go through a human. An agent that can rewrite its own instructions will, eventually, write itself a looser set.
Starter kit: brainjar. Everything above as a ready repo: map, sample notes, scripts, hooks, slash command, review prompt. Clone it or grab the zip from GitHub.
github.com/anipublik/brainjar08How this rots, and what fixes it
| Symptom | Cause | Fix |
|---|---|---|
| Answers ignore half your rules | Map grew past a few hundred lines, or imports dragged logs in | Line budget in the linter. Route, don't import. |
| Two files about the same thing | Agent created before it searched | "Search first" in the map, similarity check in the linter, merge in weekly review |
| Confidently wrong project status | Status files nobody updates | updated in frontmatter, stale warning at 30 days, auto-pause in review |
| Claude and Codex behave differently | Hand-maintained CLAUDE.md and AGENTS.md drifted | One source, generated adapters, regenerated on commit |
notes.md with 900 lines | Junk-drawer file | Split by subject. The linter's "missing description" check makes junk drawers awkward to keep. |
| History quietly rewritten | Agent "cleaned up" old lines | Never-delete rule, append-only tool in your bot, git diff on every review |
| A key or a client's private data in the repo | Pasted during capture | Run a secret scanner (gitleaks or similar) in pre-commit. Keep regulated data out entirely. |
09When to outgrow it
You'll know it's time when the agent spends more tool calls finding a file than reading it. My rough thresholds are judgment calls from my own setup, not benchmarks:
- Up to a few hundred files: map plus indexes, exactly as above. Nothing else needed.
- Low thousands: add
ripgrepand tell the map to search before reading indexes. Split big folders into subfolders, each with its own index. - Past that, or lots of "I said it differently" misses: add a search layer over the same files. SQLite FTS5 gets you fast keyword search in one file with no server. Embeddings get you meaning-based search. Expose either one as a
searchtool. The markdown stays the source of truth, the index is disposable and rebuildable.
The one move I'd never make is migrating the files into the search system. The day you do, you're back to an app, and the next agent can't read your brain on day one.
10How sure I am
| Claim | Confidence | Why |
|---|---|---|
| Claude Code loads CLAUDE.md from the working folder and its parents at launch, subfolders lazily, imports up to 5 hops | High | Stated in Anthropic's memory docs. |
| Claude Code reads AGENTS.md only when there's no CLAUDE.md, since v2.1.277 | High | Changelog and the team's own announcement, September 18, 2026. |
| SessionStart output is added to context; PostToolUse exit 2 feeds stderr back to Claude | High | Documented hook behavior. Tested the scripts' exit codes locally. |
Gemini CLI reads custom file names via context.fileName and supports @imports | High | Gemini CLI docs. |
| Codex, Cursor and Copilot don't expand @imports in AGENTS.md | Moderate | I haven't seen it documented for any of them. Flattening is safe either way. |
| Rule-following drops as the map grows past ~200 lines | Moderate | Matches the docs' guidance and my experience. I haven't measured the curve. |
| The file-count thresholds in section 09 | Low | Judgment from one setup. Your notes, model and question mix will move them. |
11Common questions
Does the map have to be called CLAUDE.md?
For Claude Code to pick it up automatically, the entry file has to be CLAUDE.md (or AGENTS.md if there's no CLAUDE.md, on recent versions). But the entry can be a one-line pointer to a map with any name. That's why mine is BRAIN.md: it's the one name no tool claims, so no tool ever overwrites it.
Can I keep using Obsidian?
Yes. An Obsidian vault is a folder of markdown files, so point the agent at it. Two things to watch: wiki-style [[links]] are fine for you but mean nothing to most agents, so put real paths in the map, and keep plugin-generated junk folders out of the agent's way.
Do I need to migrate my old notes first?
No, and please don't try. Build the skeleton, then dump old notes into inbox/ a batch at a time and let the weekly review file them. You'll find half of them weren't worth keeping, which is useful information too.
Should the agent write to the brain at all, or just read?
Write, with guardrails. A read-only brain goes stale because you're the only one updating it. The guardrails are the append-only rule, the lint hook, git, and a human review of anything structural. The map itself stays human-only.
Why frontmatter instead of just headers?
Because scripts need something to read. description feeds the index, updated feeds staleness checks, status and next feed the daily briefing. Headers are for humans. Frontmatter is for the machinery.
Where do work notes go?
In a separate brain, in a repo your employer controls, under their rules. Personal and work knowledge in one git repo is a data-handling problem waiting to happen, and in regulated industries it's a hard no.
Is this the same as Claude's built-in memory?
No. Built-in memory is notes the tool keeps about you, in a place it chooses, in a format it chooses. This is notes you keep, in a repo you own, readable by any agent. They coexist fine. Just don't let both claim a file called MEMORY.md.
A second brain for an agent is a folder, a map and a few scripts. The folder is easy. The map is where you spend your thinking: small, routing instead of containing, with real rules for reading and writing. The scripts keep it current after the novelty wears off. Write the map once, generate it for every agent, and make the machine do the filing.