@ureck/alexandria 1.3.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,26 +1,41 @@
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,
7
+ ingestAndOutline,
8
+ listDocs,
9
9
  mcpRegisteredProject,
10
10
  pkgVersion,
11
11
  planContext,
12
12
  planQualityHints,
13
13
  projectSettingsPath,
14
+ readDoc,
14
15
  registerHooks,
15
16
  registerMcpGlobal,
16
17
  registerMcpProject,
17
18
  serverCommand,
18
19
  unregisterHooks
19
- } from "./chunk-5A6CC74D.js";
20
+ } from "./chunk-SAKIVZMP.js";
20
21
  import {
21
22
  hybridSearch,
22
23
  protocolChain
23
- } from "./chunk-UWB6RKVN.js";
24
+ } from "./chunk-Y6S6SKH4.js";
25
+ import {
26
+ ARCHIVE_DIR,
27
+ applyClean,
28
+ dirBytes,
29
+ markCleaned,
30
+ planClean,
31
+ searchArchive
32
+ } from "./chunk-B7HCWKPJ.js";
33
+ import {
34
+ readStats
35
+ } from "./chunk-POA77JSS.js";
36
+ import {
37
+ formatOf
38
+ } from "./chunk-UU4MGB2C.js";
24
39
  import {
25
40
  TOKEN_TOGGLES,
26
41
  defaultVaultPath,
@@ -35,16 +50,16 @@ import {
35
50
  vaultExists,
36
51
  writeGlobalConfig,
37
52
  writeProjectConfig
38
- } from "./chunk-7LWLBJAD.js";
53
+ } from "./chunk-CEHNXDUE.js";
39
54
  import {
40
55
  serveGraph
41
- } from "./chunk-FBGIFNIO.js";
56
+ } from "./chunk-GP5A2GWI.js";
42
57
  import {
43
58
  VaultIndex,
44
59
  createNote,
45
60
  slugify,
46
61
  upsertNote
47
- } from "./chunk-QB37UGO6.js";
62
+ } from "./chunk-BV2KJV5W.js";
48
63
  import {
49
64
  MODEL_ID,
50
65
  dot,
@@ -54,9 +69,10 @@ import {
54
69
  } from "./chunk-EDYBSJSS.js";
55
70
 
56
71
  // src/cli.ts
57
- import fs6 from "fs";
58
- import path6 from "path";
72
+ import fs7 from "fs";
73
+ import path7 from "path";
59
74
  import readline from "readline/promises";
75
+ import { execFileSync as execFileSync4 } from "child_process";
60
76
  import { Command } from "commander";
61
77
  import pc from "picocolors";
62
78
 
@@ -367,6 +383,18 @@ function mergeMcpServers(file, key = "mcpServers") {
367
383
  return { ok: false, file, detail: e.message };
368
384
  }
369
385
  }
386
+ function removeMcpEntry(file, key = "mcpServers") {
387
+ try {
388
+ const cfg = JSON.parse(fs3.readFileSync(file, "utf8"));
389
+ if (!cfg[key]?.alexandria) return false;
390
+ delete cfg[key].alexandria;
391
+ if (Object.keys(cfg[key]).length === 0) delete cfg[key];
392
+ writeJson(file, cfg);
393
+ return true;
394
+ } catch {
395
+ return false;
396
+ }
397
+ }
370
398
  function home(...p) {
371
399
  return path3.join(os3.homedir(), ...p);
372
400
  }
