@ureck/alexandria 0.3.0 → 0.5.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,23 +16,29 @@ import {
16
16
  } from "./chunk-KHTYRYDR.js";
17
17
  import {
18
18
  hybridSearch
19
- } from "./chunk-FID2RAOH.js";
19
+ } from "./chunk-BCLBZ7NX.js";
20
20
  import {
21
- serveGraph
22
- } from "./chunk-I2ZBQUZD.js";
23
- import {
24
- VaultIndex
25
- } from "./chunk-VN7QOAG2.js";
26
- import {
27
- createNote,
28
21
  defaultVaultPath,
29
22
  ensureVaultStructure,
23
+ getConfigKey,
30
24
  globalConfigPath,
31
25
  resolveVault,
26
+ setConfigKey,
32
27
  vaultExists,
33
28
  writeGlobalConfig,
34
29
  writeProjectConfig
35
- } from "./chunk-CF2GLMR3.js";
30
+ } from "./chunk-DYCARGQR.js";
31
+ import {
32
+ serveGraph
33
+ } from "./chunk-RLVCH6CZ.js";
34
+ import {
35
+ VaultIndex
36
+ } from "./chunk-MLA3KZPZ.js";
37
+ import {
38
+ createNote,
39
+ slugify,
40
+ upsertNote
41
+ } from "./chunk-XWR74BQ2.js";
36
42
  import {
37
43
  MODEL_ID,
38
44
  getEmbedder,
@@ -40,8 +46,8 @@ import {
40
46
  } from "./chunk-EDYBSJSS.js";
41
47
 
42
48
  // src/cli.ts
43
- import fs3 from "fs";
44
- import path3 from "path";
49
+ import fs4 from "fs";
50
+ import path4 from "path";
45
51
  import readline from "readline/promises";
46
52
  import { Command } from "commander";
47
53
  import pc from "picocolors";
@@ -428,6 +434,115 @@ async function showBanner(animate) {
428
434
  }
429
435
  }
430
436
 
