@ureck/alexandria 0.4.0 → 0.5.1

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,26 +1,49 @@
1
1
  # 🏛️ Alexandria
2
2
 
3
- > Bóveda de conocimiento local para tus agentes de IA — ahorra tokens, recuerda entre sesiones, conecta tus ideas.
3
+ > A local knowledge vault for your AI agents — saves tokens, remembers across sessions, and turns every model into a disciplined engineer.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/%40ureck%2Falexandria)](https://www.npmjs.com/package/@ureck/alexandria)
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
7
- [![Buy Me a Coffee](https://img.shields.io/badge/☕_Invítame_un_café-ureck-yellow)](https://buymeacoffee.com/ureck)
7
+ [![Buy Me a Coffee](https://img.shields.io/badge/☕_Buy_me_a_coffee-ureck-yellow)](https://buymeacoffee.com/ureck)
8
8
 
9
- Alexandria captura automáticamente tus prompts y sesiones de IA, busca en ese conocimiento **antes** de gastar tokens, y conecta todo en un grafo estilo Obsidian. **100% local**: sin base de datos, sin API keys, sin telemetría, sin costo.
9
+ 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.
10
10
 
11
- Funciona con los agentes más usados vía MCP: **Claude Code · Cursor · OpenCode · Windsurf · Cline · Codex CLI · Gemini CLI · VS Code (Copilot) · OpenClaw · Hermes Agent**.
11
+ Works with the most popular agents via MCP: **Claude Code · Cursor · OpenCode · Windsurf · Cline · Codex CLI · Gemini CLI · VS Code (Copilot) · OpenClaw · Hermes Agent**.
12
12
 
13
- ## ¿Por qué?
13
+ ## Why?
14
14
 
15
- Cada sesión nueva de un agente de IA empieza de cero: re-explora tu código, re-deriva decisiones que ya tomaste, re-consume los mismos tokens. Alexandria rompe ese ciclo:
15
+ 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:
16
16
 
17
- - **Ahorra tokens**: cada prompt dispara una búsqueda semántica local (<100ms) que inyecta al agente solo los fragmentos relevantes — en vez de releer archivos completos.
18
- - **Cero re-análisis entre sesiones**: al abrir sesión, el agente recibe el mapa del proyecto y el conocimiento acumulado.
19
- - **Memoria de soluciones**: si un prompt casi idéntico ya se resolvió antes, inyecta esa solución — el agente no la re-deriva.
20
- - **Es un vault de Obsidian**: markdown puro con `[[wikilinks]]`. Ábrelo en Obsidian cuando quieras.
21
- - **Multiplataforma**: Windows, macOS, Linux · Node, Bun o Deno. Pure JS, sin dependencias nativas que fallen al instalar.
17
+ - **Saves tokens**: every prompt triggers a local semantic search (<100ms) that injects only the relevant fragments — instead of re-reading whole files.
18
+ - **Zero re-analysis between sessions**: on session start, the agent receives the project map and all accumulated knowledge.
19
+ - **Solution memory**: if a nearly identical prompt was already solved, the previous solution is injected — the agent doesn't re-derive it.
20
+ - **Infinite context, nothing is ever lost**: old noise gets archived, never deleted — everything stays searchable forever.
21
+ - **It's a valid Obsidian vault**: plain markdown with `[[wikilinks]]`. Open it in Obsidian anytime.
22
+ - **Cross-platform**: Windows, macOS, Linux · Node, Bun or Deno. Pure JS — no native dependencies to break your install.
22
23
 
23
- ## Instalación
24
+ ## The Alexandria Protocol
25
+
26
+ 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:
27
+
28
+ > **Plan → Execute one task → Verify with evidence → (on failure: reuse past lessons) → Extract the lesson**
29
+
30
+ 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:
31
+
32
+ | MCP tool | What the agent does with it | Token payoff |
33
+ |---|---|---|
34
+ | `plan_create(title, goal, dod, tasks)` | Writes a plan note with a **Definition of Done** and numbered tasks before touching code | No wandering; open plans are re-injected next session so work is resumed, not repeated |
35
+ | `task_verify(plan, task, passed, evidence)` | Records the real verdict of each task (test/build output, compacted) | "✅ 12/12 passed" (5 tokens) instead of a 500-line log; on failure it automatically surfaces **past lessons** that match |
36
+ | `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 |
37
+
38
+ 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:
39
+
40
+ ```bash
41
+ ale config set protocol false # classic vault only
42
+ ale config set protocol true # back on
43
+ ale init --no-protocol # install without it
44
+ ```
45
+
46
+ ## Install
24
47
 
25
48
  ```bash
26
49
  # npm (Node ≥ 20)
@@ -31,168 +54,162 @@ bun add -g @ureck/alexandria
31
54
 
32
55
  # deno
33
56
  deno install -grA -n ale npm:@ureck/alexandria/ale
34
- # (si Deno se queja de "minimum dependency date": agrega --minimum-dependency-age=0)
57
+ # (if Deno complains about "minimum dependency date", add --minimum-dependency-age=0)
35
58
  ```
36
59
 
37
- Confirma que quedó instalado:
60
+ Verify:
38
61
 
39
62
  ```bash
40
63
  $ ale --version
41
- 0.4.0
64
+ 0.5.1
42
65
  ```
43
66
 
44
- ## Primeros pasos
67
+ ## Getting started
45
68
 
46
- Un solo comando instala todo (modelo de embeddings ~130MB una única vez, hooks, MCP, índice):
69
+ One command installs everything (embedding model ~130MB downloaded once, hooks, MCP registration, index):
47
70
 
48
71
  ```bash
49
- # Global — una bóveda compartida para todas tus sesiones (~/Alexandria)
72
+ # Global — one shared vault for all your sessions (~/Alexandria)
50
73
  ale init
51
74
 
52
- # Por proyecto — bóveda DENTRO del repo (./Alexandria)
53
- cd mi-proyecto
75
+ # Per project — vault INSIDE the repo (./Alexandria)
76
+ cd my-project
54
77
  ale init --project
55
78
 
56
- # Con tu vault de Obsidian existente
57
- ale init --path ~/Documents/MiVaultObsidian
79
+ # Point at an existing Obsidian vault
80
+ ale init --path ~/Documents/MyObsidianVault
58
81
 
59
- # Eligiendo en qué agentes registrar el MCP
60
- ale init --agents all # todos los soportados
61
- ale init --agents claude,cursor,opencode # solo esos
62
- # (sin --agents: Claude Code + los que detecte instalados)
82
+ # Choose which agents get the MCP server
83
+ ale init --agents all # every supported agent
84
+ ale init --agents claude,cursor,opencode # just these
85
+ # (without --agents: Claude Code + whatever is detected on your machine)
63
86
  ```
64
87
 
65
- <details>
66
- <summary>Salida esperada de <code>ale init --project</code></summary>
88
+ `ale init --project` also, automatically:
89
+ - adds the vault to your `.gitignore` (personal knowledge, not repo code),
90
+ - **scans the project** (stack from package.json, npm scripts, folder structure, README excerpt) into an initial `Map - <project>` note — context from the very first session,
91
+ - asks *"Configure Claude to use Alexandria automatically?"* and writes the usage rules into `CLAUDE.md` (`--auto` / `--manual` to skip the question).
67
92
 
68
- ```
69
- ▄▀█ █░░ █▀▀ ▀▄▀ ▄▀█ █▄░█ █▀▄ █▀█ █ ▄▀█
70
- █▀█ █▄▄ ██▄ █░█ █▀█ █░▀█ █▄▀ █▀▄ █ █▀█
71
- 🏛 Bóveda de conocimiento local · creada por Ureck
72
-
73
- Instalación por proyecto
74
-
75
- ✓ Bóveda en /Users/tu/mi-proyecto/Alexandria (vault Obsidian válido)
76
- ✓ Config del proyecto: /Users/tu/mi-proyecto/.vault.json
77
- ✓ Hooks registrados en /Users/tu/mi-proyecto/.claude/settings.json
78
- SessionStart (digest) · UserPromptSubmit (contexto+captura) · Stop/PreCompact (sesiones)
79
- ✓ MCP → Claude Code (/Users/tu/mi-proyecto/.mcp.json)
80
- ↓ Descargando modelo de embeddings (una sola vez)…
81
- ✓ Modelo listo (búsqueda semántica activada)
82
- ✓ Índice: 0 notas, 0 conexiones
83
-
84
- ✅ Listo. Abre una sesión de tu agente y todo funciona solo — nada que reconectar nunca.
85
- ```
86
-
87
- </details>
88
-
89
- Después de `init` no hay nada que reconectar, nunca. Importante: los hooks cargan **al arrancar** una sesión — abre una sesión *nueva* de tu agente en esa carpeta (una que ya estaba abierta no los verá). Desde ahí, cada prompt busca en la bóveda antes de gastar tokens y cada cierre de sesión guarda lo aprendido.
90
-
91
- > `ale init --project` también agrega la bóveda a tu `.gitignore` automáticamente, escanea el proyecto (stack, estructura, comandos → mapa inicial) y te ofrece configurar en `CLAUDE.md` que Claude use Alexandria por default en cada sesión (`--auto` / `--manual` para decidir sin pregunta).
93
+ 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).
92
94
 
93
- ## Uso diario — ejemplos
95
+ ## Daily usage — examples
94
96
 
95
- ### Buscar conocimiento (semántico + keyword)
96
-
97
- Busca por **significado**, no por palabras exactas:
97
+ ### Search by meaning, not keywords
98
98
 
99
99
  ```bash
100
- $ ale search como publico mi app en la tienda de google
100
+ $ ale search how do I publish my app to the google store
101
101
 
102
- Despliegue de Flutter release (Alexandria/notes/2026-07-09-despliegue.md, note) ● relevancia alta
103
- Para publicar en Play Store: keystore fuera de git, key.properties,
104
- flutter build appbundle. Firmar siempre con la clave de producción.
102
+ Flutter release deployment (Alexandria/notes/2026-07-09-deploy.md, note) ● high relevance
103
+ To publish on Play Store: keystore outside git, key.properties,
104
+ flutter build appbundle. Always sign with the production key.
105
105
  ```
106
106
 
107
- Nota que la query no comparte ni una palabra clave con la nota ("tienda de google" → "Play Store"). Más ejemplos:
107
+ The query shares zero keywords with the note ("google store" → "Play Store"). More:
108
108
 
109
109
  ```bash
110
- ale search error de cors en el api # encuentra tu solución de hace meses
111
- ale search "decisión de arquitectura" -k 10 # más resultados
112
- ale search autenticacion --expand # incluye notas CONECTADAS a los resultados (grafo)
110
+ ale search cors error in the api # finds your fix from months ago
111
+ ale search "architecture decision" -k 10
112
+ ale search auth --expand # also pulls notes CONNECTED to the results (graph)
113
113
  ```
114
114
 
115
- La etiqueta `● relevancia alta/media/baja` es relativa al mejor resultado — confía en ella más que en el número.
115
+ The `● high/medium/low relevance` label is relative to the best hit — trust it over the raw number.
116
116
 
117
- ### Guardar notas manualmente
117
+ ### Save notes manually
118
118
 
119
119
  ```bash
120
- # Nota rápida
121
- ale add "Configuración de Prisma" -c "Singleton en src/lib/prisma.ts con globalThis" -t "prisma,db"
120
+ # Quick note
121
+ ale add "Prisma setup" -c "Singleton in src/lib/prisma.ts using globalThis" -t "prisma,db"
122
+
123
+ # From a file in your project (or a pipe)
124
+ ale add "Q3 architecture decisions" --file DECISIONS.md
125
+ cat DECISIONS.md | ale add "Q3 architecture decisions"
126
+
127
+ # With [[wikilinks]] to connect knowledge
128
+ ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
129
+ ```
122
130
 
123
- # Desde un archivo o pipe
124
- cat DECISIONES.md | ale add "Decisiones de arquitectura Q3"
131
+ (Automatic capture via hooks already does this in every Claude Code session — `add` is for extra knowledge.)
125
132
 
126
- # Con [[wikilinks]] para conectar conocimiento
127
- ale add "Deploy en Vercel" -c "Regiones cdg1, ver [[Configuración de Prisma]]" -t deploy
133
+ ### Create a plan from a file
134
+
135
+ Instead of typing a whole plan into the terminal, keep it as markdown in your repo:
136
+
137
+ ```bash
138
+ $ ale plan PLAN-migration.md
139
+ ✓ Plan created: notes/2026-07-11-plan-migrate-to-postgres-17.md
140
+ DoD detected: 3 criteria — backup verified · migrations run clean · app responds on staging
128
141
  ```
129
142
 
130
- (La captura automática vía hooks hace esto solo en cada sesión de Claude Code — `add` es para conocimiento extra.)
143
+ 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`.
131
144
 
132
- ### Ver el grafo de conexiones
145
+ ### View the knowledge graph
133
146
 
134
- **El grafo se mantiene solo** — no hay que generarlo: cada vez que la bóveda cambia (captura automática, `ale add`, reindex), se regenera `<bóveda>/grafo.html`. Doble clic y siempre está al día.
147
+ **The graph maintains itself** — every vault change (automatic capture, `ale add`, reindex) regenerates `<vault>/grafo.html`. Double-click it anytime.
135
148
 
136
149
  ```bash
137
- ale graph # visor EN VIVO en tu navegador: se actualiza solo cada 3s
138
- ale graph --out otro.html # copia estática a otra ruta (opcional)
150
+ ale graph # LIVE viewer in your browser: auto-refreshes every 3s
151
+ ale graph --out other.html # static copy elsewhere (optional)
139
152
  ```
140
153
 
141
- Nodos = notas (tamaño = conexiones, color = tipo), líneas sólidas = `[[wikilinks]]`, punteadas = similitud semántica. Auto-encuadre, hover resalta vecinos, click muestra detalle y conexiones, caja para filtrar por título/tag, y **filtros por tipo estilo Obsidian** (los prompts vienen ocultos por default — son ruido visual; actívalos con su checkbox). El grafo brilla a partir de ~20-30 notas — es acumulativo por diseño.
154
+ Nodes = notes (size = connections, color = type: 🟪 plans, 🟦 verifications, 🟨 lessons, 🟩 sessions…), solid lines = `[[wikilinks]]`, dashed = semantic similarity. Auto-fit, hover highlights neighbors, click shows details, Obsidian-style **type filters** (prompts hidden by default — they're visual noise). The graph shines from ~20-30 notes on — it's cumulative by design.
142
155
 
143
- **En Obsidian**: abre la carpeta de la bóveda como vault y usa su graph view nativo — las notas llevan `aliases` en el frontmatter para que Obsidian resuelva los `[[wikilinks]]` (sin eso los ve como enlaces rotos). Las notas viejas se migran solas en el siguiente reindex. Ojo: `grafo.html` no se abre *dentro* de Obsidian (no renderiza HTML) — es para el navegador.
156
+ **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.
144
157
 
145
- ### Medir cuánto te está ahorrando
158
+ ### Measure what it saves you
146
159
 
147
160
  ```bash
148
161
  $ ale stats
149
162
 
150
- 🧠 Bóveda: /Users/tu/Alexandria (global)
151
- Notas: 142 {"note":80,"prompt":38,"session":22,"map":2}
152
- Chunks indexados: 385 · Conexiones: 91
153
- Búsqueda semántica: activa
163
+ 🧠 Vault: /Users/you/Alexandria (global)
164
+ Notes: 142 {"note":80,"prompt":38,"session":22,"map":2}
165
+ Indexed chunks: 385 · Connections: 91
166
+ Semantic search: active
154
167
 
155
- 💰 Ahorro estimado
156
- Inyecciones de contexto: 57 (12 con solución cacheada)
157
- Tokens inyectados: ~21,300
158
- Tokens ahorrados (vs re-explorar): ~191,700
168
+ 🏛️ Protocol
169
+ Plans: 6 (1 open) · Verifications: 14 (86% ✓)
170
+ Lessons: 9 (4 reused — each reuse = a debug session that never happened)
171
+
172
+ 💰 Estimated savings
173
+ Context injections: 57 (12 with cached solution)
174
+ Injected tokens: ~21,300
175
+ Tokens saved (vs re-exploring): ~191,700
159
176
  ```
160
177
 
161
- ### Skills recomendadas según tus patrones
178
+ ### Audit your vault's health
162
179
 
163
180
  ```bash
164
- $ ale skills
165
-
166
- 📦 Skills recomendadas según tu bóveda:
167
- pdf-report-gen [local] — detecté 14 menciones de pdf, membrete en la bóveda
168
- auth-standard [local] — detecté 9 menciones de auth, login, jwt en la bóveda
181
+ $ ale audit
169
182
 
170
- ¿Instalar todas? [s/N/números separados por coma]
183
+ 🏛️ Alexandria Protocol audit
184
+ Plans: 2 (2 open, 0 completed, 0 failed)
185
+ Verifications: 1 (1 failures) · Lessons: 1
186
+ ⚠ Notes without connections (invisible to vault_related): 1
187
+ - Plan - Migrate to Postgres 17 → connect it with vault_link or [[wikilinks]]
171
188
  ```
172
189
 
173
- Analiza los temas de tus notas y sugiere skills de Claude (desde skills.sh o tu repo local). `-y` instala sin preguntar, `--project` instala en `.claude/skills/` del proyecto.
190
+ Flags plans without a Definition of Done, failures without lessons, and orphan notes.
174
191
 
175
- ### Mantenimiento (casi nunca lo necesitas)
192
+ ### Maintenance (you rarely need it)
176
193
 
177
194
  ```bash
178
- ale doctor # verifica y repara: modelo, hooks, MCP, índice
179
- ale reindex # reindexado incremental (solo notas cambiadas)
180
- ale reindex --force # desde cero (p. ej. tras editar mucho en Obsidian)
181
- ale uninstall # quita hooks; tus notas quedan intactas
195
+ ale doctor # checks & repairs: model, hooks, MCP, index
196
+ ale reindex [--force] # incremental by default
197
+ ale consolidate [--days 45] # ARCHIVES old unused prompts to Alexandria/archive/
198
+ # — out of the graph and injection, still searchable: nothing is ever lost
199
+ ale uninstall # removes hooks; your notes stay untouched
182
200
  ```
183
201
 
184
- Todo comando auto-repara antes de correr: si falta el modelo lo descarga, si el índice está viejo lo actualiza — no tienes que pensar en ello.
202
+ Every command self-repairs before running: missing model → downloads it; stale index → updates it.
185
203
 
186
- ## Agentes soportados
204
+ ## Supported agents
187
205
 
188
206
  ```bash
189
- ale agents # lista con detección automática (● = detectado en tu máquina)
190
- ale agents all # registra el MCP en todos
191
- ale agents cursor,gemini # solo en esos
192
- ale agents detected # solo los detectados
207
+ ale agents # list with auto-detection (● = found on your machine)
208
+ ale agents all # register the MCP server in all of them
209
+ ale agents cursor,gemini # just these
193
210
  ```
194
211
 
195
- | Agente | Config que escribe | Por proyecto |
212
+ | Agent | Config written | Per-project |
196
213
  |---|---|---|
197
214
  | Claude Code | `.mcp.json` / `claude mcp add` + hooks | ✓ |
198
215
  | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | ✓ |
@@ -201,85 +218,68 @@ ale agents detected # solo los detectados
201
218
  | Cline | `cline_mcp_settings.json` (VS Code) | — |
202
219
  | Codex CLI | `~/.codex/config.toml` | — |
203
220
  | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | ✓ |
204
- | VS Code (Copilot) | `mcp.json` (perfil) / `.vscode/mcp.json` | ✓ |
221
+ | VS Code (Copilot) | `mcp.json` (profile) / `.vscode/mcp.json` | ✓ |
205
222
  | OpenClaw | `~/.openclaw/openclaw.json` | — |
206
223
  | Hermes Agent (Nous) | `hermes mcp add` / `~/.hermes/config.yaml` | — |
207
224
 
208
- Los registros hacen **merge idempotente**: nunca pisan tus otros servidores MCP configurados.
225
+ Registrations are **idempotent merges** — your other MCP servers are never touched.
209
226
 
210
- **Nota**: la captura automática por hooks (digest de sesión, inyección por prompt, guardado al terminar) es exclusiva de Claude Code — los demás agentes no tienen sistema de hooks. En ellos el conocimiento fluye por las herramientas MCP, que el agente usa solo.
227
+ **Note**: automatic capture via hooks (session digest, per-prompt injection, session save on close) is Claude Code-only — other agents don't have a hook system. There, knowledge flows through the MCP tools, which the agent uses on its own (the protocol instructions travel inside the tool descriptions).
211
228
 
212
- ## Cómo funciona
229
+ ## How it works
213
230
 
214
231
  ```
215
- Sesión del agente de IA
232
+ AI agent session
216
233
  │
217
- ├─ SessionStart ──► inyecta digest: mapa del proyecto + conocimiento previo (hooks, Claude Code)
218
- ├─ Cada prompt ───► búsqueda híbrida local → inyecta solo lo relevante (hooks, Claude Code)
219
- │ └─ prompt casi idéntico ya resuelto → inyecta la solución (caché)
220
- ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (todos los agentes)
221
- └─ Stop/PreCompact► guarda el resultado de la sesión en la bóveda (hooks, Claude Code)
234
+ ├─ SessionStart ──► injects digest: protocol manifest + project map + open plans (hooks, Claude Code)
235
+ ├─ Every prompt ──► local hybrid search → injects only what's relevant (hooks, Claude Code)
236
+ │ └─ near-identical prompt already solved → injects the solution (cache)
237
+ ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
238
+ │ plan_create · task_verify · lesson_extract (the Protocol)
239
+ └─ Stop/PreCompact► saves the session outcome into the vault (hooks, Claude Code)
222
240
  │
223
- <Vault Obsidian>/Alexandria/*.md ← markdown, [[wikilinks]]
224
- <Vault>/.vault/ ← índice (regenerable)
241
+ <Obsidian vault>/Alexandria/*.md ← markdown, [[wikilinks]]
242
+ <vault>/.vault/ ← index (regenerable)
225
243
  ```
226
244
 
227
- - **Búsqueda híbrida**: embeddings locales (transformers.js, modelo multilingüe e5-small) + BM25, combinados con RRF y boost por recencia/uso. Sin internet funciona en modo keyword.
228
- - **Índice incremental**: solo re-procesa notas cuyo mtime cambió. El grafo nunca se recalcula completo.
229
- - **Deduplicación**: prompts casi idénticos no crean notas nuevas — suman `hits` (y suben en el ranking).
230
- - **Sobre los scores**: el modelo e5 comprime los cosenos (~0.76–0.86 incluso entre temas sin relación); el *ranking* es lo confiable, no el número crudo — por eso la etiqueta de relevancia.
245
+ - **Hybrid search**: local embeddings (transformers.js, multilingual e5-small) + BM25, combined with RRF, boosted by recency, usage, and note type (lessons/solutions rank highest).
246
+ - **Incremental index**: only re-processes notes whose mtime changed. The graph is never rebuilt from scratch.
247
+ - **Deduplication**: near-identical prompts don't create new notes — they add `hits` (and climb the ranking).
248
+ - **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.
231
249
 
232
- ## Herramientas MCP (las usa el agente solo)
250
+ ## Command reference
233
251
 
234
- En cualquier agente conectado, pídele cosas como *"busca en mi bóveda cómo configuré el deploy"* o *"guarda esta decisión en la bóveda"*:
235
-
236
- - `vault_search(query, k)` — busca conocimiento antes de explorar código.
237
- - `vault_save(title, content, tags)` — guarda decisiones/arquitectura. `title: "Mapa - <proyecto>"` actualiza el mapa que se inyecta al inicio de cada sesión de Claude Code.
238
- - `vault_related(title)` — vecinos en el grafo (wikilinks + semánticos) sin releer archivos.
239
- - `vault_link(from, to)` — conecta dos notas con `[[wikilink]]`.
240
-
241
- ## Comandos — referencia
242
-
243
- | Comando | Qué hace |
252
+ | Command | What it does |
244
253
  |---|---|
245
- | `ale init [--project] [--path <dir>] [--agents <ids>] [--auto\|--manual]` | Instala todo: bóveda (default `./Alexandria` / `~/Alexandria`), hooks, MCP, .gitignore, escaneo inicial y CLAUDE.md |
246
- | `ale agents [ids] [--project]` | Lista agentes / registra el MCP en ellos |
247
- | `ale search <query> [-k n] [--expand]` | Búsqueda híbrida; `--expand` trae vecinos del grafo |
248
- | `ale add <título> [-c texto] [-t tags]` | Guardar nota manual (o por stdin) |
249
- | `ale graph [--out file.html] [--no-open]` | Grafo interactivo local |
250
- | `ale skills [-y] [--project]` | Recomienda e instala skills de Claude según tus patrones |
251
- | `ale stats` | Notas, conexiones y tokens ahorrados estimados |
252
- | `ale reindex [--force]` | Reindexar (incremental por default) |
253
- | `ale doctor [--project]` | Verifica y repara: modelo, hooks, MCP, índice |
254
- | `ale consolidate [--days n] [--dry]` | Archiva prompts viejos sin reuso — fuera del grafo/inyección, siguen buscables: nada se pierde |
255
- | `ale uninstall [--project]` | Quita hooks (las notas quedan intactas) |
256
- | `ale --vault <ruta> <comando>` | Cualquier comando contra otra bóveda |
257
-
258
- `alexandria` funciona como alias de `ale`.
259
-
260
- ## Privacidad y seguridad
261
-
262
- - **Todo corre en tu máquina**: el modelo de embeddings se descarga una vez (Hugging Face) y después funciona offline. Tus notas jamás salen de tu disco. Sin telemetría.
263
- - **Sin API keys, sin cuentas, sin costo.**
264
- - Los escáneres de dependencias (Socket, etc.) marcan alertas de *network/shell/env access* en el árbol de dependencias: provienen del runtime de ML (`onnxruntime`/`transformers.js`, que necesita filesystem y descarga inicial del modelo) y del SDK oficial de MCP — no de código de Alexandria. El código fuente es abierto y auditable; el paquete publicado no ejecuta install scripts propios.
265
- - Los configs generados (`.mcp.json`, hooks) apuntan a la ruta de instalación de tu máquina. Si compartes un repo con equipo, cambia el `command` a `npx -y @ureck/alexandria alexandria serve-mcp` para que sea portable.
266
-
267
- ## V2 (roadmap)
268
-
269
- - Bot de Telegram (grammY, polling local — sin servidor público): `/search`, `/save` desde el teléfono.
270
-
271
-
272
- ## Código y contribuciones
273
-
274
- El código fuente se mantiene en un repositorio privado; este repositorio público contiene el compilado distribuido en npm (el mismo contenido del paquete, auditable).
275
-
276
- - 🐛 **Issues y sugerencias**: [github.com/UreckChan/alexandria/issues](https://github.com/UreckChan/alexandria/issues)
277
- - 📦 **Releases**: cada versión de npm tiene su tag aquí
278
-
279
- ## Apoya el proyecto ☕
280
-
281
- Alexandria es gratis y open source. Si te ahorra tokens (y dinero), puedes invitarme un café:
254
+ | `ale init [--project] [--path <dir>] [--agents <ids>] [--auto\|--manual] [--no-protocol] [--portable]` | Installs everything: vault, hooks, MCP, .gitignore, project scan, CLAUDE.md. `--portable` writes an npx-based MCP command safe to commit for teams |
255
+ | `ale agents [ids] [--project]` | List agents / register the MCP server |
256
+ | `ale search <query> [-k n] [--expand]` | Hybrid search; `--expand` pulls graph neighbors |
257
+ | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
258
+ | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done) |
259
+ | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
260
+ | `ale audit` | Protocol health: plans without DoD, failures without lessons, orphan notes |
261
+ | `ale stats` | Notes, connections, protocol metrics, estimated tokens saved |
262
+ | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
263
+ | `ale skills [-y] [--project]` | Recommends & installs Claude skills based on your patterns |
264
+ | `ale reindex [--force]` | Reindex (incremental by default) |
265
+ | `ale consolidate [--days n] [--dry]` | Archive old unused prompts — never deletes |
266
+ | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
267
+ | `ale uninstall [--project]` | Remove hooks (notes stay untouched) |
268
+ | `ale --vault <path> <cmd>` | Run any command against another vault |
269
+
270
+ `alexandria` works as an alias of `ale`.
271
+
272
+ ## Privacy & security
273
+
274
+ - **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.
275
+ - **No API keys, no accounts, no cost.**
276
+ - 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.
277
+ - 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.
278
+
279
+ ## Support the project ☕
280
+
281
+ Alexandria is free and open source. If it saves you tokens (and money), you can buy me a coffee:
282
282
 
283
283
  **[☕ buymeacoffee.com/ureck](https://buymeacoffee.com/ureck)**
284
284
 
285
- Hecho con 🏛 por **[Ureck](https://buymeacoffee.com/ureck)** — MIT License.
285
+ Built with 🏛 by **[Ureck](https://buymeacoffee.com/ureck)** — MIT License.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-ZW7XY3EN.js";
4
+ } from "./chunk-7G3NPKDO.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -35,12 +35,25 @@ function buildMini(idx) {
35
35
  );
36
36
  return mini;
37
37
  }
38
+ var TYPE_BOOST = {
39
+ lesson: 1.35,
40
+ solution: 1.35,
41
+ map: 1.25,
42
+ plan: 1.15,
43
+ verification: 1.1,
44
+ note: 1,
45
+ task: 1,
46
+ session: 0.9,
47
+ prompt: 0.8
48
+ };
38
49
  function recencyBoost(note) {
39
- if (!note?.created) return 1;
50
+ if (!note) return 1;
51
+ const typeBoost = TYPE_BOOST[note.type] ?? 1;
52
+ if (!note.created) return typeBoost;
40
53
  const age = (Date.now() - Date.parse(note.created)) / 864e5;
41
- if (Number.isNaN(age)) return 1;
54
+ if (Number.isNaN(age)) return typeBoost;
42
55
  const hits = Math.min(note.hits ?? 1, 10);
43
- return 1 + 0.15 * Math.exp(-Math.max(age, 0) / 45) + 0.02 * hits;
56
+ return typeBoost * (1 + 0.15 * Math.exp(-Math.max(age, 0) / 45) + 0.02 * hits);
44
57
  }
45
58
  async function hybridSearch(vault, query, k = 6, opts = {}) {
46
59
  const idx = VaultIndex.load(vault);
@@ -3,7 +3,7 @@ import {
3
3
  ensureAlias,
4
4
  listMarkdownFiles,
5
5
  parseNote
6
- } from "./chunk-JPHL2JHE.js";
6
+ } from "./chunk-XWR74BQ2.js";
7
7
  import {
8
8
  DIM,
9
9
  MODEL_ID,
@@ -80,6 +80,9 @@ var VaultIndex = class _VaultIndex {
80
80
  const rel = path.relative(this.vault.root, abs).split(path.sep).join("/");
81
81
  onDisk.set(rel, { abs, mtime: fs.statSync(abs).mtimeMs });
82
82
  }
83
+ if (withEmbeddings && this.emb === null && this.meta.chunks.length > 0) {
84
+ force = true;
85
+ }
83
86
  const changed = [];
84
87
  for (const [rel, info] of onDisk) {
85
88
  if (force || this.meta.mtimes[rel] !== info.mtime) changed.push(rel);
@@ -115,6 +118,7 @@ var VaultIndex = class _VaultIndex {
115
118
  rel,
116
119
  title: note.title,
117
120
  type: note.type,
121
+ status: note.status,
118
122
  tags: note.tags,
119
123
  created: note.created,
120
124
  hits: note.hits,
@@ -167,7 +171,7 @@ ${c.text}`),
167
171
  this.rebuildLinks();
168
172
  this.save();
169
173
  try {
170
- const { writeStaticGraph } = await import("./viewer-FRJYOK3S.js");
174
+ const { writeStaticGraph } = await import("./viewer-G3N57646.js");
171
175
  writeStaticGraph(this);
172
176
  } catch {
173
177
  }
@@ -78,7 +78,22 @@ function ensureVaultStructure(v) {
78
78
  }
79
79
  function writeGlobalConfig(vaultPath) {
80
80
  fs.mkdirSync(configDir(), { recursive: true });
81
- fs.writeFileSync(globalConfigPath(), JSON.stringify({ vaultPath }, null, 2) + "\n");
81
+ const current = readJson(globalConfigPath()) ?? {};
82
+ fs.writeFileSync(globalConfigPath(), JSON.stringify({ ...current, vaultPath }, null, 2) + "\n");
83
+ }
84
+ function getConfigKey(key) {
85
+ const cfg = readJson(globalConfigPath()) ?? {};
86
+ return cfg[key];
87
+ }
88
+ function setConfigKey(key, value) {
89
+ fs.mkdirSync(configDir(), { recursive: true });
90
+ const cfg = readJson(globalConfigPath()) ?? {};
91
+ cfg[key] = value;
92
+ fs.writeFileSync(globalConfigPath(), JSON.stringify(cfg, null, 2) + "\n");
93
+ }
94
+ function protocolEnabled() {
95
+ const v = getConfigKey("protocol");
96
+ return v !== false && v !== "false";
82
97
  }
83
98
  function writeProjectConfig(projectDir, vaultPath) {
84
99
  const file = path.join(projectDir, ".vault.json");
@@ -95,5 +110,8 @@ export {
95
110
  vaultExists,
96
111
  ensureVaultStructure,
97
112
  writeGlobalConfig,
113
+ getConfigKey,
114
+ setConfigKey,
115
+ protocolEnabled,
98
116
  writeProjectConfig
99
117
  };
@@ -73,7 +73,10 @@ function hooksRegistered(settingsPath) {
73
73
  return false;
74
74
  }
75
75
  }
76
- function registerMcpProject(projectDir) {
76
+ function serverCommand(portable) {
77
+ return portable ? { command: "npx", args: ["-y", "@ureck/alexandria", "alexandria", "serve-mcp"] } : { command: "node", args: [path.join(distDir(), "mcp", "server.js")] };
78
+ }
79
+ function registerMcpProject(projectDir, portable = false) {
77
80
  const file = path.join(projectDir, ".mcp.json");
78
81
  let cfg = {};
79
82
  try {
@@ -84,17 +87,14 @@ function registerMcpProject(projectDir) {
84
87
  }
85
88
  }
86
89
  cfg.mcpServers ??= {};
87
- cfg.mcpServers["alexandria"] = {
88
- command: "node",
89
- args: [path.join(distDir(), "mcp", "server.js")]
90
- };
90
+ cfg.mcpServers["alexandria"] = serverCommand(portable);
91
91
  fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
92
92
  return file;
93
93
  }
94
- function registerMcpGlobal() {
95
- const server = path.join(distDir(), "mcp", "server.js");
94
+ function registerMcpGlobal(portable = false) {
95
+ const { command, args } = serverCommand(portable);
96
96
  try {
97
- execFileSync("claude", ["mcp", "add", "--scope", "user", "alexandria", "--", "node", server], {
97
+ execFileSync("claude", ["mcp", "add", "--scope", "user", "alexandria", "--", command, ...args], {
98
98
  stdio: "pipe",
99
99
  timeout: 15e3
100
100
  });