Skip to main content

cairn-mem

Project memory for coding agents, stored as plain files you can review.

PyPI Python CI License: MIT Dependencies: 0

Install · Quickstart · Agents · How it works · Benchmarks · Commands

An agent finishes a session, and the next one starts from zero. You explain again why the auth flow works that way, which migration is risky, and why the team uses that commit convention.

Cairn keeps that context in .cairn/events.jsonl, inside the repository. Each entry is a short decision, convention, gotcha or fact, with the reason behind it. A new session loads a compact summary and searches the rest when it needs it.

$ cairn save --kind decision --topic storage/fts5 \
    --title "Use FTS5, not embeddings" \
    --body "BM25 over SQLite is enough for 10k memories" \
    --why "The internal query stays under 6 ms"
7a5a07d26632

$ cairn search "fts5"
7a5a07d26632  decision  Use FTS5, not embeddings — BM25 over SQLite is enough for 10k memories

There is no daemon, no server and no extra binary. Python 3.10 or newer and the standard library are enough.

Why cairn

  • Memory you can review. It is plain JSONL in the repo, so shared memory changes go through a pull request like any other change.
  • Explicit, not magic. The agent writes what it learned and why. No model decides what to keep, and there are no embeddings or hidden pipeline.
  • Portable. A CLI for any harness with a shell, plus an MCP server for clients that speak the protocol.
  • Fast where it matters. A search through 10k memories takes a few milliseconds over MCP.
  • Local by default. Nothing leaves the machine unless you run cairn init --share.
  • Deterministic. The same store and the same query give the same ranking. Nothing depends on a model or a network call.

Install

uv tool install cairn-mem     # or: pipx install cairn-mem

# development
pip install -e ".[dev]"

Cairn needs Python 3.10+ and no third-party runtime dependencies. The dev extra only adds pytest and ruff. It also needs SQLite with FTS5, which ships with the usual CPython builds on Linux, macOS and Windows.

Upgrade

uv tool upgrade cairn-mem     # or: pipx upgrade cairn-mem
pip install -U cairn-mem      # a plain pip install

Every package manager replaces the installed version in place; there is no uninstall step. Cairn has no self-update command on purpose: it would need network access and would have to guess which install to replace. cairn doctor reports when two cairn binaries are on PATH.

Quickstart

Create the store for the current repository:

cairn init                 # .cairn/ here, local-only
cairn init --share         # version events.jsonl so the team shares memory

Save something worth keeping:

cairn save \
  --kind gotcha \
  --topic auth/redirect \
  --title "OAuth callback must match exactly" \
  --body "redirect_uri is compared byte for byte; trailing slashes fail" \
  --why "Spent two hours debugging a 400 from the provider" \
  --anchor src/auth.py

--anchor stores a hash of an existing file. If the file changes later, the memory is flagged for review instead of quietly going stale.

Find it again:

cairn search "oauth redirect"                # id, kind, topic, title, snippet, stale flag
cairn get a1b2c3d4e5f6                       # full memory, including the reason
cairn check                                  # memories whose anchor file changed
cairn session save --summary "## Goal ..."   # long recap, kept out of MEMORY.md
cairn save --kind convention --title "Commits in LF" --body "every repo" --personal
                                             # knowledge shared by every repo

search covers the project and your personal scope at once and tags each result with scope ([personal] in text). Add --project or --personal to restrict it to one scope.

Anything you would otherwise repeat in the next session belongs here. Task state, logs and chat transcripts do not.

Use it from your agent

MCP

One process, eight tools (save, search, get, context, save_session, archive, session_list, session_get), JSON-RPC over stdio:

{
  "mcpServers": {
    "cairn": { "command": "cairn", "args": ["mcp"] }
  }
}

The server keeps the SQLite index open, so a tool call costs a few milliseconds instead of paying Python startup every time. save and save_session accept "scope": "personal". search takes "scope": "project" | "personal" | "all" (the default is all). context returns MEMORY.md plus the project's last session recap, so a new session starts where the previous one stopped. session_list and session_get reach older recaps without touching the current context, and archive retires a memory that no longer applies.