437
+ // src/core/setup.ts
438
+ import fs3 from "fs";
439
+ import os3 from "os";
440
+ import path3 from "path";
441
+ function ensureGitignore(projectDir, vaultRoot) {
442
+ if (!fs3.existsSync(path3.join(projectDir, ".git"))) return null;
443
+ const rel = path3.relative(projectDir, vaultRoot);
444
+ if (rel.startsWith("..")) return null;
445
+ const file = path3.join(projectDir, ".gitignore");
446
+ const entries = [`${rel.split(path3.sep).join("/")}/`];
447
+ let text = "";
448
+ try {
449
+ text = fs3.readFileSync(file, "utf8");
450
+ } catch {
451
+ }
452
+ const missing = entries.filter((e) => !text.split("\n").some((l) => l.trim() === e || l.trim() === e.slice(0, -1)));
453
+ if (missing.length === 0) return null;
454
+ const block = `${text.trimEnd()}
455
+
456
+ # Alexandria (conocimiento personal, no del repo)
457
+ ${missing.join("\n")}
458
+ `;
459
+ fs3.writeFileSync(file, text.trim() ? block : block.trimStart());
460
+ return file;
461
+ }
462
+ var CLAUDE_MD_START = "<!-- alexandria:start -->";
463
+ var CLAUDE_MD_END = "<!-- alexandria:end -->";
464
+ function configureClaudeMd(scope, projectDir) {
465
+ const file = scope === "project" ? path3.join(projectDir, "CLAUDE.md") : path3.join(os3.homedir(), ".claude", "CLAUDE.md");
466
+ const block = [
467
+ CLAUDE_MD_START,
468
+ "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
469
+ "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
470
+ "- El Protocolo Alexandria es palanca, no l\xEDmite: tareas simples se responden directo, sin ceremonia. En tareas no triviales: `plan_create` (objetivo + Definition of Done) \u2192 ejecutar con toda tu capacidad \u2192 `task_verify` con evidencia real (la evidencia elimina errores, no frena) \u2192 si algo falla, `vault_search` por lecciones previas antes de re-debuggear \u2192 `lesson_extract` al resolver algo no obvio. Soluciones cacheadas se validan contra el c\xF3digo actual antes de reutilizarse.",
471
+ "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
472
+ "- `vault_related` trae conocimiento conectado sin releer archivos.",
473
+ CLAUDE_MD_END
474
+ ].join("\n");
475
+ fs3.mkdirSync(path3.dirname(file), { recursive: true });
476
+ let text = "";
477
+ try {
478
+ text = fs3.readFileSync(file, "utf8");
479
+ } catch {
480
+ }
481
+ if (text.includes(CLAUDE_MD_START)) {
482
+ const re = new RegExp(`${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}`);
483
+ text = text.replace(re, block);
484
+ } else {
485
+ text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
486
+ }
487
+ fs3.writeFileSync(file, text);
488
+ return file;
489
+ }
490
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
491
+ function scanProject(vault, projectDir) {
492
+ const name = path3.basename(projectDir);
493
+ const mapFile = path3.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
494
+ if (fs3.existsSync(mapFile)) return null;
495
+ const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
496
+ try {
497
+ const pkg = JSON.parse(fs3.readFileSync(path3.join(projectDir, "package.json"), "utf8"));
498
+ const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
499
+ const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
500
+ parts.push(`## Stack
501
+ ${pkg.name ? `Paquete: ${pkg.name}` : ""}
502
+ - deps: ${deps.join(", ") || "\u2014"}
503
+ - dev: ${dev.join(", ") || "\u2014"}`);
504
+ const scripts = Object.entries(pkg.scripts ?? {}).slice(0, 12);
505
+ if (scripts.length) {
506
+ parts.push(`## Comandos
507
+ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
508
+ }
509
+ } catch {
510
+ }
511
+ const tree = [];
512
+ const walk = (dir, depth, prefix) => {
513
+ if (depth > 2 || tree.length > 60) return;
514
+ let entries = [];
515
+ try {
516
+ entries = fs3.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
517
+ } catch {
518
+ return;
519
+ }
520
+ for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
521
+ tree.push(`${prefix}${e.name}/`);
522
+ walk(path3.join(dir, e.name), depth + 1, prefix + " ");
523
+ }
524
+ };
525
+ walk(projectDir, 1, "");
526
+ if (tree.length) parts.push(`## Estructura
527
+ \`\`\`
528
+ ${tree.join("\n")}
529
+ \`\`\``);
530
+ try {
531
+ const readme = fs3.readFileSync(path3.join(projectDir, "README.md"), "utf8");
532
+ parts.push(`## README (extracto)
533
+ ${readme.split("\n").slice(0, 15).join("\n")}`);
534
+ } catch {
535
+ }
536
+ return upsertNote(vault.managed, {
537
+ fixedName: `mapa-${slugify(name)}`,
538
+ title: `Mapa - ${name}`,
539
+ type: "map",
540
+ tags: [name, "mapa"],
541
+ dir: "notes",
542
+ content: parts.join("\n\n")
543
+ });
544
+ }
545
+
431
546
  // src/cli.ts
432
547
  function registerAgentsMcp(agents, scope, cwd) {
433
548
  for (const agent of agents) {
@@ -483,14 +598,14 @@ async function ensureReady(vault = getVault()) {
483
598
  }
484
599
  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(
485
600
  "--path <dir>",
486
- "ruta del vault Obsidian (existente o nuevo). Default: ./KnowledgeVault con --project, ~/KnowledgeVault en global"
487
- ).option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
601
+ "ruta del vault Obsidian (existente o nuevo). Default: ./Alexandria con --project, ~/Alexandria en global"
602
+ ).option("--auto", "configurar el uso autom\xE1tico en CLAUDE.md sin preguntar").option("--manual", "no tocar CLAUDE.md (config\xFAralo t\xFA)").option("--no-protocol", "instalar sin el Protocolo Alexandria (solo b\xF3veda cl\xE1sica)").option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
488
603
  "--agents <ids>",
489
604
  `agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
490
605
  ).action(async (opts) => {
491
606
  const isProject = Boolean(opts.project) && !opts.global;
492
607
  const cwd = process.cwd();
493
- const vaultPath = path3.resolve(opts.path ?? (isProject ? path3.join(cwd, "KnowledgeVault") : defaultVaultPath()));
608
+ const vaultPath = path4.resolve(opts.path ?? (isProject ? path4.join(cwd, "Alexandria") : defaultVaultPath()));
494
609
  await showBanner();
495
610
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
496
611
  `));
@@ -515,6 +630,35 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
515
630
  if (skipped.length > 0) {
516
631
  console.log(pc.dim(` Otros agentes disponibles: ${skipped.map((a) => a.id).join(", ")} \u2192 ale agents <ids>`));
517
632
  }
633
+ if (isProject) {
634
+ const gi = ensureGitignore(cwd, vault.root);
635
+ if (gi) console.log(pc.green(`\u2713 B\xF3veda agregada a ${gi}`));
636
+ }
637
+ let auto = opts.auto ? true : opts.manual ? false : void 0;
638
+ if (auto === void 0) {
639
+ if (process.stdin.isTTY) {
640
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
641
+ const ans = (await rl.question(pc.bold("\xBFConfigurar a Claude para usar Alexandria autom\xE1ticamente (CLAUDE.md)? [S/n] "))).trim().toLowerCase();
642
+ rl.close();
643
+ auto = ans === "" || ans === "s" || ans === "si" || ans === "s\xED" || ans === "y";
644
+ } else {
645
+ auto = true;
646
+ }
647
+ }
648
+ if (auto) {
649
+ const file = configureClaudeMd(isProject ? "project" : "global", cwd);
650
+ console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${file}`));
651
+ } else {
652
+ console.log(pc.dim(" Sin auto-configuraci\xF3n (act\xEDvala luego con: ale init --auto)"));
653
+ }
654
+ setConfigKey("protocol", opts.protocol !== false);
655
+ console.log(
656
+ opts.protocol !== false ? pc.green("\u2713 Protocolo Alexandria activo (plan_create \xB7 task_verify \xB7 lesson_extract) \u2014 ap\xE1galo con: ale config set protocol false") : pc.dim(" Protocolo desactivado (b\xF3veda cl\xE1sica) \u2014 act\xEDvalo con: ale config set protocol true")
657
+ );
658
+ if (isProject) {
659
+ const map = scanProject(vault, cwd);
660
+ if (map) console.log(pc.green(`\u2713 Proyecto escaneado \u2192 ${path4.relative(vault.root, map)} (mapa inicial)`));
661
+ }
518
662
  await downloadModelIfMissing();
519
663
  const idx = VaultIndex.load(vault);
520
664
  const res = await idx.refresh();
@@ -524,6 +668,103 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
524
668
  console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents\n'));
525
669
  if (opts.skills) await runSkills({ yes: false, project: isProject });
526
670
  });
671
+ 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) => {
672
+ const { vault } = await ensureReady();
673
+ const abs = path4.resolve(file);
674
+ const raw = fs4.readFileSync(abs, "utf8");
675
+ const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
676
+ const title = opts.title ?? heading ?? path4.basename(abs).replace(/\.(md|txt)$/i, "");
677
+ const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
678
+ const noteFile = createNote(vault.managed, {
679
+ title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
680
+ type: "plan",
681
+ status: "active",
682
+ tags: ["plan"],
683
+ content: raw.trim()
684
+ });
685
+ await VaultIndex.load(vault).refresh();
686
+ console.log(pc.green(`\u2713 Plan creado: ${path4.relative(vault.root, noteFile)}`));
687
+ 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)'}`));
688
+ console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
689
+ });
690
+ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD, planes abiertos, fallos sin lecci\xF3n, notas sueltas").action(async () => {
691
+ const { vault, idx } = await ensureReady();
692
+ const notes = Object.values(idx.meta.notes).filter((n) => !n.rel.split("/").includes("archive"));
693
+ const plans = notes.filter((n) => n.type === "plan");
694
+ const linked = new Set(idx.meta.links.flatMap((l) => [l.from, l.to]));
695
+ console.log(pc.bold("\n\u{1F3DB}\uFE0F Auditor\xEDa del Protocolo Alexandria\n"));
696
+ const openPlans = plans.filter((p) => p.status === "active");
697
+ console.log(` Planes: ${plans.length} (${pc.yellow(`${openPlans.length} abiertos`)}, ${plans.filter((p) => p.status === "completed").length} completados, ${plans.filter((p) => p.status === "failed").length} fallidos)`);
698
+ for (const p of openPlans.slice(0, 8)) console.log(pc.dim(` \u25CB ${p.title}`));
699
+ const chunksByNote = /* @__PURE__ */ new Map();
700
+ for (const c of idx.meta.chunks) chunksByNote.set(c.note, (chunksByNote.get(c.note) ?? "") + "\n" + c.text);
701
+ const noDod = plans.filter((p) => !/\[[ x]\]/i.test(chunksByNote.get(p.rel) ?? ""));
702
+ if (noDod.length > 0) {
703
+ console.log(pc.yellow(` \u26A0 Planes sin Definition of Done: ${noDod.length}`));
704
+ for (const p of noDod.slice(0, 5)) console.log(pc.dim(` - ${p.title}`));
705
+ }
706
+ const fails = notes.filter((n) => n.type === "verification" && n.status === "failed");
707
+ const lessons = notes.filter((n) => n.type === "lesson");
708
+ console.log(` Verificaciones: ${notes.filter((n) => n.type === "verification").length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
709
+ if (fails.length > lessons.length) {
710
+ console.log(pc.yellow(` \u26A0 Hay m\xE1s fallos (${fails.length}) que lecciones (${lessons.length}) \u2014 fallos resueltos sin destilar aprendizaje.`));
711
+ }
712
+ const loose = notes.filter((n) => n.type !== "prompt" && n.type !== "session" && !linked.has(n.rel));
713
+ if (loose.length > 0) {
714
+ console.log(pc.yellow(` \u26A0 Notas sin conexiones (invisibles para vault_related): ${loose.length}`));
715
+ for (const n of loose.slice(0, 5)) console.log(pc.dim(` - ${n.title} \u2192 con\xE9ctala con vault_link o [[wikilinks]]`));
716
+ }
717
+ if (noDod.length === 0 && loose.length === 0 && fails.length <= lessons.length) {
718
+ console.log(pc.green("\n \u2713 B\xF3veda sana: planes con DoD, conocimiento conectado, fallos con lecci\xF3n."));
719
+ }
720
+ console.log();
721
+ });
722
+ program.command("config").description("Configuraci\xF3n de Alexandria (ej. protocol true/false)").argument("<accion>", "get | set").argument("<clave>", "ej. protocol").argument("[valor]", "para set: true/false o texto").action((accion, clave, valor) => {
723
+ const key = clave.replace(/^protocol\.enabled$/, "protocol");
724
+ if (accion === "get") {
725
+ const v = getConfigKey(key);
726
+ console.log(v === void 0 ? pc.dim(`${key} sin definir (default: ${key === "protocol" ? "true" : "\u2014"})`) : `${key} = ${JSON.stringify(v)}`);
727
+ return;
728
+ }
729
+ if (accion === "set") {
730
+ const parsed = valor === "true" ? true : valor === "false" ? false : valor;
731
+ setConfigKey(key, parsed);
732
+ console.log(pc.green(`\u2713 ${key} = ${JSON.stringify(parsed)}`));
733
+ return;
734
+ }
735
+ console.log(pc.yellow("Acci\xF3n inv\xE1lida: usa get o set"));
736
+ });
737
+ 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) => {
738
+ const { vault, idx } = await ensureReady();
739
+ const cutoff = Date.now() - (parseInt(opts.days, 10) || 45) * 864e5;
740
+ const stale = Object.values(idx.meta.notes).filter(
741
+ (n) => n.type === "prompt" && (n.hits ?? 1) <= 1 && !n.rel.split("/").includes("archive") && n.created !== void 0 && Date.parse(n.created) < cutoff
742
+ );
743
+ if (stale.length === 0) {
744
+ console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
745
+ return;
746
+ }
747
+ const archiveDir = path4.join(vault.managed, "archive");
748
+ if (!opts.dry) fs4.mkdirSync(archiveDir, { recursive: true });
749
+ for (const n of stale) {
750
+ console.log(
751
+ `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
752
+ );
753
+ if (!opts.dry) {
754
+ fs4.renameSync(path4.join(vault.root, n.rel), path4.join(archiveDir, path4.basename(n.rel)));
755
+ }
756
+ }
757
+ if (!opts.dry) {
758
+ await VaultIndex.load(vault).refresh();
759
+ console.log(
760
+ pc.green(`
761
+ \u2713 ${stale.length} prompts archivados en ${path4.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
762
+ );
763
+ } else {
764
+ console.log(pc.dim(`
765
+ ${stale.length} candidatos. Corre sin --dry para archivarlos.`));
766
+ }
767
+ });
527
768
  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) => {
528
769
  if (!ids) {
529
770
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));
@@ -544,11 +785,14 @@ program.command("agents").description("Lista los agentes de IA soportados y regi
544
785
  registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd());
545
786
  console.log(pc.dim("\n Reinicia el agente (o recarga sus MCP) para que tome el servidor.\n"));
546
787
  });
547
- 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) => {
788
+ program.command("add").description("Guardar una nota manualmente").argument("<title>", "t\xEDtulo").option("-c, --content <text>", "contenido markdown (o se lee de stdin)").option("-f, --file <path>", "leer el contenido desde un archivo .md/.txt del proyecto").option("-t, --tags <tags>", "tags separados por coma").action(async (title, opts) => {
548
789
  const { vault } = await ensureReady();
549
790
  let content = opts.content;
791
+ if (!content && opts.file) {
792
+ content = fs4.readFileSync(path4.resolve(opts.file), "utf8");
793
+ }
550
794
  if (!content && !process.stdin.isTTY) {
551
- content = fs3.readFileSync(0, "utf8");
795
+ content = fs4.readFileSync(0, "utf8");
552
796
  }
553
797
  const file = createNote(vault.managed, {
554
798
  title,
@@ -556,7 +800,7 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
556
800
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
557
801
  });
558
802
  await VaultIndex.load(vault).refresh();
559
- console.log(pc.green(`\u2713 ${path3.relative(vault.root, file)}`));
803
+ console.log(pc.green(`\u2713 ${path4.relative(vault.root, file)}`));
560
804
  });
561
805
  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) => {
562
806
  const vault = getVault();
@@ -621,6 +865,14 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
621
865
  console.log(` Notas: ${notes.length} ${pc.dim(JSON.stringify(byType))}`);
622
866
  console.log(` Chunks indexados: ${idx.meta.chunks.length} \xB7 Conexiones: ${idx.meta.links.length}`);
623
867
  console.log(` B\xFAsqueda sem\xE1ntica: ${idx.emb ? pc.green("activa") : pc.yellow("keyword-only (corre ale reindex con internet)")}`);
868
+ console.log(pc.bold("\n\u{1F3DB}\uFE0F Protocolo"));
869
+ const plans = notes.filter((n) => n.type === "plan");
870
+ const verifs = notes.filter((n) => n.type === "verification");
871
+ const lessons = notes.filter((n) => n.type === "lesson");
872
+ const reused = lessons.filter((n) => (n.hits ?? 1) > 1).length;
873
+ const passed = verifs.filter((n) => n.status === "completed").length;
874
+ console.log(` Planes: ${plans.length} (${plans.filter((p) => p.status === "active").length} abiertos) \xB7 Verificaciones: ${verifs.length}${verifs.length ? ` (${Math.round(passed / verifs.length * 100)}% \u2713)` : ""}`);
875
+ console.log(` Lecciones: ${lessons.length} (${reused} reutilizadas \u2014 cada reuso = debug que no se repiti\xF3)`);
624
876
  console.log(pc.bold("\n\u{1F4B0} Ahorro estimado"));
625
877
  console.log(` Inyecciones de contexto: ${s.injections} (${s.solutionCacheHits} con soluci\xF3n cacheada)`);
626
878
  console.log(` Tokens inyectados: ~${s.injectedTokens.toLocaleString()}`);
@@ -630,7 +882,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
630
882
  async function runSkills(opts) {
631
883
  const { vault } = await ensureReady();
632
884
  const cwd = process.cwd();
633
- const targetDir = opts.project ? path3.join(cwd, ".claude", "skills") : path3.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
885
+ const targetDir = opts.project ? path4.join(cwd, ".claude", "skills") : path4.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
634
886
  const recs = recommendSkills(vault, [targetDir]);
635
887
  if (recs.length === 0) {
636
888
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -9,14 +9,16 @@ import {
9
9
  } from "../chunk-DEDAOKAV.js";
10
10
  import {
11
11
  hybridSearch
12
- } from "../chunk-FID2RAOH.js";
13
- import "../chunk-VN7QOAG2.js";
12
+ } from "../chunk-BCLBZ7NX.js";
14
13
  import {
15
- createNote,
16
14
  resolveVault,
17
- touchNote,
18
15
  vaultExists
19
- } from "../chunk-CF2GLMR3.js";
16
+ } from "../chunk-DYCARGQR.js";
17
+ import "../chunk-MLA3KZPZ.js";
18
+ import {
19
+ createNote,
20
+ touchNote
21
+ } from "../chunk-XWR74BQ2.js";
20
22
  import "../chunk-EDYBSJSS.js";
21
23
 
22
24
  // src/hooks/on-prompt.ts
@@ -33,7 +35,14 @@ runHook(25e3, async (input) => {
33
35
  if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/")) return;
34
36
  const vault = resolveVault({ cwd: input.cwd });
35
37
  if (!vaultExists(vault)) return;
36
- const results = await hybridSearch(vault, prompt, 5, { expand: true });
38
+ const rawResults = await hybridSearch(vault, prompt, 5, { expand: true });
39
+ const STALE_DAYS = 60;
40
+ const results = rawResults.filter((r) => {
41
+ if (r.note.type !== "prompt" && r.note.type !== "session") return true;
42
+ if ((r.note.hits ?? 1) > 1) return true;
43
+ const age = r.note.created ? (Date.now() - Date.parse(r.note.created)) / 864e5 : 0;
44
+ return age <= STALE_DAYS;
45
+ });
37
46
  const maxCos = results.reduce((m, r) => Math.max(m, r.cosine), 0);
38
47
  const relevant = maxCos > 0 ? results.filter((r) => r.cosine >= RELEVANT_COSINE && r.cosine >= maxCos - RELEVANT_MARGIN) : results.filter((r) => r.score > 0.02);
39
48
  let injected = "";
@@ -44,7 +53,7 @@ runHook(25e3, async (input) => {
44
53
  const lines = [];
45
54
  if (cached) {
46
55
  lines.push(
47
- `\u26A1 Ya resolviste algo casi id\xE9ntico antes (\xAB${cached.note.title}\xBB). Reutiliza esa soluci\xF3n en vez de re-derivarla:
56
+ `\u26A1 Ya resolviste algo casi id\xE9ntico antes (\xAB${cached.note.title}\xBB). Parte de esa soluci\xF3n en vez de re-derivarla \u2014 valida que siga aplicando si el c\xF3digo cambi\xF3:
48
57
  ${truncate(cached.excerpts.join("\n"), 2e3)}`
49
58
  );
50
59
  }
@@ -66,7 +75,7 @@ Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o r
66
75
  promptChars: prompt.length
67
76
  });
