@ureck/alexandria 1.3.3 → 1.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
@@ -1,9 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- readStats
4
- } from "./chunk-XITAQVOZ.js";
5
2
  import {
6
3
  architectBlock,
4
+ distDir,
7
5
  globalSettingsPath,
8
6
  hooksRegistered,
9
7
  mcpRegisteredProject,
@@ -16,11 +14,19 @@ import {
16
14
  registerMcpProject,
17
15
  serverCommand,
18
16
  unregisterHooks
19
- } from "./chunk-5A6CC74D.js";
17
+ } from "./chunk-JI2L66DF.js";
20
18
  import {
21
19
  hybridSearch,
22
20
  protocolChain
23
- } from "./chunk-UWB6RKVN.js";
21
+ } from "./chunk-FPKJVQ2X.js";
22
+ import {
23
+ ARCHIVE_DIR,
24
+ applyClean,
25
+ dirBytes,
26
+ markCleaned,
27
+ planClean,
28
+ searchArchive
29
+ } from "./chunk-2ESJQAP4.js";
24
30
  import {
25
31
  TOKEN_TOGGLES,
26
32
  defaultVaultPath,
@@ -29,22 +35,23 @@ import {
29
35
  globalConfigPath,
30
36
  initScopeWarning,
31
37
  protocolEnabled,
38
+ readStats,
32
39
  resolveVault,
33
40
  setConfigKey,
34
41
  toggleEnabled,
35
42
  vaultExists,
36
43
  writeGlobalConfig,
37
44
  writeProjectConfig
38
- } from "./chunk-7LWLBJAD.js";
45
+ } from "./chunk-MDGFK6UC.js";
39
46
  import {
40
47
  serveGraph
41
- } from "./chunk-FBGIFNIO.js";
48
+ } from "./chunk-4ZSTD3CU.js";
42
49
  import {
43
50
  VaultIndex,
44
51
  createNote,
45
52
  slugify,
46
53
  upsertNote
47
- } from "./chunk-QB37UGO6.js";
54
+ } from "./chunk-3CB7GRFJ.js";
48
55
  import {
49
56
  MODEL_ID,
50
57
  dot,
@@ -54,9 +61,10 @@ import {
54
61
  } from "./chunk-EDYBSJSS.js";
55
62
 
56
63
  // src/cli.ts
57
- import fs6 from "fs";
58
- import path6 from "path";
64
+ import fs7 from "fs";
65
+ import path7 from "path";
59
66
  import readline from "readline/promises";
67
+ import { execFileSync as execFileSync4 } from "child_process";
60
68
  import { Command } from "commander";
61
69
  import pc from "picocolors";
62
70
 
@@ -367,6 +375,18 @@ function mergeMcpServers(file, key = "mcpServers") {
367
375
  return { ok: false, file, detail: e.message };
368
376
  }
369
377
  }
378
+ function removeMcpEntry(file, key = "mcpServers") {
379
+ try {
380
+ const cfg = JSON.parse(fs3.readFileSync(file, "utf8"));
381
+ if (!cfg[key]?.alexandria) return false;
382
+ delete cfg[key].alexandria;
383
+ if (Object.keys(cfg[key]).length === 0) delete cfg[key];
384
+ writeJson(file, cfg);
385
+ return true;
386
+ } catch {
387
+ return false;
388
+ }
389
+ }
370
390
  function home(...p) {
371
391
  return path3.join(os3.homedir(), ...p);
372
392
  }
