@ureck/alexandria 1.1.0 → 1.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/dist/cli.js CHANGED
@@ -4,7 +4,6 @@ import {
4
4
  } from "./chunk-XITAQVOZ.js";
5
5
  import {
6
6
  architectBlock,
7
- distDir,
8
7
  globalSettingsPath,
9
8
  hooksRegistered,
10
9
  mcpRegisteredProject,
@@ -15,12 +14,13 @@ import {
15
14
  registerHooks,
16
15
  registerMcpGlobal,
17
16
  registerMcpProject,
17
+ serverCommand,
18
18
  unregisterHooks
19
- } from "./chunk-T5VNBQEC.js";
19
+ } from "./chunk-ZIQYAQCF.js";
20
20
  import {
21
21
  hybridSearch,
22
22
  protocolChain
23
- } from "./chunk-AHBSZGSC.js";
23
+ } from "./chunk-UWB6RKVN.js";
24
24
  import {
25
25
  TOKEN_TOGGLES,
26
26
  defaultVaultPath,
@@ -34,18 +34,16 @@ import {
34
34
  vaultExists,
35
35
  writeGlobalConfig,
36
36
  writeProjectConfig
37
- } from "./chunk-TFQ7WSIB.js";
37
+ } from "./chunk-CIOCSIB5.js";
38
38
  import {
39
39
  serveGraph
40
- } from "./chunk-XY7U4CAQ.js";
41
- import {
42
- VaultIndex
43
- } from "./chunk-AXUEYSNZ.js";
40
+ } from "./chunk-FBGIFNIO.js";
44
41
  import {
42
+ VaultIndex,
45
43
  createNote,
46
44
  slugify,
47
45
  upsertNote
48
- } from "./chunk-XWR74BQ2.js";
46
+ } from "./chunk-QB37UGO6.js";
49
47
  import {
50
48
  MODEL_ID,
51
49
  dot,
@@ -55,8 +53,8 @@ import {
55
53
  } from "./chunk-EDYBSJSS.js";
56
54
 
57
55
  // src/cli.ts
58
- import fs5 from "fs";
59
- import path5 from "path";
56
+ import fs6 from "fs";
57
+ import path6 from "path";
60
58
  import readline from "readline/promises";
61
59
  import { Command } from "commander";
62
60
  import pc from "picocolors";
@@ -185,29 +183,182 @@ function installSkill(rec, targetDir) {
185
183
  }
186
184
  }
187
185
 
188
- // src/core/agents.ts
186
+ // src/skills/evolve.ts
189
187
  import fs2 from "fs";
190
188
  import os2 from "os";
191
189
  import path2 from "path";
