@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ureck (Uriel Gómez Becerril)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # 🏛️ Alexandria
2
+
3
+ **Bóveda de conocimiento local para tus agentes de IA.** Captura automáticamente tus prompts y sesiones, 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 costo.
4
+
5
+ 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**.
6
+
7
+ - **Ahorra tokens**: cada prompt dispara una búsqueda semántica local (<100ms) y le inyecta al agente solo los fragmentos relevantes — en vez de releer archivos o re-derivar contexto.
8
+ - **Cero re-análisis entre sesiones**: al abrir una sesión, el agente recibe el mapa del proyecto y el conocimiento acumulado. No vuelve a explorar el código que ya conoce.
9
+ - **Es un vault de Obsidian**: markdown puro con `[[wikilinks]]`. Ábrelo en Obsidian cuando quieras; el grafo también se ve con `ale graph`.
10
+ - **Multiplataforma**: Windows, macOS, Linux. Pure JS — sin dependencias nativas que fallen al instalar.
11
+
12
+ ## Instalación
13
+
14
+ ```bash
15
+ # npm (Node ≥ 20)
16
+ npm install -g @ureck/alexandria
17
+ # bun
18
+ bun add -g @ureck/alexandria
19
+ # deno
20
+ deno install -grA -n ale npm:@ureck/alexandria/ale
21
+
22
+ ale init # global: registra el MCP en Claude Code + agentes detectados
23
+ # o dentro de un proyecto:
24
+ ale init --project # solo ese proyecto (.vault.json, .claude/settings.json, .mcp.json…)
25
+ # apuntar a tu vault Obsidian existente:
26
+ ale init --path ~/Documents/MiVaultObsidian
27
+ # elegir agentes explícitamente:
28
+ ale init --agents all # todos los soportados
29
+ ale init --agents claude,cursor,opencode # solo esos
30
+ ```
31
+
32
+ `ale init` instala **todo** una sola vez: descarga el modelo de embeddings (~120MB, multilingüe, offline), registra hooks (Claude Code) y el servidor MCP en tus agentes, y construye el índice. Después no hay nada que reconectar — cada sesión nueva funciona sola.
33
+
34
+ ## Agentes soportados
35
+
36
+ ```bash
37
+ ale agents # lista con detección automática
38
+ ale agents all # registra el MCP en todos
39
+ ale agents cursor,gemini # solo en esos
40
+ ```
41
+
42
+ | Agente | Config que escribe | Por proyecto |
43
+ |---|---|---|
44
+ | Claude Code | `.mcp.json` / `claude mcp add` + hooks | ✓ |
45
+ | Cursor | `~/.cursor/mcp.json` / `.cursor/mcp.json` | ✓ |
46
+ | OpenCode | `opencode.json` | ✓ |
47
+ | Windsurf | `~/.codeium/windsurf/mcp_config.json` | — |
48
+ | Cline | `cline_mcp_settings.json` (VS Code) | — |
49
+ | Codex CLI | `~/.codex/config.toml` | — |
50
+ | Gemini CLI | `~/.gemini/settings.json` / `.gemini/settings.json` | ✓ |
51
+ | VS Code (Copilot) | `mcp.json` (perfil) / `.vscode/mcp.json` | ✓ |
52
+ | OpenClaw | `~/.openclaw/openclaw.json` | — |
53
+ | Hermes Agent (Nous) | `hermes mcp add` / `~/.hermes/config.yaml` | — |
54
+
55
+ **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 (`vault_search`, `vault_save`…), que el agente usa solo.
56
+
57
+ ## Cómo funciona
58
+
59
+ ```
60
+ Sesión del agente de IA
61
+ │
62
+ ├─ SessionStart ──► inyecta digest: mapa del proyecto + conocimiento previo (hooks, Claude Code)
63
+ ├─ Cada prompt ───► búsqueda híbrida local → inyecta solo lo relevante (hooks, Claude Code)
64
+ │ └─ prompt casi idéntico ya resuelto → inyecta la solución (caché)
65
+ ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (todos los agentes)
66
+ └─ Stop/PreCompact► guarda el resultado de la sesión en la bóveda (hooks, Claude Code)
67
+ │
68
+ <Vault Obsidian>/Alexandria/*.md ← markdown, [[wikilinks]]
69
+ <Vault>/.vault/ ← índice (regenerable)
70
+ ```
71
+
72
+ - **Búsqueda híbrida**: embeddings locales (transformers.js, modelo multilingüe) + BM25, combinados con RRF y boost por recencia/uso. Sin internet funciona en modo keyword.
73
+ - **Índice incremental**: solo re-procesa notas cuyo mtime cambió. El grafo nunca se recalcula completo.
74
+ - **Deduplicación**: prompts casi idénticos no crean notas nuevas — suman `hits` (y suben en el ranking).
75
+
76
+ ## Comandos
77
+
78
+ | Comando | Qué hace |
79
+ |---|---|
80
+ | `ale init [--project] [--path <dir>] [--agents <ids>]` | Instala todo (una vez) |
81
+ | `ale agents [ids] [--project]` | Lista agentes / registra el MCP en ellos |
82
+ | `ale search <query> [--expand]` | Búsqueda híbrida; `--expand` trae vecinos del grafo |
83
+ | `ale add <título> [-c texto] [-t tags]` | Guardar nota manual (o por stdin) |
84
+ | `ale graph [--out file.html]` | Grafo interactivo local (nodos = notas, líneas = conexiones) |
85
+ | `ale skills [-y] [--project]` | Recomienda e instala skills de Claude según tus patrones |
86
+ | `ale stats` | Notas, conexiones y tokens ahorrados estimados |
87
+ | `ale reindex [--force]` | Reindexar (incremental por default) |
88
+ | `ale doctor [--project]` | Verifica y repara: modelo, hooks, MCP, índice |
89
+ | `ale uninstall [--project]` | Quita hooks (las notas quedan intactas) |
90
+
91
+ `alexandria` funciona como alias de `ale`.
92
+
93
+ ## Herramientas MCP (las usa el agente solo)
94
+
95
+ - `vault_search(query)` — buscar conocimiento antes de explorar código.
96
+ - `vault_save(title, content, tags)` — guardar decisiones/arquitectura. `title: "Mapa - <proyecto>"` actualiza el mapa que se inyecta al inicio de cada sesión.
97
+ - `vault_related(title)` — vecinos en el grafo sin releer archivos.
98
+ - `vault_link(from, to)` — conectar dos notas con `[[wikilink]]`.
99
+
100
+ ## V2 (roadmap)
101
+
102
+ - Bot de Telegram (grammY, polling local — sin servidor público): `/search`, `/save` desde el teléfono.
103
+ - `ale consolidate`: detección de duplicados y clusters → notas-resumen.
104
+
105
+ ## Desarrollo
106
+
107
+ ```bash
108
+ npm install && npm run build && npm test
109
+ npm link # instala `ale` local
110
+ ```
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/vault.ts
4
+ import fs from "fs";
5
+ import os from "os";
6
+ import path from "path";
7
+ var MANAGED_DIR = "Alexandria";
8
+ function configDir() {
9
+ if (process.platform === "win32" && process.env.APPDATA) {
10
+ return path.join(process.env.APPDATA, "alexandria");
11
+ }
12
+ return path.join(os.homedir(), ".config", "alexandria");
13
+ }
14
+ function globalConfigPath() {
15
+ return path.join(configDir(), "config.json");
16
+ }
17
+ function defaultVaultPath() {
18
+ return path.join(os.homedir(), "KnowledgeVault");
19
+ }
20
+ function readJson(file) {
21
+ try {
22
+ return JSON.parse(fs.readFileSync(file, "utf8"));
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function findProjectConfig(from) {
28
+ let dir = path.resolve(from);
29
+ for (; ; ) {
30
+ const candidate = path.join(dir, ".vault.json");
31
+ if (fs.existsSync(candidate)) return candidate;
32
+ const parent = path.dirname(dir);
33
+ if (parent === dir) return null;
34
+ dir = parent;
35
+ }
36
+ }
37
+ function build(root, source, projectConfig) {
38
+ return {
39
+ root,
40
+ managed: path.join(root, MANAGED_DIR),
41
+ cache: path.join(root, ".vault"),
42
+ source,
43
+ projectConfig
44
+ };
45
+ }
46
+ function resolveVault(opts = {}) {
47
+ if (opts.flag) return build(path.resolve(opts.flag), "flag");
48
+ const cwd = opts.cwd ?? process.cwd();
49
+ const projectFile = findProjectConfig(cwd);
50
+ if (projectFile) {
51
+ const cfg = readJson(projectFile);
52
+ if (cfg?.vaultPath) {
53
+ const base = path.dirname(projectFile);
54
+ return build(path.resolve(base, cfg.vaultPath), "project", projectFile);
55
+ }
56
+ }
57
+ const globalCfg = readJson(globalConfigPath());
58
+ if (globalCfg?.vaultPath) return build(globalCfg.vaultPath, "global");
59
+ return build(defaultVaultPath(), "default");
60
+ }
61
+ function vaultExists(v) {
62
+ return fs.existsSync(v.managed) || fs.existsSync(v.cache);
63
+ }
64
+ function ensureVaultStructure(v) {
65
+ for (const dir of [
66
+ v.root,
67
+ v.managed,
68
+ path.join(v.managed, "notes"),
69
+ path.join(v.managed, "prompts"),
70
+ path.join(v.managed, "sessions"),
71
+ v.cache
72
+ ]) {
73
+ fs.mkdirSync(dir, { recursive: true });
74
+ }
75
+ }
76
+ function writeGlobalConfig(vaultPath) {
77
+ fs.mkdirSync(configDir(), { recursive: true });
78
+ fs.writeFileSync(globalConfigPath(), JSON.stringify({ vaultPath }, null, 2) + "\n");
79
+ }
80
+ function writeProjectConfig(projectDir, vaultPath) {
81
+ const file = path.join(projectDir, ".vault.json");
82
+ const rel = path.relative(projectDir, vaultPath) || ".";
83
+ const stored = rel.startsWith("..") ? vaultPath : rel;
84
+ fs.writeFileSync(file, JSON.stringify({ vaultPath: stored }, null, 2) + "\n");
85
+ return file;
86
+ }
87
+
88
+ // src/core/notes.ts
89
+ import fs2 from "fs";
90
+ import path2 from "path";
91
+ import matter from "gray-matter";
92
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
93
+ function extractWikilinks(content) {
94
+ const out = /* @__PURE__ */ new Set();
95
+ const re = /\[\[([^\]|#\n]+)(?:[|#][^\]]*)?\]\]/g;
96
+ let m;
97
+ while ((m = re.exec(content)) !== null) {
98
+ const target = m[1].trim();
99
+ if (target) out.add(target);
100
+ }
101
+ return [...out];
102
+ }
103
+ function slugify(text) {
104
+ return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
105
+ }
106
+ function listMarkdownFiles(root) {
107
+ const out = [];
108
+ const walk = (dir) => {
109
+ let entries;
110
+ try {
111
+ entries = fs2.readdirSync(dir, { withFileTypes: true });
112
+ } catch {
113
+ return;
114
+ }
115
+ for (const e of entries) {
116
+ if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
117
+ const full = path2.join(dir, e.name);
118
+ if (e.isDirectory()) walk(full);
119
+ else if (e.isFile() && e.name.endsWith(".md")) out.push(full);
120
+ }
121
+ };
122
+ walk(root);
123
+ return out;
124
+ }
125
+ function parseNote(root, absPath) {
126
+ const raw = fs2.readFileSync(absPath, "utf8");
127
+ const { data, content } = matter(raw);
128
+ const rel = path2.relative(root, absPath).split(path2.sep).join("/");
129
+ const title = typeof data.title === "string" && data.title || path2.basename(absPath, ".md");
130
+ const type = ["note", "prompt", "session", "map"].includes(data.type) ? data.type : "note";
131
+ const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
132
+ return {
133
+ rel,
134
+ title,
135
+ type,
136
+ tags,
137
+ created: data.created ? String(data.created) : void 0,
138
+ hits: typeof data.hits === "number" ? data.hits : 1,
139
+ content,
140
+ links: extractWikilinks(content)
141
+ };
142
+ }
143
+ function frontmatter(n) {
144
+ const lines = [
145
+ "---",
146
+ `title: ${JSON.stringify(n.title)}`,
147
+ `type: ${n.type}`,
148
+ `tags: [${n.tags.map((t) => JSON.stringify(t)).join(", ")}]`,
149
+ `created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
150
+ `hits: ${n.hits ?? 1}`,
151
+ "---",
152
+ ""
153
+ ];
154
+ return lines.join("\n");
155
+ }
156
+ function createNote(managed, n) {
157
+ const dir = path2.join(managed, n.dir ?? "notes");
158
+ fs2.mkdirSync(dir, { recursive: true });
159
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
160
+ const base = `${date}-${slugify(n.title)}`;
161
+ let file = path2.join(dir, `${base}.md`);
162
+ let i = 2;
163
+ while (fs2.existsSync(file)) file = path2.join(dir, `${base}-${i++}.md`);
164
+ fs2.writeFileSync(
165
+ file,
166
+ frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [] }) + n.content.trim() + "\n"
167
+ );
168
+ return file;
169
+ }
170
+ function touchNote(absPath) {
171
+ const raw = fs2.readFileSync(absPath, "utf8");
172
+ const { data, content } = matter(raw);
173
+ data.hits = (typeof data.hits === "number" ? data.hits : 1) + 1;
174
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
175
+ fs2.writeFileSync(absPath, matter.stringify(content, data));
176
+ }
177
+ function upsertNote(managed, n) {
178
+ const dir = path2.join(managed, n.dir ?? "notes");
179
+ fs2.mkdirSync(dir, { recursive: true });
180
+ const file = path2.join(dir, `${n.fixedName}.md`);
181
+ if (fs2.existsSync(file)) {
182
+ const raw = fs2.readFileSync(file, "utf8");
183
+ const { data } = matter(raw);
184
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
185
+ fs2.writeFileSync(file, matter.stringify(n.content.trim() + "\n", data));
186
+ } else {
187
+ fs2.writeFileSync(
188
+ file,
189
+ frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [] }) + n.content.trim() + "\n"
190
+ );
191
+ }
192
+ return file;
193
+ }
194
+ function appendToNote(managed, n) {
195
+ const dir = path2.join(managed, n.dir ?? "sessions");
196
+ fs2.mkdirSync(dir, { recursive: true });
197
+ const file = path2.join(dir, `${n.fixedName}.md`);
198
+ if (fs2.existsSync(file)) {
199
+ fs2.appendFileSync(file, "\n" + n.content.trim() + "\n");
200
+ } else {
201
+ fs2.writeFileSync(
202
+ file,
203
+ frontmatter({ title: n.title, type: n.type ?? "session", tags: n.tags ?? [] }) + n.content.trim() + "\n"
204
+ );
205
+ }
206
+ return file;
207
+ }
208
+
209
+ export {
210
+ globalConfigPath,
211
+ defaultVaultPath,
212
+ resolveVault,
213
+ vaultExists,
214
+ ensureVaultStructure,
215
+ writeGlobalConfig,
216
+ writeProjectConfig,
217
+ slugify,
218
+ listMarkdownFiles,
219
+ parseNote,
220
+ createNote,
221
+ touchNote,
222
+ upsertNote,
223
+ appendToNote
224
+ };
@@ -0,0 +1,44 @@
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
+ };
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/embedder.ts
4
+ import fs from "fs";
5
+ import os from "os";
6
+ import path from "path";
7
+ var MODEL_ID = "Xenova/multilingual-e5-small";
8
+ var DIM = 384;
9
+ function modelCacheDir() {
10
+ if (process.platform === "win32" && process.env.LOCALAPPDATA) {
11
+ return path.join(process.env.LOCALAPPDATA, "alexandria", "models");
12
+ }
13
+ return path.join(os.homedir(), ".cache", "alexandria", "models");
14
+ }
15
+ function modelPresent() {
16
+ const dir = path.join(modelCacheDir(), ...MODEL_ID.split("/"));
17
+ try {
18
+ return fs.readdirSync(dir).some((f) => f === "onnx" || f.endsWith(".json"));
19
+ } catch {
20
+ return false;
21
+ }
22
+ }
23
+ var pipePromise = null;
24
+ async function getEmbedder(onProgress) {
25
+ if (!pipePromise) {
26
+ pipePromise = (async () => {
27
+ const { pipeline, env } = await import("@huggingface/transformers");
28
+ env.cacheDir = modelCacheDir();
29
+ const pipe = await pipeline("feature-extraction", MODEL_ID, {
30
+ dtype: "q8",
31
+ progress_callback: onProgress ? (p) => {
32
+ if (p.status === "progress" && typeof p.progress === "number") {
33
+ onProgress(Math.round(p.progress), p.file ?? "");
34
+ }
35
+ } : void 0
36
+ });
37
+ return pipe;
38
+ })();
39
+ pipePromise.catch(() => {
40
+ pipePromise = null;
41
+ });
42
+ }
43
+ return pipePromise;
44
+ }
45
+ async function disposeEmbedder() {
46
+ if (!pipePromise) return;
47
+ try {
48
+ const pipe = await pipePromise;
49
+ await pipe.dispose?.();
50
+ } catch {
51
+ }
52
+ pipePromise = null;
53
+ }
54
+ async function embed(texts, kind = "passage", onProgress) {
55
+ if (texts.length === 0) return [];
56
+ const pipe = await getEmbedder(onProgress);
57
+ const prefixed = texts.map((t) => `${kind}: ${t}`);
58
+ const rows = [];
59
+ const BATCH = 16;
60
+ for (let i = 0; i < prefixed.length; i += BATCH) {
61
+ const batch = prefixed.slice(i, i + BATCH);
62
+ const out = await pipe(batch, { pooling: "mean", normalize: true });
63
+ const dim = out.dims[out.dims.length - 1];
64
+ for (let j = 0; j < batch.length; j++) {
65
+ rows.push(out.data.slice(j * dim, (j + 1) * dim));
66
+ }
67
+ }
68
+ return rows;
69
+ }
70
+ function dot(a, b) {
71
+ let s = 0;
72
+ for (let i = 0; i < a.length; i++) s += a[i] * b[i];
73
+ return s;
74
+ }
75
+ function chunkMarkdown(content, maxChars = 1200, overlap = 200) {
76
+ const out = [];
77
+ let heading;
78
+ let buf = "";
79
+ const flush = () => {
80
+ const text = buf.trim();
81
+ if (text.length > 0) out.push({ heading, text });
82
+ buf = buf.slice(Math.max(0, buf.length - overlap));
83
+ };
84
+ for (const para of content.split(/\n{2,}/)) {
85
+ const trimmed = para.trim();
86
+ if (!trimmed) continue;
87
+ const h = trimmed.match(/^#{1,6}\s+(.+)$/m);
88
+ if (h) heading = h[1].trim();
89
+ if (buf.length + trimmed.length + 2 > maxChars && buf.trim()) flush();
90
+ if (trimmed.length > maxChars) {
91
+ for (let i = 0; i < trimmed.length; i += maxChars - overlap) {
92
+ out.push({ heading, text: trimmed.slice(i, i + maxChars) });
93
+ }
94
+ buf = "";
95
+ continue;
96
+ }
97
+ buf += (buf ? "\n\n" : "") + trimmed;
98
+ }
99
+ if (buf.trim()) out.push({ heading, text: buf.trim() });
100
+ return out;
101
+ }
102
+
103
+ export {
104
+ MODEL_ID,
105
+ DIM,
106
+ modelCacheDir,
107
+ modelPresent,
108
+ getEmbedder,
109
+ disposeEmbedder,
110
+ embed,
111
+ dot,
112
+ chunkMarkdown
113
+ };
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ VaultIndex
4
+ } from "./chunk-UWAIMIG2.js";
5
+ import {
6
+ dot,
7
+ embed,
8
+ modelPresent
9
+ } from "./chunk-EDYBSJSS.js";
10
+
11
+ // src/core/search.ts
12
+ import MiniSearch from "minisearch";
13
+ var RRF_K = 60;
14
+ var VEC_WEIGHT = 1.3;
15
+ var STOPWORDS = new Set(
16
+ "de la que el en y a los del se las por un para con no una su al lo como mas m\xE1s pero sus le ya o este si s\xED porque esta entre cuando muy sin sobre tambi\xE9n me hasta hay donde quien desde todo nos durante todos uno les ni contra otros ese eso ante ellos e esto m\xED antes algunos qu\xE9 unos yo otro otras otra \xE9l tanto esa estos mucho quienes nada muchos cual poco ella estar estas algunas algo nosotros the a an and or but if of at by for with about to from in on is are was were be been being it its this that these those i you he she we they what which who whom how all any both each".split(" ")
17
+ );
18
+ function buildMini(idx) {
19
+ const mini = new MiniSearch({
20
+ fields: ["text", "title", "tags"],
21
+ storeFields: [],
22
+ idField: "id",
23
+ processTerm: (term) => {
24
+ const t = term.toLowerCase();
25
+ return t.length < 2 || STOPWORDS.has(t) ? null : t;
26
+ }
27
+ });
28
+ mini.addAll(
29
+ idx.meta.chunks.map((c, i) => ({
30
+ id: i,
31
+ text: c.text,
32
+ title: idx.meta.notes[c.note]?.title ?? "",
33
+ tags: (idx.meta.notes[c.note]?.tags ?? []).join(" ")
34
+ }))
35
+ );
36
+ return mini;
37
+ }
38
+ function recencyBoost(note) {
39
+ if (!note?.created) return 1;
40
+ const age = (Date.now() - Date.parse(note.created)) / 864e5;
41
+ if (Number.isNaN(age)) return 1;
42
+ const hits = Math.min(note.hits ?? 1, 10);
43
+ return 1 + 0.15 * Math.exp(-Math.max(age, 0) / 45) + 0.02 * hits;
44
+ }
45
+ async function hybridSearch(vault, query, k = 6, opts = {}) {
46
+ const idx = VaultIndex.load(vault);
47
+ if (opts.refresh !== false) {
48
+ await idx.refresh().catch(() => {
49
+ });
50
+ }
51
+ if (idx.meta.chunks.length === 0) return [];
52
+ const rrf = /* @__PURE__ */ new Map();
53
+ const cosineByChunk = /* @__PURE__ */ new Map();
54
+ if (idx.emb && modelPresent()) {
55
+ try {
56
+ const [q] = await embed([query], "query");
57
+ const scored = [];
58
+ for (let i = 0; i < idx.meta.chunks.length; i++) {
59
+ scored.push({ i, s: dot(q, idx.row(i)) });
60
+ }
61
+ scored.sort((a, b) => b.s - a.s);
62
+ scored.slice(0, 50).forEach(({ i, s }, rank) => {
63
+ cosineByChunk.set(i, s);
64
+ rrf.set(i, (rrf.get(i) ?? 0) + VEC_WEIGHT / (RRF_K + rank + 1));
65
+ });
66
+ } catch {
67
+ }
68
+ }
69
+ const mini = buildMini(idx);
70
+ const kwHits = mini.search(query, { fuzzy: 0.2, prefix: true });
71
+ kwHits.slice(0, 50).forEach((h, rank) => {
72
+ rrf.set(h.id, (rrf.get(h.id) ?? 0) + 1 / (RRF_K + rank + 1));
73
+ });
74
+ const byNote = /* @__PURE__ */ new Map();
75
+ const ranked = [...rrf.entries()].sort((a, b) => b[1] - a[1]);
76
+ for (const [chunkIdx, score] of ranked) {
77
+ const chunk = idx.meta.chunks[chunkIdx];
78
+ const note = idx.meta.notes[chunk.note];
79
+ const boosted = score * recencyBoost(note);
80
+ const entry = byNote.get(chunk.note) ?? { score: 0, cosine: 0, excerpts: [] };
81
+ entry.score += boosted;
82
+ entry.cosine = Math.max(entry.cosine, cosineByChunk.get(chunkIdx) ?? 0);
83
+ if (entry.excerpts.length < 2) {
84
+ entry.excerpts.push((chunk.heading ? `[${chunk.heading}] ` : "") + chunk.text);
85
+ }
86
+ byNote.set(chunk.note, entry);
87
+ }
88
+ let results = [...byNote.entries()].filter(([rel]) => idx.meta.notes[rel]).map(([rel, e]) => ({ note: idx.meta.notes[rel], score: e.score, cosine: e.cosine, excerpts: e.excerpts })).sort((a, b) => b.score - a.score).slice(0, k);
89
+ if (opts.expand && results.length > 0) {
90
+ const have = new Set(results.map((r) => r.note.rel));
91
+ for (const r of results.slice(0, 2)) {
92
+ for (const nb of idx.neighbors(r.note.rel).slice(0, 2)) {
93
+ if (have.has(nb.note.rel)) continue;
94
+ have.add(nb.note.rel);
95
+ const firstChunk = idx.meta.chunks.find((c) => c.note === nb.note.rel);
96
+ results.push({
97
+ note: nb.note,
98
+ score: r.score * 0.4,
99
+ cosine: 0,
100
+ excerpts: firstChunk ? [firstChunk.text] : []
101
+ });
102
+ }
103
+ }
104
+ results = results.sort((a, b) => b.score - a.score).slice(0, k + 3);
105
+ }
106
+ return results;
107
+ }
108
+
109
+ export {
110
+ hybridSearch
111
+ };
@@ -0,0 +1,45 @@
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
+ function readStats(vault) {
18
+ const file = path.join(vault.cache, "stats.jsonl");
19
+ const summary = {
20
+ injections: 0,
21
+ solutionCacheHits: 0,
22
+ injectedTokens: 0,
23
+ estimatedSavedTokens: 0
24
+ };
25
+ try {
26
+ for (const raw of fs.readFileSync(file, "utf8").split("\n")) {
27
+ if (!raw.trim()) continue;
28
+ try {
29
+ const line = JSON.parse(raw);
30
+ summary.injections++;
31
+ if (line.kind === "solution-cache") summary.solutionCacheHits++;
32
+ summary.injectedTokens += charsToTokens(line.injectedChars);
33
+ } catch {
34
+ }
35
+ }
36
+ } catch {
37
+ }
38
+ summary.estimatedSavedTokens = summary.injectedTokens * 9;
39
+ return summary;
40
+ }
41
+
42
+ export {
43
+ logInjection,
44
+ readStats
45
+ };