@ureck/alexandria 1.6.1 → 1.6.3

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.1
115
+ 1.6.3
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>
145
+
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
+ ```
98
168
 
99
- ### Search by meaning, not keywords
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.
194
299
 
195
- ### Deep project context (`ale scan`)
300
+ </details>
301
+
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,18 @@ 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
+ **Background reindex is single-flight.** If the index loses its vectors, the session-close hook rebuilds it in a detached, low-priority (`nice 10`) process — at most one at a time, guarded by `<vault>/.vault/reindex.lock` (holder pid; a dead or 3h-old holder is replaced). `ale reindex` and `ale doctor` respect the same lock, so two manual reindexes never run together. Notes indexed without the model (e.g. at session start) keep the existing vectors and are embedded incrementally later — no full rebuild. A full reindex of ~5,300 chunks takes ~6 min (e5-small q8, length-sorted batches).
399
+
400
+ </details>
401
+
402
+ <details>
403
+ <summary><b>🤖 Agents in detail & plugins</b></summary>
293
404
 
294
405
  ```bash
295
406
  ale agents # list with auto-detection (● = found on your machine)
@@ -299,11 +410,11 @@ ale agents cursor,gemini # just these
299
410
 
300
411
  | Agent | MCP config written | Hooks (auto capture + injection) | Per-project |
301
412
  |---|---|---|---|
302
- | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact | ✓ |
413
+ | Claude Code | `.mcp.json` / `claude mcp add` | `.claude/settings.json` — SessionStart · UserPromptSubmit · Stop · PreCompact · PreToolUse(Read) · PostToolUse(Bash) | ✓ |
303
414
  | Codex CLI | `~/.codex/config.toml` / `.codex/config.toml` | `.codex/hooks.json` — SessionStart · UserPromptSubmit · Stop · PreCompact ¹ | ✓ |
304
415
  | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | same file — SessionStart · BeforeAgent · AfterAgent · PreCompress | ✓ |
305
416
  | 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 | ✓ |
417
+ | OpenCode | `opencode.json` | plugin `.opencode/plugins/alexandria.js` — injects into the system prompt, folds bash output | ✓ |
307
418
  | Devin CLI (Cognition) | `.devin/mcp_config.local.json` | — | ✓ |
308
419
  | Cline | `cline_mcp_settings.json` (VS Code) | — | — |
309
420
  | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | — | ✓ |
@@ -318,9 +429,7 @@ ale agents cursor,gemini # just these
318
429
 
319
430
  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
431
 
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`):
432
+ **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
433
 
325
434
  ```bash
326
435
  npm i -g @ureck/alexandria
@@ -328,7 +437,10 @@ claude plugin marketplace add UreckChan/alexandria
328
437
  claude plugin install alexandria@alexandria
329
438
  ```
330
439
 
331
- ## How it works
440
+ </details>
441
+
442
+ <details>
443
+ <summary><b>⚙️ How it works</b></summary>
332
444
 
333
445
  ```
334
446
  AI agent session
@@ -352,7 +464,10 @@ AI agent session
352
464
  - **Deduplication**: near-identical prompts don't create new notes — they add `hits` (and climb the ranking).
353
465
  - **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
466
 
355
- ## Command reference
467
+ </details>
468
+
469
+ <details>
470
+ <summary><b>📋 Command reference</b></summary>
356
471
 
357
472
  | Command | What it does |
358
473
  |---|---|
@@ -366,7 +481,7 @@ AI agent session
366
481
  | `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
482
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
368
483
  | `ale audit` | Protocol health: plans without DoD, failures without lessons, orphan notes |
369
- | `ale stats` | Notes, connections, protocol metrics, estimated tokens saved |
484
+ | `ale stats` | Notes, connections, protocol metrics, measured savings (documents, folded output, no re-injection), estimated tokens saved |
370
485
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
371
486
  | `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
487
  | `ale reindex [--force]` | Reindex (incremental by default) |
@@ -374,7 +489,7 @@ AI agent session
374
489
  | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
375
490
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
376
491
  | `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 |
492
+ | `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
493
  | `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
494
  | `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
495
  | `ale code outline <file\|dir>` / `ale code symbol <file> <name>` | Code map: signatures without bodies / one symbol's body (`Class.method` works) |
@@ -385,25 +500,34 @@ AI agent session
385
500
 
386
501
  `alexandria` works as an alias of `ale`.
387
502
 
