@ureck/alexandria 1.4.0 → 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.
@@ -0,0 +1,262 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/docs/convert.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var PDF_TOKENS_PER_PAGE = 2e3;
7
+ var ROWS_PER_SECTION = 50;
8
+ var SAMPLE_VALUES = 3;
9
+ var MAX_CELL = 160;
10
+ var MIN_CHARS_PER_PAGE = 40;
11
+ var SUPPORTED_EXT = {
12
+ ".pdf": "pdf",
13
+ ".docx": "docx",
14
+ ".html": "html",
15
+ ".htm": "html",
16
+ ".xlsx": "xlsx",
17
+ ".csv": "csv",
18
+ ".tsv": "csv",
19
+ ".md": "markdown",
20
+ ".markdown": "markdown",
21
+ ".txt": "text"
22
+ };
23
+ function formatOf(file) {
24
+ return SUPPORTED_EXT[path.extname(file).toLowerCase()];
25
+ }
26
+ var tokens = (s) => Math.ceil(s.length / 4);
27
+ async function convertFile(abs) {
28
+ const format = formatOf(abs);
29
+ if (!format) throw new Error(`Formato no soportado: ${path.extname(abs) || abs} (soportados: ${Object.keys(SUPPORTED_EXT).join(" ")})`);
30
+ const buf = fs.readFileSync(abs);
31
+ switch (format) {
32
+ case "pdf":
33
+ return pdfToMarkdown(buf);
34
+ case "docx": {
35
+ const mammoth = (await import("mammoth")).default;
36
+ const { value } = await mammoth.convertToHtml({ buffer: buf });
37
+ const markdown = await htmlToMarkdown(value);
38
+ return { format, markdown, tokensOriginal: tokens(markdown) };
39
+ }
40
+ case "html": {
41
+ const markdown = await htmlToMarkdown(buf.toString("utf8"));
42
+ return { format, markdown, tokensOriginal: tokens(buf.toString("utf8")) };
43
+ }
44
+ case "xlsx":
45
+ return xlsxToMarkdown(buf);
46
+ case "csv": {
47
+ const text = buf.toString("utf8");
48
+ const delim = path.extname(abs).toLowerCase() === ".tsv" ? " " : sniffDelimiter(text);
49
+ const rows = parseCsv(text, delim);
50
+ const markdown = sheetsToMarkdown([{ name: path.basename(abs), rows }]);
51
+ return { format, markdown, rows: Math.max(0, rows.length - 1), tokensOriginal: tokens(text) };
52
+ }
53
+ default: {
54
+ const markdown = buf.toString("utf8");
55
+ return { format, markdown, tokensOriginal: tokens(markdown) };
56
+ }
57
+ }
58
+ }
59
+ async function pdfToMarkdown(buf) {
60
+ const { getDocumentProxy } = await import("unpdf");
61
+ const pdf = await getDocumentProxy(new Uint8Array(buf));
62
+ const lines = [];
63
+ for (let p = 1; p <= pdf.numPages; p++) {
64
+ const tc = await (await pdf.getPage(p)).getTextContent();
65
+ const byY = /* @__PURE__ */ new Map();
66
+ for (const it of tc.items) {
67
+ if (!it.str || !it.transform) continue;
68
+ const y = Math.round(it.transform[5]);
69
+ const size = Math.round(Math.hypot(it.transform[0], it.transform[1]) || it.height || 0);
70
+ const arr = byY.get(y) ?? [];
71
+ arr.push({ x: it.transform[4], str: it.str, size });
72
+ byY.set(y, arr);
73
+ }
74
+ for (const y of [...byY.keys()].sort((a, b) => b - a)) {
75
+ const parts = byY.get(y).sort((a, b) => a.x - b.x);
76
+ const text = parts.map((x) => x.str).join(" ").replace(/\s+/g, " ").trim();
77
+ if (text) lines.push({ page: p, text, size: Math.max(...parts.map((x) => x.size)) });
78
+ }
79
+ }
80
+ const bySize = [...lines].sort((a, b) => a.size - b.size);
81
+ const totalChars = lines.reduce((n, l) => n + l.text.length, 0);
82
+ let acc = 0;
83
+ const median = bySize.find((l) => (acc += l.text.length) >= totalChars / 2)?.size ?? 0;
84
+ const isHeading = (l) => median > 0 && l.size >= median * 1.3 && l.text.length <= 120;
85
+ const hasHeadings = lines.some(isHeading);
86
+ const out = [];
87
+ let page = 0;
88
+ let para = [];
89
+ const flush = () => {
90
+ if (para.length) out.push(para.join(" ").replace(/^#/, "\\#"));
91
+ para = [];
92
+ };
93
+ for (const l of lines) {
94
+ if (l.page !== page) {
95
+ flush();
96
+ page = l.page;
97
+ if (!hasHeadings) out.push(`## P\xE1gina ${page}`);
98
+ }
99
+ if (hasHeadings && isHeading(l)) {
100
+ flush();
101
+ const prev = out[out.length - 1];
102
+ const m = prev?.match(/^## (.+) \(p\. (\d+)\)$/);
103
+ if (m && Number(m[2]) === l.page && m[1].length + l.text.length < 240) {
104
+ out[out.length - 1] = `## ${m[1]} ${l.text} (p. ${l.page})`;
105
+ } else {
106
+ out.push(`## ${l.text} (p. ${l.page})`);
107
+ }
108
+ } else {
109
+ para.push(l.text);
110
+ if (/[.:;!?]$/.test(l.text)) flush();
111
+ }
112
+ }
113
+ flush();
114
+ const chars = lines.reduce((n, l) => n + l.text.length, 0);
115
+ if (chars < MIN_CHARS_PER_PAGE * pdf.numPages) {
116
+ out.unshift(
117
+ `## \u26A0 PDF escaneado (sin capa de texto)
118
+
119
+ Solo se extrajeron ${chars} caracteres en ${pdf.numPages} p\xE1gina(s): el contenido es imagen. Alexandria no hace OCR; para leerlo hay que verlo como imagen (Read del archivo, ~${PDF_TOKENS_PER_PAGE.toLocaleString("en")} tokens por p\xE1gina) \u2014 de preferencia solo las p\xE1ginas necesarias.`
120
+ );
121
+ }
122
+ return {
123
+ format: "pdf",
124
+ markdown: out.join("\n\n"),
125
+ pages: pdf.numPages,
126
+ tokensOriginal: pdf.numPages * PDF_TOKENS_PER_PAGE
127
+ };
128
+ }
129
+ async function htmlToMarkdown(html) {
130
+ const TurndownService = (await import("turndown")).default;
131
+ const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-" });
132
+ td.remove(["script", "style", "nav", "footer", "aside", "noscript", "iframe", "svg"]);
133
+ td.addRule("table", {
134
+ filter: "table",
135
+ replacement: (_content, node) => {
136
+ const rows = Array.from(node.querySelectorAll("tr")).map(
137
+ (tr) => Array.from(tr.children).map((c) => cell(c.textContent ?? ""))
138
+ );
139
+ return rows.length ? "\n\n" + mdTable(rows) + "\n\n" : "";
140
+ }
141
+ });
142
+ td.addRule("img", { filter: "img", replacement: (_c, node) => node.getAttribute("alt") ? `[imagen: ${node.getAttribute("alt")}]` : "" });
143
+ return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim();
144
+ }
145
+ var cell = (v) => {
146
+ const t = String(v ?? "").replace(/\s+/g, " ").trim();
147
+ return (t.length > MAX_CELL ? t.slice(0, MAX_CELL) + `\u2026(+${t.length - MAX_CELL})` : t).replace(/\|/g, "\\|");
148
+ };
149
+ function mdTable(rows) {
150
+ const width = Math.max(...rows.map((r) => r.length));
151
+ const pad = (r) => [...r, ...Array(width - r.length).fill("")];
152
+ const [head, ...body] = rows.map(pad);
153
+ return [`| ${head.join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...body.map((r) => `| ${r.join(" | ")} |`)].join("\n");
154
+ }
155
+ function inferType(values) {
156
+ const vals = values.filter((v) => v !== "");
157
+ if (vals.length === 0) return "vac\xEDa";
158
+ if (vals.every((v) => /^-?\d+(\.\d+)?(e[-+]?\d+)?$/i.test(v.replace(/,/g, "")))) return "n\xFAmero";
159
+ if (vals.every((v) => !isNaN(Date.parse(v)) && /\d{4}|\d{1,2}[/-]\d{1,2}/.test(v))) return "fecha";
160
+ if (new Set(vals).size <= Math.max(5, vals.length * 0.05)) return `categor\xEDa (${new Set(vals).size} valores)`;
161
+ return "texto";
162
+ }
163
+ function sheetsToMarkdown(sheets) {
164
+ const out = [];
165
+ for (const { name, rows } of sheets) {
166
+ const clean = rows.filter((r) => r.some((c) => c !== ""));
167
+ if (clean.length === 0) continue;
168
+ const [header, ...data] = clean;
169
+ const cols = header.map((h, i) => h || `col${i + 1}`);
170
+ out.push(`## Hoja \xAB${name}\xBB \u2014 resumen`);
171
+ out.push(`Filas de datos: ${data.length} \xB7 Columnas: ${cols.length}`);
172
+ out.push(
173
+ mdTable([
174
+ ["columna", "tipo", "ejemplos"],
175
+ ...cols.map((c, i) => {
176
+ const values = data.map((r) => r[i] ?? "");
177
+ const sample = [...new Set(values.filter(Boolean))].slice(0, SAMPLE_VALUES).map((v) => v.slice(0, 40));
178
+ return [cell(c), inferType(values), cell(sample.join(", "))];
179
+ })
180
+ ])
181
+ );
182
+ for (let i = 0; i < data.length; i += ROWS_PER_SECTION) {
183
+ const block = data.slice(i, i + ROWS_PER_SECTION);
184
+ out.push(`## Hoja \xAB${name}\xBB \xB7 filas ${i + 1}\u2013${i + block.length}`);
185
+ out.push(mdTable([cols.map(cell), ...block.map((r) => r.map(cell))]));
186
+ }
187
+ }
188
+ return out.join("\n\n");
189
+ }
190
+ async function xlsxToMarkdown(buf) {
191
+ const ExcelJS = (await import("exceljs")).default;
192
+ const wb = new ExcelJS.Workbook();
193
+ await wb.xlsx.load(buf);
194
+ const sheets = [];
195
+ let totalRows = 0;
196
+ let rawChars = 0;
197
+ wb.eachSheet((ws) => {
198
+ const rows = [];
199
+ ws.eachRow({ includeEmpty: false }, (row) => {
200
+ const vals = row.values.slice(1).map(cellText);
201
+ rows.push(vals);
202
+ rawChars += vals.join(",").length + 1;
203
+ });
204
+ totalRows += Math.max(0, rows.length - 1);
205
+ sheets.push({ name: ws.name, rows });
206
+ });
207
+ return { format: "xlsx", markdown: sheetsToMarkdown(sheets), rows: totalRows, tokensOriginal: Math.ceil(rawChars / 4) };
208
+ }
209
+ function cellText(v) {
210
+ if (v === null || v === void 0) return "";
211
+ if (v instanceof Date) return v.toISOString().slice(0, 10);
212
+ if (typeof v === "object") {
213
+ const o = v;
214
+ if (o.richText) return o.richText.map((t) => t.text).join("");
215
+ if (o.text !== void 0) return String(o.text);
216
+ if (o.result !== void 0) return cellText(o.result);
217
+ return "";
218
+ }
219
+ return String(v);
220
+ }
221
+ function sniffDelimiter(text) {
222
+ const first = text.split(/\r?\n/, 1)[0] ?? "";
223
+ const counts = [",", ";", " ", "|"].map((d) => [d, first.split(d).length]);
224
+ return counts.sort((a, b) => b[1] - a[1])[0][0];
225
+ }
226
+ function parseCsv(text, delim = ",") {
227
+ const rows = [];
228
+ let row = [];
229
+ let field = "";
230
+ let quoted = false;
231
+ for (let i = 0; i < text.length; i++) {
232
+ const c = text[i];
233
+ if (quoted) {
234
+ if (c === '"' && text[i + 1] === '"') {
235
+ field += '"';
236
+ i++;
237
+ } else if (c === '"') quoted = false;
238
+ else field += c;
239
+ } else if (c === '"' && field === "") quoted = true;
240
+ else if (c === delim) {
241
+ row.push(field.trim());
242
+ field = "";
243
+ } else if (c === "\n" || c === "\r") {
244
+ if (c === "\r" && text[i + 1] === "\n") i++;
245
+ row.push(field.trim());
246
+ rows.push(row);
247
+ row = [];
248
+ field = "";
249
+ } else field += c;
250
+ }
251
+ if (field !== "" || row.length) {
252
+ row.push(field.trim());
253
+ rows.push(row);
254
+ }
255
+ return rows;
256
+ }
257
+
258
+ export {
259
+ PDF_TOKENS_PER_PAGE,
260
+ formatOf,
261
+ convertFile
262
+ };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-3CB7GRFJ.js";
4
+ } from "./chunk-BV2KJV5W.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -4,7 +4,7 @@ import {
4
4
  defaultOutput,
5
5
  formatContext,
6
6
  normalizeInput
7
- } from "./chunk-MDGFK6UC.js";
7
+ } from "./chunk-CEHNXDUE.js";
8
8
 
