@ureck/alexandria 1.3.2 → 1.4.0

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.
@@ -1,24 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- logInjection
4
- } from "../chunk-XITAQVOZ.js";
5
- import {
3
+ emitContext,
6
4
  projectName,
7
5
  runHook,
8
6
  truncate
9
- } from "../chunk-53SIGH5A.js";
7
+ } from "../chunk-U2U53TU2.js";
10
8
  import {
11
9
  hybridSearch
12
- } from "../chunk-UWB6RKVN.js";
10
+ } from "../chunk-FPKJVQ2X.js";
13
11
  import {
12
+ isHarnessInjected,
13
+ logInjection,
14
14
  resolveVault,
15
15
  toggleEnabled,
16
16
  vaultExists
17
- } from "../chunk-CIOCSIB5.js";
17
+ } from "../chunk-MDGFK6UC.js";
18
18
  import {
19
19
  createNote,
20
20
  touchNote
21
- } from "../chunk-QB37UGO6.js";
21
+ } from "../chunk-3CB7GRFJ.js";
22
22
  import "../chunk-EDYBSJSS.js";
23
23
 
24
24
  // src/hooks/on-prompt.ts
@@ -33,7 +33,7 @@ var RELEVANT_MARGIN = 0.04;
33
33
  var KEYWORD_REL_FACTOR = 0.6;
34
34
  runHook(5e3, async (input) => {
35
35
  const prompt = (input.prompt ?? "").trim();
36
- if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/")) return;
36
+ if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/") || isHarnessInjected(prompt)) return;
37
37
  const vault = resolveVault({ cwd: input.cwd });
38
38
  if (!vaultExists(vault)) return;
39
39
  const rawResults = await hybridSearch(vault, prompt, 5, { expand: true, refresh: false });
@@ -81,8 +81,8 @@ Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o r
81
81
 
82
82
  ` + truncate(lines.join("\n\n"), MAX_INJECT_CHARS) + `
83
83
  </alexandria-contexto>`;
84
- process.stdout.write(injected);
85
- logInjection(vault, {
84
+ const written = emitContext("prompt", injected);
85
+ if (written > 0) logInjection(vault, {
86
86
  kind: cached ? "solution-cache" : "inject",
87
87
  injectedChars: injected.length,
88
88
  promptChars: prompt.length
@@ -119,4 +119,4 @@ Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o r
119
119
 
120
120
  ${truncate(prompt, 4e3)}`
121
121
  });
122
- });
122
+ }, "prompt");
@@ -1,21 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- logInjection
4
- } from "../chunk-XITAQVOZ.js";
5
- import {
3
+ emitContext,
6
4
  projectName,
7
5
  runHook,
8
6
  truncate
9
- } from "../chunk-53SIGH5A.js";
7
+ } from "../chunk-U2U53TU2.js";
10
8
  import {
9
+ logInjection,
11
10
  protocolEnabled,
12
11
  resolveVault,
13
12
  toggleEnabled,
14
13
  vaultExists
15
- } from "../chunk-CIOCSIB5.js";
14
+ } from "../chunk-MDGFK6UC.js";
16
15
  import {
17
16
  VaultIndex
18
- } from "../chunk-QB37UGO6.js";
17
+ } from "../chunk-3CB7GRFJ.js";
19
18
  import "../chunk-EDYBSJSS.js";
20
19
 
21
20
  // src/hooks/on-session-start.ts