@@ -419,6 +447,8 @@ var AGENTS = [
419
447
  name: "Claude Code",
420
448
  supportsProject: true,
421
449
  detect: () => fs3.existsSync(home(".claude")),
450
+ hooks: "claude",
451
+ unregister: (scope, projectDir) => scope === "project" ? removeMcpEntry(path3.join(projectDir, ".mcp.json")) : removeMcpEntry(home(".claude.json")),
422
452
  register(scope, projectDir) {
423
453
  if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
424
454
  return mergeMcpServers(home(".claude.json"));
@@ -429,6 +459,8 @@ var AGENTS = [
429
459
  name: "Cursor",
430
460
  supportsProject: true,
431
461
  detect: () => fs3.existsSync(home(".cursor")),
462
+ hooks: "cursor",
463
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json")),
432
464
  register(scope, projectDir) {
433
465
  const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
434
466
  return mergeMcpServers(file);
@@ -439,6 +471,8 @@ var AGENTS = [
439
471
  name: "OpenCode",
440
472
  supportsProject: true,
441
473
  detect: () => fs3.existsSync(home(".config", "opencode")) || fs3.existsSync(home(".opencode")),
474
+ hooks: "opencode",
475
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json"), "mcp"),
442
476
  register(scope, projectDir) {
443
477
  const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
444
478
  try {
@@ -459,6 +493,8 @@ var AGENTS = [
459
493
  name: "Windsurf (legacy \u2192 Devin)",
460
494
  supportsProject: false,
461
495
  detect: () => fs3.existsSync(home(".codeium", "windsurf")),
496
+ legacy: true,
497
+ unregister: () => removeMcpEntry(home(".codeium", "windsurf", "mcp_config.json")),
462
498
  register() {
463
499
  return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
464
500
  }
@@ -469,6 +505,7 @@ var AGENTS = [
469
505
  supportsProject: true,
470
506
  // El CLI vive en ~/.local/bin/devin y guarda config MCP por proyecto en .devin/
471
507
  detect: () => fs3.existsSync(home(".devin")) || fs3.existsSync(home(".local", "bin", "devin")),
508
+ unregister: (scope, projectDir) => removeMcpEntry(path3.join(scope === "project" ? projectDir : home(), ".devin", "mcp_config.local.json")),
472
509
  register(scope, projectDir) {
473
510
  const dir = scope === "project" ? projectDir : home();
474
511
  const file = path3.join(dir, ".devin", "mcp_config.local.json");
@@ -489,6 +526,7 @@ var AGENTS = [
489
526
  name: "Cline (VS Code)",
490
527
  supportsProject: false,
491
528
  detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
529
+ unregister: () => removeMcpEntry(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json")),
492
530
  register() {
493
531
  const file = path3.join(
494
532
  vscodeUserDir(),
@@ -503,14 +541,27 @@ var AGENTS = [
503
541
  {
504
542
  id: "codex",
505
543
  name: "Codex CLI (OpenAI)",
506
- supportsProject: false,
544
+ // Codex lee también <repo>/.codex/config.toml cuando el proyecto es de confianza
545
+ supportsProject: true,
507
546
  detect: () => fs3.existsSync(home(".codex")),
508
- register() {
509
- const file = home(".codex", "config.toml");
510
- const { command, args } = serverCmd();
547
+ hooks: "codex",
548
+ unregister: (scope, projectDir) => {
549
+ const file = scope === "project" ? path3.join(projectDir, ".codex", "config.toml") : home(".codex", "config.toml");
550
+ try {
551
+ const text = fs3.readFileSync(file, "utf8");
552
+ if (!/\[mcp_servers\.alexandria\]/.test(text)) return false;
553
+ fs3.writeFileSync(file, replaceTomlTable(text, "mcp_servers.alexandria", "").trimEnd() + "\n");
554
+ return true;
555
+ } catch {
556
+ return false;
557
+ }
558
+ },
559
+ register(scope, projectDir) {
560
+ const file = scope === "project" ? path3.join(projectDir, ".codex", "config.toml") : home(".codex", "config.toml");
561
+ const { command: command2, args } = serverCmd();
511
562
  const tomlArgs = args.map((a) => `"${a.replace(/\\/g, "\\\\")}"`).join(", ");
512
563
  const block = `[mcp_servers.alexandria]
513
- command = "${command}"
564
+ command = "${command2}"
514
565
  args = [${tomlArgs}]
515
566
  `;
516
567
  try {
@@ -533,6 +584,8 @@ args = [${tomlArgs}]
533
584
  name: "Gemini CLI",
534
585
  supportsProject: true,
535
586
  detect: () => fs3.existsSync(home(".gemini")),
587
+ hooks: "gemini",
588
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json")),
536
589
  register(scope, projectDir) {
537
590
  const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
538
591
  return mergeMcpServers(file);
@@ -543,6 +596,7 @@ args = [${tomlArgs}]
543
596
  name: "OpenClaw",
544
597
  supportsProject: false,
545
598
  detect: () => fs3.existsSync(home(".openclaw")),
599
+ unregister: () => removeMcpEntry(home(".openclaw", "openclaw.json")),
546
600
  register() {
547
601
  const file = home(".openclaw", "openclaw.json");
548
602
  try {
@@ -612,6 +666,7 @@ ${entry.trimEnd()}`);
612
666
  // Chat instalada. Antes bastaba con que existiera el User dir, así que
613
667
  // cualquiera con VS Code aparecía como agente detectado aunque no use MCP.
614
668
  detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "mcp.json")) || hasCopilotChatExtension(),
669
+ unregister: (scope, projectDir) => removeMcpEntry(scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json"), "servers"),
615
670
  register(scope, projectDir) {
616
671
  const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
617
672
  try {
@@ -637,6 +692,210 @@ function resolveAgents(spec) {
637
692
  return s.split(",").map((id) => agentById(id)).filter((a) => Boolean(a));
638
693
  }
639
694
 
695
+ // src/core/harness-hooks.ts
696
+ import fs4 from "fs";
697
+ import os4 from "os";
698
+ import path4 from "path";
699
+ var HOOK_HARNESSES = ["codex", "gemini", "cursor", "opencode"];
700
+ var EVENTS = {
701
+ // Codex: hooks GA desde 0.133; mismos nombres que Claude Code. Timeout en segundos.
702
+ codex: [
703
+ ["SessionStart", "on-session-start", 20],
704
+ ["UserPromptSubmit", "on-prompt", 10],
705
+ ["Stop", "on-stop", 30],
706
+ ["PreCompact", "on-stop", 30]
707
+ ],
708
+ // Gemini: BeforeAgent trae el prompt; AfterAgent trae prompt + prompt_response.
709
+ gemini: [
710
+ ["SessionStart", "on-session-start", 20],
711
+ ["BeforeAgent", "on-prompt", 10],
712
+ ["AfterAgent", "on-stop", 30],
713
+ ["PreCompress", "on-stop", 30]
714
+ ],
715
+ // Cursor: beforeSubmitPrompt no puede inyectar (solo continuar/bloquear) → ahí
716
+ // solo se captura; afterAgentResponse trae el texto de la respuesta.
717
+ cursor: [
718
+ ["sessionStart", "on-session-start", 20],
719
+ ["beforeSubmitPrompt", "on-prompt", 10],
720
+ ["afterAgentResponse", "on-stop", 30]
721
+ ]
722
+ };
723
+ function home2(...p) {
724
+ return path4.join(os4.homedir(), ...p);
725
+ }
726
+ function hookFile(h, scope, projectDir) {
727
+ const base = scope === "project" ? projectDir : os4.homedir();
728
+ switch (h) {
729
+ case "codex":
730
+ return path4.join(base, ".codex", "hooks.json");
731
+ case "gemini":
732
+ return path4.join(base, ".gemini", "settings.json");
733
+ case "cursor":
734
+ return path4.join(base, ".cursor", "hooks.json");
735
+ case "opencode":
736
+ return scope === "project" ? path4.join(projectDir, ".opencode", "plugins", "alexandria.js") : home2(".config", "opencode", "plugins", "alexandria.js");
737
+ }
738
+ }
739
+ function scriptPath(s) {
740
+ return path4.join(distDir(), "hooks", `${s}.js`);
741
+ }
742
+ function command(s, h) {
743
+ return `node "${scriptPath(s)}" --harness=${h}`;
744
+ }
745
+ var isOurs = (cmd) => typeof cmd === "string" && (cmd.includes("alexandria") || cmd.includes(distDir()));
746
+ function readJson(file) {
747
+ try {
748
+ return JSON.parse(fs4.readFileSync(file, "utf8"));
749
+ } catch {
750
+ if (fs4.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
751
+ return {};
752
+ }
753
+ }
754
+ function writeJson2(file, data) {
755
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
756
+ fs4.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
757
+ }
758
+ function stripOurs(hooks, flat) {
759
+ for (const ev of Object.keys(hooks)) {
760
+ const list = Array.isArray(hooks[ev]) ? hooks[ev] : [];
761
+ 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);
762
+ if (kept.length > 0) hooks[ev] = kept;
763
+ else delete hooks[ev];
764
+ }
765
+ }
766
+ function registerHarnessHooks(h, scope, projectDir) {
767
+ const file = hookFile(h, scope, projectDir);
768
+ try {
769
+ if (h === "opencode") {
770
+ fs4.mkdirSync(path4.dirname(file), { recursive: true });
771
+ fs4.writeFileSync(file, opencodePlugin());
772
+ return { ok: true, file };
773
+ }
774
+ const cfg = readJson(file);
775
+ const hooks = cfg.hooks ?? {};
776
+ const flat = h === "cursor";
777
+ stripOurs(hooks, flat);
778
+ for (const [ev, script, secs] of EVENTS[h]) {
779
+ const list = hooks[ev] ?? [];
780
+ if (flat) {
781
+ list.push({ command: command(script, h), timeout: secs });
782
+ } else if (h === "gemini") {
783
+ list.push({ hooks: [{ type: "command", name: `alexandria-${script}`, command: command(script, h), timeout: secs * 1e3 }] });
784
+ } else {
785
+ list.push({ hooks: [{ type: "command", command: command(script, h), timeout: secs }] });
786
+ }
787
+ hooks[ev] = list;
788
+ }
789
+ cfg.hooks = hooks;
790
+ if (flat) cfg.version ??= 1;
791
+ writeJson2(file, cfg);
792
+ return {
793
+ ok: true,
794
+ file,
795
+ detail: h === "codex" ? "abre Codex y aprueba los hooks con /hooks (Codex salta hooks no confiados)" : void 0
796
+ };
797
+ } catch (e) {
798
+ return { ok: false, file, detail: e.message };
799
+ }
800
+ }
801
+ function unregisterHarnessHooks(h, scope, projectDir) {
802
+ const file = hookFile(h, scope, projectDir);
803
+ try {
804
+ if (!fs4.existsSync(file)) return false;
805
+ if (h === "opencode") {
806
+ fs4.rmSync(file, { force: true });
807
+ return true;
808
+ }
809
+ const cfg = readJson(file);
810
+ const hooks = cfg.hooks;
811
+ if (!hooks) return false;
812
+ const before = JSON.stringify(hooks);
813
+ stripOurs(hooks, h === "cursor");
814
+ if (JSON.stringify(hooks) === before) return false;
815
+ if (Object.keys(hooks).length === 0) delete cfg.hooks;
816
+ writeJson2(file, cfg);
817
+ return true;
818
+ } catch {
819
+ return false;
820
+ }
821
+ }
822
+ function opencodePlugin() {
823
+ const scripts = {
824
+ session: scriptPath("on-session-start"),
825
+ prompt: scriptPath("on-prompt"),
826
+ stop: scriptPath("on-stop")
827
+ };
828
+ return `// Alexandria \u2014 plugin de OpenCode (generado por \`ale agents opencode\`; se sobrescribe al re-registrar).
829
+ // Captura prompts/sesiones en la b\xF3veda e inyecta contexto relevante en el system prompt.
830
+ import { execFile } from 'node:child_process';
831
+
832
+ const SCRIPTS = ${JSON.stringify(scripts, null, 2)};
833
+
834
+ function run(script, payload, timeoutMs) {
835
+ return new Promise((resolve) => {
836
+ const child = execFile('node', [script, '--harness=opencode'], { timeout: timeoutMs, windowsHide: true }, (_e, stdout) =>
837
+ resolve(typeof stdout === 'string' ? stdout.trim() : '')
838
+ );
839
+ child.stdin?.end(JSON.stringify(payload));
840
+ });
841
+ }
842
+
843
+ // Solo export default: OpenCode registra CADA funci\xF3n exportada como plugin.
844
+ const AlexandriaPlugin = async ({ directory }) => {
845
+ const digest = new Map(); // sessionID \u2192 contexto de inicio
846
+ const turn = new Map(); // sessionID \u2192 contexto del prompt actual
847
+ const lastPrompt = new Map();
848
+ const roles = new Map(); // messageID \u2192 role
849
+ const texts = new Map(); // messageID \u2192 texto acumulado
850
+ const lastAssistant = new Map(); // sessionID \u2192 messageID
851
+
852
+ return {
853
+ event: async ({ event }) => {
854
+ try {
855
+ const p = event?.properties ?? {};
856
+ if (event.type === 'session.created') {
857
+ const id = p.info?.id ?? p.sessionID;
858
+ if (id) digest.set(id, await run(SCRIPTS.session, { session_id: id, cwd: directory, source: 'startup' }, 15000));
859
+ } else if (event.type === 'message.updated' && p.info?.id) {
860
+ roles.set(p.info.id, p.info.role);
861
+ if (p.info.role === 'assistant' && p.info.sessionID) lastAssistant.set(p.info.sessionID, p.info.id);
862
+ } else if (event.type === 'message.part.updated' && p.part?.type === 'text' && !p.part.synthetic) {
863
+ texts.set(p.part.messageID, p.part.text ?? '');
864
+ } else if (event.type === 'session.idle' && p.sessionID) {
865
+ const mid = lastAssistant.get(p.sessionID);
866
+ const answer = mid ? texts.get(mid) : '';
867
+ if (answer) {
868
+ await run(SCRIPTS.stop, { session_id: p.sessionID, cwd: directory, prompt: lastPrompt.get(p.sessionID) ?? '', last_assistant_message: answer }, 25000);
869
+ }
870
+ }
871
+ } catch {
872
+ /* Alexandria jam\xE1s rompe la sesi\xF3n */
873
+ }
874
+ },
875
+ 'chat.message': async (input, output) => {
876
+ try {
877
+ const prompt = (output?.parts ?? []).filter((x) => x?.type === 'text' && !x.synthetic).map((x) => x.text).join('\\n').trim();
878
+ if (!prompt) return;
879
+ lastPrompt.set(input.sessionID, prompt);
880
+ turn.set(input.sessionID, await run(SCRIPTS.prompt, { session_id: input.sessionID, cwd: directory, prompt }, 8000));
881
+ } catch {
882
+ /* sin contexto este turno */
883
+ }
884
+ },
885
+ 'experimental.chat.system.transform': async (input, output) => {
886
+ if (!Array.isArray(output?.system) || !input?.sessionID) return;
887
+ const d = digest.get(input.sessionID);
888
+ const t = turn.get(input.sessionID);
889
+ if (d) output.system.push(d);
890
+ if (t) output.system.push(t);
891
+ }
892
+ };
893
+ };
894
+
895
+ export default AlexandriaPlugin;
896
+ `;
897
+ }
898
+
640
899
  // src/cli/banner.ts
641
900
  var ART = [
642
901
  "\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 +957,9 @@ async function showBanner(animate) {
698
957
  }
699
958
 
700
959
  // src/core/setup.ts
701
- import fs4 from "fs";
702
- import os4 from "os";
703
- import path4 from "path";
960
+ import fs5 from "fs";
961
+ import os5 from "os";
962
+ import path5 from "path";
704
963
  import { execFileSync as execFileSync3 } from "child_process";
705
964
  var PERSONAL_CONFIG_FILES = [
706
965
  ".vault.json",
@@ -709,18 +968,23 @@ var PERSONAL_CONFIG_FILES = [
709
968
  "opencode.json",
710
969
  ".vscode/mcp.json",
711
970
  ".gemini/settings.json",
712
- ".devin/mcp_config.local.json"
971
+ ".devin/mcp_config.local.json",
972
+ // hooks/MCP por proyecto de los demás arneses: llevan rutas de esta máquina
973
+ ".codex/hooks.json",
974
+ ".codex/config.toml",
975
+ ".cursor/hooks.json",
976
+ ".opencode/plugins/alexandria.js"
713
977
  ];
714
978
  function ensureGitignore(projectDir, vaultRoot) {
715
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return null;
979
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return null;
716
980
  const entries = [];
717
- const rel = path4.relative(projectDir, vaultRoot);
718
- if (!rel.startsWith("..")) entries.push(`${rel.split(path4.sep).join("/")}/`);
981
+ const rel = path5.relative(projectDir, vaultRoot);
982
+ if (!rel.startsWith("..")) entries.push(`${rel.split(path5.sep).join("/")}/`);
719
983
  entries.push(...PERSONAL_CONFIG_FILES);
720
- const file = path4.join(projectDir, ".gitignore");
984
+ const file = path5.join(projectDir, ".gitignore");
721
985
  let text = "";
722
986
  try {
723
- text = fs4.readFileSync(file, "utf8");
987
+ text = fs5.readFileSync(file, "utf8");
724
988
  } catch {
725
989
  }
726
990
  const has = (e) => text.split("\n").some((l) => l.trim() === e || l.trim() === e.replace(/\/$/, ""));
@@ -731,14 +995,14 @@ function ensureGitignore(projectDir, vaultRoot) {
731
995
  # Alexandria (conocimiento y config personal \u2014 no del repo)
732
996
  ${missing.join("\n")}
733
997
  `;
734
- fs4.writeFileSync(file, text.trim() ? block : block.trimStart());
998
+ fs5.writeFileSync(file, text.trim() ? block : block.trimStart());
735
999
  return file;
736
1000
  }
737
1001
  function untrackPersonalConfigs(projectDir) {
738
- if (!fs4.existsSync(path4.join(projectDir, ".git"))) return [];
1002
+ if (!fs5.existsSync(path5.join(projectDir, ".git"))) return [];
739
1003
  const untracked = [];
740
1004
  for (const f of PERSONAL_CONFIG_FILES) {
741
- if (!fs4.existsSync(path4.join(projectDir, f))) continue;
1005
+ if (!fs5.existsSync(path5.join(projectDir, f))) continue;
742
1006
  try {
743
1007
  const tracked = execFileSync3("git", ["ls-files", "--error-unmatch", f], {
744
1008
  cwd: projectDir,
@@ -755,60 +1019,81 @@ function untrackPersonalConfigs(projectDir) {
755
1019
  }
756
1020
  var CLAUDE_MD_START = "<!-- alexandria:start -->";
757
1021
  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 });
1022
+ var BLOCK = [
1023
+ CLAUDE_MD_START,
1024
+ "## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
1025
+ "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
1026
+ "- 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.",
1027
+ "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
1028
+ "- 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.",
1029
+ "- 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.",
1030
+ "- `vault_related` trae conocimiento conectado sin releer archivos.",
1031
+ "- PDF/DOCX/XLSX/CSV/HTML: nunca leas el archivo completo \u2014 `doc_ingest` (\xEDndice de secciones, ~200 tokens) y luego `doc_read` con las secciones o una pregunta.",
1032
+ CLAUDE_MD_END
1033
+ ].join("\n");
1034
+ function instructionFiles(scope, projectDir) {
1035
+ if (scope === "project") {
1036
+ const claude = path5.join(projectDir, "CLAUDE.md");
1037
+ const agents = path5.join(projectDir, "AGENTS.md");
1038
+ let claudeText = "";
1039
+ try {
1040
+ claudeText = fs5.readFileSync(claude, "utf8");
1041
+ } catch {
1042
+ }
1043
+ return /^@AGENTS\.md\s*$/m.test(claudeText) ? [agents] : [claude, agents];
1044
+ }
1045
+ const files = [path5.join(os5.homedir(), ".claude", "CLAUDE.md")];
1046
+ for (const dir of [path5.join(os5.homedir(), ".codex"), path5.join(os5.homedir(), ".config", "opencode")]) {
1047
+ if (fs5.existsSync(dir)) files.push(path5.join(dir, "AGENTS.md"));
1048
+ }
1049
+ return files;
1050
+ }
1051
+ function writeBlock(file) {
1052
+ fs5.mkdirSync(path5.dirname(file), { recursive: true });
772
1053
  let text = "";
773
1054
  try {
774
- text = fs4.readFileSync(file, "utf8");
1055
+ text = fs5.readFileSync(file, "utf8");
775
1056
  } catch {
776
1057
  }
777
1058
  if (text.includes(CLAUDE_MD_START)) {
778
1059
  const re = new RegExp(`${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}`);
779
- text = text.replace(re, block);
1060
+ text = text.replace(re, BLOCK);
780
1061
  } else {
781
- text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
1062
+ text = (text.trimEnd() + "\n\n" + BLOCK + "\n").trimStart();
782
1063
  }
783
- fs4.writeFileSync(file, text);
784
- return file;
1064
+ fs5.writeFileSync(file, text);
1065
+ }
1066
+ function configureClaudeMd(scope, projectDir) {
1067
+ const files = instructionFiles(scope, projectDir);
1068
+ for (const f of files) writeBlock(f);
1069
+ return files;
785
1070
  }
786
1071
  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;
1072
+ const removed = [];
1073
+ for (const file of instructionFiles(scope, projectDir)) {
1074
+ let text;
1075
+ try {
1076
+ text = fs5.readFileSync(file, "utf8");
1077
+ } catch {
1078
+ continue;
1079
+ }
1080
+ if (!text.includes(CLAUDE_MD_START)) continue;
1081
+ const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
1082
+ const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
1083
+ if (cleaned === "") fs5.rmSync(file, { force: true });
1084
+ else fs5.writeFileSync(file, cleaned + "\n");
1085
+ removed.push(file);
1086
+ }
1087
+ return removed;
803
1088
  }
804
1089
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
805
1090
  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;
1091
+ const name = path5.basename(projectDir);
1092
+ const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1093
+ if (fs5.existsSync(mapFile)) return null;
809
1094
  const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
810
1095
  try {
811
- const pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
1096
+ const pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
812
1097
  const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
813
1098
  const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
814
1099
  parts.push(`## Stack
@@ -827,13 +1112,13 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
827
1112
  if (depth > 2 || tree.length > 60) return;
828
1113
  let entries = [];
829
1114
  try {
830
- entries = fs4.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
1115
+ entries = fs5.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
831
1116
  } catch {
832
1117
  return;
833
1118
  }
834
1119
  for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
835
1120
  tree.push(`${prefix}${e.name}/`);
836
- walk(path4.join(dir, e.name), depth + 1, prefix + " ");
1121
+ walk(path5.join(dir, e.name), depth + 1, prefix + " ");
837
1122
  }
838
1123
  };
839
1124
  walk(projectDir, 1, "");
@@ -842,7 +1127,7 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
842
1127
  ${tree.join("\n")}
843
1128
  \`\`\``);
844
1129
  try {
845
- const readme = fs4.readFileSync(path4.join(projectDir, "README.md"), "utf8");
1130
+ const readme = fs5.readFileSync(path5.join(projectDir, "README.md"), "utf8");
846
1131
  parts.push(`## README (extracto)
847
1132
  ${readme.split("\n").slice(0, 15).join("\n")}`);
848
1133
  } catch {
@@ -858,8 +1143,8 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
858
1143
  }
859
1144
 
860
1145
  // src/core/scan.ts
861
- import fs5 from "fs";
862
- import path5 from "path";
1146
+ import fs6 from "fs";
1147
+ import path6 from "path";
863
1148
  var SKIP_DIRS2 = /* @__PURE__ */ new Set([
864
1149
  "node_modules",
865
1150
  ".git",
@@ -904,15 +1189,15 @@ function collectSourceFiles(projectDir) {
904
1189
  for (const dir of level) {
905
1190
  let entries = [];
906
1191
  try {
907
- entries = fs5.readdirSync(dir, { withFileTypes: true });
1192
+ entries = fs6.readdirSync(dir, { withFileTypes: true });
908
1193
  } catch {
909
1194
  continue;
910
1195
  }
911
1196
  for (const e of entries) {
912
1197
  if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
913
- const full = path5.join(dir, e.name);
1198
+ const full = path6.join(dir, e.name);
914
1199
  if (e.isDirectory()) next.push(full);
915
- else if (e.isFile() && SOURCE_EXT.has(path5.extname(e.name))) {
1200
+ else if (e.isFile() && SOURCE_EXT.has(path6.extname(e.name))) {
916
1201
  candidates.push(full);
917
1202
  if (candidates.length >= TRAVERSE_SAFETY) break;
918
1203
  }
@@ -925,7 +1210,7 @@ function collectSourceFiles(projectDir) {
925
1210
  if (candidates.length > MAX_FILES) {
926
1211
  const groups = /* @__PURE__ */ new Map();
927
1212
  for (const c of candidates) {
928
- const key = path5.relative(projectDir, c).split(path5.sep)[0];
1213
+ const key = path6.relative(projectDir, c).split(path6.sep)[0];
929
1214
  const g = groups.get(key);
930
1215
  if (g) g.push(c);
931
1216
  else groups.set(key, [c]);
@@ -947,10 +1232,10 @@ function collectSourceFiles(projectDir) {
947
1232
  const out = [];
948
1233
  for (const full of chosen) {
949
1234
  try {
950
- if (fs5.statSync(full).size > MAX_FILE_BYTES) continue;
1235
+ if (fs6.statSync(full).size > MAX_FILE_BYTES) continue;
951
1236
  out.push({
952
- rel: path5.relative(projectDir, full).split(path5.sep).join("/"),
953
- content: fs5.readFileSync(full, "utf8")
1237
+ rel: path6.relative(projectDir, full).split(path6.sep).join("/"),
1238
+ content: fs6.readFileSync(full, "utf8")
954
1239
  });
955
1240
  } catch {
956
1241
  }
@@ -1048,7 +1333,7 @@ function scanEnvNames(projectDir) {
1048
1333
  for (const file of [".env.example", ".env", ".env.local"]) {
1049
1334
  let text;
1050
1335
  try {
1051
- text = fs5.readFileSync(path5.join(projectDir, file), "utf8");
1336
+ text = fs6.readFileSync(path6.join(projectDir, file), "utf8");
1052
1337
  } catch {
1053
1338
  continue;
1054
1339
  }
@@ -1062,7 +1347,7 @@ function scanEnvNames(projectDir) {
1062
1347
  function scanDataSchema(projectDir, files) {
1063
1348
  const lines = [];
1064
1349
  try {
1065
- const schema = fs5.readFileSync(path5.join(projectDir, "prisma", "schema.prisma"), "utf8");
1350
+ const schema = fs6.readFileSync(path6.join(projectDir, "prisma", "schema.prisma"), "utf8");
1066
1351
  for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
1067
1352
  const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
1068
1353
  const shown = fields.slice(0, 8).join(", ");
@@ -1079,14 +1364,14 @@ function scanDataSchema(projectDir, files) {
1079
1364
  for (const dir of migDirs) {
1080
1365
  let sqlFiles = [];
1081
1366
  try {
1082
- sqlFiles = fs5.readdirSync(path5.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
1367
+ sqlFiles = fs6.readdirSync(path6.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
1083
1368
  } catch {
1084
1369
  continue;
1085
1370
  }
1086
1371
  const tables = /* @__PURE__ */ new Set();
1087
1372
  for (const f of sqlFiles) {
1088
1373
  try {
1089
- const sql = fs5.readFileSync(path5.join(projectDir, dir, f), "utf8");
1374
+ const sql = fs6.readFileSync(path6.join(projectDir, dir, f), "utf8");
1090
1375
  for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
1091
1376
  } catch {
1092
1377
  }
@@ -1097,17 +1382,17 @@ function scanDataSchema(projectDir, files) {
1097
1382
  }
1098
1383
  function scanConventions(projectDir) {
1099
1384
  const lines = [];
1100
- const has = (f) => fs5.existsSync(path5.join(projectDir, f));
1385
+ const has = (f) => fs6.existsSync(path6.join(projectDir, f));
1101
1386
  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
1387
  if (pm) lines.push(`- gestor de paquetes: ${pm}`);
1103
1388
  let pkg = {};
1104
1389
  try {
1105
- pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
1390
+ pkg = JSON.parse(fs6.readFileSync(path6.join(projectDir, "package.json"), "utf8"));
1106
1391
  } catch {
1107
1392
  }
1108
1393
  if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
1109
1394
  try {
1110
- const ts = JSON.parse(fs5.readFileSync(path5.join(projectDir, "tsconfig.json"), "utf8"));
1395
+ const ts = JSON.parse(fs6.readFileSync(path6.join(projectDir, "tsconfig.json"), "utf8"));
1111
1396
  const co = ts.compilerOptions ?? {};
1112
1397
  lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
1113
1398
  const paths = Object.keys(co.paths ?? {}).slice(0, 5);
@@ -1129,18 +1414,18 @@ function scanConventions(projectDir) {
1129
1414
  }
1130
1415
  function linkMapToScans(vault, name, titles) {
1131
1416
  if (titles.length === 0) return;
1132
- const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1417
+ const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1133
1418
  try {
1134
- const text = fs5.readFileSync(mapFile, "utf8");
1419
+ const text = fs6.readFileSync(mapFile, "utf8");
1135
1420
  if (text.includes("Contexto ampliado:")) return;
1136
- fs5.appendFileSync(mapFile, `
1421
+ fs6.appendFileSync(mapFile, `
1137
1422
  Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
1138
1423
  `);
1139
1424
  } catch {
1140
1425
  }
1141
1426
  }
1142
1427
  function scanAll(vault, projectDir) {
1143
- const name = path5.basename(projectDir);
1428
+ const name = path6.basename(projectDir);
1144
1429
  const gitignored = ensureGitignore(projectDir, vault.root) !== null;
1145
1430
  try {
1146
1431
  untrackPersonalConfigs(projectDir);
@@ -1215,7 +1500,16 @@ Proyecto: [[Mapa - ${name}]]`
1215
1500
  }
1216
1501
 
1217
1502
  // src/cli.ts
1218
- function registerAgentsMcp(agents, scope, cwd, portable = false) {
1503
+ function registerAgentHooks(agent, scope, cwd) {
1504
+ if (!agent.hooks || agent.hooks === "claude") return;
1505
+ const res = registerHarnessHooks(agent.hooks, scope, cwd);
1506
+ if (res.ok) {
1507
+ console.log(pc.green(`\u2713 Hooks \u2192 ${agent.name} (${res.file})`) + (res.detail ? pc.dim(` \u2014 ${res.detail}`) : ""));
1508
+ } else {
1509
+ console.log(pc.yellow(`\u26A0 Hooks \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
1510
+ }
1511
+ }
1512
+ function registerAgentsMcp(agents, scope, cwd, portable = false, hooks = true) {
1219
1513
  setPortableMode(portable);
1220
1514
  for (const agent of agents) {
1221
1515
  if (agent.id === "claude") {
@@ -1234,6 +1528,7 @@ function registerAgentsMcp(agents, scope, cwd, portable = false) {
1234
1528
  if (res.ok) {
1235
1529
  const note = effScope !== scope ? pc.dim(" [global: no soporta por-proyecto]") : "";
1236
1530
  console.log(pc.green(`\u2713 MCP \u2192 ${agent.name} (${res.file})`) + note);
1531
+ if (hooks) registerAgentHooks(agent, effScope, cwd);
1237
1532
  } else {
1238
1533
  console.log(pc.yellow(`\u26A0 MCP \u2192 ${agent.name}: ${res.detail ?? "fall\xF3"}`));
1239
1534
  }
@@ -1277,7 +1572,7 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1277
1572
  ).action(async (opts) => {
1278
1573
  const isProject = Boolean(opts.project) && !opts.global;
1279
1574
  const cwd = process.cwd();
1280
- const vaultPath = path6.resolve(opts.path ?? (isProject ? path6.join(cwd, "Alexandria") : defaultVaultPath()));
1575
+ const vaultPath = path7.resolve(opts.path ?? (isProject ? path7.join(cwd, "Alexandria") : defaultVaultPath()));
1281
1576
  await showBanner();
1282
1577
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
1283
1578
  `));
@@ -1327,8 +1622,8 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1327
1622
  }
1328
1623
  }
1329
1624
  if (auto) {
1330
- const file = configureClaudeMd(isProject ? "project" : "global", cwd);
1331
- console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${file}`));
1625
+ const files = configureClaudeMd(isProject ? "project" : "global", cwd);
1626
+ console.log(pc.green(`\u2713 Uso autom\xE1tico configurado en ${files.join(", ")}`));
1332
1627
  } else {
1333
1628
  console.log(pc.dim(" Sin auto-configuraci\xF3n (act\xEDvala luego con: ale init --auto)"));
1334
1629
  }
@@ -1358,27 +1653,27 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1358
1653
  const res = await idx.refresh();
1359
1654
  console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
1360
1655
  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."));
1656
+ console.log(pc.dim(" Captura autom\xE1tica (hooks): Claude Code, Codex, Gemini CLI, Cursor y OpenCode. El resto usa las tools MCP."));
1362
1657
  console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents'));
1363
1658
  console.log(pc.dim(" Controla qu\xE9 gasta tokens (antes o despu\xE9s de instalar): ale toggles\n"));
1364
1659
  if (opts.skills) await runSkills({ yes: false, project: isProject });
1365
1660
  });
1366
1661
  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
1662
  const { vault } = await ensureReady();
1368
- const abs = path6.resolve(file);
1369
- const raw = fs6.readFileSync(abs, "utf8");
1663
+ const abs = path7.resolve(file);
1664
+ const raw = fs7.readFileSync(abs, "utf8");
1370
1665
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
1371
- const title = opts.title ?? heading ?? path6.basename(abs).replace(/\.(md|txt)$/i, "");
1666
+ const title = opts.title ?? heading ?? path7.basename(abs).replace(/\.(md|txt)$/i, "");
1372
1667
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
1373
1668
  const noteFile = createNote(vault.managed, {
1374
1669
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
1375
1670
  type: "plan",
1376
1671
  status: "active",
1377
- tags: ["plan"],
1672
+ tags: ["plan", path7.basename(process.cwd())],
1378
1673
  content: raw.trim()
1379
1674
  });
1380
1675
  await VaultIndex.load(vault).refresh();
1381
- console.log(pc.green(`\u2713 Plan creado: ${path6.relative(vault.root, noteFile)}`));
1676
+ console.log(pc.green(`\u2713 Plan creado: ${path7.relative(vault.root, noteFile)}`));
1382
1677
  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
1678
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1384
1679
  const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
@@ -1440,44 +1735,67 @@ program.command("config").description("Configuraci\xF3n de Alexandria (ej. proto
1440
1735
  }
1441
1736
  console.log(pc.yellow("Acci\xF3n inv\xE1lida: usa get o set"));
1442
1737
  });
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) => {
1738
+ async function runClean(opts) {
1444
1739
  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."));
1740
+ const log = (m) => {
1741
+ if (!opts.quiet) console.log(m);
1742
+ };
1743
+ const plan = planClean(vault, Object.values(idx.meta.notes), {
1744
+ days: parseInt(opts.days, 10) || 45,
1745
+ keepNoise: opts.keepNoise
1746
+ });
1747
+ if (opts.promptsOnly) {
1748
+ plan.tmpFiles = [];
1749
+ plan.staleModels = [];
1750
+ }
1751
+ const nPrompts = [...plan.bundles.values()].reduce((s, l) => s + l.length, 0);
1752
+ const valuable = Object.values(idx.meta.notes).filter((n) => n.type !== "prompt").length;
1753
+ const before = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
1754
+ const mb = (b) => `${(b / 1024 / 1024).toFixed(1)} MB`;
1755
+ log(pc.bold("\n\u{1F9F9} Limpieza segura de la b\xF3veda") + pc.dim(` (${vault.root})`));
1756
+ log(pc.dim(` Intacto siempre: ${valuable} notas de conocimiento (lecciones, planes, mapas, sesiones, verificaciones, notas)`));
1757
+ log(` \u2022 ${nPrompts} prompts viejos sin reuso \u2192 ${plan.bundles.size} archivos compactados (texto \xEDntegro) en ${ARCHIVE_DIR}/`);
1758
+ log(` \u2022 ${plan.noise.length} prompts que inyect\xF3 el arn\xE9s (notificaciones/recordatorios) \u2192 ${opts.keepNoise ? "se compactan" : "se descartan"}`);
1759
+ if (plan.tmpFiles.length) log(` \u2022 ${plan.tmpFiles.length} temporales hu\xE9rfanos del \xEDndice`);
1760
+ if (plan.staleModels.length) log(` \u2022 ${plan.staleModels.length} modelos viejos en cach\xE9: ${plan.staleModels.map((m) => path7.basename(m)).join(", ")}`);
1761
+ if (plan.statsLinesToRotate) log(` \u2022 stats.jsonl: ${plan.statsLinesToRotate} l\xEDneas de >90 d\xEDas \u2192 resumen (los totales de \`ale stats\` no cambian)`);
1762
+ const nothing = nPrompts + plan.noise.length + plan.tmpFiles.length + plan.staleModels.length + plan.statsLinesToRotate === 0;
1763
+ if (nothing) {
1764
+ log(pc.dim("\n Nada que limpiar."));
1765
+ markCleaned(vault);
1451
1766
  return;
1452
1767
  }
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
- }
1768
+ if (!opts.yes) {
1769
+ log(pc.dim("\n Vista previa (no se toc\xF3 nada). Aplica con: ale clean --yes \xB7 respaldo antes: --backup <archivo.tar.gz>\n"));
1770
+ return;
1462
1771
  }
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.`));
1772
+ if (opts.backup) {
1773
+ const out = path7.resolve(opts.backup);
1774
+ execFileSync4("tar", ["-czf", out, "-C", vault.root, path7.relative(vault.root, vault.managed) || "."], { stdio: "ignore" });
1775
+ log(pc.green(`\u2713 Respaldo en ${out}`));
1472
1776
  }
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) => {
1777
+ const res = applyClean(vault, plan);
1778
+ await VaultIndex.load(vault).refresh();
1779
+ markCleaned(vault);
1780
+ const after = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
1781
+ log(
1782
+ pc.green(
1783
+ `
1784
+ \u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados`
1785
+ )
1786
+ );
1787
+ log(pc.dim(` B\xF3veda ${mb(before.vault)} \u2192 ${mb(after.vault)} \xB7 \xEDndice ${mb(before.cache)} \u2192 ${mb(after.cache)}`));
1788
+ log(pc.dim(' Lo compactado sigue buscable: ale search --archive "<texto>"\n'));
1789
+ }
1790
+ 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);
1791
+ 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 }));
1792
+ 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
1793
  if (!ids) {
1476
1794
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Agentes de IA soportados:\n"));
1477
1795
  for (const a of AGENTS) {
1478
1796
  const det = a.detect();
1479
1797
  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)")}`
1798
+ ` ${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
1799
  );
1482
1800
  }
1483
1801
  console.log(pc.dim("\n Registrar MCP: ale agents all \xB7 ale agents detected \xB7 ale agents cursor,opencode\n"));
@@ -1488,17 +1806,17 @@ program.command("agents").description("Lista los agentes de IA soportados y regi
1488
1806
  console.log(pc.yellow(`Ning\xFAn agente coincide con \xAB${ids}\xBB. Ids v\xE1lidos: ${AGENTS.map((a) => a.id).join(", ")}`));
1489
1807
  return;
1490
1808
  }
1491
- registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd());
1809
+ registerAgentsMcp(chosen, opts.project ? "project" : "global", process.cwd(), false, opts.hooks);
1492
1810
  console.log(pc.dim("\n Reinicia el agente (o recarga sus MCP) para que tome el servidor.\n"));
1493
1811
  });
1494
1812
  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
1813
  const { vault } = await ensureReady();
1496
1814
  let content = opts.content;
1497
1815
  if (!content && opts.file) {
1498
- content = fs6.readFileSync(path6.resolve(opts.file), "utf8");
1816
+ content = fs7.readFileSync(path7.resolve(opts.file), "utf8");
1499
1817
  }
1500
1818
  if (!content && !process.stdin.isTTY) {
1501
- content = fs6.readFileSync(0, "utf8");
1819
+ content = fs7.readFileSync(0, "utf8");
1502
1820
  }
1503
1821
  const file = createNote(vault.managed, {
1504
1822
  title,
@@ -1506,15 +1824,26 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
1506
1824
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
1507
1825
  });
1508
1826
  await VaultIndex.load(vault).refresh();
1509
- console.log(pc.green(`\u2713 ${path6.relative(vault.root, file)}`));
1827
+ console.log(pc.green(`\u2713 ${path7.relative(vault.root, file)}`));
1510
1828
  });
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) => {
1829
+ 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
1830
  const vault = getVault();
1513
1831
  if (!vaultExists(vault)) {
1514
1832
  console.log(pc.yellow("No hay b\xF3veda aqu\xED. Corre `ale init` primero."));
1515
1833
  return;
1516
1834
  }
1517
1835
  const q = query.join(" ");
1836
+ if (opts.archive) {
1837
+ const hits = searchArchive(vault, q, parseInt(opts.k, 10) || 6);
1838
+ if (hits.length === 0) console.log(pc.dim("Sin resultados en el archivo."));
1839
+ for (const h of hits) {
1840
+ console.log(`
1841
+ ${pc.bold(pc.cyan(h.heading))} ${pc.dim(`(${h.file})`)}`);
1842
+ console.log(pc.dim(" " + h.excerpt.replace(/\n+/g, " ").slice(0, 300)));
1843
+ }
1844
+ console.log();
1845
+ return;
1846
+ }
1518
1847
  const results = await hybridSearch(vault, q, parseInt(opts.k, 10) || 6, { expand: opts.expand });
1519
1848
  if (results.length === 0) {
1520
1849
  console.log(pc.dim("Sin resultados."));
@@ -1600,7 +1929,7 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1600
1929
  console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
1601
1930
  }
1602
1931
  if (s.notes.length) {
1603
- for (const n of s.notes) console.log(pc.dim(` ${path6.relative(vault.root, n)}`));
1932
+ for (const n of s.notes) console.log(pc.dim(` ${path7.relative(vault.root, n)}`));
1604
1933
  } else {
1605
1934
  console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1606
1935
  }
@@ -1651,6 +1980,13 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1651
1980
  console.log(` Inyecciones de contexto: ${s.injections}`);
1652
1981
  console.log(` Aciertos de cach\xE9 de soluci\xF3n: ${s.solutionCacheHits} (${s.cacheHitTokens.toLocaleString()} tokens \u2014 el ahorro m\xE1s claro: soluciones no re-derivadas)`);
1653
1982
  console.log(` Tokens inyectados (costo): ~${s.injectedTokens.toLocaleString()}`);
1983
+ if (s.docIngests + s.docReads > 0) {
1984
+ const saved = Math.max(0, s.docTokensOriginal - s.docTokensServed);
1985
+ const pct = s.docTokensOriginal ? Math.round(saved / s.docTokensOriginal * 100) : 0;
1986
+ console.log(
1987
+ ` Documentos: ${s.docIngests} ingestas \xB7 ${s.docReads} lecturas \xB7 ~${s.docTokensServed.toLocaleString()} tokens entregados vs ~${s.docTokensOriginal.toLocaleString()} de leer los originales \u2192 ${pc.green(`~${saved.toLocaleString()} ahorrados (${pct}%)`)}`
1988
+ );
1989
+ }
1654
1990
  if (s.injectedTokens > 0) {
1655
1991
  console.log(pc.bold("\n\u{1F4B0} Ahorro estimado ") + pc.dim("(banda, NO auditado)"));
1656
1992
  console.log(` ~${pc.green(s.estSavedLow.toLocaleString())} \u2013 ${pc.green(s.estSavedHigh.toLocaleString())} tokens`);
@@ -1661,7 +1997,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1661
1997
  async function runSkills(opts) {
1662
1998
  const { vault } = await ensureReady();
1663
1999
  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");
2000
+ const targetDir = opts.project ? path7.join(cwd, ".claude", "skills") : path7.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1665
2001
  const recs = await recommendSkills(vault, [targetDir]);
1666
2002
  if (recs.length === 0) {
1667
2003
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -1703,7 +2039,7 @@ program.command("skills").description("Analiza la b\xF3veda y recomienda/instala
1703
2039
  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
2040
  const { vault } = await ensureReady();
1705
2041
  const cwd = process.cwd();
1706
- const proj = path6.basename(cwd);
2042
+ const proj = path7.basename(cwd);
1707
2043
  const targetDir = skillTargetDir(cwd, Boolean(opts.global));
1708
2044
  const result = evolveSkill(vault, proj, targetDir);
1709
2045
  if (!result) {
@@ -1790,10 +2126,10 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1790
2126
  );
1791
2127
  }
1792
2128
  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;
2129
+ const name = path7.basename(cwd);
2130
+ const mapFile = path7.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
2131
+ const pkgM = fs7.statSync(path7.join(cwd, "package.json")).mtimeMs;
2132
+ const mapM = fs7.statSync(mapFile).mtimeMs;
1797
2133
  if (pkgM > mapM) {
1798
2134
  console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1799
2135
  } else {
@@ -1801,41 +2137,104 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1801
2137
  }
1802
2138
  } catch {
1803
2139
  }
2140
+ const all = Object.values(idx.meta.notes);
2141
+ const prompts = all.filter((n) => n.type === "prompt").length;
2142
+ if (prompts > 5 * Math.max(1, all.length - prompts)) {
2143
+ 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)`));
2144
+ }
1804
2145
  const skillsRepoCfg = localSkillsRepo();
1805
- if (skillsRepoCfg && !fs6.existsSync(skillsRepoCfg)) {
2146
+ if (skillsRepoCfg && !fs7.existsSync(skillsRepoCfg)) {
1806
2147
  console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1807
2148
  }
1808
2149
  console.log();
1809
2150
  });
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) => {
2151
+ 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
2152
  const cwd = process.cwd();
1812
2153
  const scope = opts.project ? "project" : "global";
1813
2154
  const settings = opts.project ? projectSettingsPath(cwd) : globalSettingsPath();
1814
2155
  unregisterHooks(settings);
1815
2156
  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."));
2157
+ for (const f of removeClaudeMd(scope, cwd)) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${f}`));
2158
+ for (const agent of AGENTS) {
2159
+ if (agent.unregister?.(scope, cwd)) console.log(pc.green(`\u2713 MCP removido de ${agent.name}`));
2160
+ }
2161
+ for (const h of HOOK_HARNESSES) {
2162
+ if (unregisterHarnessHooks(h, scope, cwd)) console.log(pc.green(`\u2713 Hooks removidos de ${h}`));
2163
+ }
2164
+ if (!opts.project) {
2165
+ console.log(pc.dim(" Hermes: qu\xEDtalo con `hermes mcp remove alexandria` si lo registraste. Tus notas quedan intactas."));
1834
2166
  }
1835
2167
  });
1836
2168
  program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
1837
2169
  await import("./mcp/server.js");
1838
2170
  });
2171
+ program.command("ingest").description("Convierte documentos (PDF, DOCX, XLSX, CSV, HTML, MD) a markdown por secciones y los indexa: el agente lee solo lo que necesita").argument("<paths...>", "archivos o carpetas").option("--force", "reconvertir aunque el archivo no haya cambiado").action(async (paths, opts) => {
2172
+ const vault = getVault();
2173
+ ensureVaultStructure(vault);
2174
+ const files = [];
2175
+ for (const p of paths) {
2176
+ const abs = path7.resolve(p);
2177
+ if (!fs7.existsSync(abs)) {
2178
+ console.log(pc.yellow(`\u26A0 No existe: ${abs}`));
2179
+ continue;
2180
+ }
2181
+ if (fs7.statSync(abs).isDirectory()) {
2182
+ for (const f of fs7.readdirSync(abs, { recursive: true })) {
2183
+ const full = path7.join(abs, f);
2184
+ if (formatOf(full) && !f.split(path7.sep).some((x) => x.startsWith(".") || x === "node_modules") && fs7.statSync(full).isFile()) files.push(full);
2185
+ }
2186
+ } else files.push(abs);
2187
+ }
2188
+ let original = 0;
2189
+ let served = 0;
2190
+ for (const f of files) {
2191
+ try {
2192
+ const { text, doc, reused } = await ingestAndOutline(vault, f, { force: opts.force });
2193
+ original += doc.tokensOriginal;
2194
+ served += Math.ceil(text.length / 4);
2195
+ console.log(`
2196
+ ${pc.green(reused ? "= " : "\u2713 ")}${pc.bold(doc.title)} ${pc.dim(`\u2192 ${doc.rel}`)}`);
2197
+ if (files.length === 1) console.log(pc.dim(text.split("\n").map((l) => " " + l).join("\n")));
2198
+ else console.log(pc.dim(` ${doc.sections.length} secciones \xB7 original \u2248 ${doc.tokensOriginal.toLocaleString()} tokens`));
2199
+ } catch (e) {
2200
+ console.log(pc.yellow(`\u26A0 ${path7.basename(f)}: ${e.message}`));
2201
+ }
2202
+ }
2203
+ if (files.length > 1) console.log(pc.dim(`
2204
+ ${files.length} documentos \xB7 original \u2248 ${original.toLocaleString()} tokens \xB7 \xEDndices \u2248 ${served.toLocaleString()}`));
2205
+ console.log(pc.dim('\nEl agente los consulta con doc_read (o: ale docs read <doc> --query "\u2026").\n'));
2206
+ });
2207
+ var docsCmd = program.command("docs").description("Documentos ingeridos: lista, o lectura por secciones con presupuesto de tokens");
2208
+ docsCmd.action(() => {
2209
+ const docs = listDocs(getVault());
2210
+ if (docs.length === 0) {
2211
+ console.log(pc.dim("Sin documentos. Ingiere con: ale ingest <archivo|carpeta>"));
2212
+ return;
2213
+ }
2214
+ console.log(pc.bold(`
2215
+ \u{1F4C4} ${docs.length} documentos
2216
+ `));
2217
+ for (const d of docs) {
2218
+ console.log(` ${pc.cyan(d.title.padEnd(40))} ${d.format.padEnd(8)} ${String(d.sections.length).padStart(4)} secc \xB7 original \u2248 ${d.tokensOriginal.toLocaleString()} tok`);
2219
+ }
2220
+ console.log();
2221
+ });
2222
+ docsCmd.command("read").description("Lee secciones de un documento (por id o por pregunta) sin pasar de --max-tokens").argument("<doc>", "ruta del original, t\xEDtulo o parte del nombre").option("-s, --section <ids>", "ids separados por coma (s1,s3)").option("-q, --query <text>", "pregunta: devuelve las secciones m\xE1s relevantes").option("--max-tokens <n>", "presupuesto", "1500").action(async (doc, opts) => {
2223
+ const text = await readDoc(getVault(), doc, {
2224
+ sections: opts.section?.split(",").filter(Boolean),
2225
+ query: opts.query,
2226
+ maxTokens: parseInt(opts.maxTokens, 10) || 1500
2227
+ });
2228
+ console.log("\n" + text + "\n");
2229
+ });
2230
+ program.command("hook").description("Corre un hook (lo usan los plugins de Claude Code/Codex): session-start | prompt | stop | read").argument("<event>", "session-start | prompt | stop | read").option("--harness <id>", "claude | codex | gemini | cursor | opencode", "claude").action(async (event) => {
2231
+ const i = process.argv.indexOf("--harness");
2232
+ if (i > -1 && process.argv[i + 1]) process.argv.push(`--harness=${process.argv[i + 1]}`);
2233
+ if (event === "session-start") await import("./hooks/on-session-start.js");
2234
+ else if (event === "prompt") await import("./hooks/on-prompt.js");
2235
+ else if (event === "stop") await import("./hooks/on-stop.js");
2236
+ else if (event === "read") await import("./hooks/on-read.js");
2237
+ });
1839
2238
  if (process.argv.length <= 2) {
1840
2239
  await showBanner();
1841
2240
  program.outputHelp();