@ureck/alexandria 1.1.0 → 1.3.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.
@@ -6,20 +6,19 @@ import {
6
6
  projectName,
7
7
  runHook,
8
8
  truncate
9
- } from "../chunk-DEDAOKAV.js";
9
+ } from "../chunk-53SIGH5A.js";
10
10
  import {
11
11
  hybridSearch
12
- } from "../chunk-AHBSZGSC.js";
12
+ } from "../chunk-UWB6RKVN.js";
13
13
  import {
14
14
  resolveVault,
15
15
  toggleEnabled,
16
16
  vaultExists
17
- } from "../chunk-TFQ7WSIB.js";
18
- import "../chunk-AXUEYSNZ.js";
17
+ } from "../chunk-CIOCSIB5.js";
19
18
  import {
20
19
  createNote,
21
20
  touchNote
22
- } from "../chunk-XWR74BQ2.js";
21
+ } from "../chunk-QB37UGO6.js";
23
22
  import "../chunk-EDYBSJSS.js";
24
23
 
25
24
  // src/hooks/on-prompt.ts
@@ -31,12 +30,13 @@ var DEDUP_COSINE = 0.93;
31
30
  var SOLUTION_COSINE = 0.93;
32
31
  var RELEVANT_COSINE = 0.82;
33
32
  var RELEVANT_MARGIN = 0.04;
34
- runHook(25e3, async (input) => {
33
+ var KEYWORD_REL_FACTOR = 0.6;
34
+ runHook(5e3, async (input) => {
35
35
  const prompt = (input.prompt ?? "").trim();
36
36
  if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/")) return;
37
37
  const vault = resolveVault({ cwd: input.cwd });
38
38
  if (!vaultExists(vault)) return;
39
- const rawResults = await hybridSearch(vault, prompt, 5, { expand: true });
39
+ const rawResults = await hybridSearch(vault, prompt, 5, { expand: true, refresh: false });
40
40
  const STALE_DAYS = 60;
41
41
  const results = rawResults.filter((r) => {
42
42
  if (r.note.type !== "prompt" && r.note.type !== "session") return true;
@@ -45,7 +45,14 @@ runHook(25e3, async (input) => {
45
45
  return age <= STALE_DAYS;
46
46
  });
47
47
  const maxCos = results.reduce((m, r) => Math.max(m, r.cosine), 0);
48
- const relevant = maxCos > 0 ? results.filter((r) => r.cosine >= RELEVANT_COSINE && r.cosine >= maxCos - RELEVANT_MARGIN) : results.filter((r) => r.score > 0.02);
48
+ const maxScore = results.reduce((m, r) => Math.max(m, r.score), 0);
49
+ const relevant = maxCos > 0 ? results.filter((r) => r.cosine >= RELEVANT_COSINE && r.cosine >= maxCos - RELEVANT_MARGIN) : (
50
+ // Keyword-only: criterio RELATIVO al mejor resultado, nunca absoluto. El
51
+ // umbral fijo de 0.02 era inalcanzable — el RRF máximo es 1/(60+1)=0.0164,
52
+ // así que notas tipo note/session/prompt (boost ≤1.0) jamás lo cruzaban y
53
+ // la mayoría de la bóveda quedaba invisible en modo degradado.
54
+ results.filter((r) => maxScore > 0 && r.score >= maxScore * KEYWORD_REL_FACTOR).slice(0, 3)
55
+ );
49
56
  const solutionCacheOn = toggleEnabled("tokens.solutionCache");
50
57
  const promptSearchOn = toggleEnabled("tokens.promptSearch");
51
58
  let injected = "";
@@ -6,17 +6,16 @@ import {
6
6
  projectName,
7
7
  runHook,
8
8
  truncate
9
- } from "../chunk-DEDAOKAV.js";
9
+ } from "../chunk-53SIGH5A.js";
10
10
  import {
11
11
  protocolEnabled,
12
12
  resolveVault,
13
13
  toggleEnabled,
14
14
  vaultExists
15
- } from "../chunk-TFQ7WSIB.js";
15
+ } from "../chunk-CIOCSIB5.js";
16
16
  import {
17
17
  VaultIndex
18
- } from "../chunk-AXUEYSNZ.js";
19
- import "../chunk-XWR74BQ2.js";
18
+ } from "../chunk-QB37UGO6.js";
20
19
  import "../chunk-EDYBSJSS.js";
21
20
 
22
21
  // src/hooks/on-session-start.ts
@@ -3,18 +3,24 @@ import {
3
3
  projectName,
4
4
  runHook,
5
5
  truncate
6
- } from "../chunk-DEDAOKAV.js";
6
+ } from "../chunk-53SIGH5A.js";
7
7
  import {
8
8
  ensureVaultStructure,
9
9
  resolveVault,
10
+ toggleEnabled,
10
11
  vaultExists
11
- } from "../chunk-TFQ7WSIB.js";
12
+ } from "../chunk-CIOCSIB5.js";
12
13
  import {
14
+ VaultIndex,
13
15
  appendToNote
14
- } from "../chunk-XWR74BQ2.js";
16
+ } from "../chunk-QB37UGO6.js";
17
+ import "../chunk-EDYBSJSS.js";
15
18
 
