@ureck/alexandria 1.6.0 → 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,51 +1,100 @@
1
+ <div align="center">
2
+
1
3
  # 🏛️ Alexandria
2
4
 
3
- > A local knowledge vault for your AI agents — saves tokens, remembers across sessions, and turns every model into a disciplined engineer.
5
+ **Persistent memory and a token diet for your AI coding agents.**
6
+ 100% local · no API keys · no telemetry · free
4
7
 
5
8
  [![npm](https://img.shields.io/npm/v/%40ureck%2Falexandria)](https://www.npmjs.com/package/@ureck/alexandria)
6
9
  [![license](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
10
+ [![docs](https://img.shields.io/badge/docs-ES%20%C2%B7%20EN-b8860b)](https://alexandria.ureck.dev/)
7
11
  [![Buy Me a Coffee](https://img.shields.io/badge/☕_Buy_me_a_coffee-ureck-yellow)](https://buymeacoffee.com/ureck)
8
12
 
9
- [![docs](https://img.shields.io/badge/docs-ES%20%C2%B7%20EN-b8860b)](https://alexandria.ureck.dev/) **[Documentation / Documentación](https://alexandria.ureck.dev/)**
13
+ **[📖 Documentation / Documentación](https://alexandria.ureck.dev/)**
10
14
 
11
- Alexandria automatically captures your AI prompts and sessions, searches that knowledge **before** spending tokens, and connects everything in an Obsidian-style graph. **100% local**: no database, no API keys, no telemetry, no cost.
15
+ </div>
12
16
 
13
- Works with the most popular agents via MCP: **Claude Code · Codex CLI · Gemini CLI · Cursor · OpenCode · Devin CLI · Cline · VS Code (Copilot) · OpenClaw · Hermes Agent · Windsurf (legacy)** — and since 1.4, **automatic capture + context injection via hooks in Claude Code, Codex, Gemini CLI, Cursor and OpenCode**.
17
+ 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.
14
18
 
15
- ## Why?
19
+ ## 📉 Measured savings
16
20
 
17
- Every new AI session starts from zero: it re-explores your code, re-derives decisions you already made, re-spends the same tokens. Alexandria breaks that cycle:
21
+ | What the agent needed | Read directly | With Alexandria |
22
+ |---|---:|---:|
23
+ | Test suite output (121 tests) | 3,443 tokens | **~330** |
24
+ | A failing run (keeps the failing test + `file:line`) | 3,148 | **140** |
25
+ | Answer from a 10-page PDF manual | ~20,000 | **~300** |
26
+ | Matching rows of a 2,016-row spreadsheet | ~1,240,000 | **~411** |
27
+ | Structure of `src/cli.ts` (code map) | 14,978 | **377** |
18
28
 
19
- - **Saves tokens**: every prompt triggers a local semantic search (<100ms) that injects only the relevant fragments — instead of re-reading whole files.
20
- - **Zero re-analysis between sessions**: on session start, the agent receives the project map and all accumulated knowledge.
21
- - **Solution memory**: if a nearly identical prompt was already solved, the previous solution is injected — the agent doesn't re-derive it.
22
- - **Infinite context, nothing is ever lost**: old noise gets archived, never deleted — everything stays searchable forever.
23
- - **It's a valid Obsidian vault**: plain markdown with `[[wikilinks]]`. Open it in Obsidian anytime.
24
- - **Cross-platform**: Windows, macOS, Linux · Node, Bun or Deno. Pure JS — no native dependencies to break your install.
29
+ Real numbers from real files — see [how they were measured](#-full-documentation).
25
30
 
26
- ## The Alexandria Protocol
31
+ ## ⚡ Install
27
32
 
28
- Beyond memory, Alexandria ships a lightweight engineering protocol that turns **any** MCP-capable model into a senior agent that plans, verifies with evidence, and learns:
33
+ ```bash
34
+ npm install -g @ureck/alexandria
35
+ ale init # vault + hooks + MCP in every agent it finds
36
+ ```
29
37
 
30
- > **Plan → Execute one task → Verify with evidence → (on failure: reuse past lessons) → Extract the lesson**
38
+ Open a **new** agent session — that's it. Nothing to reconnect, ever.
31
39
 
32
- 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:
40
+ ## ✨ What it does
33
41
 
34
- | MCP tool | What the agent does with it | Token payoff |
35
- |---|---|---|
36
- | `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 |
37
- | `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 |
38
- | `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 |
42
+ - 🧠 **Remembers across sessions** — captures prompts and outcomes; each session starts with your project map, open plans and lessons.
43
+ - ⚡ **Sends only what's relevant** — local semantic search (<100 ms) injects the right fragments; never re-sends what's already in context.
44
+ - 📄 **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.
45
+ - ✂️ **Folds noisy output** — tests, builds and logs arrive as errors + summary; the full output stays on disk.
46
+ - 🗺️ **Maps your code** — function signatures first, then only the body you ask for.
47
+ - 🏗️ **Disciplined engineer protocol** — plan → verify with a real command → learn; lessons resurface when the problem does.
48
+ - 🧹 **Cleans itself** — compacts old noise without ever deleting knowledge.
39
49
 
40
- 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:
50
+ Works as a valid **Obsidian** vault (markdown + `[[wikilinks]]`). Windows · macOS · Linux · Node, Bun or Deno.
51
+
52
+ ## 🤖 Agents
53
+
54
+ | Agent | MCP | Automatic hooks |
55
+ |---|:---:|:---:|
56
+ | Claude Code | ✅ | ✅ |
57
+ | Codex CLI | ✅ | ✅ |
58
+ | Gemini CLI | ✅ | ✅ |
59
+ | Cursor | ✅ | ✅ |
60
+ | OpenCode | ✅ | ✅ (plugin) |
61
+ | Devin CLI · Cline · VS Code (Copilot) · OpenClaw · Hermes · Windsurf | ✅ | — |
62
+
63
+ ## 🧰 Top commands
41
64
 
42
65
  ```bash
43
- ale config set protocol false # classic vault only
44
- ale config set protocol true # back on
45
- ale init --no-protocol # install without it
66
+ ale search "cors error in the api" # search your knowledge by meaning
67
+ ale ingest manual.pdf # documents → sections the agent can query
68
+ ale run -- npm test # run with folded output (same exit code)
69
+ ale code outline src/ # code map: signatures, no bodies
70
+ ale stats # what it saved you (measured)
71
+ ale context # what was injected per session
72
+ ale toggles # turn any token-spending feature on/off
73
+ ale clean # preview a safe cleanup
74
+ ale doctor # check & repair the install
75
+ ale agents # register in more agents
46
76
  ```
47
77
 
48
- ## Install
78
+ ---
79
+
80
+ ## 📚 Full documentation
81
+
82
+ Everything below is collapsed — open what you need. The same content, with diagrams, lives at **[alexandria.ureck.dev](https://alexandria.ureck.dev/)**.
83
+
84
+ <details>
85
+ <summary><b>💡 Why Alexandria</b></summary>
86
+
87
+ - **Saves tokens**: every prompt triggers a local semantic search (<100ms) that injects only the relevant fragments — instead of re-reading whole files.
88
+ - **Zero re-analysis between sessions**: on session start, the agent receives the project map and all accumulated knowledge.
89
+ - **Solution memory**: if a nearly identical prompt was already solved, the previous solution is injected — the agent doesn't re-derive it.
90
+ - **Infinite context, nothing is ever lost**: old noise gets archived, never deleted — everything stays searchable forever.
91
+ - **It's a valid Obsidian vault**: plain markdown with `[[wikilinks]]`. Open it in Obsidian anytime.
92
+ - **Cross-platform**: Windows, macOS, Linux · Node, Bun or Deno. Pure JS — no native dependencies to break your install.
93
+
94
+ </details>
95
+
96
+ <details>
97
+ <summary><b>📦 Install options & first steps</b></summary>
49
98
 
50
99
  ```bash
51
100
  # npm (Node ≥ 20)
@@ -63,11 +112,9 @@ Verify:
63
112
 
64
113
  ```bash
65
114
  $ ale --version
66
- 1.6.0
115
+ 1.6.1
67
116
  ```
68
117
 
69
- ## Getting started
70
-
71
118
  One command installs everything (embedding model ~130MB downloaded once, hooks, MCP registration, index):
72
119
 
73
120
  ```bash
@@ -94,9 +141,45 @@ ale init --agents claude,cursor,opencode # just these
94
141
 
95
142
  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).
96
143
 
97
- ## Daily usage — examples
144
+ </details>
98
145
 
99
- ### Search by meaning, not keywords
146
+ <details>
147
+ <summary><b>🏗️ The Alexandria Protocol (plan → verify → learn)</b></summary>
148
+
149
+ A lightweight engineering protocol that turns **any** MCP-capable model into a senior agent that plans, verifies with evidence, and learns:
150
+
151
+ > **Plan → Execute one task → Verify with evidence → (on failure: reuse past lessons) → Extract the lesson**
152
+
153
+ 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:
154
+
155
+ | MCP tool | What the agent does with it | Token payoff |
156
+ |---|---|---|
157
+ | `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 |
158
+ | `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 |
159
+ | `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 |
160
+
161
+ 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:
162
+
163
+ ```bash
164
+ ale config set protocol false # classic vault only
165
+ ale config set protocol true # back on
166
+ ale init --no-protocol # install without it
167
+ ```
168
+
169
+ Create a plan from a markdown file instead of typing it:
170
+
171
+ ```bash
172
+ $ ale plan PLAN-migration.md
173
+ ✓ Plan created: notes/2026-07-11-plan-migrate-to-postgres-17.md
174
+ DoD detected: 3 criteria — backup verified · migrations run clean · app responds on staging
175
+ ```
176
+
177
+ 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`.
178
+
179
+ </details>
180
+
181
+ <details>
182
+ <summary><b>🔎 Search & save knowledge</b></summary>
100
183
 
101
184
  ```bash
102
185
  $ ale search how do I publish my app to the google store
@@ -116,7 +199,7 @@ ale search auth --expand # also pulls notes CONNECTED to the resu
116
199
 
117
200
  The `● high/medium/low relevance` label is relative to the best hit — trust it over the raw number.
118
201
 
119
- ### Save notes manually
202
+ 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):
120
203
 
121
204
  ```bash
122
205
  # Quick note
@@ -130,14 +213,16 @@ cat DECISIONS.md | ale add "Q3 architecture decisions"
130
213
  ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
131
214
  ```
132
215
 
133
- (Automatic capture via hooks already does this in every Claude Code, Codex, Gemini CLI, Cursor and OpenCode session — `add` is for extra knowledge.)
216
+ </details>
134
217
 
135
- ### Read documents without paying for the whole thing (PDF, DOCX, XLSX, CSV, HTML)
218
+ <details>
219
+ <summary><b>📄 Documents: PDF, Word, Excel, CSV, HTML, URLs</b></summary>
136
220
 
137
221
  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:
138
222
 
139
223
  ```bash
140
224
  ale ingest "Manual Tecnico.pdf" reports/ # file or folder (pdf, docx, xlsx, csv, tsv, html, md, txt)
225
+ ale ingest https://example.com/docs/api # one docs page, fetched once, reused 7 days
141
226
  ale docs # list ingested documents
142
227
  ale docs read "Manual Tecnico" -q "which env vars does the deploy need?"
143
228
  ale docs read pagos.xlsx -q "F-137 pagado" # spreadsheets: returns the MATCHING ROWS
@@ -147,16 +232,20 @@ From any agent, the MCP tools `doc_ingest` (returns a ~200-token section outline
147
232
 
148
233
  | Document | Read directly | Outline | Answer to one question |
149
234
  |---|---|---|---|
150
- | 10-page technical manual (PDF) | ~20,000 tokens | ~248 | ~179 |
151
- | 2,016-row spreadsheet (XLSX) | ~1,241,000 tokens | ~526 | ~579 (matching rows) |
235
+ | 10-page technical manual (PDF) | ~20,000 tokens | ~248 | ~179–300 |
236
+ | 2,016-row spreadsheet (XLSX) | ~1,241,000 tokens | ~526 | ~411–579 (matching rows) |
152
237
 
153
238
  - **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.
154
- - **Spreadsheets**: never sent whole — a per-column summary (type, distinct values, samples) plus 50-row blocks; huge cells (geometries, JSON) are trimmed.
239
+ - **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.
155
240
  - **Claude Code**: the first direct `Read` of a large PDF/DOCX/XLSX/CSV in a session is redirected to `doc_ingest`/`doc_read`; a second attempt goes through (for when the agent really needs to see images). Toggle: `docs.interceptRead`.
156
241
  - 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.
242
+ - **Docs by URL**: `doc_ingest`/`ale ingest` accept `https://…`: one page, fetched once, reused 7 days — the only network access, and only when asked.
157
243
  - `ale stats` shows the **measured** document savings: tokens of the originals vs tokens actually served.
158
244
 
159
- ### Manage the context window (1.6)
245
+ </details>
246
+
247
+ <details>
248
+ <summary><b>✂️ Context window management (folded output, code map, capsule)</b></summary>
160
249
 
161
250
  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):
162
251
 
@@ -172,15 +261,17 @@ ale supersede "Decision - MySQL" "Decision - Postgres"
172
261
  | Feature | What it does | Measured |
173
262
  |---|---|---|
174
263
  | **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` |
175
- | **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 |
264
+ | **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) |
176
265
  | **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` |
177
266
  | **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 |
178
267
  | **Facts that expire** | `vault_save(..., supersedes: [...])` / `ale supersede`: the old note is marked, linked and no longer injected — never deleted | |
179
268
  | **Duplicate suggestions** | `ale clean` lists near-identical lessons/notes (cosine ≥ 0.96); applied only with `--dedupe` | |
180
269
  | **Context meter** | `ale context [--session id]`: injections, tokens, notes, folded runs, savings per session | |
181
- | **Docs by URL** | `doc_ingest`/`ale ingest` accept `https://…`: one page, fetched once, reused 7 days — the only network access, and only when asked | |
182
270
 
183
- ### Control what spends tokens (`ale toggles`)
271
+ </details>
272
+
273
+ <details>
274
+ <summary><b>🎛️ Control what spends tokens (<code>ale toggles</code>)</b></summary>
184
275
 
185
276
  Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
186
277
 
@@ -190,9 +281,26 @@ ale init --off architect.enrich,digest.map # disable from the start
190
281
  ale config set tokens.solutionCache false # scriptable, one by one
191
282
  ```
192
283
 
193
- The toggles: Protocol manifest (~6% of the session digest), Architect enrichment in `plan_create` (~+90 tokens/plan), solution cache (up to ~500 tokens/prompt), per-prompt semantic search (the **main saving mechanism** — up to ~1500 tokens/prompt, disabling it defeats the point), project map in the digest (up to ~1000 tokens), title index (~200 tokens), redirecting direct reads of large PDFs/spreadsheets to `doc_read` (`docs.interceptRead`), folding large command output (`run.fold`), not re-injecting notes already in context (`context.dedupe`), background index rebuild at session close, and weekly background cleanup `clean.auto` (neither costs tokens). All on by default; nothing changes unless you touch them.
284
+ | Toggle | What it controls | Cost |
285
+ |---|---|---|
286
+ | `protocol` | Protocol manifest in the session digest | ~6% of the digest |
287
+ | `architect.enrich` | Similar plans + lessons in `plan_create` | ~+90 tokens/plan |
288
+ | `tokens.solutionCache` | Inject a previous solution to a near-identical prompt | up to ~500 tokens/prompt |
289
+ | `tokens.promptSearch` | Per-prompt semantic search — the **main saving mechanism** | up to ~1500 tokens/prompt (disabling it defeats the point) |
290
+ | `digest.map` | Project map in the digest | up to ~1000 tokens |
291
+ | `digest.titleIndex` | Title index in the digest | ~200 tokens |
292
+ | `docs.interceptRead` | Redirect direct reads of large PDFs/spreadsheets to `doc_read` | saves ~2,000 tokens/PDF page |
293
+ | `run.fold` | Fold large command output | saves most of a build/test run |
294
+ | `context.dedupe` | Don't re-inject notes already in context | saves up to ~1500 tokens/prompt |
295
+ | `index.autoRebuild` | Background index rebuild at session close | no tokens |
296
+ | `clean.auto` | Weekly background cleanup | no tokens |
297
+
298
+ All on by default; nothing changes unless you touch them.
299
+
300
+ </details>
194
301
 
195
- ### Deep project context (`ale scan`)
302
+ <details>
303
+ <summary><b>🗂️ Deep project context (<code>ale scan</code>)</b></summary>
196
304
 
197
305
  `ale init --project` already runs it; re-run anytime the project changes:
198
306
 
@@ -201,7 +309,7 @@ $ ale scan
201
309
  ✓ API: 12 rutas · Env: 8 vars (solo nombres) · Datos: 5 · Convenciones: 4 · .gitignore ✓
202
310
  ```
203
311
 
204
- Four 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):
312
+ 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):
205
313
 
206
314
  - **`API - <project>`** — App Router routes with HTTP methods, Pages Router handlers, `"use server"` actions, Express/Hono routes.
207
315
  - **`Env - <project>`** — environment variable **NAMES only, never values** (from `.env.example` / `.env` / `.env.local`).
@@ -211,19 +319,12 @@ Four read-only scanners write compact notes (one line per entry) that the agent
211
319
 
212
320
  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`.
213
321
 
214
- ### Create a plan from a file
215
-
216
- Instead of typing a whole plan into the terminal, keep it as markdown in your repo:
217
-
218
- ```bash
219
- $ ale plan PLAN-migration.md
220
- ✓ Plan created: notes/2026-07-11-plan-migrate-to-postgres-17.md
221
- DoD detected: 3 criteria — backup verified · migrations run clean · app responds on staging
222
- ```
322
+ `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.
223
323
 
224
- 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`.
324
+ </details>
225
325
 
226
- ### View the knowledge graph
326
+ <details>
327
+ <summary><b>🕸️ Knowledge graph, stats & audit</b></summary>
227
328
 
228
329
  **The graph maintains itself** — every vault change (automatic capture, `ale add`, reindex) regenerates `<vault>/grafo.html`. Double-click it anytime.
229
330
 
@@ -236,7 +337,7 @@ Nodes = notes (size = connections, color = type: 🟪 plans, 🟦 verifications,
236
337
 
237
338
  **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.
238
339
 
239
- ### Measure what it saves you
340
+ **Measure what it saves you:**
240
341
 
241
342
  ```bash
242
343
  $ ale stats
@@ -254,6 +355,7 @@ $ ale stats
254
355
  Context injections: 57
255
356
  Solution cache hits: 12 (~9,400 tokens — clearest win: solutions not re-derived)
256
357
  Injected tokens (cost): ~21,300
358
+ Folded command output, documents and no-re-injection savings (when used)
257
359
 
258
360
  💰 Estimated savings (band, NOT audited)
259
361
  ~63,900 – 170,400 tokens
@@ -261,7 +363,7 @@ $ ale stats
261
363
  measurement — the real number depends on what you'd have re-read without the vault.
262
364
  ```
263
365
 
264
- ### Audit your vault's health
366
+ **Audit your vault's health:**
265
367
 
266
368
  ```bash
267
369
  $ ale audit
@@ -275,7 +377,10 @@ $ ale audit
275
377
 
276
378
  Flags plans without a Definition of Done, failures without lessons, and orphan notes.
277
379
 
278
- ### Maintenance (you rarely need it)
380
+ </details>
381
+
382
+ <details>
383
+ <summary><b>🧹 Maintenance & cleanup</b></summary>
279
384
 
280
385
  ```bash
281
386
  ale doctor # checks & repairs: model, hooks, MCP, index
@@ -284,12 +389,16 @@ ale clean # PREVIEW of a safe cleanup (touches nothing)
284
389
  ale clean --yes [--backup f] # apply: old unused prompts → compacted monthly files (full text),
285
390
  # harness noise dropped, stale caches purged. Lessons, plans, maps,
286
391
  # sessions are NEVER touched. Still searchable: ale search --archive "…"
392
+ ale clean --yes --dedupe # also mark suggested near-duplicates as superseded
287
393
  ale uninstall # removes hooks + MCP from every agent; your notes stay untouched
288
394
  ```
289
395
 
290
396
  Every command self-repairs before running: missing model → downloads it; stale index → updates it.
291
397
 
292
- ## Supported agents
398
+ </details>
399
+
400
+ <details>
401
+ <summary><b>🤖 Agents in detail & plugins</b></summary>
293
402
 
294
403
  ```bash
295
404
  ale agents # list with auto-detection (● = found on your machine)
@@ -299,11 +408,11 @@ ale agents cursor,gemini # just these
299
408
 
300
409
  | Agent | MCP config written | Hooks (auto capture + injection) | Per-project |
301
410
  |---|---|---|---|
302
- | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact | ✓ |
411
+ | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact · PreToolUse(Read) · PostToolUse(Bash) | ✓ |
303
412
  | Codex CLI | `~/.codex/config.toml` / `.codex/config.toml` | `.codex/hooks.json` — SessionStart · UserPromptSubmit · Stop · PreCompact ¹ | ✓ |
304
413
  | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | same file — SessionStart · BeforeAgent · AfterAgent · PreCompress | ✓ |
305
414
  | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | `.cursor/hooks.json` — sessionStart · beforeSubmitPrompt ² · afterAgentResponse | ✓ |
306
- | OpenCode | `opencode.json` | plugin `.opencode/plugins/alexandria.js` — injects into the system prompt | ✓ |
415
+ | OpenCode | `opencode.json` | plugin `.opencode/plugins/alexandria.js` — injects into the system prompt, folds bash output | ✓ |
307
416
  | Devin CLI (Cognition) | `.devin/mcp_config.local.json` | — | ✓ |
308
417
  | Cline | `cline_mcp_settings.json` (VS Code) | — | — |
309
418
  | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | — | ✓ |
@@ -318,9 +427,7 @@ ale agents cursor,gemini # just these
318
427
 
319
428
  Agents without hooks still get everything through the MCP tools, which the agent uses on its own (the protocol instructions travel inside the tool descriptions).
320
429
 
321
- ### As a plugin
322
-
323
- The public repo is also a **Claude Code plugin marketplace** (and ships a Codex plugin manifest). The plugin runs the globally installed `alexandria` (falls back to `npx`):
430
+ **As a plugin** — the public repo is also a **Claude Code plugin marketplace** (and ships a Codex plugin manifest). The plugin runs the globally installed `alexandria` (falls back to `npx`):
324
431
 
325
432
  ```bash
326
433
  npm i -g @ureck/alexandria
@@ -328,7 +435,10 @@ claude plugin marketplace add UreckChan/alexandria
328
435
  claude plugin install alexandria@alexandria
329
436
  ```
330
437
 
331
- ## How it works
438
+ </details>
439
+
440
+ <details>
441
+ <summary><b>⚙️ How it works</b></summary>
332
442
 
333
443
  ```
334
444
  AI agent session
@@ -352,7 +462,10 @@ AI agent session
352
462
  - **Deduplication**: near-identical prompts don't create new notes — they add `hits` (and climb the ranking).
353
463
  - **About scores**: the e5 model compresses cosines (~0.76–0.86 even for unrelated topics); the *ranking* is what's reliable, hence the relevance label.
354
464
 
355
- ## Command reference
465
+ </details>
466
+
467
+ <details>
468
+ <summary><b>📋 Command reference</b></summary>
356
469
 
357
470
  | Command | What it does |
358
471
  |---|---|
@@ -366,7 +479,7 @@ AI agent session
366
479
  | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done); surfaces similar past plans + quality hints |
367
480
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
368
481
  | `ale audit` | Protocol health: plans without DoD, failures without lessons, orphan notes |
369
- | `ale stats` | Notes, connections, protocol metrics, estimated tokens saved |
482
+ | `ale stats` | Notes, connections, protocol metrics, measured savings (documents, folded output, no re-injection), estimated tokens saved |
370
483
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
371
484
  | `ale skills [-y] [--project]` | Recommends & installs Claude skills — semantic (e5) + keyword detection over your vault. Local source configurable with `ale config set skills.repo <path>`; otherwise installs from skills.sh |
372
485
  | `ale reindex [--force]` | Reindex (incremental by default) |
@@ -374,7 +487,7 @@ AI agent session
374
487
  | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
375
488
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
376
489
  | `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
377
- | `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD to markdown sections and store them in the vault |
490
+ | `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD (or a docs URL) to markdown sections and store them in the vault |
378
491
  | `ale docs` / `ale docs read <doc> [-s ids] [-q question] [--max-tokens n]` | List ingested documents / read only the sections (or spreadsheet rows) you need |
379
492
  | `ale run -- <cmd>` / `ale run show <id\|last> [--grep re] [--lines a-b]` / `ale run list` | Run a command with folded output (same exit code) / read the full output |
380
493
  | `ale code outline <file\|dir>` / `ale code symbol <file> <name>` | Code map: signatures without bodies / one symbol's body (`Class.method` works) |
@@ -385,25 +498,34 @@ AI agent session
385
498
 
386
499
  `alexandria` works as an alias of `ale`.
387
500
 
388
- ## Privacy & security
501
+ **MCP tools** (every agent): `vault_search` · `vault_save` (with `supersedes`) · `vault_related` · `vault_link` · `doc_ingest` · `doc_read` · `code_outline` · `code_symbol` · `run_output` · `plan_create` · `task_verify` · `lesson_extract`.
502
+
503
+ </details>
504
+
505
+ <details>
506
+ <summary><b>🔒 Privacy & security</b></summary>
389
507
 
390
508
  - **Everything runs on your machine**: the embedding model is downloaded once (Hugging Face) and then works offline. Your notes never leave your disk. No telemetry.
391
- - **No API keys, no accounts, no cost.**
509
+ - **No API keys, no accounts, no cost.** The only other network access is `ale ingest <url>` / `doc_ingest` with a URL — one page, only when you ask.
392
510
  - **`ale scan` never reads secrets**: it extracts environment variable **names** only (values are never copied), parses schema **files** (no live DB connection), and guarantees the vault is gitignored before writing — your notes never reach a shared repo.
393
511
  - Dependency scanners (Socket, etc.) flag *network/shell/env access* in the dependency tree: those come from the ML runtime (`onnxruntime`/`transformers.js`, which needs filesystem access and the one-time model download) and the official MCP SDK — not from Alexandria's code. The published package runs no install scripts of its own.
394
- - **`npm audit` may report `sharp <0.35.0` (libvips CVEs, [GHSA-f88m-g3jw-g9cj](https://github.com/advisories/GHSA-f88m-g3jw-g9cj))**, inherited from `@huggingface/transformers`. As of this writing no published version of `transformers.js` (including the newest, 4.x) uses a patched sharp, so there's no upstream fix yet — and it isn't reachable in Alexandria's own usage anyway: Alexandria only calls `pipeline('feature-extraction', ...)` for text embeddings and never touches images. If you want a clean `npm audit` in your own project, add this to its `package.json`:
512
+ - **`npm audit` may report `sharp` (libvips CVEs, e.g. [GHSA-f88m-g3jw-g9cj](https://github.com/advisories/GHSA-f88m-g3jw-g9cj))**, inherited from `@huggingface/transformers`. It isn't reachable in Alexandria's own usage: Alexandria only calls `pipeline('feature-extraction', ...)` for text embeddings and never touches images. If you want a clean `npm audit` in your own project, add this to its `package.json`:
395
513
  ```json
396
514
  "overrides": {
397
- "sharp": "^0.35.4"
515
+ "sharp": "^0.35.5"
398
516
  }
399
517
  ```
400
518
  (npm's `overrides` only applies at the root of an install, so this must go in *your* project — Alexandria declaring it in its own `package.json` doesn't propagate to consumers.)
401
519
  - Generated per-project configs (`.mcp.json`, `.vault.json`, etc.) point at your machine's install path, so `ale init --project` automatically gitignores them (and untracks any already committed) — they never leak to a shared repo. For a team that *wants* a shared MCP config, run `ale init --project --portable`, which writes an npx-based command that works on any machine.
402
520
 
403
- ## Support the project ☕
521
+ </details>
522
+
523
+ ---
524
+
525
+ <div align="center">
404
526
 
405
- Alexandria is free and open source. If it saves you tokens (and money), you can buy me a coffee:
527
+ **Free and open source.** If it saves you tokens (and money): **[☕ buymeacoffee.com/ureck](https://buymeacoffee.com/ureck)**
406
528
 
407
- **[☕ buymeacoffee.com/ureck](https://buymeacoffee.com/ureck)**
529
+ Built with 🏛 by **[Ureck](https://buymeacoffee.com/ureck)** — MIT License · [Changelog](https://github.com/UreckChan/alexandria/releases)
408
530
 
409
- Built with 🏛 by **[Ureck](https://buymeacoffee.com/ureck)** — MIT License.
531
+ </div>
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-44QPE5IM.js";
4
+ } from "./chunk-DELBYC3Y.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";
@@ -6,7 +6,7 @@ import {
6
6
  dot,
7
7
  embed,
8
8
  modelPresent
9
- } from "./chunk-EDYBSJSS.js";
9
+ } from "./chunk-LUAVB3CA.js";
10
10
 
11
11
  // src/core/notes.ts
12
12
  import fs from "fs";
@@ -326,10 +326,13 @@ var VaultIndex = class _VaultIndex {
326
326
  withEmbeddings = false;
327
327
  }
328
328
  }
329
+ const pending = new Set((this.meta.pending ?? []).filter((rel) => onDisk.has(rel)));
329
330
  const changed = [];
330
331
  for (const [rel, info] of onDisk) {
331
332
  if (force || this.meta.mtimes[rel] !== info.mtime) changed.push(rel);
333
+ else if (withEmbeddings && this.emb !== null && pending.has(rel)) changed.push(rel);
332
334
  }
335
+ const changedSet = new Set(changed);
333
336
  const removed = Object.keys(this.meta.mtimes).filter((rel) => !onDisk.has(rel));
334
337
  if (changed.length === 0 && removed.length === 0) {
335
338
  return { changed: 0, removed: 0, embedded: this.emb !== null };
@@ -338,7 +341,7 @@ var VaultIndex = class _VaultIndex {
338
341
  const keep = new Set(
339
342
  this.meta.chunks.map((_, i) => i).filter((i) => {
340
343
  const rel = this.meta.chunks[i].note;
341
- return onDisk.has(rel) && !changed.includes(rel);
344
+ return onDisk.has(rel) && !changedSet.has(rel);
342
345
  })
343
346
  );
344
347
  const newChunks = [];
@@ -406,19 +409,27 @@ ${c.text}`),
406
409
  embedded = false;
407
410
  }
408
411
  this.meta.chunks = [...newChunks, ...freshChunks];
412
+ for (const rel of changed) pending.delete(rel);
409
413
  if (embedded && (hadEmb || newChunks.length === 0) && freshRows.length === freshChunks.length) {
410
414
  const all = new Float32Array(this.meta.chunks.length * this.meta.dim);
411
415
  [...keptRows, ...freshRows].forEach((r, i) => all.set(r, i * this.meta.dim));
412
416
  this.emb = all;
417
+ } else if (hadEmb && freshChunks.length > 0) {
418
+ const all = new Float32Array(this.meta.chunks.length * this.meta.dim);
419
+ keptRows.forEach((r, i) => all.set(r, i * this.meta.dim));
420
+ this.emb = all;
421
+ for (const c of freshChunks) pending.add(c.note);
413
422
  } else if (freshChunks.length > 0 && !embedded) {
414
423
  this.emb = null;
415
424
  }
425
+ if (pending.size > 0 && this.emb !== null) this.meta.pending = [...pending];
426
+ else delete this.meta.pending;
416
427
  this.rebuildLinks();
417
428
  this.save();
418
429
  if (this.emb !== null) this.clearNeedsRebuild();
419
430
  else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
420
431
  if (!isHookProcess()) try {
421
- const { writeStaticGraph } = await import("./viewer-T2SEBP6Z.js");
432
+ const { writeStaticGraph } = await import("./viewer-V7WGXOFM.js");
422
433
  writeStaticGraph(this);
423
434
  } catch {
424
435
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  modelCacheDir
4
- } from "./chunk-EDYBSJSS.js";
4
+ } from "./chunk-LUAVB3CA.js";
5
5
 
6
6
  // src/run/fold.ts
7
7
  var FOLD_THRESHOLD = 2048;
@@ -49,7 +49,7 @@ function runHook(budgetMs, body, kind = "stop") {
49
49
  process.env.ALEXANDRIA_HOOK = "1";
50
50
  const cleanup = async () => {
51
51
  try {
52
- const { disposeEmbedder } = await import("./embedder-7Z4XNL6H.js");
52
+ const { disposeEmbedder } = await import("./embedder-JBYRHKR4.js");
53
53
  await disposeEmbedder();
54
54
  } catch {
55
55
  }