@ureck/alexandria 1.5.0 → 1.6.1

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/README.md CHANGED
@@ -63,7 +63,7 @@ Verify:
63
63
 
64
64
  ```bash
65
65
  $ ale --version
66
- 1.5.0
66
+ 1.6.1
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -156,6 +156,30 @@ From any agent, the MCP tools `doc_ingest` (returns a ~200-token section outline
156
156
  - Unchanged files are never reconverted (sha256). Documents live in `Alexandria/docs/`, outside the vector index (a big spreadsheet would be thousands of chunks); section vectors are computed once per document version and cached.
157
157
  - `ale stats` shows the **measured** document savings: tokens of the originals vs tokens actually served.
158
158
 
159
+ ### Manage the context window (1.6)
160
+
161
+ Most tokens don't go into your prompt — they go into **tool output** and **re-reading**. Alexandria trims both, locally, without a proxy and without rewriting history (which would break the provider's prompt cache):
162
+
163
+ ```bash
164
+ ale run -- npm test # exit code preserved; agent gets errors + summary + tail
165
+ ale run show last --grep "FAIL|Error" # the full output stays on disk
166
+ ale code outline src/ # symbols per file, no bodies
167
+ ale code symbol src/cli.ts runClean # just that function, with line numbers
168
+ ale context # what was injected per session, and what was saved
169
+ ale supersede "Decision - MySQL" "Decision - Postgres"
170
+ ```
171
+
172
+ | Feature | What it does | Measured |
173
+ |---|---|---|
174
+ | **Folded command output** | Large outputs of tests/builds/installs/logs → errors (with stack location) + test summary + tail; full output in `~/.cache/alexandria/runs`. Automatic in Claude Code (`PostToolUse` on Bash, successful commands) and OpenCode (plugin, also failures); `ale run -- <cmd>` everywhere else. Commands that *read* (`cat`, `git diff`, `grep`…) are never folded | test suite 12.1 KB → 1.4 KB; failing run 12.6 KB → 561 B keeping the failing test, assertion and `file:line` |
175
+ | **Code map** | `code_outline` (signatures + line ranges, classes → methods, top-level constants) and `code_symbol` (one body). JS/TS, Python, PHP, Go, Java, C#, Kotlin, Rust — heuristic, no native deps | `src/cli.ts` ~13,600 tokens → outline ~253 |
176
+ | **No re-injection** | A note already injected in this session is referenced in one line instead of re-sent (toggle `context.dedupe`) | shown in `ale context` / `ale stats` |
177
+ | **Anti-compaction capsule** | Before compacting, a capsule (goal, last request, files edited/read, recent commands, what was saved, open plans) is built **without an LLM** and re-injected right after | real 8.4 MB transcript → ~576 tokens |
178
+ | **Facts that expire** | `vault_save(..., supersedes: [...])` / `ale supersede`: the old note is marked, linked and no longer injected — never deleted | |
179
+ | **Duplicate suggestions** | `ale clean` lists near-identical lessons/notes (cosine ≥ 0.96); applied only with `--dedupe` | |
180
+ | **Context meter** | `ale context [--session id]`: injections, tokens, notes, folded runs, savings per session | |
181
+ | **Docs by URL** | `doc_ingest`/`ale ingest` accept `https://…`: one page, fetched once, reused 7 days — the only network access, and only when asked | |
182
+
159
183
  ### Control what spends tokens (`ale toggles`)
160
184
 
161
185
  Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
@@ -166,7 +190,7 @@ ale init --off architect.enrich,digest.map # disable from the start
166
190
  ale config set tokens.solutionCache false # scriptable, one by one
