@ureck/alexandria 1.3.2 → 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,34 +14,44 @@ import {
16
14
  registerMcpProject,
17
15
  serverCommand,
18
16
  unregisterHooks
19
- } from "./chunk-ZIQYAQCF.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,
27
33
  ensureVaultStructure,
28
34
  getConfigKey,
29
35
  globalConfigPath,
36
+ initScopeWarning,
30
37
  protocolEnabled,
38
+ readStats,
31
39
  resolveVault,
32
40
  setConfigKey,
33
41
  toggleEnabled,
34
42
  vaultExists,
35
43
  writeGlobalConfig,
36
44
  writeProjectConfig
37
- } from "./chunk-CIOCSIB5.js";
45
+ } from "./chunk-MDGFK6UC.js";
38
46
  import {
39
47
  serveGraph
40
- } from "./chunk-FBGIFNIO.js";
48
+ } from "./chunk-4ZSTD3CU.js";
41
49
  import {
42
50
  VaultIndex,
43
51
  createNote,
44
52
  slugify,
45
53
  upsertNote
46
- } from "./chunk-QB37UGO6.js";
54
+ } from "./chunk-3CB7GRFJ.js";
47
55
  import {
48
56
  MODEL_ID,
49
57
  dot,
@@ -53,9 +61,10 @@ import {
53
61
  } from "./chunk-EDYBSJSS.js";
54
62
 
55
63
  // src/cli.ts
56
- import fs6 from "fs";
57
- import path6 from "path";
64
+ import fs7 from "fs";
65
+ import path7 from "path";
58
66
  import readline from "readline/promises";
67
+ import { execFileSync as execFileSync4 } from "child_process";
59
68
  import { Command } from "commander";
60
69
  import pc from "picocolors";
61
70
 
@@ -258,7 +267,7 @@ ${items}
258
267
  }
259
268
  let body = parts.join("\n");
260
269
  if (body.length > MAX_BODY_CHARS) body = body.slice(0, MAX_BODY_CHARS) + "\n\n\u2026(truncado)\n";
261
- const skillName = `proyecto-${slug}`;
270
+ const skillName = slug.startsWith("proyecto-") ? slug : `proyecto-${slug}`;
262
271
  const desc = `Conocimiento vivo del proyecto ${projectName}: stack, convenciones, flujo de la aplicaci\xF3n y lecciones ya aprendidas. \xDAsala al trabajar en ${projectName} \u2014 antes de explorar el c\xF3digo o decidir arquitectura.`;
263
272
  const front = [
264
273
  "---",
@@ -366,6 +375,18 @@ function mergeMcpServers(file, key = "mcpServers") {
366
375
  return { ok: false, file, detail: e.message };
367
376
  }
368
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
+ }
369
390
  function home(...p) {
370
391
  return path3.join(os3.homedir(), ...p);
371
392
  }