68
77
  }
69
- const dupe = results.find((r) => r.note.type === "prompt" && r.cosine >= DEDUP_COSINE);
78
+ const dupe = rawResults.find((r) => r.note.type === "prompt" && r.cosine >= DEDUP_COSINE);
70
79
  if (dupe) {
71
80
  try {
72
81
  touchNote(path.join(vault.root, dupe.note.rel));
@@ -8,12 +8,14 @@ import {
8
8
  truncate
9
9
  } from "../chunk-DEDAOKAV.js";
10
10
  import {
11
- VaultIndex
12
- } from "../chunk-VN7QOAG2.js";
13
- import {
11
+ protocolEnabled,
14
12
  resolveVault,
15
13
  vaultExists
16
- } from "../chunk-CF2GLMR3.js";
14
+ } from "../chunk-DYCARGQR.js";
15
+ import {
16
+ VaultIndex
17
+ } from "../chunk-MLA3KZPZ.js";
18
+ import "../chunk-XWR74BQ2.js";
17
19
  import "../chunk-EDYBSJSS.js";
18
20
 
19
21
  // src/hooks/on-session-start.ts
@@ -30,6 +32,14 @@ runHook(15e3, async (input) => {
30
32
  if (notes.length === 0) return;
31
33
  const proj = projectName(input.cwd);
32
34
  const parts = [];
35
+ if (protocolEnabled()) {
36
+ const openPlans = notes.filter((n) => n.type === "plan" && n.status === "active");
37
+ parts.push(
38
+ `## Protocolo Alexandria (activo)
39
+ El protocolo es PALANCA, no l\xEDmite: \xFAsalo para rendir m\xE1s con menos tokens, nunca como burocracia. Tareas simples \u2192 responde directo, sin ceremonia. Tareas no triviales \u2192 ciclo con las tools MCP: 1) plan_create (objetivo + Definition of Done) \u2192 2) ejecuta con toda tu capacidad \u2192 3) task_verify con evidencia real (tests/build \u2014 la evidencia elimina errores, no te frena) \u2192 si algo falla, vault_search por lecciones ANTES de re-debuggear (conocimiento previo = tokens gratis) \u2192 4) lesson_extract si resolviste algo no obvio. Reutiliza lo cacheado con criterio: valida que siga aplicando si el c\xF3digo cambi\xF3.` + (openPlans.length > 0 ? `
40
+ **Planes abiertos:** ${openPlans.map((p) => p.title).join(" \xB7 ")} \u2014 ret\xF3malos, no dupliques.` : "")
41
+ );
42
+ }
33
43
  const map = notes.find(
34
44
  (n) => (n.type === "map" || n.title.toLowerCase().startsWith("mapa - ")) && n.title.toLowerCase().includes(proj.toLowerCase())
35
45
  );
@@ -5,11 +5,13 @@ import {
5
5
  truncate
6
6
  } from "../chunk-DEDAOKAV.js";
7
7
  import {
8
- appendToNote,
9
8
  ensureVaultStructure,
10
9
  resolveVault,
11
10
  vaultExists
12
- } from "../chunk-CF2GLMR3.js";
11
+ } from "../chunk-DYCARGQR.js";
12
+ import {
13
+ appendToNote
14
+ } from "../chunk-XWR74BQ2.js";
13
15
 
14
16
  // src/hooks/on-stop.ts
15
17
  import fs from "fs";
@@ -4,17 +4,20 @@ import {
4
4
  } from "../chunk-KHTYRYDR.js";
5
5
  import {
6
6
  hybridSearch
7
- } from "../chunk-FID2RAOH.js";
7
+ } from "../chunk-BCLBZ7NX.js";
8
+ import {
9
+ ensureVaultStructure,
10
+ resolveVault
11
+ } from "../chunk-DYCARGQR.js";
8
12
  import {
9
13
  VaultIndex
10
- } from "../chunk-VN7QOAG2.js";
14
+ } from "../chunk-MLA3KZPZ.js";
11
15
  import {
12
16
  createNote,
13
- ensureVaultStructure,
14
- resolveVault,
17
+ setNoteStatus,
15
18
  slugify,
16
19
  upsertNote
17
- } from "../chunk-CF2GLMR3.js";
20
+ } from "../chunk-XWR74BQ2.js";
18
21
  import "../chunk-EDYBSJSS.js";