@@ -33,7 +32,11 @@ runHook(15e3, async (input) => {
33
32
  const proj = projectName(input.cwd);
34
33
  const parts = [];
35
34
  if (protocolEnabled()) {
36
- const openPlans = idx.notesByTag("plan").filter((n) => n.status === "active");
35
+ const recent = Date.now() - 30 * 864e5;
36
+ const seen = /* @__PURE__ */ new Set();
37
+ const openPlans = idx.notesByTag("plan").filter((n) => n.status === "active" && !n.rel.split("/").includes("archive")).filter(
38
+ (n) => n.tags.some((t) => t.toLowerCase() === proj.toLowerCase()) || n.tags.every((t) => t === "plan") && Date.parse(n.created ?? "") > recent
39
+ ).filter((n) => !seen.has(n.title) && Boolean(seen.add(n.title))).slice(0, 8);
37
40
  parts.push(
38
41
  `## Protocolo Alexandria (activo)
39
42
  El protocolo es PALANCA, no l\xEDmite: \xFAsalo para rendir m\xE1s con menos tokens, nunca como burocracia. Tareas simples \u2192 responde directo, sin ceremonia. Tareas no triviales \u2192 ciclo con las tools MCP: 1) plan_create (objetivo + Definition of Done) \u2192 2) ejecuta con toda tu capacidad \u2192 3) task_verify con evidencia real (tests/build \u2014 la evidencia elimina errores, no te frena) \u2192 si algo falla, vault_search por lecciones ANTES de re-debuggear (conocimiento previo = tokens gratis) \u2192 4) lesson_extract si resolviste algo no obvio. Reutiliza lo cacheado con criterio: valida que siga aplicando si el c\xF3digo cambi\xF3.` + (openPlans.length > 0 ? `
@@ -52,7 +55,7 @@ ${truncate(body.trim(), 4e3)}`);
52
55
  } catch {
53
56
  }
54
57
  }
55
- const sessions = idx.notesByTag("session").sort((a, b) => (b.created ?? "").localeCompare(a.created ?? "")).slice(0, 3);
58
+ const sessions = idx.notesByTag("session").filter((s) => s.tags.some((t) => t.toLowerCase() === proj.toLowerCase())).sort((a, b) => (b.created ?? "").localeCompare(a.created ?? "")).slice(0, 3);
56
59
  if (sessions.length > 0) {
57
60
  const lines = sessions.map((s) => `- ${s.title} (${(s.created ?? "").slice(0, 10)})`);
58
61
  parts.push(`## Sesiones recientes en la b\xF3veda
@@ -75,6 +78,5 @@ B\xF3veda de conocimiento local activa (${notes.length} notas). ANTES de explora
75
78
 
76
79
  ` + truncate(parts.join("\n\n"), MAX_CHARS) + `
77
80
  </alexandria-digest>`;
78
- process.stdout.write(digest);
79
- logInjection(vault, { kind: "session-start", injectedChars: digest.length });
80
- });
81
+ if (emitContext("session", digest) > 0) logInjection(vault, { kind: "session-start", injectedChars: digest.length });
82
+ }, "session");
@@ -3,17 +3,22 @@ import {
3
3
  projectName,
4
4
  runHook,
5
5
  truncate
6
- } from "../chunk-53SIGH5A.js";
6
+ } from "../chunk-U2U53TU2.js";
7
+ import {
8
+ autoCleanDue,
9
+ markCleaned
10
+ } from "../chunk-2ESJQAP4.js";
7
11
  import {
8
12
  ensureVaultStructure,
13
+ lastExchange,
9
14
  resolveVault,
10
15
  toggleEnabled,
11
16
  vaultExists
12
- } from "../chunk-CIOCSIB5.js";
17
+ } from "../chunk-MDGFK6UC.js";
13
18
  import {
14
19
  VaultIndex,
15
20
  appendToNote
16
- } from "../chunk-QB37UGO6.js";
21
+ } from "../chunk-3CB7GRFJ.js";
17
22
  import "../chunk-EDYBSJSS.js";
18
23
 
19
24
  // src/hooks/on-stop.ts
@@ -21,39 +26,24 @@ import fs from "fs";
21
26
  import path from "path";
22
27
  import { spawn } from "child_process";
23
28
  import { fileURLToPath } from "url";
