🏛️ Alexandria
Persistent memory and a token diet for your AI coding agents. 100% local · no API keys · no telemetry · free
Every new AI session starts from zero: it re-reads your code, re-derives decisions and re-spends the same tokens. Alexandria remembers for it — and sends the model only what it needs.
📉 Measured savings
| What the agent needed | Read directly | With Alexandria |
|---|---|---|
| Test suite output (121 tests) | 3,443 tokens | ~330 |
A failing run (keeps the failing test + file:line) |
3,148 | 140 |
| Answer from a 10-page PDF manual | ~20,000 | ~300 |
| Matching rows of a 2,016-row spreadsheet | ~1,240,000 | ~411 |
Structure of src/cli.ts (code map) |
14,978 | 377 |
Real numbers from real files — see how they were measured.
⚡ Install
npm install -g @ureck/alexandria
ale init # vault + hooks + MCP in every agent it finds
Open a new agent session — that's it. Nothing to reconnect, ever.
✨ What it does
- 🧠 Remembers across sessions — captures prompts and outcomes; each session starts with your project map, open plans and lessons.
- ⚡ Sends only what's relevant — local semantic search (<100 ms) injects the right fragments; never re-sends what's already in context.
- 📄 Reads documents by section — PDF, Word, Excel, CSV, HTML or a docs URL: the agent asks for the part it needs, not the whole file.
- ✂️ Folds noisy output — tests, builds and logs arrive as errors + summary; the full output stays on disk.
- 🗺️ Maps your code — function signatures first, then only the body you ask for.
- 🏗️ Disciplined engineer protocol — plan → verify with a real command → learn; lessons resurface when the problem does.
- 🧹 Cleans itself — compacts old noise without ever deleting knowledge.
Works as a valid Obsidian vault (markdown + [[wikilinks]]). Windows · macOS · Linux · Node, Bun or Deno.
🤖 Agents
| Agent | MCP | Automatic hooks |
|---|---|---|
| Claude Code | ✅ | ✅ |
| Codex CLI | ✅ | ✅ |
| Gemini CLI | ✅ | ✅ |
| Cursor | ✅ | ✅ |
| OpenCode | ✅ | ✅ (plugin) |
| Devin CLI · Cline · VS Code (Copilot) · OpenClaw · Hermes · Windsurf | ✅ | — |
🧰 Top commands
ale search "cors error in the api" # search your knowledge by meaning
ale ingest manual.pdf # documents → sections the agent can query
ale run -- npm test # run with folded output (same exit code)
ale code outline src/ # code map: signatures, no bodies
ale stats # what it saved you (measured)
ale context # what was injected per session
ale toggles # turn any token-spending feature on/off
ale clean # preview a safe cleanup
ale doctor # check & repair the install
ale agents # register in more agents
📚 Full documentation
Everything below is collapsed — open what you need. The same content, with diagrams, lives at alexandria.ureck.dev.
💡 Why Alexandria
- Saves tokens: every prompt triggers a local semantic search (<100ms) that injects only the relevant fragments — instead of re-reading whole files.
- Zero re-analysis between sessions: on session start, the agent receives the project map and all accumulated knowledge.
- Solution memory: if a nearly identical prompt was already solved, the previous solution is injected — the agent doesn't re-derive it.
- Infinite context, nothing is ever lost: old noise gets archived, never deleted — everything stays searchable forever.
- It's a valid Obsidian vault: plain markdown with
[[wikilinks]]. Open it in Obsidian anytime. - Cross-platform: Windows, macOS, Linux · Node, Bun or Deno. Pure JS — no native dependencies to break your install.
📦 Install options & first steps
# npm (Node ≥ 20)
npm install -g @ureck/alexandria
# bun
bun add -g @ureck/alexandria
# deno
deno install -grA -n ale npm:@ureck/alexandria/ale
# (if Deno complains about "minimum dependency date", add --minimum-dependency-age=0)
Verify:
$ ale --version
1.6.1
One command installs everything (embedding model ~130MB downloaded once, hooks, MCP registration, index):
# Global — one shared vault for all your sessions (~/Alexandria)
ale init
# Per project — vault INSIDE the repo (./Alexandria)
cd my-project
ale init --project
# Point at an existing Obsidian vault
ale init --path ~/Documents/MyObsidianVault
# Choose which agents get the MCP server
ale init --agents all # every supported agent
ale init --agents claude,cursor,opencode # just these
# (without --agents: Claude Code + whatever is detected on your machine)
ale init --project also, automatically:
- adds the vault to your
.gitignore(personal knowledge, not repo code), - scans the project (stack from package.json, npm scripts, folder structure, README excerpt) into an initial
Map - <project>note — context from the very first session, - asks "Configure Claude to use Alexandria automatically?" and writes the usage rules into
CLAUDE.md(--auto/--manualto skip the question).
After init there is nothing to reconnect, ever. Important: hooks load when a session starts — open a new agent session in that folder (an already-open one won't see them).
🏗️ The Alexandria Protocol (plan → verify → learn)
A lightweight engineering protocol that turns any MCP-capable model into a senior agent that plans, verifies with evidence, and learns:
Plan → Execute one task → Verify with evidence → (on failure: reuse past lessons) → Extract the lesson
It lives in the MCP tools themselves — their names and descriptions carry the instructions — so it works identically across every agent, with or without hooks:
| MCP tool | What the agent does with it | Token payoff |
|---|---|---|
plan_create(title, goal, dod, tasks, design?) |
Plans like an architect: clarifies vague goals first, optionally records the architecture (design → a ## Design section), and the response surfaces similar past plans + relevant lessons plus quality hints (verifiable DoD, small tasks) — suggestions, never a gate |
No wandering; open plans are re-injected next session so work is resumed, not repeated |
task_verify(plan, task, passed, verify_command, cwd?) |
Runs verify_command (e.g. npm test) and takes the verdict from the real exit code — not from the agent's word. Flags a discrepancy if the agent claimed otherwise; without a command the note is tagged self-reported and ale audit calls it out |
"✅ 12/12 passed" (5 tokens) instead of a 500-line log; on failure it automatically surfaces past lessons that match |
lesson_extract(title, lesson, links) |
Distills the root cause + fix after solving something non-obvious | ~200 tokens today replace ~20,000 tokens of re-debugging next month |
Lessons and solutions get a ranking boost in search, so the most valuable knowledge always surfaces first. The protocol is on by default; toggle it anytime:
ale config set protocol false # classic vault only
ale config set protocol true # back on
ale init --no-protocol # install without it
Create a plan from a markdown file instead of typing it:
$ ale plan PLAN-migration.md
✓ Plan created: notes/2026-07-11-plan-migrate-to-postgres-17.md
DoD detected: 3 criteria — backup verified · migrations run clean · app responds on staging
Checkbox lines (- [ ] ...) become the Definition of Done. The agent sees it as an open plan at the start of the next session and resumes it with task_verify.
🔎 Search & save knowledge
$ ale search how do I publish my app to the google store
Flutter release deployment (Alexandria/notes/2026-07-09-deploy.md, note) ● high relevance
To publish on Play Store: keystore outside git, key.properties,
flutter build appbundle. Always sign with the production key.
The query shares zero keywords with the note ("google store" → "Play Store"). More:
ale search cors error in the api # finds your fix from months ago
ale search "architecture decision" -k 10
ale search auth --expand # also pulls notes CONNECTED to the results (graph)
The ● high/medium/low relevance label is relative to the best hit — trust it over the raw number.
Save notes manually (automatic capture via hooks already does this in every Claude Code, Codex, Gemini CLI, Cursor and OpenCode session — add is for extra knowledge):
# Quick note
ale add "Prisma setup" -c "Singleton in src/lib/prisma.ts using globalThis" -t "prisma,db"
# From a file in your project (or a pipe)
ale add "Q3 architecture decisions" --file DECISIONS.md
cat DECISIONS.md | ale add "Q3 architecture decisions"
# With [[wikilinks]] to connect knowledge
ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
📄 Documents: PDF, Word, Excel, CSV, HTML, URLs
Reading a PDF directly costs an agent ~1,500–3,000 tokens per page (Claude sends each page as image + text). Alexandria converts documents locally to markdown sections and the agent asks only for what it needs:
ale ingest "Manual Tecnico.pdf" reports/ # file or folder (pdf, docx, xlsx, csv, tsv, html, md, txt)
ale ingest https://example.com/docs/api # one docs page, fetched once, reused 7 days
ale docs # list ingested documents
ale docs read "Manual Tecnico" -q "which env vars does the deploy need?"
ale docs read pagos.xlsx -q "F-137 pagado" # spreadsheets: returns the MATCHING ROWS
From any agent, the MCP tools doc_ingest (returns a ~200-token section outline) and doc_read (sections by id or by question, never over max_tokens, always telling what was left out) do the same. Measured on real documents:
| Document | Read directly | Outline | Answer to one question |
|---|---|---|---|
| 10-page technical manual (PDF) | ~20,000 tokens | ~248 | ~179–300 |
| 2,016-row spreadsheet (XLSX) | ~1,241,000 tokens | ~526 | ~411–579 (matching rows) |
- PDF: headings detected by font size (multi-line titles merged), source page kept for citations; scanned PDFs (no text layer) are flagged — Alexandria doesn't do OCR.
- Spreadsheets: never sent whole — a per-column summary (type, distinct values, samples) plus 50-row blocks; huge cells (geometries, JSON) are trimmed. Own XLSX reader (merged cells, styled dates, formula results) — no heavy dependencies.
- Claude Code: the first direct
Readof a large PDF/DOCX/XLSX/CSV in a session is redirected todoc_ingest/doc_read; a second attempt goes through (for when the agent really needs to see images). Toggle:docs.interceptRead. - Unchanged files are never reconverted (sha256). Documents live in
Alexandria/docs/, outside the vector index (a big spreadsheet would be thousands of chunks); section vectors are computed once per document version and cached. - Docs by URL:
doc_ingest/ale ingestaccepthttps://…: one page, fetched once, reused 7 days — the only network access, and only when asked. ale statsshows the measured document savings: tokens of the originals vs tokens actually served.
✂️ Context window management (folded output, code map, capsule)
Most tokens don't go into your prompt — they go into tool output and re-reading. Alexandria trims both, locally, without a proxy and without rewriting history (which would break the provider's prompt cache):
ale run -- npm test # exit code preserved; agent gets errors + summary + tail
ale run show last --grep "FAIL|Error" # the full output stays on disk
ale code outline src/ # symbols per file, no bodies
ale code symbol src/cli.ts runClean # just that function, with line numbers
ale context # what was injected per session, and what was saved
ale supersede "Decision - MySQL" "Decision - Postgres"
| Feature | What it does | Measured |
|---|---|---|
| Folded command output | Large outputs of tests/builds/installs/logs → errors (with stack location) + test summary + tail; full output in ~/.cache/alexandria/runs. Automatic in Claude Code (PostToolUse on Bash, successful commands) and OpenCode (plugin, also failures); ale run -- <cmd> everywhere else. Commands that read (cat, git diff, grep…) are never folded |
test suite 12.1 KB → 1.4 KB; failing run 12.6 KB → 561 B keeping the failing test, assertion and file:line |
| Code map | code_outline (signatures + line ranges, classes → methods, top-level constants) and code_symbol (one body). JS/TS, Python, PHP, Go, Java, C#, Kotlin, Rust — heuristic, no native deps |
src/cli.ts ~13,600 tokens → outline ~253 (in 1.6.1: 14,978 → 377) |
| No re-injection | A note already injected in this session is referenced in one line instead of re-sent (toggle context.dedupe) |
shown in ale context / ale stats |
| Anti-compaction capsule | Before compacting, a capsule (goal, last request, files edited/read, recent commands, what was saved, open plans) is built without an LLM and re-injected right after | real 8.4 MB transcript → ~576 tokens |
| Facts that expire | vault_save(..., supersedes: [...]) / ale supersede: the old note is marked, linked and no longer injected — never deleted |
|
| Duplicate suggestions | ale clean lists near-identical lessons/notes (cosine ≥ 0.96); applied only with --dedupe |
|
| Context meter | ale context [--session id]: injections, tokens, notes, folded runs, savings per session |
🎛️ Control what spends tokens (ale toggles)
Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
$ ale toggles # interactive menu: each toggle with its real approximate cost
ale init --off architect.enrich,digest.map # disable from the start
ale config set tokens.solutionCache false # scriptable, one by one
| Toggle | What it controls | Cost |
|---|---|---|
protocol |
Protocol manifest in the session digest | ~6% of the digest |
architect.enrich |
Similar plans + lessons in plan_create |
~+90 tokens/plan |
tokens.solutionCache |
Inject a previous solution to a near-identical prompt | up to ~500 tokens/prompt |
tokens.promptSearch |
Per-prompt semantic search — the main saving mechanism | up to ~1500 tokens/prompt (disabling it defeats the point) |
digest.map |
Project map in the digest | up to ~1000 tokens |
digest.titleIndex |
Title index in the digest | ~200 tokens |
docs.interceptRead |
Redirect direct reads of large PDFs/spreadsheets to doc_read |
saves ~2,000 tokens/PDF page |
run.fold |
Fold large command output | saves most of a build/test run |
context.dedupe |
Don't re-inject notes already in context | saves up to ~1500 tokens/prompt |
index.autoRebuild |
Background index rebuild at session close | no tokens |
clean.auto |
Weekly background cleanup | no tokens |
All on by default; nothing changes unless you touch them.
🗂️ Deep project context (ale scan)
ale init --project already runs it; re-run anytime the project changes:
$ ale scan
✓ API: 12 rutas · Env: 8 vars (solo nombres) · Datos: 5 · Convenciones: 4 · .gitignore ✓
Read-only scanners write compact notes (one line per entry) that the agent receives only when relevant (per-prompt semantic search — the session digest doesn't grow):
API - <project>— App Router routes with HTTP methods, Pages Router handlers,"use server"actions, Express/Hono routes.Env - <project>— environment variable NAMES only, never values (from.env.example/.env/.env.local).Datos - <project>— data schema parsed from files (prisma models, drizzle tables,CREATE TABLEin migrations) — no DB connection.Convenciones - <project>— package manager, monorepo, TS strict, import aliases, framework.Flujo - <project>— what a request goes through:GET /api/x → auth: requirePermiso(...) → datos: getX, createX → audits, plus what the middleware protects. The others say what exists; this one says how it connects.
It never touches your source code, and it guarantees the vault (and personal configs) are gitignored before writing — your notes never reach a shared repo, even if you never ran ale init.
ale skills:evolve turns what the vault knows (stack, conventions, app flow, lessons) into a living project skill — always shows a diff and asks before writing.
🕸️ Knowledge graph, stats & audit
The graph maintains itself — every vault change (automatic capture, ale add, reindex) regenerates <vault>/grafo.html. Double-click it anytime.
ale graph # LIVE viewer in your browser: auto-refreshes every 3s
ale graph --out other.html # static copy elsewhere (optional)
Nodes = notes (size = connections, color = type: 🟪 plans, 🟦 verifications, 🟨 lessons, 🟩 sessions…), solid lines = [[wikilinks]], dashed = semantic similarity. Auto-fit, hover highlights neighbors, click shows details, Obsidian-style type filters (prompts hidden by default — they're visual noise). The graph shines from ~20-30 notes on — it's cumulative by design.
In Obsidian: open the vault folder as a vault and use the native graph view — notes carry aliases in their frontmatter so Obsidian resolves the [[wikilinks]]. Old notes are migrated automatically on the next reindex. Note: grafo.html is for your browser; Obsidian doesn't render HTML.
Measure what it saves you:
$ ale stats
🧠 Vault: /Users/you/Alexandria (global)
Notes: 142 {"note":80,"prompt":38,"session":22,"map":2}
Indexed chunks: 385 · Connections: 91
Semantic search: active
🏛️ Protocol
Plans: 6 (1 open) · Verifications: 14 (86% ✓)
Lessons: 9 (4 reused — each reuse = a debug session that never happened)
📊 Measured (facts, not estimates)
Context injections: 57
Solution cache hits: 12 (~9,400 tokens — clearest win: solutions not re-derived)
Injected tokens (cost): ~21,300
Folded command output, documents and no-re-injection savings (when used)
💰 Estimated savings (band, NOT audited)
~63,900 – 170,400 tokens
Assumption: injected context replaces re-reading 3–8× its size in files. Not a
measurement — the real number depends on what you'd have re-read without the vault.
Audit your vault's health:
$ ale audit
🏛️ Alexandria Protocol audit
Plans: 2 (2 open, 0 completed, 0 failed)
Verifications: 1 (1 failures) · Lessons: 1
⚠ Notes without connections (invisible to vault_related): 1
- Plan - Migrate to Postgres 17 → connect it with vault_link or [[wikilinks]]
Flags plans without a Definition of Done, failures without lessons, and orphan notes.
🧹 Maintenance & cleanup
ale doctor # checks & repairs: model, hooks, MCP, index
ale reindex [--force] # incremental by default
ale clean # PREVIEW of a safe cleanup (touches nothing)
ale clean --yes [--backup f] # apply: old unused prompts → compacted monthly files (full text),