388
- ## Privacy & security
503
+ **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`.
504
+
505
+ </details>
506
+
507
+ <details>
508
+ <summary><b>🔒 Privacy & security</b></summary>
389
509
 
390
510
  - **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.**
511
+ - **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
512
  - **`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
513
  - 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`:
514
+ - **`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
515
  ```json
396
516
  "overrides": {
397
- "sharp": "^0.35.4"
517
+ "sharp": "^0.35.5"
398
518
  }
399
519
  ```
400
520
  (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
521
  - 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
522
 
403
- ## Support the project ☕
523
+ </details>
524
+
525
+ ---
526
+
527
+ <div align="center">
404
528
 
405
- Alexandria is free and open source. If it saves you tokens (and money), you can buy me a coffee:
529
+ **Free and open source.** If it saves you tokens (and money): **[☕ buymeacoffee.com/ureck](https://buymeacoffee.com/ureck)**
406
530
 
407
- **[☕ buymeacoffee.com/ureck](https://buymeacoffee.com/ureck)**
531
+ Built with 🏛 by **[Ureck](https://buymeacoffee.com/ureck)** — MIT License · [Changelog](https://github.com/UreckChan/alexandria/releases)
408
532
 
409
- Built with 🏛 by **[Ureck](https://buymeacoffee.com/ureck)** — MIT License.
533
+ </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
  }
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/lock.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var STALE_MS = 3 * 60 * 60 * 1e3;
7
+ function reindexLockPath(vault) {
8
+ return path.join(vault.cache, "reindex.lock");
9
+ }
10
+ function pidAlive(pid) {
11
+ if (!Number.isInteger(pid) || pid <= 0) return false;
12
+ try {
13
+ process.kill(pid, 0);
14
+ return true;
15
+ } catch (e) {
16
+ return e.code === "EPERM";
17
+ }
18
+ }
19
+ function reindexLockHolder(vault) {
20
+ try {
21
+ const file = reindexLockPath(vault);
22
+ const st = fs.statSync(file);
23
+ const pid = Number.parseInt(fs.readFileSync(file, "utf8").trim(), 10);
24
+ if (Date.now() - st.mtimeMs > STALE_MS) return null;
25
+ return pidAlive(pid) ? pid : null;
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+ function acquireReindexLock(vault, opts = {}) {
31
+ const pid = opts.pid ?? process.pid;
32
+ const file = reindexLockPath(vault);
33
+ fs.mkdirSync(vault.cache, { recursive: true });
34
+ for (let attempt = 0; attempt < 2; attempt++) {
35
+ try {
36
+ fs.writeFileSync(file, String(pid), { flag: "wx" });
37
+ return true;
38
+ } catch (e) {
39
+ if (e.code !== "EEXIST") return false;
40
+ }
41
+ let holder = null;
42
+ try {
43
+ holder = Number.parseInt(fs.readFileSync(file, "utf8").trim(), 10);
44
+ } catch {
45
+ continue;
46
+ }
47
+ if (holder === pid || opts.adoptFrom !== void 0 && holder === opts.adoptFrom) {
48
+ fs.writeFileSync(file, String(pid));
49
+ return true;
50
+ }
51
+ if (reindexLockHolder(vault) !== null) return false;
52
+ try {
53
+ fs.rmSync(file, { force: true });
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+ function transferReindexLock(vault, toPid, fromPid = process.pid) {
61
+ const file = reindexLockPath(vault);
62
+ try {
63
+ if (Number.parseInt(fs.readFileSync(file, "utf8").trim(), 10) === fromPid) {
64
+ fs.writeFileSync(file, String(toPid));
65
+ }
66
+ } catch {
67
+ }
68
+ }
69
+ function releaseReindexLock(vault, pid = process.pid) {
70
+ const file = reindexLockPath(vault);
71
+ try {
72
+ if (Number.parseInt(fs.readFileSync(file, "utf8").trim(), 10) === pid) fs.rmSync(file, { force: true });
73
+ } catch {
74
+ }
75
+ }
76
+
77
+ export {
78
+ reindexLockHolder,
79
+ acquireReindexLock,
80
+ transferReindexLock,
81
+ releaseReindexLock
82
+ };
@@ -55,15 +55,19 @@ async function embed(texts, kind = "passage", onProgress) {
55
55
  if (texts.length === 0) return [];
56
56
  const pipe = await getEmbedder(onProgress);
57
57
  const prefixed = texts.map((t) => `${kind}: ${t}`);
58
- const rows = [];
59
- const BATCH = 16;
60
- for (let i = 0; i < prefixed.length; i += BATCH) {
61
- const batch = prefixed.slice(i, i + BATCH);
62
- const out = await pipe(batch, { pooling: "mean", normalize: true });
58
+ const rows = new Array(prefixed.length);
59
+ const order = prefixed.map((_, i) => i).sort((a, b) => prefixed[a].length - prefixed[b].length);
60
+ const BATCH = 8;
61
+ for (let i = 0; i < order.length; i += BATCH) {
62
+ const ids = order.slice(i, i + BATCH);
63
+ const out = await pipe(
64
+ ids.map((k) => prefixed[k]),
65
+ { pooling: "mean", normalize: true }
66
+ );
63
67
  const dim = out.dims[out.dims.length - 1];
64
- for (let j = 0; j < batch.length; j++) {
65
- rows.push(out.data.slice(j * dim, (j + 1) * dim));
66
- }
68
+ ids.forEach((k, j) => {
69
+ rows[k] = out.data.slice(j * dim, (j + 1) * dim);
70
+ });
67
71
  }
68
72
  return rows;
69
73
  }
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  hybridSearch
4
- } from "./chunk-47S5I3D3.js";
4
+ } from "./chunk-WSKQM5XI.js";
5
5
  import {
6
6
  slugify
7
- } from "./chunk-44QPE5IM.js";
7
+ } from "./chunk-DELBYC3Y.js";
8
8
  import {
9
9
  convertFile,
10
10
  htmlToMarkdown
@@ -20,7 +20,7 @@ import {
20
20
  dot,
21
21
  embed,
22
22
  modelPresent
23
- } from "./chunk-EDYBSJSS.js";
23
+ } from "./chunk-LUAVB3CA.js";
24
24
 
25
25
  // src/core/planning.ts
26
26
  var MAX_ITEMS = 2;
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  isoDate,
4
4
  supersedeNote
5
- } from "./chunk-44QPE5IM.js";
5
+ } from "./chunk-DELBYC3Y.js";
6
6
  import {
7
7
  charsToTokens
8
8
  } from "./chunk-X4V6SYYA.js";
@@ -13,7 +13,7 @@ import {
13
13
  MODEL_ID,
14
14
  dot,
15
15
  modelCacheDir
16
- } from "./chunk-EDYBSJSS.js";
16
+ } from "./chunk-LUAVB3CA.js";
17
17
 
18
18
  // src/core/clean.ts
19
19
  import fs from "fs";
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-44QPE5IM.js";
4
+ } from "./chunk-DELBYC3Y.js";
5
5
  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/search.ts
12
12
  import MiniSearch from "minisearch";
package/dist/cli.js CHANGED
@@ -1,7 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  serveGraph
4
- } from "./chunk-SSTG2NOO.js";
4
+ } from "./chunk-AAHJNPLB.js";
5
+ import {
6
+ acquireReindexLock,
7
+ reindexLockHolder,
8
+ releaseReindexLock
9
+ } from "./chunk-KRMDWHCZ.js";
5
10
  import {
6
11
  architectBlock,
7
12
  distDir,
@@ -24,11 +29,11 @@ import {
24
29
  serverCommand,
25
30
  symbolSource,
26
31
  unregisterHooks
27
- } from "./chunk-YNCL5JSF.js";
32
+ } from "./chunk-MKGNA7ZC.js";
28
33
  import {
29
34
  hybridSearch,
30
35
  protocolChain
31
- } from "./chunk-47S5I3D3.js";
36
+ } from "./chunk-WSKQM5XI.js";
32
37
  import {
33
38
  ARCHIVE_DIR,
34
39
  applyClean,
@@ -36,14 +41,14 @@ import {
36
41
  markCleaned,
37
42
  planClean,
38
43
  searchArchive
39
- } from "./chunk-WSVNMMNN.js";
44
+ } from "./chunk-VCVBX3VT.js";
40
45
  import {
41
46
  VaultIndex,
42
47
  createNote,
43
48
  slugify,
44
49
  supersedeNote,
45
50
  upsertNote
46
- } from "./chunk-44QPE5IM.js";
51
+ } from "./chunk-DELBYC3Y.js";
47
52
  import {
48
53
  formatOf
49
54
  } from "./chunk-NUG7HLOU.js";
