@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 +21 -0
- package/README.md +110 -0
- package/dist/chunk-CZM5NQZJ.js +224 -0
- package/dist/chunk-DEDAOKAV.js +44 -0
- package/dist/chunk-EDYBSJSS.js +113 -0
- package/dist/chunk-O7FDC2PB.js +111 -0
- package/dist/chunk-OPUPZRP6.js +45 -0
- package/dist/chunk-UWAIMIG2.js +231 -0
- package/dist/cli.js +975 -0
- package/dist/embedder-7Z4XNL6H.js +23 -0
- package/dist/hooks/on-prompt.js +91 -0
- package/dist/hooks/on-session-start.js +64 -0
- package/dist/hooks/on-stop.js +63 -0
- package/dist/mcp/server.js +107 -0
- package/package.json +57 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,975 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
readStats
|
|
4
|
+
} from "./chunk-OPUPZRP6.js";
|
|
5
|
+
import {
|
|
6
|
+
hybridSearch
|
|
7
|
+
} from "./chunk-O7FDC2PB.js";
|
|
8
|
+
import {
|
|
9
|
+
VaultIndex
|
|
10
|
+
} from "./chunk-UWAIMIG2.js";
|
|
11
|
+
import {
|
|
12
|
+
createNote,
|
|
13
|
+
defaultVaultPath,
|
|
14
|
+
ensureVaultStructure,
|
|
15
|
+
globalConfigPath,
|
|
16
|
+
resolveVault,
|
|
17
|
+
vaultExists,
|
|
18
|
+
writeGlobalConfig,
|
|
19
|
+
writeProjectConfig
|
|
20
|
+
} from "./chunk-CZM5NQZJ.js";
|
|
21
|
+
import {
|
|
22
|
+
MODEL_ID,
|
|
23
|
+
getEmbedder,
|
|
24
|
+
modelPresent
|
|
25
|
+
} from "./chunk-EDYBSJSS.js";
|
|
26
|
+
|
|
27
|
+
// src/cli.ts
|
|
28
|
+
import fs5 from "fs";
|
|
29
|
+
import path5 from "path";
|
|
30
|
+
import readline from "readline/promises";
|
|
31
|
+
import { Command } from "commander";
|
|
32
|
+
import pc from "picocolors";
|
|
33
|
+
|
|
34
|
+
// src/core/register.ts
|
|
35
|
+
import fs from "fs";
|
|
36
|
+
import os from "os";
|
|
37
|
+
import path from "path";
|
|
38
|
+
import { fileURLToPath } from "url";
|
|
39
|
+
import { execFileSync } from "child_process";
|
|
40
|
+
function distDir() {
|
|
41
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
42
|
+
return here.endsWith(`${path.sep}hooks`) || here.endsWith(`${path.sep}mcp`) ? path.dirname(here) : here;
|
|
43
|
+
}
|
|
44
|
+
var MARKER = "alexandria";
|
|
45
|
+
function hookCommand(script, timeout) {
|
|
46
|
+
return { type: "command", command: `node "${script}"`, timeout };
|
|
47
|
+
}
|
|
48
|
+
function isOurs(cmd) {
|
|
49
|
+
return cmd.includes(MARKER) || cmd.includes(distDir());
|
|
50
|
+
}
|
|
51
|
+
function registerHooks(settingsPath) {
|
|
52
|
+
const d = distDir();
|
|
53
|
+
const wanted = {
|
|
54
|
+
SessionStart: hookCommand(path.join(d, "hooks", "on-session-start.js"), 20),
|
|
55
|
+
UserPromptSubmit: hookCommand(path.join(d, "hooks", "on-prompt.js"), 30),
|
|
56
|
+
Stop: hookCommand(path.join(d, "hooks", "on-stop.js"), 30),
|
|
57
|
+
PreCompact: hookCommand(path.join(d, "hooks", "on-stop.js"), 30)
|
|
58
|
+
};
|
|
59
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
60
|
+
let settings = {};
|
|
61
|
+
try {
|
|
62
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
63
|
+
} catch {
|
|
64
|
+
if (fs.existsSync(settingsPath)) {
|
|
65
|
+
throw new Error(`No pude parsear ${settingsPath} \u2014 rev\xEDsalo manualmente antes de registrar hooks.`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
settings.hooks ??= {};
|
|
69
|
+
for (const [event, cmd] of Object.entries(wanted)) {
|
|
70
|
+
const matchers = (settings.hooks[event] ?? []).filter(
|
|
71
|
+
(m) => !m.hooks?.some((h) => isOurs(h.command))
|
|
72
|
+
);
|
|
73
|
+
matchers.push({ hooks: [cmd] });
|
|
74
|
+
settings.hooks[event] = matchers;
|
|
75
|
+
}
|
|
76
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
77
|
+
}
|
|
78
|
+
function unregisterHooks(settingsPath) {
|
|
79
|
+
try {
|
|
80
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
81
|
+
if (!settings.hooks) return;
|
|
82
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
83
|
+
settings.hooks[event] = settings.hooks[event].map((m) => ({ ...m, hooks: m.hooks.filter((h) => !isOurs(h.command)) })).filter((m) => m.hooks.length > 0);
|
|
84
|
+
if (settings.hooks[event].length === 0) delete settings.hooks[event];
|
|
85
|
+
}
|
|
86
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
87
|
+
} catch {
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function projectSettingsPath(projectDir) {
|
|
91
|
+
return path.join(projectDir, ".claude", "settings.json");
|
|
92
|
+
}
|
|
93
|
+
function globalSettingsPath() {
|
|
94
|
+
return path.join(os.homedir(), ".claude", "settings.json");
|
|
95
|
+
}
|
|
96
|
+
function hooksRegistered(settingsPath) {
|
|
97
|
+
try {
|
|
98
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
99
|
+
const hooks = settings.hooks ?? {};
|
|
100
|
+
return ["SessionStart", "UserPromptSubmit"].every(
|
|
101
|
+
(ev) => (hooks[ev] ?? []).some((m) => m.hooks?.some((h) => isOurs(h.command)))
|
|
102
|
+
);
|
|
103
|
+
} catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function registerMcpProject(projectDir) {
|
|
108
|
+
const file = path.join(projectDir, ".mcp.json");
|
|
109
|
+
let cfg = {};
|
|
110
|
+
try {
|
|
111
|
+
cfg = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
112
|
+
} catch {
|
|
113
|
+
if (fs.existsSync(file)) {
|
|
114
|
+
throw new Error(`No pude parsear ${file} \u2014 rev\xEDsalo manualmente.`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
cfg.mcpServers ??= {};
|
|
118
|
+
cfg.mcpServers["alexandria"] = {
|
|
119
|
+
command: "node",
|
|
120
|
+
args: [path.join(distDir(), "mcp", "server.js")]
|
|
121
|
+
};
|
|
122
|
+
fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
|
|
123
|
+
return file;
|
|
124
|
+
}
|
|
125
|
+
function registerMcpGlobal() {
|
|
126
|
+
const server = path.join(distDir(), "mcp", "server.js");
|
|
127
|
+
try {
|
|
128
|
+
execFileSync("claude", ["mcp", "add", "--scope", "user", "alexandria", "--", "node", server], {
|
|
129
|
+
stdio: "pipe",
|
|
130
|
+
timeout: 15e3
|
|
131
|
+
});
|
|
132
|
+
return true;
|
|
133
|
+
} catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function mcpRegisteredProject(projectDir) {
|
|
138
|
+
try {
|
|
139
|
+
const cfg = JSON.parse(fs.readFileSync(path.join(projectDir, ".mcp.json"), "utf8"));
|
|
140
|
+
return Boolean(cfg.mcpServers?.alexandria);
|
|
141
|
+
} catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/graph/viewer.ts
|
|
147
|
+
import fs2 from "fs";
|
|
148
|
+
import http from "http";
|
|
149
|
+
import path2 from "path";
|
|
150
|
+
import { spawn } from "child_process";
|
|
151
|
+
function buildGraphData(idx) {
|
|
152
|
+
const deg = /* @__PURE__ */ new Map();
|
|
153
|
+
for (const l of idx.meta.links) {
|
|
154
|
+
deg.set(l.from, (deg.get(l.from) ?? 0) + 1);
|
|
155
|
+
deg.set(l.to, (deg.get(l.to) ?? 0) + 1);
|
|
156
|
+
}
|
|
157
|
+
const nodes = Object.values(idx.meta.notes).map((n) => ({
|
|
158
|
+
id: n.rel,
|
|
159
|
+
title: n.title,
|
|
160
|
+
type: n.type,
|
|
161
|
+
deg: deg.get(n.rel) ?? 0,
|
|
162
|
+
hits: n.hits ?? 1
|
|
163
|
+
}));
|
|
164
|
+
const edges = idx.meta.links.map((l) => ({ s: l.from, t: l.to, type: l.type }));
|
|
165
|
+
return { nodes, edges };
|
|
166
|
+
}
|
|
167
|
+
function renderGraphHtml(data) {
|
|
168
|
+
return `<!doctype html>
|
|
169
|
+
<html lang="es">
|
|
170
|
+
<head>
|
|
171
|
+
<meta charset="utf-8">
|
|
172
|
+
<title>Alexandria \u2014 grafo de conocimiento</title>
|
|
173
|
+
<style>
|
|
174
|
+
html,body{margin:0;height:100%;background:#0f1117;color:#e6e6e6;font:14px/1.4 system-ui,sans-serif;overflow:hidden}
|
|
175
|
+
#hud{position:fixed;top:12px;left:12px;background:#1a1d27cc;padding:10px 14px;border-radius:10px;max-width:340px}
|
|
176
|
+
#hud h1{font-size:15px;margin:0 0 4px}
|
|
177
|
+
#hud .leg span{display:inline-block;width:10px;height:10px;border-radius:50%;margin:0 4px 0 10px}
|
|
178
|
+
#info{position:fixed;bottom:12px;left:12px;background:#1a1d27cc;padding:10px 14px;border-radius:10px;max-width:420px;display:none}
|
|
179
|
+
canvas{display:block}
|
|
180
|
+
</style>
|
|
181
|
+
</head>
|
|
182
|
+
<body>
|
|
183
|
+
<div id="hud">
|
|
184
|
+
<h1>\u{1F9E0} Alexandria \u2014 grafo</h1>
|
|
185
|
+
<div id="counts"></div>
|
|
186
|
+
<div class="leg">
|
|
187
|
+
<span style="background:#7aa2f7"></span>nota
|
|
188
|
+
<span style="background:#9ece6a"></span>sesi\xF3n
|
|
189
|
+
<span style="background:#e0af68"></span>prompt
|
|
190
|
+
<span style="background:#f7768e"></span>mapa
|
|
191
|
+
</div>
|
|
192
|
+
<div style="opacity:.7;margin-top:4px">arrastra nodos \xB7 rueda = zoom \xB7 click = detalle<br>l\xEDnea s\xF3lida = [[wikilink]] \xB7 punteada = sem\xE1ntica</div>
|
|
193
|
+
</div>
|
|
194
|
+
<div id="info"></div>
|
|
195
|
+
<canvas id="c"></canvas>
|
|
196
|
+
<script>
|
|
197
|
+
const DATA = ${JSON.stringify(data)};
|
|
198
|
+
const COLORS = { note:'#7aa2f7', session:'#9ece6a', prompt:'#e0af68', map:'#f7768e' };
|
|
199
|
+
const cv = document.getElementById('c'), ctx = cv.getContext('2d');
|
|
200
|
+
let W, H; const fit = () => { W = cv.width = innerWidth; H = cv.height = innerHeight; };
|
|
201
|
+
fit(); addEventListener('resize', fit);
|
|
202
|
+
document.getElementById('counts').textContent = DATA.nodes.length + ' notas \xB7 ' + DATA.edges.length + ' conexiones';
|
|
203
|
+
|
|
204
|
+
const nodes = DATA.nodes.map((n,i) => ({...n,
|
|
205
|
+
x: Math.cos(i/DATA.nodes.length*6.283)*Math.min(W,H)*.3 + W/2 + (Math.random()-.5)*40,
|
|
206
|
+
y: Math.sin(i/DATA.nodes.length*6.283)*Math.min(W,H)*.3 + H/2 + (Math.random()-.5)*40,
|
|
207
|
+
vx:0, vy:0, r: 4 + Math.min(n.deg,12)*1.2 + Math.min(n.hits,8)*.5
|
|
208
|
+
}));
|
|
209
|
+
const byId = new Map(nodes.map(n=>[n.id,n]));
|
|
210
|
+
const edges = DATA.edges.filter(e=>byId.has(e.s)&&byId.has(e.t)).map(e=>({a:byId.get(e.s), b:byId.get(e.t), type:e.type}));
|
|
211
|
+
|
|
212
|
+
let zoom = 1, panX = 0, panY = 0, dragNode = null, hot = true, heat = 300;
|
|
213
|
+
function step(){
|
|
214
|
+
if(!hot) return;
|
|
215
|
+
// repulsi\xF3n O(n\xB2) \u2014 bien hasta ~1500 nodos
|
|
216
|
+
for(let i=0;i<nodes.length;i++) for(let j=i+1;j<nodes.length;j++){
|
|
217
|
+
const a=nodes[i], b=nodes[j];
|
|
218
|
+
let dx=b.x-a.x, dy=b.y-a.y, d2=dx*dx+dy*dy+0.01, d=Math.sqrt(d2);
|
|
219
|
+
const f = Math.min(1800/d2, 8);
|
|
220
|
+
dx/=d; dy/=d;
|
|
221
|
+
a.vx-=dx*f; a.vy-=dy*f; b.vx+=dx*f; b.vy+=dy*f;
|
|
222
|
+
}
|
|
223
|
+
for(const e of edges){
|
|
224
|
+
let dx=e.b.x-e.a.x, dy=e.b.y-e.a.y, d=Math.sqrt(dx*dx+dy*dy)+0.01;
|
|
225
|
+
const want = e.type==='wikilink'?110:160;
|
|
226
|
+
const f=(d-want)*0.004*(e.type==='wikilink'?1.4:0.7);
|
|
227
|
+
dx/=d; dy/=d;
|
|
228
|
+
e.a.vx+=dx*f*d; e.a.vy+=dy*f*d; e.b.vx-=dx*f*d; e.b.vy-=dy*f*d;
|
|
229
|
+
}
|
|
230
|
+
for(const n of nodes){
|
|
231
|
+
n.vx += (W/2-n.x)*0.0004; n.vy += (H/2-n.y)*0.0004; // gravedad al centro
|
|
232
|
+
n.vx*=0.85; n.vy*=0.85;
|
|
233
|
+
if(n!==dragNode){ n.x+=n.vx; n.y+=n.vy; }
|
|
234
|
+
}
|
|
235
|
+
if(--heat<=0 && !dragNode) hot=false;
|
|
236
|
+
}
|
|
237
|
+
function draw(){
|
|
238
|
+
ctx.setTransform(1,0,0,1,0,0); ctx.clearRect(0,0,W,H);
|
|
239
|
+
ctx.setTransform(zoom,0,0,zoom,panX,panY);
|
|
240
|
+
for(const e of edges){
|
|
241
|
+
ctx.beginPath();
|
|
242
|
+
ctx.setLineDash(e.type==='semantic'?[4,4]:[]);
|
|
243
|
+
ctx.strokeStyle = e.type==='semantic' ? '#3b4261' : '#565f89';
|
|
244
|
+
ctx.lineWidth = 1;
|
|
245
|
+
ctx.moveTo(e.a.x,e.a.y); ctx.lineTo(e.b.x,e.b.y); ctx.stroke();
|
|
246
|
+
}
|
|
247
|
+
ctx.setLineDash([]);
|
|
248
|
+
for(const n of nodes){
|
|
249
|
+
ctx.beginPath(); ctx.fillStyle = COLORS[n.type]||'#7aa2f7';
|
|
250
|
+
ctx.arc(n.x,n.y,n.r,0,6.283); ctx.fill();
|
|
251
|
+
}
|
|
252
|
+
if(zoom>0.6){
|
|
253
|
+
ctx.fillStyle='#c0caf5'; ctx.font = (11/Math.max(zoom,1))+'px system-ui';
|
|
254
|
+
for(const n of nodes){ if(n.deg>0||zoom>1.1) ctx.fillText(n.title.slice(0,28), n.x+n.r+3, n.y+3); }
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
(function loop(){ step(); draw(); requestAnimationFrame(loop); })();
|
|
258
|
+
|
|
259
|
+
const toWorld = (x,y)=>[(x-panX)/zoom,(y-panY)/zoom];
|
|
260
|
+
const pick = (x,y)=>{ const [wx,wy]=toWorld(x,y); return nodes.find(n=>{const dx=n.x-wx,dy=n.y-wy;return dx*dx+dy*dy<=(n.r+4)*(n.r+4);}); };
|
|
261
|
+
let panning=false, px=0, py=0;
|
|
262
|
+
cv.addEventListener('mousedown',e=>{ const n=pick(e.clientX,e.clientY); if(n){dragNode=n;hot=true;heat=150;} else {panning=true;px=e.clientX;py=e.clientY;} });
|
|
263
|
+
addEventListener('mousemove',e=>{
|
|
264
|
+
if(dragNode){ const [wx,wy]=toWorld(e.clientX,e.clientY); dragNode.x=wx; dragNode.y=wy; }
|
|
265
|
+
else if(panning){ panX+=e.clientX-px; panY+=e.clientY-py; px=e.clientX; py=e.clientY; }
|
|
266
|
+
});
|
|
267
|
+
addEventListener('mouseup',e=>{
|
|
268
|
+
if(dragNode===null && !panning) return;
|
|
269
|
+
if(dragNode){ dragNode=null; }
|
|
270
|
+
panning=false;
|
|
271
|
+
});
|
|
272
|
+
cv.addEventListener('click',e=>{
|
|
273
|
+
const n=pick(e.clientX,e.clientY); const info=document.getElementById('info');
|
|
274
|
+
if(n){ info.style.display='block'; info.innerHTML='<b>'+n.title+'</b><br><span style="opacity:.7">'+n.id+'</span><br>tipo: '+n.type+' \xB7 conexiones: '+n.deg+' \xB7 usos: '+n.hits; }
|
|
275
|
+
else info.style.display='none';
|
|
276
|
+
});
|
|
277
|
+
cv.addEventListener('wheel',e=>{
|
|
278
|
+
e.preventDefault();
|
|
279
|
+
const f = e.deltaY<0?1.1:0.9;
|
|
280
|
+
panX = e.clientX-(e.clientX-panX)*f; panY = e.clientY-(e.clientY-panY)*f; zoom*=f;
|
|
281
|
+
},{passive:false});
|
|
282
|
+
</script>
|
|
283
|
+
</body>
|
|
284
|
+
</html>`;
|
|
285
|
+
}
|
|
286
|
+
function openBrowser(url) {
|
|
287
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
288
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
289
|
+
try {
|
|
290
|
+
spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
|
|
291
|
+
} catch {
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
async function serveGraph(vault, opts = {}) {
|
|
295
|
+
const idx = VaultIndex.load(vault);
|
|
296
|
+
await idx.refresh(false).catch(() => {
|
|
297
|
+
});
|
|
298
|
+
const html = renderGraphHtml(buildGraphData(idx));
|
|
299
|
+
if (opts.out) {
|
|
300
|
+
const file = path2.resolve(opts.out);
|
|
301
|
+
fs2.writeFileSync(file, html);
|
|
302
|
+
return file;
|
|
303
|
+
}
|
|
304
|
+
return new Promise((resolve) => {
|
|
305
|
+
const server = http.createServer((_req, res) => {
|
|
306
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
307
|
+
res.end(html);
|
|
308
|
+
});
|
|
309
|
+
server.listen(0, "127.0.0.1", () => {
|
|
310
|
+
const addr = server.address();
|
|
311
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
312
|
+
const url = `http://127.0.0.1:${port}`;
|
|
313
|
+
if (opts.open !== false) openBrowser(url);
|
|
314
|
+
resolve(url);
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/skills/recommend.ts
|
|
320
|
+
import fs3 from "fs";
|
|
321
|
+
import os2 from "os";
|
|
322
|
+
import path3 from "path";
|
|
323
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
324
|
+
var RULES = [
|
|
325
|
+
{ skill: "pdf-report-gen", keywords: ["pdf", "reporte pdf", "membrete"] },
|
|
326
|
+
{ skill: "excel-report-gen", keywords: ["excel", "xlsx", "spreadsheet", "hoja de calculo", "hoja de c\xE1lculo"] },
|
|
327
|
+
{ skill: "qr-checkin", keywords: ["qr", "codigo qr", "c\xF3digo qr", "check-in", "checkin"] },
|
|
328
|
+
{ skill: "auth-standard", keywords: ["auth", "login", "jwt", "sesion", "autenticacion", "autenticaci\xF3n"] },
|
|
329
|
+
{ skill: "prisma-workflow", keywords: ["prisma", "migracion", "migraci\xF3n", "orm"] },
|
|
330
|
+
{ skill: "flutter-offline-scaffold", keywords: ["flutter", "dart", "riverpod", "drift"] },
|
|
331
|
+
{ skill: "mapbox-geo", keywords: ["mapbox", "geolocalizacion", "geolocalizaci\xF3n", "geocode", "leaflet"] },
|
|
332
|
+
{ skill: "spanish-form-validation", keywords: ["curp", "rfc", "zod", "validacion", "validaci\xF3n", "formulario"] },
|
|
333
|
+
{ skill: "testing-ci-setup", keywords: ["vitest", "playwright", "test", "ci", "github actions"] },
|
|
334
|
+
{ skill: "tiptap-rich-text", keywords: ["tiptap", "editor de texto", "wysiwyg", "rich text"] },
|
|
335
|
+
{ skill: "signature-upload-optimizer", keywords: ["firma", "signature", "compress", "upload", "subir foto"] },
|
|
336
|
+
{ skill: "security-headers-baseline", keywords: ["csp", "security headers", "hsts", "seguridad web"] },
|
|
337
|
+
{ skill: "server-state-standard", keywords: ["react-query", "tanstack", "zustand", "estado"] },
|
|
338
|
+
{ skill: "nextjs-folder-structure", keywords: ["next.js", "nextjs", "app router"] }
|
|
339
|
+
];
|
|
340
|
+
var MIN_MENTIONS = 3;
|
|
341
|
+
function localSkillsRepo() {
|
|
342
|
+
return path3.join(os2.homedir(), "Documents", "Projects", "Skills");
|
|
343
|
+
}
|
|
344
|
+
function recommendSkills(vault, installedDirs) {
|
|
345
|
+
const idx = VaultIndex.load(vault);
|
|
346
|
+
const corpus = (idx.meta.chunks.map((c) => c.text).join("\n") + "\n" + Object.values(idx.meta.notes).map((n) => `${n.title} ${n.tags.join(" ")}`).join("\n")).toLowerCase();
|
|
347
|
+
const installed = /* @__PURE__ */ new Set();
|
|
348
|
+
for (const dir of installedDirs) {
|
|
349
|
+
try {
|
|
350
|
+
for (const e of fs3.readdirSync(dir)) installed.add(e);
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const out = [];
|
|
355
|
+
for (const rule of RULES) {
|
|
356
|
+
if (installed.has(rule.skill)) continue;
|
|
357
|
+
let mentions = 0;
|
|
358
|
+
const found = [];
|
|
359
|
+
for (const kw of rule.keywords) {
|
|
360
|
+
const re = new RegExp(`(?<![\\p{L}\\p{N}-])${kw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\p{L}\\p{N}-])`, "gu");
|
|
361
|
+
const count = (corpus.match(re) ?? []).length;
|
|
362
|
+
if (count > 0) found.push(kw);
|
|
363
|
+
mentions += count;
|
|
364
|
+
}
|
|
365
|
+
if (mentions >= MIN_MENTIONS) {
|
|
366
|
+
const local = fs3.existsSync(path3.join(localSkillsRepo(), rule.skill));
|
|
367
|
+
out.push({
|
|
368
|
+
skill: rule.skill,
|
|
369
|
+
mentions,
|
|
370
|
+
reason: `detect\xE9 ${mentions} menciones de ${found.slice(0, 3).join(", ")} en la b\xF3veda`,
|
|
371
|
+
source: local ? "local" : "skills.sh"
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return out.sort((a, b) => b.mentions - a.mentions);
|
|
376
|
+
}
|
|
377
|
+
function installSkill(rec, targetDir) {
|
|
378
|
+
fs3.mkdirSync(targetDir, { recursive: true });
|
|
379
|
+
const dest = path3.join(targetDir, rec.skill);
|
|
380
|
+
if (fs3.existsSync(dest)) return { ok: true, detail: "ya instalada" };
|
|
381
|
+
if (rec.source === "local") {
|
|
382
|
+
try {
|
|
383
|
+
fs3.cpSync(path3.join(localSkillsRepo(), rec.skill), dest, { recursive: true });
|
|
384
|
+
return { ok: true, detail: `copiada desde ${localSkillsRepo()}` };
|
|
385
|
+
} catch (e) {
|
|
386
|
+
return { ok: false, detail: `error copiando: ${e.message}` };
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
execFileSync2("npx", ["--yes", "skills", "add", rec.skill, "--yes"], {
|
|
391
|
+
stdio: "pipe",
|
|
392
|
+
timeout: 12e4,
|
|
393
|
+
cwd: path3.dirname(targetDir)
|
|
394
|
+
});
|
|
395
|
+
return { ok: true, detail: "instalada desde skills.sh" };
|
|
396
|
+
} catch {
|
|
397
|
+
return {
|
|
398
|
+
ok: false,
|
|
399
|
+
detail: `no disponible en skills.sh \u2014 instala manual: npx skills add <owner>/${rec.skill}`
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// src/core/agents.ts
|
|
405
|
+
import fs4 from "fs";
|
|
406
|
+
import os3 from "os";
|
|
407
|
+
import path4 from "path";
|
|
408
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
409
|
+
var serverScript = () => path4.join(distDir(), "mcp", "server.js");
|
|
410
|
+
function readJsonSafe(file) {
|
|
411
|
+
try {
|
|
412
|
+
return JSON.parse(fs4.readFileSync(file, "utf8"));
|
|
413
|
+
} catch {
|
|
414
|
+
if (fs4.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
|
|
415
|
+
return {};
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
function writeJson(file, data) {
|
|
419
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
420
|
+
fs4.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
|
|
421
|
+
}
|
|
422
|
+
function mergeMcpServers(file, key = "mcpServers") {
|
|
423
|
+
try {
|
|
424
|
+
const cfg = readJsonSafe(file);
|
|
425
|
+
const servers = cfg[key] ?? {};
|
|
426
|
+
servers["alexandria"] = { command: "node", args: [serverScript()] };
|
|
427
|
+
cfg[key] = servers;
|
|
428
|
+
writeJson(file, cfg);
|
|
429
|
+
return { ok: true, file };
|
|
430
|
+
} catch (e) {
|
|
431
|
+
return { ok: false, file, detail: e.message };
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
function home(...p) {
|
|
435
|
+
return path4.join(os3.homedir(), ...p);
|
|
436
|
+
}
|
|
437
|
+
function vscodeUserDir() {
|
|
438
|
+
if (process.platform === "darwin") return home("Library", "Application Support", "Code", "User");
|
|
439
|
+
if (process.platform === "win32") return path4.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
|
|
440
|
+
return home(".config", "Code", "User");
|
|
441
|
+
}
|
|
442
|
+
var AGENTS = [
|
|
443
|
+
{
|
|
444
|
+
id: "claude",
|
|
445
|
+
name: "Claude Code",
|
|
446
|
+
supportsProject: true,
|
|
447
|
+
detect: () => fs4.existsSync(home(".claude")),
|
|
448
|
+
register(scope, projectDir) {
|
|
449
|
+
if (scope === "project") return mergeMcpServers(path4.join(projectDir, ".mcp.json"));
|
|
450
|
+
return mergeMcpServers(home(".claude.json"));
|
|
451
|
+
}
|
|
452
|
+
},
|
|
453
|
+
{
|
|
454
|
+
id: "cursor",
|
|
455
|
+
name: "Cursor",
|
|
456
|
+
supportsProject: true,
|
|
457
|
+
detect: () => fs4.existsSync(home(".cursor")),
|
|
458
|
+
register(scope, projectDir) {
|
|
459
|
+
const file = scope === "project" ? path4.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
|
|
460
|
+
return mergeMcpServers(file);
|
|
461
|
+
}
|
|
462
|
+
},
|
|
463
|
+
{
|
|
464
|
+
id: "opencode",
|
|
465
|
+
name: "OpenCode",
|
|
466
|
+
supportsProject: true,
|
|
467
|
+
detect: () => fs4.existsSync(home(".config", "opencode")) || fs4.existsSync(home(".opencode")),
|
|
468
|
+
register(scope, projectDir) {
|
|
469
|
+
const file = scope === "project" ? path4.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
|
|
470
|
+
try {
|
|
471
|
+
const cfg = readJsonSafe(file);
|
|
472
|
+
cfg["$schema"] ??= "https://opencode.ai/config.json";
|
|
473
|
+
const mcp = cfg["mcp"] ?? {};
|
|
474
|
+
mcp["alexandria"] = { type: "local", command: ["node", serverScript()], enabled: true };
|
|
475
|
+
cfg["mcp"] = mcp;
|
|
476
|
+
writeJson(file, cfg);
|
|
477
|
+
return { ok: true, file };
|
|
478
|
+
} catch (e) {
|
|
479
|
+
return { ok: false, file, detail: e.message };
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
},
|
|
483
|
+
{
|
|
484
|
+
id: "windsurf",
|
|
485
|
+
name: "Windsurf",
|
|
486
|
+
supportsProject: false,
|
|
487
|
+
detect: () => fs4.existsSync(home(".codeium", "windsurf")),
|
|
488
|
+
register() {
|
|
489
|
+
return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
|
|
490
|
+
}
|
|
491
|
+
},
|
|
492
|
+
{
|
|
493
|
+
id: "cline",
|
|
494
|
+
name: "Cline (VS Code)",
|
|
495
|
+
supportsProject: false,
|
|
496
|
+
detect: () => fs4.existsSync(path4.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
|
|
497
|
+
register() {
|
|
498
|
+
const file = path4.join(
|
|
499
|
+
vscodeUserDir(),
|
|
500
|
+
"globalStorage",
|
|
501
|
+
"saoudrizwan.claude-dev",
|
|
502
|
+
"settings",
|
|
503
|
+
"cline_mcp_settings.json"
|
|
504
|
+
);
|
|
505
|
+
return mergeMcpServers(file);
|
|
506
|
+
}
|
|
507
|
+
},
|
|
508
|
+
{
|
|
509
|
+
id: "codex",
|
|
510
|
+
name: "Codex CLI (OpenAI)",
|
|
511
|
+
supportsProject: false,
|
|
512
|
+
detect: () => fs4.existsSync(home(".codex")),
|
|
513
|
+
register() {
|
|
514
|
+
const file = home(".codex", "config.toml");
|
|
515
|
+
const block = `[mcp_servers.alexandria]
|
|
516
|
+
command = "node"
|
|
517
|
+
args = ["${serverScript().replace(/\\/g, "\\\\")}"]
|
|
518
|
+
`;
|
|
519
|
+
try {
|
|
520
|
+
let text = "";
|
|
521
|
+
try {
|
|
522
|
+
text = fs4.readFileSync(file, "utf8");
|
|
523
|
+
} catch {
|
|
524
|
+
}
|
|
525
|
+
if (/^\[mcp_servers\.alexandria\]/m.test(text)) {
|
|
526
|
+
text = text.replace(/\[mcp_servers\.alexandria\][^[]*/m, block);
|
|
527
|
+
} else {
|
|
528
|
+
text = text.trimEnd() + (text.trim() ? "\n\n" : "") + block;
|
|
529
|
+
}
|
|
530
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
531
|
+
fs4.writeFileSync(file, text);
|
|
532
|
+
return { ok: true, file };
|
|
533
|
+
} catch (e) {
|
|
534
|
+
return { ok: false, file, detail: e.message };
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
id: "gemini",
|
|
540
|
+
name: "Gemini CLI",
|
|
541
|
+
supportsProject: true,
|
|
542
|
+
detect: () => fs4.existsSync(home(".gemini")),
|
|
543
|
+
register(scope, projectDir) {
|
|
544
|
+
const file = scope === "project" ? path4.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
|
|
545
|
+
return mergeMcpServers(file);
|
|
546
|
+
}
|
|
547
|
+
},
|
|
548
|
+
{
|
|
549
|
+
id: "openclaw",
|
|
550
|
+
name: "OpenClaw",
|
|
551
|
+
supportsProject: false,
|
|
552
|
+
detect: () => fs4.existsSync(home(".openclaw")),
|
|
553
|
+
register() {
|
|
554
|
+
const file = home(".openclaw", "openclaw.json");
|
|
555
|
+
try {
|
|
556
|
+
const cfg = readJsonSafe(file);
|
|
557
|
+
const servers = cfg["mcpServers"] ?? {};
|
|
558
|
+
servers["alexandria"] = { command: "node", args: [serverScript()], transport: "stdio" };
|
|
559
|
+
cfg["mcpServers"] = servers;
|
|
560
|
+
writeJson(file, cfg);
|
|
561
|
+
return { ok: true, file, detail: "reinicia el gateway de OpenClaw para que lo tome" };
|
|
562
|
+
} catch (e) {
|
|
563
|
+
return { ok: false, file, detail: e.message };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
},
|
|
567
|
+
{
|
|
568
|
+
id: "hermes",
|
|
569
|
+
name: "Hermes Agent (Nous)",
|
|
570
|
+
supportsProject: false,
|
|
571
|
+
detect: () => fs4.existsSync(home(".hermes")),
|
|
572
|
+
register() {
|
|
573
|
+
const file = home(".hermes", "config.yaml");
|
|
574
|
+
try {
|
|
575
|
+
execFileSync3("hermes", ["mcp", "add", "alexandria", "--command", "node", "--args", serverScript()], {
|
|
576
|
+
stdio: "pipe",
|
|
577
|
+
timeout: 15e3
|
|
578
|
+
});
|
|
579
|
+
return { ok: true, file, detail: "v\xEDa hermes mcp add" };
|
|
580
|
+
} catch {
|
|
581
|
+
}
|
|
582
|
+
try {
|
|
583
|
+
let text = "";
|
|
584
|
+
try {
|
|
585
|
+
text = fs4.readFileSync(file, "utf8");
|
|
586
|
+
} catch {
|
|
587
|
+
}
|
|
588
|
+
if (/^\s*alexandria:/m.test(text)) return { ok: true, file, detail: "ya registrado" };
|
|
589
|
+
const entry = ` alexandria:
|
|
590
|
+
type: stdio
|
|
591
|
+
command: node
|
|
592
|
+
args:
|
|
593
|
+
- "${serverScript()}"
|
|
594
|
+
`;
|
|
595
|
+
if (/^mcp_servers:\s*$/m.test(text)) {
|
|
596
|
+
text = text.replace(/^mcp_servers:\s*$/m, (m) => `${m}
|
|
597
|
+
${entry.trimEnd()}`);
|
|
598
|
+
} else if (/^mcp_servers:/m.test(text)) {
|
|
599
|
+
return { ok: false, file, detail: "mcp_servers ya existe con formato no est\xE1ndar \u2014 agr\xE9galo manual o usa `hermes mcp add`" };
|
|
600
|
+
} else {
|
|
601
|
+
text = text.trimEnd() + (text.trim() ? "\n\n" : "") + "mcp_servers:\n" + entry;
|
|
602
|
+
}
|
|
603
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
604
|
+
fs4.writeFileSync(file, text);
|
|
605
|
+
return { ok: true, file };
|
|
606
|
+
} catch (e) {
|
|
607
|
+
return { ok: false, file, detail: e.message };
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
},
|
|
611
|
+
{
|
|
612
|
+
id: "vscode",
|
|
613
|
+
name: "VS Code (Copilot)",
|
|
614
|
+
supportsProject: true,
|
|
615
|
+
detect: () => fs4.existsSync(vscodeUserDir()),
|
|
616
|
+
register(scope, projectDir) {
|
|
617
|
+
const file = scope === "project" ? path4.join(projectDir, ".vscode", "mcp.json") : path4.join(vscodeUserDir(), "mcp.json");
|
|
618
|
+
try {
|
|
619
|
+
const cfg = readJsonSafe(file);
|
|
620
|
+
const servers = cfg["servers"] ?? {};
|
|
621
|
+
servers["alexandria"] = { type: "stdio", command: "node", args: [serverScript()] };
|
|
622
|
+
cfg["servers"] = servers;
|
|
623
|
+
writeJson(file, cfg);
|
|
624
|
+
return { ok: true, file };
|
|
625
|
+
} catch (e) {
|
|
626
|
+
return { ok: false, file, detail: e.message };
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
];
|
|
631
|
+
function agentById(id) {
|
|
632
|
+
return AGENTS.find((a) => a.id === id.toLowerCase().trim());
|
|
633
|
+
}
|
|
634
|
+
function resolveAgents(spec) {
|
|
635
|
+
const s = spec.toLowerCase().trim();
|
|
636
|
+
if (s === "all" || s === "todos") return AGENTS;
|
|
637
|
+
if (s === "detected" || s === "detectados") return AGENTS.filter((a) => a.detect());
|
|
638
|
+
return s.split(",").map((id) => agentById(id)).filter((a) => Boolean(a));
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// src/cli/banner.ts
|
|
642
|
+
var ART = [
|
|
643
|
+
"\u2584\u2580\u2588 \u2588\u2591\u2591 \u2588\u2580\u2580 \u2580\u2584\u2580 \u2584\u2580\u2588 \u2588\u2584\u2591\u2588 \u2588\u2580\u2584 \u2588\u2580\u2588 \u2588 \u2584\u2580\u2588",
|
|
644
|
+
"\u2588\u2580\u2588 \u2588\u2584\u2584 \u2588\u2588\u2584 \u2588\u2591\u2588 \u2588\u2580\u2588 \u2588\u2591\u2580\u2588 \u2588\u2584\u2580 \u2588\u2580\u2584 \u2588 \u2588\u2580\u2588"
|
|
645
|
+
];
|
|
646
|
+
var TAGLINE = "\u{1F3DB} B\xF3veda de conocimiento local \xB7 creada por Ureck";
|
|
647
|
+
var BAND = [45, 51, 87, 123, 159, 195, 230, 220];
|
|
648
|
+
var BASE = 30;
|
|
649
|
+
var esc = (c) => `\x1B[${c}`;
|
|
650
|
+
var fg = (n) => esc(`38;5;${n}m`);
|
|
651
|
+
var RESET = esc("0m");
|
|
652
|
+
var HIDE = esc("?25l");
|
|
653
|
+
var SHOW = esc("?25h");
|
|
654
|
+
var UP = (n) => esc(`${n}A`);
|
|
655
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
656
|
+
function paintFrame(band) {
|
|
657
|
+
const half = Math.floor(BAND.length / 2);
|
|
658
|
+
return ART.map((line) => {
|
|
659
|
+
let out = " ";
|
|
660
|
+
const chars = [...line];
|
|
661
|
+
for (let i = 0; i < chars.length; i++) {
|
|
662
|
+
const d = Math.abs(i - band);
|
|
663
|
+
out += d <= half ? fg(BAND[Math.min(BAND.length - 1, half + (band - i))] ?? BAND[0]) + chars[i] : fg(BASE) + chars[i];
|
|
664
|
+
}
|
|
665
|
+
return out + RESET;
|
|
666
|
+
}).join("\n");
|
|
667
|
+
}
|
|
668
|
+
async function showBanner(animate) {
|
|
669
|
+
const tty = process.stdout.isTTY && !process.env.CI && process.env.TERM !== "dumb";
|
|
670
|
+
const doAnim = animate ?? tty;
|
|
671
|
+
const width = [...ART[0]].length;
|
|
672
|
+
console.log();
|
|
673
|
+
if (!doAnim || !tty) {
|
|
674
|
+
for (const line of ART) console.log(" " + fg(51) + line + RESET);
|
|
675
|
+
console.log(" " + fg(245) + TAGLINE + RESET + "\n");
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
process.stdout.write(HIDE);
|
|
679
|
+
try {
|
|
680
|
+
process.stdout.write(paintFrame(-99) + "\n");
|
|
681
|
+
const half = Math.floor(BAND.length / 2);
|
|
682
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
683
|
+
for (let band = -half; band <= width + half; band += 2) {
|
|
684
|
+
process.stdout.write(UP(ART.length) + "\r" + paintFrame(band) + "\n");
|
|
685
|
+
await sleep(pass === 0 ? 22 : 14);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
process.stdout.write(UP(ART.length) + "\r" + paintFrame(-99) + "\n");
|
|
689
|
+
const tag = [...TAGLINE];
|
|
690
|
+
process.stdout.write(" " + fg(245));
|
|
691
|
+
for (const ch of tag) {
|
|
692
|
+
process.stdout.write(ch);
|
|
693
|
+
await sleep(9);
|
|
694
|
+
}
|
|
695
|
+
process.stdout.write(RESET + "\n\n");
|
|
696
|
+
} finally {
|
|
697
|
+
process.stdout.write(SHOW);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// src/cli.ts
|
|
702
|
+
function registerAgentsMcp(agents, scope, cwd) {
|
|
703
|
+
for (const agent of agents) {
|
|
704
|
+
if (agent.id === "claude") {
|
|
705
|
+
if (scope === "project") {
|
|
706
|
+
const file = registerMcpProject(cwd);
|
|
707
|
+
console.log(pc.green(`\u2713 MCP \u2192 Claude Code (${file})`));
|
|
708
|
+
continue;
|
|
709
|
+
}
|
|
710
|
+
if (registerMcpGlobal()) {
|
|
711
|
+
console.log(pc.green("\u2713 MCP \u2192 Claude Code (scope user, v\xEDa claude mcp add)"));
|
|
712
|
+
continue;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
const effScope = agent.supportsProject && scope === "project" ? "project" : "global";
|
|
716
|
+
const res = agent.register(effScope, cwd);
|
|
717
|
+
if (res.ok) {
|
|
718
|
+
const note = effScope !== scope ? pc.dim(" [global: no soporta por-proyecto]") : "";
|
|
719
|
+
console.log(pc.green(`\u2713 MCP \u2192 ${agent.name} (${res.file})`) + note);
|
|
720
|
+
} else {
|
|
721
|
+
console.log(pc.yellow(`\u26A0 MCP \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
var program = new Command();
|
|
726
|
+
program.name("ale").description("Alexandria \u2014 b\xF3veda de conocimiento local para agentes de IA (Claude Code, Cursor, OpenCode, Windsurf y m\xE1s): captura autom\xE1tica, b\xFAsqueda sem\xE1ntica offline y grafo de conexiones.").version("0.2.0").option("--vault <path>", "ruta de la b\xF3veda (anula la configuraci\xF3n)");
|
|
727
|
+
var getVault = () => resolveVault({ flag: program.opts().vault });
|
|
728
|
+
async function downloadModelIfMissing() {
|
|
729
|
+
if (modelPresent()) return true;
|
|
730
|
+
console.log(pc.cyan(`\u2193 Descargando modelo de embeddings (${MODEL_ID}, una sola vez)\u2026`));
|
|
731
|
+
let lastPct = -1;
|
|
732
|
+
try {
|
|
733
|
+
await getEmbedder((pct) => {
|
|
734
|
+
if (pct !== lastPct && pct % 10 === 0) {
|
|
735
|
+
lastPct = pct;
|
|
736
|
+
process.stdout.write(`\r ${pct}% `);
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
process.stdout.write("\r 100% \n");
|
|
740
|
+
console.log(pc.green("\u2713 Modelo listo (b\xFAsqueda sem\xE1ntica activada)"));
|
|
741
|
+
return true;
|
|
742
|
+
} catch (e) {
|
|
743
|
+
console.log(pc.yellow(`\u26A0 No pude descargar el modelo (${e.message}).`));
|
|
744
|
+
console.log(pc.yellow(" La b\xF3veda funcionar\xE1 en modo keyword-only; corre `ale doctor` con internet para activar la b\xFAsqueda sem\xE1ntica."));
|
|
745
|
+
return false;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
async function ensureReady(vault = getVault()) {
|
|
749
|
+
ensureVaultStructure(vault);
|
|
750
|
+
const idx = VaultIndex.load(vault);
|
|
751
|
+
const res = await idx.refresh();
|
|
752
|
+
return { vault, idx, res };
|
|
753
|
+
}
|
|
754
|
+
program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: modelo, hooks (Claude Code) y MCP en tus agentes de IA (una sola vez, persiste entre sesiones)").option("--project", "registrar para este proyecto (cwd): .vault.json + .claude/settings.json + .mcp.json").option("--global", "registrar para todas las sesiones del usuario (default)").option("--path <dir>", "ruta del vault Obsidian (existente o nuevo)", defaultVaultPath()).option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
|
|
755
|
+
"--agents <ids>",
|
|
756
|
+
`agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
|
|
757
|
+
).action(async (opts) => {
|
|
758
|
+
const isProject = Boolean(opts.project) && !opts.global;
|
|
759
|
+
const vaultPath = path5.resolve(opts.path);
|
|
760
|
+
const cwd = process.cwd();
|
|
761
|
+
await showBanner();
|
|
762
|
+
console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
|
|
763
|
+
`));
|
|
764
|
+
const vault = resolveVault({ flag: vaultPath });
|
|
765
|
+
ensureVaultStructure(vault);
|
|
766
|
+
console.log(pc.green(`\u2713 B\xF3veda en ${vault.root} (vault Obsidian v\xE1lido \u2014 \xE1brelo en Obsidian cuando quieras)`));
|
|
767
|
+
if (isProject) {
|
|
768
|
+
const file = writeProjectConfig(cwd, vaultPath);
|
|
769
|
+
console.log(pc.green(`\u2713 Config del proyecto: ${file}`));
|
|
770
|
+
} else {
|
|
771
|
+
writeGlobalConfig(vaultPath);
|
|
772
|
+
console.log(pc.green(`\u2713 Config global: ${globalConfigPath()}`));
|
|
773
|
+
}
|
|
774
|
+
const settings = isProject ? projectSettingsPath(cwd) : globalSettingsPath();
|
|
775
|
+
registerHooks(settings);
|
|
776
|
+
console.log(pc.green(`\u2713 Hooks registrados en ${settings}`));
|
|
777
|
+
console.log(pc.dim(" SessionStart (digest) \xB7 UserPromptSubmit (contexto+captura) \xB7 Stop/PreCompact (sesiones)"));
|
|
778
|
+
const scope = isProject ? "project" : "global";
|
|
779
|
+
const chosen = opts.agents ? resolveAgents(opts.agents) : [...AGENTS.filter((a) => a.id === "claude" || a.detect())];
|
|
780
|
+
registerAgentsMcp(chosen, scope, cwd);
|
|
781
|
+
const skipped = AGENTS.filter((a) => !chosen.includes(a));
|
|
782
|
+
if (skipped.length > 0) {
|
|
783
|
+
console.log(pc.dim(` Otros agentes disponibles: ${skipped.map((a) => a.id).join(", ")} \u2192 ale agents <ids>`));
|
|
784
|
+
}
|
|
785
|
+
await downloadModelIfMissing();
|
|
786
|
+
const idx = VaultIndex.load(vault);
|
|
787
|
+
const res = await idx.refresh();
|
|
788
|
+
console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
|
|
789
|
+
console.log(pc.bold(pc.green("\n\u2705 Listo. Abre una sesi\xF3n de tu agente y todo funciona solo \u2014 nada que reconectar nunca.")));
|
|
790
|
+
console.log(pc.dim(" Hooks (captura autom\xE1tica) solo en Claude Code; los dem\xE1s agentes usan las tools MCP."));
|
|
791
|
+
console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents\n'));
|
|
792
|
+
if (opts.skills) await runSkills({ yes: false, project: isProject });
|
|
793
|
+
});
|
|
794
|
+
program.command("agents").description("Lista los agentes de IA soportados y registra el MCP de Alexandria en los que elijas").argument("[ids]", `"all", "detected" o csv (${AGENTS.map((a) => a.id).join(",")})`).option("--project", "registrar a nivel proyecto (cwd) cuando el agente lo soporte").action((ids, opts) => {
|
|
795
|
+
if (!ids) {
|
|
796
|
+
console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));
|
|
797
|
+
for (const a of AGENTS) {
|
|
798
|
+
const det = a.detect();
|
|
799
|
+
console.log(
|
|
800
|
+
` ${det ? pc.green("\u25CF") : pc.dim("\u25CB")} ${a.id.padEnd(9)} ${a.name}${det ? pc.green(" detectado") : pc.dim(" no detectado")}${a.supportsProject ? "" : pc.dim(" (solo global)")}`
|
|
801
|
+
);
|
|
802
|
+
}
|
|
803
|
+
console.log(pc.dim("\n Registrar MCP: ale agents all \xB7 ale agents detected \xB7 ale agents cursor,opencode\n"));
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const chosen = resolveAgents(ids);
|
|
807
|
+
if (chosen.length === 0) {
|
|
808
|
+
console.log(pc.yellow(`Ning\xFAn agente coincide con \xAB${ids}\xBB. Ids v\xE1lidos: ${AGENTS.map((a) => a.id).join(", ")}`));
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd());
|
|
812
|
+
console.log(pc.dim("\n Reinicia el agente (o recarga sus MCP) para que tome el servidor.\n"));
|
|
813
|
+
});
|
|
814
|
+
program.command("add").description("Guardar una nota manualmente").argument("<title>", "t\xEDtulo").option("-c, --content <text>", "contenido markdown (o se lee de stdin)").option("-t, --tags <tags>", "tags separados por coma").action(async (title, opts) => {
|
|
815
|
+
const { vault } = await ensureReady();
|
|
816
|
+
let content = opts.content;
|
|
817
|
+
if (!content && !process.stdin.isTTY) {
|
|
818
|
+
content = fs5.readFileSync(0, "utf8");
|
|
819
|
+
}
|
|
820
|
+
const file = createNote(vault.managed, {
|
|
821
|
+
title,
|
|
822
|
+
content: content ?? "",
|
|
823
|
+
tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
|
|
824
|
+
});
|
|
825
|
+
await VaultIndex.load(vault).refresh();
|
|
826
|
+
console.log(pc.green(`\u2713 ${path5.relative(vault.root, file)}`));
|
|
827
|
+
});
|
|
828
|
+
program.command("search").description("B\xFAsqueda h\xEDbrida (sem\xE1ntica + keyword) en la b\xF3veda").argument("<query...>", "qu\xE9 buscar").option("-k <n>", "n\xFAmero de resultados", "6").option("--expand", "incluir vecinos del grafo").action(async (query, opts) => {
|
|
829
|
+
const vault = getVault();
|
|
830
|
+
if (!vaultExists(vault)) {
|
|
831
|
+
console.log(pc.yellow("No hay b\xF3veda aqu\xED. Corre `ale init` primero."));
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
const q = query.join(" ");
|
|
835
|
+
const results = await hybridSearch(vault, q, parseInt(opts.k, 10) || 6, { expand: opts.expand });
|
|
836
|
+
if (results.length === 0) {
|
|
837
|
+
console.log(pc.dim("Sin resultados."));
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
for (const r of results) {
|
|
841
|
+
const cos = r.cosine > 0 ? pc.dim(` cos ${r.cosine.toFixed(2)}`) : "";
|
|
842
|
+
console.log(`
|
|
843
|
+
${pc.bold(pc.cyan(r.note.title))} ${pc.dim(`(${r.note.rel}, ${r.note.type})`)}${cos}`);
|
|
844
|
+
for (const e of r.excerpts) {
|
|
845
|
+
console.log(pc.dim(" " + e.replace(/\n+/g, " ").slice(0, 220)));
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
console.log();
|
|
849
|
+
});
|
|
850
|
+
program.command("reindex").description("Reindexar la b\xF3veda (incremental; --force para todo)").option("--force", "reindexar todo desde cero").action(async (opts) => {
|
|
851
|
+
const vault = getVault();
|
|
852
|
+
ensureVaultStructure(vault);
|
|
853
|
+
await downloadModelIfMissing();
|
|
854
|
+
const idx = VaultIndex.load(vault);
|
|
855
|
+
const res = await idx.refresh(modelPresent(), opts.force);
|
|
856
|
+
console.log(
|
|
857
|
+
pc.green(
|
|
858
|
+
`\u2713 ${res.changed} notas reindexadas, ${res.removed} eliminadas \u2014 ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`
|
|
859
|
+
)
|
|
860
|
+
);
|
|
861
|
+
});
|
|
862
|
+
program.command("graph").description("Visor del grafo de conocimiento (local, estilo Obsidian/Graphify)").option("--out <file>", "escribir HTML autocontenido en vez de servir").option("--no-open", "no abrir el navegador").action(async (opts) => {
|
|
863
|
+
const { vault } = await ensureReady();
|
|
864
|
+
const where = await serveGraph(vault, { out: opts.out, open: opts.open });
|
|
865
|
+
if (opts.out) console.log(pc.green(`\u2713 Grafo escrito en ${where}`));
|
|
866
|
+
else {
|
|
867
|
+
console.log(pc.green(`\u2713 Grafo en ${pc.bold(where)} ${pc.dim("(Ctrl+C para cerrar)")}`));
|
|
868
|
+
await new Promise(() => {
|
|
869
|
+
});
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados").action(async () => {
|
|
873
|
+
const { vault, idx } = await ensureReady();
|
|
874
|
+
const notes = Object.values(idx.meta.notes);
|
|
875
|
+
const byType = notes.reduce((acc, n) => {
|
|
876
|
+
acc[n.type] = (acc[n.type] ?? 0) + 1;
|
|
877
|
+
return acc;
|
|
878
|
+
}, {});
|
|
879
|
+
const s = readStats(vault);
|
|
880
|
+
console.log(pc.bold("\n\u{1F9E0} B\xF3veda: ") + vault.root + pc.dim(` (${vault.source})`));
|
|
881
|
+
console.log(` Notas: ${notes.length} ${pc.dim(JSON.stringify(byType))}`);
|
|
882
|
+
console.log(` Chunks indexados: ${idx.meta.chunks.length} \xB7 Conexiones: ${idx.meta.links.length}`);
|
|
883
|
+
console.log(` B\xFAsqueda sem\xE1ntica: ${idx.emb ? pc.green("activa") : pc.yellow("keyword-only (corre ale reindex con internet)")}`);
|
|
884
|
+
console.log(pc.bold("\n\u{1F4B0} Ahorro estimado"));
|
|
885
|
+
console.log(` Inyecciones de contexto: ${s.injections} (${s.solutionCacheHits} con soluci\xF3n cacheada)`);
|
|
886
|
+
console.log(` Tokens inyectados: ~${s.injectedTokens.toLocaleString()}`);
|
|
887
|
+
console.log(` Tokens ahorrados (vs re-explorar): ~${pc.green(s.estimatedSavedTokens.toLocaleString())}
|
|
888
|
+
`);
|
|
889
|
+
});
|
|
890
|
+
async function runSkills(opts) {
|
|
891
|
+
const { vault } = await ensureReady();
|
|
892
|
+
const cwd = process.cwd();
|
|
893
|
+
const targetDir = opts.project ? path5.join(cwd, ".claude", "skills") : path5.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
|
|
894
|
+
const recs = recommendSkills(vault, [targetDir]);
|
|
895
|
+
if (recs.length === 0) {
|
|
896
|
+
console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
console.log(pc.bold(`
|
|
900
|
+
\u{1F4E6} Skills recomendadas seg\xFAn tu b\xF3veda (destino: ${targetDir}):
|
|
901
|
+
`));
|
|
902
|
+
for (const r of recs) {
|
|
903
|
+
console.log(` ${pc.cyan(r.skill)} ${pc.dim(`[${r.source}]`)} \u2014 ${r.reason}`);
|
|
904
|
+
}
|
|
905
|
+
let selected = recs;
|
|
906
|
+
if (!opts.yes) {
|
|
907
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
908
|
+
const answer = (await rl.question(pc.bold("\n\xBFInstalar todas? [s/N/n\xFAmeros separados por coma] "))).trim().toLowerCase();
|
|
909
|
+
rl.close();
|
|
910
|
+
if (answer === "s" || answer === "si" || answer === "s\xED" || answer === "y") {
|
|
911
|
+
selected = recs;
|
|
912
|
+
} else if (/^[\d,\s]+$/.test(answer)) {
|
|
913
|
+
const nums = answer.split(",").map((n) => parseInt(n.trim(), 10) - 1);
|
|
914
|
+
selected = recs.filter((_, i) => nums.includes(i));
|
|
915
|
+
} else {
|
|
916
|
+
console.log(pc.dim("Nada instalado."));
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
for (const r of selected) {
|
|
921
|
+
const res = installSkill(r, targetDir);
|
|
922
|
+
console.log(res.ok ? pc.green(`\u2713 ${r.skill} \u2014 ${res.detail}`) : pc.yellow(`\u26A0 ${r.skill} \u2014 ${res.detail}`));
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
program.command("skills").description("Analiza la b\xF3veda y recomienda/instala skills de Claude (skills.sh o repo local)").option("-y, --yes", "instalar sin preguntar").option("--project", "instalar en .claude/skills del proyecto (default: global del usuario)").action(runSkills);
|
|
926
|
+
program.command("doctor").description("Verifica y repara la instalaci\xF3n (modelo, hooks, MCP, \xEDndice)").option("--project", "revisar registros del proyecto (cwd) en vez de los globales").action(async (opts) => {
|
|
927
|
+
const vault = getVault();
|
|
928
|
+
const cwd = process.cwd();
|
|
929
|
+
const nodeOk = parseInt(process.versions.node.split(".")[0], 10) >= 20;
|
|
930
|
+
console.log(pc.bold("\n\u{1FA7A} ale doctor\n"));
|
|
931
|
+
console.log(`${nodeOk ? pc.green("\u2713") : pc.red("\u2717")} Node ${process.versions.node} ${nodeOk ? "" : "(se requiere \u2265 20: https://nodejs.org)"}`);
|
|
932
|
+
ensureVaultStructure(vault);
|
|
933
|
+
console.log(`${pc.green("\u2713")} B\xF3veda: ${vault.root} (${vault.source})`);
|
|
934
|
+
const model = await downloadModelIfMissing();
|
|
935
|
+
console.log(`${model ? pc.green("\u2713") : pc.yellow("\u26A0")} Modelo de embeddings ${model ? "presente" : "ausente (keyword-only)"}`);
|
|
936
|
+
const settings = opts.project ? projectSettingsPath(cwd) : globalSettingsPath();
|
|
937
|
+
if (!hooksRegistered(settings)) {
|
|
938
|
+
registerHooks(settings);
|
|
939
|
+
console.log(`${pc.green("\u2713")} Hooks re-registrados en ${settings}`);
|
|
940
|
+
} else {
|
|
941
|
+
console.log(`${pc.green("\u2713")} Hooks registrados (${settings})`);
|
|
942
|
+
}
|
|
943
|
+
if (opts.project) {
|
|
944
|
+
if (!mcpRegisteredProject(cwd)) {
|
|
945
|
+
registerMcpProject(cwd);
|
|
946
|
+
console.log(`${pc.green("\u2713")} MCP re-registrado en .mcp.json`);
|
|
947
|
+
} else {
|
|
948
|
+
console.log(`${pc.green("\u2713")} MCP registrado (.mcp.json)`);
|
|
949
|
+
}
|
|
950
|
+
} else {
|
|
951
|
+
console.log(pc.dim(" MCP global: verifica con `claude mcp list` (repara con `claude mcp add --scope user alexandria -- node \u2026/mcp/server.js`)"));
|
|
952
|
+
}
|
|
953
|
+
const idx = VaultIndex.load(vault);
|
|
954
|
+
const res = await idx.refresh();
|
|
955
|
+
console.log(`${pc.green("\u2713")} \xCDndice al d\xEDa (${res.changed} reindexadas, ${Object.keys(idx.meta.notes).length} notas)
|
|
956
|
+
`);
|
|
957
|
+
});
|
|
958
|
+
program.command("uninstall").description("Quita hooks de Claude Code (no borra la b\xF3veda ni las notas)").option("--project", "quitar del proyecto (cwd)").action((opts) => {
|
|
959
|
+
const settings = opts.project ? projectSettingsPath(process.cwd()) : globalSettingsPath();
|
|
960
|
+
unregisterHooks(settings);
|
|
961
|
+
console.log(pc.green(`\u2713 Hooks de alexandria eliminados de ${settings}`));
|
|
962
|
+
console.log(pc.dim(" MCP: qu\xEDtalo con `claude mcp remove alexandria` o borrando la entrada de .mcp.json. Tus notas quedan intactas."));
|
|
963
|
+
});
|
|
964
|
+
program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
|
|
965
|
+
await import("./mcp/server.js");
|
|
966
|
+
});
|
|
967
|
+
if (process.argv.length <= 2) {
|
|
968
|
+
await showBanner();
|
|
969
|
+
program.outputHelp();
|
|
970
|
+
} else {
|
|
971
|
+
program.parseAsync().catch((e) => {
|
|
972
|
+
console.error(pc.red(`Error: ${e.message}`));
|
|
973
|
+
process.exit(1);
|
|
974
|
+
});
|
|
975
|
+
}
|