167
191
  ```
168
192
 
169
- The toggles: Protocol manifest (~6% of the session digest), Architect enrichment in `plan_create` (~+90 tokens/plan), solution cache (up to ~500 tokens/prompt), per-prompt semantic search (the **main saving mechanism** — up to ~1500 tokens/prompt, disabling it defeats the point), project map in the digest (up to ~1000 tokens), title index (~200 tokens), redirecting direct reads of large PDFs/spreadsheets to `doc_read` (`docs.interceptRead`), background index rebuild at session close, and weekly background cleanup `clean.auto` (neither costs tokens). All on by default; nothing changes unless you touch them.
193
+ The toggles: Protocol manifest (~6% of the session digest), Architect enrichment in `plan_create` (~+90 tokens/plan), solution cache (up to ~500 tokens/prompt), per-prompt semantic search (the **main saving mechanism** — up to ~1500 tokens/prompt, disabling it defeats the point), project map in the digest (up to ~1000 tokens), title index (~200 tokens), redirecting direct reads of large PDFs/spreadsheets to `doc_read` (`docs.interceptRead`), folding large command output (`run.fold`), not re-injecting notes already in context (`context.dedupe`), background index rebuild at session close, and weekly background cleanup `clean.auto` (neither costs tokens). All on by default; nothing changes unless you touch them.
170
194
 
171
195
  ### Deep project context (`ale scan`)
172
196
 
@@ -314,6 +338,7 @@ AI agent session
314
338
  │ └─ near-identical prompt already solved → injects the solution (cache)
315
339
  ├─ MCP tools ─────► vault_search · vault_save · vault_related · vault_link (all agents)
316
340
  │ doc_ingest · doc_read (documents by section, token budget)
341
+ │ code_outline · code_symbol · run_output (code map, folded runs)
317
342
  │ plan_create · task_verify · lesson_extract (the Protocol)
318
343
  └─ Stop/PreCompact► saves the session outcome into the vault (hooks)
319
344
  hooks: Claude Code · Codex · Gemini CLI · Cursor · OpenCode (one set of scripts, --harness=<id>)
@@ -345,13 +370,17 @@ AI agent session
345
370
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
346
371
  | `ale skills [-y] [--project]` | Recommends & installs Claude skills — semantic (e5) + keyword detection over your vault. Local source configurable with `ale config set skills.repo <path>`; otherwise installs from skills.sh |
347
372
  | `ale reindex [--force]` | Reindex (incremental by default) |
348
- | `ale clean [--yes] [--days n] [--backup f] [--keep-noise]` | Safe cleanup: compacts old unused prompts (full text kept, out of the vector index), drops harness noise, purges regenerable caches, rotates stats. Preview by default. Runs weekly in the background (toggle `clean.auto`) |
373
+ | `ale clean [--yes] [--days n] [--backup f] [--keep-noise] [--dedupe]` | Safe cleanup: compacts old unused prompts (full text kept, out of the vector index), drops harness noise, purges regenerable caches, rotates stats. Preview by default. Runs weekly in the background (toggle `clean.auto`) |
349
374
  | `ale consolidate [--days n] [--dry]` | Alias of `ale clean --prompts-only` |
350
375
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
351
376
  | `ale uninstall [--project]` | Remove hooks, MCP and instruction blocks from every agent (notes stay untouched) |
352
377
  | `ale ingest <paths...> [--force]` | Convert PDF/DOCX/XLSX/CSV/HTML/MD to markdown sections and store them in the vault |
353
378
  | `ale docs` / `ale docs read <doc> [-s ids] [-q question] [--max-tokens n]` | List ingested documents / read only the sections (or spreadsheet rows) you need |
354
- | `ale hook <session-start\|prompt\|stop\|read> [--harness id]` | Run a hook (used by the plugins) |
379
+ | `ale run -- <cmd>` / `ale run show <id\|last> [--grep re] [--lines a-b]` / `ale run list` | Run a command with folded output (same exit code) / read the full output |
380
+ | `ale code outline <file\|dir>` / `ale code symbol <file> <name>` | Code map: signatures without bodies / one symbol's body (`Class.method` works) |
381
+ | `ale context [--session id] [--last n]` | Context meter per agent session |
382
+ | `ale supersede <old> <new>` | Mark a note as replaced (stops being injected, never deleted) |
383
+ | `ale hook <session-start\|prompt\|stop\|read\|bash> [--harness id]` | Run a hook (used by the plugins) |
355
384
  | `ale --vault <path> <cmd>` | Run any command against another vault |
356
385
 
357
386
  `alexandria` works as an alias of `ale`.
@@ -71,7 +71,7 @@ function parseNote(root, absPath) {
71
71
  const rel = path.relative(root, absPath).split(path.sep).join("/");
72
72
  const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
73
73
  const type = NOTE_TYPES.includes(data.type) ? data.type : "note";
74
- const status = ["active", "completed", "failed"].includes(data.status) ? data.status : void 0;
74
+ const status = ["active", "completed", "failed", "superseded"].includes(data.status) ? data.status : void 0;
75
75
  const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
76
76
  return {
77
77
  rel,
@@ -81,6 +81,7 @@ function parseNote(root, absPath) {
81
81
  tags,
82
82
  created: isoDate(data.created),
83
83
  hits: typeof data.hits === "number" ? data.hits : 1,
84
+ supersededBy: typeof data.superseded_by === "string" ? data.superseded_by : void 0,
84
85
  content,
85
86
  links: extractWikilinks(content)
86
87
  };
@@ -135,6 +136,18 @@ function setNoteStatus(absPath, status) {
135
136
  data.updated = (/* @__PURE__ */ new Date()).toISOString();
136
137
  fs.writeFileSync(absPath, matter.stringify(content, data));
137
138
  }
139
+ function supersedeNote(absPath, newTitle) {
140
+ const raw = fs.readFileSync(absPath, "utf8");
141
+ const { data, content } = matter(raw);
142
+ data.status = "superseded";
143
+ data.superseded_by = newTitle;
144
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
145
+ const marker = `> \u26A0 Reemplazada por [[${newTitle}]]`;
146
+ const body = content.includes(marker) ? content : `${marker}
147
+
148
+ ${content.trimStart()}`;
149
+ fs.writeFileSync(absPath, matter.stringify(body, data));
150
+ }
138
151
  function touchNote(absPath) {
139
152
  const raw = fs.readFileSync(absPath, "utf8");
140
153
  const { data, content } = matter(raw);
@@ -350,6 +363,7 @@ var VaultIndex = class _VaultIndex {
350
363
  title: note.title,
351
364
  type: note.type,
352
365
  status: note.status,
366
+ supersededBy: note.supersededBy,
353
367
  tags: note.tags,
354
368
  created: note.created,
355
369
  hits: note.hits,
@@ -404,7 +418,7 @@ ${c.text}`),
404
418
  if (this.emb !== null) this.clearNeedsRebuild();