@@ -53,7 +58,7 @@ import {
53
58
  saveRun,
54
59
  shouldFoldOutput,
55
60
  showRun
56
- } from "./chunk-OGVWOBYH.js";
61
+ } from "./chunk-EVF6HDVH.js";
57
62
  import {
58
63
  logFold,
59
64
  readSessionUsage,
@@ -80,7 +85,7 @@ import {
80
85
  embed,
81
86
  getEmbedder,
82
87
  modelPresent
83
- } from "./chunk-EDYBSJSS.js";
88
+ } from "./chunk-LUAVB3CA.js";
84
89
 
85
90
  // src/cli.ts
86
91
  import fs7 from "fs";
@@ -855,8 +860,83 @@ function run(script, payload, timeoutMs) {
855
860
  });
856
861
  }
857
862
 
858
- // Solo export default: OpenCode registra CADA funci\xF3n exportada como plugin.
859
- const AlexandriaPlugin = async ({ directory }) => {
863
+ // Pliega una salida grande de shell; devuelve '' si no conviene o falla.
864
+ function fold(output, command, exit, cwd) {
865
+ if (typeof output !== 'string' || output.length <= 2048) return Promise.resolve('');
866
+ return new Promise((resolve) => {
867
+ const child = execFile('node', [CLI, 'run', '--stdin', '--command', command, '--exit', String(exit)], { cwd, timeout: 8000, windowsHide: true, maxBuffer: 1 << 20 }, (_e, stdout) => {
868
+ const folded = typeof stdout === 'string' ? stdout.trim() : '';
869
+ resolve(folded && folded.length < output.length ? folded : '');
870
+ });
871
+ child.stdin?.end(output);
872
+ });
873
+ }
874
+
875
+ // \u2500\u2500 OpenCode 2 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
876
+ async function setup(ctx) {
877
+ const cwd = ctx.location.directory;
878
+ const digest = new Map(); // sessionID \u2192 contexto de inicio
879
+ const turn = new Map(); // sessionID \u2192 contexto del prompt actual
880
+ const lastPrompt = new Map();
881
+
882
+ // V2 no tiene hook de inicio de sesi\xF3n: el digest se pide en el primer prompt.
883
+ await ctx.session.hook('prompt', async (event) => {
884
+ try {
885
+ const id = event.sessionID;
886
+ const prompt = String(event.prompt?.text ?? '').trim();
887
+ if (!prompt) return;
888
+ lastPrompt.set(id, prompt);
889
+ if (!digest.has(id)) digest.set(id, await run(SCRIPTS.session, { session_id: id, cwd, source: 'startup' }, 15000));
890
+ turn.set(id, await run(SCRIPTS.prompt, { session_id: id, cwd, prompt }, 8000));
891
+ } catch {
892
+ /* Alexandria jam\xE1s rompe la sesi\xF3n */
893
+ }
894
+ });
895
+
896
+ await ctx.session.hook('context', (event) => {
897
+ for (const text of [digest.get(event.sessionID), turn.get(event.sessionID)]) {
898
+ if (text) event.system.push({ type: 'text', text });
899
+ }
900
+ });
901
+
902
+ await ctx.tool.hook('execute.after', async (event) => {
903
+ try {
904
+ if (event.tool !== 'shell' && event.tool !== 'bash') return;
905
+ const result = event.result;
906
+ const output = result?.output?.output;
907
+ const exit = Number(result?.output?.exitCode ?? result?.metadata?.exit ?? 0) || 0;
908
+ const folded = await fold(output, String(event.input?.command ?? ''), exit, cwd);
909
+ if (!folded) return;
910
+ result.output.output = folded;
911
+ for (const part of result.content ?? []) {
912
+ if (part?.type === 'text' && part.text === output) part.text = folded;
913
+ }
914
+ } catch {
915
+ /* sin plegado: la salida original sigue intacta */
916
+ }
917
+ });
918
+
919
+ const abort = new AbortController();
920
+ void (async () => {
921
+ for await (const event of ctx.event.subscribe({ signal: abort.signal })) {
922
+ const sessionID = event.data?.sessionID;
923
+ // solo las sesiones que pasaron por esta instancia (los eventos son globales)
924
+ if (event.type !== 'session.execution.succeeded' || !lastPrompt.has(sessionID)) continue;
925
+ try {
926
+ const messages = await ctx.session.context({ sessionID });
927
+ const last = [...messages].reverse().find((m) => m.type === 'assistant' && m.content?.some((c) => c.type === 'text' && c.text));
928
+ const answer = last?.content.filter((c) => c.type === 'text').map((c) => c.text).join('\\n').trim();
929
+ if (answer) await run(SCRIPTS.stop, { session_id: sessionID, cwd, prompt: lastPrompt.get(sessionID), last_assistant_message: answer }, 25000);
930
+ } catch {
931
+ /* sin captura este turno */
932
+ }
933
+ }
934
+ })().catch(() => {});
935
+ return () => abort.abort();
936
+ }
937
+
938
+ // \u2500\u2500 OpenCode 1.x \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
939
+ const server = async ({ directory }) => {
860
940
  const digest = new Map(); // sessionID \u2192 contexto de inicio
861
941
  const turn = new Map(); // sessionID \u2192 contexto del prompt actual
862
942
  const lastPrompt = new Map();
@@ -901,16 +981,10 @@ const AlexandriaPlugin = async ({ directory }) => {
901
981
  // Aqu\xED s\xED cubre comandos que fallan: OpenCode deja reescribir output.output.
902
982
  'tool.execute.after': async (input, output) => {
903
983
  try {
904
- if (input?.tool !== 'bash' || typeof output?.output !== 'string' || output.output.length <= 2048) return;
905
- const command = String(input.args?.command ?? '');
984
+ if (input?.tool !== 'bash') return;
906
985
  const exit = Number(output.metadata?.exit ?? output.metadata?.exitCode ?? 0) || 0;
907
- const folded = await new Promise((resolve) => {
908
- const child = execFile('node', [CLI, 'run', '--stdin', '--command', command, '--exit', String(exit)], { cwd: directory, timeout: 8000, windowsHide: true, maxBuffer: 1 << 20 }, (_e, stdout) =>
909
- resolve(typeof stdout === 'string' ? stdout.trim() : '')
910
- );
911
- child.stdin?.end(output.output);
912
- });
913
- if (folded && folded.length < output.output.length) output.output = folded;
986
+ const folded = await fold(output.output, String(input.args?.command ?? ''), exit, directory);
987
+ if (folded) output.output = folded;
914
988
  } catch {
915
989
  /* sin plegado: la salida original sigue intacta */
916
990
  }
@@ -925,7 +999,8 @@ const AlexandriaPlugin = async ({ directory }) => {
925
999
  };
926
1000
  };
927
1001
 
928
- export default AlexandriaPlugin;
1002
+ // Solo export default: OpenCode registra CADA funci\xF3n exportada como plugin.
1003
+ export default { id: 'alexandria', setup, server };
929
1004
  `;
930
1005
  }
931
1006
 
@@ -1980,14 +2055,24 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1980
2055
  program.command("reindex").description("Reindexar la b\xF3veda (incremental; --force para todo)").option("--force", "reindexar todo desde cero").action(async (opts) => {
1981
2056
  const vault = getVault();
1982
2057
  ensureVaultStructure(vault);
1983
- await downloadModelIfMissing();
1984
- const idx = VaultIndex.load(vault);
1985
- const res = await idx.refresh(modelPresent(), opts.force);
1986
- console.log(
1987
- pc.green(
1988
- `\u2713 ${res.changed} notas reindexadas, ${res.removed} eliminadas \u2014 ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`
1989
- )
1990
- );
2058
+ const parent = Number.parseInt(process.env.ALEXANDRIA_REINDEX_PARENT ?? "", 10);
2059
+ if (!acquireReindexLock(vault, { adoptFrom: Number.isNaN(parent) ? void 0 : parent })) {
2060
+ console.log(pc.yellow(`\u26A0 Ya hay un reindex en curso (pid ${reindexLockHolder(vault) ?? "?"}) \u2014 espera a que termine`));
2061
+ process.exitCode = 1;
2062
+ return;
2063
+ }
2064
+ try {
2065
+ await downloadModelIfMissing();
2066
+ const idx = VaultIndex.load(vault);
2067
+ const res = await idx.refresh(modelPresent(), opts.force);
2068
+ console.log(
2069
+ pc.green(
2070
+ `\u2713 ${res.changed} notas reindexadas, ${res.removed} eliminadas \u2014 ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`
2071
+ )
2072
+ );
2073
+ } finally {
2074
+ releaseReindexLock(vault);
2075
+ }
1991
2076
  });
1992
2077
  program.command("graph").description("Visor del grafo de conocimiento (local, estilo Obsidian/Graphify)").option("--out <file>", "escribir HTML autocontenido en vez de servir").option("--no-open", "no abrir el navegador").action(async (opts) => {
1993
2078
  const { vault } = await ensureReady();
@@ -2169,11 +2254,20 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
2169
2254
  } else if (idx.emb) {
2170
2255
  console.log(`${pc.green("\u2713")} Embeddings alineados (${idx.meta.chunks.length} chunks)`);
2171
2256
  } else if (idx.meta.chunks.length > 0 && model) {
2172
- console.log(pc.yellow(`\u26A0 \xCDndice SIN vectores (${idx.meta.chunks.length} chunks) \u2014 b\xFAsqueda degradada a keyword. Reconstruyendo\u2026`));
2173
- const rebuilt = await idx.refresh(true, true);
2174
- console.log(
2175
- idx.emb ? `${pc.green("\u2713")} \xCDndice sem\xE1ntico reconstruido (${rebuilt.changed} notas)` : pc.yellow("\u26A0 No se pudo reconstruir \u2014 corre `ale reindex --force` y revisa el modelo")
2176
- );
2257
+ const holder = reindexLockHolder(vault);
2258
+ if (holder !== null || !acquireReindexLock(vault)) {
2259
+ console.log(pc.yellow(`\u26A0 \xCDndice SIN vectores \u2014 ya hay un reindex en curso (pid ${holder ?? "?"}); se repara solo al terminar`));
2260
+ } else {
2261
+ try {
2262
+ console.log(pc.yellow(`\u26A0 \xCDndice SIN vectores (${idx.meta.chunks.length} chunks) \u2014 b\xFAsqueda degradada a keyword. Reconstruyendo\u2026`));
2263
+ const rebuilt = await idx.refresh(true, true);
2264
+ console.log(
2265
+ idx.emb ? `${pc.green("\u2713")} \xCDndice sem\xE1ntico reconstruido (${rebuilt.changed} notas)` : pc.yellow("\u26A0 No se pudo reconstruir \u2014 corre `ale reindex --force` y revisa el modelo")
2266
+ );
2267
+ } finally {
2268
+ releaseReindexLock(vault);
2269
+ }
2270
+ }
2177
2271
  }
2178
2272
  try {
2179
2273
  const name = path7.basename(cwd);
@@ -9,7 +9,7 @@ import {
9
9
  getEmbedder,
10
10
  modelCacheDir,
11
11
  modelPresent
12
- } from "./chunk-EDYBSJSS.js";
12
+ } from "./chunk-LUAVB3CA.js";
13
13
  export {
14
14
  DIM,
15
15
  MODEL_ID,
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runHook
4
- } from "../chunk-WVZQGLRI.js";
4
+ } from "../chunk-JJ62U6UP.js";
5
5
  import {
6
6
  saveRun,
7
7
  shouldFoldOutput
8
- } from "../chunk-OGVWOBYH.js";
8
+ } from "../chunk-EVF6HDVH.js";
9
9
  import {
10
10
  logFold
11
11
  } from "../chunk-X4V6SYYA.js";
@@ -14,7 +14,7 @@ import {
14
14
  toggleEnabled,
15
15
  vaultExists
16
16
  } from "../chunk-YICWI3U3.js";
17
- import "../chunk-EDYBSJSS.js";
17
+ import "../chunk-LUAVB3CA.js";
18
18
 
19
19
  // src/hooks/on-bash.ts
20
20
  runHook(3e3, async (input) => {
@@ -8,14 +8,14 @@ import {
8
8
  projectName,
9
9
  runHook,
10
10
  truncate
11
- } from "../chunk-WVZQGLRI.js";
11
+ } from "../chunk-JJ62U6UP.js";
12
12
  import {
13
13
  hybridSearch
14
- } from "../chunk-47S5I3D3.js";
14
+ } from "../chunk-WSKQM5XI.js";
15
15
  import {
16
16
  createNote,
17
17
  touchNote
18
- } from "../chunk-44QPE5IM.js";
18
+ } from "../chunk-DELBYC3Y.js";
19
19
  import {
20
20
  logInjection
21
21
  } from "../chunk-X4V6SYYA.js";
@@ -25,7 +25,7 @@ import {
25
25
  toggleEnabled,
26
26
  vaultExists
27
27
  } from "../chunk-YICWI3U3.js";
28
- import "../chunk-EDYBSJSS.js";
28
+ import "../chunk-LUAVB3CA.js";
29
29
 
30
30
  // src/hooks/on-prompt.ts
31
31
  import fs from "fs";
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runHook
4
- } from "../chunk-WVZQGLRI.js";
4
+ } from "../chunk-JJ62U6UP.js";
5
5
  import {
6
6
  PDF_TOKENS_PER_PAGE,
7
7
  formatOf
@@ -8,10 +8,10 @@ import {
8
8
  projectName,
9
9
  runHook,
10
10
  truncate
11
- } from "../chunk-WVZQGLRI.js";
11
+ } from "../chunk-JJ62U6UP.js";
12
12
  import {
13
13
  VaultIndex
14
- } from "../chunk-44QPE5IM.js";
14
+ } from "../chunk-DELBYC3Y.js";
15
15
  import {
16
16
  logInjection
17
17
  } from "../chunk-X4V6SYYA.js";
@@ -21,7 +21,7 @@ import {
21
21
  toggleEnabled,
22
22
  vaultExists
23
23
  } from "../chunk-YICWI3U3.js";
24
- import "../chunk-EDYBSJSS.js";
24
+ import "../chunk-LUAVB3CA.js";
25
25
 
26
26
  // src/hooks/on-session-start.ts
27
27
  import fs from "fs";
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ acquireReindexLock,
4
+ releaseReindexLock,
5
+ transferReindexLock
6
+ } from "../chunk-KRMDWHCZ.js";
2
7
  import {
3
8
  buildCapsule,
4
9
  extractSession,
@@ -9,15 +14,15 @@ import {
9
14
  projectName,
10
15
  runHook,
11
16
  truncate
12
- } from "../chunk-WVZQGLRI.js";
17
+ } from "../chunk-JJ62U6UP.js";
13
18
  import {
14
19
  autoCleanDue,
15
20
  markCleaned
16
- } from "../chunk-WSVNMMNN.js";
21
+ } from "../chunk-VCVBX3VT.js";
17
22
  import {
18
23
  VaultIndex,
19
24
  appendToNote
20
- } from "../chunk-44QPE5IM.js";
25
+ } from "../chunk-DELBYC3Y.js";
21
26
  import "../chunk-X4V6SYYA.js";
22
27
  import {
23
28
  ensureVaultStructure,
@@ -26,11 +31,12 @@ import {
26
31
  toggleEnabled,
27
32
  vaultExists
28
33
  } from "../chunk-YICWI3U3.js";
29
- import "../chunk-EDYBSJSS.js";
34
+ import "../chunk-LUAVB3CA.js";
30
35
 
31
36
  // src/hooks/on-stop.ts
32
37
  import fs from "fs";
33
38
  import path from "path";
39
+ import os from "os";
34
40
  import { spawn } from "child_process";
35
41
  import { fileURLToPath } from "url";
36
42
  runHook(25e3, async (input) => {
@@ -96,23 +102,36 @@ function maybeCleanInBackground(vault) {
96
102
  } catch {
97
103
  }
98
104
  }
99
- async function maybeRebuildInBackground(vault) {
105
+ async function maybeRebuildInBackground(vault, cli = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.js")) {
106
+ let locked = false;
100
107
  try {
101
108
  if (!toggleEnabled("index.autoRebuild")) return;
102
109
  const idx = VaultIndex.load(vault);
103
110
  if (!idx.needsRebuild() && !idx.isDegraded()) return;
104
- const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.js");
105
111
  if (!fs.existsSync(cli)) return;
112
+ if (!acquireReindexLock(vault)) return;
113
+ locked = true;
106
114
  const child = spawn(process.execPath, [cli, "--vault", vault.root, "reindex", "--force"], {
107
115
  detached: true,
108
116
  stdio: "ignore",
109
117
  windowsHide: true,
110
118
  // Windows: sin esto puede parpadear una consola al cerrar sesión
111
- env: { ...process.env, ALEXANDRIA_HOOK: "" }
112
- // proceso CLI: sí puede reconstruir
119
+ // proceso CLI: sí puede reconstruir; ALEXANDRIA_REINDEX_PARENT le permite adoptar el candado
120
+ env: { ...process.env, ALEXANDRIA_HOOK: "", ALEXANDRIA_REINDEX_PARENT: String(process.pid) }
113
121
  });
122
+ if (!child.pid) {
123
+ releaseReindexLock(vault);
124
+ return;
125
+ }
126
+ transferReindexLock(vault, child.pid);
127
+ locked = false;
128
+ try {
129
+ os.setPriority(child.pid, 10);
130
+ } catch {
131
+ }
114
132
  child.unref();
115
133
  } catch {
134
+ if (locked) releaseReindexLock(vault);
116
135
  }
117
136
  }
118
137
  export {
@@ -10,13 +10,13 @@ import {
10
10
  planQualityHints,
11
11
  readDoc,
12
12
  symbolSource
13
- } from "../chunk-YNCL5JSF.js";
13
+ } from "../chunk-MKGNA7ZC.js";
14
14
  import {
15
15
  hybridSearch
16
- } from "../chunk-47S5I3D3.js";
16
+ } from "../chunk-WSKQM5XI.js";
17
17
  import {
18
18
  searchArchive
19
- } from "../chunk-WSVNMMNN.js";
19
+ } from "../chunk-VCVBX3VT.js";
20
20
  import {
21
21
  VaultIndex,
22
22
  createNote,
@@ -24,18 +24,18 @@ import {
24
24
  slugify,
25
25
  supersedeNote,
26
26
  upsertNote
27
- } from "../chunk-44QPE5IM.js";
27
+ } from "../chunk-DELBYC3Y.js";
28
28
  import "../chunk-NUG7HLOU.js";
29
29
  import {
30
30
  showRun
31
- } from "../chunk-OGVWOBYH.js";
31
+ } from "../chunk-EVF6HDVH.js";
32
32
  import "../chunk-X4V6SYYA.js";
33
33
  import {
34
34
  ensureVaultStructure,
35
35
  resolveVault,
36
36
  toggleEnabled
37
37
  } from "../chunk-YICWI3U3.js";
38
- import "../chunk-EDYBSJSS.js";
38
+ import "../chunk-LUAVB3CA.js";
39
39
 
40
40
  // src/mcp/server.ts
41
41
  import path from "path";
@@ -4,9 +4,9 @@ import {
4
4
  renderGraphHtml,
5
5
  serveGraph,
6
6
  writeStaticGraph
7
- } from "./chunk-SSTG2NOO.js";
8
- import "./chunk-44QPE5IM.js";
9
- import "./chunk-EDYBSJSS.js";
7
+ } from "./chunk-AAHJNPLB.js";
8
+ import "./chunk-DELBYC3Y.js";
9
+ import "./chunk-LUAVB3CA.js";
10
10
  export {
11
11
  buildGraphData,
12
12
  renderGraphHtml,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ureck/alexandria",
3
- "version": "1.6.1",
3
+ "version": "1.6.3",
4
4
  "description": "Alexandria — bóveda de conocimiento local para agentes de IA (Claude Code, Codex, Gemini CLI, Cursor, OpenCode y más): captura automática por hooks, búsqueda semántica offline y grafo estilo Obsidian. Ahorra tokens inyectando solo el contexto relevante.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -47,13 +47,13 @@
47
47
  "dependencies": {
48
48
  "@huggingface/transformers": "^4.3.2",
49
49
  "@modelcontextprotocol/sdk": "^1.32.2",
50
- "commander": "^15.0.0",
50
+ "commander": "^15.1.0",
51
51
  "gray-matter": "^4.0.3",
52
52
  "jszip": "^3.10.2",
53
53
  "mammoth": "^1.13.0",
54
54
  "minisearch": "^7.1.2",
55
55
  "picocolors": "^1.1.1",
56
- "turndown": "^7.2.4",
56
+ "turndown": "^7.2.5",
57
57
  "unpdf": "^1.9.1",
58
58
  "zod": "^4.6.7"
59
59
  },
@@ -62,12 +62,12 @@
62
62
  "uuid": "^11.1.1"
63
63
  },
64
64
  "devDependencies": {
65
- "@types/node": "^22.20.5",
65
+ "@types/node": "^22.20.7",
66
66
  "@types/turndown": "^5.0.6",
67
67
  "exceljs": "^4.4.0",
68
68
  "tsup": "^9.0.0",
69
69
  "typescript": "^5.7.3",
70
- "vitest": "^5.0.5"
70
+ "vitest": "^5.1.2"
71
71
  },
72
72
  "author": "Ureck <urielgomezbecerril@gmail.com>",
73
73
  "publishConfig": {