@ureck/alexandria 0.2.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -16,12 +16,8 @@ import {
16
16
  } from "./chunk-KHTYRYDR.js";
17
17
  import {
18
18
  hybridSearch
19
- } from "./chunk-O7FDC2PB.js";
19
+ } from "./chunk-ADHRHLX7.js";
20
20
  import {
21
- VaultIndex
22
- } from "./chunk-UWAIMIG2.js";
23
- import {
24
- createNote,
25
21
  defaultVaultPath,
26
22
  ensureVaultStructure,
27
23
  globalConfigPath,
@@ -29,7 +25,18 @@ import {
29
25
  vaultExists,
30
26
  writeGlobalConfig,
31
27
  writeProjectConfig
32
- } from "./chunk-CZM5NQZJ.js";
28
+ } from "./chunk-KB6KYZFQ.js";
29
+ import {
30
+ serveGraph
31
+ } from "./chunk-WPNU64MA.js";
32
+ import {
33
+ VaultIndex
34
+ } from "./chunk-ZW7XY3EN.js";
35
+ import {
36
+ createNote,
37
+ slugify,
38
+ upsertNote
39
+ } from "./chunk-JPHL2JHE.js";
33
40
  import {
34
41
  MODEL_ID,
35
42
  getEmbedder,
@@ -43,183 +50,10 @@ import readline from "readline/promises";
43
50
  import { Command } from "commander";
44
51
  import pc from "picocolors";
45
52
 
46
- // src/graph/viewer.ts
47
- import fs from "fs";
48
- import http from "http";
49
- import path from "path";
50
- import { spawn } from "child_process";
51
- function buildGraphData(idx) {
52
- const deg = /* @__PURE__ */ new Map();
53
- for (const l of idx.meta.links) {
54
- deg.set(l.from, (deg.get(l.from) ?? 0) + 1);
55
- deg.set(l.to, (deg.get(l.to) ?? 0) + 1);
56
- }
57
- const nodes = Object.values(idx.meta.notes).map((n) => ({
58
- id: n.rel,
59
- title: n.title,
60
- type: n.type,
61
- deg: deg.get(n.rel) ?? 0,
62
- hits: n.hits ?? 1
63
- }));
64
- const edges = idx.meta.links.map((l) => ({ s: l.from, t: l.to, type: l.type }));
65
- return { nodes, edges };
66
- }
67
- function renderGraphHtml(data) {
68
- return `<!doctype html>
69
- <html lang="es">
70
- <head>
71
- <meta charset="utf-8">
72
- <title>Alexandria \u2014 grafo de conocimiento</title>
73
- <style>
74
- html,body{margin:0;height:100%;background:#0f1117;color:#e6e6e6;font:14px/1.4 system-ui,sans-serif;overflow:hidden}
75
- #hud{position:fixed;top:12px;left:12px;background:#1a1d27cc;padding:10px 14px;border-radius:10px;max-width:340px}
76
- #hud h1{font-size:15px;margin:0 0 4px}
77
- #hud .leg span{display:inline-block;width:10px;height:10px;border-radius:50%;margin:0 4px 0 10px}
78
- #info{position:fixed;bottom:12px;left:12px;background:#1a1d27cc;padding:10px 14px;border-radius:10px;max-width:420px;display:none}
79
- canvas{display:block}
80
- </style>
81
- </head>
82
- <body>
83
- <div id="hud">
84
- <h1>\u{1F9E0} Alexandria \u2014 grafo</h1>
85
- <div id="counts"></div>
86
- <div class="leg">
87
- <span style="background:#7aa2f7"></span>nota
88
- <span style="background:#9ece6a"></span>sesi\xF3n
89
- <span style="background:#e0af68"></span>prompt
90
- <span style="background:#f7768e"></span>mapa
91
- </div>
92
- <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>
93
- </div>
94
- <div id="info"></div>
95
- <canvas id="c"></canvas>
96
- <script>
97
- const DATA = ${JSON.stringify(data)};
98
- const COLORS = { note:'#7aa2f7', session:'#9ece6a', prompt:'#e0af68', map:'#f7768e' };
99
- const cv = document.getElementById('c'), ctx = cv.getContext('2d');
100
- let W, H; const fit = () => { W = cv.width = innerWidth; H = cv.height = innerHeight; };
101
- fit(); addEventListener('resize', fit);
102
- document.getElementById('counts').textContent = DATA.nodes.length + ' notas \xB7 ' + DATA.edges.length + ' conexiones';
103
-
104
- const nodes = DATA.nodes.map((n,i) => ({...n,
105
- x: Math.cos(i/DATA.nodes.length*6.283)*Math.min(W,H)*.3 + W/2 + (Math.random()-.5)*40,
106
- y: Math.sin(i/DATA.nodes.length*6.283)*Math.min(W,H)*.3 + H/2 + (Math.random()-.5)*40,
107
- vx:0, vy:0, r: 4 + Math.min(n.deg,12)*1.2 + Math.min(n.hits,8)*.5
108
- }));
109
- const byId = new Map(nodes.map(n=>[n.id,n]));
110
- 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}));
111
-
112
- let zoom = 1, panX = 0, panY = 0, dragNode = null, hot = true, heat = 300;
113
- function step(){
114
- if(!hot) return;
115
- // repulsi\xF3n O(n\xB2) \u2014 bien hasta ~1500 nodos
116
- for(let i=0;i<nodes.length;i++) for(let j=i+1;j<nodes.length;j++){
117
- const a=nodes[i], b=nodes[j];
118
- let dx=b.x-a.x, dy=b.y-a.y, d2=dx*dx+dy*dy+0.01, d=Math.sqrt(d2);
119
- const f = Math.min(1800/d2, 8);
120
- dx/=d; dy/=d;
121
- a.vx-=dx*f; a.vy-=dy*f; b.vx+=dx*f; b.vy+=dy*f;
122
- }
123
- for(const e of edges){
124
- let dx=e.b.x-e.a.x, dy=e.b.y-e.a.y, d=Math.sqrt(dx*dx+dy*dy)+0.01;
125
- const want = e.type==='wikilink'?110:160;
126
- const f=(d-want)*0.004*(e.type==='wikilink'?1.4:0.7);
127
- dx/=d; dy/=d;
128
- e.a.vx+=dx*f*d; e.a.vy+=dy*f*d; e.b.vx-=dx*f*d; e.b.vy-=dy*f*d;
129
- }
130
- for(const n of nodes){
131
- n.vx += (W/2-n.x)*0.0004; n.vy += (H/2-n.y)*0.0004; // gravedad al centro
132
- n.vx*=0.85; n.vy*=0.85;
133
- if(n!==dragNode){ n.x+=n.vx; n.y+=n.vy; }
134
- }
135
- if(--heat<=0 && !dragNode) hot=false;
136
- }
137
- function draw(){
138
- ctx.setTransform(1,0,0,1,0,0); ctx.clearRect(0,0,W,H);
139
- ctx.setTransform(zoom,0,0,zoom,panX,panY);
140
- for(const e of edges){
141
- ctx.beginPath();
142
- ctx.setLineDash(e.type==='semantic'?[4,4]:[]);
143
- ctx.strokeStyle = e.type==='semantic' ? '#3b4261' : '#565f89';
144
- ctx.lineWidth = 1;
145
- ctx.moveTo(e.a.x,e.a.y); ctx.lineTo(e.b.x,e.b.y); ctx.stroke();
146
- }
147
- ctx.setLineDash([]);
148
- for(const n of nodes){
149
- ctx.beginPath(); ctx.fillStyle = COLORS[n.type]||'#7aa2f7';
150
- ctx.arc(n.x,n.y,n.r,0,6.283); ctx.fill();
151
- }
152
- if(zoom>0.6){
153
- ctx.fillStyle='#c0caf5'; ctx.font = (11/Math.max(zoom,1))+'px system-ui';
154
- 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); }
155
- }
156
- }
157
- (function loop(){ step(); draw(); requestAnimationFrame(loop); })();
158
-
159
- const toWorld = (x,y)=>[(x-panX)/zoom,(y-panY)/zoom];
160
- 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);}); };
161
- let panning=false, px=0, py=0;
162
- 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;} });
163
- addEventListener('mousemove',e=>{
164
- if(dragNode){ const [wx,wy]=toWorld(e.clientX,e.clientY); dragNode.x=wx; dragNode.y=wy; }
165
- else if(panning){ panX+=e.clientX-px; panY+=e.clientY-py; px=e.clientX; py=e.clientY; }
166
- });
167
- addEventListener('mouseup',e=>{
168
- if(dragNode===null && !panning) return;
169
- if(dragNode){ dragNode=null; }
170
- panning=false;
171
- });
172
- cv.addEventListener('click',e=>{
173
- const n=pick(e.clientX,e.clientY); const info=document.getElementById('info');
174
- 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; }
175
- else info.style.display='none';
176
- });
177
- cv.addEventListener('wheel',e=>{
178
- e.preventDefault();
179
- const f = e.deltaY<0?1.1:0.9;
180
- panX = e.clientX-(e.clientX-panX)*f; panY = e.clientY-(e.clientY-panY)*f; zoom*=f;
181
- },{passive:false});
182
- </script>
183
- </body>
184
- </html>`;
185
- }
186
- function openBrowser(url) {
187
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
188
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
189
- try {
190
- spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
191
- } catch {
192
- }
193
- }
194
- async function serveGraph(vault, opts = {}) {
195
- const idx = VaultIndex.load(vault);
196
- await idx.refresh(false).catch(() => {
197
- });
198
- const html = renderGraphHtml(buildGraphData(idx));
199
- if (opts.out) {
200
- const file = path.resolve(opts.out);
201
- fs.writeFileSync(file, html);
202
- return file;
203
- }
204
- return new Promise((resolve) => {
205
- const server = http.createServer((_req, res) => {
206
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
207
- res.end(html);
208
- });
209
- server.listen(0, "127.0.0.1", () => {
210
- const addr = server.address();
211
- const port = typeof addr === "object" && addr ? addr.port : 0;
212
- const url = `http://127.0.0.1:${port}`;
213
- if (opts.open !== false) openBrowser(url);
214
- resolve(url);
215
- });
216
- });
217
- }
218
-
219
53
  // src/skills/recommend.ts
220
- import fs2 from "fs";
54
+ import fs from "fs";
221
55
  import os from "os";
222
- import path2 from "path";
56
+ import path from "path";
223
57
  import { execFileSync } from "child_process";
224
58
  var RULES = [
225
59
  { skill: "pdf-report-gen", keywords: ["pdf", "reporte pdf", "membrete"] },
@@ -239,7 +73,7 @@ var RULES = [
239
73
  ];
240
74
  var MIN_MENTIONS = 3;
241
75
  function localSkillsRepo() {
242
- return path2.join(os.homedir(), "Documents", "Projects", "Skills");
76
+ return path.join(os.homedir(), "Documents", "Projects", "Skills");
243
77
  }
244
78
  function recommendSkills(vault, installedDirs) {
245
79
  const idx = VaultIndex.load(vault);
@@ -247,7 +81,7 @@ function recommendSkills(vault, installedDirs) {
247
81
  const installed = /* @__PURE__ */ new Set();
248
82
  for (const dir of installedDirs) {
249
83
  try {
250
- for (const e of fs2.readdirSync(dir)) installed.add(e);
84
+ for (const e of fs.readdirSync(dir)) installed.add(e);
251
85
  } catch {
252
86
  }
253
87
  }
@@ -263,7 +97,7 @@ function recommendSkills(vault, installedDirs) {
263
97
  mentions += count;
264
98
  }
265
99
  if (mentions >= MIN_MENTIONS) {
266
- const local = fs2.existsSync(path2.join(localSkillsRepo(), rule.skill));
100
+ const local = fs.existsSync(path.join(localSkillsRepo(), rule.skill));
267
101
  out.push({
268
102
  skill: rule.skill,
269
103
  mentions,
@@ -275,12 +109,12 @@ function recommendSkills(vault, installedDirs) {
275
109
  return out.sort((a, b) => b.mentions - a.mentions);
276
110
  }
277
111
  function installSkill(rec, targetDir) {
278
- fs2.mkdirSync(targetDir, { recursive: true });
279
- const dest = path2.join(targetDir, rec.skill);
280
- if (fs2.existsSync(dest)) return { ok: true, detail: "ya instalada" };
112
+ fs.mkdirSync(targetDir, { recursive: true });
113
+ const dest = path.join(targetDir, rec.skill);
114
+ if (fs.existsSync(dest)) return { ok: true, detail: "ya instalada" };
281
115
  if (rec.source === "local") {
282
116
  try {
283
- fs2.cpSync(path2.join(localSkillsRepo(), rec.skill), dest, { recursive: true });
117
+ fs.cpSync(path.join(localSkillsRepo(), rec.skill), dest, { recursive: true });
284
118
  return { ok: true, detail: `copiada desde ${localSkillsRepo()}` };
285
119
  } catch (e) {
286
120
  return { ok: false, detail: `error copiando: ${e.message}` };
@@ -290,7 +124,7 @@ function installSkill(rec, targetDir) {
290
124
  execFileSync("npx", ["--yes", "skills", "add", rec.skill, "--yes"], {
291
125
  stdio: "pipe",
292
126
  timeout: 12e4,
293
- cwd: path2.dirname(targetDir)
127
+ cwd: path.dirname(targetDir)
294
128
  });
295
129
  return { ok: true, detail: "instalada desde skills.sh" };
296
130
  } catch {
@@ -302,22 +136,22 @@ function installSkill(rec, targetDir) {
302
136
  }
303
137
 
304
138
  // src/core/agents.ts
305
- import fs3 from "fs";
139
+ import fs2 from "fs";
306
140
  import os2 from "os";
307
- import path3 from "path";
141
+ import path2 from "path";
308
142
  import { execFileSync as execFileSync2 } from "child_process";
309
- var serverScript = () => path3.join(distDir(), "mcp", "server.js");
143
+ var serverScript = () => path2.join(distDir(), "mcp", "server.js");
310
144
  function readJsonSafe(file) {
311
145
  try {
312
- return JSON.parse(fs3.readFileSync(file, "utf8"));
146
+ return JSON.parse(fs2.readFileSync(file, "utf8"));
313
147
  } catch {
314
- if (fs3.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
148
+ if (fs2.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
315
149
  return {};
316
150
  }
317
151
  }
318
152
  function writeJson(file, data) {
319
- fs3.mkdirSync(path3.dirname(file), { recursive: true });
320
- fs3.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
153
+ fs2.mkdirSync(path2.dirname(file), { recursive: true });
154
+ fs2.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
321
155
  }
322
156
  function mergeMcpServers(file, key = "mcpServers") {
323
157
  try {
@@ -332,11 +166,11 @@ function mergeMcpServers(file, key = "mcpServers") {
332
166
  }
333
167
  }
334
168
  function home(...p) {
335
- return path3.join(os2.homedir(), ...p);
169
+ return path2.join(os2.homedir(), ...p);
336
170
  }
337
171
  function vscodeUserDir() {
338
172
  if (process.platform === "darwin") return home("Library", "Application Support", "Code", "User");
339
- if (process.platform === "win32") return path3.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
173
+ if (process.platform === "win32") return path2.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
340
174
  return home(".config", "Code", "User");
341
175
  }
342
176
  var AGENTS = [
@@ -344,9 +178,9 @@ var AGENTS = [
344
178
  id: "claude",
345
179
  name: "Claude Code",
346
180
  supportsProject: true,
347
- detect: () => fs3.existsSync(home(".claude")),
181
+ detect: () => fs2.existsSync(home(".claude")),
348
182
  register(scope, projectDir) {
349
- if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
183
+ if (scope === "project") return mergeMcpServers(path2.join(projectDir, ".mcp.json"));
350
184
  return mergeMcpServers(home(".claude.json"));
351
185
  }
352
186
  },
@@ -354,9 +188,9 @@ var AGENTS = [
354
188
  id: "cursor",
355
189
  name: "Cursor",
356
190
  supportsProject: true,
357
- detect: () => fs3.existsSync(home(".cursor")),
191
+ detect: () => fs2.existsSync(home(".cursor")),
358
192
  register(scope, projectDir) {
359
- const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
193
+ const file = scope === "project" ? path2.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
360
194
  return mergeMcpServers(file);
361
195
  }
362
196
  },
@@ -364,9 +198,9 @@ var AGENTS = [
364
198
  id: "opencode",
365
199
  name: "OpenCode",
366
200
  supportsProject: true,
367
- detect: () => fs3.existsSync(home(".config", "opencode")) || fs3.existsSync(home(".opencode")),
201
+ detect: () => fs2.existsSync(home(".config", "opencode")) || fs2.existsSync(home(".opencode")),
368
202
  register(scope, projectDir) {
369
- const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
203
+ const file = scope === "project" ? path2.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
370
204
  try {
371
205
  const cfg = readJsonSafe(file);
372
206
  cfg["$schema"] ??= "https://opencode.ai/config.json";
@@ -384,7 +218,7 @@ var AGENTS = [
384
218
  id: "windsurf",
385
219
  name: "Windsurf",
386
220
  supportsProject: false,
387
- detect: () => fs3.existsSync(home(".codeium", "windsurf")),
221
+ detect: () => fs2.existsSync(home(".codeium", "windsurf")),
388
222
  register() {
389
223
  return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
390
224
  }
@@ -393,9 +227,9 @@ var AGENTS = [
393
227
  id: "cline",
394
228
  name: "Cline (VS Code)",
395
229
  supportsProject: false,
396
- detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
230
+ detect: () => fs2.existsSync(path2.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
397
231
  register() {
398
- const file = path3.join(
232
+ const file = path2.join(
399
233
  vscodeUserDir(),
400
234
  "globalStorage",
401
235
  "saoudrizwan.claude-dev",
@@ -409,7 +243,7 @@ var AGENTS = [
409
243
  id: "codex",
410
244
  name: "Codex CLI (OpenAI)",
411
245
  supportsProject: false,
412
- detect: () => fs3.existsSync(home(".codex")),
246
+ detect: () => fs2.existsSync(home(".codex")),
413
247
  register() {
414
248
  const file = home(".codex", "config.toml");
415
249
  const block = `[mcp_servers.alexandria]
@@ -419,7 +253,7 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
419
253
  try {
420
254
  let text = "";
421
255
  try {
422
- text = fs3.readFileSync(file, "utf8");
256
+ text = fs2.readFileSync(file, "utf8");
423
257
  } catch {
424
258
  }
425
259
  if (/^\[mcp_servers\.alexandria\]/m.test(text)) {
@@ -427,8 +261,8 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
427
261
  } else {
428
262
  text = text.trimEnd() + (text.trim() ? "\n\n" : "") + block;
429
263
  }
430
- fs3.mkdirSync(path3.dirname(file), { recursive: true });
431
- fs3.writeFileSync(file, text);
264
+ fs2.mkdirSync(path2.dirname(file), { recursive: true });
265
+ fs2.writeFileSync(file, text);
432
266
  return { ok: true, file };
433
267
  } catch (e) {
434
268
  return { ok: false, file, detail: e.message };
@@ -439,9 +273,9 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
439
273
  id: "gemini",
440
274
  name: "Gemini CLI",
441
275
  supportsProject: true,
442
- detect: () => fs3.existsSync(home(".gemini")),
276
+ detect: () => fs2.existsSync(home(".gemini")),
443
277
  register(scope, projectDir) {
444
- const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
278
+ const file = scope === "project" ? path2.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
445
279
  return mergeMcpServers(file);
446
280
  }
447
281
  },
@@ -449,7 +283,7 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
449
283
  id: "openclaw",
450
284
  name: "OpenClaw",
451
285
  supportsProject: false,
452
- detect: () => fs3.existsSync(home(".openclaw")),
286
+ detect: () => fs2.existsSync(home(".openclaw")),
453
287
  register() {
454
288
  const file = home(".openclaw", "openclaw.json");
455
289
  try {
@@ -468,7 +302,7 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
468
302
  id: "hermes",
469
303
  name: "Hermes Agent (Nous)",
470
304
  supportsProject: false,
471
- detect: () => fs3.existsSync(home(".hermes")),
305
+ detect: () => fs2.existsSync(home(".hermes")),
472
306
  register() {
473
307
  const file = home(".hermes", "config.yaml");
474
308
  try {
@@ -482,7 +316,7 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
482
316
  try {
483
317
  let text = "";
484
318
  try {
485
- text = fs3.readFileSync(file, "utf8");
319
+ text = fs2.readFileSync(file, "utf8");
486
320
  } catch {
487
321
  }
488
322
  if (/^\s*alexandria:/m.test(text)) return { ok: true, file, detail: "ya registrado" };
@@ -500,8 +334,8 @@ ${entry.trimEnd()}`);
500
334
  } else {
501
335
  text = text.trimEnd() + (text.trim() ? "\n\n" : "") + "mcp_servers:\n" + entry;
502
336
  }
503
- fs3.mkdirSync(path3.dirname(file), { recursive: true });
504
- fs3.writeFileSync(file, text);
337
+ fs2.mkdirSync(path2.dirname(file), { recursive: true });
338
+ fs2.writeFileSync(file, text);
505
339
  return { ok: true, file };
506
340
  } catch (e) {
507
341
  return { ok: false, file, detail: e.message };
@@ -512,9 +346,9 @@ ${entry.trimEnd()}`);
512
346
  id: "vscode",
513
347
  name: "VS Code (Copilot)",
514
348
  supportsProject: true,
515
- detect: () => fs3.existsSync(vscodeUserDir()),
349
+ detect: () => fs2.existsSync(vscodeUserDir()),
516
350
  register(scope, projectDir) {
517
- const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
351
+ const file = scope === "project" ? path2.join(projectDir, ".vscode", "mcp.json") : path2.join(vscodeUserDir(), "mcp.json");
518
352
  try {
519
353
  const cfg = readJsonSafe(file);
520
354
  const servers = cfg["servers"] ?? {};
@@ -598,6 +432,114 @@ async function showBanner(animate) {
598
432
  }
599
433
  }
600
434
 
435
+ // src/core/setup.ts
436
+ import fs3 from "fs";
437
+ import os3 from "os";
438
+ import path3 from "path";
439
+ function ensureGitignore(projectDir, vaultRoot) {
440
+ if (!fs3.existsSync(path3.join(projectDir, ".git"))) return null;
441
+ const rel = path3.relative(projectDir, vaultRoot);
442
+ if (rel.startsWith("..")) return null;
443
+ const file = path3.join(projectDir, ".gitignore");
444
+ const entries = [`${rel.split(path3.sep).join("/")}/`];
445
+ let text = "";
446
+ try {
447
+ text = fs3.readFileSync(file, "utf8");
448
+ } catch {
449
+ }
450
+ const missing = entries.filter((e) => !text.split("\n").some((l) => l.trim() === e || l.trim() === e.slice(0, -1)));
451
+ if (missing.length === 0) return null;
452
+ const block = `${text.trimEnd()}
453
+
454
+ # Alexandria (conocimiento personal, no del repo)
455
+ ${missing.join("\n")}
456
+ `;
457
+ fs3.writeFileSync(file, text.trim() ? block : block.trimStart());
458
+ return file;
459
+ }
460
+ var CLAUDE_MD_START = "<!-- alexandria:start -->";
461
+ var CLAUDE_MD_END = "<!-- alexandria:end -->";
462
+ function configureClaudeMd(scope, projectDir) {
463
+ const file = scope === "project" ? path3.join(projectDir, "CLAUDE.md") : path3.join(os3.homedir(), ".claude", "CLAUDE.md");
464
+ const block = [
465
+ CLAUDE_MD_START,
466
+ "## Alexandria \u2014 b\xF3veda de conocimiento (uso por default)",
467
+ "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
468
+ "- Al descubrir arquitectura, decisiones o soluciones: gu\xE1rdalas con `vault_save` (usa `[[wikilinks]]` a notas relacionadas; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al inicio de cada sesi\xF3n).",
469
+ "- Usa `vault_related` para traer conocimiento conectado sin releer archivos.",
470
+ CLAUDE_MD_END
471
+ ].join("\n");
472
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
473
+ let text = "";
474
+ try {
475
+ text = fs3.readFileSync(file, "utf8");
476
+ } catch {
477
+ }
478
+ if (text.includes(CLAUDE_MD_START)) {
479
+ const re = new RegExp(`${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}`);
480
+ text = text.replace(re, block);
481
+ } else {
482
+ text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
483
+ }
484
+ fs3.writeFileSync(file, text);
485
+ return file;
486
+ }
487
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
488
+ function scanProject(vault, projectDir) {
489
+ const name = path3.basename(projectDir);
490
+ const mapFile = path3.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
491
+ if (fs3.existsSync(mapFile)) return null;
492
+ const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
493
+ try {
494
+ const pkg = JSON.parse(fs3.readFileSync(path3.join(projectDir, "package.json"), "utf8"));
495
+ const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
496
+ const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
497
+ parts.push(`## Stack
498
+ ${pkg.name ? `Paquete: ${pkg.name}` : ""}
499
+ - deps: ${deps.join(", ") || "\u2014"}
500
+ - dev: ${dev.join(", ") || "\u2014"}`);
501
+ const scripts = Object.entries(pkg.scripts ?? {}).slice(0, 12);
502
+ if (scripts.length) {
503
+ parts.push(`## Comandos
504
+ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
505
+ }
506
+ } catch {
507
+ }
508
+ const tree = [];
509
+ const walk = (dir, depth, prefix) => {
510
+ if (depth > 2 || tree.length > 60) return;
511
+ let entries = [];
512
+ try {
513
+ entries = fs3.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
514
+ } catch {
515
+ return;
516
+ }
517
+ for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
518
+ tree.push(`${prefix}${e.name}/`);
519
+ walk(path3.join(dir, e.name), depth + 1, prefix + " ");
520
+ }
521
+ };
522
+ walk(projectDir, 1, "");
523
+ if (tree.length) parts.push(`## Estructura
524
+ \`\`\`
525
+ ${tree.join("\n")}
526
+ \`\`\``);
527
+ try {
528
+ const readme = fs3.readFileSync(path3.join(projectDir, "README.md"), "utf8");
529
+ parts.push(`## README (extracto)
530
+ ${readme.split("\n").slice(0, 15).join("\n")}`);
531
+ } catch {
532
+ }
533
+ return upsertNote(vault.managed, {
534
+ fixedName: `mapa-${slugify(name)}`,
535
+ title: `Mapa - ${name}`,
536
+ type: "map",
537
+ tags: [name, "mapa"],
538
+ dir: "notes",
539
+ content: parts.join("\n\n")
540
+ });
541
+ }
542
+
601
543
  // src/cli.ts
602
544
  function registerAgentsMcp(agents, scope, cwd) {
603
545
  for (const agent of agents) {
@@ -653,14 +595,14 @@ async function ensureReady(vault = getVault()) {
653
595
  }
654
596
  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(
655
597
  "--path <dir>",
656
- "ruta del vault Obsidian (existente o nuevo). Default: ./KnowledgeVault con --project, ~/KnowledgeVault en global"
657
- ).option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
598
+ "ruta del vault Obsidian (existente o nuevo). Default: ./Alexandria con --project, ~/Alexandria en global"
599
+ ).option("--auto", "configurar el uso autom\xE1tico en CLAUDE.md sin preguntar").option("--manual", "no tocar CLAUDE.md (config\xFAralo t\xFA)").option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
658
600
  "--agents <ids>",
659
601
  `agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
660
602
  ).action(async (opts) => {
661
603
  const isProject = Boolean(opts.project) && !opts.global;
662
604
  const cwd = process.cwd();
663
- const vaultPath = path4.resolve(opts.path ?? (isProject ? path4.join(cwd, "KnowledgeVault") : defaultVaultPath()));
605
+ const vaultPath = path4.resolve(opts.path ?? (isProject ? path4.join(cwd, "Alexandria") : defaultVaultPath()));
664
606
  await showBanner();
665
607
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
666
608
  `));
@@ -685,6 +627,31 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
685
627
  if (skipped.length > 0) {
686
628
  console.log(pc.dim(` Otros agentes disponibles: ${skipped.map((a) => a.id).join(", ")} \u2192 ale agents <ids>`));
687
629
  }
630
+ if (isProject) {
631
+ const gi = ensureGitignore(cwd, vault.root);
632
+ if (gi) console.log(pc.green(`\u2713 B\xF3veda agregada a ${gi}`));
633
+ }
634
+ let auto = opts.auto ? true : opts.manual ? false : void 0;
635
+ if (auto === void 0) {
636
+ if (process.stdin.isTTY) {
637
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
638
+ const ans = (await rl.question(pc.bold("\xBFConfigurar a Claude para usar Alexandria autom\xE1ticamente (CLAUDE.md)? [S/n] "))).trim().toLowerCase();
639
+ rl.close();
640
+ auto = ans === "" || ans === "s" || ans === "si" || ans === "s\xED" || ans === "y";
641
+ } else {
642
+ auto = true;
643
+ }
644
+ }
645
+ if (auto) {
646
+ const file = configureClaudeMd(isProject ? "project" : "global", cwd);
647
+ console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${file}`));
648
+ } else {
649
+ console.log(pc.dim(" Sin auto-configuraci\xF3n (act\xEDvala luego con: ale init --auto)"));
650
+ }
651
+ if (isProject) {
652
+ const map = scanProject(vault, cwd);
653
+ if (map) console.log(pc.green(`\u2713 Proyecto escaneado \u2192 ${path4.relative(vault.root, map)} (mapa inicial)`));
654
+ }
688
655
  await downloadModelIfMissing();
689
656
  const idx = VaultIndex.load(vault);
690
657
  const res = await idx.refresh();
@@ -694,6 +661,37 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
694
661
  console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents\n'));
695
662
  if (opts.skills) await runSkills({ yes: false, project: isProject });
696
663
  });
664
+ program.command("consolidate").description("Archiva prompts viejos sin reuso: salen del grafo y de la inyecci\xF3n, pero NUNCA se pierden \u2014 siguen buscables (contexto infinito)").option("--days <n>", "antig\xFCedad m\xEDnima en d\xEDas", "45").option("--dry", "solo mostrar qu\xE9 se archivar\xEDa").action(async (opts) => {
665
+ const { vault, idx } = await ensureReady();
666
+ const cutoff = Date.now() - (parseInt(opts.days, 10) || 45) * 864e5;
667
+ const stale = Object.values(idx.meta.notes).filter(
668
+ (n) => n.type === "prompt" && (n.hits ?? 1) <= 1 && !n.rel.split("/").includes("archive") && n.created !== void 0 && Date.parse(n.created) < cutoff
669
+ );
670
+ if (stale.length === 0) {
671
+ console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
672
+ return;
673
+ }
674
+ const archiveDir = path4.join(vault.managed, "archive");
675
+ if (!opts.dry) fs4.mkdirSync(archiveDir, { recursive: true });
676
+ for (const n of stale) {
677
+ console.log(
678
+ `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
679
+ );
680
+ if (!opts.dry) {
681
+ fs4.renameSync(path4.join(vault.root, n.rel), path4.join(archiveDir, path4.basename(n.rel)));
682
+ }
683
+ }
684
+ if (!opts.dry) {
685
+ await VaultIndex.load(vault).refresh();
686
+ console.log(
687
+ pc.green(`
688
+ \u2713 ${stale.length} prompts archivados en ${path4.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
689
+ );
690
+ } else {
691
+ console.log(pc.dim(`
692
+ ${stale.length} candidatos. Corre sin --dry para archivarlos.`));
693
+ }
694
+ });
697
695
  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) => {
698
696
  if (!ids) {
699
697
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));