9
9
  // src/hooks/util.ts
10
10
  import fs from "fs";
package/dist/cli.js CHANGED
@@ -4,21 +4,24 @@ import {
4
4
  distDir,
5
5
  globalSettingsPath,
6
6
  hooksRegistered,
7
+ ingestAndOutline,
8
+ listDocs,
7
9
  mcpRegisteredProject,
8
10
  pkgVersion,
9
11
  planContext,
10
12
  planQualityHints,
11
13
  projectSettingsPath,
14
+ readDoc,
12
15
  registerHooks,
13
16
  registerMcpGlobal,
14
17
  registerMcpProject,
15
18
  serverCommand,
16
19
  unregisterHooks
17
- } from "./chunk-JI2L66DF.js";
20
+ } from "./chunk-SAKIVZMP.js";
18
21
  import {
19
22
  hybridSearch,
20
23
  protocolChain
21
- } from "./chunk-FPKJVQ2X.js";
24
+ } from "./chunk-Y6S6SKH4.js";
22
25
  import {
23
26
  ARCHIVE_DIR,
24
27
  applyClean,
@@ -26,7 +29,13 @@ import {
26
29
  markCleaned,
27
30
  planClean,
28
31
  searchArchive
29
- } from "./chunk-2ESJQAP4.js";
32
+ } from "./chunk-B7HCWKPJ.js";
33
+ import {
34
+ readStats
35
+ } from "./chunk-POA77JSS.js";
36
+ import {
37
+ formatOf
38
+ } from "./chunk-UU4MGB2C.js";
30
39
  import {
31
40
  TOKEN_TOGGLES,
32
41
  defaultVaultPath,
@@ -35,23 +44,22 @@ import {
35
44
  globalConfigPath,
36
45
  initScopeWarning,
37
46
  protocolEnabled,
38
- readStats,
39
47
  resolveVault,
40
48
  setConfigKey,
41
49
  toggleEnabled,
42
50
  vaultExists,
43
51
  writeGlobalConfig,
44
52
  writeProjectConfig
45
- } from "./chunk-MDGFK6UC.js";
53
+ } from "./chunk-CEHNXDUE.js";
46
54
  import {
47
55
  serveGraph
48
- } from "./chunk-4ZSTD3CU.js";
56
+ } from "./chunk-GP5A2GWI.js";
49
57
  import {
50
58
  VaultIndex,
51
59
  createNote,
52
60
  slugify,
53
61
  upsertNote
54
- } from "./chunk-3CB7GRFJ.js";
62
+ } from "./chunk-BV2KJV5W.js";
55
63
  import {
56
64
  MODEL_ID,
57
65
  dot,
@@ -1020,6 +1028,7 @@ var BLOCK = [
1020
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.",
1021
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.",
1022
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.",
1023
1032
  CLAUDE_MD_END
1024
1033
  ].join("\n");
1025
1034
  function instructionFiles(scope, projectDir) {
@@ -1971,6 +1980,13 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1971
1980
  console.log(` Inyecciones de contexto: ${s.injections}`);
1972
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)`);
1973
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
+ }
1974
1990
  if (s.injectedTokens > 0) {
1975
1991
  console.log(pc.bold("\n\u{1F4B0} Ahorro estimado ") + pc.dim("(banda, NO auditado)"));
1976
1992
  console.log(` ~${pc.green(s.estSavedLow.toLocaleString())} \u2013 ${pc.green(s.estSavedHigh.toLocaleString())} tokens`);
@@ -2152,12 +2168,72 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
2152
2168
  program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
2153
2169
  await import("./mcp/server.js");
2154
2170
  });
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) => {
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) => {
2156
2231
  const i = process.argv.indexOf("--harness");
2157
2232
  if (i > -1 && process.argv[i + 1]) process.argv.push(`--harness=${process.argv[i + 1]}`);
2158
2233
  if (event === "session-start") await import("./hooks/on-session-start.js");
2159
2234
  else if (event === "prompt") await import("./hooks/on-prompt.js");
2160
2235
  else if (event === "stop") await import("./hooks/on-stop.js");
2236
+ else if (event === "read") await import("./hooks/on-read.js");
2161
2237
  });
2162
2238
  if (process.argv.length <= 2) {
2163
2239
  await showBanner();
@@ -4,21 +4,23 @@ import {
4
4
  projectName,
5
5
  runHook,
6
6
  truncate
7
- } from "../chunk-U2U53TU2.js";
7
+ } from "../chunk-ZDS6VULX.js";
8
8
  import {
9
9
  hybridSearch
10
- } from "../chunk-FPKJVQ2X.js";
10
+ } from "../chunk-Y6S6SKH4.js";
11
+ import {
12
+ logInjection
13
+ } from "../chunk-POA77JSS.js";
11
14
  import {
12
15
  isHarnessInjected,
13
- logInjection,
14
16
  resolveVault,
15
17
  toggleEnabled,
16
18
  vaultExists
17
- } from "../chunk-MDGFK6UC.js";
19
+ } from "../chunk-CEHNXDUE.js";
18
20
  import {
19
21
  createNote,
20
22
  touchNote
21
- } from "../chunk-3CB7GRFJ.js";
23
+ } from "../chunk-BV2KJV5W.js";
22
24
  import "../chunk-EDYBSJSS.js";
23
25
 
24
26
  // src/hooks/on-prompt.ts
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ runHook
4
+ } from "../chunk-ZDS6VULX.js";
5
+ import {
6
+ PDF_TOKENS_PER_PAGE,
7
+ formatOf
8
+ } from "../chunk-UU4MGB2C.js";
9
+ import {
10
+ resolveVault,
11
+ toggleEnabled,
12
+ vaultExists
13
+ } from "../chunk-CEHNXDUE.js";
14
+
15
+ // src/hooks/on-read.ts
16
+ import fs from "fs";
17
+ import path from "path";
18
+ var MIN_BYTES = 20 * 1024;
19
+ var INTERCEPT = /* @__PURE__ */ new Set(["pdf", "docx", "xlsx", "csv"]);
20
+ var MAX_SESSIONS = 20;
21
+ function shouldIntercept(cacheDir, sessionId, file) {
22
+ const store = path.join(cacheDir, "read-intercepts.json");
23
+ let data = {};
24
+ try {
25
+ data = JSON.parse(fs.readFileSync(store, "utf8"));
26
+ } catch {
27
+ }
28
+ const seen = data[sessionId] ?? [];
29
+ if (seen.includes(file)) return false;
30
+ data[sessionId] = [...seen, file];
31
+ const keys = Object.keys(data);
32
+ for (const k of keys.slice(0, Math.max(0, keys.length - MAX_SESSIONS))) delete data[k];
33
+ try {
34
+ fs.mkdirSync(cacheDir, { recursive: true });
35
+ fs.writeFileSync(store, JSON.stringify(data));
36
+ } catch {
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+ runHook(2e3, async (input) => {
42
+ if (!toggleEnabled("docs.interceptRead")) return;
43
+ const file = input.filePath;
44
+ if (!file || input.toolName && input.toolName !== "Read") return;
45
+ const format = formatOf(file);
46
+ if (!format || !INTERCEPT.has(format)) return;
47
+ let size = 0;
48
+ try {
49
+ size = fs.statSync(file).size;
50
+ } catch {
51
+ return;
52
+ }
53
+ if (size < MIN_BYTES) return;
54
+ const vault = resolveVault({ cwd: input.cwd });
55
+ if (!vaultExists(vault)) return;
56
+ if (!shouldIntercept(vault.cache, input.session_id ?? "sin-sesion", path.resolve(file))) return;
57
+ const cost = format === "pdf" ? `un PDF le\xEDdo directo cuesta ~${PDF_TOKENS_PER_PAGE.toLocaleString("en")} tokens POR P\xC1GINA (imagen + texto)` : `leer el ${format.toUpperCase()} completo cuesta ~${Math.ceil(size / 4).toLocaleString("en")} tokens`;
58
+ process.stdout.write(
59
+ JSON.stringify({
60
+ hookSpecificOutput: {
61
+ hookEventName: "PreToolUse",
62
+ permissionDecision: "deny",
63
+ permissionDecisionReason: `Alexandria: ${cost}. Usa la tool MCP doc_ingest con path "${file}" (devuelve el \xEDndice de secciones, ~200 tokens) y luego doc_read con las secciones o una pregunta. Si de verdad necesitas ver im\xE1genes o gr\xE1ficas del archivo, vuelve a llamar Read: el segundo intento pasa.`
64
+ }
65
+ })
66
+ );
67
+ });
68
+ export {
69
+ shouldIntercept
70
+ };
@@ -4,17 +4,19 @@ import {
4
4
  projectName,
5
5
  runHook,
6
6
  truncate
7
- } from "../chunk-U2U53TU2.js";
7
+ } from "../chunk-ZDS6VULX.js";
8
+ import {
9
+ logInjection
10
+ } from "../chunk-POA77JSS.js";
8
11
  import {
9
- logInjection,
10
12
  protocolEnabled,
11
13
  resolveVault,
12
14
  toggleEnabled,
13
15
  vaultExists
14
- } from "../chunk-MDGFK6UC.js";
16
+ } from "../chunk-CEHNXDUE.js";
15
17
  import {
16
18
  VaultIndex
17
- } from "../chunk-3CB7GRFJ.js";
19
+ } from "../chunk-BV2KJV5W.js";
18
20
  import "../chunk-EDYBSJSS.js";
19
21
 
20
22
  // src/hooks/on-session-start.ts
@@ -3,22 +3,23 @@ import {
3
3
  projectName,
4
4
  runHook,
5
5
  truncate
6
- } from "../chunk-U2U53TU2.js";
6
+ } from "../chunk-ZDS6VULX.js";
7
7
  import {
8
8
  autoCleanDue,
9
9
  markCleaned
10
- } from "../chunk-2ESJQAP4.js";
10
+ } from "../chunk-B7HCWKPJ.js";
11
+ import "../chunk-POA77JSS.js";
11
12
  import {
12
13
  ensureVaultStructure,
13
14
  lastExchange,
14
15
  resolveVault,
15
16
  toggleEnabled,
16
17
  vaultExists
17
- } from "../chunk-MDGFK6UC.js";
18
+ } from "../chunk-CEHNXDUE.js";
18
19
  import {
19
20
  VaultIndex,
20
21
  appendToNote
21
- } from "../chunk-3CB7GRFJ.js";
22
+ } from "../chunk-BV2KJV5W.js";
22
23
  import "../chunk-EDYBSJSS.js";
23
24
 
24
25
  // src/hooks/on-stop.ts
@@ -1,28 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  architectBlock,
4
+ ingestAndOutline,
4
5
  pkgVersion,
5
6
  planContext,
6
- planQualityHints
7
- } from "../chunk-JI2L66DF.js";
7
+ planQualityHints,
8
+ readDoc
9
+ } from "../chunk-SAKIVZMP.js";
8
10
  import {
9
11
  hybridSearch
10
- } from "../chunk-FPKJVQ2X.js";
12
+ } from "../chunk-Y6S6SKH4.js";
11
13
  import {
12
14
  searchArchive
13
- } from "../chunk-2ESJQAP4.js";
15
+ } from "../chunk-B7HCWKPJ.js";
16
+ import "../chunk-POA77JSS.js";
17
+ import "../chunk-UU4MGB2C.js";
14
18
  import {
15
19
  ensureVaultStructure,
16
20
  resolveVault,
17
21
  toggleEnabled
18
- } from "../chunk-MDGFK6UC.js";
22
+ } from "../chunk-CEHNXDUE.js";
19
23
  import {
20
24
  VaultIndex,
21
25
  createNote,
22
26
  setNoteStatus,
23
27
  slugify,
24
28
  upsertNote
25
- } from "../chunk-3CB7GRFJ.js";
29
+ } from "../chunk-BV2KJV5W.js";
26
30
  import "../chunk-EDYBSJSS.js";
27
31
 
28
32
  // src/mcp/server.ts
@@ -170,6 +174,38 @@ server.registerTool(
170
174
  return text(`Conectado: \xAB${a.title}\xBB \u2192 [[${b.title}]]`);
171
175
  }
172
176
  );
177
+ server.registerTool(
178
+ "doc_ingest",
179
+ {
180
+ description: "\xDAsala EN VEZ de leer directamente un PDF, DOCX, XLSX, CSV o HTML (leer un PDF cuesta ~2,000 tokens por p\xE1gina). La convierte localmente a markdown por secciones, la indexa y devuelve SOLO el \xEDndice de secciones (~200 tokens). Si el archivo no cambi\xF3, reutiliza la conversi\xF3n. Despu\xE9s pide lo que necesites con doc_read.",
181
+ inputSchema: {
182
+ path: z.string().describe("Ruta del archivo (absoluta o relativa al proyecto)"),
183
+ force: z.boolean().optional().describe("Reconvertir aunque no haya cambiado")
184
+ }
185
+ },
186
+ async ({ path: p, force }) => {
187
+ try {
188
+ const abs = path.isAbsolute(p) ? p : path.resolve(process.cwd(), p);
189
+ const res = await ingestAndOutline(vault, abs, { force });
190
+ return text(res.text);
191
+ } catch (e) {
192
+ return text(`No pude ingerir \xAB${p}\xBB: ${e.message}`);
193
+ }
194
+ }
195
+ );
196
+ server.registerTool(
197
+ "doc_read",
198
+ {
199
+ description: "Lee un documento ya ingerido SIN cargarlo completo: por ids de secci\xF3n (del \xEDndice de doc_ingest) o por pregunta (devuelve las secciones m\xE1s relevantes). Nunca pasa de max_tokens y dice qu\xE9 secciones quedaron fuera para que pidas m\xE1s solo si hace falta.",
200
+ inputSchema: {
201
+ doc: z.string().describe("Ruta del archivo original, t\xEDtulo o parte del nombre"),
202
+ sections: z.array(z.string()).optional().describe('Ids de secci\xF3n, ej. ["s2","s5"]'),
203
+ query: z.string().optional().describe("Pregunta: devuelve las secciones que la responden"),
204
+ max_tokens: z.number().int().min(200).max(2e4).optional().describe("Presupuesto de tokens (default 1500)")
205
+ }
206
+ },
207
+ async ({ doc, sections, query, max_tokens }) => text(await readDoc(vault, doc, { sections, query, maxTokens: max_tokens }))
208
+ );
173
209
  server.registerTool(
174
210
  "plan_create",
175
211
  {