Any other harness

cairn setup claude-code writes .mcp.json and appends the snippet to CLAUDE.md; cairn setup opencode writes opencode.json (mcp.servers.cairn) and AGENTS.md. Both merge into an existing config, keep their own other keys, and are idempotent. Use --dir <path> to configure another root.

For anything else, copy the snippet from docs/AGENT_SNIPPET.md into your AGENTS.md or CLAUDE.md. The agent reads MEMORY.md at the start of a task, searches before writing, and saves only what is worth keeping. If the harness cannot run cairn, cairn export --out MEMORIA.md writes the same knowledge as plain Markdown.

How it works

agent ── MCP or shell ──> cairn ──> .cairn/events.jsonl     (truth, append-only)
                                    ├── .cairn/sessions.jsonl (long recaps)
                                    ├── cairn.db            (derived, FTS5)
                                    └── MEMORY.md           (L0, <= 3000 chars)

MEMORY.md is the compact summary an agent reads at startup. It is built round-robin across kinds, so a noisy kind cannot push the others out of the budget. Each line shows the topic key when the entry has one.

Level What Size
L0 .cairn/MEMORY.md, loaded at startup ≤ 3000 characters
L1 cairn search "<terms>" about 50 tokens per result
L2 cairn get <id> full entry, body ≤ 500 characters

Search covers the title, body, reason, topic key and anchor path, so storage/fts5 or src/auth.py find the entry without remembering the title.

Only events.jsonl is the source of truth. cairn.db is rebuilt automatically when it is missing or out of date. MEMORY.md is regenerated by save, archive, rebuild or cairn render. sessions.jsonl is append-only and local: session recaps are continuity, not curated memory.

An entry can point to a file with --anchor. Cairn stores a hash of that file and flags the entry with ⚠ revisar when the file changes. Stale entries are never deleted or hidden automatically. cairn archive <id> is the explicit way to retire one. Saving with the same topic supersedes the previous entry, so the list stays current.

What it stores

Four kinds, with a title of at most 200 characters and a body of at most 500:

Kind Use it for
decision A choice and its reason: storage, architecture, a library
convention How this repo does things: naming, commits, structure
gotcha A trap that cost time, such as a platform quirk or an API failure
fact Stable context that is not obvious from the code

Cairn refuses text that looks like a secret, such as cloud keys, private keys, JWTs, password = ... or URLs with credentials. It does not redact them silently.

How it compares

Memory tools usually keep entries in a local database and let a model decide what to save. That works until you need to review the memory, share it with a teammate, or explain why the agent believes something.

Database-backed memory tools cairn-mem
Storage Local database, outside the repo .cairn/events.jsonl, plain text
Review Open the database Read the diff in a pull request
Sharing Export and import git clone, or local-only by default
Who writes Often an LLM extracts a summary The agent writes what it learned, with a reason
Output Varies with the model Deterministic ranking, no model in the loop
Runtime A server or a separate binary Python standard library

Commands

Command Purpose
cairn init [--share] Create .cairn/; --share versions events.jsonl
cairn save Store a decision, convention, gotcha or fact
cairn search "terms" Ranked active memories from project and personal scope (--project/--personal)
cairn get <id> Full memory
cairn archive <id> Stop returning a memory (either scope)
cairn check [--personal] List memories whose anchor changed
cairn render [--personal] Regenerate and print MEMORY.md
cairn rebuild [--personal] Rebuild the index from events.jsonl
cairn session save|list|get [--personal] Session recaps, separate from curated memory
cairn import legacy --db <path> [--dry-run] Migrate observations from another SQLite store
cairn doctor [--personal] Check SQLite/FTS5, JSONL lines, DB sync, L0 budget, stale anchors, .gitignore and duplicate installs
cairn setup claude-code|opencode [--dir <path>] Write the MCP config and the rules snippet for that harness
cairn export [--personal] [--sessions N] [--out <path>] Dump active memory (and recaps) as Markdown for a harness without cairn
cairn mcp Serve MCP over stdio