405
419
  else if (this.meta.chunks.length > 0 && modelPresent()) this.markNeedsRebuild();
406
420
  if (!isHookProcess()) try {
407
- const { writeStaticGraph } = await import("./viewer-WQQSQETT.js");
421
+ const { writeStaticGraph } = await import("./viewer-T2SEBP6Z.js");
408
422
  writeStaticGraph(this);
409
423
  } catch {
410
424
  }
@@ -479,6 +493,35 @@ ${c.text}`),
479
493
  }
480
494
  return (this._tagIndex.get(key) ?? []).map((rel) => this.meta.notes[rel]).filter(Boolean);
481
495
  }
496
+ /**
497
+ * Vector por nota = media normalizada de sus chunks (mismo cálculo que el
498
+ * grafo semántico). Para detectar notas casi duplicadas en `ale clean`.
499
+ */
500
+ noteVectors(types) {
501
+ const out = /* @__PURE__ */ new Map();
502
+ if (!this.emb) return out;
503
+ const byNote = /* @__PURE__ */ new Map();
504
+ this.meta.chunks.forEach((c, i) => {
505
+ const n = this.meta.notes[c.note];
506
+ if (!n || !types.includes(n.type) || n.status === "superseded") return;
507
+ const arr = byNote.get(c.note) ?? [];
508
+ arr.push(i);
509
+ byNote.set(c.note, arr);
510
+ });
511
+ for (const [rel, idxs] of byNote) {
512
+ const v = new Float32Array(this.meta.dim);
513
+ for (const i of idxs) {
514
+ const r = this.row(i);
515
+ for (let d = 0; d < this.meta.dim; d++) v[d] += r[d];
516
+ }
517
+ let norm = 0;
518
+ for (let d = 0; d < this.meta.dim; d++) norm += v[d] * v[d];
519
+ norm = Math.sqrt(norm) || 1;
520
+ for (let d = 0; d < this.meta.dim; d++) v[d] /= norm;
521
+ out.set(rel, v);
522
+ }
523
+ return out;
524
+ }
482
525
  /** Vecinos directos de una nota en el grafo (sin releer archivos). */
483
526
  neighbors(rel) {
484
527
  const out = [];
@@ -497,6 +540,7 @@ export {
497
540
  isoDate,
498
541
  createNote,
499
542
  setNoteStatus,
543
+ supersedeNote,
500
544
  touchNote,
501
545
  upsertNote,
502
546
  appendToNote,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-BV2KJV5W.js";
4
+ } from "./chunk-44QPE5IM.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -48,7 +48,7 @@ var TYPE_BOOST = {
48
48
  };
49
49
  function recencyBoost(note) {
50
50
  if (!note) return 1;
51
- const typeBoost = TYPE_BOOST[note.type] ?? 1;
51
+ const typeBoost = (TYPE_BOOST[note.type] ?? 1) * (note.status === "superseded" ? 0.3 : 1);
52
52
  if (!note.created) return typeBoost;
53
53
  const age = (Date.now() - Date.parse(note.created)) / 864e5;
54
54
  if (Number.isNaN(age)) return typeBoost;
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ isHarnessInjected
4
+ } from "./chunk-YICWI3U3.js";
5
+
6
+ // src/core/capsule.ts
7
+ import fs from "fs";
8
+ import path from "path";
9
+ var MAX_SESSIONS = 30;
10
+ var CAPSULE_CHARS = 2400;
11
+ function injectedFile(cacheDir) {
12
+ return path.join(cacheDir, "injected.json");
13
+ }
14
+ function readStore(cacheDir) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(injectedFile(cacheDir), "utf8"));
17
+ } catch {
18
+ return {};
19
+ }
20
+ }
21
+ function injectedInSession(cacheDir, session) {
22
+ return new Set(readStore(cacheDir)[session]?.rels ?? []);
23
+ }
24
+ function rememberInjected(cacheDir, session, rels) {
25
+ if (!rels.length) return;
26
+ try {
27
+ const store = readStore(cacheDir);
28
+ const prev = store[session]?.rels ?? [];
29
+ store[session] = { rels: [.../* @__PURE__ */ new Set([...prev, ...rels])], t: (/* @__PURE__ */ new Date()).toISOString() };
30
+ const keys = Object.keys(store).sort((a, b) => store[a].t.localeCompare(store[b].t));
31
+ for (const k of keys.slice(0, Math.max(0, keys.length - MAX_SESSIONS))) delete store[k];
32
+ fs.mkdirSync(cacheDir, { recursive: true });
33
+ fs.writeFileSync(injectedFile(cacheDir), JSON.stringify(store));
34
+ } catch {
35
+ }
36
+ }
37
+ function forgetInjected(cacheDir, session) {
38
+ try {
39
+ const store = readStore(cacheDir);
40
+ if (!store[session]) return;
41
+ delete store[session];
42
+ fs.writeFileSync(injectedFile(cacheDir), JSON.stringify(store));
43
+ } catch {
44
+ }
45
+ }
46
+ var FILE_KEYS = ["file_path", "path", "notebook_path", "filePath"];
47
+ var TMP_PATH = /^(\/private)?\/tmp\/|^\/var\/folders\/|[\\/]scratchpad[\\/]|[\\/]tasks[\\/][^\\/]+\.output$/;
48
+ var EDIT_TOOLS = /^(Edit|Write|MultiEdit|NotebookEdit|apply_patch|edit|write)$/i;
49
+ function extractSession(lines) {
50
+ const out = { prompts: [], edited: [], read: [], commands: [], saved: [] };
51
+ for (const line of lines) {
52
+ let msg;
53
+ try {
54
+ msg = JSON.parse(line);
55
+ } catch {
56
+ continue;
57
+ }
58
+ const role = msg.message?.role ?? msg.type;
59
+ const content = msg.message?.content;
60
+ if (role === "user" && typeof content === "string") {
61
+ if (!content.trim().startsWith("<") && !isHarnessInjected(content)) out.prompts.push(content.trim());
62
+ continue;
63
+ }
64
+ if (!Array.isArray(content)) continue;
65
+ for (const b of content) {
66
+ if (role === "user" && b.type === "text" && b.text && !b.text.trim().startsWith("<") && !isHarnessInjected(b.text)) out.prompts.push(b.text.trim());
67
+ if (b.type !== "tool_use" || !b.input) continue;
68
+ const name = b.name ?? "";
69
+ const file = FILE_KEYS.map((k) => b.input[k]).find((v) => typeof v === "string" && /[\\/.]/.test(v));
70
+ if (file && !TMP_PATH.test(file)) (EDIT_TOOLS.test(name) ? out.edited : out.read).push(file);
71
+ if (/^(Bash|shell|bash)$/.test(name) && typeof b.input.command === "string") out.commands.push(b.input.command.split("\n")[0]);
72
+ if (/(vault_save|lesson_extract|plan_create)$/.test(name) && typeof b.input.title === "string") {
73
+ const prefix = name.endsWith("lesson_extract") ? "Lecci\xF3n - " : name.endsWith("plan_create") ? "Plan - " : "";
74
+ out.saved.push(prefix + b.input.title);
75
+ }
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+ var one = (s, n) => {
81
+ const t = s.replace(/\s+/g, " ").trim();
82
+ return t.length > n ? t.slice(0, n) + "\u2026" : t;
83
+ };
84
+ var uniq = (xs) => [...new Set(xs)];
85
+ var short = (p, cwd) => cwd && p.startsWith(cwd) ? path.relative(cwd, p) || p : p;
86
+ function buildCapsule(ex, opts = {}) {
87
+ const parts = [];
88
+ if (ex.prompts.length) {
89
+ parts.push(`Objetivo inicial: ${one(ex.prompts[0], 300)}`);
90
+ if (ex.prompts.length > 1) parts.push(`\xDAltimo pedido: ${one(ex.prompts[ex.prompts.length - 1], 300)}`);
91
+ const mid = uniq(ex.prompts.slice(1, -1)).slice(-4);
92
+ if (mid.length) parts.push(`Pedidos intermedios:
93
+ ${mid.map((p) => `- ${one(p, 150)}`).join("\n")}`);
94
+ }
95
+ const edited = uniq(ex.edited.map((f) => short(f, opts.cwd))).slice(-12);
96
+ const read = uniq(ex.read.map((f) => short(f, opts.cwd))).filter((f) => !edited.includes(f)).slice(-6);
97
+ if (edited.length) parts.push(`Archivos editados: ${edited.join(", ")}`);
98
+ if (read.length) parts.push(`Archivos consultados: ${read.join(", ")}`);
99
+ const cmds = uniq(ex.commands.map((c) => one(c, 90))).slice(-4);
100
+ if (cmds.length) parts.push(`Comandos recientes:
101
+ ${cmds.map((c) => `- ${c}`).join("\n")}`);
102
+ if (ex.saved.length) parts.push(`Guardado en la b\xF3veda: ${uniq(ex.saved).slice(-8).join(" \xB7 ")}`);
103
+ if (opts.openPlans?.length) parts.push(`Planes abiertos: ${opts.openPlans.slice(0, 5).join(" \xB7 ")}`);
104
+ if (!parts.length) return "";
105
+ const body = parts.join("\n");
106
+ return `<alexandria-capsula>
107
+ C\xE1psula de esta sesi\xF3n guardada antes de compactar \u2014 recupera lo que la compactaci\xF3n pudo perder (no re-explores lo que ya est\xE1 aqu\xED):
108
+ ` + (body.length > CAPSULE_CHARS ? body.slice(0, CAPSULE_CHARS) + "\u2026" : body) + `
109
+ </alexandria-capsula>`;
110
+ }
111
+ function capsuleFile(cacheDir, session) {
112
+ return path.join(cacheDir, "capsules", `${session.replace(/[^\w.-]/g, "_")}.md`);
113
+ }
114
+ function saveCapsule(cacheDir, session, text) {
115
+ if (!text) return;
116
+ try {
117
+ const f = capsuleFile(cacheDir, session);
118
+ fs.mkdirSync(path.dirname(f), { recursive: true });
119
+ fs.writeFileSync(f, text);
120
+ const dir = path.dirname(f);
121
+ const files = fs.readdirSync(dir).map((n) => ({ n, t: fs.statSync(path.join(dir, n)).mtimeMs })).sort((a, b) => a.t - b.t);
122
+ for (const x of files.slice(0, Math.max(0, files.length - MAX_SESSIONS))) fs.rmSync(path.join(dir, x.n), { force: true });
123
+ } catch {
124
+ }
125
+ }
126
+ function loadCapsule(cacheDir, session) {
127
+ try {
128
+ return fs.readFileSync(capsuleFile(cacheDir, session), "utf8");
129
+ } catch {
130
+ return null;
131
+ }
132
+ }
133
+
134
+ export {
135
+ injectedInSession,
136
+ rememberInjected,
137
+ forgetInjected,
138
+ extractSession,
139
+ buildCapsule,
140
+ saveCapsule,
141
+ loadCapsule
142
+ };
@@ -129,7 +129,7 @@ Solo se extrajeron ${chars} caracteres en ${pdf.numPages} p\xE1gina(s): el conte
129
129
  async function htmlToMarkdown(html) {
130
130
  const TurndownService = (await import("turndown")).default;
131
131
  const td = new TurndownService({ headingStyle: "atx", codeBlockStyle: "fenced", bulletListMarker: "-" });
132
- td.remove(["script", "style", "nav", "footer", "aside", "noscript", "iframe", "svg"]);
132
+ td.remove(["script", "style", "nav", "footer", "aside", "noscript", "iframe", "svg", "title", "head"]);
133
133
  td.addRule("table", {
134
134
  filter: "table",
135
135
  replacement: (_content, node) => {
@@ -163,7 +163,7 @@ function inferType(values) {
163
163
  function sheetsToMarkdown(sheets) {
164
164
  const out = [];
165
165
  for (const { name, rows } of sheets) {
166
- const clean = rows.filter((r) => r.some((c) => c !== ""));
166
+ const clean = rows.map((r) => Array.from(r ?? [], (c) => c ?? "")).filter((r) => r.some((c) => c !== ""));
167
167
  if (clean.length === 0) continue;
168
168
  const [header, ...data] = clean;
169
169
  const cols = header.map((h, i) => h || `col${i + 1}`);
@@ -188,35 +188,15 @@ function sheetsToMarkdown(sheets) {
188
188
  return out.join("\n\n");
189
189
  }
190
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 = [];
191
+ const { readXlsx } = await import("./xlsx-THZM4FNX.js");
192
+ const sheets = await readXlsx(buf);
195
193
  let totalRows = 0;
196
194
  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 "";
195
+ for (const sh of sheets) {
196
+ totalRows += Math.max(0, sh.rows.length - 1);
197
+ for (const r of sh.rows) rawChars += r.join(",").length + 1;
218
198
  }
219
- return String(v);
199
+ return { format: "xlsx", markdown: sheetsToMarkdown(sheets), rows: totalRows, tokensOriginal: Math.ceil(rawChars / 4) };
220
200
  }
221
201
  function sniffDelimiter(text) {
222
202
  const first = text.split(/\r?\n/, 1)[0] ?? "";
@@ -258,5 +238,6 @@ function parseCsv(text, delim = ",") {
258
238
  export {
259
239
  PDF_TOKENS_PER_PAGE,
260
240
  formatOf,
261
- convertFile
241
+ convertFile,
242
+ htmlToMarkdown
262
243
  };
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ modelCacheDir
4
+ } from "./chunk-EDYBSJSS.js";
5
+
6
+ // src/run/fold.ts
7
+ var FOLD_THRESHOLD = 2048;
8
+ var MAX_ERROR_LINES = 30;
9
+ var TAIL_LINES = 15;
10
+ var MAX_LINE = 300;
11
+ var ANSI = /\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07]*\x07/g;
12
+ var ERROR_RE = /\b(error|errors|fail|failed|failure|failing|fatal|panic|exception|traceback|ERR!|cannot find|not found|undefined is not|segmentation fault)\b|✗|✘|×\s|FAIL\b|E\d{3,}/i;
13
+ var SUMMARY_RE = /^\s*(tests?:|test files|test suites?:|suites?:|ran \d+ tests?|\d+ (passed|failed|passing|failing)|=+ .*(passed|failed).* =+|ok\s+\S+\s+[\d.]+s|build (succeeded|failed|success)|compiled (successfully|with)|found \d+ (vulnerabilit|error))/i;
14
+ function stripAnsi(s) {
15
+ return s.replace(ANSI, "").replace(/\r(?!\n)/g, "\n");
16
+ }
17
+ var clip = (l) => l.length > MAX_LINE ? l.slice(0, MAX_LINE) + "\u2026" : l;
18
+ function collapse(lines) {
19
+ const out = [];
20
+ for (const l of lines) {
21
+ if (!l.trim()) {
22
+ if (out.length && out[out.length - 1] !== "") out.push("");
23
+ continue;
24
+ }
25
+ const prev = out[out.length - 1];
26
+ const m = prev?.match(/^(.*) \(×(\d+)\)$/);
27
+ if (prev === l) out[out.length - 1] = `${l} (\xD72)`;
28
+ else if (m && m[1] === l) out[out.length - 1] = `${l} (\xD7${Number(m[2]) + 1})`;
29
+ else out.push(l);
30
+ }
31
+ return out;
32
+ }
33
+ function foldOutput({ output, exitCode, ms, id, command }) {
34
+ const clean = stripAnsi(output);
35
+ if (clean.length <= FOLD_THRESHOLD) return { text: clean, folded: false, originalChars: clean.length };
36
+ const lines = clean.split("\n");
37
+ const keep = /* @__PURE__ */ new Set();
38
+ let errors = 0;
39
+ const PASS = /^\s*(✓|✔|√|ok\b|PASS\b|passed\b)/i;
40
+ lines.forEach((l, i) => {
41
+ if (errors >= MAX_ERROR_LINES || PASS.test(l) || !ERROR_RE.test(l)) return;
42
+ for (let j = i - 1; j <= i + 3; j++) if (j >= 0 && j < lines.length && lines[j].trim()) keep.add(j);
43
+ errors++;
44
+ });
45
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
46
+ const tailStart = Math.max(0, lines.length - TAIL_LINES);
47
+ const summary = lines.filter((l, i) => i < tailStart && SUMMARY_RE.test(l)).slice(-8);
48
+ const errBlock = [];
49
+ let last = -2;
50
+ for (const i of [...keep].sort((a, b) => a - b)) {
51
+ if (i >= tailStart) continue;
52
+ if (i > last + 1 && errBlock.length) errBlock.push(" \u22EF");
53
+ errBlock.push(clip(lines[i]));
54
+ last = i;
55
+ }
56
+ const secs = (ms / 1e3).toFixed(1);
57
+ const parts = [
58
+ `\u29C9 ${command.length > 80 ? command.slice(0, 80) + "\u2026" : command} \xB7 exit ${exitCode} \xB7 ${secs}s \xB7 ${lines.length} l\xEDneas (${Math.ceil(clean.length / 4).toLocaleString("en")} tokens) \u2192 plegado por Alexandria`
59
+ ];
60
+ if (errBlock.length) parts.push(`\u2014 errores/fallos \u2014
61
+ ${collapse(errBlock).join("\n")}`);
62
+ const shown = new Set(errBlock);
63
+ const freshSummary = summary.map(clip).filter((l) => !shown.has(l));
64
+ if (freshSummary.length) parts.push(`\u2014 resumen \u2014
65
+ ${collapse(freshSummary).join("\n")}`);
66
+ parts.push(`\u2014 final \u2014
67
+ ${collapse(lines.slice(tailStart).map(clip)).join("\n").trim()}`);
68
+ parts.push(`salida completa: ale run show ${id} [--grep <regex>] [--lines a-b] (o tool MCP run_output)`);
69
+ return { text: parts.join("\n"), folded: true, originalChars: clean.length };
70
+ }
71
+ var NOISY = /^(\s*(npx\s+|bunx\s+)?)(npm|pnpm|yarn|bun)\s+(run\s+)?(test|build|lint|typecheck|check|install|i|ci|add|audit)\b|^\s*npx\s+(vitest|jest|tsc|eslint|next\s+build|playwright\s+test|prisma\s+(migrate|generate))\b|^\s*(pytest|python3?\s+-m\s+pytest|cargo\s+(build|test|check|clippy)|go\s+(test|build|vet)|mvn\b|\.?\/?gradlew?\b|docker\s+(build|compose\s+(up|build))|dotnet\s+(build|test)|composer\s+install|pip3?\s+install|make)\b/;
72
+ var VIEWER = /^\s*(cat|head|tail|sed|awk|less|more|bat|jq|yq|diff|grep|rg|find|ls|tree|curl|wget|wc|git\s+(show|diff|log|blame|status)|node\s+-[ep]|python3?\s+-c)\b/;
73
+ var GENERIC_FOLD = 4e4;
74
+ function shouldFoldOutput(command, chars) {
75
+ if (chars <= FOLD_THRESHOLD) return false;
76
+ if (/\bale\s+run\b|\balexandria\s+run\b|cli\.js"?\s+run\b/.test(command)) return false;
77
+ const last = (command.split("&&").pop() ?? "").trim();
78
+ if (NOISY.test(last)) return true;
79
+ return chars > GENERIC_FOLD && !VIEWER.test(last);
80
+ }
81
+
82
+ // src/run/run.ts
83
+ import fs from "fs";
84
+ import path from "path";
85
+ import crypto from "crypto";
86
+ import { spawn } from "child_process";
87
+ var KEEP_RUNS = 50;
88
+ var MAX_CAPTURE = 50 * 1024 * 1024;
89
+ function runsDir() {
90
+ return path.join(path.dirname(modelCacheDir()), "runs");
91
+ }
92
+ function newId() {
93
+ return Date.now().toString(36) + crypto.randomBytes(2).toString("hex");
94
+ }
95
+ function rotate() {
96
+ try {
97
+ const metas = fs.readdirSync(runsDir()).filter((f) => f.endsWith(".json")).sort();
98
+ for (const f of metas.slice(0, Math.max(0, metas.length - KEEP_RUNS))) {
99
+ const id = f.slice(0, -5);
100
+ fs.rmSync(path.join(runsDir(), `${id}.json`), { force: true });
101
+ fs.rmSync(path.join(runsDir(), `${id}.log`), { force: true });
102
+ }
103
+ } catch {
104
+ }
105
+ }
106
+ function runCommand(command, cwd = process.cwd()) {
107
+ return new Promise((resolve) => {
108
+ const started = Date.now();
109
+ const chunks = [];
110
+ let size = 0;
111
+ const take = (b) => {
112
+ if (size < MAX_CAPTURE) chunks.push(b);
113
+ size += b.length;
114
+ };
115
+ const child = spawn(command, { cwd, shell: true, env: process.env, windowsHide: true });
116
+ child.stdout.on("data", take);
117
+ child.stderr.on("data", take);
118
+ const finish = (code) => {
119
+ let output = Buffer.concat(chunks).toString("utf8");
120
+ if (size > MAX_CAPTURE) output += `
121
+ \u2026(salida truncada a ${MAX_CAPTURE / 1024 / 1024} MB de ${(size / 1024 / 1024).toFixed(1)} MB)`;
122
+ resolve(saveRun({ command, cwd, output, exitCode: code, ms: Date.now() - started }));
123
+ };
124
+ child.on("error", (e) => {
125
+ take(Buffer.from(String(e.message)));
126
+ finish(127);
127
+ });
128
+ child.on("close", (code, signal) => finish(code ?? (signal ? 128 : 1)));
129
+ });
130
+ }
131
+ function saveRun(r) {
132
+ const id = newId();
133
+ const meta = { id, command: r.command, cwd: r.cwd, exitCode: r.exitCode, ms: r.ms, chars: r.output.length, t: (/* @__PURE__ */ new Date()).toISOString() };
134
+ const fold = foldOutput({ output: r.output, exitCode: r.exitCode, ms: r.ms, id, command: r.command });
135
+ if (fold.folded) {
136
+ try {
137
+ fs.mkdirSync(runsDir(), { recursive: true });
138
+ fs.writeFileSync(path.join(runsDir(), `${id}.log`), stripAnsi(r.output));
139
+ fs.writeFileSync(path.join(runsDir(), `${id}.json`), JSON.stringify(meta));
140
+ rotate();
141
+ } catch {
142
+ }
143
+ }
144
+ return { meta, fold };
145
+ }
146
+ function showRun(id, opts = {}) {
147
+ const ref = id === "last" ? lastRunId() : id;
148
+ const file = ref ? path.join(runsDir(), `${ref}.log`) : "";
149
+ if (!ref || !fs.existsSync(file)) return `No encontr\xE9 la corrida \xAB${id}\xBB. Las \xFAltimas: ${listRuns(5).map((m) => m.id).join(", ") || "(ninguna)"}`;
150
+ const all = fs.readFileSync(file, "utf8").split("\n");
151
+ let picked = all.map((l, i) => ({ n: i + 1, l }));
152
+ if (opts.lines) {
153
+ const [a, b] = opts.lines.split("-").map((x) => parseInt(x, 10));
154
+ picked = picked.filter((x) => x.n >= (a || 1) && x.n <= (b || a || all.length));
155
+ }
156
+ if (opts.grep) {
157
+ let re;
158
+ try {
159
+ re = new RegExp(opts.grep, "i");
160
+ } catch {
161
+ re = new RegExp(opts.grep.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
162
+ }
163
+ picked = picked.filter((x) => re.test(x.l));
164
+ }
165
+ const budget = (opts.maxTokens ?? 2e3) * 4;
166
+ const out = [];
167
+ let used = 0;
168
+ for (const x of picked) {
169
+ const line = `${x.n}: ${x.l}`;
170
+ if (used + line.length > budget) {
171
+ out.push(`\u2026(+${picked.length - out.length} l\xEDneas; acota con --lines o --grep, o sube max_tokens)`);
172
+ break;
173
+ }
174
+ out.push(line);
175
+ used += line.length + 1;
176
+ }
177
+ return `corrida ${ref} \xB7 ${picked.length} de ${all.length} l\xEDneas
178
+ ${out.join("\n")}`;
179
+ }
180
+ function listRuns(n = 10) {
181
+ try {
182
+ return fs.readdirSync(runsDir()).filter((f) => f.endsWith(".json")).sort().slice(-n).reverse().map((f) => JSON.parse(fs.readFileSync(path.join(runsDir(), f), "utf8")));
183
+ } catch {
184
+ return [];
185
+ }
186
+ }
187
+ function lastRunId() {
188
+ return listRuns(1)[0]?.id;
189
+ }
190
+
191
+ export {
192
+ shouldFoldOutput,
193
+ runCommand,
194
+ saveRun,
195
+ showRun,
196
+ listRuns
197
+ };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-BV2KJV5W.js";
4
+ } from "./chunk-44QPE5IM.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";