@ureck/alexandria 1.4.0 → 1.6.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.
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/stats.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var charsToTokens = (chars) => Math.round(chars / 4);
7
+ function logInjection(vault, line) {
8
+ try {
9
+ fs.mkdirSync(vault.cache, { recursive: true });
10
+ fs.appendFileSync(
11
+ path.join(vault.cache, "stats.jsonl"),
12
+ JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), ...line }) + "\n"
13
+ );
14
+ } catch {
15
+ }
16
+ }
17
+ function logDocUse(vault, line) {
18
+ try {
19
+ fs.mkdirSync(vault.cache, { recursive: true });
20
+ fs.appendFileSync(path.join(vault.cache, "stats.jsonl"), JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), kind: "doc", ...line }) + "\n");
21
+ } catch {
22
+ }
23
+ }
24
+ function logFold(vault, line) {
25
+ try {
26
+ fs.mkdirSync(vault.cache, { recursive: true });
27
+ fs.appendFileSync(path.join(vault.cache, "stats.jsonl"), JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), kind: "fold", ...line }) + "\n");
28
+ } catch {
29
+ }
30
+ }
31
+ var EST_LOW = 3;
32
+ var EST_HIGH = 8;
33
+ function readStats(vault) {
34
+ const file = path.join(vault.cache, "stats.jsonl");
35
+ const summary = {
36
+ injections: 0,
37
+ solutionCacheHits: 0,
38
+ injectedTokens: 0,
39
+ cacheHitTokens: 0,
40
+ estSavedLow: 0,
41
+ estSavedHigh: 0,
42
+ docIngests: 0,
43
+ docReads: 0,
44
+ docTokensOriginal: 0,
45
+ docTokensServed: 0,
46
+ folds: 0,
47
+ foldTokensOriginal: 0,
48
+ foldTokensServed: 0,
49
+ dedupSavedTokens: 0
50
+ };
51
+ try {
52
+ for (const raw of fs.readFileSync(file, "utf8").split("\n")) {
53
+ if (!raw.trim()) continue;
54
+ try {
55
+ const line = JSON.parse(raw);
56
+ if (line.kind === "fold") {
57
+ const f = line;
58
+ summary.folds++;
59
+ summary.foldTokensOriginal += charsToTokens(f.originalChars ?? 0);
60
+ summary.foldTokensServed += charsToTokens(f.servedChars ?? 0);
61
+ continue;
62
+ }
63
+ if (line.kind === "doc") {
64
+ const d = line;
65
+ if (d.op === "ingest") summary.docIngests++;
66
+ else summary.docReads++;
67
+ summary.docTokensOriginal += d.tokensOriginal ?? 0;
68
+ summary.docTokensServed += d.tokensServed ?? 0;
69
+ continue;
70
+ }
71
+ const n = line.count ?? 1;
72
+ if (line.dedupSkippedChars) summary.dedupSavedTokens += charsToTokens(line.dedupSkippedChars);
73
+ summary.injections += n;
74
+ const tk = line.tokens ?? charsToTokens(line.injectedChars);
75
+ summary.injectedTokens += tk;
76
+ if (line.kind === "solution-cache") {
77
+ summary.solutionCacheHits += n;
78
+ summary.cacheHitTokens += tk;
79
+ }
80
+ } catch {
81
+ }
82
+ }
83
+ } catch {
84
+ }
85
+ summary.estSavedLow = summary.injectedTokens * EST_LOW;
86
+ summary.estSavedHigh = summary.injectedTokens * EST_HIGH;
87
+ return summary;
88
+ }
89
+ function readSessionUsage(vault) {
90
+ const by = /* @__PURE__ */ new Map();
91
+ let raw = "";
92
+ try {
93
+ raw = fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8");
94
+ } catch {
95
+ return [];
96
+ }
97
+ for (const l of raw.split("\n")) {
98
+ if (!l.trim()) continue;
99
+ let o;
100
+ try {
101
+ o = JSON.parse(l);
102
+ } catch {
103
+ continue;
104
+ }
105
+ if (!o.session || o.t === "summary") continue;
106
+ const u = by.get(o.session) ?? { session: o.session, first: o.t ?? "", last: o.t ?? "", injections: 0, injectedTokens: 0, dedupSavedTokens: 0, folds: 0, foldTokensOriginal: 0, foldTokensServed: 0, topNotes: [], notes: /* @__PURE__ */ new Map() };
107
+ if (o.t && o.t < u.first) u.first = o.t;
108
+ if (o.t && o.t > u.last) u.last = o.t;
109
+ if (o.kind === "fold") {
110
+ u.folds++;
111
+ u.foldTokensOriginal += charsToTokens(o.originalChars ?? 0);
112
+ u.foldTokensServed += charsToTokens(o.servedChars ?? 0);
113
+ } else if (o.kind !== "doc") {
114
+ u.injections++;
115
+ u.injectedTokens += charsToTokens(o.injectedChars ?? 0);
116
+ u.dedupSavedTokens += charsToTokens(o.dedupSkippedChars ?? 0);
117
+ for (const r of o.rels ?? []) u.notes.set(r, (u.notes.get(r) ?? 0) + 1);
118
+ }
119
+ by.set(o.session, u);
120
+ }
121
+ return [...by.values()].map(({ notes, ...u }) => ({ ...u, topNotes: [...notes].sort((a, b) => b[1] - a[1]).slice(0, 5) })).sort((a, b) => b.last.localeCompare(a.last));
122
+ }
123
+
124
+ export {
125
+ charsToTokens,
126
+ logInjection,
127
+ logDocUse,
128
+ logFold,
129
+ readStats,
130
+ readSessionUsage
131
+ };
@@ -148,6 +148,24 @@ var TOKEN_TOGGLES = [
148
148
  desc: "Si el \xEDndice qued\xF3 sin vectores, reconstruirlo en segundo plano al terminar la sesi\xF3n",
149
149
  impact: "no gasta tokens; sin esto la b\xFAsqueda puede quedarse en keyword-only (peor contexto por prompt)"
150
150
  },
