@ureck/alexandria 0.2.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.
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DIM,
4
+ MODEL_ID,
5
+ chunkMarkdown,
6
+ disposeEmbedder,
7
+ dot,
8
+ embed,
9
+ getEmbedder,
10
+ modelCacheDir,
11
+ modelPresent
12
+ } from "./chunk-EDYBSJSS.js";
13
+ export {
14
+ DIM,
15
+ MODEL_ID,
16
+ chunkMarkdown,
17
+ disposeEmbedder,
18
+ dot,
19
+ embed,
20
+ getEmbedder,
21
+ modelCacheDir,
22
+ modelPresent
23
+ };
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ logInjection
4
+ } from "../chunk-OPUPZRP6.js";
5
+ import {
6
+ projectName,
7
+ runHook,
8
+ truncate
9
+ } from "../chunk-DEDAOKAV.js";
10
+ import {
11
+ hybridSearch
12
+ } from "../chunk-O7FDC2PB.js";
13
+ import "../chunk-UWAIMIG2.js";
14
+ import {
15
+ createNote,
16
+ resolveVault,
17
+ touchNote,
18
+ vaultExists
19
+ } from "../chunk-CZM5NQZJ.js";
20
+ import "../chunk-EDYBSJSS.js";
21
+
22
+ // src/hooks/on-prompt.ts
23
+ import fs from "fs";
24
+ import path from "path";
25
+ var MAX_INJECT_CHARS = 6e3;
26
+ var MIN_PROMPT_CHARS = 20;
27
+ var DEDUP_COSINE = 0.93;
28
+ var SOLUTION_COSINE = 0.93;
29
+ var RELEVANT_COSINE = 0.82;
30
+ var RELEVANT_MARGIN = 0.04;
31
+ runHook(25e3, async (input) => {
32
+ const prompt = (input.prompt ?? "").trim();
33
+ if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/")) return;
34
+ const vault = resolveVault({ cwd: input.cwd });
35
+ if (!vaultExists(vault)) return;
36
+ const results = await hybridSearch(vault, prompt, 5, { expand: true });
37
+ const maxCos = results.reduce((m, r) => Math.max(m, r.cosine), 0);
38
+ const relevant = maxCos > 0 ? results.filter((r) => r.cosine >= RELEVANT_COSINE && r.cosine >= maxCos - RELEVANT_MARGIN) : results.filter((r) => r.score > 0.02);
39
+ let injected = "";
40
+ if (relevant.length > 0) {
41
+ const cached = relevant.find(
42
+ (r) => (r.note.type === "prompt" || r.note.type === "session") && r.cosine >= SOLUTION_COSINE
43
+ );
44
+ const lines = [];
45
+ if (cached) {
46
+ lines.push(
47
+ `\u26A1 Ya resolviste algo casi id\xE9ntico antes (\xAB${cached.note.title}\xBB). Reutiliza esa soluci\xF3n en vez de re-derivarla:
48
+ ${truncate(cached.excerpts.join("\n"), 2e3)}`
49
+ );
50
+ }
51
+ for (const r of relevant) {
52
+ if (r === cached) continue;
53
+ lines.push(`\u2022 \xAB${r.note.title}\xBB (${r.note.rel}):
54
+ ${truncate(r.excerpts.join("\n"), 900)}`);
55
+ if (lines.join("\n\n").length > MAX_INJECT_CHARS) break;
56
+ }
57
+ injected = `<alexandria-contexto>
58
+ Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o re-explorar):
59
+
60
+ ` + truncate(lines.join("\n\n"), MAX_INJECT_CHARS) + `
61
+ </alexandria-contexto>`;
62
+ process.stdout.write(injected);
63
+ logInjection(vault, {
64
+ kind: cached ? "solution-cache" : "inject",
65
+ injectedChars: injected.length,
66
+ promptChars: prompt.length
67
+ });
68
+ }
69
+ const dupe = results.find((r) => r.note.type === "prompt" && r.cosine >= DEDUP_COSINE);
70
+ if (dupe) {
71
+ try {
72
+ touchNote(path.join(vault.root, dupe.note.rel));
73
+ } catch {
74
+ }
75
+ return;
76
+ }
77
+ const proj = projectName(input.cwd);
78
+ const title = truncate(prompt.replace(/\s+/g, " "), 70);
79
+ fs.mkdirSync(vault.managed, { recursive: true });
80
+ createNote(vault.managed, {
81
+ title,
82
+ type: "prompt",
83
+ tags: [proj],
84
+ dir: "prompts",
85
+ content: `Proyecto: [[Mapa - ${proj}]]
86
+
87
+ ## Prompt
88
+
89
+ ${truncate(prompt, 4e3)}`
90
+ });
91
+ });
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ logInjection
4
+ } from "../chunk-OPUPZRP6.js";
5
+ import {
6
+ projectName,
7
+ runHook,
8
+ truncate
9
+ } from "../chunk-DEDAOKAV.js";
10
+ import {
11
+ VaultIndex
12
+ } from "../chunk-UWAIMIG2.js";
13
+ import {
14
+ resolveVault,
15
+ vaultExists
16
+ } from "../chunk-CZM5NQZJ.js";
17
+ import "../chunk-EDYBSJSS.js";
18
+
19
+ // src/hooks/on-session-start.ts
20
+ import fs from "fs";
21
+ import path from "path";
22
+ var MAX_CHARS = 8e3;
23
+ runHook(15e3, async (input) => {
24
+ const vault = resolveVault({ cwd: input.cwd });
25
+ if (!vaultExists(vault)) return;
26
+ const idx = VaultIndex.load(vault);
27
+ await idx.refresh(false).catch(() => {
28
+ });
29
+ const notes = Object.values(idx.meta.notes);
30
+ if (notes.length === 0) return;
31
+ const proj = projectName(input.cwd);
32
+ const parts = [];
33
+ const map = notes.find(
34
+ (n) => (n.type === "map" || n.title.toLowerCase().startsWith("mapa - ")) && n.title.toLowerCase().includes(proj.toLowerCase())
35
+ );
36
+ if (map) {
37
+ try {
38
+ const raw = fs.readFileSync(path.join(vault.root, map.rel), "utf8");
39
+ const body = raw.replace(/^---[\s\S]*?---\n/, "");
40
+ parts.push(`## Mapa del proyecto \xAB${proj}\xBB (conocimiento previo \u2014 NO re-explorar lo ya mapeado)
41
+ ${truncate(body.trim(), 4e3)}`);
42
+ } catch {
43
+ }
44
+ }
45
+ const sessions = notes.filter((n) => n.type === "session").sort((a, b) => (b.created ?? "").localeCompare(a.created ?? "")).slice(0, 3);
46
+ if (sessions.length > 0) {
47
+ const lines = sessions.map((s) => `- ${s.title} (${(s.created ?? "").slice(0, 10)})`);
48
+ parts.push(`## Sesiones recientes en la b\xF3veda
49
+ ${lines.join("\n")}`);
50
+ }
51
+ const titles = notes.filter((n) => n.type !== "prompt").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1)).slice(0, 25).map((n) => n.title);
52
+ if (titles.length > 0) {
53
+ parts.push(`## La b\xF3veda ya tiene conocimiento sobre
54
+ ${titles.join(" \xB7 ")}`);
55
+ }
56
+ if (parts.length === 0) return;
57
+ const digest = `<alexandria-digest>
58
+ B\xF3veda de conocimiento local activa (${notes.length} notas). ANTES de explorar c\xF3digo o re-derivar contexto, usa la herramienta MCP vault_search \u2014 ahorra tokens. Cuando descubras arquitectura o decisiones nuevas, gu\xE1rdalas con vault_save (title: "Mapa - ${proj}").
59
+
60
+ ` + truncate(parts.join("\n\n"), MAX_CHARS) + `
61
+ </alexandria-digest>`;
62
+ process.stdout.write(digest);
63
+ logInjection(vault, { kind: "session-start", injectedChars: digest.length });
64
+ });
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ projectName,
4
+ runHook,
5
+ truncate
6
+ } from "../chunk-DEDAOKAV.js";
7
+ import {
8
+ appendToNote,
9
+ ensureVaultStructure,
10
+ resolveVault,
11
+ vaultExists
12
+ } from "../chunk-CZM5NQZJ.js";
13
+
14
+ // src/hooks/on-stop.ts
15
+ import fs from "fs";
16
+ function textOf(msg) {
17
+ const c = msg.message?.content;
18
+ if (typeof c === "string") return c;
19
+ if (Array.isArray(c)) {
20
+ return c.filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("\n");
21
+ }
22
+ return "";
23
+ }
24
+ runHook(25e3, async (input) => {
25
+ if (!input.transcript_path || !fs.existsSync(input.transcript_path)) return;
26
+ const vault = resolveVault({ cwd: input.cwd });
27
+ if (!vaultExists(vault)) return;
28
+ ensureVaultStructure(vault);
29
+ const raw = fs.readFileSync(input.transcript_path, "utf8");
30
+ const lines = raw.split("\n").filter(Boolean);
31
+ let lastUser = "";
32
+ let lastAssistant = "";
33
+ for (const line of lines.slice(-200)) {
34
+ try {
35
+ const msg = JSON.parse(line);
36
+ const text = textOf(msg).trim();
37
+ if (!text) continue;
38
+ if (msg.type === "user" && !text.startsWith("<")) lastUser = text;
39
+ if (msg.type === "assistant") lastAssistant = text;
40
+ } catch {
41
+ }
42
+ }
43
+ if (!lastAssistant) return;
44
+ const proj = projectName(input.cwd);
45
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
46
+ const sid = (input.session_id ?? "sesion").slice(0, 8);
47
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().slice(11, 16);
48
+ const isCompact = input.hook_event_name === "PreCompact" || Boolean(input.trigger);
49
+ appendToNote(vault.managed, {
50
+ fixedName: `${date}-${proj}-${sid}`,
51
+ title: `Sesi\xF3n ${date} \u2014 ${proj}`,
52
+ type: "session",
53
+ tags: [proj, "sesion"],
54
+ dir: "sessions",
55
+ content: `## ${stamp}${isCompact ? " (pre-compactaci\xF3n)" : ""}
56
+
57
+ ` + (lastUser ? `**Pregunta:** ${truncate(lastUser.replace(/\s+/g, " "), 500)}
58
+
59
+ ` : "") + `**Resultado:** ${truncate(lastAssistant, 2500)}
60
+
61
+ Proyecto: [[Mapa - ${proj}]]`
62
+ });
63
+ });
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ hybridSearch
4
+ } from "../chunk-O7FDC2PB.js";
5
+ import {
6
+ VaultIndex
7
+ } from "../chunk-UWAIMIG2.js";
8
+ import {
9
+ createNote,
10
+ ensureVaultStructure,
11
+ resolveVault,
12
+ slugify,
13
+ upsertNote
14
+ } from "../chunk-CZM5NQZJ.js";
15
+ import "../chunk-EDYBSJSS.js";
16
+
17
+ // src/mcp/server.ts
18
+ import path from "path";
19
+ import fs from "fs";
20
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
21
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
22
+ import { z } from "zod";
23
+ var vault = resolveVault({ cwd: process.cwd() });
24
+ var server = new McpServer({ name: "alexandria", version: "0.1.0" });
25
+ var text = (t) => ({ content: [{ type: "text", text: t }] });
26
+ server.tool(
27
+ "vault_search",
28
+ "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.",
29
+ { query: z.string().describe("Qu\xE9 buscar, en lenguaje natural"), k: z.number().int().min(1).max(15).optional() },
30
+ async ({ query, k }) => {
31
+ const results = await hybridSearch(vault, query, k ?? 5, { expand: true });
32
+ if (results.length === 0) return text("Sin resultados en la b\xF3veda.");
33
+ const out = results.map(
34
+ (r, i) => `${i + 1}. \xAB${r.note.title}\xBB (${r.note.rel}, tipo: ${r.note.type})
35
+ ${r.excerpts.map((e) => " " + e.replace(/\n/g, "\n ").slice(0, 900)).join("\n")}`
36
+ ).join("\n\n");
37
+ return text(out);
38
+ }
39
+ );
40
+ server.tool(
41
+ "vault_save",
42
+ '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).',
43
+ {
44
+ title: z.string(),
45
+ content: z.string().describe("Markdown; puede incluir [[wikilinks]] a otras notas"),
46
+ tags: z.array(z.string()).optional()
47
+ },
48
+ async ({ title, content, tags }) => {
49
+ ensureVaultStructure(vault);
50
+ let file;
51
+ if (title.startsWith("Mapa - ")) {
52
+ file = upsertNote(vault.managed, {
53
+ fixedName: `mapa-${slugify(title.replace("Mapa - ", ""))}`,
54
+ title,
55
+ type: "map",
56
+ tags: tags ?? [],
57
+ dir: "notes",
58
+ content
59
+ });
60
+ } else {
61
+ file = createNote(vault.managed, { title, content, tags: tags ?? [], type: "note" });
62
+ }
63
+ await VaultIndex.load(vault).refresh().catch(() => {
64
+ });
65
+ return text(`Guardado en ${path.relative(vault.root, file)}`);
66
+ }
67
+ );
68
+ server.tool(
69
+ "vault_related",
70
+ "Vecinos de una nota en el grafo de conocimiento (wikilinks + conexiones sem\xE1nticas) \u2014 trae conocimiento conectado sin releer archivos.",
71
+ { title: z.string().describe("T\xEDtulo o ruta relativa de la nota") },
72
+ async ({ title }) => {
73
+ const idx = VaultIndex.load(vault);
74
+ const lower = title.toLowerCase();
75
+ const note = Object.values(idx.meta.notes).find(
76
+ (n) => n.title.toLowerCase() === lower || n.rel.toLowerCase() === lower
77
+ );
78
+ if (!note) return text(`No encontr\xE9 la nota \xAB${title}\xBB.`);
79
+ const nbs = idx.neighbors(note.rel);
80
+ if (nbs.length === 0) return text(`\xAB${note.title}\xBB no tiene conexiones a\xFAn.`);
81
+ return text(
82
+ nbs.map((n) => `- \xAB${n.note.title}\xBB (${n.note.rel}) [${n.type}${n.w ? ` ${n.w}` : ""}]`).join("\n")
83
+ );
84
+ }
85
+ );
86
+ server.tool(
87
+ "vault_link",
88
+ "Crea una conexi\xF3n expl\xEDcita [[wikilink]] entre dos notas de la b\xF3veda.",
89
+ { from: z.string(), to: z.string() },
90
+ async ({ from, to }) => {
91
+ const idx = VaultIndex.load(vault);
92
+ const find = (t) => Object.values(idx.meta.notes).find(
93
+ (n) => n.title.toLowerCase() === t.toLowerCase() || n.rel.toLowerCase() === t.toLowerCase()
94
+ );
95
+ const a = find(from);
96
+ const b = find(to);
97
+ if (!a || !b) return text(`No encontr\xE9 ${!a ? `\xAB${from}\xBB` : `\xAB${to}\xBB`}.`);
98
+ const file = path.join(vault.root, a.rel);
99
+ fs.appendFileSync(file, `
100
+ [[${b.title}]]
101
+ `);
102
+ await idx.refresh().catch(() => {
103
+ });
104
+ return text(`Conectado: \xAB${a.title}\xBB \u2192 [[${b.title}]]`);
105
+ }
106
+ );
107
+ await server.connect(new StdioServerTransport());
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@ureck/alexandria",
3
+ "version": "0.2.0",
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
+ "type": "module",
6
+ "license": "MIT",
7
+ "bin": {
8
+ "ale": "dist/cli.js",
9
+ "alexandria": "dist/cli.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "scripts": {
20
+ "build": "tsup",
21
+ "dev": "tsup --watch",
22
+ "test": "vitest run",
23
+ "prepublishOnly": "npm run build"
24
+ },
25
+ "keywords": [
26
+ "claude-code",
27
+ "knowledge-base",
28
+ "obsidian",
29
+ "semantic-search",
30
+ "mcp",
31
+ "embeddings",
32
+ "local-first"
33
+ ],
34
+ "dependencies": {
35
+ "@huggingface/transformers": "^3.3.3",
36
+ "@modelcontextprotocol/sdk": "^1.12.1",
37
+ "commander": "^13.1.0",
38
+ "gray-matter": "^4.0.3",
39
+ "minisearch": "^7.1.2",
40
+ "picocolors": "^1.1.1",
41
+ "zod": "^3.24.2"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^22.13.0",
45
+ "tsup": "^8.4.0",
46
+ "typescript": "^5.7.3",
47
+ "vitest": "^3.0.5"
48
+ },
49
+ "author": "Ureck <urielgomezbecerril@gmail.com>",
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "https://github.com/ureck/alexandria"
56
+ }
57
+ }