19
22
 
20
23
  // src/mcp/server.ts
@@ -26,6 +29,15 @@ import { z } from "zod";
26
29
  var vault = resolveVault({ cwd: process.cwd() });
27
30
  var server = new McpServer({ name: "alexandria", version: pkgVersion() });
28
31
  var text = (t) => ({ content: [{ type: "text", text: t }] });
32
+ function findMap(idx) {
33
+ return Object.values(idx.meta.notes).find((n) => n.type === "map" || n.title.startsWith("Mapa - "));
34
+ }
35
+ function findByTitle(idx, t) {
36
+ const lower = t.toLowerCase();
37
+ return Object.values(idx.meta.notes).find(
38
+ (n) => n.title.toLowerCase() === lower || n.rel.toLowerCase() === lower
39
+ );
40
+ }
29
41
  server.tool(
30
42
  "vault_search",
31
43
  "Busca conocimiento en la b\xF3veda local (b\xFAsqueda sem\xE1ntica + keyword). \xDAsala ANTES de explorar c\xF3digo o re-derivar contexto: si la b\xF3veda ya lo sabe, ahorras tokens.",
@@ -50,6 +62,15 @@ server.tool(
50
62
  },
51
63
  async ({ title, content, tags }) => {
52
64
  ensureVaultStructure(vault);
65
+ if (!title.startsWith("Mapa - ") && !/\[\[/.test(content)) {
66
+ const idxPre = VaultIndex.load(vault);
67
+ const map = Object.values(idxPre.meta.notes).find(
68
+ (n) => n.type === "map" || n.title.startsWith("Mapa - ")
69
+ );
70
+ if (map) content = `${content.trim()}
71
+
72
+ Proyecto: [[${map.title}]]`;
73
+ }
53
74
  let file;
54
75
  if (title.startsWith("Mapa - ")) {
55
76
  file = upsertNote(vault.managed, {
@@ -107,4 +128,122 @@ server.tool(
107
128
  return text(`Conectado: \xAB${a.title}\xBB \u2192 [[${b.title}]]`);
108
129
  }
109
130
  );
131
+ server.tool(
132
+ "plan_create",
133
+ 'PROTOCOLO paso 1 (solo tareas NO triviales \u2014 las simples resp\xF3ndelas directo, sin ceremonia): crea el plan con Definition of Done (criterios verificables de "terminado") y tareas numeradas. Verifica cada tarea con task_verify. El plan enfoca tu capacidad, no la limita; y deja huella reutilizable.',
134
+ {
135
+ title: z.string().describe('Nombre corto del objetivo, ej. "Login con Google"'),
136
+ goal: z.string().describe("Qu\xE9 se quiere lograr, en una o dos frases"),
137
+ dod: z.array(z.string()).describe("Definition of Done: criterios verificables de \xE9xito"),
138
+ tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables")
139
+ },
140
+ async ({ title, goal, dod, tasks }) => {
141
+ ensureVaultStructure(vault);
142
+ const idx = VaultIndex.load(vault);
143
+ const map = findMap(idx);
144
+ const content = [
145
+ `## Objetivo
146
+ ${goal}`,
147
+ `## Definition of Done
148
+ ${dod.map((d) => `- [ ] ${d}`).join("\n")}`,
149
+ `## Tareas
150
+ ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
151
+ map ? `Proyecto: [[${map.title}]]` : ""
152
+ ].join("\n\n");
153
+ const file = createNote(vault.managed, {
154
+ title: `Plan - ${title}`,
155
+ type: "plan",
156
+ status: "active",
157
+ tags: ["plan"],
158
+ dir: "notes",
159
+ content
160
+ });
161
+ await VaultIndex.load(vault).refresh().catch(() => {
162
+ });
163
+ return text(
164
+ `Plan guardado en ${path.relative(vault.root, file)}. Ejecuta las tareas UNA por una; tras cada una llama task_verify con evidencia real (salida de tests/build). Al terminar todo, llama lesson_extract.`
165
+ );
166
+ }
167
+ );
168
+ server.tool(
169
+ "task_verify",
170
+ "PROTOCOLO paso 2: registra el resultado VERIFICADO de una tarea con evidencia real (salida de tests, build, curl \u2014 no lo des por hecho sin correrlo). Guarda el veredicto compacto; si fall\xF3, busca lecciones previas con vault_search antes de improvisar.",
171
+ {
172
+ plan: z.string().describe('T\xEDtulo del plan al que pertenece (ej. "Plan - Login con Google")'),
173
+ task: z.string().describe("Qu\xE9 tarea se verific\xF3"),
174
+ passed: z.boolean().describe("true si la evidencia confirma que funciona"),
175
+ evidence: z.string().describe('Evidencia compacta: "npm test \u2192 12/12 passed", c\xF3digo de error, etc.'),
176
+ completes_plan: z.boolean().optional().describe("true si esta era la \xFAltima tarea y el plan queda completado")
177
+ },
178
+ async ({ plan, task, passed, evidence, completes_plan }) => {
179
+ ensureVaultStructure(vault);
180
+ const idx = VaultIndex.load(vault);
181
+ const planNote = findByTitle(idx, plan);
182
+ const file = createNote(vault.managed, {
183
+ title: `${passed ? "OK" : "FALLO"} - ${task.slice(0, 60)}`,
184
+ type: "verification",
185
+ status: passed ? "completed" : "failed",
186
+ tags: ["verificacion"],
187
+ dir: "notes",
188
+ content: `**Tarea:** ${task}
189
+
190
+ **Veredicto:** ${passed ? "\u2705 pas\xF3" : "\u274C fall\xF3"}
191
+
192
+ **Evidencia:**
193
+ \`\`\`
194
+ ${evidence.slice(0, 1500)}
195
+ \`\`\`
196
+
197
+ ${planNote ? `Plan: [[${planNote.title}]]` : ""}`
198
+ });
199
+ if (completes_plan && planNote) {
200
+ try {
201
+ setNoteStatus(path.join(vault.root, planNote.rel), passed ? "completed" : "failed");
202
+ } catch {
203
+ }
204
+ }
205
+ await VaultIndex.load(vault).refresh().catch(() => {
206
+ });
207
+ if (!passed) {
208
+ const lessons = await hybridSearch(vault, `${task} ${evidence.slice(0, 200)}`, 3);
209
+ const useful = lessons.filter((l) => l.note.type === "lesson" || l.note.type === "solution");
210
+ if (useful.length > 0) {
211
+ return text(
212
+ `Fallo registrado (${path.relative(vault.root, file)}). LECCIONES PREVIAS que podr\xEDan aplicar \u2014 \xFAsalas antes de improvisar:
213
+ ` + useful.map((l) => `- \xAB${l.note.title}\xBB: ${l.excerpts[0]?.slice(0, 300) ?? ""}`).join("\n")
214
+ );
215
+ }
216
+ return text(`Fallo registrado. Sin lecciones previas para esto \u2014 cuando lo resuelvas, guarda la lecci\xF3n con lesson_extract.`);
217
+ }
218
+ return text(`Verificaci\xF3n guardada${completes_plan ? " y plan marcado como completado" : ""}. ${completes_plan ? "Cierra con lesson_extract si hubo aprendizaje." : "Siguiente tarea."}`);
219
+ }
220
+ );
221
+ server.tool(
222
+ "lesson_extract",
223
+ "PROTOCOLO paso 3: al resolver un error o terminar un plan, destila LA lecci\xF3n (qu\xE9 fall\xF3/funcion\xF3 y c\xF3mo evitarlo/repetirlo). 200 tokens hoy ahorran 20,000 de re-debug ma\xF1ana. Se inyecta autom\xE1ticamente cuando el problema reaparezca.",
224
+ {
225
+ title: z.string().describe('Lecci\xF3n en una frase, ej. "GOOGLE_CLIENT_SECRET debe ir en .env"'),
226
+ lesson: z.string().describe("Qu\xE9 pas\xF3, causa ra\xEDz, y c\xF3mo aplicarla la pr\xF3xima vez"),
227
+ links: z.array(z.string()).optional().describe("T\xEDtulos de notas relacionadas (plan, feature, etc.)")
228
+ },
229
+ async ({ title, lesson, links }) => {
230
+ ensureVaultStructure(vault);
231
+ const idx = VaultIndex.load(vault);
232
+ const map = findMap(idx);
233
+ const wikilinks = (links ?? []).map((l) => findByTitle(idx, l)).filter((n) => Boolean(n)).map((n) => `[[${n.title}]]`);
234
+ if (map) wikilinks.push(`[[${map.title}]]`);
235
+ const file = createNote(vault.managed, {
236
+ title: `Lecci\xF3n - ${title.slice(0, 70)}`,
237
+ type: "lesson",
238
+ tags: ["leccion"],
239
+ dir: "notes",
240
+ content: `${lesson}
241
+
242
+ ${wikilinks.length ? `Relacionado: ${[...new Set(wikilinks)].join(" \xB7 ")}` : ""}`
243
+ });
244
+ await VaultIndex.load(vault).refresh().catch(() => {
245
+ });
246
+ return text(`Lecci\xF3n guardada en ${path.relative(vault.root, file)} \u2014 se inyectar\xE1 autom\xE1ticamente cuando el tema reaparezca.`);
247
+ }
248
+ );
110
249
  await server.connect(new StdioServerTransport());