151
+ {
152
+ key: "docs.interceptRead",
153
+ label: "Redirigir lectura de PDF/DOCX/XLSX",
154
+ desc: "En Claude Code, la primera lectura directa de un PDF/DOCX/XLSX/CSV grande se redirige a doc_ingest/doc_read (el segundo intento pasa)",
155
+ impact: "ahorra ~2,000 tokens por p\xE1gina de PDF; desact\xEDvalo si sueles necesitar ver im\xE1genes/gr\xE1ficas"
156
+ },
157
+ {
158
+ key: "run.fold",
159
+ label: "Plegar salida grande de comandos",
160
+ desc: "Builds/tests/installs/logs largos: el agente recibe errores + resumen + final; la salida completa queda en disco (ale run show)",
161
+ impact: "ahorra la mayor parte de un build o test suite (miles de tokens por corrida); desact\xEDvalo si quieres ver siempre todo"
162
+ },
163
+ {
164
+ key: "context.dedupe",
165
+ label: "No reinyectar lo ya inyectado",
166
+ desc: "Si una nota ya se inyect\xF3 en esta sesi\xF3n, se manda una referencia de 1 l\xEDnea en vez del extracto completo",
167
+ impact: "ahorra hasta ~1500 tokens por prompt en conversaciones largas sobre el mismo tema"
168
+ },
151
169
  {
152
170
  key: "clean.auto",
153
171
  label: "Limpieza autom\xE1tica semanal",
@@ -163,55 +181,6 @@ function writeProjectConfig(projectDir, vaultPath) {
163
181
  return file;
164
182
  }
165
183
 
166
- // src/core/stats.ts
167
- import fs2 from "fs";
168
- import path2 from "path";
169
- var charsToTokens = (chars) => Math.round(chars / 4);
170
- function logInjection(vault, line) {
171
- try {
172
- fs2.mkdirSync(vault.cache, { recursive: true });
173
- fs2.appendFileSync(
174
- path2.join(vault.cache, "stats.jsonl"),
175
- JSON.stringify({ t: (/* @__PURE__ */ new Date()).toISOString(), ...line }) + "\n"
176
- );
177
- } catch {
178
- }
179
- }
180
- var EST_LOW = 3;
181
- var EST_HIGH = 8;
182
- function readStats(vault) {
183
- const file = path2.join(vault.cache, "stats.jsonl");
184
- const summary = {
185
- injections: 0,
186
- solutionCacheHits: 0,
187
- injectedTokens: 0,
188
- cacheHitTokens: 0,
189
- estSavedLow: 0,
190
- estSavedHigh: 0
191
- };
192
- try {
193
- for (const raw of fs2.readFileSync(file, "utf8").split("\n")) {
194
- if (!raw.trim()) continue;
195
- try {
196
- const line = JSON.parse(raw);
197
- const n = line.count ?? 1;
198
- summary.injections += n;
199
- const tk = line.tokens ?? charsToTokens(line.injectedChars);
200
- summary.injectedTokens += tk;
201
- if (line.kind === "solution-cache") {
202
- summary.solutionCacheHits += n;
203
- summary.cacheHitTokens += tk;
204
- }
205
- } catch {
206
- }
207
- }
208
- } catch {
209
- }
210
- summary.estSavedLow = summary.injectedTokens * EST_LOW;
211
- summary.estSavedHigh = summary.injectedTokens * EST_HIGH;
212
- return summary;
213
- }
214
-
215
184
  // src/hooks/adapters.ts
216
185
  var HARNESSES = ["claude", "codex", "gemini", "cursor", "opencode"];
217
186
  function currentHarness(argv = process.argv) {
@@ -226,7 +195,13 @@ function normalizeInput(raw) {
226
195
  cwd: raw.cwd ?? raw.workspace_roots?.[0],
227
196
  prompt: raw.prompt,
228
197
  answer: raw.last_assistant_message ?? raw.prompt_response ?? raw.text,
229
- compact: /^(PreCompact|PreCompress|preCompact)$/.test(event) || Boolean(raw.trigger)
198
+ compact: /^(PreCompact|PreCompress|preCompact)$/.test(event) || Boolean(raw.trigger),
199
+ toolName: raw.tool_name,
200
+ filePath: raw.tool_input?.file_path,
201
+ command: typeof raw.tool_input?.command === "string" ? raw.tool_input.command : void 0,
202
+ toolResponse: raw.tool_response,
203
+ durationMs: raw.duration_ms,
204
+ source: raw.source
230
205
  };
231
206
  }
232
207
  function formatContext(harness, kind, text) {
@@ -275,7 +250,9 @@ function lastExchange(lines) {
275
250
  return { user, assistant };
276
251
  }
277
252
  function isHarnessInjected(prompt) {
278
- return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(prompt.trim());
253
+ const p = prompt.trim();
254
+ return /^<(task-notification|system-reminder|command-|local-command|user-prompt-submit-hook|ide_)/i.test(p) || // mensajes que el arnés escribe como si fueran del usuario
255
+ /^(Tool loaded\.|Your response above was cut off|This session is being continued from a previous conversation|\[Request interrupted|Caveat: The messages below were generated)/i.test(p);
279
256
  }
280
257
 
281
258
  export {
@@ -292,9 +269,6 @@ export {
292
269
  initScopeWarning,
293
270
  TOKEN_TOGGLES,
294
271
  writeProjectConfig,
295
- charsToTokens,
296
- logInjection,
297
- readStats,
298
272
  currentHarness,
299
273
  normalizeInput,
300
274
  formatContext,
package/dist/cli.js CHANGED
@@ -1,24 +1,34 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ serveGraph
4
+ } from "./chunk-SSTG2NOO.js";
2
5
  import {
3
6
  architectBlock,
4
7
  distDir,
5
8
  globalSettingsPath,
6
9
  hooksRegistered,
10
+ ingestAndOutline,
11
+ isUrl,
12
+ listDocs,
7
13
  mcpRegisteredProject,
14
+ outlineDir,
15
+ outlineFile,
8
16
  pkgVersion,
9
17
  planContext,
10
18
  planQualityHints,
11
19
  projectSettingsPath,
20
+ readDoc,
12
21
  registerHooks,
13
22
  registerMcpGlobal,
14
23
  registerMcpProject,
15
24
  serverCommand,
25
+ symbolSource,
16
26
  unregisterHooks
17
- } from "./chunk-JI2L66DF.js";
27
+ } from "./chunk-BXVNQVLX.js";
18
28
  import {
19
29
  hybridSearch,
20
30
  protocolChain
21
- } from "./chunk-FPKJVQ2X.js";
31
+ } from "./chunk-47S5I3D3.js";
22
32
  import {
23
33
  ARCHIVE_DIR,
24
34
  applyClean,
@@ -26,7 +36,29 @@ import {
26
36
  markCleaned,
27
37
  planClean,
28
38
  searchArchive
29
- } from "./chunk-2ESJQAP4.js";
39
+ } from "./chunk-WSVNMMNN.js";
40
+ import {
41
+ VaultIndex,
42
+ createNote,
43
+ slugify,
44
+ supersedeNote,
45
+ upsertNote
46
+ } from "./chunk-44QPE5IM.js";
47
+ import {
48
+ formatOf
49
+ } from "./chunk-I5H4BN3F.js";
50
+ import {
51
+ listRuns,
52
+ runCommand,
53
+ saveRun,
54
+ shouldFoldOutput,
55
+ showRun
56
+ } from "./chunk-OGVWOBYH.js";
57
+ import {
58
+ logFold,
59
+ readSessionUsage,
60
+ readStats
61
+ } from "./chunk-X4V6SYYA.js";
30
62
  import {
31
63
  TOKEN_TOGGLES,
32
64
  defaultVaultPath,
@@ -35,23 +67,13 @@ import {
35
67
  globalConfigPath,
36
68
  initScopeWarning,
37
69
  protocolEnabled,
38
- readStats,
39
70
  resolveVault,
40
71
  setConfigKey,
41
72
  toggleEnabled,
42
73
  vaultExists,
43
74
  writeGlobalConfig,
44
75
  writeProjectConfig
45
- } from "./chunk-MDGFK6UC.js";
46
- import {
47
- serveGraph
48
- } from "./chunk-4ZSTD3CU.js";
49
- import {
50
- VaultIndex,
51
- createNote,
52
- slugify,
53
- upsertNote
54
- } from "./chunk-3CB7GRFJ.js";
76
+ } from "./chunk-YICWI3U3.js";
55
77
  import {
56
78
  MODEL_ID,
57
79
  dot,
@@ -822,6 +844,7 @@ function opencodePlugin() {
822
844
  import { execFile } from 'node:child_process';
823
845
 
824
846
  const SCRIPTS = ${JSON.stringify(scripts, null, 2)};
847
+ const CLI = ${JSON.stringify(path4.join(distDir(), "cli.js"))};
825
848
 
826
849
  function run(script, payload, timeoutMs) {
827
850
  return new Promise((resolve) => {
@@ -874,6 +897,24 @@ const AlexandriaPlugin = async ({ directory }) => {
874
897
  /* sin contexto este turno */
875
898
  }
876
899
  },
900
+ // Salida grande de bash \u2192 plegada (errores + resumen + final; completa en disco).
901
+ // Aqu\xED s\xED cubre comandos que fallan: OpenCode deja reescribir output.output.
902
+ 'tool.execute.after': async (input, output) => {
903
+ try {
904
+ if (input?.tool !== 'bash' || typeof output?.output !== 'string' || output.output.length <= 2048) return;
905
+ const command = String(input.args?.command ?? '');
906
+ const exit = Number(output.metadata?.exit ?? output.metadata?.exitCode ?? 0) || 0;
907
+ const folded = await new Promise((resolve) => {
908
+ const child = execFile('node', [CLI, 'run', '--stdin', '--command', command, '--exit', String(exit)], { cwd: directory, timeout: 8000, windowsHide: true, maxBuffer: 1 << 20 }, (_e, stdout) =>
909
+ resolve(typeof stdout === 'string' ? stdout.trim() : '')
910
+ );
911
+ child.stdin?.end(output.output);
912
+ });
913
+ if (folded && folded.length < output.output.length) output.output = folded;
914
+ } catch {
915
+ /* sin plegado: la salida original sigue intacta */
916
+ }
917
+ },
877
918
  'experimental.chat.system.transform': async (input, output) => {
878
919
  if (!Array.isArray(output?.system) || !input?.sessionID) return;
879
920
  const d = digest.get(input.sessionID);
@@ -1020,6 +1061,8 @@ var BLOCK = [
1020
1061
  "- 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
1062
  "- 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
1063
  "- `vault_related` trae conocimiento conectado sin releer archivos.",
1064
+ "- Tests/builds/installs con salida larga: `ale run -- <comando>` (devuelve errores + resumen + final y el mismo c\xF3digo de salida; lo completo con `ale run show <id> --grep \u2026`). Para explorar c\xF3digo: `code_outline` / `code_symbol` antes de leer archivos enteros.",
1065
+ "- 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.",
1023
1066
  CLAUDE_MD_END
1024
1067
  ].join("\n");
1025
1068
  function instructionFiles(scope, projectDir) {
@@ -1733,7 +1776,10 @@ async function runClean(opts) {
1733
1776
  };
1734
1777
  const plan = planClean(vault, Object.values(idx.meta.notes), {
1735
1778
  days: parseInt(opts.days, 10) || 45,
1736
- keepNoise: opts.keepNoise
1779
+ keepNoise: opts.keepNoise,
1780
+ dedupe: !opts.promptsOnly && !opts.quiet,
1781
+ // la limpieza automática ni siquiera los busca
1782
+ idx
1737
1783
  });
1738
1784
  if (opts.promptsOnly) {
1739
1785
  plan.tmpFiles = [];
@@ -1749,8 +1795,14 @@ async function runClean(opts) {
1749
1795
  log(` \u2022 ${plan.noise.length} prompts que inyect\xF3 el arn\xE9s (notificaciones/recordatorios) \u2192 ${opts.keepNoise ? "se compactan" : "se descartan"}`);
1750
1796
  if (plan.tmpFiles.length) log(` \u2022 ${plan.tmpFiles.length} temporales hu\xE9rfanos del \xEDndice`);
1751
1797
  if (plan.staleModels.length) log(` \u2022 ${plan.staleModels.length} modelos viejos en cach\xE9: ${plan.staleModels.map((m) => path7.basename(m)).join(", ")}`);
1798
+ if (plan.duplicates.length) {
1799
+ log(
1800
+ ` \u2022 ${plan.duplicates.length} posibles duplicados ${opts.dedupe ? "\u2192 la m\xE1s vieja se marca como reemplazada por la m\xE1s nueva (no se borra)" : pc.dim("(sugerencia: rev\xEDsalos; se aplican solo con --dedupe, o uno por uno con ale supersede)")}:`
1801
+ );
1802
+ for (const d of plan.duplicates.slice(0, 10)) log(pc.dim(` \xAB${d.older.title}\xBB \u2192 \xAB${d.newer.title}\xBB (coseno ${d.cos})`));
1803
+ }
1752
1804
  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;
1805
+ const nothing = nPrompts + plan.noise.length + plan.tmpFiles.length + plan.staleModels.length + plan.statsLinesToRotate + (opts.dedupe ? plan.duplicates.length : 0) === 0;
1754
1806
  if (nothing) {
1755
1807
  log(pc.dim("\n Nada que limpiar."));
1756
1808
  markCleaned(vault);
@@ -1765,20 +1817,20 @@ async function runClean(opts) {
1765
1817
  execFileSync4("tar", ["-czf", out, "-C", vault.root, path7.relative(vault.root, vault.managed) || "."], { stdio: "ignore" });
1766
1818
  log(pc.green(`\u2713 Respaldo en ${out}`));
1767
1819
  }
1768
- const res = applyClean(vault, plan);
1820
+ const res = applyClean(vault, plan, { applyDuplicates: opts.dedupe });
1769
1821
  await VaultIndex.load(vault).refresh();
1770
1822
  markCleaned(vault);
1771
1823
  const after = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
1772
1824
  log(
1773
1825
  pc.green(
1774
1826
  `
1775
- \u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados`
1827
+ \u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados \xB7 ${res.superseded} duplicados marcados`
1776
1828
  )
1777
1829
  );
1778
1830
  log(pc.dim(` B\xF3veda ${mb(before.vault)} \u2192 ${mb(after.vault)} \xB7 \xEDndice ${mb(before.cache)} \u2192 ${mb(after.cache)}`));
1779
1831
  log(pc.dim(' Lo compactado sigue buscable: ale search --archive "<texto>"\n'));
1780
1832
  }
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);
1833
+ 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("--dedupe", "aplicar tambi\xE9n los duplicados sugeridos (la m\xE1s vieja queda reemplazada por la m\xE1s nueva)").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
1834
  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
1835
  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) => {
1784
1836
  if (!ids) {
@@ -1971,6 +2023,20 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1971
2023
  console.log(` Inyecciones de contexto: ${s.injections}`);
1972
2024
  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)`);
1973
2025
  console.log(` Tokens inyectados (costo): ~${s.injectedTokens.toLocaleString()}`);
2026
+ if (s.dedupSavedTokens > 0) console.log(` No reinyectado (ya estaba en contexto): ~${s.dedupSavedTokens.toLocaleString()} tokens`);
2027
+ if (s.folds > 0) {
2028
+ const saved = Math.max(0, s.foldTokensOriginal - s.foldTokensServed);
2029
+ console.log(
2030
+ ` Salida de comandos plegada: ${s.folds} corridas \xB7 ~${s.foldTokensServed.toLocaleString()} tokens entregados vs ~${s.foldTokensOriginal.toLocaleString()} originales \u2192 ${pc.green(`~${saved.toLocaleString()} ahorrados`)}`
2031
+ );
2032
+ }
2033
+ if (s.docIngests + s.docReads > 0) {
2034
+ const saved = Math.max(0, s.docTokensOriginal - s.docTokensServed);
2035
+ const pct = s.docTokensOriginal ? Math.round(saved / s.docTokensOriginal * 100) : 0;
2036
+ console.log(
2037
+ ` 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}%)`)}`
2038
+ );
2039
+ }
1974
2040
  if (s.injectedTokens > 0) {
1975
2041
  console.log(pc.bold("\n\u{1F4B0} Ahorro estimado ") + pc.dim("(banda, NO auditado)"));
1976
2042
  console.log(` ~${pc.green(s.estSavedLow.toLocaleString())} \u2013 ${pc.green(s.estSavedHigh.toLocaleString())} tokens`);
@@ -2152,14 +2218,167 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
2152
2218
  program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
2153
2219
  await import("./mcp/server.js");
2154
2220
  });
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) => {
2221
+ program.command("context").description("Medidor de contexto: qu\xE9 inyect\xF3 Alexandria por sesi\xF3n, cu\xE1nto cost\xF3 y cu\xE1nto ahorr\xF3 (plegado, no-reinyecci\xF3n)").option("--session <id>", "detalle de una sesi\xF3n (id o prefijo)").option("--last <n>", "sesiones a mostrar", "10").action((o) => {
2222
+ const vault = getVault();
2223
+ const all = readSessionUsage(vault);
2224
+ const list = o.session ? all.filter((u) => u.session.startsWith(o.session)) : all.slice(0, parseInt(o.last, 10) || 10);
2225
+ if (list.length === 0) return console.log(pc.dim("Sin datos por sesi\xF3n todav\xEDa (se registran desde 1.6)."));
2226
+ let saved = 0;
2227
+ console.log(pc.bold("\n\u{1F4CF} Contexto por sesi\xF3n\n"));
2228
+ for (const u of list) {
2229
+ const fold = Math.max(0, u.foldTokensOriginal - u.foldTokensServed);
2230
+ saved += fold + u.dedupSavedTokens;
2231
+ console.log(
2232
+ ` ${pc.cyan(u.session.slice(0, 8))} ${pc.dim(u.last.slice(0, 16).replace("T", " "))} inyecciones ${u.injections} (~${u.injectedTokens.toLocaleString()} tok)` + (u.dedupSavedTokens ? ` \xB7 no reinyectado ~${u.dedupSavedTokens.toLocaleString()}` : "") + (u.folds ? ` \xB7 plegado ${u.folds}\xD7 ~${u.foldTokensOriginal.toLocaleString()}\u2192${u.foldTokensServed.toLocaleString()}` : "")
2233
+ );
2234
+ if (o.session) for (const [rel, n] of u.topNotes) console.log(pc.dim(` ${n}\xD7 ${rel}`));
2235
+ }
2236
+ console.log(pc.green(`
2237
+ Ahorro medido en estas sesiones: ~${saved.toLocaleString()} tokens (plegado + no reinyecci\xF3n)
2238
+ `));
2239
+ });
2240
+ program.command("supersede").description("Marca una nota como reemplazada por otra: deja de inyectarse y rankea abajo (no se borra)").argument("<vieja>", "t\xEDtulo o ruta de la nota desactualizada").argument("<nueva>", "t\xEDtulo o ruta de la nota que la reemplaza").action(async (oldRef, newRef) => {
2241
+ const { vault, idx } = await ensureReady();
2242
+ const find = (r) => Object.values(idx.meta.notes).find((n) => [n.title.toLowerCase(), n.rel.toLowerCase()].includes(r.toLowerCase().trim()));
2243
+ const a = find(oldRef);
2244
+ const b = find(newRef);
2245
+ if (!a || !b) return console.log(pc.yellow(`No encontr\xE9 ${!a ? `\xAB${oldRef}\xBB` : `\xAB${newRef}\xBB`}.`));
2246
+ supersedeNote(path7.join(vault.root, a.rel), b.title);
2247
+ await VaultIndex.load(vault).refresh();
2248
+ console.log(pc.green(`\u2713 \xAB${a.title}\xBB reemplazada por \xAB${b.title}\xBB \u2014 ya no se inyecta; sigue buscable.`));
2249
+ });
2250
+ var codeCmd = program.command("code").description("Mapa de c\xF3digo por s\xEDmbolos: firmas sin cuerpos y cuerpo de un s\xEDmbolo puntual");
2251
+ codeCmd.command("outline").description("Firmas de un archivo (con rangos de l\xEDnea) o resumen de una carpeta").argument("<ruta>", "archivo o carpeta").option("--max-tokens <n>", "tope para carpetas", "2500").action((p, o) => {
2252
+ const abs = path7.resolve(p);
2253
+ if (!fs7.existsSync(abs)) return console.log(pc.yellow(`No existe: ${abs}`));
2254
+ console.log(fs7.statSync(abs).isDirectory() ? outlineDir(abs, parseInt(o.maxTokens, 10) || 2500) : outlineFile(abs));
2255
+ });
2256
+ codeCmd.command("symbol").description("Cuerpo de un s\xEDmbolo (funci\xF3n, clase o Clase.metodo) con n\xFAmeros de l\xEDnea").argument("<archivo>").argument("<nombre>").action((f, name) => {
2257
+ const abs = path7.resolve(f);
2258
+ if (!fs7.existsSync(abs)) return console.log(pc.yellow(`No existe: ${abs}`));
2259
+ console.log(symbolSource(abs, name));
2260
+ });
2261
+ 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, carpetas o URLs de documentaci\xF3n").option("--force", "reconvertir aunque el archivo no haya cambiado").action(async (paths, opts) => {
2262
+ const vault = getVault();
2263
+ ensureVaultStructure(vault);
2264
+ const files = [];
2265
+ for (const p of paths) {
2266
+ if (isUrl(p)) {
2267
+ files.push(p.trim());
2268
+ continue;
2269
+ }
2270
+ const abs = path7.resolve(p);
2271
+ if (!fs7.existsSync(abs)) {
2272
+ console.log(pc.yellow(`\u26A0 No existe: ${abs}`));
2273
+ continue;
2274
+ }
2275
+ if (fs7.statSync(abs).isDirectory()) {
2276
+ for (const f of fs7.readdirSync(abs, { recursive: true })) {
2277
+ const full = path7.join(abs, f);
2278
+ if (formatOf(full) && !f.split(path7.sep).some((x) => x.startsWith(".") || x === "node_modules") && fs7.statSync(full).isFile()) files.push(full);
2279
+ }
2280
+ } else files.push(abs);
2281
+ }
2282
+ let original = 0;
2283
+ let served = 0;
2284
+ for (const f of files) {
2285
+ try {
2286
+ const { text, doc, reused } = await ingestAndOutline(vault, f, { force: opts.force });
2287
+ original += doc.tokensOriginal;
2288
+ served += Math.ceil(text.length / 4);
2289
+ console.log(`
2290
+ ${pc.green(reused ? "= " : "\u2713 ")}${pc.bold(doc.title)} ${pc.dim(`\u2192 ${doc.rel}`)}`);
2291
+ if (files.length === 1) console.log(pc.dim(text.split("\n").map((l) => " " + l).join("\n")));
2292
+ else console.log(pc.dim(` ${doc.sections.length} secciones \xB7 original \u2248 ${doc.tokensOriginal.toLocaleString()} tokens`));
2293
+ } catch (e) {
2294
+ console.log(pc.yellow(`\u26A0 ${path7.basename(f)}: ${e.message}`));
2295
+ }
2296
+ }
2297
+ if (files.length > 1) console.log(pc.dim(`
2298
+ ${files.length} documentos \xB7 original \u2248 ${original.toLocaleString()} tokens \xB7 \xEDndices \u2248 ${served.toLocaleString()}`));
2299
+ console.log(pc.dim('\nEl agente los consulta con doc_read (o: ale docs read <doc> --query "\u2026").\n'));
2300
+ });
2301
+ var docsCmd = program.command("docs").description("Documentos ingeridos: lista, o lectura por secciones con presupuesto de tokens");
2302
+ docsCmd.action(() => {
2303
+ const docs = listDocs(getVault());
2304
+ if (docs.length === 0) {
2305
+ console.log(pc.dim("Sin documentos. Ingiere con: ale ingest <archivo|carpeta>"));
2306
+ return;
2307
+ }
2308
+ console.log(pc.bold(`
2309
+ \u{1F4C4} ${docs.length} documentos
2310
+ `));
2311
+ for (const d of docs) {
2312
+ 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`);
2313
+ }
2314
+ console.log();
2315
+ });
2316
+ 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) => {
2317
+ const text = await readDoc(getVault(), doc, {
2318
+ sections: opts.section?.split(",").filter(Boolean),
2319
+ query: opts.query,
2320
+ maxTokens: parseInt(opts.maxTokens, 10) || 1500
2321
+ });
2322
+ console.log("\n" + text + "\n");
2323
+ });
2324
+ program.command("hook").description("Corre un hook (lo usan los plugins de Claude Code/Codex): session-start | prompt | stop | read | bash").argument("<event>", "session-start | prompt | stop | read | bash").option("--harness <id>", "claude | codex | gemini | cursor | opencode", "claude").action(async (event) => {
2156
2325
  const i = process.argv.indexOf("--harness");
2157
2326
  if (i > -1 && process.argv[i + 1]) process.argv.push(`--harness=${process.argv[i + 1]}`);
2158
2327
  if (event === "session-start") await import("./hooks/on-session-start.js");
2159
2328
  else if (event === "prompt") await import("./hooks/on-prompt.js");
2160
2329
  else if (event === "stop") await import("./hooks/on-stop.js");
2330
+ else if (event === "read") await import("./hooks/on-read.js");
2331
+ else if (event === "bash") await import("./hooks/on-bash.js");
2161
2332
  });
2162
- if (process.argv.length <= 2) {
2333
+ program.command("run").description("Ejecuta un comando y le entrega al agente su salida PLEGADA (errores, resumen, final); la completa queda en disco. Uso: ale run -- <comando>").addCommand(
2334
+ new Command("show").description("Muestra una corrida guardada (completa, por l\xEDneas o filtrada)").argument("<id>", 'id de la corrida, o "last"').option("--grep <regex>", "solo l\xEDneas que coinciden").option("--lines <a-b>", "rango de l\xEDneas").option("--max-tokens <n>", "presupuesto", "2000").action((id, o) => {
2335
+ console.log(showRun(id, { grep: o.grep, lines: o.lines, maxTokens: parseInt(o.maxTokens, 10) || 2e3 }));
2336
+ })
2337
+ ).addCommand(
2338
+ new Command("list").description("\xDAltimas corridas guardadas").action(() => {
2339
+ const runs = listRuns(15);
2340
+ if (runs.length === 0) console.log(pc.dim("Sin corridas guardadas."));
2341
+ for (const r of runs) {
2342
+ console.log(` ${pc.cyan(r.id)} exit ${r.exitCode} ${(r.ms / 1e3).toFixed(1)}s ${Math.ceil(r.chars / 4).toLocaleString()} tok ${pc.dim(r.command.slice(0, 70))}`);
2343
+ }
2344
+ })
2345
+ );
2346
+ async function runDispatch(args) {
2347
+ const vault = getVault();
2348
+ const log = (originalChars, servedChars) => {
2349
+ if (vaultExists(vault)) logFold(vault, { originalChars, servedChars, session: process.env.ALEXANDRIA_SESSION });
2350
+ };
2351
+ if (args[0] === "--stdin") {
2352
+ const ci = args.indexOf("--command");
2353
+ const ei = args.indexOf("--exit");
2354
+ const command3 = ci > -1 ? args[ci + 1] ?? "" : "";
2355
+ const chunks = [];
2356
+ for await (const c of process.stdin) chunks.push(c);
2357
+ const output = Buffer.concat(chunks).toString("utf8");
2358
+ if (!shouldFoldOutput(command3, output.length)) {
2359
+ process.stdout.write(output);
2360
+ return;
2361
+ }
2362
+ const { fold: fold2 } = saveRun({ command: command3, cwd: process.cwd(), output, exitCode: ei > -1 ? Number(args[ei + 1]) || 0 : 0, ms: 0 });
2363
+ if (fold2.folded) log(fold2.originalChars, fold2.text.length);
2364
+ process.stdout.write(fold2.text);
2365
+ return;
2366
+ }
2367
+ const rest = args[0] === "--" ? args.slice(1) : args;
2368
+ if (rest.length === 0) {
2369
+ console.log("Uso: ale run -- <comando> \xB7 ale run show <id|last> \xB7 ale run list");
2370
+ return;
2371
+ }
2372
+ const command2 = rest.length === 1 ? rest[0] : rest.map((a) => /[\s"'$`\\]/.test(a) ? JSON.stringify(a) : a).join(" ");
2373
+ const { meta, fold } = await runCommand(command2);
2374
+ if (fold.folded) log(fold.originalChars, fold.text.length);
2375
+ process.stdout.write(fold.text.endsWith("\n") ? fold.text : fold.text + "\n");
2376
+ process.exitCode = meta.exitCode;
2377
+ }
2378
+ var runArgs = process.argv.slice(3);
2379
+ if (process.argv[2] === "run" && !["show", "list", "--help", "-h"].includes(runArgs[0] ?? "--help")) {
2380
+ await runDispatch(runArgs);
2381
+ } else if (process.argv.length <= 2) {
2163
2382
  await showBanner();
2164
2383
  program.outputHelp();
2165
2384
  } else {
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ runHook
4
+ } from "../chunk-WVZQGLRI.js";
5
+ import {
6
+ saveRun,
7
+ shouldFoldOutput
8
+ } from "../chunk-OGVWOBYH.js";
9
+ import {
10
+ logFold
11
+ } from "../chunk-X4V6SYYA.js";
12
+ import {
13
+ resolveVault,
14
+ toggleEnabled,
15
+ vaultExists
16
+ } from "../chunk-YICWI3U3.js";
17
+ import "../chunk-EDYBSJSS.js";
18
+
19
+ // src/hooks/on-bash.ts
20
+ runHook(3e3, async (input) => {
21
+ if (!toggleEnabled("run.fold")) return;
22
+ if (input.toolName && input.toolName !== "Bash") return;
23
+ const res = input.toolResponse;
24
+ if (!input.command || !res || res.interrupted || res.isImage) return;
25
+ const stdout = typeof res.stdout === "string" ? res.stdout : "";
26
+ const stderr = typeof res.stderr === "string" ? res.stderr : "";
27
+ const output = stderr ? `${stdout}
28
+ ${stderr}` : stdout;
29
+ if (!shouldFoldOutput(input.command, output.length)) return;
30
+ const { fold } = saveRun({ command: input.command, cwd: input.cwd ?? process.cwd(), output, exitCode: 0, ms: input.durationMs ?? 0 });
31
+ if (!fold.folded) return;
32
+ process.stdout.write(
33
+ JSON.stringify({
34
+ hookSpecificOutput: {
35
+ hookEventName: "PostToolUse",
36
+ updatedToolOutput: { stdout: fold.text, stderr: "", interrupted: false, isImage: false }
37
+ }
38
+ })
39
+ );
40
+ try {
41
+ const vault = resolveVault({ cwd: input.cwd });
42
+ if (vaultExists(vault)) logFold(vault, { originalChars: fold.originalChars, servedChars: fold.text.length, session: input.session_id });
43
+ } catch {
44
+ }
45
+ });