@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.
- package/README.md +60 -4
- package/dist/{chunk-3CB7GRFJ.js → chunk-44QPE5IM.js} +52 -4
- package/dist/{chunk-FPKJVQ2X.js → chunk-47S5I3D3.js} +2 -2
- package/dist/chunk-ADA25MTF.js +142 -0
- package/dist/chunk-BXVNQVLX.js +831 -0
- package/dist/chunk-I5H4BN3F.js +263 -0
- package/dist/chunk-OGVWOBYH.js +197 -0
- package/dist/{chunk-4ZSTD3CU.js → chunk-SSTG2NOO.js} +1 -1
- package/dist/{chunk-2ESJQAP4.js → chunk-WSVNMMNN.js} +45 -9
- package/dist/{chunk-U2U53TU2.js → chunk-WVZQGLRI.js} +1 -1
- package/dist/chunk-X4V6SYYA.js +131 -0
- package/dist/{chunk-MDGFK6UC.js → chunk-YICWI3U3.js} +28 -54
- package/dist/cli.js +240 -21
- package/dist/hooks/on-bash.js +45 -0
- package/dist/hooks/on-prompt.js +37 -13
- package/dist/hooks/on-read.js +70 -0
- package/dist/hooks/on-session-start.js +20 -9
- package/dist/hooks/on-stop.js +26 -7
- package/dist/mcp/server.js +118 -15
- package/dist/{viewer-OU4TB3X5.js → viewer-T2SEBP6Z.js} +2 -2
- package/package.json +15 -3
- package/dist/chunk-JI2L66DF.js +0 -189
|
@@ -0,0 +1,263 @@
|
|
|
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", "title", "head"]);
|
|
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
|
+
htmlToMarkdown
|
|
263
|
+
};
|
|
@@ -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,13 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "./chunk-
|
|
3
|
+
isoDate,
|
|
4
|
+
supersedeNote
|
|
5
|
+
} from "./chunk-44QPE5IM.js";
|
|
6
|
+
import {
|
|
7
|
+
charsToTokens
|
|
8
|
+
} from "./chunk-X4V6SYYA.js";
|
|
6
9
|
import {
|
|
7
|
-
|
|
8
|
-
} from "./chunk-
|
|
10
|
+
isHarnessInjected
|
|
11
|
+
} from "./chunk-YICWI3U3.js";
|
|
9
12
|
import {
|
|
10
13
|
MODEL_ID,
|
|
14
|
+
dot,
|
|
11
15
|
modelCacheDir
|
|
12
16
|
} from "./chunk-EDYBSJSS.js";
|
|
13
17
|
|
|
@@ -17,6 +21,8 @@ import path from "path";
|
|
|
17
21
|
import matter from "gray-matter";
|
|
18
22
|
var ARCHIVE_DIR = "archive";
|
|
19
23
|
var STATS_KEEP_DAYS = 90;
|
|
24
|
+
var DUPLICATE_COSINE = 0.96;
|
|
25
|
+
var DEDUPE_TYPES = ["lesson", "note", "solution"];
|
|
20
26
|
function archiveRoot(vault) {
|
|
21
27
|
return path.join(vault.managed, ARCHIVE_DIR);
|
|
22
28
|
}
|
|
@@ -98,7 +104,30 @@ function planClean(vault, notes, opts) {
|
|
|
98
104
|
}
|
|
99
105
|
} catch {
|
|
100
106
|
}
|
|
101
|
-
return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length };
|
|
107
|
+
return { bundles, noise, tmpFiles, staleModels, statsLinesToRotate: oldStatsLines(vault).length, duplicates: findDuplicates(opts) };
|
|
108
|
+
}
|
|
109
|
+
function findDuplicates(opts) {
|
|
110
|
+
if (opts.dedupe === false || !opts.idx) return [];
|
|
111
|
+
const vecs = opts.idx.noteVectors(DEDUPE_TYPES);
|
|
112
|
+
const rels = [...vecs.keys()];
|
|
113
|
+
const used = /* @__PURE__ */ new Set();
|
|
114
|
+
const out = [];
|
|
115
|
+
for (let i = 0; i < rels.length; i++) {
|
|
116
|
+
for (let j = i + 1; j < rels.length; j++) {
|
|
117
|
+
const a = rels[i];
|
|
118
|
+
const b = rels[j];
|
|
119
|
+
if (used.has(a) || used.has(b)) continue;
|
|
120
|
+
const na = opts.idx.meta.notes[a];
|
|
121
|
+
const nb = opts.idx.meta.notes[b];
|
|
122
|
+
if (!na || !nb || na.type !== nb.type) continue;
|
|
123
|
+
const cos = dot(vecs.get(a), vecs.get(b));
|
|
124
|
+
if (cos < DUPLICATE_COSINE) continue;
|
|
125
|
+
const [older, newer] = (na.created ?? "") <= (nb.created ?? "") ? [na, nb] : [nb, na];
|
|
126
|
+
out.push({ older, newer, cos: Math.round(cos * 1e3) / 1e3 });
|
|
127
|
+
used.add(older.rel);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return out;
|
|
102
131
|
}
|
|
103
132
|
function oldStatsLines(vault) {
|
|
104
133
|
const cutoff = Date.now() - STATS_KEEP_DAYS * 864e5;
|
|
@@ -106,7 +135,7 @@ function oldStatsLines(vault) {
|
|
|
106
135
|
return fs.readFileSync(path.join(vault.cache, "stats.jsonl"), "utf8").split("\n").filter((l) => {
|
|
107
136
|
try {
|
|
108
137
|
const o = JSON.parse(l);
|
|
109
|
-
return o.t !== "summary" && Date.parse(o.t ?? "") < cutoff;
|
|
138
|
+
return o.t !== "summary" && ["inject", "session-start", "solution-cache"].includes(o.kind ?? "inject") && Date.parse(o.t ?? "") < cutoff;
|
|
110
139
|
} catch {
|
|
111
140
|
return false;
|
|
112
141
|
}
|
|
@@ -126,8 +155,8 @@ function section(n, text) {
|
|
|
126
155
|
${text}
|
|
127
156
|
`;
|
|
128
157
|
}
|
|
129
|
-
function applyClean(vault, plan) {
|
|
130
|
-
const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0 };
|
|
158
|
+
function applyClean(vault, plan, opts = {}) {
|
|
159
|
+
const res = { compacted: 0, dropped: 0, bundlesWritten: 0, removedDerived: 0, bytesFreed: 0, superseded: 0 };
|
|
131
160
|
for (const [key, list] of plan.bundles) {
|
|
132
161
|
const [proj, month] = key.split("/");
|
|
133
162
|
const file = path.join(archiveRoot(vault), proj, `${month}.md`);
|
|
@@ -169,6 +198,13 @@ Proyecto: [[Mapa - ${proj}]]
|
|
|
169
198
|
fs.rmSync(p, { recursive: true, force: true });
|
|
170
199
|
res.removedDerived++;
|
|
171
200
|
}
|
|
201
|
+
for (const d of opts.applyDuplicates ? plan.duplicates : []) {
|
|
202
|
+
try {
|
|
203
|
+
supersedeNote(path.join(vault.root, d.older.rel), d.newer.title);
|
|
204
|
+
res.superseded++;
|
|
205
|
+
} catch {
|
|
206
|
+
}
|
|
207
|
+
}
|
|
172
208
|
rotateStats(vault);
|
|
173
209
|
return res;
|
|
174
210
|
}
|