Second brain The second brain
The second brain
A memory for coding agents: a vault of Markdown notes with typed metadata, which agents read before they start and add to when something has been proved, through an MCP server or a command line, whatever model runs them.
My work
- 442 notes on the morning of 26 November 2026, across 10 projects, in use since April 2026
- 305 / 32 episodes: what worked and what failed
How it is built
This layout is real: it is how the system works today. The names of the projects and the contents of the notes are private and are not shown. The counts are those of one day; they say how much is kept, not how well it is found.
While the provider does not answer
the route after the failure unavailable
- The search sees that the vector side is not there, or fails on it, and answers by the keywords alone: a session is not left without memory because a provider did not answer.
- Keyword search still works after the fallback, but a relevant note can fall outside the results returned.
Components
Press a component to read what it does.
Agents any model
Coding agents in different tools and on different models: through the MCP server first, a local one also through the command line; in Claude Code, hooks bring the memory in at the start of a session and before each prompt.
Embeddings provider
The provider that turns a query into a vector, to compare with the vectors of the notes.
MCP server stdio / HTTP
The interface for agents: tools, resources and prompts. stdio for a local client, streamable HTTP for a container or the network.
Search vectors + words
Ranks by keywords and by vectors and fuses the two by reciprocal rank, filtered by project and feature: the keywords before ranking, the vectors after it; keywords alone when the vector side fails.
Service layer validation
Episodes captured through MCP are written here: it refuses one without a project key, fills the metadata, and prints nothing to the protocol’s stream.
Merge queue proposals
Where a remote client leaves a change to an existing note: a base snapshot and a candidate; the merged text is made when it is applied.
Indexes graph, catalog
Generated files: a catalog, a graph of the relations, a readable map. They can be deleted and built again from the notes alone.
Vault Markdown + YAML
The notes themselves, under version control, each with a typed header (kind, project, feature, case, status, version, links): anchors of projects and features, knowledge, cases, episodes. A person opens the same files in Obsidian.
Owner review
Looks at a proposal on his own machine, and applies it or rejects it; decides what becomes knowledge and what a skill.
Packs imported
Libraries of skills imported from outside: searched by a light index, a skill read from them only when it is needed.
Skills four places
Procedures an agent loads for the task they fit, kept in four places: skill notes, the orchestrator’s registry, the agent’s own skills folder, imported packs.
-
Context
Two hooks bring the memory in: at the start of a session, the anchors of the project, its cases and the latest successful episodes; before each substantive prompt, the notes that match it.
My part Together with AI agents, I designed the memory model: what is loaded always, what is verified knowledge, what is an episode, what is a skill, and how a note moves from one kind to the next.
In detail
The setup command writes hooks into the agent’s settings. At the start of a session one gives the guardrails, the anchors of the project and its feature, up to eight case keys and the two latest successful episodes; before each prompt another runs a fast keyword search scoped to the project and adds up to four matching notes, skipping slash commands and short prompts, except a short request to go on, for which it brings back the active project’s context, and staying silent on any error. Then, by its contract, the agent asks for context in this order: the note of the project and, for a feature’s task, of the feature, a search, the smallest set of notes, verified knowledge before episodes. It follows a general rule of context: the smallest possible set of high-signal tokens. 1
Where it breaks As a context grows, a model can recall what is in it less accurately: so the context should hold what the task needs.
-
Search
Search ranks notes two ways, by the cosine similarity of embeddings and by matching words, each filtered by project and feature, and fuses the two rankings by reciprocal rank.
In detail
The vector side embeds the query and ranks by cosine similarity; the keyword side matches the query’s terms against the fields of the notes. In its automatic mode the search tries the hybrid when the embedding provider is configured and the index holds vectors; a setting can force either mode, and a search filtered by tag stays on keywords. The two lists are fused with Reciprocal Rank Fusion, k = 60 by default: keyword scores and cosine similarity are on different scales, and fusion by rank does not depend on scale. In the fusion, the durable kinds (knowledge, cases, the anchors of projects and features, skills, decisions) weigh twice as much as episodes. 2
Where it breaks A note found first is not a note that is true: ranking says what fits the query, the status of a note says whether it was verified.
-
Cases
A recurring problem has one canonical note, its case. Asked for similar cases, the memory returns case notes first, one for each case, and dated episodes only behind them.
In detail
A case note holds the context, the pattern of the failure, the stable guidance, the links and its evolution; its episodes keep the evidence. Of what the search finds, the case search keeps case notes and the success episodes of a case, one for each case. With no case found, it offers up to three success episodes and a hint to make a case of them, or says the ground is new and to record what solves it. A new lesson about a known case is added to it: a dated episode and, in the same step, a line in the case’s evolution, its version one higher and today’s date of verification; if validation fails, both are undone. The guidance written into the case is the agent’s; the code does not infer it.
Where it breaks Finding a case does not make an agent use it: reading the case note before its episodes is a rule of the memory model, not a check.
-
Skills
A skill is found by the task: one search over four places (skill notes, the orchestrator’s registry, the agent’s skills folder, imported packs) returns a ranked list, and the agent reads what it picks.
In detail
The ranking is by keywords, with weights per field: in skill notes, the registry and the agent’s folder a match in the key counts 5, in the title 4, in the tags or triggers 3, in the summary 2 and a little more for repeats, and the registry adds a bonus for its triggers; packs weigh their own fields, the name 5, the tags and the domain 3, the description 2. Russian words are matched to their English aliases too. Claude Code itself uses a skill of its folder when relevant, its description helping it decide when to load the skill. In a run of the orchestrator a stage’s agent profile names its skills, or, where the stage allows it, up to three are matched by their triggers; their prompt fragments and tools are put into the stage. 4
Where it breaks The memory offers, it does not choose: which skill an agent uses is the agent’s decision. And nothing puts skills into Codex: it gets the MCP server and its contract file.
-
Capture
When something has been proved, the agent records an episode: the problem, the solution, the evidence, how to use it again. A run of the orchestrator records its own when it completes or fails.
My part I built the tooling together with agents: a Python service with a command line, and an MCP server on the official SDK, with search, context bundles, validation and the rebuilding of indexes.
In detail
Over MCP, capture goes to the service layer, which validates the note, writes it under its project and has the indexes rebuilt from the notes: the catalog, the graph of relations, the map. It prints nothing: over stdio the server writes nothing to its stdout but protocol messages. When a run’s new episode is close enough to older ones of the same project, feature and outcome, in its title and in its text, the code tries to mark them deprecated, one version higher. The capture skill sorts what is recorded on its own (a fix proven by a test or a check, a trap with a stable workaround), what only after asking (a finding that matters but is not verified yet, a project that is unclear), and what never (a guess or a dead end with no new lesson, raw logs, what a note already covers, which is updated instead). 3
Where it breaks “Verified” is the writer’s word: capture checks the form of a note, not that its evidence holds, and a run counts as a success when it completes, whether or not a check ran in it.
-
A proposal
A remote client that wants to change a note that exists leaves a proposal instead of overwriting it. The owner looks at it on his own machine and applies it or rejects it.
In detail
A proposal holds a base snapshot and a candidate. Applied, they are merged three ways, section by section and field by field of the header; a conflict leaves the note as it was unless forced. The notes are validated again, the old text restored if they fail, and the indexes rebuilt; the version becomes one more than the higher of the two, and a drift from the base is recorded.
Where it breaks Review is a step of the workflow, not a proof of approval: the server can apply a proposal itself, and the update of a case or a deprecated episode is written without going through the queue.
-
Generalisation
No code turns an episode or an artifact into a skill. A lesson that works again becomes knowledge, and knowledge that has become a procedure a skill: the owner or an agent decides and writes it.
In detail
Memory has kinds, not one pile: short rules every session sees, verified knowledge, dated episodes with their evidence, and skills, loaded only for the task they fit; a note has a status (verified, needs review, deprecated), the date it was last verified, and a version. The capture skill’s last step is to promote the pattern later, if it proves stable across more than one case. What code does is narrower: a skill of an imported pack can be promoted into the registry, into a skill note, which starts as a draft at version 1, or into the agent’s skills folder, and the promotion is recorded; an update of the pack reports promoted skills whose source has changed, and leaves them as they are. An existing skill, too, is changed by the owner or an agent: a run’s result does not rewrite it. A lesson that has bitten twice can become a reflex too: a rule of the command guard, a hook that denies the command before it runs and gives the lesson as the reason.
Where it breaks A stale note is meant to move to “needs review”: a check reports source-of-truth notes not verified for 120 days, but does not change their status.
Code: a template
A second brain to adapt
A template, not the system itself: the rules of the figure in four files small enough to read at one sitting, to be adapted to your own folders, kinds of note and weights. The memory has no dependencies; the server needs the official MCP SDK for Python, version 2.
brain/cases/<project>/<case>.md The note of a case: a typed header and five sections. 32 lines
Lines 1–13 The search in memory.py reads this header: a case is a DURABLE kind, so its score doubles; title, summary and tags weigh 5, 4 and 3 per query word; similar_cases groups by the case key.
---
title: <a recurring problem, in one line>
type: case
project: <project-key>
case: <case-key>
status: verified
note_version: 1
last_verified: <YYYY-MM-DD>
summary: <what goes wrong and what to do, in one sentence: the search ranks this line>
tags:
- entity/case
---
Lines 14–25 Three sections in the order a reader needs them: how to recognise the problem, what goes wrong and why, what to do. In search, the body adds at most 3 per query word, less than one title match.
## Context
Where the problem shows up, and how to recognise it.
## Failure pattern
What goes wrong, and why.
## Stable guidance
What to do. A new lesson is added with its date, and an old one stays until it is shown wrong.
Lines 26–32 Links lead to the folder capture writes episodes into, where the evidence lies. Evolution is a dated log; memory.py never edits a case note, so its writer updates the log, note_version and last_verified.
## Links
- The episodes of this case, the evidence for each lesson: brain/episodes/<project-key>/
## Evolution
- <YYYY-MM-DD>: the case opened.
memory.py Notes, the search, the cases and the capture, apart from any protocol. 159 lines
Lines 1–19 VAULT starts from this file’s folder, not the working directory, so the server and the hook find the same notes. DURABLE lists the kinds whose score doubles; WEIGHTS gives the points per query word.
"""The memory itself, apart from any protocol: notes on disk, a search, cases, and capture.
A template to adapt. The rules are those of the second brain on this page (a typed header on every
note, durable notes before episodes, a case note before its history, nothing captured without
evidence); the folders, the kinds and the weights are yours to change. Python 3.10+, no dependencies.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import date
from pathlib import Path
VAULT = Path(__file__).resolve().parent / "brain"
DURABLE = {"knowledge", "case", "skill", "project"} # weigh twice as much as an episode
WEIGHTS = {"title": 5, "summary": 4, "tags": 3} # per word of the query; the body counts up to 3
Lines 20–34 The header stays a plain dict in meta, so a new field needs no change here. kind returns the type field; title falls back to the file name when the header has none, so search and results always have one.
@dataclass(frozen=True)
class Note:
path: Path
meta: dict[str, object]
body: str
@property
def kind(self) -> str:
return str(self.meta.get("type", ""))
@property
def title(self) -> str:
return str(self.meta.get("title", self.path.stem))
Lines 35–59 parse reads key: value lines and list items indented by two spaces, with no YAML library. It silently skips other lines, keeps values as strings and raises ValueError on a missing or unclosed header.
def parse(text: str) -> tuple[dict[str, object], str]:
"""The header between the first two '---' lines, and the body after it.
A subset of YAML on purpose, enough for these notes and no dependency: `key: value` lines,
and `key:` followed by `- item` lines for a list.
"""
if not text.startswith("---\n"):
raise ValueError("a note starts with its header")
head, closed, body = text[4:].partition("\n---\n")
if not closed:
raise ValueError("the header is not closed by a '---' line")
meta: dict[str, object] = {}
key = ""
for line in head.splitlines():
if line.startswith(" - ") and key:
items = meta.setdefault(key, [])
if isinstance(items, list):
items.append(line[4:].strip())
elif ":" in line:
key, _, value = line.partition(":")
key, value = key.strip(), value.strip()
meta[key] = value if value else []
return meta, body
Lines 60–69 load parses every .md under the vault, subfolders included, and catches nothing, so one broken header stops it. Every .md in brain, a README included, needs a header and UTF-8 text.
def load(vault: Path = VAULT) -> list[Note]:
"""Every note of the vault. A note whose header cannot be read stops the loading, by design:
a memory that silently skips its own notes is worse than one that says it is broken."""
notes = []
for path in sorted(vault.rglob("*.md")):
meta, body = parse(path.read_text(encoding="utf-8"))
notes.append(Note(path, meta, body))
return notes
Lines 70–101 The fields title, summary and tags match whole words via _words; the body counts substrings, at most 3 per word, so hook also matches hooks, and repeats never beat a title match. A given project keeps only its notes.
def _words(text: str) -> set[str]:
return set(re.findall(r"\w+", text.lower()))
def search(notes: list[Note], query: str, project: str = "", limit: int = 5) -> list[Note]:
"""Notes ranked by the words of the query; durable kinds count twice as much as episodes.
A rank says what fits the query, not what is true: a note's status says that.
"""
words = _words(query)
scored = []
for note in notes:
if project and note.meta.get("project") != project:
continue
fields = {
"title": _words(note.title),
"summary": _words(str(note.meta.get("summary", ""))),
"tags": _words(" ".join(map(str, note.meta.get("tags") or []))),
}
body = note.body.lower()
score = sum(
sum(w for name, w in WEIGHTS.items() if word in fields[name]) + min(body.count(word), 3)
for word in words
)
if score and note.kind in DURABLE:
score *= 2
if score:
scored.append((score, note))
scored.sort(key=lambda pair: (-pair[0], pair[1].title))
return [note for _, note in scored[:limit]]
Lines 102–120 similar_cases ranks all notes before grouping, not just the top five, so a case note ranked low still replaces its episode. Notes without a case key drop out; case notes go first, then limit (three) cuts the list.
def similar_cases(notes: list[Note], problem: str, project: str, limit: int = 3) -> list[Note]:
"""Cases for a problem: case notes first, one result per case.
An episode stands for its case only where the case note itself did not match. With nothing
found, the caller should say so: the problem may be new, and its solution worth a case.
"""
found = search(notes, problem, project, limit=len(notes)) # all of them: grouped, then cut
by_case: dict[str, Note] = {}
for note in found:
case = str(note.meta.get("case", ""))
if not case:
continue
kept = by_case.get(case)
if kept is None or (note.kind == "case" and kept.kind != "case"):
by_case[case] = note
ordered = sorted(by_case.values(), key=lambda n: n.kind != "case")
return ordered[:limit]
Lines 121–142 capture accepts a project key of letters, digits and hyphens only, so no / or .. reaches the file path. It refuses blank evidence, and a line break in title or case, which would add lines to the header.
def capture(
project: str,
title: str,
problem: str,
solution: str,
evidence: str,
reuse: str,
case: str = "",
vault: Path = VAULT,
today: date | None = None,
) -> Path:
"""Write an episode: dated, under its project's folder, and only with evidence.
The evidence is the writer's claim: this checks that it is there, not that it holds.
"""
if not project or not project.replace("-", "").isalnum():
raise ValueError("an episode needs a project key: never guess one")
if not evidence.strip():
raise ValueError("no evidence, no episode: an unproved idea is not memory")
for name, value in (("title", title), ("case", case)):
if "\n" in value or "\r" in value:
raise ValueError(f"the {name} is one line: it goes into the header")
Lines 143–159 summary squeezes the problem into one header line of at most 200 characters. The read-back refuses a title that changes in the header: empty, space-padded or split by U+2028. Mode x never overwrites an existing note.
day = (today or date.today()).isoformat()
slug = "-".join(sorted(_words(title), key=title.lower().find))[:60] or "episode"
path = vault / "episodes" / project / f"{day}-{slug}.md"
summary = " ".join(problem.split())[:200] # one line in the header; the problem stays whole below
lines = ["---", f"title: {title}", "type: episode", f"project: {project}"]
lines += [f"case: {case}"] if case else []
lines += ["status: verified", f"last_verified: {day}", f"summary: {summary}", "---"]
lines += ["", "## Problem", problem, "", "## Solution", solution, "", "## Evidence", evidence]
lines += ["", "## How to use it again", reuse, ""]
text = "\n".join(lines)
meta, _ = parse(text) # read back before it is written: what is kept is what was meant
if meta.get("project") != project or meta.get("title") != title:
raise ValueError("the header did not come out as written")
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "x", encoding="utf-8") as note: # "x": never over a note written meanwhile
note.write(text)
return path
server.py Three tools over MCP, on stdio. 67 lines
Lines 1–21 logging.basicConfig writes to stderr by default, keeping stdout for protocol messages only: a stray print would break the stdio stream. The rules stay in memory.py; the server only wraps them as tools.
"""The memory over MCP: three tools an agent can call. A template to adapt.
The official Python SDK, version 2 (`pip install "mcp>=2"`; in version 1 the class was FastMCP).
A tool's arguments and type hints become its input schema, and its docstring its description.
It runs over stdio, so nothing but the protocol may go to stdout: logging goes to stderr.
"""
from __future__ import annotations
import logging
from mcp.server.mcpserver import MCPServer
import memory
logging.basicConfig(level=logging.INFO) # to stderr
log = logging.getLogger("memory")
mcp = MCPServer("second-brain")
Lines 22–31 _brief turns a note into a short card, not its body: title, type, status, summary and a path relative to the vault in forward slashes, so the agent sees each status and opens only the notes it picks.
def _brief(note: memory.Note) -> dict[str, str]:
return {
"title": note.title,
"type": note.kind,
"status": str(note.meta.get("status", "")),
"summary": str(note.meta.get("summary", "")),
"path": note.path.relative_to(memory.VAULT).as_posix(),
}
Lines 32–42 search_notes loads the vault on every call: no cache, so a hand-edited note counts at once, and the cost grows with the vault. Its docstring is the tool’s description and tells the agent to check each status.
@mcp.tool()
def search_notes(query: str, project: str = "", limit: int = 5) -> list[dict[str, str]]:
"""Find notes by the words of a query; knowledge and cases weigh twice as much as episodes.
A note found first is not a note that is true: read it, and look at its status.
"""
notes = memory.search(memory.load(), query, project, limit)
log.info("search %r: %d notes", query, len(notes))
return [_brief(note) for note in notes]
Lines 43–51 The project argument is required here, unlike in search_notes, though an empty string still searches every project. The tool exposes no limit: similar_cases returns at most three.
@mcp.tool()
def find_similar_cases(problem: str, project: str) -> list[dict[str, str]]:
"""Cases of a recurring problem, case notes first. Read the case note before its episodes.
An empty list means no case matched: the problem may be new, and worth a case once solved.
"""
return [_brief(note) for note in memory.similar_cases(memory.load(), problem, project)]
Lines 52–67 The docstring holds the capture policy (record, ask first, never), which the agent sees in its tool list. A ValueError from memory.capture goes up to the SDK uncaught; mcp.run() serves stdio.
@mcp.tool()
def capture_success(
project: str, title: str, problem: str, solution: str, evidence: str, reuse: str, case: str = ""
) -> str:
"""Record what was proved, as a dated episode of the project. Without evidence it is refused.
Record a fix proven by a test or a check, or a trap with a stable workaround; ask first when
the finding is not verified yet or the project is unclear; never record a guess or raw logs.
"""
path = memory.capture(project, title, problem, solution, evidence, reuse, case)
log.info("captured %s", path.name)
return path.relative_to(memory.VAULT).as_posix()
if __name__ == "__main__":
mcp.run() # stdio
session_context.py The hook that brings the memory into a session. 46 lines
Lines 1–13 The entry has no matcher, so it runs on every SessionStart, resume, /clear and compaction included. ${CLAUDE_PROJECT_DIR} is the project root where the session started, so this file belongs there.
r"""A SessionStart hook: what the memory holds for this project, said before the first prompt.
Claude Code adds a SessionStart hook's plain stdout to the agent's context. Keep this file next to
memory.py and register it in .claude/settings.json (this is valid JSON, ready to paste):
{"hooks": {"SessionStart": [{"hooks": [
{"type": "command", "command": "python \"${CLAUDE_PROJECT_DIR}/session_context.py\""}
]}]}}
It fails open: on any error it prints nothing and exits 0, so a broken memory never blocks a
session. A template to adapt: here the project's key is the name of the folder the session is in.
"""
Lines 14–22 The import of memory resolves because Python puts the script’s own folder first on sys.path, which is why the hook must sit next to memory.py. It shares load and VAULT with the server instead of copying them.
from __future__ import annotations
import json
import sys
from pathlib import Path
import memory
Lines 23–35 Episode names start with an ISO date, so sorting by name puts the two latest last. Up to eight case keys and two episodes keep the context short; summary returns nothing for a project without notes.
def summary(project: str, notes: list[memory.Note]) -> list[str]:
own = [n for n in notes if n.meta.get("project") == project]
if not own:
return []
cases = sorted(str(n.meta.get("case")) for n in own if n.kind == "case")
episodes = sorted((n for n in own if n.kind == "episode"), key=lambda n: n.path.name)[-2:]
lines = [f"The memory holds {len(own)} notes for {project}."]
if cases:
lines.append("Its cases (read a case note before its episodes): " + ", ".join(cases[:8]))
lines += [f"A recent episode: {n.title} ({n.path.relative_to(memory.VAULT).as_posix()})" for n in episodes]
return lines
Lines 36–41 main reads the hook event as JSON from stdin; the project key is the last folder of its cwd, so a session opened in a subfolder looks for the subfolder’s name. Map folders to keys here when they differ.
def main() -> None:
event = json.load(sys.stdin) # session_id, cwd, source, ...
project = Path(event.get("cwd", ".")).name
print("\n".join(summary(project, memory.load())))
Lines 42–46 The except clause turns any error in main, a broken header from load included, into no output and exit 0. The import of memory sits above the try, so a missing or broken memory.py still exits 1 with a traceback.
if __name__ == "__main__":
try:
main()
except Exception: # fail open: a hook must never stop a session
sys.exit(0)
Next section
Tandem
Claude is the coordinator and the only author of code. Codex works read-only: it researches, challenges, reviews and verifies.