@@ -419,6 +439,8 @@ var AGENTS = [
419
439
  name: "Claude Code",
420
440
  supportsProject: true,
421
441
  detect: () => fs3.existsSync(home(".claude")),
442
+ hooks: "claude",
443
+ unregister: (scope, projectDir) => scope === "project" ? removeMcpEntry(path3.join(projectDir, ".mcp.json")) : removeMcpEntry(home(".claude.json")),
422
444
  register(scope, projectDir) {
423
445
  if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
424
446
  return mergeMcpServers(home(".claude.json"));
@@ -429,6 +451,8 @@ var AGENTS = [
429
451
  name: "Cursor",
430
452
  supportsProject: true,
431
453
  detect: () => fs3.existsSync(home(".cursor")),
454
+ hooks: "cursor",
455
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json")),
432
456
  register(scope, projectDir) {
433
457
  const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
434
458
  return mergeMcpServers(file);
@@ -439,6 +463,8 @@ var AGENTS = [
439
463
  name: "OpenCode",
440
464
  supportsProject: true,
441
465
  detect: () => fs3.existsSync(home(".config", "opencode")) || fs3.existsSync(home(".opencode")),
466
+ hooks: "opencode",
467
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json"), "mcp"),
442
468
  register(scope, projectDir) {
443
469
  const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
444
470
  try {
@@ -459,6 +485,8 @@ var AGENTS = [
459
485
  name: "Windsurf (legacy \u2192 Devin)",
460
486
  supportsProject: false,
461
487
  detect: () => fs3.existsSync(home(".codeium", "windsurf")),
488
+ legacy: true,
489
+ unregister: () => removeMcpEntry(home(".codeium", "windsurf", "mcp_config.json")),
462
490
  register() {
463
491
  return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
464
492
  }
@@ -469,6 +497,7 @@ var AGENTS = [
469
497
  supportsProject: true,
470
498
  // El CLI vive en ~/.local/bin/devin y guarda config MCP por proyecto en .devin/
471
499
  detect: () => fs3.existsSync(home(".devin")) || fs3.existsSync(home(".local", "bin", "devin")),
500
+ unregister: (scope, projectDir) => removeMcpEntry(path3.join(scope === "project" ? projectDir : home(), ".devin", "mcp_config.local.json")),
472
501
  register(scope, projectDir) {
473
502
  const dir = scope === "project" ? projectDir : home();
474
503
  const file = path3.join(dir, ".devin", "mcp_config.local.json");
@@ -489,6 +518,7 @@ var AGENTS = [
489
518
  name: "Cline (VS Code)",
490
519
  supportsProject: false,
491
520
  detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
521
+ unregister: () => removeMcpEntry(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json")),
492
522
  register() {
493
523
  const file = path3.join(
494
524
  vscodeUserDir(),
@@ -503,14 +533,27 @@ var AGENTS = [
503
533
  {
504
534
  id: "codex",
505
535
  name: "Codex CLI (OpenAI)",
506
- supportsProject: false,
536
+ // Codex lee también <repo>/.codex/config.toml cuando el proyecto es de confianza
537
+ supportsProject: true,
507
538
  detect: () => fs3.existsSync(home(".codex")),
508
- register() {
509
- const file = home(".codex", "config.toml");
510
- const { command, args } = serverCmd();
539
+ hooks: "codex",
540
+ unregister: (scope, projectDir) => {
541
+ const file = scope === "project" ? path3.join(projectDir, ".codex", "config.toml") : home(".codex", "config.toml");
542
+ try {
543
+ const text = fs3.readFileSync(file, "utf8");
544
+ if (!/\[mcp_servers\.alexandria\]/.test(text)) return false;
545
+ fs3.writeFileSync(file, replaceTomlTable(text, "mcp_servers.alexandria", "").trimEnd() + "\n");
546
+ return true;
547
+ } catch {
548
+ return false;
549
+ }
550
+ },
551
+ register(scope, projectDir) {
552
+ const file = scope === "project" ? path3.join(projectDir, ".codex", "config.toml") : home(".codex", "config.toml");
553
+ const { command: command2, args } = serverCmd();
511
554
  const tomlArgs = args.map((a) => `"${a.replace(/\\/g, "\\\\")}"`).join(", ");
512
555
  const block = `[mcp_servers.alexandria]
513
- command = "${command}"
556
+ command = "${command2}"
514
557
  args = [${tomlArgs}]
515
558
  `;
516
559
  try {
@@ -533,6 +576,8 @@ args = [${tomlArgs}]
533
576
  name: "Gemini CLI",
534
577
  supportsProject: true,
535
578
  detect: () => fs3.existsSync(home(".gemini")),
579
+ hooks: "gemini",
580
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json")),
536
581
  register(scope, projectDir) {
537
582
  const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
538
583
  return mergeMcpServers(file);
@@ -543,6 +588,7 @@ args = [${tomlArgs}]
543
588
  name: "OpenClaw",
544
589
  supportsProject: false,
545
590
  detect: () => fs3.existsSync(home(".openclaw")),
591
+ unregister: () => removeMcpEntry(home(".openclaw", "openclaw.json")),
546
592
  register() {
547
593
  const file = home(".openclaw", "openclaw.json");
548
594
  try {
@@ -612,6 +658,7 @@ ${entry.trimEnd()}`);
612
658
  // Chat instalada. Antes bastaba con que existiera el User dir, así que
613
659
  // cualquiera con VS Code aparecía como agente detectado aunque no use MCP.
614
660
  detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "mcp.json")) || hasCopilotChatExtension(),
661
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json"), "servers"),
615
662
  register(scope, projectDir) {
616
663
  const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
617
664
  try {
@@ -637,6 +684,210 @@ function resolveAgents(spec) {
637
684
  return s.split(",").map((id) => agentById(id)).filter((a) => Boolean(a));
638
685
  }
639
686
 
687
+ // src/core/harness-hooks.ts
688
+ import fs4 from "fs";
689
+ import os4 from "os";
690
+ import path4 from "path";
691
+ var HOOK_HARNESSES = ["codex", "gemini", "cursor", "opencode"];
692
+ var EVENTS = {
693
+ // Codex: hooks GA desde 0.133; mismos nombres que Claude Code. Timeout en segundos.
694
+ codex: [
695
+ ["SessionStart", "on-session-start", 20],
696
+ ["UserPromptSubmit", "on-prompt", 10],
697
+ ["Stop", "on-stop", 30],
698
+ ["PreCompact", "on-stop", 30]
699
+ ],
700
+ // Gemini: BeforeAgent trae el prompt; AfterAgent trae prompt + prompt_response.
701
+ gemini: [
702
+ ["SessionStart", "on-session-start", 20],
703
+ ["BeforeAgent", "on-prompt", 10],
704
+ ["AfterAgent", "on-stop", 30],
705
+ ["PreCompress", "on-stop", 30]
706
+ ],
707
+ // Cursor: beforeSubmitPrompt no puede inyectar (solo continuar/bloquear) → ahí
708
+ // solo se captura; afterAgentResponse trae el texto de la respuesta.
709
+ cursor: [
710
+ ["sessionStart", "on-session-start", 20],
711
+ ["beforeSubmitPrompt", "on-prompt", 10],
712
+ ["afterAgentResponse", "on-stop", 30]
713
+ ]
714
+ };
715
+ function home2(...p) {
716
+ return path4.join(os4.homedir(), ...p);
717
+ }
718
+ function hookFile(h, scope, projectDir) {
719
+ const base = scope === "project" ? projectDir : os4.homedir();
720
+ switch (h) {
721
+ case "codex":
722
+ return path4.join(base, ".codex", "hooks.json");
723
+ case "gemini":
724
+ return path4.join(base, ".gemini", "settings.json");
725
+ case "cursor":
726
+ return path4.join(base, ".cursor", "hooks.json");
727
+ case "opencode":
728
+ return scope === "project" ? path4.join(projectDir, ".opencode", "plugins", "alexandria.js") : home2(".config", "opencode", "plugins", "alexandria.js");
729
+ }
730
+ }
731
+ function scriptPath(s) {
732
+ return path4.join(distDir(), "hooks", `${s}.js`);
733
+ }
734
+ function command(s, h) {
735
+ return `node "${scriptPath(s)}" --harness=${h}`;
736
+ }
737
+ var isOurs = (cmd) => typeof cmd === "string" && (cmd.includes("alexandria") || cmd.includes(distDir()));
738
+ function readJson(file) {
739
+ try {
740
+ return JSON.parse(fs4.readFileSync(file, "utf8"));
741
+ } catch {
742
+ if (fs4.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
743
+ return {};
744
+ }
745
+ }
746
+ function writeJson2(file, data) {
747
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
748
+ fs4.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
749
+ }
750
+ function stripOurs(hooks, flat) {
751
+ for (const ev of Object.keys(hooks)) {
752
+ const list = Array.isArray(hooks[ev]) ? hooks[ev] : [];
753
+ const kept = flat ? list.filter((c) => !isOurs(c.command)) : list.map((m) => ({ ...m, hooks: (m.hooks ?? []).filter((c) => !isOurs(c.command)) })).filter((m) => m.hooks.length > 0);
754
+ if (kept.length > 0) hooks[ev] = kept;
755
+ else delete hooks[ev];
756
+ }
757
+ }
758
+ function registerHarnessHooks(h, scope, projectDir) {
759
+ const file = hookFile(h, scope, projectDir);
760
+ try {
761
+ if (h === "opencode") {
762
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
763
+ fs4.writeFileSync(file, opencodePlugin());
764
+ return { ok: true, file };
765
+ }
766
+ const cfg = readJson(file);
767
+ const hooks = cfg.hooks ?? {};
768
+ const flat = h === "cursor";
769
+ stripOurs(hooks, flat);
770
+ for (const [ev, script, secs] of EVENTS[h]) {
771
+ const list = hooks[ev] ?? [];
772
+ if (flat) {
773
+ list.push({ command: command(script, h), timeout: secs });
774
+ } else if (h === "gemini") {
775
+ list.push({ hooks: [{ type: "command", name: `alexandria-${script}`, command: command(script, h), timeout: secs * 1e3 }] });
776
+ } else {
777
+ list.push({ hooks: [{ type: "command", command: command(script, h), timeout: secs }] });
778
+ }
779
+ hooks[ev] = list;
780
+ }
781
+ cfg.hooks = hooks;
782
+ if (flat) cfg.version ??= 1;
783
+ writeJson2(file, cfg);
784
+ return {
785
+ ok: true,
786
+ file,
787
+ detail: h === "codex" ? "abre Codex y aprueba los hooks con /hooks (Codex salta hooks no confiados)" : void 0
788
+ };
789
+ } catch (e) {
790
+ return { ok: false, file, detail: e.message };
791
+ }
792
+ }
793
+ function unregisterHarnessHooks(h, scope, projectDir) {
794
+ const file = hookFile(h, scope, projectDir);
795
+ try {
796
+ if (!fs4.existsSync(file)) return false;
797
+ if (h === "opencode") {
798
+ fs4.rmSync(file, { force: true });
799
+ return true;
800
+ }
801
+ const cfg = readJson(file);
802
+ const hooks = cfg.hooks;
803
+ if (!hooks) return false;
804
+ const before = JSON.stringify(hooks);
805
+ stripOurs(hooks, h === "cursor");
806
+ if (JSON.stringify(hooks) === before) return false;
807
+ if (Object.keys(hooks).length === 0) delete cfg.hooks;
808
+ writeJson2(file, cfg);
809
+ return true;
810
+ } catch {
811
+ return false;
812
+ }
813
+ }
814
+ function opencodePlugin() {
815
+ const scripts = {
816
+ session: scriptPath("on-session-start"),
817
+ prompt: scriptPath("on-prompt"),
818
+ stop: scriptPath("on-stop")
819
+ };
820
+ return `// Alexandria \u2014 plugin de OpenCode (generado por \`ale agents opencode\`; se sobrescribe al re-registrar).
821
+ // Captura prompts/sesiones en la b\xF3veda e inyecta contexto relevante en el system prompt.
822
+ import { execFile } from 'node:child_process';
823
+
824
+ const SCRIPTS = ${JSON.stringify(scripts, null, 2)};
825
+
826
+ function run(script, payload, timeoutMs) {
827
+ return new Promise((resolve) => {
828
+ const child = execFile('node', [script, '--harness=opencode'], { timeout: timeoutMs, windowsHide: true }, (_e, stdout) =>
829
+ resolve(typeof stdout === 'string' ? stdout.trim() : '')
830
+ );
831
+ child.stdin?.end(JSON.stringify(payload));
832
+ });
833
+ }
834
+
835
+ // Solo export default: OpenCode registra CADA funci\xF3n exportada como plugin.
836
+ const AlexandriaPlugin = async ({ directory }) => {
837
+ const digest = new Map(); // sessionID \u2192 contexto de inicio
838
+ const turn = new Map(); // sessionID \u2192 contexto del prompt actual
839
+ const lastPrompt = new Map();
840
+ const roles = new Map(); // messageID \u2192 role
841
+ const texts = new Map(); // messageID \u2192 texto acumulado
842
+ const lastAssistant = new Map(); // sessionID \u2192 messageID
843
+
844
+ return {
845
+ event: async ({ event }) => {
846
+ try {
847
+ const p = event?.properties ?? {};
848
+ if (event.type === 'session.created') {
849
+ const id = p.info?.id ?? p.sessionID;
850
+ if (id) digest.set(id, await run(SCRIPTS.session, { session_id: id, cwd: directory, source: 'startup' }, 15000));
851
+ } else if (event.type === 'message.updated' && p.info?.id) {
852
+ roles.set(p.info.id, p.info.role);
853
+ if (p.info.role === 'assistant' && p.info.sessionID) lastAssistant.set(p.info.sessionID, p.info.id);
854
+ } else if (event.type === 'message.part.updated' && p.part?.type === 'text' && !p.part.synthetic) {
855
+ texts.set(p.part.messageID, p.part.text ?? '');
856
+ } else if (event.type === 'session.idle' && p.sessionID) {
857
+ const mid = lastAssistant.get(p.sessionID);
858
+ const answer = mid ? texts.get(mid) : '';
859
+ if (answer) {
860
+ await run(SCRIPTS.stop, { session_id: p.sessionID, cwd: directory, prompt: lastPrompt.get(p.sessionID) ?? '', last_assistant_message: answer }, 25000);
861
+ }
862
+ }
863
+ } catch {
864
+ /* Alexandria jam\xE1s rompe la sesi\xF3n */
865
+ }
866
+ },
867
+ 'chat.message': async (input, output) => {
868
+ try {
869
+ const prompt = (output?.parts ?? []).filter((x) => x?.type === 'text' && !x.synthetic).map((x) => x.text).join('\\n').trim();
870
+ if (!prompt) return;
871
+ lastPrompt.set(input.sessionID, prompt);
872
+ turn.set(input.sessionID, await run(SCRIPTS.prompt, { session_id: input.sessionID, cwd: directory, prompt }, 8000));
873
+ } catch {
874
+ /* sin contexto este turno */
875
+ }
876
+ },
877
+ 'experimental.chat.system.transform': async (input, output) => {
878
+ if (!Array.isArray(output?.system) || !input?.sessionID) return;
879
+ const d = digest.get(input.sessionID);
880
+ const t = turn.get(input.sessionID);
881
+ if (d) output.system.push(d);
882
+ if (t) output.system.push(t);
883
+ }
884
+ };
885
+ };
886
+
887
+ export default AlexandriaPlugin;
888
+ `;
889
+ }
890
+
640
891
  // src/cli/banner.ts
641
892
  var ART = [
642
893
  "\u2584\u2580\u2588 \u2588\u2591\u2591 \u2588\u2580\u2580 \u2580\u2584\u2580 \u2584\u2580\u2588 \u2588\u2584\u2591\u2588 \u2588\u2580\u2584 \u2588\u2580\u2588 \u2588 \u2584\u2580\u2588",
@@ -698,9 +949,9 @@ async function showBanner(animate) {
698
949
  }
699
950
 
700
951
  // src/core/setup.ts
701
- import fs4 from "fs";
702
- import os4 from "os";
703
- import path4 from "path";
952
+ import fs5 from "fs";
953
+ import os5 from "os";
954
+ import path5 from "path";
704
955
  import { execFileSync as execFileSync3 } from "child_process";
705
956
  var PERSONAL_CONFIG_FILES = [
706
957
  ".vault.json",
@@ -709,18 +960,23 @@ var PERSONAL_CONFIG_FILES = [
709
960
  "opencode.json",
710
961
  ".vscode/mcp.json",
711
962
  ".gemini/settings.json",
712
- ".devin/mcp_config.local.json"
963
+ ".devin/mcp_config.local.json",
964
+ // hooks/MCP por proyecto de los demás arneses: llevan rutas de esta máquina
965
+ ".codex/hooks.json",
966
+ ".codex/config.toml",
967
+ ".cursor/hooks.json",
968
+ ".opencode/plugins/alexandria.js"
713
969
  ];
714
970
  function ensureGitignore(projectDir, vaultRoot) {
715
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return null;
971
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return null;
716
972
  const entries = [];
717
- const rel = path4.relative(projectDir, vaultRoot);
718
- if (!rel.startsWith("..")) entries.push(`${rel.split(path4.sep).join("/")}/`);
973
+ const rel = path5.relative(projectDir, vaultRoot);
974
+ if (!rel.startsWith("..")) entries.push(`${rel.split(path5.sep).join("/")}/`);
719
975
  entries.push(...PERSONAL_CONFIG_FILES);
720
- const file = path4.join(projectDir, ".gitignore");
976
+ const file = path5.join(projectDir, ".gitignore");
721
977
  let text = "";
722
978
  try {
723
- text = fs4.readFileSync(file, "utf8");
979
+ text = fs5.readFileSync(file, "utf8");
724
980
  } catch {
725
981
  }
726
982
  const has = (e) => text.split("\n").some((l) => l.trim() === e || l.trim() === e.replace(/\/$/, ""));
@@ -731,14 +987,14 @@ function ensureGitignore(projectDir, vaultRoot) {
731
987
  # Alexandria (conocimiento y config personal \u2014 no del repo)
732
988
  ${missing.join("\n")}
733
989
  `;
734
- fs4.writeFileSync(file, text.trim() ? block : block.trimStart());
990
+ fs5.writeFileSync(file, text.trim() ? block : block.trimStart());
735
991
  return file;
736
992
  }
737
993
  function untrackPersonalConfigs(projectDir) {
738
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return [];
994
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return [];
739
995
  const untracked = [];
740
996
  for (const f of PERSONAL_CONFIG_FILES) {
741
- if (!fs4.existsSync(path4.join(projectDir, f))) continue;
997
+ if (!fs5.existsSync(path5.join(projectDir, f))) continue;
742
998
  try {
743
999
  const tracked = execFileSync3("git", ["ls-files", "--error-unmatch", f], {
744
1000
  cwd: projectDir,
@@ -755,60 +1011,80 @@ function untrackPersonalConfigs(projectDir) {
755
1011
  }
756
1012
  var CLAUDE_MD_START = "<!-- alexandria:start -->";
757
1013
  var CLAUDE_MD_END = "<!-- alexandria:end -->";
758
- function configureClaudeMd(scope, projectDir) {
759
- const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
760
- const block = [
761
- CLAUDE_MD_START,
762
- "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
763
- "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
764
- "- 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.",
765
- "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
766
- "- Enriquece la b\xF3veda cuando el trabajo lo revele (no como tarea aparte): decisiones de arquitectura con su porqu\xE9 (por qu\xE9 X y no Y), qu\xE9 hace cada m\xF3dulo/feature al tocarlo, vocabulario propio del dominio, y errores no obvios con su fix (`lesson_extract`). Notas compactas: el objetivo es ahorrar tokens futuros, no escribir prosa.",
767
- "- Las notas `API - <proyecto>` / `Env - <proyecto>` / `Datos - <proyecto>` / `Convenciones - <proyecto>` (de `ale scan`) ya traen rutas, variables (solo nombres) y esquema \u2014 cons\xFAltalas por b\xFAsqueda antes de releer esos archivos.",
768
- "- `vault_related` trae conocimiento conectado sin releer archivos.",
769
- CLAUDE_MD_END
770
- ].join("\n");
771
- fs4.mkdirSync(path4.dirname(file), { recursive: true });
1014
+ var BLOCK = [
1015
+ CLAUDE_MD_START,
1016
+ "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
1017
+ "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
1018
+ "- 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.",
1019
+ "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
1020
+ "- Enriquece la b\xF3veda cuando el trabajo lo revele (no como tarea aparte): decisiones de arquitectura con su porqu\xE9 (por qu\xE9 X y no Y), qu\xE9 hace cada m\xF3dulo/feature al tocarlo, vocabulario propio del dominio, y errores no obvios con su fix (`lesson_extract`). Notas compactas: el objetivo es ahorrar tokens futuros, no escribir prosa.",
1021
+ "- Las notas `API - <proyecto>` / `Env - <proyecto>` / `Datos - <proyecto>` / `Convenciones - <proyecto>` / `Flujo - <proyecto>` (de `ale scan`) ya traen rutas, variables (solo nombres), esquema y flujo de peticiones \u2014 cons\xFAltalas por b\xFAsqueda antes de releer esos archivos.",
1022
+ "- `vault_related` trae conocimiento conectado sin releer archivos.",
1023
+ CLAUDE_MD_END
1024
+ ].join("\n");
1025
+ function instructionFiles(scope, projectDir) {
1026
+ if (scope === "project") {
1027
+ const claude = path5.join(projectDir, "CLAUDE.md");
1028
+ const agents = path5.join(projectDir, "AGENTS.md");
1029
+ let claudeText = "";
1030
+ try {
1031
+ claudeText = fs5.readFileSync(claude, "utf8");
1032
+ } catch {
1033
+ }
1034
+ return /^@AGENTS\.md\s*$/m.test(claudeText) ? [agents] : [claude, agents];
1035
+ }
1036
+ const files = [path5.join(os5.homedir(), ".claude", "CLAUDE.md")];
1037
+ for (const dir of [path5.join(os5.homedir(), ".codex"), path5.join(os5.homedir(), ".config", "opencode")]) {
1038
+ if (fs5.existsSync(dir)) files.push(path5.join(dir, "AGENTS.md"));
1039
+ }
1040
+ return files;
1041
+ }
1042
+ function writeBlock(file) {
1043
+ fs5.mkdirSync(path5.dirname(file), { recursive: true });
772
1044
  let text = "";
773
1045
  try {
774
- text = fs4.readFileSync(file, "utf8");
1046
+ text = fs5.readFileSync(file, "utf8");
775
1047
  } catch {
776
1048
  }
777
1049
  if (text.includes(CLAUDE_MD_START)) {
778
1050
  const re = new RegExp(`${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}`);
779
- text = text.replace(re, block);
1051
+ text = text.replace(re, BLOCK);
780
1052
  } else {
781
- text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
1053
+ text = (text.trimEnd() + "\n\n" + BLOCK + "\n").trimStart();
782
1054
  }
783
- fs4.writeFileSync(file, text);
784
- return file;
1055
+ fs5.writeFileSync(file, text);
1056
+ }
1057
+ function configureClaudeMd(scope, projectDir) {
1058
+ const files = instructionFiles(scope, projectDir);
1059
+ for (const f of files) writeBlock(f);
1060
+ return files;
785
1061
  }
786
1062
  function removeClaudeMd(scope, projectDir) {
787
- const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
788
- let text;
789
- try {
790
- text = fs4.readFileSync(file, "utf8");
791
- } catch {
792
- return null;
793
- }
794
- if (!text.includes(CLAUDE_MD_START)) return null;
795
- const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
796
- const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
797
- if (cleaned === "") {
798
- fs4.rmSync(file, { force: true });
799
- } else {
800
- fs4.writeFileSync(file, cleaned + "\n");
801
- }
802
- return file;
1063
+ const removed = [];
1064
+ for (const file of instructionFiles(scope, projectDir)) {
1065
+ let text;
1066
+ try {
1067
+ text = fs5.readFileSync(file, "utf8");
1068
+ } catch {
1069
+ continue;
1070
+ }
1071
+ if (!text.includes(CLAUDE_MD_START)) continue;
1072
+ const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
1073
+ const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
1074
+ if (cleaned === "") fs5.rmSync(file, { force: true });
1075
+ else fs5.writeFileSync(file, cleaned + "\n");
1076
+ removed.push(file);
1077
+ }
1078
+ return removed;
803
1079
  }
804
1080
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
805
1081
  function scanProject(vault, projectDir) {
806
- const name = path4.basename(projectDir);
807
- const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
808
- if (fs4.existsSync(mapFile)) return null;
1082
+ const name = path5.basename(projectDir);
1083
+ const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1084
+ if (fs5.existsSync(mapFile)) return null;
809
1085
  const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
810
1086
  try {
811
- const pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
1087
+ const pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
812
1088
  const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
813
1089
  const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
814
1090
  parts.push(`## Stack
@@ -827,13 +1103,13 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
827
1103
  if (depth > 2 || tree.length > 60) return;
828
1104
  let entries = [];
829
1105
  try {
830
- entries = fs4.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
1106
+ entries = fs5.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
831
1107
  } catch {
832
1108
  return;
833
1109
  }
834
1110
  for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
835
1111
  tree.push(`${prefix}${e.name}/`);
836
- walk(path4.join(dir, e.name), depth + 1, prefix + " ");
1112
+ walk(path5.join(dir, e.name), depth + 1, prefix + " ");
837
1113
  }
838
1114
  };
839
1115
  walk(projectDir, 1, "");
@@ -842,7 +1118,7 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
842
1118
  ${tree.join("\n")}
843
1119
  \`\`\``);
844
1120
  try {
845
- const readme = fs4.readFileSync(path4.join(projectDir, "README.md"), "utf8");
1121
+ const readme = fs5.readFileSync(path5.join(projectDir, "README.md"), "utf8");
846
1122
  parts.push(`## README (extracto)
847
1123
  ${readme.split("\n").slice(0, 15).join("\n")}`);
848
1124
  } catch {
@@ -858,8 +1134,8 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
858
1134
  }
859
1135
 
860
1136
  // src/core/scan.ts
861
- import fs5 from "fs";
862
- import path5 from "path";
1137
+ import fs6 from "fs";
1138
+ import path6 from "path";
863
1139
  var SKIP_DIRS2 = /* @__PURE__ */ new Set([
864
1140
  "node_modules",
865
1141
  ".git",
@@ -904,15 +1180,15 @@ function collectSourceFiles(projectDir) {
904
1180
  for (const dir of level) {
905
1181
  let entries = [];
906
1182
  try {
907
- entries = fs5.readdirSync(dir, { withFileTypes: true });
1183
+ entries = fs6.readdirSync(dir, { withFileTypes: true });
908
1184
  } catch {
909
1185
  continue;
910
1186
  }
911
1187
  for (const e of entries) {
912
1188
  if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
913
- const full = path5.join(dir, e.name);
1189
+ const full = path6.join(dir, e.name);
914
1190
  if (e.isDirectory()) next.push(full);
915
- else if (e.isFile() && SOURCE_EXT.has(path5.extname(e.name))) {
1191
+ else if (e.isFile() && SOURCE_EXT.has(path6.extname(e.name))) {
916
1192
  candidates.push(full);
917
1193
  if (candidates.length >= TRAVERSE_SAFETY) break;
918
1194
  }
@@ -925,7 +1201,7 @@ function collectSourceFiles(projectDir) {
925
1201
  if (candidates.length > MAX_FILES) {
926
1202
  const groups = /* @__PURE__ */ new Map();
927
1203
  for (const c of candidates) {
928
- const key = path5.relative(projectDir, c).split(path5.sep)[0];
1204
+ const key = path6.relative(projectDir, c).split(path6.sep)[0];
929
1205
  const g = groups.get(key);
930
1206
  if (g) g.push(c);
931
1207
  else groups.set(key, [c]);
@@ -947,10 +1223,10 @@ function collectSourceFiles(projectDir) {
947
1223
  const out = [];
948
1224
  for (const full of chosen) {
949
1225
  try {
950
- if (fs5.statSync(full).size > MAX_FILE_BYTES) continue;
1226
+ if (fs6.statSync(full).size > MAX_FILE_BYTES) continue;
951
1227
  out.push({
952
- rel: path5.relative(projectDir, full).split(path5.sep).join("/"),
953
- content: fs5.readFileSync(full, "utf8")
1228
+ rel: path6.relative(projectDir, full).split(path6.sep).join("/"),
1229
+ content: fs6.readFileSync(full, "utf8")
954
1230
  });
955
1231
  } catch {
956
1232
  }
@@ -1048,7 +1324,7 @@ function scanEnvNames(projectDir) {
1048
1324
  for (const file of [".env.example", ".env", ".env.local"]) {
1049
1325
  let text;
1050
1326
  try {
1051
- text = fs5.readFileSync(path5.join(projectDir, file), "utf8");
1327
+ text = fs6.readFileSync(path6.join(projectDir, file), "utf8");
1052
1328
  } catch {
1053
1329
  continue;
1054
1330
  }
@@ -1062,7 +1338,7 @@ function scanEnvNames(projectDir) {
1062
1338
  function scanDataSchema(projectDir, files) {
1063
1339
  const lines = [];
1064
1340
  try {
1065
- const schema = fs5.readFileSync(path5.join(projectDir, "prisma", "schema.prisma"), "utf8");
1341
+ const schema = fs6.readFileSync(path6.join(projectDir, "prisma", "schema.prisma"), "utf8");
1066
1342
  for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
1067
1343
  const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
1068
1344
  const shown = fields.slice(0, 8).join(", ");
@@ -1079,14 +1355,14 @@ function scanDataSchema(projectDir, files) {
1079
1355
  for (const dir of migDirs) {
1080
1356
  let sqlFiles = [];
1081
1357
  try {
1082
- sqlFiles = fs5.readdirSync(path5.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
1358
+ sqlFiles = fs6.readdirSync(path6.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
1083
1359
  } catch {
1084
1360
  continue;
1085
1361
  }
1086
1362
  const tables = /* @__PURE__ */ new Set();
1087
1363
  for (const f of sqlFiles) {
1088
1364
  try {
1089
- const sql = fs5.readFileSync(path5.join(projectDir, dir, f), "utf8");
1365
+ const sql = fs6.readFileSync(path6.join(projectDir, dir, f), "utf8");
1090
1366
  for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
1091
1367
  } catch {
1092
1368
  }
@@ -1097,17 +1373,17 @@ function scanDataSchema(projectDir, files) {
1097
1373
  }
1098
1374
  function scanConventions(projectDir) {
1099
1375
  const lines = [];
1100
- const has = (f) => fs5.existsSync(path5.join(projectDir, f));
1376
+ const has = (f) => fs6.existsSync(path6.join(projectDir, f));
1101
1377
  const pm = has("bun.lockb") || has("bun.lock") ? "bun" : has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("package-lock.json") ? "npm" : null;
1102
1378
  if (pm) lines.push(`- gestor de paquetes: ${pm}`);
1103
1379
  let pkg = {};
1104
1380
  try {
1105
- pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
1381
+ pkg = JSON.parse(fs6.readFileSync(path6.join(projectDir, "package.json"), "utf8"));
1106
1382
  } catch {
1107
1383
  }
1108
1384
  if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
1109
1385
  try {
1110
- const ts = JSON.parse(fs5.readFileSync(path5.join(projectDir, "tsconfig.json"), "utf8"));
1386
+ const ts = JSON.parse(fs6.readFileSync(path6.join(projectDir, "tsconfig.json"), "utf8"));
1111
1387
  const co = ts.compilerOptions ?? {};
1112
1388
  lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
1113
1389
  const paths = Object.keys(co.paths ?? {}).slice(0, 5);
@@ -1129,18 +1405,18 @@ function scanConventions(projectDir) {
1129
1405
  }
1130
1406
  function linkMapToScans(vault, name, titles) {
1131
1407
  if (titles.length === 0) return;
1132
- const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1408
+ const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1133
1409
  try {
1134
- const text = fs5.readFileSync(mapFile, "utf8");
1410
+ const text = fs6.readFileSync(mapFile, "utf8");
1135
1411
  if (text.includes("Contexto ampliado:")) return;
1136
- fs5.appendFileSync(mapFile, `
1412
+ fs6.appendFileSync(mapFile, `
1137
1413
  Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
1138
1414
  `);
1139
1415
  } catch {
1140
1416
  }
1141
1417
  }
1142
1418
  function scanAll(vault, projectDir) {
1143
- const name = path5.basename(projectDir);
1419
+ const name = path6.basename(projectDir);
1144
1420
  const gitignored = ensureGitignore(projectDir, vault.root) !== null;
1145
1421
  try {
1146
1422
  untrackPersonalConfigs(projectDir);
@@ -1215,7 +1491,16 @@ Proyecto: [[Mapa - ${name}]]`
1215
1491
  }
1216
1492
 
1217
1493
  // src/cli.ts
1218
- function registerAgentsMcp(agents, scope, cwd, portable = false) {
1494
+ function registerAgentHooks(agent, scope, cwd) {
1495
+ if (!agent.hooks || agent.hooks === "claude") return;
1496
+ const res = registerHarnessHooks(agent.hooks, scope, cwd);
1497
+ if (res.ok) {
1498
+ console.log(pc.green(`\u2713 Hooks \u2192 ${agent.name} (${res.file})`) + (res.detail ? pc.dim(` \u2014 ${res.detail}`) : ""));
1499
+ } else {
1500
+ console.log(pc.yellow(`\u26A0 Hooks \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
1501
+ }
1502
+ }
1503
+ function registerAgentsMcp(agents, scope, cwd, portable = false, hooks = true) {
1219
1504
  setPortableMode(portable);
1220
1505
  for (const agent of agents) {
1221
1506
  if (agent.id === "claude") {
@@ -1234,6 +1519,7 @@ function registerAgentsMcp(agents, scope, cwd, portable = false) {
1234
1519
  if (res.ok) {
1235
1520
  const note = effScope !== scope ? pc.dim(" [global: no soporta por-proyecto]") : "";
1236
1521
  console.log(pc.green(`\u2713 MCP \u2192 ${agent.name} (${res.file})`) + note);
1522
+ if (hooks) registerAgentHooks(agent, effScope, cwd);
1237
1523
  } else {
1238
1524
  console.log(pc.yellow(`\u26A0 MCP \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
1239
1525
  }
@@ -1277,7 +1563,7 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1277
1563
  ).action(async (opts) => {
1278
1564
  const isProject = Boolean(opts.project) && !opts.global;
1279
1565
  const cwd = process.cwd();
1280
- const vaultPath = path6.resolve(opts.path ?? (isProject ? path6.join(cwd, "Alexandria") : defaultVaultPath()));
1566
+ const vaultPath = path7.resolve(opts.path ?? (isProject ? path7.join(cwd, "Alexandria") : defaultVaultPath()));
1281
1567
  await showBanner();
1282
1568
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
1283
1569
  `));
@@ -1327,8 +1613,8 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1327
1613
  }
1328
1614
  }
1329
1615
  if (auto) {
1330
- const file = configureClaudeMd(isProject ? "project" : "global", cwd);
1331
- console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${file}`));
1616
+ const files = configureClaudeMd(isProject ? "project" : "global", cwd);
1617
+ console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${files.join(", ")}`));
1332
1618
  } else {
1333
1619
  console.log(pc.dim(" Sin auto-configuraci\xF3n (act\xEDvala luego con: ale init --auto)"));
1334
1620
  }
@@ -1358,27 +1644,27 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1358
1644
  const res = await idx.refresh();
1359
1645
  console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
1360
1646
  console.log(pc.bold(pc.green("\n\u2705 Listo. Abre una sesi\xF3n de tu agente y todo funciona solo \u2014 nada que reconectar nunca.")));
1361
- console.log(pc.dim(" Hooks (captura autom\xE1tica) solo en Claude Code; los dem\xE1s agentes usan las tools MCP."));
1647
+ console.log(pc.dim(" Captura autom\xE1tica (hooks): Claude Code, Codex, Gemini CLI, Cursor y OpenCode. El resto usa las tools MCP."));
1362
1648
  console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents'));
1363
1649
  console.log(pc.dim(" Controla qu\xE9 gasta tokens (antes o despu\xE9s de instalar): ale toggles\n"));
1364
1650
  if (opts.skills) await runSkills({ yes: false, project: isProject });
1365
1651
  });
1366
1652
  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) => {
1367
1653
  const { vault } = await ensureReady();
1368
- const abs = path6.resolve(file);
1369
- const raw = fs6.readFileSync(abs, "utf8");
1654
+ const abs = path7.resolve(file);
1655
+ const raw = fs7.readFileSync(abs, "utf8");
1370
1656
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
1371
- const title = opts.title ?? heading ?? path6.basename(abs).replace(/\.(md|txt)$/i, "");
1657
+ const title = opts.title ?? heading ?? path7.basename(abs).replace(/\.(md|txt)$/i, "");
1372
1658
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
1373
1659
  const noteFile = createNote(vault.managed, {
1374
1660
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
1375
1661
  type: "plan",
1376
1662
  status: "active",
1377
- tags: ["plan"],
1663
+ tags: ["plan", path7.basename(process.cwd())],
1378
1664
  content: raw.trim()
1379
1665
  });
1380
1666
  await VaultIndex.load(vault).refresh();
1381
- console.log(pc.green(`\u2713 Plan creado: ${path6.relative(vault.root, noteFile)}`));
1667
+ console.log(pc.green(`\u2713 Plan creado: ${path7.relative(vault.root, noteFile)}`));
1382
1668
  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)'}`));
1383
1669
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1384
1670
  const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
@@ -1440,44 +1726,67 @@ program.command("config").description("Configuraci\xF3n de Alexandria (ej. proto
1440
1726
  }
1441
1727
  console.log(pc.yellow("Acci\xF3n inv\xE1lida: usa get o set"));
1442
1728
  });
1443
- 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) => {
1729
+ async function runClean(opts) {
1444
1730
  const { vault, idx } = await ensureReady();
1445
- const cutoff = Date.now() - (parseInt(opts.days, 10) || 45) * 864e5;
1446
- const stale = Object.values(idx.meta.notes).filter(
1447
- (n) => n.type === "prompt" && (n.hits ?? 1) <= 1 && !n.rel.split("/").includes("archive") && n.created !== void 0 && Date.parse(n.created) < cutoff
1448
- );
1449
- if (stale.length === 0) {
1450
- console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
1731
+ const log = (m) => {
1732
+ if (!opts.quiet) console.log(m);
1733
+ };
1734
+ const plan = planClean(vault, Object.values(idx.meta.notes), {
1735
+ days: parseInt(opts.days, 10) || 45,
1736
+ keepNoise: opts.keepNoise
1737
+ });
1738
+ if (opts.promptsOnly) {
1739
+ plan.tmpFiles = [];
1740
+ plan.staleModels = [];
1741
+ }
1742
+ const nPrompts = [...plan.bundles.values()].reduce((s, l) => s + l.length, 0);
1743
+ const valuable = Object.values(idx.meta.notes).filter((n) => n.type !== "prompt").length;
1744
+ const before = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
1745
+ const mb = (b) => `${(b / 1024 / 1024).toFixed(1)} MB`;
1746
+ log(pc.bold("\n\u{1F9F9} Limpieza segura de la b\xF3veda") + pc.dim(` (${vault.root})`));
1747
+ log(pc.dim(` Intacto siempre: ${valuable} notas de conocimiento (lecciones, planes, mapas, sesiones, verificaciones, notas)`));
1748
+ log(` \u2022 ${nPrompts} prompts viejos sin reuso \u2192 ${plan.bundles.size} archivos compactados (texto \xEDntegro) en ${ARCHIVE_DIR}/`);
1749
+ log(` \u2022 ${plan.noise.length} prompts que inyect\xF3 el arn\xE9s (notificaciones/recordatorios) \u2192 ${opts.keepNoise ? "se compactan" : "se descartan"}`);
1750
+ if (plan.tmpFiles.length) log(` \u2022 ${plan.tmpFiles.length} temporales hu\xE9rfanos del \xEDndice`);
1751
+ if (plan.staleModels.length) log(` \u2022 ${plan.staleModels.length} modelos viejos en cach\xE9: ${plan.staleModels.map((m) => path7.basename(m)).join(", ")}`);
1752
+ if (plan.statsLinesToRotate) log(` \u2022 stats.jsonl: ${plan.statsLinesToRotate} l\xEDneas de >90 d\xEDas \u2192 resumen (los totales de \`ale stats\` no cambian)`);
1753
+ const nothing = nPrompts + plan.noise.length + plan.tmpFiles.length + plan.staleModels.length + plan.statsLinesToRotate === 0;
1754
+ if (nothing) {
1755
+ log(pc.dim("\n Nada que limpiar."));
1756
+ markCleaned(vault);
1451
1757
  return;
1452
1758
  }
1453
- const archiveDir = path6.join(vault.managed, "archive");
1454
- if (!opts.dry) fs6.mkdirSync(archiveDir, { recursive: true });
1455
- for (const n of stale) {
1456
- console.log(
1457
- `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
1458
- );
1459
- if (!opts.dry) {
1460
- fs6.renameSync(path6.join(vault.root, n.rel), path6.join(archiveDir, path6.basename(n.rel)));
1461
- }
1759
+ if (!opts.yes) {
1760
+ log(pc.dim("\n Vista previa (no se toc\xF3 nada). Aplica con: ale clean --yes \xB7 respaldo antes: --backup <archivo.tar.gz>\n"));
1761
+ return;
1462
1762
  }
1463
- if (!opts.dry) {
1464
- await VaultIndex.load(vault).refresh();
1465
- console.log(
1466
- pc.green(`
1467
- \u2713 ${stale.length} prompts archivados en ${path6.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1468
- );
1469
- } else {
1470
- console.log(pc.dim(`
1471
- ${stale.length} candidatos. Corre sin --dry para archivarlos.`));
1763
+ if (opts.backup) {
1764
+ const out = path7.resolve(opts.backup);
1765
+ execFileSync4("tar", ["-czf", out, "-C", vault.root, path7.relative(vault.root, vault.managed) || "."], { stdio: "ignore" });
1766
+ log(pc.green(`\u2713 Respaldo en ${out}`));
1472
1767
  }
1473
- });
1474
- 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) => {
1768
+ const res = applyClean(vault, plan);
1769
+ await VaultIndex.load(vault).refresh();
1770
+ markCleaned(vault);
1771
+ const after = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
1772
+ log(
1773
+ pc.green(
1774
+ `
1775
+ \u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados`
1776
+ )
1777
+ );
1778
+ log(pc.dim(` B\xF3veda ${mb(before.vault)} \u2192 ${mb(after.vault)} \xB7 \xEDndice ${mb(before.cache)} \u2192 ${mb(after.cache)}`));
1779
+ log(pc.dim(' Lo compactado sigue buscable: ale search --archive "<texto>"\n'));
1780
+ }
1781
+ program.command("clean").description("Limpieza segura: compacta prompts viejos sin reuso (texto \xEDntegro, fuera del \xEDndice), descarta ruido del arn\xE9s y purga cach\xE9s regenerables. Nunca toca lecciones, planes, mapas ni sesiones").option("--days <n>", "antig\xFCedad m\xEDnima de un prompt para compactarlo", "45").option("-y, --yes", "aplicar (sin esto solo muestra la vista previa)").option("--keep-noise", "compactar tambi\xE9n los prompts inyectados por el arn\xE9s en vez de descartarlos").option("--prompts-only", "solo compactar prompts (sin tocar cach\xE9s)").option("--backup <file>", "respaldo .tar.gz de la b\xF3veda antes de aplicar").option("--quiet", "sin salida (lo usa la limpieza autom\xE1tica)").action(runClean);
1782
+ program.command("consolidate").description("(alias de `ale clean --prompts-only`) compacta prompts viejos sin reuso").option("--days <n>", "antig\xFCedad m\xEDnima en d\xEDas", "45").option("--dry", "solo mostrar qu\xE9 se har\xEDa").action((opts) => runClean({ days: opts.days, yes: !opts.dry, promptsOnly: true }));
1783
+ 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").option("--no-hooks", "solo MCP, sin hooks de captura autom\xE1tica").action((ids, opts) => {
1475
1784
  if (!ids) {
1476
1785
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));
1477
1786
  for (const a of AGENTS) {
1478
1787
  const det = a.detect();
1479
1788
  console.log(
1480
- ` ${det ? pc.green("\u25CF") : pc.dim("\u25CB")} ${a.id.padEnd(9)} ${a.name}${det ? pc.green(" detectado") : pc.dim(" no detectado")}${a.supportsProject ? "" : pc.dim(" (solo global)")}`
1789
+ ` ${det ? pc.green("\u25CF") : pc.dim("\u25CB")} ${a.id.padEnd(9)} ${a.name.padEnd(26)}${a.hooks ? pc.cyan(" MCP+hooks") : pc.dim(" MCP ")}${det ? pc.green(" detectado") : pc.dim(" no detectado")}${a.supportsProject ? "" : pc.dim(" (solo global)")}${a.legacy ? pc.dim(" [legado]") : ""}`
1481
1790
  );
1482
1791
  }
1483
1792
  console.log(pc.dim("\n Registrar MCP: ale agents all \xB7 ale agents detected \xB7 ale agents cursor,opencode\n"));
@@ -1488,17 +1797,17 @@ program.command("agents").description("Lista los agentes de IA soportados y regi
1488
1797
  console.log(pc.yellow(`Ning\xFAn agente coincide con \xAB${ids}\xBB. Ids v\xE1lidos: ${AGENTS.map((a) => a.id).join(", ")}`));
1489
1798
  return;
1490
1799
  }
1491
- registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd());
1800
+ registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd(), false, opts.hooks);
1492
1801
  console.log(pc.dim("\n Reinicia el agente (o recarga sus MCP) para que tome el servidor.\n"));
1493
1802
  });
1494
1803
  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) => {
1495
1804
  const { vault } = await ensureReady();
1496
1805
  let content = opts.content;
1497
1806
  if (!content && opts.file) {
1498
- content = fs6.readFileSync(path6.resolve(opts.file), "utf8");
1807
+ content = fs7.readFileSync(path7.resolve(opts.file), "utf8");
1499
1808
  }
1500
1809
  if (!content && !process.stdin.isTTY) {
1501
- content = fs6.readFileSync(0, "utf8");
1810
+ content = fs7.readFileSync(0, "utf8");
1502
1811
  }
1503
1812
  const file = createNote(vault.managed, {
1504
1813
  title,
@@ -1506,15 +1815,26 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
1506
1815
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
1507
1816
  });
1508
1817
  await VaultIndex.load(vault).refresh();
1509
- console.log(pc.green(`\u2713 ${path6.relative(vault.root, file)}`));
1818
+ console.log(pc.green(`\u2713 ${path7.relative(vault.root, file)}`));
1510
1819
  });
1511
- 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) => {
1820
+ 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").option("--archive", "buscar en los prompts compactados por `ale clean` (keyword)").action(async (query, opts) => {
1512
1821
  const vault = getVault();
1513
1822
  if (!vaultExists(vault)) {
1514
1823
  console.log(pc.yellow("No hay b\xF3veda aqu\xED. Corre `ale init` primero."));
1515
1824
  return;
1516
1825
  }
1517
1826
  const q = query.join(" ");
1827
+ if (opts.archive) {
1828
+ const hits = searchArchive(vault, q, parseInt(opts.k, 10) || 6);
1829
+ if (hits.length === 0) console.log(pc.dim("Sin resultados en el archivo."));
1830
+ for (const h of hits) {
1831
+ console.log(`
1832
+ ${pc.bold(pc.cyan(h.heading))} ${pc.dim(`(${h.file})`)}`);
1833
+ console.log(pc.dim(" " + h.excerpt.replace(/\n+/g, " ").slice(0, 300)));
1834
+ }
1835
+ console.log();
1836
+ return;
1837
+ }
1518
1838
  const results = await hybridSearch(vault, q, parseInt(opts.k, 10) || 6, { expand: opts.expand });
1519
1839
  if (results.length === 0) {
1520
1840
  console.log(pc.dim("Sin resultados."));
@@ -1600,7 +1920,7 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1600
1920
  console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
1601
1921
  }
1602
1922
  if (s.notes.length) {
1603
- for (const n of s.notes) console.log(pc.dim(` ${path6.relative(vault.root, n)}`));
1923
+ for (const n of s.notes) console.log(pc.dim(` ${path7.relative(vault.root, n)}`));
1604
1924
  } else {
1605
1925
  console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1606
1926
  }
@@ -1661,7 +1981,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1661
1981
  async function runSkills(opts) {
1662
1982
  const { vault } = await ensureReady();
1663
1983
  const cwd = process.cwd();
1664
- const targetDir = opts.project ? path6.join(cwd, ".claude", "skills") : path6.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1984
+ const targetDir = opts.project ? path7.join(cwd, ".claude", "skills") : path7.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1665
1985
  const recs = await recommendSkills(vault, [targetDir]);
1666
1986
  if (recs.length === 0) {
1667
1987
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -1703,7 +2023,7 @@ program.command("skills").description("Analiza la b\xF3veda y recomienda/instala
1703
2023
  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) => {
1704
2024
  const { vault } = await ensureReady();
1705
2025
  const cwd = process.cwd();
1706
- const proj = path6.basename(cwd);
2026
+ const proj = path7.basename(cwd);
1707
2027
  const targetDir = skillTargetDir(cwd, Boolean(opts.global));
1708
2028
  const result = evolveSkill(vault, proj, targetDir);
1709
2029
  if (!result) {
@@ -1790,10 +2110,10 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1790
2110
  );
1791
2111
  }
1792
2112
  try {
1793
- const name = path6.basename(cwd);
1794
- const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1795
- const pkgM = fs6.statSync(path6.join(cwd, "package.json")).mtimeMs;
1796
- const mapM = fs6.statSync(mapFile).mtimeMs;
2113
+ const name = path7.basename(cwd);
2114
+ const mapFile = path7.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
2115
+ const pkgM = fs7.statSync(path7.join(cwd, "package.json")).mtimeMs;
2116
+ const mapM = fs7.statSync(mapFile).mtimeMs;
1797
2117
  if (pkgM > mapM) {
1798
2118
  console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1799
2119
  } else {
@@ -1801,41 +2121,44 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1801
2121
  }
1802
2122
  } catch {
1803
2123
  }
2124
+ const all = Object.values(idx.meta.notes);
2125
+ const prompts = all.filter((n) => n.type === "prompt").length;
2126
+ if (prompts > 5 * Math.max(1, all.length - prompts)) {
2127
+ console.log(pc.yellow(`\u26A0 ${prompts} prompts vs ${all.length - prompts} notas de conocimiento \u2014 corre \`ale clean\` (vista previa, no borra nada sin --yes)`));
2128
+ }
1804
2129
  const skillsRepoCfg = localSkillsRepo();
1805
- if (skillsRepoCfg && !fs6.existsSync(skillsRepoCfg)) {
2130
+ if (skillsRepoCfg && !fs7.existsSync(skillsRepoCfg)) {
1806
2131
  console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1807
2132
  }
1808
2133
  console.log();
1809
2134
  });
1810
- program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloque de CLAUDE.md y MCP del proyecto (no borra la b\xF3veda ni las notas)").option("--project", "quitar del proyecto (cwd)").action((opts) => {
2135
+ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloques de CLAUDE.md/AGENTS.md y MCP de todos los agentes (no borra la b\xF3veda ni las notas)").option("--project", "quitar del proyecto (cwd)").action((opts) => {
1811
2136
  const cwd = process.cwd();
1812
2137
  const scope = opts.project ? "project" : "global";
1813
2138
  const settings = opts.project ? projectSettingsPath(cwd) : globalSettingsPath();
1814
2139
  unregisterHooks(settings);
1815
2140
  console.log(pc.green(`\u2713 Hooks de alexandria eliminados de ${settings}`));
1816
- const claudeMd = removeClaudeMd(scope, cwd);
1817
- if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
1818
- if (opts.project) {
1819
- const mcpFile = path6.join(cwd, ".mcp.json");
1820
- try {
1821
- const cfg = JSON.parse(fs6.readFileSync(mcpFile, "utf8"));
1822
- if (cfg.mcpServers?.alexandria) {
1823
- delete cfg.mcpServers.alexandria;
1824
- if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
1825
- if (Object.keys(cfg).length === 0) fs6.rmSync(mcpFile, { force: true });
1826
- else fs6.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1827
- console.log(pc.green("\u2713 MCP removido de .mcp.json"));
1828
- }
1829
- } catch {
1830
- }
1831
- console.log(pc.dim(' Otros agentes (Cursor/OpenCode/\u2026): quita "alexandria" de su config si lo registraste.'));
1832
- } else {
1833
- console.log(pc.dim(" MCP global: qu\xEDtalo con `claude mcp remove alexandria`. Tus notas quedan intactas."));
2141
+ for (const f of removeClaudeMd(scope, cwd)) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${f}`));
2142
+ for (const agent of AGENTS) {
2143
+ if (agent.unregister?.(scope, cwd)) console.log(pc.green(`\u2713 MCP removido de ${agent.name}`));
2144
+ }
2145
+ for (const h of HOOK_HARNESSES) {
2146
+ if (unregisterHarnessHooks(h, scope, cwd)) console.log(pc.green(`\u2713 Hooks removidos de ${h}`));
2147
+ }
2148
+ if (!opts.project) {
2149
+ console.log(pc.dim(" Hermes: qu\xEDtalo con `hermes mcp remove alexandria` si lo registraste. Tus notas quedan intactas."));
1834
2150
  }
1835
2151
  });
1836
2152
  program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
1837
2153
  await import("./mcp/server.js");
1838
2154
  });
2155
+ program.command("hook").description("Corre un hook (lo usan los plugins de Claude Code/Codex): session-start | prompt | stop").argument("<event>", "session-start | prompt | stop").option("--harness <id>", "claude | codex | gemini | cursor | opencode", "claude").action(async (event) => {
2156
+ const i = process.argv.indexOf("--harness");
2157
+ if (i > -1 && process.argv[i + 1]) process.argv.push(`--harness=${process.argv[i + 1]}`);
2158
+ if (event === "session-start") await import("./hooks/on-session-start.js");
2159
+ else if (event === "prompt") await import("./hooks/on-prompt.js");
2160
+ else if (event === "stop") await import("./hooks/on-stop.js");
2161
+ });
1839
2162
  if (process.argv.length <= 2) {
1840
2163
  await showBanner();
1841
2164
  program.outputHelp();