@@ -418,6 +439,8 @@ var AGENTS = [
418
439
  name: "Claude Code",
419
440
  supportsProject: true,
420
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")),
421
444
  register(scope, projectDir) {
422
445
  if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
423
446
  return mergeMcpServers(home(".claude.json"));
@@ -428,6 +451,8 @@ var AGENTS = [
428
451
  name: "Cursor",
429
452
  supportsProject: true,
430
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")),
431
456
  register(scope, projectDir) {
432
457
  const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
433
458
  return mergeMcpServers(file);
@@ -438,6 +463,8 @@ var AGENTS = [
438
463
  name: "OpenCode",
439
464
  supportsProject: true,
440
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"),
441
468
  register(scope, projectDir) {
442
469
  const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
443
470
  try {
@@ -458,6 +485,8 @@ var AGENTS = [
458
485
  name: "Windsurf (legacy \u2192 Devin)",
459
486
  supportsProject: false,
460
487
  detect: () => fs3.existsSync(home(".codeium", "windsurf")),
488
+ legacy: true,
489
+ unregister: () => removeMcpEntry(home(".codeium", "windsurf", "mcp_config.json")),
461
490
  register() {
462
491
  return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
463
492
  }
@@ -468,6 +497,7 @@ var AGENTS = [
468
497
  supportsProject: true,
469
498
  // El CLI vive en ~/.local/bin/devin y guarda config MCP por proyecto en .devin/
470
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")),
471
501
  register(scope, projectDir) {
472
502
  const dir = scope === "project" ? projectDir : home();
473
503
  const file = path3.join(dir, ".devin", "mcp_config.local.json");
@@ -488,6 +518,7 @@ var AGENTS = [
488
518
  name: "Cline (VS Code)",
489
519
  supportsProject: false,
490
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")),
491
522
  register() {
492
523
  const file = path3.join(
493
524
  vscodeUserDir(),
@@ -502,14 +533,27 @@ var AGENTS = [
502
533
  {
503
534
  id: "codex",
504
535
  name: "Codex CLI (OpenAI)",
505
- supportsProject: false,
536
+ // Codex lee también <repo>/.codex/config.toml cuando el proyecto es de confianza
537
+ supportsProject: true,
506
538
  detect: () => fs3.existsSync(home(".codex")),
507
- register() {
508
- const file = home(".codex", "config.toml");
509
- 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();
510
554
  const tomlArgs = args.map((a) => `"${a.replace(/\\/g, "\\\\")}"`).join(", ");
511
555
  const block = `[mcp_servers.alexandria]
512
- command = "${command}"
556
+ command = "${command2}"
513
557
  args = [${tomlArgs}]
514
558
  `;
515
559
  try {
@@ -532,6 +576,8 @@ args = [${tomlArgs}]
532
576
  name: "Gemini CLI",
533
577
  supportsProject: true,
534
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")),
535
581
  register(scope, projectDir) {
536
582
  const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
537
583
  return mergeMcpServers(file);
@@ -542,6 +588,7 @@ args = [${tomlArgs}]
542
588
  name: "OpenClaw",
543
589
  supportsProject: false,
544
590
  detect: () => fs3.existsSync(home(".openclaw")),
591
+ unregister: () => removeMcpEntry(home(".openclaw", "openclaw.json")),
545
592
  register() {
546
593
  const file = home(".openclaw", "openclaw.json");
547
594
  try {
@@ -566,7 +613,9 @@ args = [${tomlArgs}]
566
613
  try {
567
614
  execFileSync2("hermes", ["mcp", "add", "alexandria", "--command", serverCmd().command, "--args", serverCmd().args.join(" ")], {
568
615
  stdio: "pipe",
569
- timeout: 15e3
616
+ timeout: 15e3,
617
+ shell: process.platform === "win32"
618
+ // en Windows los binarios globales de npm son shims .cmd/.ps1
570
619
  });
571
620
  return { ok: true, file, detail: "v\xEDa hermes mcp add" };
572
621
  } catch {
@@ -609,6 +658,7 @@ ${entry.trimEnd()}`);
609
658
  // Chat instalada. Antes bastaba con que existiera el User dir, así que
610
659
  // cualquiera con VS Code aparecía como agente detectado aunque no use MCP.
611
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"),
612
662
  register(scope, projectDir) {
613
663
  const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
614
664
  try {
@@ -634,6 +684,210 @@ function resolveAgents(spec) {
634
684
  return s.split(",").map((id) => agentById(id)).filter((a) => Boolean(a));
635
685
  }
636
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
+
637
891
  // src/cli/banner.ts
638
892
  var ART = [
639
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",
@@ -695,9 +949,9 @@ async function showBanner(animate) {
695
949
  }
696
950
 
697
951
  // src/core/setup.ts
698
- import fs4 from "fs";
699
- import os4 from "os";
700
- import path4 from "path";
952
+ import fs5 from "fs";
953
+ import os5 from "os";
954
+ import path5 from "path";
701
955
  import { execFileSync as execFileSync3 } from "child_process";
702
956
  var PERSONAL_CONFIG_FILES = [
703
957
  ".vault.json",
@@ -706,18 +960,23 @@ var PERSONAL_CONFIG_FILES = [
706
960
  "opencode.json",
707
961
  ".vscode/mcp.json",
708
962
  ".gemini/settings.json",
709
- ".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"
710
969
  ];
711
970
  function ensureGitignore(projectDir, vaultRoot) {
712
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return null;
971
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return null;
713
972
  const entries = [];
714
- const rel = path4.relative(projectDir, vaultRoot);
715
- 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("/")}/`);
716
975
  entries.push(...PERSONAL_CONFIG_FILES);
717
- const file = path4.join(projectDir, ".gitignore");
976
+ const file = path5.join(projectDir, ".gitignore");
718
977
  let text = "";
719
978
  try {
720
- text = fs4.readFileSync(file, "utf8");
979
+ text = fs5.readFileSync(file, "utf8");
721
980
  } catch {
722
981
  }
723
982
  const has = (e) => text.split("\n").some((l) => l.trim() === e || l.trim() === e.replace(/\/$/, ""));
@@ -728,14 +987,14 @@ function ensureGitignore(projectDir, vaultRoot) {
728
987
  # Alexandria (conocimiento y config personal \u2014 no del repo)
729
988
  ${missing.join("\n")}
730
989
  `;
731
- fs4.writeFileSync(file, text.trim() ? block : block.trimStart());
990
+ fs5.writeFileSync(file, text.trim() ? block : block.trimStart());
732
991
  return file;
733
992
  }
734
993
  function untrackPersonalConfigs(projectDir) {
735
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return [];
994
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return [];
736
995
  const untracked = [];
737
996
  for (const f of PERSONAL_CONFIG_FILES) {
738
- if (!fs4.existsSync(path4.join(projectDir, f))) continue;
997
+ if (!fs5.existsSync(path5.join(projectDir, f))) continue;
739
998
  try {
740
999
  const tracked = execFileSync3("git", ["ls-files", "--error-unmatch", f], {
741
1000
  cwd: projectDir,
@@ -752,60 +1011,80 @@ function untrackPersonalConfigs(projectDir) {
752
1011
  }
753
1012
  var CLAUDE_MD_START = "<!-- alexandria:start -->";
754
1013
  var CLAUDE_MD_END = "<!-- alexandria:end -->";
755
- function configureClaudeMd(scope, projectDir) {
756
- const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
757
- const block = [
758
- CLAUDE_MD_START,
759
- "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
760
- "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
761
- "- 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.",
762
- "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
763
- "- 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.",
764
- "- 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.",
765
- "- `vault_related` trae conocimiento conectado sin releer archivos.",
766
- CLAUDE_MD_END
767
- ].join("\n");
768
- 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 });
769
1044
  let text = "";
770
1045
  try {
771
- text = fs4.readFileSync(file, "utf8");
1046
+ text = fs5.readFileSync(file, "utf8");
772
1047
  } catch {
773
1048
  }
774
1049
  if (text.includes(CLAUDE_MD_START)) {
775
1050
  const re = new RegExp(`${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}`);
776
- text = text.replace(re, block);
1051
+ text = text.replace(re, BLOCK);
777
1052
  } else {
778
- text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
1053
+ text = (text.trimEnd() + "\n\n" + BLOCK + "\n").trimStart();
779
1054
  }
780
- fs4.writeFileSync(file, text);
781
- 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;
782
1061
  }
783
1062
  function removeClaudeMd(scope, projectDir) {
784
- const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
785
- let text;
786
- try {
787
- text = fs4.readFileSync(file, "utf8");
788
- } catch {
789
- return null;
790
- }
791
- if (!text.includes(CLAUDE_MD_START)) return null;
792
- const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
793
- const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
794
- if (cleaned === "") {
795
- fs4.rmSync(file, { force: true });
796
- } else {
797
- fs4.writeFileSync(file, cleaned + "\n");
798
- }
799
- 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;
800
1079
  }
801
1080
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
802
1081
  function scanProject(vault, projectDir) {
803
- const name = path4.basename(projectDir);
804
- const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
805
- 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;
806
1085
  const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
807
1086
  try {
808
- 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"));
809
1088
  const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
810
1089
  const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
811
1090
  parts.push(`## Stack
@@ -824,13 +1103,13 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
824
1103
  if (depth > 2 || tree.length > 60) return;
825
1104
  let entries = [];
826
1105
  try {
827
- 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));
828
1107
  } catch {
829
1108
  return;
830
1109
  }
831
1110
  for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
832
1111
  tree.push(`${prefix}${e.name}/`);
833
- walk(path4.join(dir, e.name), depth + 1, prefix + " ");
1112
+ walk(path5.join(dir, e.name), depth + 1, prefix + " ");
834
1113
  }
835
1114
  };
836
1115
  walk(projectDir, 1, "");
@@ -839,7 +1118,7 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
839
1118
  ${tree.join("\n")}
840
1119
  \`\`\``);
841
1120
  try {
842
- const readme = fs4.readFileSync(path4.join(projectDir, "README.md"), "utf8");
1121
+ const readme = fs5.readFileSync(path5.join(projectDir, "README.md"), "utf8");
843
1122
  parts.push(`## README (extracto)
844
1123
  ${readme.split("\n").slice(0, 15).join("\n")}`);
845
1124
  } catch {
@@ -855,8 +1134,8 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
855
1134
  }
856
1135
 
857
1136
  // src/core/scan.ts
858
- import fs5 from "fs";
859
- import path5 from "path";
1137
+ import fs6 from "fs";
1138
+ import path6 from "path";
860
1139
  var SKIP_DIRS2 = /* @__PURE__ */ new Set([
861
1140
  "node_modules",
862
1141
  ".git",
@@ -901,15 +1180,15 @@ function collectSourceFiles(projectDir) {
901
1180
  for (const dir of level) {
902
1181
  let entries = [];
903
1182
  try {
904
- entries = fs5.readdirSync(dir, { withFileTypes: true });
1183
+ entries = fs6.readdirSync(dir, { withFileTypes: true });
905
1184
  } catch {
906
1185
  continue;
907
1186
  }
908
1187
  for (const e of entries) {
909
1188
  if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
910
- const full = path5.join(dir, e.name);
1189
+ const full = path6.join(dir, e.name);
911
1190
  if (e.isDirectory()) next.push(full);
912
- else if (e.isFile() && SOURCE_EXT.has(path5.extname(e.name))) {
1191
+ else if (e.isFile() && SOURCE_EXT.has(path6.extname(e.name))) {
913
1192
  candidates.push(full);
914
1193
  if (candidates.length >= TRAVERSE_SAFETY) break;
915
1194
  }
@@ -922,7 +1201,7 @@ function collectSourceFiles(projectDir) {
922
1201
  if (candidates.length > MAX_FILES) {
923
1202
  const groups = /* @__PURE__ */ new Map();
924
1203
  for (const c of candidates) {
925
- const key = path5.relative(projectDir, c).split(path5.sep)[0];
1204
+ const key = path6.relative(projectDir, c).split(path6.sep)[0];
926
1205
  const g = groups.get(key);
927
1206
  if (g) g.push(c);
928
1207
  else groups.set(key, [c]);
@@ -944,10 +1223,10 @@ function collectSourceFiles(projectDir) {
944
1223
  const out = [];
945
1224
  for (const full of chosen) {
946
1225
  try {
947
- if (fs5.statSync(full).size > MAX_FILE_BYTES) continue;
1226
+ if (fs6.statSync(full).size > MAX_FILE_BYTES) continue;
948
1227
  out.push({
949
- rel: path5.relative(projectDir, full).split(path5.sep).join("/"),
950
- content: fs5.readFileSync(full, "utf8")
1228
+ rel: path6.relative(projectDir, full).split(path6.sep).join("/"),
1229
+ content: fs6.readFileSync(full, "utf8")
951
1230
  });
952
1231
  } catch {
953
1232
  }
@@ -1045,7 +1324,7 @@ function scanEnvNames(projectDir) {
1045
1324
  for (const file of [".env.example", ".env", ".env.local"]) {
1046
1325
  let text;
1047
1326
  try {
1048
- text = fs5.readFileSync(path5.join(projectDir, file), "utf8");
1327
+ text = fs6.readFileSync(path6.join(projectDir, file), "utf8");
1049
1328
  } catch {
1050
1329
  continue;
1051
1330
  }
@@ -1059,7 +1338,7 @@ function scanEnvNames(projectDir) {
1059
1338
  function scanDataSchema(projectDir, files) {
1060
1339
  const lines = [];
1061
1340
  try {
1062
- const schema = fs5.readFileSync(path5.join(projectDir, "prisma", "schema.prisma"), "utf8");
1341
+ const schema = fs6.readFileSync(path6.join(projectDir, "prisma", "schema.prisma"), "utf8");
1063
1342
  for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
1064
1343
  const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
1065
1344
  const shown = fields.slice(0, 8).join(", ");
@@ -1076,14 +1355,14 @@ function scanDataSchema(projectDir, files) {
1076
1355
  for (const dir of migDirs) {
1077
1356
  let sqlFiles = [];
1078
1357
  try {
1079
- 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);
1080
1359
  } catch {
1081
1360
  continue;
1082
1361
  }
1083
1362
  const tables = /* @__PURE__ */ new Set();
1084
1363
  for (const f of sqlFiles) {
1085
1364
  try {
1086
- const sql = fs5.readFileSync(path5.join(projectDir, dir, f), "utf8");
1365
+ const sql = fs6.readFileSync(path6.join(projectDir, dir, f), "utf8");
1087
1366
  for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
1088
1367
  } catch {
1089
1368
  }
@@ -1094,17 +1373,17 @@ function scanDataSchema(projectDir, files) {
1094
1373
  }
1095
1374
  function scanConventions(projectDir) {
1096
1375
  const lines = [];
1097
- const has = (f) => fs5.existsSync(path5.join(projectDir, f));
1376
+ const has = (f) => fs6.existsSync(path6.join(projectDir, f));
1098
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;
1099
1378
  if (pm) lines.push(`- gestor de paquetes: ${pm}`);
1100
1379
  let pkg = {};
1101
1380
  try {
1102
- pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
1381
+ pkg = JSON.parse(fs6.readFileSync(path6.join(projectDir, "package.json"), "utf8"));
1103
1382
  } catch {
1104
1383
  }
1105
1384
  if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
1106
1385
  try {
1107
- 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"));
1108
1387
  const co = ts.compilerOptions ?? {};
1109
1388
  lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
1110
1389
  const paths = Object.keys(co.paths ?? {}).slice(0, 5);
@@ -1126,18 +1405,18 @@ function scanConventions(projectDir) {
1126
1405
  }
1127
1406
  function linkMapToScans(vault, name, titles) {
1128
1407
  if (titles.length === 0) return;
1129
- const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1408
+ const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1130
1409
  try {
1131
- const text = fs5.readFileSync(mapFile, "utf8");
1410
+ const text = fs6.readFileSync(mapFile, "utf8");
1132
1411
  if (text.includes("Contexto ampliado:")) return;
1133
- fs5.appendFileSync(mapFile, `
1412
+ fs6.appendFileSync(mapFile, `
1134
1413
  Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
1135
1414
  `);
1136
1415
  } catch {
1137
1416
  }
1138
1417
  }
1139
1418
  function scanAll(vault, projectDir) {
1140
- const name = path5.basename(projectDir);
1419
+ const name = path6.basename(projectDir);
1141
1420
  const gitignored = ensureGitignore(projectDir, vault.root) !== null;
1142
1421
  try {
1143
1422
  untrackPersonalConfigs(projectDir);
@@ -1212,7 +1491,16 @@ Proyecto: [[Mapa - ${name}]]`
1212
1491
  }
1213
1492
 
1214
1493
  // src/cli.ts
1215
- 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) {
1216
1504
  setPortableMode(portable);
1217
1505
  for (const agent of agents) {
1218
1506
  if (agent.id === "claude") {
@@ -1231,6 +1519,7 @@ function registerAgentsMcp(agents, scope, cwd, portable = false) {
1231
1519
  if (res.ok) {
1232
1520
  const note = effScope !== scope ? pc.dim(" [global: no soporta por-proyecto]") : "";
1233
1521
  console.log(pc.green(`\u2713 MCP \u2192 ${agent.name} (${res.file})`) + note);
1522
+ if (hooks) registerAgentHooks(agent, effScope, cwd);
1234
1523
  } else {
1235
1524
  console.log(pc.yellow(`\u26A0 MCP \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
1236
1525
  }
@@ -1274,10 +1563,12 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1274
1563
  ).action(async (opts) => {
1275
1564
  const isProject = Boolean(opts.project) && !opts.global;
1276
1565
  const cwd = process.cwd();
1277
- 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()));
1278
1567
  await showBanner();
1279
1568
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
1280
1569
  `));
1570
+ const scopeWarning = initScopeWarning(opts);
1571
+ if (scopeWarning) console.log(pc.yellow(scopeWarning));
1281
1572
  const vault = resolveVault({ flag: vaultPath });
1282
1573
  ensureVaultStructure(vault);
1283
1574
  console.log(pc.green(`\u2713 B\xF3veda en ${vault.root} (vault Obsidian v\xE1lido \u2014 \xE1brelo en Obsidian cuando quieras)`));
@@ -1322,8 +1613,8 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1322
1613
  }
1323
1614
  }
1324
1615
  if (auto) {
1325
- const file = configureClaudeMd(isProject ? "project" : "global", cwd);
1326
- 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(", ")}`));
1327
1618
  } else {
1328
1619
  console.log(pc.dim(" Sin auto-configuraci\xF3n (act\xEDvala luego con: ale init --auto)"));
1329
1620
  }
@@ -1353,27 +1644,27 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1353
1644
  const res = await idx.refresh();
1354
1645
  console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
1355
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.")));
1356
- 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."));
1357
1648
  console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents'));
1358
1649
  console.log(pc.dim(" Controla qu\xE9 gasta tokens (antes o despu\xE9s de instalar): ale toggles\n"));
1359
1650
  if (opts.skills) await runSkills({ yes: false, project: isProject });
1360
1651
  });
1361
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) => {
1362
1653
  const { vault } = await ensureReady();
1363
- const abs = path6.resolve(file);
1364
- const raw = fs6.readFileSync(abs, "utf8");
1654
+ const abs = path7.resolve(file);
1655
+ const raw = fs7.readFileSync(abs, "utf8");
1365
1656
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
1366
- 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, "");
1367
1658
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
1368
1659
  const noteFile = createNote(vault.managed, {
1369
1660
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
1370
1661
  type: "plan",
1371
1662
  status: "active",
1372
- tags: ["plan"],
1663
+ tags: ["plan", path7.basename(process.cwd())],
1373
1664
  content: raw.trim()
1374
1665
  });
1375
1666
  await VaultIndex.load(vault).refresh();
1376
- 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)}`));
1377
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)'}`));
1378
1669
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1379
1670
  const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
@@ -1435,44 +1726,67 @@ program.command("config").description("Configuraci\xF3n de Alexandria (ej. proto
1435
1726
  }
1436
1727
  console.log(pc.yellow("Acci\xF3n inv\xE1lida: usa get o set"));
1437
1728
  });
1438
- 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) {
1439
1730
  const { vault, idx } = await ensureReady();
1440
- const cutoff = Date.now() - (parseInt(opts.days, 10) || 45) * 864e5;
1441
- const stale = Object.values(idx.meta.notes).filter(
1442
- (n) => n.type === "prompt" && (n.hits ?? 1) <= 1 && !n.rel.split("/").includes("archive") && n.created !== void 0 && Date.parse(n.created) < cutoff
1443
- );
1444
- if (stale.length === 0) {
1445
- 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);
1446
1757
  return;
1447
1758
  }
1448
- const archiveDir = path6.join(vault.managed, "archive");
1449
- if (!opts.dry) fs6.mkdirSync(archiveDir, { recursive: true });
1450
- for (const n of stale) {
1451
- console.log(
1452
- `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
1453
- );
1454
- if (!opts.dry) {
1455
- fs6.renameSync(path6.join(vault.root, n.rel), path6.join(archiveDir, path6.basename(n.rel)));
1456
- }
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;
1457
1762
  }
1458
- if (!opts.dry) {
1459
- await VaultIndex.load(vault).refresh();
1460
- console.log(
1461
- pc.green(`
1462
- \u2713 ${stale.length} prompts archivados en ${path6.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1463
- );
1464
- } else {
1465
- console.log(pc.dim(`
1466
- ${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}`));
1467
1767
  }
1468
- });
1469
- 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) => {
1470
1784
  if (!ids) {
1471
1785
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));
1472
1786
  for (const a of AGENTS) {
1473
1787
  const det = a.detect();
1474
1788
  console.log(
1475
- ` ${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]") : ""}`
1476
1790
  );
1477
1791
  }
1478
1792
  console.log(pc.dim("\n Registrar MCP: ale agents all \xB7 ale agents detected \xB7 ale agents cursor,opencode\n"));
@@ -1483,17 +1797,17 @@ program.command("agents").description("Lista los agentes de IA soportados y regi
1483
1797
  console.log(pc.yellow(`Ning\xFAn agente coincide con \xAB${ids}\xBB. Ids v\xE1lidos: ${AGENTS.map((a) => a.id).join(", ")}`));
1484
1798
  return;
1485
1799
  }
1486
- registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd());
1800
+ registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd(), false, opts.hooks);
1487
1801
  console.log(pc.dim("\n Reinicia el agente (o recarga sus MCP) para que tome el servidor.\n"));
1488
1802
  });
1489
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) => {
1490
1804
  const { vault } = await ensureReady();
1491
1805
  let content = opts.content;
1492
1806
  if (!content && opts.file) {
1493
- content = fs6.readFileSync(path6.resolve(opts.file), "utf8");
1807
+ content = fs7.readFileSync(path7.resolve(opts.file), "utf8");
1494
1808
  }
1495
1809
  if (!content && !process.stdin.isTTY) {
1496
- content = fs6.readFileSync(0, "utf8");
1810
+ content = fs7.readFileSync(0, "utf8");
1497
1811
  }
1498
1812
  const file = createNote(vault.managed, {
1499
1813
  title,
@@ -1501,15 +1815,26 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
1501
1815
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
1502
1816
  });
1503
1817
  await VaultIndex.load(vault).refresh();
1504
- console.log(pc.green(`\u2713 ${path6.relative(vault.root, file)}`));
1818
+ console.log(pc.green(`\u2713 ${path7.relative(vault.root, file)}`));
1505
1819
  });
1506
- 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) => {
1507
1821
  const vault = getVault();
1508
1822
  if (!vaultExists(vault)) {
1509
1823
  console.log(pc.yellow("No hay b\xF3veda aqu\xED. Corre `ale init` primero."));
1510
1824
  return;
1511
1825
  }
1512
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
+ }
1513
1838
  const results = await hybridSearch(vault, q, parseInt(opts.k, 10) || 6, { expand: opts.expand });
1514
1839
  if (results.length === 0) {
1515
1840
  console.log(pc.dim("Sin resultados."));
@@ -1582,7 +1907,7 @@ program.command("toggles").description("Activa/desactiva comportamientos que gas
1582
1907
  printList();
1583
1908
  console.log();
1584
1909
  });
1585
- program.command("scan").description("Escanea el proyecto (API, env-nombres, datos, convenciones) \u2192 notas de contexto en la b\xF3veda. Re-ejecutable; solo-lectura del c\xF3digo; garantiza .gitignore").action(async () => {
1910
+ program.command("scan").description("Escanea el proyecto (API, env-nombres, datos, convenciones, flujo) \u2192 notas de contexto en la b\xF3veda. Re-ejecutable; solo-lectura del c\xF3digo; garantiza .gitignore").action(async () => {
1586
1911
  const vault = getVault();
1587
1912
  ensureVaultStructure(vault);
1588
1913
  const cwd = process.cwd();
@@ -1595,7 +1920,7 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1595
1920
  console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
1596
1921
  }
1597
1922
  if (s.notes.length) {
1598
- 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)}`));
1599
1924
  } else {
1600
1925
  console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1601
1926
  }
@@ -1656,7 +1981,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1656
1981
  async function runSkills(opts) {
1657
1982
  const { vault } = await ensureReady();
1658
1983
  const cwd = process.cwd();
1659
- 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");
1660
1985
  const recs = await recommendSkills(vault, [targetDir]);
1661
1986
  if (recs.length === 0) {
1662
1987
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -1698,7 +2023,7 @@ program.command("skills").description("Analiza la b\xF3veda y recomienda/instala
1698
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) => {
1699
2024
  const { vault } = await ensureReady();
1700
2025
  const cwd = process.cwd();
1701
- const proj = path6.basename(cwd);
2026
+ const proj = path7.basename(cwd);
1702
2027
  const targetDir = skillTargetDir(cwd, Boolean(opts.global));
1703
2028
  const result = evolveSkill(vault, proj, targetDir);
1704
2029
  if (!result) {
@@ -1785,10 +2110,10 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1785
2110
  );
1786
2111
  }
1787
2112
  try {
1788
- const name = path6.basename(cwd);
1789
- const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1790
- const pkgM = fs6.statSync(path6.join(cwd, "package.json")).mtimeMs;
1791
- 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;
1792
2117
  if (pkgM > mapM) {
1793
2118
  console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1794
2119
  } else {
@@ -1796,41 +2121,44 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1796
2121
  }
1797
2122
  } catch {
1798
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
+ }
1799
2129
  const skillsRepoCfg = localSkillsRepo();
1800
- if (skillsRepoCfg && !fs6.existsSync(skillsRepoCfg)) {
2130
+ if (skillsRepoCfg && !fs7.existsSync(skillsRepoCfg)) {
1801
2131
  console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1802
2132
  }
1803
2133
  console.log();
1804
2134
  });
1805
- 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) => {
1806
2136
  const cwd = process.cwd();
1807
2137
  const scope = opts.project ? "project" : "global";
1808
2138
  const settings = opts.project ? projectSettingsPath(cwd) : globalSettingsPath();
1809
2139
  unregisterHooks(settings);
1810
2140
  console.log(pc.green(`\u2713 Hooks de alexandria eliminados de ${settings}`));
1811
- const claudeMd = removeClaudeMd(scope, cwd);
1812
- if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
1813
- if (opts.project) {
1814
- const mcpFile = path6.join(cwd, ".mcp.json");
1815
- try {
1816
- const cfg = JSON.parse(fs6.readFileSync(mcpFile, "utf8"));
1817
- if (cfg.mcpServers?.alexandria) {
1818
- delete cfg.mcpServers.alexandria;
1819
- if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
1820
- if (Object.keys(cfg).length === 0) fs6.rmSync(mcpFile, { force: true });
1821
- else fs6.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1822
- console.log(pc.green("\u2713 MCP removido de .mcp.json"));
1823
- }
1824
- } catch {
1825
- }
1826
- console.log(pc.dim(' Otros agentes (Cursor/OpenCode/\u2026): quita "alexandria" de su config si lo registraste.'));
1827
- } else {
1828
- 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."));
1829
2150
  }
1830
2151
  });
1831
2152
  program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
1832
2153
  await import("./mcp/server.js");
1833
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
+ });
1834
2162
  if (process.argv.length <= 2) {
1835
2163
  await showBanner();
1836
2164
  program.outputHelp();