190
+ var MAX_BODY_CHARS = 6e3;
191
+ var MAX_LESSONS = 12;
192
+ function skillTargetDir(projectDir, global) {
193
+ return global ? path2.join(os2.homedir(), ".claude", "skills") : path2.join(projectDir, ".claude", "skills");
194
+ }
195
+ function noteBody(vault, rel) {
196
+ try {
197
+ return fs2.readFileSync(path2.join(vault.root, rel), "utf8").replace(/^---[\s\S]*?---\n/, "").trim();
198
+ } catch {
199
+ return "";
200
+ }
201
+ }
202
+ function cleanScanNote(text) {
203
+ return text.replace(/^[^\n]*`ale scan`[^\n]*\n+/g, "").replace(/\n*Proyecto: \[\[[^\]]+\]\]\s*$/g, "").trim();
204
+ }
205
+ function buildSkill(vault, projectName) {
206
+ const idx = VaultIndex.load(vault);
207
+ const slug = slugify(projectName);
208
+ const byTitle = (prefix) => idx.notesByTag("map").find((n) => n.title.toLowerCase() === `${prefix} - ${projectName}`.toLowerCase());
209
+ const flujoNote = byTitle("Flujo");
210
+ const convNote = byTitle("Convenciones");
211
+ const mapaNote = byTitle("Mapa");
212
+ const apiNote = byTitle("API");
213
+ const todasLecciones = idx.notesByTag("lesson").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1));
214
+ const propias = todasLecciones.filter((n) => n.tags.includes(projectName) || n.rel.includes(slug));
215
+ const lecciones = (propias.length > 0 ? propias : todasLecciones).slice(0, MAX_LESSONS);
216
+ if (!flujoNote && !convNote && !mapaNote && lecciones.length === 0) return null;
217
+ const parts = [];
218
+ parts.push(`# ${projectName}
219
+ `);
220
+ parts.push(
221
+ `Conocimiento vivo de este proyecto, destilado por Alexandria desde su b\xF3veda. Refl\xE9jalo al trabajar aqu\xED: evita re-explorar lo que ya est\xE1 mapeado.
222
+ `
223
+ );
224
+ if (convNote) {
225
+ const t = cleanScanNote(noteBody(vault, convNote.rel));
226
+ if (t) parts.push(`## Stack y convenciones
227
+
228
+ ${t}
229
+ `);
230
+ }
231
+ if (flujoNote) {
232
+ const t = cleanScanNote(noteBody(vault, flujoNote.rel));
233
+ if (t) parts.push(`## Flujo de la aplicaci\xF3n
234
+
235
+ C\xF3mo recorre una petici\xF3n el sistema:
236
+
237
+ ${t}
238
+ `);
239
+ } else if (apiNote) {
240
+ const t = cleanScanNote(noteBody(vault, apiNote.rel));
241
+ if (t) parts.push(`## Superficie de API
242
+
243
+ ${t}
244
+ `);
245
+ }
246
+ if (lecciones.length) {
247
+ const items = lecciones.map((l) => {
248
+ const cuerpo = cleanScanNote(noteBody(vault, l.rel)).split("\n").filter(Boolean).slice(0, 2).join(" ");
249
+ const titulo = l.title.replace(/^Lección\s*-\s*/i, "");
250
+ return `- **${titulo}** \u2014 ${cuerpo.slice(0, 240)}`;
251
+ }).join("\n");
252
+ parts.push(`## Lecciones aprendidas aqu\xED
253
+
254
+ Errores ya pagados: no los repitas.
255
+
256
+ ${items}
257
+ `);
258
+ }
259
+ let body = parts.join("\n");
260
+ if (body.length > MAX_BODY_CHARS) body = body.slice(0, MAX_BODY_CHARS) + "\n\n\u2026(truncado)\n";
261
+ const skillName = `proyecto-${slug}`;
262
+ const desc = `Conocimiento vivo del proyecto ${projectName}: stack, convenciones, flujo de la aplicaci\xF3n y lecciones ya aprendidas. \xDAsala al trabajar en ${projectName} \u2014 antes de explorar el c\xF3digo o decidir arquitectura.`;
263
+ const front = [
264
+ "---",
265
+ `name: ${skillName}`,
266
+ `description: ${desc}`,
267
+ "metadata:",
268
+ " author: alexandria",
269
+ ` version: "${nextVersion(null)}"`,
270
+ ` generated: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`,
271
+ " source: ale skills evolve",
272
+ "---",
273
+ ""
274
+ ].join("\n");
275
+ const file = path2.join("SKILL.md");
276
+ return {
277
+ skillName,
278
+ file,
279
+ content: front + body.trimEnd() + "\n",
280
+ previous: null,
281
+ changed: true,
282
+ sources: {
283
+ flujo: Boolean(flujoNote),
284
+ convenciones: Boolean(convNote),
285
+ mapa: Boolean(mapaNote),
286
+ lecciones: lecciones.length
287
+ }
288
+ };
289
+ }
290
+ function nextVersion(previous) {
291
+ if (!previous) return "1.0.0";
292
+ const m = previous.match(/version:\s*["']?(\d+)\.(\d+)\.(\d+)/);
293
+ if (!m) return "1.0.0";
294
+ return `${m[1]}.${Number(m[2]) + 1}.0`;
295
+ }
296
+ function evolveSkill(vault, projectName, targetDir) {
297
+ const built = buildSkill(vault, projectName);
298
+ if (!built) return null;
299
+ const dir = path2.join(targetDir, built.skillName);
300
+ const file = path2.join(dir, "SKILL.md");
301
+ let previous = null;
302
+ try {
303
+ previous = fs2.readFileSync(file, "utf8");
304
+ } catch {
305
+ }
306
+ let content = built.content;
307
+ if (previous) {
308
+ content = content.replace(/(\n {2}version: ")[^"]+(")/, `$1${nextVersion(previous)}$2`);
309
+ }
310
+ const norm = (s) => s.replace(/^ {2}(?:version|generated):.*$/gm, "").trim();
311
+ return {
312
+ ...built,
313
+ file,
314
+ content,
315
+ previous,
316
+ changed: !previous || norm(previous) !== norm(content)
317
+ };
318
+ }
319
+ function writeSkill(result) {
320
+ fs2.mkdirSync(path2.dirname(result.file), { recursive: true });
321
+ fs2.writeFileSync(result.file, result.content);
322
+ }
323
+ function simpleDiff(previous, next) {
324
+ if (!previous) return next.split("\n").map((l) => `+ ${l}`);
325
+ const a = previous.split("\n");
326
+ const b = next.split("\n");
327
+ const setA = new Set(a);
328
+ const setB = new Set(b);
329
+ const out = [];
330
+ for (const l of a) if (!setB.has(l)) out.push(`- ${l}`);
331
+ for (const l of b) if (!setA.has(l)) out.push(`+ ${l}`);
332
+ return out;
333
+ }
334
+
335
+ // src/core/agents.ts
336
+ import fs3 from "fs";
337
+ import os3 from "os";
338
+ import path3 from "path";
192
339
  import { execFileSync as execFileSync2 } from "child_process";
193
- var serverScript = () => path2.join(distDir(), "mcp", "server.js");
340
+ var portableMode = false;
341
+ function setPortableMode(on) {
342
+ portableMode = on;
343
+ }
344
+ var serverCmd = () => serverCommand(portableMode);
194
345
  function readJsonSafe(file) {
195
346
  try {
196
- return JSON.parse(fs2.readFileSync(file, "utf8"));
347
+ return JSON.parse(fs3.readFileSync(file, "utf8"));
197
348
  } catch {
198
- if (fs2.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
349
+ if (fs3.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
199
350
  return {};
200
351
  }
201
352
  }
202
353
  function writeJson(file, data) {
203
- fs2.mkdirSync(path2.dirname(file), { recursive: true });
204
- fs2.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
354
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
355
+ fs3.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
205
356
  }
206
357
  function mergeMcpServers(file, key = "mcpServers") {
207
358
  try {
208
359
  const cfg = readJsonSafe(file);
209
360
  const servers = cfg[key] ?? {};
210
- servers["alexandria"] = { command: "node", args: [serverScript()] };
361
+ servers["alexandria"] = serverCmd();
211
362
  cfg[key] = servers;
212
363
  writeJson(file, cfg);
213
364
  return { ok: true, file };
@@ -216,21 +367,59 @@ function mergeMcpServers(file, key = "mcpServers") {
216
367
  }
217
368
  }
218
369
  function home(...p) {
219
- return path2.join(os2.homedir(), ...p);
370
+ return path3.join(os3.homedir(), ...p);
371
+ }
372
+ function replaceTomlTable(text, table, block) {
373
+ const lines = text.split("\n");
374
+ const isHeader = (l) => /^\s*\[/.test(l);
375
+ const belongsToTable = (l) => {
376
+ const m = l.match(/^\s*\[+\s*([^\]]+?)\s*\]+/);
377
+ if (!m) return false;
378
+ const name = m[1].trim();
379
+ return name === table || name.startsWith(`${table}.`);
380
+ };
381
+ const out = [];
382
+ let i = 0;
383
+ let replaced = false;
384
+ while (i < lines.length) {
385
+ if (belongsToTable(lines[i])) {
386
+ if (!replaced) {
387
+ out.push(...block.replace(/\n+$/, "").split("\n"));
388
+ replaced = true;
389
+ }
390
+ i++;
391
+ while (i < lines.length && !isHeader(lines[i])) i++;
392
+ continue;
393
+ }
394
+ out.push(lines[i]);
395
+ i++;
396
+ }
397
+ let result = out.join("\n");
398
+ if (!replaced) {
399
+ result = result.trimEnd() + (result.trim() ? "\n\n" : "") + block;
400
+ }
401
+ return result.replace(/\n{3,}/g, "\n\n");
220
402
  }
221
403
  function vscodeUserDir() {
222
404
  if (process.platform === "darwin") return home("Library", "Application Support", "Code", "User");
223
- if (process.platform === "win32") return path2.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
405
+ if (process.platform === "win32") return path3.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
224
406
  return home(".config", "Code", "User");
225
407
  }
408
+ function hasCopilotChatExtension() {
409
+ try {
410
+ return fs3.readdirSync(home(".vscode", "extensions")).some((d) => d.toLowerCase().startsWith("github.copilot-chat"));
411
+ } catch {
412
+ return false;
413
+ }
414
+ }
226
415
  var AGENTS = [
227
416
  {
228
417
  id: "claude",
229
418
  name: "Claude Code",
230
419
  supportsProject: true,
231
- detect: () => fs2.existsSync(home(".claude")),
420
+ detect: () => fs3.existsSync(home(".claude")),
232
421
  register(scope, projectDir) {
233
- if (scope === "project") return mergeMcpServers(path2.join(projectDir, ".mcp.json"));
422
+ if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
234
423
  return mergeMcpServers(home(".claude.json"));
235
424
  }
236
425
  },
@@ -238,9 +427,9 @@ var AGENTS = [
238
427
  id: "cursor",
239
428
  name: "Cursor",
240
429
  supportsProject: true,
241
- detect: () => fs2.existsSync(home(".cursor")),
430
+ detect: () => fs3.existsSync(home(".cursor")),
242
431
  register(scope, projectDir) {
243
- const file = scope === "project" ? path2.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
432
+ const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
244
433
  return mergeMcpServers(file);
245
434
  }
246
435
  },
@@ -248,14 +437,14 @@ var AGENTS = [
248
437
  id: "opencode",
249
438
  name: "OpenCode",
250
439
  supportsProject: true,
251
- detect: () => fs2.existsSync(home(".config", "opencode")) || fs2.existsSync(home(".opencode")),
440
+ detect: () => fs3.existsSync(home(".config", "opencode")) || fs3.existsSync(home(".opencode")),
252
441
  register(scope, projectDir) {
253
- const file = scope === "project" ? path2.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
442
+ const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
254
443
  try {
255
444
  const cfg = readJsonSafe(file);
256
445
  cfg["$schema"] ??= "https://opencode.ai/config.json";
257
446
  const mcp = cfg["mcp"] ?? {};
258
- mcp["alexandria"] = { type: "local", command: ["node", serverScript()], enabled: true };
447
+ mcp["alexandria"] = { type: "local", command: [serverCmd().command, ...serverCmd().args], enabled: true };
259
448
  cfg["mcp"] = mcp;
260
449
  writeJson(file, cfg);
261
450
  return { ok: true, file };
@@ -268,7 +457,7 @@ var AGENTS = [
268
457
  id: "windsurf",
269
458
  name: "Windsurf",
270
459
  supportsProject: false,
271
- detect: () => fs2.existsSync(home(".codeium", "windsurf")),
460
+ detect: () => fs3.existsSync(home(".codeium", "windsurf")),
272
461
  register() {
273
462
  return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
274
463
  }
@@ -277,9 +466,9 @@ var AGENTS = [
277
466
  id: "cline",
278
467
  name: "Cline (VS Code)",
279
468
  supportsProject: false,
280
- detect: () => fs2.existsSync(path2.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
469
+ detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
281
470
  register() {
282
- const file = path2.join(
471
+ const file = path3.join(
283
472
  vscodeUserDir(),
284
473
  "globalStorage",
285
474
  "saoudrizwan.claude-dev",
@@ -293,26 +482,24 @@ var AGENTS = [
293
482
  id: "codex",
294
483
  name: "Codex CLI (OpenAI)",
295
484
  supportsProject: false,
296
- detect: () => fs2.existsSync(home(".codex")),
485
+ detect: () => fs3.existsSync(home(".codex")),
297
486
  register() {
298
487
  const file = home(".codex", "config.toml");
488
+ const { command, args } = serverCmd();
489
+ const tomlArgs = args.map((a) => `"${a.replace(/\\/g, "\\\\")}"`).join(", ");
299
490
  const block = `[mcp_servers.alexandria]
300
- command = "node"
301
- args = ["${serverScript().replace(/\\/g, "\\\\")}"]
491
+ command = "${command}"
492
+ args = [${tomlArgs}]
302
493
  `;
303
494
  try {
304
495
  let text = "";
305
496
  try {
306
- text = fs2.readFileSync(file, "utf8");
497
+ text = fs3.readFileSync(file, "utf8");
307
498
  } catch {
308
499
  }
309
- if (/^\[mcp_servers\.alexandria\]/m.test(text)) {
310
- text = text.replace(/\[mcp_servers\.alexandria\][^[]*/m, block);
311
- } else {
312
- text = text.trimEnd() + (text.trim() ? "\n\n" : "") + block;
313
- }
314
- fs2.mkdirSync(path2.dirname(file), { recursive: true });
315
- fs2.writeFileSync(file, text);
500
+ text = replaceTomlTable(text, "mcp_servers.alexandria", block);
501
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
502
+ fs3.writeFileSync(file, text);
316
503
  return { ok: true, file };
317
504
  } catch (e) {
318
505
  return { ok: false, file, detail: e.message };
@@ -323,9 +510,9 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
323
510
  id: "gemini",
324
511
  name: "Gemini CLI",
325
512
  supportsProject: true,
326
- detect: () => fs2.existsSync(home(".gemini")),
513
+ detect: () => fs3.existsSync(home(".gemini")),
327
514
  register(scope, projectDir) {
328
- const file = scope === "project" ? path2.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
515
+ const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
329
516
  return mergeMcpServers(file);
330
517
  }
331
518
  },
@@ -333,13 +520,13 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
333
520
  id: "openclaw",
334
521
  name: "OpenClaw",
335
522
  supportsProject: false,
336
- detect: () => fs2.existsSync(home(".openclaw")),
523
+ detect: () => fs3.existsSync(home(".openclaw")),
337
524
  register() {
338
525
  const file = home(".openclaw", "openclaw.json");
339
526
  try {
340
527
  const cfg = readJsonSafe(file);
341
528
  const servers = cfg["mcpServers"] ?? {};
342
- servers["alexandria"] = { command: "node", args: [serverScript()], transport: "stdio" };
529
+ servers["alexandria"] = { ...serverCmd(), transport: "stdio" };
343
530
  cfg["mcpServers"] = servers;
344
531
  writeJson(file, cfg);
345
532
  return { ok: true, file, detail: "reinicia el gateway de OpenClaw para que lo tome" };
@@ -352,11 +539,11 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
352
539
  id: "hermes",
353
540
  name: "Hermes Agent (Nous)",
354
541
  supportsProject: false,
355
- detect: () => fs2.existsSync(home(".hermes")),
542
+ detect: () => fs3.existsSync(home(".hermes")),
356
543
  register() {
357
544
  const file = home(".hermes", "config.yaml");
358
545
  try {
359
- execFileSync2("hermes", ["mcp", "add", "alexandria", "--command", "node", "--args", serverScript()], {
546
+ execFileSync2("hermes", ["mcp", "add", "alexandria", "--command", serverCmd().command, "--args", serverCmd().args.join(" ")], {
360
547
  stdio: "pipe",
361
548
  timeout: 15e3
362
549
  });
@@ -366,15 +553,16 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
366
553
  try {
367
554
  let text = "";
368
555
  try {
369
- text = fs2.readFileSync(file, "utf8");
556
+ text = fs3.readFileSync(file, "utf8");
370
557
  } catch {
371
558
  }
372
559
  if (/^\s*alexandria:/m.test(text)) return { ok: true, file, detail: "ya registrado" };
560
+ const hc = serverCmd();
373
561
  const entry = ` alexandria:
374
562
  type: stdio
375
- command: node
563
+ command: ${hc.command}
376
564
  args:
377
- - "${serverScript()}"
565
+ ${hc.args.map((a) => ` - "${a}"`).join("\n")}
378
566
  `;
379
567
  if (/^mcp_servers:\s*$/m.test(text)) {
380
568
  text = text.replace(/^mcp_servers:\s*$/m, (m) => `${m}
@@ -384,8 +572,8 @@ ${entry.trimEnd()}`);
384
572
  } else {
385
573
  text = text.trimEnd() + (text.trim() ? "\n\n" : "") + "mcp_servers:\n" + entry;
386
574
  }
387
- fs2.mkdirSync(path2.dirname(file), { recursive: true });
388
- fs2.writeFileSync(file, text);
575
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
576
+ fs3.writeFileSync(file, text);
389
577
  return { ok: true, file };
390
578
  } catch (e) {
391
579
  return { ok: false, file, detail: e.message };
@@ -396,13 +584,16 @@ ${entry.trimEnd()}`);
396
584
  id: "vscode",
397
585
  name: "VS Code (Copilot)",
398
586
  supportsProject: true,
399
- detect: () => fs2.existsSync(vscodeUserDir()),
587
+ // Señal REAL de soporte MCP: un mcp.json existente o la extensión de Copilot
588
+ // Chat instalada. Antes bastaba con que existiera el User dir, así que
589
+ // cualquiera con VS Code aparecía como agente detectado aunque no use MCP.
590
+ detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "mcp.json")) || hasCopilotChatExtension(),
400
591
  register(scope, projectDir) {
401
- const file = scope === "project" ? path2.join(projectDir, ".vscode", "mcp.json") : path2.join(vscodeUserDir(), "mcp.json");
592
+ const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
402
593
  try {
403
594
  const cfg = readJsonSafe(file);
404
595
  const servers = cfg["servers"] ?? {};
405
- servers["alexandria"] = { type: "stdio", command: "node", args: [serverScript()] };
596
+ servers["alexandria"] = { type: "stdio", ...serverCmd() };
406
597
  cfg["servers"] = servers;
407
598
  writeJson(file, cfg);
408
599
  return { ok: true, file };
@@ -483,9 +674,9 @@ async function showBanner(animate) {
483
674
  }
484
675
 
485
676
  // src/core/setup.ts
486
- import fs3 from "fs";
487
- import os3 from "os";
488
- import path3 from "path";
677
+ import fs4 from "fs";
678
+ import os4 from "os";
679
+ import path4 from "path";
489
680
  import { execFileSync as execFileSync3 } from "child_process";
490
681
  var PERSONAL_CONFIG_FILES = [
491
682
  ".vault.json",
@@ -496,15 +687,15 @@ var PERSONAL_CONFIG_FILES = [
496
687
  ".gemini/settings.json"
497
688
  ];
498
689
  function ensureGitignore(projectDir, vaultRoot) {
499
- if (!fs3.existsSync(path3.join(projectDir, ".git"))) return null;
690
+ if (!fs4.existsSync(path4.join(projectDir, ".git"))) return null;
500
691
  const entries = [];
501
- const rel = path3.relative(projectDir, vaultRoot);
502
- if (!rel.startsWith("..")) entries.push(`${rel.split(path3.sep).join("/")}/`);
692
+ const rel = path4.relative(projectDir, vaultRoot);
693
+ if (!rel.startsWith("..")) entries.push(`${rel.split(path4.sep).join("/")}/`);
503
694
  entries.push(...PERSONAL_CONFIG_FILES);
504
- const file = path3.join(projectDir, ".gitignore");
695
+ const file = path4.join(projectDir, ".gitignore");
505
696
  let text = "";
506
697
  try {
507
- text = fs3.readFileSync(file, "utf8");
698
+ text = fs4.readFileSync(file, "utf8");
508
699
  } catch {
509
700
  }
510
701
  const has = (e) => text.split("\n").some((l) => l.trim() === e || l.trim() === e.replace(/\/$/, ""));
@@ -515,14 +706,14 @@ function ensureGitignore(projectDir, vaultRoot) {
515
706
  # Alexandria (conocimiento y config personal \u2014 no del repo)
516
707
  ${missing.join("\n")}
517
708
  `;
518
- fs3.writeFileSync(file, text.trim() ? block : block.trimStart());
709
+ fs4.writeFileSync(file, text.trim() ? block : block.trimStart());
519
710
  return file;
520
711
  }
521
712
  function untrackPersonalConfigs(projectDir) {
522
- if (!fs3.existsSync(path3.join(projectDir, ".git"))) return [];
713
+ if (!fs4.existsSync(path4.join(projectDir, ".git"))) return [];
523
714
  const untracked = [];
524
715
  for (const f of PERSONAL_CONFIG_FILES) {
525
- if (!fs3.existsSync(path3.join(projectDir, f))) continue;
716
+ if (!fs4.existsSync(path4.join(projectDir, f))) continue;
526
717
  try {
527
718
  const tracked = execFileSync3("git", ["ls-files", "--error-unmatch", f], {
528
719
  cwd: projectDir,
@@ -540,7 +731,7 @@ function untrackPersonalConfigs(projectDir) {
540
731
  var CLAUDE_MD_START = "<!-- alexandria:start -->";
541
732
  var CLAUDE_MD_END = "<!-- alexandria:end -->";
542
733
  function configureClaudeMd(scope, projectDir) {
543
- const file = scope === "project" ? path3.join(projectDir, "CLAUDE.md") : path3.join(os3.homedir(), ".claude", "CLAUDE.md");
734
+ const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
544
735
  const block = [
545
736
  CLAUDE_MD_START,
546
737
  "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
@@ -552,10 +743,10 @@ function configureClaudeMd(scope, projectDir) {
552
743
  "- `vault_related` trae conocimiento conectado sin releer archivos.",
553
744
  CLAUDE_MD_END
554
745
  ].join("\n");
555
- fs3.mkdirSync(path3.dirname(file), { recursive: true });
746
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
556
747
  let text = "";
557
748
  try {
558
- text = fs3.readFileSync(file, "utf8");
749
+ text = fs4.readFileSync(file, "utf8");
559
750
  } catch {
560
751
  }
561
752
  if (text.includes(CLAUDE_MD_START)) {
@@ -564,14 +755,14 @@ function configureClaudeMd(scope, projectDir) {
564
755
  } else {
565
756
  text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
566
757
  }
567
- fs3.writeFileSync(file, text);
758
+ fs4.writeFileSync(file, text);
568
759
  return file;
569
760
  }
570
761
  function removeClaudeMd(scope, projectDir) {
571
- const file = scope === "project" ? path3.join(projectDir, "CLAUDE.md") : path3.join(os3.homedir(), ".claude", "CLAUDE.md");
762
+ const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
572
763
  let text;
573
764
  try {
574
- text = fs3.readFileSync(file, "utf8");
765
+ text = fs4.readFileSync(file, "utf8");
575
766
  } catch {
576
767
  return null;
577
768
  }
@@ -579,20 +770,20 @@ function removeClaudeMd(scope, projectDir) {
579
770
  const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
580
771
  const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
581
772
  if (cleaned === "") {
582
- fs3.rmSync(file, { force: true });
773
+ fs4.rmSync(file, { force: true });
583
774
  } else {
584
- fs3.writeFileSync(file, cleaned + "\n");
775
+ fs4.writeFileSync(file, cleaned + "\n");
585
776
  }
586
777
  return file;
587
778
  }
588
779
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
589
780
  function scanProject(vault, projectDir) {
590
- const name = path3.basename(projectDir);
591
- const mapFile = path3.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
592
- if (fs3.existsSync(mapFile)) return null;
781
+ const name = path4.basename(projectDir);
782
+ const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
783
+ if (fs4.existsSync(mapFile)) return null;
593
784
  const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
594
785
  try {
595
- const pkg = JSON.parse(fs3.readFileSync(path3.join(projectDir, "package.json"), "utf8"));
786
+ const pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
596
787
  const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
597
788
  const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
598
789
  parts.push(`## Stack
@@ -611,13 +802,13 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
611
802
  if (depth > 2 || tree.length > 60) return;
612
803
  let entries = [];
613
804
  try {
614
- entries = fs3.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
805
+ entries = fs4.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
615
806
  } catch {
616
807
  return;
617
808
  }
618
809
  for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
619
810
  tree.push(`${prefix}${e.name}/`);
620
- walk(path3.join(dir, e.name), depth + 1, prefix + " ");
811
+ walk(path4.join(dir, e.name), depth + 1, prefix + " ");
621
812
  }
622
813
  };
623
814
  walk(projectDir, 1, "");
@@ -626,7 +817,7 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
626
817
  ${tree.join("\n")}
627
818
  \`\`\``);
628
819
  try {
629
- const readme = fs3.readFileSync(path3.join(projectDir, "README.md"), "utf8");
820
+ const readme = fs4.readFileSync(path4.join(projectDir, "README.md"), "utf8");
630
821
  parts.push(`## README (extracto)
631
822
  ${readme.split("\n").slice(0, 15).join("\n")}`);
632
823
  } catch {
@@ -642,8 +833,8 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
642
833
  }
643
834
 
644
835
  // src/core/scan.ts
645
- import fs4 from "fs";
646
- import path4 from "path";
836
+ import fs5 from "fs";
837
+ import path5 from "path";
647
838
  var SKIP_DIRS2 = /* @__PURE__ */ new Set([
648
839
  "node_modules",
649
840
  ".git",
@@ -688,15 +879,15 @@ function collectSourceFiles(projectDir) {
688
879
  for (const dir of level) {
689
880
  let entries = [];
690
881
  try {
691
- entries = fs4.readdirSync(dir, { withFileTypes: true });
882
+ entries = fs5.readdirSync(dir, { withFileTypes: true });
692
883
  } catch {
693
884
  continue;
694
885
  }
695
886
  for (const e of entries) {
696
887
  if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
697
- const full = path4.join(dir, e.name);
888
+ const full = path5.join(dir, e.name);
698
889
  if (e.isDirectory()) next.push(full);
699
- else if (e.isFile() && SOURCE_EXT.has(path4.extname(e.name))) {
890
+ else if (e.isFile() && SOURCE_EXT.has(path5.extname(e.name))) {
700
891
  candidates.push(full);
701
892
  if (candidates.length >= TRAVERSE_SAFETY) break;
702
893
  }
@@ -709,7 +900,7 @@ function collectSourceFiles(projectDir) {
709
900
  if (candidates.length > MAX_FILES) {
710
901
  const groups = /* @__PURE__ */ new Map();
711
902
  for (const c of candidates) {
712
- const key = path4.relative(projectDir, c).split(path4.sep)[0];
903
+ const key = path5.relative(projectDir, c).split(path5.sep)[0];
713
904
  const g = groups.get(key);
714
905
  if (g) g.push(c);
715
906
  else groups.set(key, [c]);
@@ -731,10 +922,10 @@ function collectSourceFiles(projectDir) {
731
922
  const out = [];
732
923
  for (const full of chosen) {
733
924
  try {
734
- if (fs4.statSync(full).size > MAX_FILE_BYTES) continue;
925
+ if (fs5.statSync(full).size > MAX_FILE_BYTES) continue;
735
926
  out.push({
736
- rel: path4.relative(projectDir, full).split(path4.sep).join("/"),
737
- content: fs4.readFileSync(full, "utf8")
927
+ rel: path5.relative(projectDir, full).split(path5.sep).join("/"),
928
+ content: fs5.readFileSync(full, "utf8")
738
929
  });
739
930
  } catch {
740
931
  }
@@ -778,12 +969,61 @@ function scanApi(files) {
778
969
  }
779
970
  return lines;
780
971
  }
972
+ function scanFlow(files) {
973
+ const lines = [];
974
+ for (const f of files) {
975
+ if (!/(^|\/)(middleware|proxy)\.[tj]sx?$/.test(f.rel)) continue;
976
+ const matcher = f.content.match(/matcher:\s*\[([^\]]+)\]/)?.[1] ?? f.content.match(/matcher:\s*['"`]([^'"`]+)/)?.[1];
977
+ const rutas = matcher ? matcher.replace(/['"`\s]/g, " ").trim().split(/\s+/).slice(0, 6).join(", ") : "todas las rutas";
978
+ const auth = /auth|session|token|jwt|cookie/i.test(f.content) ? " (verifica sesi\xF3n)" : "";
979
+ lines.push(`- middleware protege: ${rutas}${auth} \u2014 ${f.rel}`);
980
+ }
981
+ for (const f of files) {
982
+ if (lines.length >= RAW_SAFETY) break;
983
+ const body = f.content.replace(/^\s*import[\s\S]*?from\s+['"][^'"]+['"];?\s*$/gm, "");
984
+ const isRoute = /(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel);
985
+ const isPagesApi = /(?:^|\/)pages\/api\//.test(f.rel);
986
+ const isAction = /^\s*['"]use server['"]/m.test(f.content.slice(0, 400));
987
+ if (!isRoute && !isPagesApi && !isAction) continue;
988
+ const parts = [];
989
+ if (isRoute) {
990
+ const methods = HTTP_METHODS.filter(
991
+ (m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
992
+ );
993
+ parts.push(`${methods.join("/") || "handler"} ${appRoutePath(f.rel)}`);
994
+ } else if (isPagesApi) {
995
+ parts.push(`handler /api/${f.rel.replace(/.*pages\/api\//, "").replace(/\.[tj]sx?$/, "")}`);
996
+ } else {
997
+ const fns = [...f.content.matchAll(/export\s+(?:async\s+)?function\s+(\w+)/g)].map((m) => m[1]);
998
+ parts.push(`action ${fns.slice(0, 3).join("/") || "(an\xF3nima)"}`);
999
+ }
1000
+ const authCall = body.match(
1001
+ /\b(require(?:Auth|User|Permiso|Permission|Role|Session)\w*|getServerSession|getSession|currentUser|verifyToken|getToken|auth)\s*\(\s*(["'`]([^"'`]+)["'`])?/
1002
+ );
1003
+ if (authCall) {
1004
+ parts.push(authCall[3] ? `auth: ${authCall[1]}(${authCall[3]})` : `auth: ${authCall[1]}`);
1005
+ }
1006
+ const datos = /* @__PURE__ */ new Set();
1007
+ for (const m of body.matchAll(/\bprisma\.(\w+)\.(\w+)/g)) datos.add(`${m[1]}.${m[2]}`);
1008
+ if (/\bdb\s*\.\s*(?:select|insert|update|delete)\s*\(/.test(body)) datos.add("drizzle");
1009
+ for (const m of body.matchAll(/\b(?:FROM|INTO|UPDATE|JOIN)\s+["'`]?(\w{3,})["'`]?/g)) datos.add(m[1].toLowerCase());
1010
+ for (const imp of f.content.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"][^'"]*(?:queries|db|repository|dal|models?)['"]/g)) {
1011
+ for (const fn of imp[1].split(",").map((x) => x.trim().split(/\s+as\s+/)[0]).filter(Boolean)) datos.add(fn);
1012
+ }
1013
+ if (datos.size) parts.push(`datos: ${[...datos].slice(0, 4).join(", ")}${datos.size > 4 ? "\u2026" : ""}`);
1014
+ if (/\b(?:auditar|audit|logEvent)\s*\(/.test(body)) parts.push("audita");
1015
+ if (/\b(?:fetch|axios)\s*\(/.test(body)) parts.push("llama API externa");
1016
+ if (/\b(?:revalidatePath|revalidateTag|updateTag)\s*\(/.test(body)) parts.push("revalida cach\xE9");
1017
+ lines.push(`- ${parts.join(" \u2192 ")} \u2014 ${f.rel}`);
1018
+ }
1019
+ return lines;
1020
+ }
781
1021
  function scanEnvNames(projectDir) {
782
1022
  const seen = /* @__PURE__ */ new Map();
783
1023
  for (const file of [".env.example", ".env", ".env.local"]) {
784
1024
  let text;
785
1025
  try {
786
- text = fs4.readFileSync(path4.join(projectDir, file), "utf8");
1026
+ text = fs5.readFileSync(path5.join(projectDir, file), "utf8");
787
1027
  } catch {
788
1028
  continue;
789
1029
  }
@@ -797,7 +1037,7 @@ function scanEnvNames(projectDir) {
797
1037
  function scanDataSchema(projectDir, files) {
798
1038
  const lines = [];
799
1039
  try {
800
- const schema = fs4.readFileSync(path4.join(projectDir, "prisma", "schema.prisma"), "utf8");
1040
+ const schema = fs5.readFileSync(path5.join(projectDir, "prisma", "schema.prisma"), "utf8");
801
1041
  for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
802
1042
  const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
803
1043
  const shown = fields.slice(0, 8).join(", ");
@@ -814,14 +1054,14 @@ function scanDataSchema(projectDir, files) {
814
1054
  for (const dir of migDirs) {
815
1055
  let sqlFiles = [];
816
1056
  try {
817
- sqlFiles = fs4.readdirSync(path4.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
1057
+ sqlFiles = fs5.readdirSync(path5.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
818
1058
  } catch {
819
1059
  continue;
820
1060
  }
821
1061
  const tables = /* @__PURE__ */ new Set();
822
1062
  for (const f of sqlFiles) {
823
1063
  try {
824
- const sql = fs4.readFileSync(path4.join(projectDir, dir, f), "utf8");
1064
+ const sql = fs5.readFileSync(path5.join(projectDir, dir, f), "utf8");
825
1065
  for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
826
1066
  } catch {
827
1067
  }
@@ -832,17 +1072,17 @@ function scanDataSchema(projectDir, files) {
832
1072
  }
833
1073
  function scanConventions(projectDir) {
834
1074
  const lines = [];
835
- const has = (f) => fs4.existsSync(path4.join(projectDir, f));
1075
+ const has = (f) => fs5.existsSync(path5.join(projectDir, f));
836
1076
  const pm = has("bun.lockb") || has("bun.lock") ? "bun" : has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("package-lock.json") ? "npm" : null;
837
1077
  if (pm) lines.push(`- gestor de paquetes: ${pm}`);
838
1078
  let pkg = {};
839
1079
  try {
840
- pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
1080
+ pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
841
1081
  } catch {
842
1082
  }
843
1083
  if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
844
1084
  try {
845
- const ts = JSON.parse(fs4.readFileSync(path4.join(projectDir, "tsconfig.json"), "utf8"));
1085
+ const ts = JSON.parse(fs5.readFileSync(path5.join(projectDir, "tsconfig.json"), "utf8"));
846
1086
  const co = ts.compilerOptions ?? {};
847
1087
  lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
848
1088
  const paths = Object.keys(co.paths ?? {}).slice(0, 5);
@@ -864,18 +1104,18 @@ function scanConventions(projectDir) {
864
1104
  }
865
1105
  function linkMapToScans(vault, name, titles) {
866
1106
  if (titles.length === 0) return;
867
- const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1107
+ const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
868
1108
  try {
869
- const text = fs4.readFileSync(mapFile, "utf8");
1109
+ const text = fs5.readFileSync(mapFile, "utf8");
870
1110
  if (text.includes("Contexto ampliado:")) return;
871
- fs4.appendFileSync(mapFile, `
1111
+ fs5.appendFileSync(mapFile, `
872
1112
  Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
873
1113
  `);
874
1114
  } catch {
875
1115
  }
876
1116
  }
877
1117
  function scanAll(vault, projectDir) {
878
- const name = path4.basename(projectDir);
1118
+ const name = path5.basename(projectDir);
879
1119
  const gitignored = ensureGitignore(projectDir, vault.root) !== null;
880
1120
  try {
881
1121
  untrackPersonalConfigs(projectDir);
@@ -901,6 +1141,7 @@ function scanAll(vault, projectDir) {
901
1141
  const env = run(() => scanEnvNames(projectDir));
902
1142
  const data = run(() => scanDataSchema(projectDir, files));
903
1143
  const conventions = run(() => scanConventions(projectDir));
1144
+ const flow = run(() => scanFlow(files));
904
1145
  const notes = [];
905
1146
  const titles = [];
906
1147
  const truncated = [];
@@ -929,12 +1170,28 @@ Proyecto: [[Mapa - ${name}]]`
929
1170
  write("env", `Env - ${name}`, `Variables de entorno (SOLO nombres \u2014 los valores nunca se guardan).`, env);
930
1171
  write("datos", `Datos - ${name}`, `Esquema de datos detectado en archivos (sin conexi\xF3n a BD).`, data);
931
1172
  write("convenciones", `Convenciones - ${name}`, `Convenciones detectadas por \`ale scan\`.`, conventions);
1173
+ write(
1174
+ "flujo",
1175
+ `Flujo - ${name}`,
1176
+ `Flujo de la app: qu\xE9 recorre una petici\xF3n (entrada \u2192 auth \u2192 datos). Detectado por \`ale scan\`.`,
1177
+ flow
1178
+ );
932
1179
  linkMapToScans(vault, name, titles);
933
- return { api: api.length, env: env.length, data: data.length, conventions: conventions.length, notes, gitignored, truncated };
1180
+ return {
1181
+ api: api.length,
1182
+ env: env.length,
1183
+ data: data.length,
1184
+ conventions: conventions.length,
1185
+ flow: flow.length,
1186
+ notes,
1187
+ gitignored,
1188
+ truncated
1189
+ };
934
1190
  }
935
1191
 
936
1192
  // src/cli.ts
937
1193
  function registerAgentsMcp(agents, scope, cwd, portable = false) {
1194
+ setPortableMode(portable);
938
1195
  for (const agent of agents) {
939
1196
  if (agent.id === "claude") {
940
1197
  if (scope === "project") {
@@ -995,7 +1252,7 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
995
1252
  ).action(async (opts) => {
996
1253
  const isProject = Boolean(opts.project) && !opts.global;
997
1254
  const cwd = process.cwd();
998
- const vaultPath = path5.resolve(opts.path ?? (isProject ? path5.join(cwd, "Alexandria") : defaultVaultPath()));
1255
+ const vaultPath = path6.resolve(opts.path ?? (isProject ? path6.join(cwd, "Alexandria") : defaultVaultPath()));
999
1256
  await showBanner();
1000
1257
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
1001
1258
  `));
@@ -1067,7 +1324,7 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1067
1324
  }
1068
1325
  if (isProject) {
1069
1326
  const s = scanAll(vault, cwd);
1070
- console.log(pc.green(`\u2713 Proyecto escaneado \u2192 API: ${s.api} \xB7 Env: ${s.env} \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions} (re-ejecuta con: ale scan)`));
1327
+ console.log(pc.green(`\u2713 Proyecto escaneado \u2192 API: ${s.api} \xB7 Env: ${s.env} \xB7 Datos: ${s.data} \xB7 Flujo: ${s.flow} \xB7 Convenciones: ${s.conventions} (re-ejecuta con: ale scan)`));
1071
1328
  }
1072
1329
  await downloadModelIfMissing();
1073
1330
  const idx = VaultIndex.load(vault);
@@ -1081,10 +1338,10 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1081
1338
  });
1082
1339
  program.command("plan").description("Crear un plan del Protocolo desde un archivo .md/.txt (en vez de escribirlo en la terminal)").argument("<file>", 'archivo con el plan (los checkboxes "- [ ]" se toman como Definition of Done)').option("--title <t>", "t\xEDtulo del plan (default: nombre del archivo o primer heading)").action(async (file, opts) => {
1083
1340
  const { vault } = await ensureReady();
1084
- const abs = path5.resolve(file);
1085
- const raw = fs5.readFileSync(abs, "utf8");
1341
+ const abs = path6.resolve(file);
1342
+ const raw = fs6.readFileSync(abs, "utf8");
1086
1343
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
1087
- const title = opts.title ?? heading ?? path5.basename(abs).replace(/\.(md|txt)$/i, "");
1344
+ const title = opts.title ?? heading ?? path6.basename(abs).replace(/\.(md|txt)$/i, "");
1088
1345
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
1089
1346
  const noteFile = createNote(vault.managed, {
1090
1347
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
@@ -1094,7 +1351,7 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
1094
1351
  content: raw.trim()
1095
1352
  });
1096
1353
  await VaultIndex.load(vault).refresh();
1097
- console.log(pc.green(`\u2713 Plan creado: ${path5.relative(vault.root, noteFile)}`));
1354
+ console.log(pc.green(`\u2713 Plan creado: ${path6.relative(vault.root, noteFile)}`));
1098
1355
  console.log(pc.dim(` DoD detectada: ${dod.length} criterios${dod.length ? " \u2014 " + dod.slice(0, 3).join(" \xB7 ") + (dod.length > 3 ? " \u2026" : "") : ' (agrega checkboxes "- [ ]" para criterios verificables)'}`));
1099
1356
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1100
1357
  const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
@@ -1166,21 +1423,21 @@ program.command("consolidate").description("Archiva prompts viejos sin reuso: sa
1166
1423
  console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
1167
1424
  return;
1168
1425
  }
1169
- const archiveDir = path5.join(vault.managed, "archive");
1170
- if (!opts.dry) fs5.mkdirSync(archiveDir, { recursive: true });
1426
+ const archiveDir = path6.join(vault.managed, "archive");
1427
+ if (!opts.dry) fs6.mkdirSync(archiveDir, { recursive: true });
1171
1428
  for (const n of stale) {
1172
1429
  console.log(
1173
1430
  `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
1174
1431
  );
1175
1432
  if (!opts.dry) {
1176
- fs5.renameSync(path5.join(vault.root, n.rel), path5.join(archiveDir, path5.basename(n.rel)));
1433
+ fs6.renameSync(path6.join(vault.root, n.rel), path6.join(archiveDir, path6.basename(n.rel)));
1177
1434
  }
1178
1435
  }
1179
1436
  if (!opts.dry) {
1180
1437
  await VaultIndex.load(vault).refresh();
1181
1438
  console.log(
1182
1439
  pc.green(`
1183
- \u2713 ${stale.length} prompts archivados en ${path5.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1440
+ \u2713 ${stale.length} prompts archivados en ${path6.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1184
1441
  );
1185
1442
  } else {
1186
1443
  console.log(pc.dim(`
@@ -1211,10 +1468,10 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
1211
1468
  const { vault } = await ensureReady();
1212
1469
  let content = opts.content;
1213
1470
  if (!content && opts.file) {
1214
- content = fs5.readFileSync(path5.resolve(opts.file), "utf8");
1471
+ content = fs6.readFileSync(path6.resolve(opts.file), "utf8");
1215
1472
  }
1216
1473
  if (!content && !process.stdin.isTTY) {
1217
- content = fs5.readFileSync(0, "utf8");
1474
+ content = fs6.readFileSync(0, "utf8");
1218
1475
  }
1219
1476
  const file = createNote(vault.managed, {
1220
1477
  title,
@@ -1222,7 +1479,7 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
1222
1479
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
1223
1480
  });
1224
1481
  await VaultIndex.load(vault).refresh();
1225
- console.log(pc.green(`\u2713 ${path5.relative(vault.root, file)}`));
1482
+ console.log(pc.green(`\u2713 ${path6.relative(vault.root, file)}`));
1226
1483
  });
1227
1484
  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) => {
1228
1485
  const vault = getVault();
@@ -1311,12 +1568,12 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1311
1568
  const idx = VaultIndex.load(vault);
1312
1569
  await idx.refresh().catch(() => {
1313
1570
  });
1314
- console.log(pc.green(`\u2713 API: ${s.api} rutas \xB7 Env: ${s.env} vars (solo nombres) \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions}${s.gitignored ? " \xB7 .gitignore \u2713" : ""}`));
1571
+ console.log(pc.green(`\u2713 API: ${s.api} rutas \xB7 Env: ${s.env} vars (solo nombres) \xB7 Datos: ${s.data} \xB7 Flujo: ${s.flow} \xB7 Convenciones: ${s.conventions}${s.gitignored ? " \xB7 .gitignore \u2713" : ""}`));
1315
1572
  if (s.truncated.length) {
1316
1573
  console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
1317
1574
  }
1318
1575
  if (s.notes.length) {
1319
- for (const n of s.notes) console.log(pc.dim(` ${path5.relative(vault.root, n)}`));
1576
+ for (const n of s.notes) console.log(pc.dim(` ${path6.relative(vault.root, n)}`));
1320
1577
  } else {
1321
1578
  console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1322
1579
  }
@@ -1377,7 +1634,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1377
1634
  async function runSkills(opts) {
1378
1635
  const { vault } = await ensureReady();
1379
1636
  const cwd = process.cwd();
1380
- const targetDir = opts.project ? path5.join(cwd, ".claude", "skills") : path5.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1637
+ const targetDir = opts.project ? path6.join(cwd, ".claude", "skills") : path6.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1381
1638
  const recs = await recommendSkills(vault, [targetDir]);
1382
1639
  if (recs.length === 0) {
1383
1640
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -1416,6 +1673,54 @@ async function runSkills(opts) {
1416
1673
  }
1417
1674
  }
1418
1675
  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);
1676
+ program.command("skills:evolve").alias("evolve").description("Genera/actualiza una skill VIVA del proyecto con lo que la b\xF3veda sabe (flujo, convenciones, lecciones). Muestra el diff y pide aprobaci\xF3n").option("-y, --yes", "escribir sin preguntar (para scripts)").option("--global", "guardar en ~/.claude/skills en vez de .claude/skills del proyecto").action(async (opts) => {
1677
+ const { vault } = await ensureReady();
1678
+ const cwd = process.cwd();
1679
+ const proj = path6.basename(cwd);
1680
+ const targetDir = skillTargetDir(cwd, Boolean(opts.global));
1681
+ const result = evolveSkill(vault, proj, targetDir);
1682
+ if (!result) {
1683
+ console.log(pc.yellow(`Sin material todav\xEDa para \xAB${proj}\xBB.`));
1684
+ console.log(pc.dim(" Corre `ale scan` (flujo/convenciones) y acumula lecciones con el Protocolo; luego repite."));
1685
+ return;
1686
+ }
1687
+ const s = result.sources;
1688
+ console.log(pc.bold(`
1689
+ \u{1F9EC} Skill del proyecto: ${result.skillName}`));
1690
+ console.log(pc.dim(` fuentes \u2192 flujo:${s.flujo ? "\u2713" : "\u2014"} convenciones:${s.convenciones ? "\u2713" : "\u2014"} lecciones:${s.lecciones}`));
1691
+ console.log(pc.dim(` destino \u2192 ${result.file}`));
1692
+ if (!result.changed) {
1693
+ console.log(pc.green("\n\u2713 La skill ya est\xE1 al d\xEDa \u2014 nada que cambiar.\n"));
1694
+ return;
1695
+ }
1696
+ const diff = simpleDiff(result.previous, result.content);
1697
+ console.log(pc.bold(`
1698
+ ${result.previous ? "Cambios" : "Contenido nuevo"} (${diff.length} l\xEDneas):
1699
+ `));
1700
+ for (const l of diff.slice(0, 40)) {
1701
+ console.log(l.startsWith("+") ? pc.green(l) : pc.red(l));
1702
+ }
1703
+ if (diff.length > 40) console.log(pc.dim(` \u2026 +${diff.length - 40} l\xEDneas m\xE1s`));
1704
+ let ok = Boolean(opts.yes);
1705
+ if (!ok) {
1706
+ if (!process.stdin.isTTY) {
1707
+ console.log(pc.yellow("\n(no interactivo: no se escribi\xF3 nada \u2014 usa `--yes` para aplicar)\n"));
1708
+ return;
1709
+ }
1710
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1711
+ const ans = (await rl.question(pc.bold("\n\xBFEscribir esta skill? [s/N] "))).trim().toLowerCase();
1712
+ rl.close();
1713
+ ok = ans === "s" || ans === "si" || ans === "s\xED" || ans === "y";
1714
+ }
1715
+ if (!ok) {
1716
+ console.log(pc.dim("Sin cambios.\n"));
1717
+ return;
1718
+ }
1719
+ writeSkill(result);
1720
+ console.log(pc.green(`
1721
+ \u2713 Skill escrita en ${result.file}`));
1722
+ console.log(pc.dim(" Se recarga al abrir una sesi\xF3n nueva del agente en este proyecto.\n"));
1723
+ });
1419
1724
  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) => {
1420
1725
  const vault = getVault();
1421
1726
  const cwd = process.cwd();
@@ -1450,12 +1755,18 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1450
1755
  console.log(pc.yellow("\u26A0 Embeddings desalineados con el \xEDndice \u2014 corre `ale reindex --force`"));
1451
1756
  } else if (idx.emb) {
1452
1757
  console.log(`${pc.green("\u2713")} Embeddings alineados (${idx.meta.chunks.length} chunks)`);
1758
+ } else if (idx.meta.chunks.length > 0 && model) {
1759
+ console.log(pc.yellow(`\u26A0 \xCDndice SIN vectores (${idx.meta.chunks.length} chunks) \u2014 b\xFAsqueda degradada a keyword. Reconstruyendo\u2026`));
1760
+ const rebuilt = await idx.refresh(true, true);
1761
+ console.log(
1762
+ idx.emb ? `${pc.green("\u2713")} \xCDndice sem\xE1ntico reconstruido (${rebuilt.changed} notas)` : pc.yellow("\u26A0 No se pudo reconstruir \u2014 corre `ale reindex --force` y revisa el modelo")
1763
+ );
1453
1764
  }
1454
1765
  try {
1455
- const name = path5.basename(cwd);
1456
- const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1457
- const pkgM = fs5.statSync(path5.join(cwd, "package.json")).mtimeMs;
1458
- const mapM = fs5.statSync(mapFile).mtimeMs;
1766
+ const name = path6.basename(cwd);
1767
+ const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1768
+ const pkgM = fs6.statSync(path6.join(cwd, "package.json")).mtimeMs;
1769
+ const mapM = fs6.statSync(mapFile).mtimeMs;
1459
1770
  if (pkgM > mapM) {
1460
1771
  console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1461
1772
  } else {
@@ -1464,7 +1775,7 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1464
1775
  } catch {
1465
1776
  }
1466
1777
  const skillsRepoCfg = localSkillsRepo();
1467
- if (skillsRepoCfg && !fs5.existsSync(skillsRepoCfg)) {
1778
+ if (skillsRepoCfg && !fs6.existsSync(skillsRepoCfg)) {
1468
1779
  console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1469
1780
  }
1470
1781
  console.log();
@@ -1478,14 +1789,14 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
1478
1789
  const claudeMd = removeClaudeMd(scope, cwd);
1479
1790
  if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
1480
1791
  if (opts.project) {
1481
- const mcpFile = path5.join(cwd, ".mcp.json");
1792
+ const mcpFile = path6.join(cwd, ".mcp.json");
1482
1793
  try {
1483
- const cfg = JSON.parse(fs5.readFileSync(mcpFile, "utf8"));
1794
+ const cfg = JSON.parse(fs6.readFileSync(mcpFile, "utf8"));
1484
1795
  if (cfg.mcpServers?.alexandria) {
1485
1796
  delete cfg.mcpServers.alexandria;
1486
1797
  if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
1487
- if (Object.keys(cfg).length === 0) fs5.rmSync(mcpFile, { force: true });
1488
- else fs5.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1798
+ if (Object.keys(cfg).length === 0) fs6.rmSync(mcpFile, { force: true });
1799
+ else fs6.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1489
1800
  console.log(pc.green("\u2713 MCP removido de .mcp.json"));
1490
1801
  }
1491
1802
  } catch {