16
19
  // src/hooks/on-stop.ts
17
20
  import fs from "fs";
21
+ import path from "path";
22
+ import { spawn } from "child_process";
23
+ import { fileURLToPath } from "url";
18
24
  function textOf(msg) {
19
25
  const c = msg.message?.content;
20
26
  if (typeof c === "string") return c;
@@ -62,4 +68,22 @@ runHook(25e3, async (input) => {
62
68
 
63
69
  Proyecto: [[Mapa - ${proj}]]`
64
70
  });
71
+ await maybeRebuildInBackground(vault);
65
72
  });
73
+ async function maybeRebuildInBackground(vault) {
74
+ try {
75
+ if (!toggleEnabled("index.autoRebuild")) return;
76
+ const idx = VaultIndex.load(vault);
77
+ if (!idx.needsRebuild() && !idx.isDegraded()) return;
78
+ const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cli.js");
79
+ if (!fs.existsSync(cli)) return;
80
+ const child = spawn(process.execPath, [cli, "--vault", vault.root, "reindex", "--force"], {
81
+ detached: true,
82
+ stdio: "ignore",
83
+ env: { ...process.env, ALEXANDRIA_HOOK: "" }
84
+ // proceso CLI: sí puede reconstruir
85
+ });
86
+ child.unref();
87
+ } catch {
88
+ }
89
+ }
@@ -4,24 +4,22 @@ import {
4
4
  pkgVersion,
5
5
  planContext,
6
6
  planQualityHints
7
- } from "../chunk-T5VNBQEC.js";
7
+ } from "../chunk-ZIQYAQCF.js";
8
8
  import {
9
9
  hybridSearch
10
- } from "../chunk-AHBSZGSC.js";
10
+ } from "../chunk-UWB6RKVN.js";
11
11
  import {
12
12
  ensureVaultStructure,
13
13
  resolveVault,
14
14
  toggleEnabled
15
- } from "../chunk-TFQ7WSIB.js";
16
- import {
17
- VaultIndex
18
- } from "../chunk-AXUEYSNZ.js";
15
+ } from "../chunk-CIOCSIB5.js";
19
16
  import {
17
+ VaultIndex,
20
18
  createNote,
21
19
  setNoteStatus,
22
20
  slugify,
23
21
  upsertNote
24
- } from "../chunk-XWR74BQ2.js";
22
+ } from "../chunk-QB37UGO6.js";
25
23
  import "../chunk-EDYBSJSS.js";
26
24
 
27
25
  // src/mcp/server.ts
@@ -188,10 +186,11 @@ server.tool(
188
186
  task: z.string().describe("Qu\xE9 tarea se verific\xF3"),
189
187
  passed: z.boolean().describe("Lo que T\xDA crees que pas\xF3 (se compara contra el resultado real del comando)"),
190
188
  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.'),
189
+ 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."),
191
190
  evidence: z.string().optional().describe("Solo si NO hay comando: evidencia textual (queda marcada como auto-reportada, sin verificar)."),
192
191
  completes_plan: z.boolean().optional().describe("true si esta era la \xFAltima tarea y el plan queda completado")
193
192
  },
194
- async ({ plan, task, passed, verify_command, evidence, completes_plan }) => {
193
+ async ({ plan, task, passed, verify_command, cwd, evidence, completes_plan }) => {
195
194
  ensureVaultStructure(vault);
196
195
  const idx = VaultIndex.load(vault);
197
196
  const planNote = findByTitle(idx, plan);
@@ -199,11 +198,12 @@ server.tool(
199
198
  let realEvidence;
200
199
  let verified = false;
201
200
  let discrepancy = "";
201
+ const runDir = cwd?.trim() && fs.existsSync(cwd.trim()) ? cwd.trim() : process.cwd();
202
202
  if (verify_command && verify_command.trim()) {
203
203
  verified = true;
204
204
  try {
205
205
  const out = execSync(verify_command, {
206
- cwd: process.cwd(),
206
+ cwd: runDir,
207
207
  timeout: 18e4,
208
208
  encoding: "utf8",
209
209
  stdio: ["ignore", "pipe", "pipe"],
@@ -211,14 +211,14 @@ server.tool(
211
211
  });
212
212
  realPassed = true;
213
213
  realEvidence = `$ ${verify_command}
214
- (exit 0)
214
+ (cwd: ${runDir}, exit 0)
215
215
  ${tail(out, 1500)}`;
216
216
  } catch (e) {
217
217
  const err = e;
218
218
  realPassed = false;
219
219
  const output = ((err.stdout ?? "") + "\n" + (err.stderr ?? "")).trim() || err.message;
220
220
  realEvidence = `$ ${verify_command}
221
- (exit ${err.status ?? "\u22600"})
221
+ (cwd: ${runDir}, exit ${err.status ?? "\u22600"})
222
222
  ${tail(output, 1500)}`;
223
223
  }
224
224
  if (passed !== realPassed) {
@@ -4,9 +4,8 @@ import {
4
4
  renderGraphHtml,
5
5
  serveGraph,
6
6
  writeStaticGraph
7
- } from "./chunk-XY7U4CAQ.js";
8
- import "./chunk-AXUEYSNZ.js";
9
- import "./chunk-XWR74BQ2.js";
7
+ } from "./chunk-FBGIFNIO.js";
8
+ import "./chunk-QB37UGO6.js";
10
9
  import "./chunk-EDYBSJSS.js";
11
10
  export {
12
11
  buildGraphData,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ureck/alexandria",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
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.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1,44 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/hooks/util.ts
4
- async function readStdinJson() {
5
- const chunks = [];
6
- for await (const chunk of process.stdin) chunks.push(chunk);
7
- const raw = Buffer.concat(chunks).toString("utf8").trim();
8
- if (!raw) return {};
9
- try {
10
- return JSON.parse(raw);
11
- } catch {
12
- return {};
13
- }
14
- }
15
- function runHook(budgetMs, body) {
16
- const cleanup = async () => {
17
- try {
18
- const { disposeEmbedder } = await import("./embedder-7Z4XNL6H.js");
19
- await disposeEmbedder();
20
- } catch {
21
- }
22
- };
23
- const timer = setTimeout(() => void cleanup(), budgetMs);
24
- timer.unref();
25
- process.exitCode = 0;
26
- readStdinJson().then((input) => body(input)).catch(() => {
27
- }).finally(() => {
28
- clearTimeout(timer);
29
- void cleanup();
30
- });
31
- }
32
- function projectName(cwd) {
33
- if (!cwd) return "general";
34
- return cwd.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || "general";
35
- }
36
- function truncate(text, max) {
37
- return text.length <= max ? text : text.slice(0, max) + " \u2026";
38
- }
39
-
40
- export {
41
- runHook,
42
- projectName,
43
- truncate
44
- };
@@ -1,170 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/core/notes.ts
4
- import fs from "fs";
5
- import path from "path";
6
- import matter from "gray-matter";
7
- var NOTE_TYPES = [
8
- "note",
9
- "prompt",
10
- "session",
11
- "map",
12
- "plan",
13
- "task",
14
- "verification",
15
- "lesson",
16
- "solution"
17
- ];
18
- var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
19
- function extractWikilinks(content) {
20
- const out = /* @__PURE__ */ new Set();
21
- const re = /\[\[([^\]|#\n]+)(?:[|#][^\]]*)?\]\]/g;
22
- let m;
23
- while ((m = re.exec(content)) !== null) {
24
- const target = m[1].trim();
25
- if (target) out.add(target);
26
- }
27
- return [...out];
28
- }
29
- function slugify(text) {
30
- return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
31
- }
32
- function listMarkdownFiles(root) {
33
- const out = [];
34
- const walk = (dir) => {
35
- let entries;
36
- try {
37
- entries = fs.readdirSync(dir, { withFileTypes: true });
38
- } catch {
39
- return;
40
- }
41
- for (const e of entries) {
42
- if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
43
- const full = path.join(dir, e.name);
44
- if (e.isDirectory()) walk(full);
45
- else if (e.isFile() && e.name.endsWith(".md")) out.push(full);
46
- }
47
- };
48
- walk(root);
49
- return out;
50
- }
51
- function parseNote(root, absPath) {
52
- const raw = fs.readFileSync(absPath, "utf8");
53
- const { data, content } = matter(raw);
54
- const rel = path.relative(root, absPath).split(path.sep).join("/");
55
- const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
56
- const type = NOTE_TYPES.includes(data.type) ? data.type : "note";
57
- const status = ["active", "completed", "failed"].includes(data.status) ? data.status : void 0;
58
- const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
59
- return {
60
- rel,
61
- title,
62
- type,
63
- status,
64
- tags,
65
- created: data.created ? String(data.created) : void 0,
66
- hits: typeof data.hits === "number" ? data.hits : 1,
67
- content,
68
- links: extractWikilinks(content)
69
- };
70
- }
71
- function frontmatter(n) {
72
- const lines = [
73
- "---",
74
- `title: ${JSON.stringify(n.title)}`,
75
- // aliases: Obsidian resuelve [[wikilinks]] contra alias, no contra el title
76
- // del frontmatter — sin esto su graph view muestra los enlaces como rotos
77
- `aliases: [${JSON.stringify(n.title)}]`,
78
- `type: ${n.type}`,
79
- ...n.status ? [`status: ${n.status}`] : [],
80
- `tags: [${n.tags.map((t) => JSON.stringify(t)).join(", ")}]`,
81
- `created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
82
- `hits: ${n.hits ?? 1}`,
83
- "---",
84
- ""
85
- ];
86
- return lines.join("\n");
87
- }
88
- function ensureAlias(absPath) {
89
- try {
90
- const raw = fs.readFileSync(absPath, "utf8");
91
- const { data, content } = matter(raw);
92
- if (!data.title || data.aliases) return false;
93
- data.aliases = [String(data.title)];
94
- fs.writeFileSync(absPath, matter.stringify(content, data));
95
- return true;
96
- } catch {
97
- return false;
98
- }
99
- }
100
- function createNote(managed, n) {
101
- const dir = path.join(managed, n.dir ?? "notes");
102
- fs.mkdirSync(dir, { recursive: true });
103
- const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
104
- const base = `${date}-${slugify(n.title)}`;
105
- let file = path.join(dir, `${base}.md`);
106
- let i = 2;
107
- while (fs.existsSync(file)) file = path.join(dir, `${base}-${i++}.md`);
108
- fs.writeFileSync(
109
- file,
110
- frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
111
- );
112
- return file;
113
- }
114
- function setNoteStatus(absPath, status) {
115
- const raw = fs.readFileSync(absPath, "utf8");
116
- const { data, content } = matter(raw);
117
- data.status = status;
118
- data.updated = (/* @__PURE__ */ new Date()).toISOString();
119
- fs.writeFileSync(absPath, matter.stringify(content, data));
120
- }
121
- function touchNote(absPath) {
122
- const raw = fs.readFileSync(absPath, "utf8");
123
- const { data, content } = matter(raw);
124
- data.hits = (typeof data.hits === "number" ? data.hits : 1) + 1;
125
- data.updated = (/* @__PURE__ */ new Date()).toISOString();
126
- fs.writeFileSync(absPath, matter.stringify(content, data));
127
- }
128
- function upsertNote(managed, n) {
129
- const dir = path.join(managed, n.dir ?? "notes");
130
- fs.mkdirSync(dir, { recursive: true });
131
- const file = path.join(dir, `${n.fixedName}.md`);
132
- if (fs.existsSync(file)) {
133
- const raw = fs.readFileSync(file, "utf8");
134
- const { data } = matter(raw);
135
- data.updated = (/* @__PURE__ */ new Date()).toISOString();
136
- fs.writeFileSync(file, matter.stringify(n.content.trim() + "\n", data));
137
- } else {
138
- fs.writeFileSync(
139
- file,
140
- frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
141
- );
142
- }
143
- return file;
144
- }
145
- function appendToNote(managed, n) {
146
- const dir = path.join(managed, n.dir ?? "sessions");
147
- fs.mkdirSync(dir, { recursive: true });
148
- const file = path.join(dir, `${n.fixedName}.md`);
149
- if (fs.existsSync(file)) {
150
- fs.appendFileSync(file, "\n" + n.content.trim() + "\n");
151
- } else {
152
- fs.writeFileSync(
153
- file,
154
- frontmatter({ title: n.title, type: n.type ?? "session", tags: n.tags ?? [], status: n.status }) + n.content.trim() + "\n"
155
- );
156
- }
157
- return file;
158
- }
159
-
160
- export {
161
- slugify,
162
- listMarkdownFiles,
163
- parseNote,
164
- ensureAlias,
165
- createNote,
166
- setNoteStatus,
167
- touchNote,
168
- upsertNote,
169
- appendToNote
170
- };