24
- function textOf(msg) {
25
- const c = msg.message?.content;
26
- if (typeof c === "string") return c;
27
- if (Array.isArray(c)) {
28
- return c.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");
29
- }
30
- return "";
31
- }
32
29
  runHook(25e3, async (input) => {
33
- if (!input.transcript_path || !fs.existsSync(input.transcript_path)) return;
34
30
  const vault = resolveVault({ cwd: input.cwd });
35
31
  if (!vaultExists(vault)) return;
36
- ensureVaultStructure(vault);
37
- const raw = fs.readFileSync(input.transcript_path, "utf8");
38
- const lines = raw.split("\n").filter(Boolean);
39
- let lastUser = "";
40
- let lastAssistant = "";
41
- for (const line of lines.slice(-200)) {
42
- try {
43
- const msg = JSON.parse(line);
44
- const text = textOf(msg).trim();
45
- if (!text) continue;
46
- if (msg.type === "user" && !text.startsWith("<")) lastUser = text;
47
- if (msg.type === "assistant") lastAssistant = text;
48
- } catch {
49
- }
32
+ let lastUser = input.prompt?.trim() ?? "";
33
+ let lastAssistant = input.answer?.trim() ?? "";
34
+ if (!lastAssistant && input.transcript_path && fs.existsSync(input.transcript_path)) {
35
+ const lines = fs.readFileSync(input.transcript_path, "utf8").split("\n").filter(Boolean);
36
+ const ex = lastExchange(lines.slice(-200));
37
+ lastAssistant = ex.assistant;
38
+ lastUser ||= ex.user;
50
39
  }
51
40
  if (!lastAssistant) return;
41
+ ensureVaultStructure(vault);
52
42
  const proj = projectName(input.cwd);
53
43
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
54
44
  const sid = (input.session_id ?? "sesion").slice(0, 8);
55
45
  const stamp = (/* @__PURE__ */ new Date()).toISOString().slice(11, 16);
56
- const isCompact = input.hook_event_name === "PreCompact" || Boolean(input.trigger);
46
+ const isCompact = input.compact;
57
47
  appendToNote(vault.managed, {
58
48
  fixedName: `${date}-${proj}-${sid}`,
59
49
  title: `Sesi\xF3n ${date} \u2014 ${proj}`,
@@ -69,7 +59,24 @@ runHook(25e3, async (input) => {
69
59
  Proyecto: [[Mapa - ${proj}]]`
70
60
  });
71
61
  await maybeRebuildInBackground(vault);
62
+ maybeCleanInBackground(vault);
72
63
  });
64
+ function maybeCleanInBackground(vault) {
65
+ try {
66
+ if (!toggleEnabled("clean.auto") || !autoCleanDue(vault)) return;
67
+ markCleaned(vault);
68
+ const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.js");
69
+ if (!fs.existsSync(cli)) return;
70
+ const child = spawn(process.execPath, [cli, "--vault", vault.root, "clean", "--yes", "--quiet"], {
71
+ detached: true,
72
+ stdio: "ignore",
73
+ windowsHide: true,
74
+ env: { ...process.env, ALEXANDRIA_HOOK: "" }
75
+ });
76
+ child.unref();
77
+ } catch {
78
+ }
79
+ }
73
80
  async function maybeRebuildInBackground(vault) {
74
81
  try {
75
82
  if (!toggleEnabled("index.autoRebuild")) return;
@@ -80,6 +87,8 @@ async function maybeRebuildInBackground(vault) {
80
87
  const child = spawn(process.execPath, [cli, "--vault", vault.root, "reindex", "--force"], {
81
88
  detached: true,
82
89
  stdio: "ignore",
90
+ windowsHide: true,
91
+ // Windows: sin esto puede parpadear una consola al cerrar sesión
83
92
  env: { ...process.env, ALEXANDRIA_HOOK: "" }
84
93
  // proceso CLI: sí puede reconstruir
85
94
  });
@@ -87,3 +96,6 @@ async function maybeRebuildInBackground(vault) {
87
96
  } catch {
88
97
  }
89
98
  }
99
+ export {
100
+ maybeRebuildInBackground
101
+ };
@@ -4,22 +4,25 @@ import {
4
4
  pkgVersion,
5
5
  planContext,
6
6
  planQualityHints
7
- } from "../chunk-ZIQYAQCF.js";
7
+ } from "../chunk-JI2L66DF.js";
8
8
  import {
9
9
  hybridSearch
10
- } from "../chunk-UWB6RKVN.js";
10
+ } from "../chunk-FPKJVQ2X.js";
11
+ import {
12
+ searchArchive
13
+ } from "../chunk-2ESJQAP4.js";
11
14
  import {
12
15
  ensureVaultStructure,
13
16
  resolveVault,
14
17
  toggleEnabled
15
- } from "../chunk-CIOCSIB5.js";
18
+ } from "../chunk-MDGFK6UC.js";
16
19
  import {
17
20
  VaultIndex,
18
21
  createNote,
19
22
  setNoteStatus,
20
23
  slugify,
21
24
  upsertNote
22
- } from "../chunk-QB37UGO6.js";
25
+ } from "../chunk-3CB7GRFJ.js";
23
26
  import "../chunk-EDYBSJSS.js";
24
27
 
25
28
  // src/mcp/server.ts
@@ -54,21 +57,33 @@ var server = new McpServer({ name: "alexandria", version: pkgVersion() });
54
57
  var text = (t) => ({ content: [{ type: "text", text: t }] });
55
58
  var tail = (s, n) => s.length > n ? "\u2026\n" + s.slice(-n) : s;
56
59
  function findMap(idx) {
57
- return Object.values(idx.meta.notes).find((n) => n.type === "map" || n.title.startsWith("Mapa - "));
60
+ const maps = Object.values(idx.meta.notes).filter((n) => n.type === "map" || n.title.startsWith("Mapa - "));
61
+ const own = `Mapa - ${path.basename(process.cwd())}`.toLowerCase();
62
+ return maps.find((n) => n.title.toLowerCase() === own) ?? maps[0];
58
63
  }
59
64
  function findByTitle(idx, t) {
60
65
  const lower = t.toLowerCase();
66
+ const alt = lower.startsWith("plan - ") ? lower : `plan - ${lower}`;
61
67
  return Object.values(idx.meta.notes).find(
62
- (n) => n.title.toLowerCase() === lower || n.rel.toLowerCase() === lower
68
+ (n) => [lower, alt].includes(n.title.toLowerCase()) || n.rel.toLowerCase() === lower
63
69
  );
64
70
  }
65
- server.tool(
71
+ server.registerTool(
66
72
  "vault_search",
67
- "Busca conocimiento en la b\xF3veda local (b\xFAsqueda sem\xE1ntica + keyword). \xDAsala ANTES de explorar c\xF3digo o re-derivar contexto: si la b\xF3veda ya lo sabe, ahorras tokens.",
68
- { query: z.string().describe("Qu\xE9 buscar, en lenguaje natural"), k: z.number().int().min(1).max(15).optional() },
73
+ {
74
+ description: "Busca conocimiento en la b\xF3veda local (b\xFAsqueda sem\xE1ntica + keyword). \xDAsala ANTES de explorar c\xF3digo o re-derivar contexto: si la b\xF3veda ya lo sabe, ahorras tokens.",
75
+ inputSchema: { query: z.string().describe("Qu\xE9 buscar, en lenguaje natural"), k: z.number().int().min(1).max(15).optional() }
76
+ },
69
77
  async ({ query, k }) => {
70
78
  const results = await hybridSearch(vault, query, k ?? 5, { expand: true });
71
- if (results.length === 0) return text("Sin resultados en la b\xF3veda.");
79
+ if (results.length === 0) {
80
+ const arch = searchArchive(vault, query, 3);
81
+ if (arch.length === 0) return text("Sin resultados en la b\xF3veda.");
82
+ return text(
83
+ "Sin resultados en el \xEDndice; en el archivo de prompts compactados:\n\n" + arch.map((h, i) => `${i + 1}. \xAB${h.heading}\xBB (${h.file})
84
+ ${h.excerpt.replace(/\n/g, " ").slice(0, 400)}`).join("\n\n")
85
+ );
86
+ }
72
87
  const out = results.map(
73
88
  (r, i) => `${i + 1}. \xAB${r.note.title}\xBB (${r.note.rel}, tipo: ${r.note.type})
74
89
  ${r.excerpts.map((e) => " " + e.replace(/\n/g, "\n ").slice(0, 900)).join("\n")}`
@@ -76,21 +91,20 @@ ${r.excerpts.map((e) => " " + e.replace(/\n/g, "\n ").slice(0, 900)).join("\
76
91
  return text(out);
77
92
  }
78
93
  );
79
- server.tool(
94
+ server.registerTool(
80
95
  "vault_save",
81
- 'Guarda conocimiento destilado en la b\xF3veda (decisiones, arquitectura, soluciones). Si title empieza con "Mapa - " actualiza/crea el mapa del proyecto (se inyecta al inicio de cada sesi\xF3n).',
82
96
  {
83
- title: z.string(),
84
- content: z.string().describe("Markdown; puede incluir [[wikilinks]] a otras notas"),
85
- tags: z.array(z.string()).optional()
97
+ description: 'Guarda conocimiento destilado en la b\xF3veda (decisiones, arquitectura, soluciones). Si title empieza con "Mapa - " actualiza/crea el mapa del proyecto (se inyecta al inicio de cada sesi\xF3n).',
98
+ inputSchema: {
99
+ title: z.string(),
100
+ content: z.string().describe("Markdown; puede incluir [[wikilinks]] a otras notas"),
101
+ tags: z.array(z.string()).optional()
102
+ }
86
103
  },
87
104
  async ({ title, content, tags }) => {
88
105
  ensureVaultStructure(vault);
89
106
  if (!title.startsWith("Mapa - ") && !/\[\[/.test(content)) {
90
- const idxPre = VaultIndex.load(vault);
91
- const map = Object.values(idxPre.meta.notes).find(
92
- (n) => n.type === "map" || n.title.startsWith("Mapa - ")
93
- );
107
+ const map = findMap(VaultIndex.load(vault));
94
108
  if (map) content = `${content.trim()}
95
109
 
96
110
  Proyecto: [[${map.title}]]`;
@@ -113,10 +127,12 @@ Proyecto: [[${map.title}]]`;
113
127
  return text(`Guardado en ${path.relative(vault.root, file)}`);
114
128
  }
115
129
  );
116
- server.tool(
130
+ server.registerTool(
117
131
  "vault_related",
118
- "Vecinos de una nota en el grafo de conocimiento (wikilinks + conexiones sem\xE1nticas) \u2014 trae conocimiento conectado sin releer archivos.",
119
- { title: z.string().describe("T\xEDtulo o ruta relativa de la nota") },
132
+ {
133
+ description: "Vecinos de una nota en el grafo de conocimiento (wikilinks + conexiones sem\xE1nticas) \u2014 trae conocimiento conectado sin releer archivos.",
134
+ inputSchema: { title: z.string().describe("T\xEDtulo o ruta relativa de la nota") }
135
+ },
120
136
  async ({ title }) => {
121
137
  const idx = VaultIndex.load(vault);
122
138
  const lower = title.toLowerCase();
@@ -131,10 +147,12 @@ server.tool(
131
147
  );
132
148
  }
133
149
  );
134
- server.tool(
150
+ server.registerTool(
135
151
  "vault_link",
136
- "Crea una conexi\xF3n expl\xEDcita [[wikilink]] entre dos notas de la b\xF3veda.",
137
- { from: z.string(), to: z.string() },
152
+ {
153
+ description: "Crea una conexi\xF3n expl\xEDcita [[wikilink]] entre dos notas de la b\xF3veda.",
154
+ inputSchema: { from: z.string(), to: z.string() }
155
+ },
138
156
  async ({ from, to }) => {
139
157
  const idx = VaultIndex.load(vault);
140
158
  const find = (t) => Object.values(idx.meta.notes).find(
@@ -152,15 +170,17 @@ server.tool(
152
170
  return text(`Conectado: \xAB${a.title}\xBB \u2192 [[${b.title}]]`);
153
171
  }
154
172
  );
155
- server.tool(
173
+ server.registerTool(
156
174
  "plan_create",
157
- "PROTOCOLO paso 1 (solo tareas NO triviales \u2014 las simples resp\xF3ndelas directo, sin ceremonia): crea el plan como un ARQUITECTO. Si el objetivo es vago, haz 2-3 preguntas de aclaraci\xF3n al usuario ANTES de crear el plan (qu\xE9 es \xE9xito, restricciones, alcance). DoD = criterios verificables por comando; tareas chicas y en orden de construcci\xF3n. Para planes grandes pasa `design` (stack/decisiones de arquitectura). La respuesta trae planes similares previos y lecciones \u2014 \xFAsalos para planear mejor. Verifica cada tarea con task_verify.",
158
175
  {
159
- title: z.string().describe('Nombre corto del objetivo, ej. "Login con Google"'),
160
- goal: z.string().describe("Qu\xE9 se quiere lograr, en una o dos frases"),
161
- dod: z.array(z.string()).describe("Definition of Done: criterios verificables de \xE9xito"),
162
- tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables, en orden de construcci\xF3n"),
163
- design: z.string().optional().describe('Decisiones de arquitectura/stack del plan (el "blueprint"): qu\xE9 se eligi\xF3 y por qu\xE9. Recomendado en planes de >5 tareas.')
176
+ description: "PROTOCOLO paso 1 (solo tareas NO triviales \u2014 las simples resp\xF3ndelas directo, sin ceremonia): crea el plan como un ARQUITECTO. Si el objetivo es vago, haz 2-3 preguntas de aclaraci\xF3n al usuario ANTES de crear el plan (qu\xE9 es \xE9xito, restricciones, alcance). DoD = criterios verificables por comando; tareas chicas y en orden de construcci\xF3n. Para planes grandes pasa `design` (stack/decisiones de arquitectura). La respuesta trae planes similares previos y lecciones \u2014 \xFAsalos para planear mejor. Verifica cada tarea con task_verify.",
177
+ inputSchema: {
178
+ title: z.string().describe('Nombre corto del objetivo, ej. "Login con Google"'),
179
+ goal: z.string().describe("Qu\xE9 se quiere lograr, en una o dos frases"),
180
+ dod: z.array(z.string()).describe("Definition of Done: criterios verificables de \xE9xito"),
181
+ tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables, en orden de construcci\xF3n"),
182
+ design: z.string().optional().describe('Decisiones de arquitectura/stack del plan (el "blueprint"): qu\xE9 se eligi\xF3 y por qu\xE9. Recomendado en planes de >5 tareas.')
183
+ }
164
184
  },
165
185
  async ({ title, goal, dod, tasks, design }) => {
166
186
  ensureVaultStructure(vault);
@@ -180,11 +200,13 @@ ${dod.map((d) => `- [ ] ${d}`).join("\n")}`,
180
200
  ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
181
201
  map ? `Proyecto: [[${map.title}]]` : ""
182
202
  ].filter(Boolean).join("\n\n");
203
+ const cleanTitle = title.replace(/^\s*(plan\s*-\s*)+/i, "").trim() || title;
183
204
  const file = createNote(vault.managed, {
184
- title: `Plan - ${title}`,
205
+ title: `Plan - ${cleanTitle}`,
185
206
  type: "plan",
186
207
  status: "active",
187
- tags: ["plan"],
208
+ // tag del proyecto: el digest de inicio muestra solo los planes de este proyecto
209
+ tags: ["plan", path.basename(process.cwd())],
188
210
  dir: "notes",
189
211
  content
190
212
  });
@@ -198,17 +220,19 @@ ${extra}` : "")
198
220
  );
199
221
  }
200
222
  );
201
- server.tool(
223
+ server.registerTool(
202
224
  "task_verify",
203
- 'PROTOCOLO paso 2: verifica una tarea con EVIDENCIA REAL, no con tu palabra. Pasa verify_command (ej. "npm test", "npm run build", "curl -sf localhost:3000") y Alexandria lo EJECUTA \u2014 el veredicto sale del exit code real. Si no puedes correr un comando, pasa evidence textual, pero se marca como auto-reportado (m\xE1s d\xE9bil). Si falla, busca lecciones previas antes de improvisar.',
204
225
  {
205
- plan: z.string().describe('T\xEDtulo del plan al que pertenece (ej. "Plan - Login con Google")'),
206
- task: z.string().describe("Qu\xE9 tarea se verific\xF3"),
207
- passed: z.boolean().describe("Lo que T\xDA crees que pas\xF3 (se compara contra el resultado real del comando)"),
208
- verify_command: z.string().optional().describe('Comando a EJECUTAR para verificar de verdad; exit 0 = pas\xF3. Ej. "npm test", "npm run build". Preferido sobre evidence.'),
209
- cwd: z.string().optional().describe("Directorio donde correr verify_command. Por defecto se usa el del agente (a menudo la RA\xCDZ del workspace, no tu subproyecto): si tu comando usa rutas relativas, pasa aqu\xED la carpeta del proyecto."),
210
- evidence: z.string().optional().describe("Solo si NO hay comando: evidencia textual (queda marcada como auto-reportada, sin verificar)."),
211
- completes_plan: z.boolean().optional().describe("true si esta era la \xFAltima tarea y el plan queda completado")
226
+ description: 'PROTOCOLO paso 2: verifica una tarea con EVIDENCIA REAL, no con tu palabra. Pasa verify_command (ej. "npm test", "npm run build", "curl -sf localhost:3000") y Alexandria lo EJECUTA \u2014 el veredicto sale del exit code real. Si no puedes correr un comando, pasa evidence textual, pero se marca como auto-reportado (m\xE1s d\xE9bil). Si falla, busca lecciones previas antes de improvisar.',
227
+ inputSchema: {
228
+ plan: z.string().describe('T\xEDtulo del plan al que pertenece, tal como lo devolvi\xF3 plan_create (ej. "Plan - Login con Google")'),
229
+ task: z.string().describe("Qu\xE9 tarea se verific\xF3"),
230
+ passed: z.boolean().describe("Lo que T\xDA crees que pas\xF3 (se compara contra el resultado real del comando)"),
231
+ verify_command: z.string().optional().describe('Comando a EJECUTAR para verificar de verdad; exit 0 = pas\xF3. Ej. "npm test", "npm run build". Preferido sobre evidence.'),
232
+ cwd: z.string().optional().describe("Directorio donde correr verify_command. Por defecto se usa el del agente (a menudo la RA\xCDZ del workspace, no tu subproyecto): si tu comando usa rutas relativas, pasa aqu\xED la carpeta del proyecto."),
233
+ evidence: z.string().optional().describe("Solo si NO hay comando: evidencia textual (queda marcada como auto-reportada, sin verificar)."),
234
+ completes_plan: z.boolean().optional().describe("true si esta era la \xFAltima tarea y el plan queda completado")
235
+ }
212
236
  },
213
237
  async ({ plan, task, passed, verify_command, cwd, evidence, completes_plan }) => {
214
238
  ensureVaultStructure(vault);
@@ -295,13 +319,15 @@ Sin lecciones previas \u2014 cuando lo resuelvas, gu\xE1rdala con lesson_extract
295
319
  );
296
320
  }
297
321
  );
298
- server.tool(
322
+ server.registerTool(
299
323
  "lesson_extract",
300
- "PROTOCOLO paso 3: al resolver un error o terminar un plan, destila LA lecci\xF3n (qu\xE9 fall\xF3/funcion\xF3 y c\xF3mo evitarlo/repetirlo). 200 tokens hoy ahorran 20,000 de re-debug ma\xF1ana. Se inyecta autom\xE1ticamente cuando el problema reaparezca.",
301
324
  {
302
- title: z.string().describe('Lecci\xF3n en una frase, ej. "GOOGLE_CLIENT_SECRET debe ir en .env"'),
303
- lesson: z.string().describe("Qu\xE9 pas\xF3, causa ra\xEDz, y c\xF3mo aplicarla la pr\xF3xima vez"),
304
- links: z.array(z.string()).optional().describe("T\xEDtulos de notas relacionadas (plan, feature, etc.)")
325
+ description: "PROTOCOLO paso 3: al resolver un error o terminar un plan, destila LA lecci\xF3n (qu\xE9 fall\xF3/funcion\xF3 y c\xF3mo evitarlo/repetirlo). 200 tokens hoy ahorran 20,000 de re-debug ma\xF1ana. Se inyecta autom\xE1ticamente cuando el problema reaparezca.",
326
+ inputSchema: {
327
+ title: z.string().describe('Lecci\xF3n en una frase, ej. "GOOGLE_CLIENT_SECRET debe ir en .env"'),
328
+ lesson: z.string().describe("Qu\xE9 pas\xF3, causa ra\xEDz, y c\xF3mo aplicarla la pr\xF3xima vez"),
329
+ links: z.array(z.string()).optional().describe("T\xEDtulos de notas relacionadas (plan, feature, etc.)")
330
+ }
305
331
  },
306
332
  async ({ title, lesson, links }) => {
307
333
  ensureVaultStructure(vault);
@@ -4,8 +4,8 @@ import {
4
4
  renderGraphHtml,
5
5
  serveGraph,
6
6
  writeStaticGraph
7
- } from "./chunk-FBGIFNIO.js";
8
- import "./chunk-QB37UGO6.js";
7
+ } from "./chunk-4ZSTD3CU.js";
8
+ import "./chunk-3CB7GRFJ.js";
9
9
  import "./chunk-EDYBSJSS.js";
10
10
  export {
11
11
  buildGraphData,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ureck/alexandria",
3
- "version": "1.3.2",
4
- "description": "Alexandria — bóveda de conocimiento local para agentes de IA (Claude Code, Cursor, OpenCode, Windsurf y más): captura automática, búsqueda semántica offline y grafo de conexiones estilo Obsidian. Ahorra tokens inyectando solo el contexto relevante.",
3
+ "version": "1.4.0",
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",
7
7
  "bin": {
@@ -30,25 +30,32 @@
30
30
  "semantic-search",
31
31
  "mcp",
32
32
  "embeddings",
33
- "local-first"
33
+ "local-first",
34
+ "codex",
35
+ "gemini-cli",
36
+ "cursor",
37
+ "opencode",
38
+ "hooks",
39
+ "ai-memory",
40
+ "agents-md"
34
41
  ],
35
42
  "dependencies": {
36
- "@huggingface/transformers": "^3.3.3",
37
- "@modelcontextprotocol/sdk": "^1.12.1",
38
- "commander": "^13.1.0",
43
+ "@huggingface/transformers": "^4.3.2",
44
+ "@modelcontextprotocol/sdk": "^1.32.2",
45
+ "commander": "^15.0.0",
39
46
  "gray-matter": "^4.0.3",
40
47
  "minisearch": "^7.1.2",
41
48
  "picocolors": "^1.1.1",
42
- "zod": "^3.24.2"
49
+ "zod": "^4.6.7"
43
50
  },
44
51
  "overrides": {
45
- "sharp": "^0.35.4"
52
+ "sharp": "^0.35.5"
46
53
  },
47
54
  "devDependencies": {
48
- "@types/node": "^22.13.0",
49
- "tsup": "^8.4.0",
55
+ "@types/node": "^22.20.5",
56
+ "tsup": "^9.0.0",
50
57
  "typescript": "^5.7.3",
51
- "vitest": "^3.0.5"
58
+ "vitest": "^5.0.5"
52
59
  },
53
60
  "author": "Ureck <urielgomezbecerril@gmail.com>",
54
61
  "publishConfig": {
@@ -58,7 +65,7 @@
58
65
  "type": "git",
59
66
  "url": "git+https://github.com/UreckChan/alexandria.git"
60
67
  },
61
- "homepage": "https://github.com/UreckChan/alexandria#readme",
68
+ "homepage": "https://alexandria.ureck.dev",
62
69
  "bugs": {
63
70
  "url": "https://github.com/UreckChan/alexandria/issues"
64
71
  }
@@ -1,54 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/core/stats.ts
4
- import fs from "fs";
5
- import path from "path";
6
- var charsToTokens = (chars) => Math.round(chars / 4);
7
- function logInjection(vault, line) {
8
- try {
9
- fs.mkdirSync(vault.cache, { recursive: true });
10
- fs.appendFileSync(
11
- path.join(vault.cache, "stats.jsonl"),
12
- JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), ...line }) + "\n"
13
- );
14
- } catch {
15
- }
16
- }
17
- var EST_LOW = 3;
18
- var EST_HIGH = 8;
19
- function readStats(vault) {
20
- const file = path.join(vault.cache, "stats.jsonl");
21
- const summary = {
22
- injections: 0,
23
- solutionCacheHits: 0,
24
- injectedTokens: 0,
25
- cacheHitTokens: 0,
26
- estSavedLow: 0,
27
- estSavedHigh: 0
28
- };
29
- try {
30
- for (const raw of fs.readFileSync(file, "utf8").split("\n")) {
31
- if (!raw.trim()) continue;
32
- try {
33
- const line = JSON.parse(raw);
34
- summary.injections++;
35
- const tk = charsToTokens(line.injectedChars);
36
- summary.injectedTokens += tk;
37
- if (line.kind === "solution-cache") {
38
- summary.solutionCacheHits++;
39
- summary.cacheHitTokens += tk;
40
- }
41
- } catch {
42
- }
43
- }
44
- } catch {
45
- }
46
- summary.estSavedLow = summary.injectedTokens * EST_LOW;
47
- summary.estSavedHigh = summary.injectedTokens * EST_HIGH;
48
- return summary;
49
- }
50
-
51
- export {
52
- logInjection,
53
- readStats
54
- };