--json is available on save, search, get, check, session, doctor and import for agent consumption. --personal selects the personal scope on save, search, rebuild, render, check, session and doctor; search also takes --project. search spans both scopes by default, and get and archive check both stores.

Benchmarks

Windows 11, 10k memories, idle CPU, 2026-11-04. CLI numbers include Python startup. MCP numbers are in-process tool calls. You can see all measurements:

Operation p95
cairn search via CLI (project + personal) 309.3 ms
cairn save via CLI, summary render included 329.6 ms
search via MCP tool call 6.6 ms
save via MCP tool call 17.9 ms
context via MCP tool call 12.4 ms
Internal FTS5 query 4.5 ms

Retrieval precision@3 on the bundled golden set is 30/30. A small paired test, 8 tasks run twice, went from 0/16 correct answers and 26,826 tokens without memory to 16/16 and 20,982 tokens with it. The sample is too small to prove much, but the direction was consistent (details).

Migrating from another memory store

cairn import legacy --db <path> --dry-run   # counts without writing
cairn import legacy --db <path>             # project rows to .cairn/, global rows to ~/.cairn

Running it again is a no-op, because ids are derived from the source observation id.

Design choices

Saving is explicit. No model decides what to keep, and nothing calls an LLM, so the same store and query produce the same ranking.

Memory stays local unless you run cairn init --share. Internal context does not leave the machine by default.

The JSONL format and anchor hashes work the same on Linux, macOS and Windows. Anchor hashes normalize CRLF to LF. CI runs the suite on all three systems and on Python 3.10 and 3.14.

New capabilities need a measurement that justifies them. hits, decay, embeddings and passive capture stay in the backlog until a benchmark or a real user shows a gap (PLAN.md).

Development

pip install -e ".[dev]"
pytest -q
ruff check src tests bench
python bench/bench_mcp.py --reps 20

See PLAN.md for milestones, docs/DESIGN.md for the design and docs/DECISIONS.md for the reasoning behind each trade-off.

Contributing

Issues and pull requests are welcome. Keep changes small, add a test for behavior changes, and run pytest -q plus ruff check src tests bench before opening a PR. The PR template lists the full checklist, and AGENTS.md documents the project conventions.

License

MIT. See LICENSE.

Metadata

Release files for cairn-mem 0.15.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cairn-mem 0.15.1
File Size Uploaded Provenance Actions
cairn_mem-0.15.1.tar.gz 70.9 kB With provenance Details for cairn_mem-0.15.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cairn-mem 0.15.1
File Interpreter ABI Platform Actions
cairn_mem-0.15.1-py3-none-any.whl Python 3 none any Details for cairn_mem-0.15.1-py3-none-any.whl

Total release size: 113.4 kB

Release files / cairn_mem-0.15.1.tar.gz

Download URL cairn_mem-0.15.1.tar.gz
Size 70.9 kB
Tags Source
SHA-256 checksum
How to use checksums
08885d99fa9bb940d5a6cbe98148dccdfe0e58d7d0d599c8ab2c72b8f639d12d
BLAKE2b-256 checksum
How to use checksums
d97f150932f229366f603c44d1c38abcb077c6682620ac46c51ead6a13890390
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / cairn_mem-0.15.1-py3-none-any.whl

Download URL cairn_mem-0.15.1-py3-none-any.whl
Size 42.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
54365b99e2ec695c3137778da891ec5f1fae0f87eb890d2f04200448aca6146f
BLAKE2b-256 checksum
How to use checksums
daccd9dc1dbaef1ced8cf0d60ec16f9c227d2ca14f4017927e31127365c79878
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for cairn-mem 0.15.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cairn_mem-0.15.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page