@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 +33 -4
- package/dist/{chunk-BV2KJV5W.js → chunk-44QPE5IM.js} +46 -2
- package/dist/{chunk-Y6S6SKH4.js → chunk-47S5I3D3.js} +2 -2
- package/dist/chunk-ADA25MTF.js +142 -0
- package/dist/{chunk-UU4MGB2C.js → chunk-NUG7HLOU.js} +10 -29
- package/dist/chunk-OGVWOBYH.js +197 -0
- package/dist/{chunk-GP5A2GWI.js → chunk-SSTG2NOO.js} +1 -1
- package/dist/{chunk-B7HCWKPJ.js → chunk-WSVNMMNN.js} +43 -9
- package/dist/{chunk-ZDS6VULX.js → chunk-WVZQGLRI.js} +1 -1
- package/dist/chunk-X4V6SYYA.js +131 -0
- package/dist/{chunk-CEHNXDUE.js → chunk-YICWI3U3.js} +20 -2
- package/dist/chunk-YNCL5JSF.js +831 -0
- package/dist/cli.js +167 -24
- package/dist/hooks/on-bash.js +45 -0
- package/dist/hooks/on-prompt.js +35 -13
- package/dist/hooks/on-read.js +3 -3
- package/dist/hooks/on-session-start.js +18 -9
- package/dist/hooks/on-stop.js +26 -8
- package/dist/mcp/server.js +88 -21
- package/dist/{viewer-WQQSQETT.js → viewer-T2SEBP6Z.js} +2 -2
- package/dist/xlsx-THZM4FNX.js +128 -0
- package/package.json +3 -3
- package/dist/chunk-POA77JSS.js +0 -76
- package/dist/chunk-SAKIVZMP.js +0 -495
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
hybridSearch
|
|
4
|
+
} from "./chunk-47S5I3D3.js";
|
|
5
|
+
import {
|
|
6
|
+
slugify
|
|
7
|
+
} from "./chunk-44QPE5IM.js";
|
|
8
|
+
import {
|
|
9
|
+
convertFile,
|
|
10
|
+
htmlToMarkdown
|
|
11
|
+
} from "./chunk-NUG7HLOU.js";
|
|
12
|
+
import {
|
|
13
|
+
logDocUse
|
|
14
|
+
} from "./chunk-X4V6SYYA.js";
|
|
15
|
+
import {
|
|
16
|
+
ensureVaultStructure
|
|
17
|
+
} from "./chunk-YICWI3U3.js";
|
|
18
|
+
import {
|
|
19
|
+
DIM,
|
|
20
|
+
dot,
|
|
21
|
+
embed,
|
|
22
|
+
modelPresent
|
|
23
|
+
} from "./chunk-EDYBSJSS.js";
|
|
24
|
+
|
|
25
|
+
// src/core/planning.ts
|
|
26
|
+
var MAX_ITEMS = 2;
|
|
27
|
+
var EXCERPT_CHARS = 150;
|
|
28
|
+
async function planContext(vault, query) {
|
|
29
|
+
const out = { similarPlans: [], lessons: [] };
|
|
30
|
+
try {
|
|
31
|
+
const results = await hybridSearch(vault, query, 8);
|
|
32
|
+
for (const r of results) {
|
|
33
|
+
const excerpt = (r.excerpts[0] ?? "").replace(/\n+/g, " ").slice(0, EXCERPT_CHARS);
|
|
34
|
+
if (r.note.type === "plan" && out.similarPlans.length < MAX_ITEMS) {
|
|
35
|
+
out.similarPlans.push(`\xAB${r.note.title}\xBB (${r.note.status ?? "?"}): ${excerpt}`);
|
|
36
|
+
} else if ((r.note.type === "lesson" || r.note.type === "solution") && out.lessons.length < MAX_ITEMS) {
|
|
37
|
+
out.lessons.push(`\xAB${r.note.title}\xBB: ${excerpt}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
} catch {
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
var FAT_TASK_CHARS = 140;
|
|
45
|
+
var MAX_HINTS = 3;
|
|
46
|
+
function planQualityHints(dod, tasks, design) {
|
|
47
|
+
const hints = [];
|
|
48
|
+
const fat = tasks.filter((t) => t.length > FAT_TASK_CHARS);
|
|
49
|
+
if (fat.length) hints.push(`${fat.length} tarea(s) gorda(s) (>${FAT_TASK_CHARS}c) \u2014 1 tarea = 1 task_verify`);
|
|
50
|
+
if (dod.length < 2) hints.push("DoD <2 criterios verificables");
|
|
51
|
+
const vague = dod.filter((d) => /funcione bien|quede bonito|esté listo|sea mejor/i.test(d));
|
|
52
|
+
if (vague.length) hints.push(`${vague.length} criterio(s) no verificable(s) por comando`);
|
|
53
|
+
if (tasks.length > 5 && !design?.trim()) hints.push("sin `design` (plan grande)");
|
|
54
|
+
return hints.slice(0, MAX_HINTS);
|
|
55
|
+
}
|
|
56
|
+
function architectBlock(ctx, hints) {
|
|
57
|
+
const parts = [];
|
|
58
|
+
for (const p of ctx.similarPlans) parts.push(`Similar: ${p}`);
|
|
59
|
+
for (const l of ctx.lessons) parts.push(`Lecci\xF3n: ${l}`);
|
|
60
|
+
if (hints.length) parts.push(`Hints: ${hints.join(" \xB7 ")}`);
|
|
61
|
+
return parts.join("\n");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/core/register.ts
|
|
65
|
+
import fs from "fs";
|
|
66
|
+
import os from "os";
|
|
67
|
+
import path from "path";
|
|
68
|
+
import { fileURLToPath } from "url";
|
|
69
|
+
import { execFileSync } from "child_process";
|
|
70
|
+
function distDir() {
|
|
71
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
72
|
+
return here.endsWith(`${path.sep}hooks`) || here.endsWith(`${path.sep}mcp`) ? path.dirname(here) : here;
|
|
73
|
+
}
|
|
74
|
+
var MARKER = "alexandria";
|
|
75
|
+
function hookCommand(script, timeout) {
|
|
76
|
+
return { type: "command", command: `node "${script}"`, timeout };
|
|
77
|
+
}
|
|
78
|
+
function isOurs(cmd) {
|
|
79
|
+
return cmd.includes(MARKER) || cmd.includes(distDir());
|
|
80
|
+
}
|
|
81
|
+
function registerHooks(settingsPath) {
|
|
82
|
+
const d = distDir();
|
|
83
|
+
const wanted = {
|
|
84
|
+
SessionStart: hookCommand(path.join(d, "hooks", "on-session-start.js"), 20),
|
|
85
|
+
UserPromptSubmit: hookCommand(path.join(d, "hooks", "on-prompt.js"), 30),
|
|
86
|
+
Stop: hookCommand(path.join(d, "hooks", "on-stop.js"), 30),
|
|
87
|
+
PreCompact: hookCommand(path.join(d, "hooks", "on-stop.js"), 30),
|
|
88
|
+
// Read de PDF/DOCX/XLSX → sugiere doc_ingest/doc_read (toggle docs.interceptRead)
|
|
89
|
+
PreToolUse: { ...hookCommand(path.join(d, "hooks", "on-read.js"), 5), matcher: "Read" },
|
|
90
|
+
// Salida grande de Bash → plegada (toggle run.fold)
|
|
91
|
+
PostToolUse: { ...hookCommand(path.join(d, "hooks", "on-bash.js"), 5), matcher: "Bash" }
|
|
92
|
+
};
|
|
93
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
|
|
94
|
+
let settings = {};
|
|
95
|
+
try {
|
|
96
|
+
settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
97
|
+
} catch {
|
|
98
|
+
if (fs.existsSync(settingsPath)) {
|
|
99
|
+
throw new Error(`No pude parsear ${settingsPath} \u2014 rev\xEDsalo manualmente antes de registrar hooks.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
settings.hooks ??= {};
|
|
103
|
+
for (const [event, { matcher, ...cmd }] of Object.entries(wanted)) {
|
|
104
|
+
const matchers = (settings.hooks[event] ?? []).filter(
|
|
105
|
+
(m) => !m.hooks?.some((h) => isOurs(h.command))
|
|
106
|
+
);
|
|
107
|
+
matchers.push(matcher ? { matcher, hooks: [cmd] } : { hooks: [cmd] });
|
|
108
|
+
settings.hooks[event] = matchers;
|
|
109
|
+
}
|
|
110
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
111
|
+
}
|
|
112
|
+
function unregisterHooks(settingsPath) {
|
|
113
|
+
try {
|
|
114
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
115
|
+
if (!settings.hooks) return;
|
|
116
|
+
for (const event of Object.keys(settings.hooks)) {
|
|
117
|
+
settings.hooks[event] = settings.hooks[event].map((m) => ({ ...m, hooks: m.hooks.filter((h) => !isOurs(h.command)) })).filter((m) => m.hooks.length > 0);
|
|
118
|
+
if (settings.hooks[event].length === 0) delete settings.hooks[event];
|
|
119
|
+
}
|
|
120
|
+
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function projectSettingsPath(projectDir) {
|
|
125
|
+
return path.join(projectDir, ".claude", "settings.json");
|
|
126
|
+
}
|
|
127
|
+
function globalSettingsPath() {
|
|
128
|
+
return path.join(os.homedir(), ".claude", "settings.json");
|
|
129
|
+
}
|
|
130
|
+
function hooksRegistered(settingsPath) {
|
|
131
|
+
try {
|
|
132
|
+
const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
|
|
133
|
+
const hooks = settings.hooks ?? {};
|
|
134
|
+
return ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"].every(
|
|
135
|
+
(ev) => (hooks[ev] ?? []).some((m) => m.hooks?.some((h) => isOurs(h.command)))
|
|
136
|
+
);
|
|
137
|
+
} catch {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function serverCommand(portable) {
|
|
142
|
+
return portable ? { command: "npx", args: ["-y", "@ureck/alexandria", "alexandria", "serve-mcp"] } : { command: "node", args: [path.join(distDir(), "mcp", "server.js")] };
|
|
143
|
+
}
|
|
144
|
+
function registerMcpProject(projectDir, portable = false) {
|
|
145
|
+
const file = path.join(projectDir, ".mcp.json");
|
|
146
|
+
let cfg = {};
|
|
147
|
+
try {
|
|
148
|
+
cfg = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
149
|
+
} catch {
|
|
150
|
+
if (fs.existsSync(file)) {
|
|
151
|
+
throw new Error(`No pude parsear ${file} \u2014 rev\xEDsalo manualmente.`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
cfg.mcpServers ??= {};
|
|
155
|
+
cfg.mcpServers["alexandria"] = serverCommand(portable);
|
|
156
|
+
fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
|
|
157
|
+
return file;
|
|
158
|
+
}
|
|
159
|
+
function registerMcpGlobal(portable = false) {
|
|
160
|
+
const { command, args } = serverCommand(portable);
|
|
161
|
+
try {
|
|
162
|
+
execFileSync("claude", ["mcp", "add", "--scope", "user", "alexandria", "--", command, ...args], {
|
|
163
|
+
stdio: "pipe",
|
|
164
|
+
timeout: 15e3,
|
|
165
|
+
shell: process.platform === "win32"
|
|
166
|
+
// en Windows los binarios globales de npm son shims .cmd/.ps1
|
|
167
|
+
});
|
|
168
|
+
return true;
|
|
169
|
+
} catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function mcpRegisteredProject(projectDir) {
|
|
174
|
+
try {
|
|
175
|
+
const cfg = JSON.parse(fs.readFileSync(path.join(projectDir, ".mcp.json"), "utf8"));
|
|
176
|
+
return Boolean(cfg.mcpServers?.alexandria);
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/core/pkg.ts
|
|
183
|
+
import fs2 from "fs";
|
|
184
|
+
import path2 from "path";
|
|
185
|
+
var cached = null;
|
|
186
|
+
function pkgVersion() {
|
|
187
|
+
if (cached) return cached;
|
|
188
|
+
try {
|
|
189
|
+
const pkg = JSON.parse(fs2.readFileSync(path2.join(distDir(), "..", "package.json"), "utf8"));
|
|
190
|
+
cached = String(pkg.version);
|
|
191
|
+
} catch {
|
|
192
|
+
cached = "0.0.0";
|
|
193
|
+
}
|
|
194
|
+
return cached;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// src/code/outline.ts
|
|
198
|
+
import fs3 from "fs";
|
|
199
|
+
import path3 from "path";
|
|
200
|
+
var EXT = {
|
|
201
|
+
".ts": "c",
|
|
202
|
+
".tsx": "c",
|
|
203
|
+
".mts": "c",
|
|
204
|
+
".cts": "c",
|
|
205
|
+
".js": "c",
|
|
206
|
+
".jsx": "c",
|
|
207
|
+
".mjs": "c",
|
|
208
|
+
".cjs": "c",
|
|
209
|
+
".php": "c",
|
|
210
|
+
".go": "c",
|
|
211
|
+
".java": "c",
|
|
212
|
+
".cs": "c",
|
|
213
|
+
".kt": "c",
|
|
214
|
+
".kts": "c",
|
|
215
|
+
".rs": "c",
|
|
216
|
+
".swift": "c",
|
|
217
|
+
".dart": "c",
|
|
218
|
+
".py": "python"
|
|
219
|
+
};
|
|
220
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".next", "vendor", "coverage", "target", "__pycache__", ".venv", "venv", "out", "Alexandria", "KnowledgeVault"]);
|
|
221
|
+
function langOf(file) {
|
|
222
|
+
return EXT[path3.extname(file).toLowerCase()];
|
|
223
|
+
}
|
|
224
|
+
function maskCode(src, lang) {
|
|
225
|
+
const out = src.split("");
|
|
226
|
+
let i = 0;
|
|
227
|
+
const blank = (a, b) => {
|
|
228
|
+
for (let k = a; k < b && k < out.length; k++) if (out[k] !== "\n") out[k] = " ";
|
|
229
|
+
};
|
|
230
|
+
while (i < src.length) {
|
|
231
|
+
const c = src[i];
|
|
232
|
+
const n = src[i + 1];
|
|
233
|
+
if (lang === "c" && c === "/" && n === "/") {
|
|
234
|
+
const e = src.indexOf("\n", i);
|
|
235
|
+
blank(i, e < 0 ? src.length : e);
|
|
236
|
+
i = e < 0 ? src.length : e;
|
|
237
|
+
} else if (lang === "c" && c === "/" && n === "*") {
|
|
238
|
+
const e = src.indexOf("*/", i + 2);
|
|
239
|
+
blank(i, e < 0 ? src.length : e + 2);
|
|
240
|
+
i = e < 0 ? src.length : e + 2;
|
|
241
|
+
} else if (c === "#" && (lang === "python" || (i === 0 || src[i - 1] === "\n") && n !== "[" && n !== "!")) {
|
|
242
|
+
const e = src.indexOf("\n", i);
|
|
243
|
+
blank(i, e < 0 ? src.length : e);
|
|
244
|
+
i = e < 0 ? src.length : e;
|
|
245
|
+
} else if (lang === "python" && (src.startsWith('"""', i) || src.startsWith("'''", i))) {
|
|
246
|
+
const q = src.slice(i, i + 3);
|
|
247
|
+
const e = src.indexOf(q, i + 3);
|
|
248
|
+
blank(i + 3, e < 0 ? src.length : e);
|
|
249
|
+
i = e < 0 ? src.length : e + 3;
|
|
250
|
+
} else if (c === '"' || c === "'" || c === "`") {
|
|
251
|
+
let j = i + 1;
|
|
252
|
+
while (j < src.length && src[j] !== c) {
|
|
253
|
+
if (src[j] === "\\") j++;
|
|
254
|
+
else if (src[j] === "\n" && c !== "`") break;
|
|
255
|
+
j++;
|
|
256
|
+
}
|
|
257
|
+
blank(i + 1, j);
|
|
258
|
+
i = j + 1;
|
|
259
|
+
} else i++;
|
|
260
|
+
}
|
|
261
|
+
return out.join("");
|
|
262
|
+
}
|
|
263
|
+
var KEYWORDS = /* @__PURE__ */ new Set(["if", "for", "while", "switch", "catch", "return", "function", "else", "do", "try", "with", "new", "typeof", "await", "sizeof", "foreach", "using", "lock", "match", "loop", "unless"]);
|
|
264
|
+
var TOP_PATTERNS = [
|
|
265
|
+
[/^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/, "function"],
|
|
266
|
+
[/^\s*(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:final\s+)?(?:public\s+|internal\s+|private\s+)?(?:static\s+)?(?:partial\s+)?(?:data\s+|sealed\s+|open\s+)?class\s+([A-Za-z_$][\w$]*)/, "class"],
|
|
267
|
+
[/^\s*(?:export\s+)?(?:declare\s+)?(?:public\s+)?interface\s+([A-Za-z_$][\w$]*)/, "interface"],
|
|
268
|
+
[/^\s*(?:export\s+)?(?:declare\s+)?(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/, "enum"],
|
|
269
|
+
[/^\s*(?:export\s+)?(?:declare\s+)?type\s+([A-Za-z_$][\w$]*)\s*(?:<[^=]*>)?\s*=/, "type"],
|
|
270
|
+
[/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/, "function"],
|
|
271
|
+
[/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)/, "function"],
|
|
272
|
+
[/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|trait|enum)\s+([A-Za-z_]\w*)/, "struct"],
|
|
273
|
+
[/^\s*impl(?:<[^>]*>)?\s+(?:[\w:<>]+\s+for\s+)?([A-Za-z_][\w:]*)/, "impl"],
|
|
274
|
+
[/^func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/, "function"],
|
|
275
|
+
// constantes/variables de primer nivel (regex, config, tablas): también se piden por nombre
|
|
276
|
+
[/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]+)?=/, "const"],
|
|
277
|
+
[/^(?:pub(?:\([^)]*\))?\s+)?(?:const|static)\s+([A-Z_][A-Z0-9_]*)\s*:/, "const"],
|
|
278
|
+
[/^([A-Z_][A-Z0-9_]*)\s*=/, "const"],
|
|
279
|
+
[/^type\s+([A-Za-z_]\w*)\s+(?:struct|interface)\b/, "struct"],
|
|
280
|
+
[/^\s*(?:abstract\s+|final\s+)?(?:trait)\s+([A-Za-z_]\w*)/, "trait"],
|
|
281
|
+
[/^\s*(?:public\s+|private\s+|protected\s+)?(?:static\s+)?function\s+([A-Za-z_]\w*)/, "function"]
|
|
282
|
+
];
|
|
283
|
+
var METHOD = /^\s*(?:(?:public|private|protected|internal|static|async|readonly|override|abstract|final|virtual|get|set|suspend|open|fun|def)\s+)*(?:[\w<>[\],.?]+\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(/;
|
|
284
|
+
function signature(lines, start) {
|
|
285
|
+
let sig = "";
|
|
286
|
+
for (let k = start; k < Math.min(lines.length, start + 4); k++) {
|
|
287
|
+
sig += (sig ? " " : "") + lines[k].trim();
|
|
288
|
+
if (/[{:]\s*$|=>\s*\{?\s*$|;\s*$/.test(lines[k]) || /\)\s*(:[^{]*)?\{/.test(lines[k])) break;
|
|
289
|
+
}
|
|
290
|
+
sig = sig.replace(/\s*\{\s*$/, "").replace(/\s+/g, " ");
|
|
291
|
+
return sig.length > 160 ? sig.slice(0, 160) + "\u2026" : sig;
|
|
292
|
+
}
|
|
293
|
+
function braceEnd(masked, start) {
|
|
294
|
+
let depth = 0;
|
|
295
|
+
let opened = false;
|
|
296
|
+
let paren = 0;
|
|
297
|
+
let typeDepth = 0;
|
|
298
|
+
let prev = "";
|
|
299
|
+
for (let k = start; k < masked.length; k++) {
|
|
300
|
+
for (const ch of masked[k]) {
|
|
301
|
+
if (!opened) {
|
|
302
|
+
if (ch === "(") paren++;
|
|
303
|
+
else if (ch === ")") paren = Math.max(0, paren - 1);
|
|
304
|
+
else if (ch === "{") {
|
|
305
|
+
if (paren > 0 || typeDepth > 0 || /[:<,|&(]/.test(prev)) typeDepth++;
|
|
306
|
+
else {
|
|
307
|
+
opened = true;
|
|
308
|
+
depth = 1;
|
|
309
|
+
}
|
|
310
|
+
} else if (ch === "}") typeDepth = Math.max(0, typeDepth - 1);
|
|
311
|
+
else if (ch === ";" && paren === 0 && typeDepth === 0) return k;
|
|
312
|
+
} else if (ch === "{") depth++;
|
|
313
|
+
else if (ch === "}") {
|
|
314
|
+
depth--;
|
|
315
|
+
if (depth === 0) return k;
|
|
316
|
+
}
|
|
317
|
+
if (ch.trim()) prev = ch;
|
|
318
|
+
}
|
|
319
|
+
if (!opened && k >= start + 8) return start;
|
|
320
|
+
}
|
|
321
|
+
return opened ? masked.length - 1 : start;
|
|
322
|
+
}
|
|
323
|
+
function constEnd(masked, start) {
|
|
324
|
+
for (let k = start; k < Math.min(masked.length, start + 200); k++) {
|
|
325
|
+
if (k > start && /^\S/.test(masked[k]) && !/^[)\]}]/.test(masked[k])) return k - 1;
|
|
326
|
+
if (/;\s*$/.test(masked[k])) return k;
|
|
327
|
+
}
|
|
328
|
+
return start;
|
|
329
|
+
}
|
|
330
|
+
function outlineC(src) {
|
|
331
|
+
const lines = src.split("\n");
|
|
332
|
+
const masked = maskCode(src, "c").split("\n");
|
|
333
|
+
const syms = [];
|
|
334
|
+
const containers = [];
|
|
335
|
+
for (let i = 0; i < masked.length; i++) {
|
|
336
|
+
const m = masked[i];
|
|
337
|
+
if (!m.trim()) continue;
|
|
338
|
+
const parent = containers.find((c) => i > c.start - 1 && i <= c.end - 1 && i !== c.start - 1);
|
|
339
|
+
let hit = null;
|
|
340
|
+
for (const [re, kind] of TOP_PATTERNS) {
|
|
341
|
+
const mm = m.match(re);
|
|
342
|
+
if (mm) {
|
|
343
|
+
hit = [mm[1], kind];
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (!hit && parent && ["class", "interface", "impl", "trait", "struct"].includes(parent.kind)) {
|
|
348
|
+
const mm = m.match(METHOD);
|
|
349
|
+
if (mm && !KEYWORDS.has(mm[1]) && /\)\s*(?::[^;{]*)?\{|\)\s*(?:->[^{]*)?\{|\)\s*$/.test(m) && !/;\s*$/.test(m)) hit = [mm[1], "method"];
|
|
350
|
+
}
|
|
351
|
+
if (!hit) continue;
|
|
352
|
+
const end = hit[1] === "const" ? constEnd(masked, i) : hit[1] === "type" && !m.includes("{") ? i : braceEnd(masked, i);
|
|
353
|
+
const sym = { name: hit[0], kind: hit[1], start: i + 1, end: end + 1, signature: signature(lines, i), parent: parent?.name };
|
|
354
|
+
syms.push(sym);
|
|
355
|
+
if (["class", "interface", "impl", "trait", "struct"].includes(sym.kind)) containers.push(sym);
|
|
356
|
+
if (["function", "method", "type", "enum", "const"].includes(sym.kind)) i = Math.max(i, end);
|
|
357
|
+
}
|
|
358
|
+
return syms;
|
|
359
|
+
}
|
|
360
|
+
function outlinePython(src) {
|
|
361
|
+
const lines = src.split("\n");
|
|
362
|
+
const masked = maskCode(src, "python").split("\n");
|
|
363
|
+
const syms = [];
|
|
364
|
+
const indentOf = (l) => l.match(/^\s*/)[0].length;
|
|
365
|
+
for (let i = 0; i < masked.length; i++) {
|
|
366
|
+
const m = masked[i].match(/^(\s*)(?:async\s+)?(def|class)\s+([A-Za-z_]\w*)/);
|
|
367
|
+
if (!m) continue;
|
|
368
|
+
const ind = m[1].length;
|
|
369
|
+
let end = i;
|
|
370
|
+
for (let k = i + 1; k < masked.length; k++) {
|
|
371
|
+
if (!masked[k].trim()) continue;
|
|
372
|
+
if (indentOf(masked[k]) <= ind) break;
|
|
373
|
+
end = k;
|
|
374
|
+
}
|
|
375
|
+
const parent = [...syms].reverse().find((s) => s.kind === "class" && s.start - 1 < i && s.end - 1 >= i);
|
|
376
|
+
syms.push({ name: m[3], kind: m[2] === "class" ? "class" : parent ? "method" : "function", start: i + 1, end: end + 1, signature: signature(lines, i).replace(/:\s*$/, ""), parent: parent?.name });
|
|
377
|
+
}
|
|
378
|
+
return syms;
|
|
379
|
+
}
|
|
380
|
+
function outlineSource(src, lang) {
|
|
381
|
+
return lang === "python" ? outlinePython(src) : outlineC(src);
|
|
382
|
+
}
|
|
383
|
+
var tok = (s) => Math.ceil(s.length / 4);
|
|
384
|
+
function outlineFile(file) {
|
|
385
|
+
const lang = langOf(file);
|
|
386
|
+
if (!lang) return `Sin soporte para ${path3.extname(file) || file}: usa Read con offset/limit.`;
|
|
387
|
+
const src = fs3.readFileSync(file, "utf8");
|
|
388
|
+
const syms = outlineSource(src, lang);
|
|
389
|
+
const total = src.split("\n").length;
|
|
390
|
+
const head = `${file} \xB7 ${total} l\xEDneas \xB7 ~${tok(src).toLocaleString("en")} tokens \xB7 ${syms.length} s\xEDmbolos`;
|
|
391
|
+
if (syms.length === 0) return `${head}
|
|
392
|
+
(sin declaraciones detectadas: usa Read con offset/limit)`;
|
|
393
|
+
const body = syms.map((s) => `${s.parent ? " " : ""}L${s.start}${s.end > s.start ? `\u2013${s.end}` : ""} ${s.signature}`).join("\n");
|
|
394
|
+
return `${head}
|
|
395
|
+
${body}
|
|
396
|
+
|
|
397
|
+
Pide el cuerpo de uno con code_symbol (archivo + nombre, o Clase.metodo).`;
|
|
398
|
+
}
|
|
399
|
+
function outlineDir(dir, maxTokens = 2500) {
|
|
400
|
+
const files = [];
|
|
401
|
+
const walk = (d) => {
|
|
402
|
+
let entries = [];
|
|
403
|
+
try {
|
|
404
|
+
entries = fs3.readdirSync(d, { withFileTypes: true });
|
|
405
|
+
} catch {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
409
|
+
if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
|
|
410
|
+
const full = path3.join(d, e.name);
|
|
411
|
+
if (e.isDirectory()) walk(full);
|
|
412
|
+
else if (langOf(full) && !/\.(min|d)\.[jt]s$/.test(e.name)) files.push(full);
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
walk(dir);
|
|
416
|
+
const out = [];
|
|
417
|
+
let used = 0;
|
|
418
|
+
let shown = 0;
|
|
419
|
+
for (const f of files) {
|
|
420
|
+
let syms = [];
|
|
421
|
+
let lines = 0;
|
|
422
|
+
try {
|
|
423
|
+
const src = fs3.readFileSync(f, "utf8");
|
|
424
|
+
if (src.length > 1e6) continue;
|
|
425
|
+
lines = src.split("\n").length;
|
|
426
|
+
syms = outlineSource(src, langOf(f)).filter((s) => !s.parent);
|
|
427
|
+
} catch {
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const names = syms.map((s) => s.name);
|
|
431
|
+
const line = `${path3.relative(dir, f)} (${lines} l): ${names.slice(0, 25).join(", ")}${names.length > 25 ? ` \u2026+${names.length - 25}` : ""}`;
|
|
432
|
+
if (used + tok(line) > maxTokens) break;
|
|
433
|
+
out.push(line);
|
|
434
|
+
used += tok(line);
|
|
435
|
+
shown++;
|
|
436
|
+
}
|
|
437
|
+
const more = files.length > shown ? `
|
|
438
|
+
\u2026 +${files.length - shown} archivos (sube max_tokens o pide una subcarpeta)` : "";
|
|
439
|
+
return `${dir} \xB7 ${files.length} archivos de c\xF3digo
|
|
440
|
+
${out.join("\n")}${more}
|
|
441
|
+
|
|
442
|
+
Detalle de un archivo: code_outline con su ruta.`;
|
|
443
|
+
}
|
|
444
|
+
function symbolSource(file, name, maxTokens = 4e3) {
|
|
445
|
+
const lang = langOf(file);
|
|
446
|
+
if (!lang) return `Sin soporte para ${path3.extname(file) || file}: usa Read con offset/limit.`;
|
|
447
|
+
const src = fs3.readFileSync(file, "utf8");
|
|
448
|
+
const lines = src.split("\n");
|
|
449
|
+
const syms = outlineSource(src, lang);
|
|
450
|
+
const [a, b] = name.includes(".") ? name.split(".", 2) : [void 0, name];
|
|
451
|
+
const matches = syms.filter((s2) => s2.name === b && (!a || s2.parent === a));
|
|
452
|
+
if (matches.length === 0) {
|
|
453
|
+
const near = syms.filter((s2) => s2.name.toLowerCase().includes(b.toLowerCase())).slice(0, 8);
|
|
454
|
+
return `No encontr\xE9 \xAB${name}\xBB en ${file}.${near.length ? ` Parecidos: ${near.map((s2) => (s2.parent ? `${s2.parent}.${s2.name}` : s2.name) + ` (L${s2.start})`).join(", ")}` : ""} Si es una declaraci\xF3n poco com\xFAn, usa Read con offset/limit.`;
|
|
455
|
+
}
|
|
456
|
+
const s = matches[0];
|
|
457
|
+
const body = lines.slice(s.start - 1, s.end).map((l, k) => `${s.start + k}: ${l}`).join("\n");
|
|
458
|
+
const cut = body.length > maxTokens * 4 ? body.slice(0, maxTokens * 4) + `
|
|
459
|
+
\u2026(recortado: el s\xEDmbolo ocupa ~${tok(body)} tokens; sube max_tokens)` : body;
|
|
460
|
+
const others = matches.length > 1 ? `
|
|
461
|
+
(otras ${matches.length - 1} coincidencias: ${matches.slice(1).map((m) => `L${m.start}`).join(", ")})` : "";
|
|
462
|
+
return `${file} L${s.start}\u2013${s.end} \xB7 ${s.kind}${s.parent ? ` de ${s.parent}` : ""}
|
|
463
|
+
${cut}${others}`;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/docs/docs.ts
|
|
467
|
+
import fs4 from "fs";
|
|
468
|
+
import path4 from "path";
|
|
469
|
+
import crypto from "crypto";
|
|
470
|
+
import matter from "gray-matter";
|
|
471
|
+
import MiniSearch from "minisearch";
|
|
472
|
+
var DOCS_DIR = "docs";
|
|
473
|
+
var OUTLINE_MAX = 60;
|
|
474
|
+
var tok2 = (s) => Math.ceil(s.length / 4);
|
|
475
|
+
var sha256 = (b) => crypto.createHash("sha256").update(b).digest("hex");
|
|
476
|
+
function docsDir(vault) {
|
|
477
|
+
return path4.join(vault.managed, DOCS_DIR);
|
|
478
|
+
}
|
|
479
|
+
function docFile(vault, abs) {
|
|
480
|
+
const name = slugify(path4.basename(abs, path4.extname(abs))) || "documento";
|
|
481
|
+
return path4.join(docsDir(vault), `${name}-${sha256(abs).slice(0, 6)}.md`);
|
|
482
|
+
}
|
|
483
|
+
function parseSections(body) {
|
|
484
|
+
const out = [];
|
|
485
|
+
let title = "Inicio";
|
|
486
|
+
let buf = [];
|
|
487
|
+
const push = () => {
|
|
488
|
+
const text = buf.join("\n").trim();
|
|
489
|
+
if (text) out.push({ id: `s${out.length + 1}`, title, text, tokens: tok2(text) });
|
|
490
|
+
buf = [];
|
|
491
|
+
};
|
|
492
|
+
for (const line of body.split("\n")) {
|
|
493
|
+
const h = line.match(/^#{1,3}\s+(.+)$/);
|
|
494
|
+
if (h) {
|
|
495
|
+
push();
|
|
496
|
+
title = h[1].trim();
|
|
497
|
+
buf = [line];
|
|
498
|
+
} else buf.push(line);
|
|
499
|
+
}
|
|
500
|
+
push();
|
|
501
|
+
return out;
|
|
502
|
+
}
|
|
503
|
+
function docBody(content) {
|
|
504
|
+
return content.replace(/^Fuente:.*\n+(Proyecto: \[\[[^\]]*\]\]\n+)?/, "");
|
|
505
|
+
}
|
|
506
|
+
function loadDoc(vault, file) {
|
|
507
|
+
try {
|
|
508
|
+
const { data, content } = matter(fs4.readFileSync(file, "utf8"));
|
|
509
|
+
if (data.type !== "document") return null;
|
|
510
|
+
return {
|
|
511
|
+
rel: path4.relative(vault.root, file).split(path4.sep).join("/"),
|
|
512
|
+
title: String(data.title ?? path4.basename(file)),
|
|
513
|
+
source: String(data.source ?? ""),
|
|
514
|
+
format: data.format,
|
|
515
|
+
pages: data.pages,
|
|
516
|
+
rows: data.rows,
|
|
517
|
+
tokensOriginal: Number(data.tokensOriginal ?? 0),
|
|
518
|
+
sections: parseSections(docBody(content))
|
|
519
|
+
};
|
|
520
|
+
} catch {
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function listDocs(vault) {
|
|
525
|
+
try {
|
|
526
|
+
return fs4.readdirSync(docsDir(vault)).filter((f) => f.endsWith(".md")).map((f) => loadDoc(vault, path4.join(docsDir(vault), f))).filter((d) => Boolean(d));
|
|
527
|
+
} catch {
|
|
528
|
+
return [];
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
function findDoc(vault, ref) {
|
|
532
|
+
const r = ref.trim();
|
|
533
|
+
if (!r) return null;
|
|
534
|
+
const abs = path4.resolve(r);
|
|
535
|
+
const byFile = path4.isAbsolute(r) || fs4.existsSync(abs) ? docFile(vault, abs) : null;
|
|
536
|
+
if (byFile && fs4.existsSync(byFile)) return loadDoc(vault, byFile);
|
|
537
|
+
const low = r.toLowerCase();
|
|
538
|
+
const docs = listDocs(vault);
|
|
539
|
+
return docs.find((d) => d.rel.toLowerCase() === low || d.title.toLowerCase() === low || d.source.toLowerCase() === low) ?? docs.find((d) => d.title.toLowerCase().includes(low) || path4.basename(d.source).toLowerCase().includes(low)) ?? null;
|
|
540
|
+
}
|
|
541
|
+
var isUrl = (s) => /^https?:\/\//i.test(s.trim());
|
|
542
|
+
var URL_TTL_MS = 7 * 864e5;
|
|
543
|
+
var URL_MAX_BYTES = 5 * 1024 * 1024;
|
|
544
|
+
async function ingestUrl(vault, url, opts) {
|
|
545
|
+
const target = docFile(vault, url);
|
|
546
|
+
if (!opts.force && fs4.existsSync(target)) {
|
|
547
|
+
try {
|
|
548
|
+
const fetched = Date.parse(String(matter(fs4.readFileSync(target, "utf8")).data.fetched_at ?? ""));
|
|
549
|
+
if (Date.now() - fetched < URL_TTL_MS) {
|
|
550
|
+
const doc = loadDoc(vault, target);
|
|
551
|
+
if (doc) return { doc, reused: true };
|
|
552
|
+
}
|
|
553
|
+
} catch {
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
const ctrl = new AbortController();
|
|
557
|
+
const timer = setTimeout(() => ctrl.abort(), 2e4);
|
|
558
|
+
let res;
|
|
559
|
+
try {
|
|
560
|
+
res = await fetch(url, { signal: ctrl.signal, headers: { "user-agent": "alexandria-doc-ingest", accept: "text/html,text/markdown,text/plain" } });
|
|
561
|
+
} finally {
|
|
562
|
+
clearTimeout(timer);
|
|
563
|
+
}
|
|
564
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} al bajar ${url}`);
|
|
565
|
+
const type = (res.headers.get("content-type") ?? "").toLowerCase();
|
|
566
|
+
if (!/text\/(html|markdown|plain|x-markdown)|application\/xhtml/.test(type)) throw new Error(`Tipo no soportado: ${type || "desconocido"} (solo HTML, Markdown o texto)`);
|
|
567
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
568
|
+
if (buf.length > URL_MAX_BYTES) throw new Error(`La p\xE1gina pesa ${(buf.length / 1024 / 1024).toFixed(1)} MB (tope 5 MB)`);
|
|
569
|
+
const raw = buf.toString("utf8");
|
|
570
|
+
const isHtml = /html/.test(type);
|
|
571
|
+
const markdown = isHtml ? await htmlToMarkdown(raw) : raw;
|
|
572
|
+
const title = isHtml && raw.match(/<title[^>]*>([^<]{1,160})<\/title>/i)?.[1]?.trim() || url;
|
|
573
|
+
return writeDoc(vault, target, {
|
|
574
|
+
title,
|
|
575
|
+
source: url,
|
|
576
|
+
format: isHtml ? "html" : "markdown",
|
|
577
|
+
sha: sha256(buf),
|
|
578
|
+
tokensOriginal: tok2(raw),
|
|
579
|
+
markdown,
|
|
580
|
+
project: opts.project,
|
|
581
|
+
extra: { fetched_at: (/* @__PURE__ */ new Date()).toISOString() }
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
function writeDoc(vault, target, d) {
|
|
585
|
+
ensureVaultStructure(vault);
|
|
586
|
+
fs4.mkdirSync(path4.dirname(target), { recursive: true });
|
|
587
|
+
const proj = d.project ?? path4.basename(process.cwd());
|
|
588
|
+
const markdown = d.markdown.trim() ? d.markdown : "## \u26A0 Sin texto extra\xEDble\n\nEl cuerpo del documento est\xE1 vac\xEDo: puede ser una plantilla, o tener solo encabezado/pie, im\xE1genes o cuadros de texto.";
|
|
589
|
+
const meta = {
|
|
590
|
+
title: d.title,
|
|
591
|
+
aliases: [d.title],
|
|
592
|
+
type: "document",
|
|
593
|
+
tags: [proj, "documento"],
|
|
594
|
+
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
595
|
+
hits: 1,
|
|
596
|
+
source: d.source,
|
|
597
|
+
format: d.format,
|
|
598
|
+
sha256: d.sha,
|
|
599
|
+
tokensOriginal: d.tokensOriginal,
|
|
600
|
+
...d.extra
|
|
601
|
+
};
|
|
602
|
+
if (d.pages) meta.pages = d.pages;
|
|
603
|
+
if (d.rows !== void 0) meta.rows = d.rows;
|
|
604
|
+
const header = `Fuente: \`${d.source}\` \xB7 ${d.format}${d.pages ? ` \xB7 ${d.pages} p\xE1ginas` : ""}${d.rows !== void 0 ? ` \xB7 ${d.rows} filas` : ""}
|
|
605
|
+
|
|
606
|
+
Proyecto: [[Mapa - ${proj}]]
|
|
607
|
+
|
|
608
|
+
`;
|
|
609
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
610
|
+
fs4.writeFileSync(tmp, matter.stringify(header + markdown + "\n", meta));
|
|
611
|
+
fs4.renameSync(tmp, target);
|
|
612
|
+
return { doc: loadDoc(vault, target), reused: false };
|
|
613
|
+
}
|
|
614
|
+
async function ingestDoc(vault, file, opts = {}) {
|
|
615
|
+
if (isUrl(file)) return ingestUrl(vault, file.trim(), opts);
|
|
616
|
+
const abs = path4.resolve(file);
|
|
617
|
+
if (!fs4.existsSync(abs) || !fs4.statSync(abs).isFile()) throw new Error(`No existe el archivo: ${abs}`);
|
|
618
|
+
const hash = sha256(fs4.readFileSync(abs));
|
|
619
|
+
const target = docFile(vault, abs);
|
|
620
|
+
if (!opts.force && fs4.existsSync(target)) {
|
|
621
|
+
try {
|
|
622
|
+
if (matter(fs4.readFileSync(target, "utf8")).data.sha256 === hash) {
|
|
623
|
+
const doc = loadDoc(vault, target);
|
|
624
|
+
if (doc) return { doc, reused: true };
|
|
625
|
+
}
|
|
626
|
+
} catch {
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const conv = await convertFile(abs);
|
|
630
|
+
return writeDoc(vault, target, {
|
|
631
|
+
title: path4.basename(abs),
|
|
632
|
+
source: abs,
|
|
633
|
+
format: conv.format,
|
|
634
|
+
sha: hash,
|
|
635
|
+
tokensOriginal: conv.tokensOriginal,
|
|
636
|
+
markdown: conv.markdown,
|
|
637
|
+
pages: conv.pages,
|
|
638
|
+
rows: conv.rows,
|
|
639
|
+
project: opts.project
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
function outline(doc) {
|
|
643
|
+
const total = doc.sections.reduce((s, x) => s + x.tokens, 0);
|
|
644
|
+
const lines = doc.sections.slice(0, OUTLINE_MAX).map((s) => `${s.id} \xB7 ${s.title} (~${s.tokens} tok)`);
|
|
645
|
+
const more = doc.sections.length > OUTLINE_MAX ? `
|
|
646
|
+
\u2026 +${doc.sections.length - OUTLINE_MAX} secciones (usa query para encontrarlas)` : "";
|
|
647
|
+
const text = `\xAB${doc.title}\xBB \u2014 ${doc.format}${doc.pages ? `, ${doc.pages} p\xE1gs` : ""}${doc.rows !== void 0 ? `, ${doc.rows} filas` : ""} \xB7 ${doc.sections.length} secciones
|
|
648
|
+
` + lines.join("\n") + more;
|
|
649
|
+
return `${text}
|
|
650
|
+
|
|
651
|
+
Original \u2248 ${doc.tokensOriginal.toLocaleString("en")} tokens \xB7 todo convertido \u2248 ${total.toLocaleString("en")} \xB7 este \xEDndice \u2248 ${tok2(text)}. Pide solo lo necesario con doc_read (sections o query).`;
|
|
652
|
+
}
|
|
653
|
+
async function ingestAndOutline(vault, file, opts = {}) {
|
|
654
|
+
const { doc, reused } = await ingestDoc(vault, file, opts);
|
|
655
|
+
const text = outline(doc);
|
|
656
|
+
logDocUse(vault, { op: "ingest", tokensOriginal: doc.tokensOriginal, tokensServed: tok2(text) });
|
|
657
|
+
return { text: (reused ? "(sin cambios desde la \xFAltima ingesta)\n" : "") + text, doc, reused };
|
|
658
|
+
}
|
|
659
|
+
async function rankSections(vault, doc, query) {
|
|
660
|
+
const mini = new MiniSearch({
|
|
661
|
+
fields: ["title", "text"],
|
|
662
|
+
storeFields: ["id"],
|
|
663
|
+
processTerm: (t) => fold(t),
|
|
664
|
+
searchOptions: { boost: { title: 2 }, fuzzy: 0.2, prefix: true }
|
|
665
|
+
});
|
|
666
|
+
mini.addAll(doc.sections);
|
|
667
|
+
const bm = /* @__PURE__ */ new Map();
|
|
668
|
+
const hits = mini.search(query);
|
|
669
|
+
const top = hits[0]?.score ?? 0;
|
|
670
|
+
for (const h of hits) bm.set(String(h.id), top ? h.score / top : 0);
|
|
671
|
+
const cos = /* @__PURE__ */ new Map();
|
|
672
|
+
if (modelPresent() && doc.sections.length <= MAX_SEMANTIC_SECTIONS) {
|
|
673
|
+
try {
|
|
674
|
+
const vecs = await sectionVectors(vault, doc);
|
|
675
|
+
const [q] = await embed([query], "query");
|
|
676
|
+
doc.sections.forEach((s, i) => cos.set(s.id, dot(q, vecs[i])));
|
|
677
|
+
const vals = [...cos.values()];
|
|
678
|
+
const lo = Math.min(...vals);
|
|
679
|
+
const hi = Math.max(...vals);
|
|
680
|
+
for (const [id, c] of cos) cos.set(id, hi > lo ? (c - lo) / (hi - lo) : 1);
|
|
681
|
+
} catch {
|
|
682
|
+
cos.clear();
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
const score = (id) => cos.size ? 0.5 * (bm.get(id) ?? 0) + 0.5 * (cos.get(id) ?? 0) : bm.get(id) ?? 0;
|
|
686
|
+
const ranked = doc.sections.map((s) => ({ s, sc: score(s.id) })).filter((x) => x.sc > 0).sort((a, b) => b.sc - a.sc);
|
|
687
|
+
const best = ranked[0]?.sc ?? 0;
|
|
688
|
+
return ranked.filter((x) => x.sc >= best * 0.6).map((x) => x.s);
|
|
689
|
+
}
|
|
690
|
+
var fold = (t) => t.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "");
|
|
691
|
+
function matchRows(doc, query, budget) {
|
|
692
|
+
const terms = fold(query).split(/\s+/).filter((t) => t.length > 1);
|
|
693
|
+
if (terms.length === 0) return null;
|
|
694
|
+
const hits = [];
|
|
695
|
+
for (const s of doc.sections) {
|
|
696
|
+
const m = s.title.match(/^Hoja «(.+)» · filas/);
|
|
697
|
+
if (!m) continue;
|
|
698
|
+
const lines = s.text.split("\n").filter((l) => l.startsWith("|"));
|
|
699
|
+
const [header, , ...body] = lines;
|
|
700
|
+
for (const row of body) {
|
|
701
|
+
const f = fold(row);
|
|
702
|
+
const score = terms.filter((t) => f.includes(t)).length;
|
|
703
|
+
if (score > 0) hits.push({ sheet: m[1], header, row, score });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (hits.length === 0) return null;
|
|
707
|
+
const top = Math.max(...hits.map((h) => h.score));
|
|
708
|
+
const best = hits.filter((h) => h.score === top);
|
|
709
|
+
const out = [];
|
|
710
|
+
let used = 0;
|
|
711
|
+
let shown = 0;
|
|
712
|
+
let sheet = "";
|
|
713
|
+
for (const h of best) {
|
|
714
|
+
const add = (h.sheet !== sheet ? `
|
|
715
|
+
### Hoja \xAB${h.sheet}\xBB
|
|
716
|
+
${h.header}
|
|
717
|
+
${h.header.replace(/[^|]+/g, " --- ")}
|
|
718
|
+
` : "") + h.row;
|
|
719
|
+
if (used + tok2(add) > budget) break;
|
|
720
|
+
out.push(add);
|
|
721
|
+
used += tok2(add);
|
|
722
|
+
sheet = h.sheet;
|
|
723
|
+
shown++;
|
|
724
|
+
}
|
|
725
|
+
const match = top === terms.length ? "contienen todos los t\xE9rminos" : `contienen ${top} de ${terms.length} t\xE9rminos`;
|
|
726
|
+
return `\xAB${doc.title}\xBB \xB7 ${best.length} filas ${match}; mostrando ${shown} (\u2248 ${used} de \u2248 ${doc.tokensOriginal.toLocaleString("en")} tokens del original)
|
|
727
|
+
` + out.join("\n") + (shown < best.length ? `
|
|
728
|
+
|
|
729
|
+
+${best.length - shown} filas m\xE1s: sube max_tokens o afina la pregunta.` : "");
|
|
730
|
+
}
|
|
731
|
+
var MAX_SEMANTIC_SECTIONS = 300;
|
|
732
|
+
async function sectionVectors(vault, doc) {
|
|
733
|
+
const key = sha256(doc.rel + doc.sections.map((s) => s.text).join("\0")).slice(0, 16);
|
|
734
|
+
const file = path4.join(vault.cache, "docvec", `${key}.bin`);
|
|
735
|
+
const dim = DIM;
|
|
736
|
+
try {
|
|
737
|
+
const buf = fs4.readFileSync(file);
|
|
738
|
+
const all = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
|
|
739
|
+
if (all.length === doc.sections.length * dim) {
|
|
740
|
+
return doc.sections.map((_, i) => all.subarray(i * dim, (i + 1) * dim));
|
|
741
|
+
}
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
const vecs = await embed(doc.sections.map((s) => `${s.title}
|
|
745
|
+
${s.text.slice(0, 1200)}`), "passage");
|
|
746
|
+
try {
|
|
747
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
748
|
+
const flat = new Float32Array(vecs.length * dim);
|
|
749
|
+
vecs.forEach((v, i) => flat.set(v, i * dim));
|
|
750
|
+
fs4.writeFileSync(file, Buffer.from(flat.buffer));
|
|
751
|
+
} catch {
|
|
752
|
+
}
|
|
753
|
+
return vecs;
|
|
754
|
+
}
|
|
755
|
+
async function readDoc(vault, ref, opts = {}) {
|
|
756
|
+
const doc = findDoc(vault, ref);
|
|
757
|
+
if (!doc) return `No encontr\xE9 el documento \xAB${ref}\xBB. Ingi\xE9relo primero con doc_ingest (ruta del archivo).`;
|
|
758
|
+
const budget = Math.max(200, opts.maxTokens ?? 1500);
|
|
759
|
+
if (!opts.sections?.length && opts.query?.trim() && (doc.format === "xlsx" || doc.format === "csv")) {
|
|
760
|
+
const rows = matchRows(doc, opts.query, budget);
|
|
761
|
+
if (rows) {
|
|
762
|
+
logDocUse(vault, { op: "read", tokensOriginal: 0, tokensServed: tok2(rows) });
|
|
763
|
+
return rows;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
let candidates;
|
|
767
|
+
if (opts.sections?.length) {
|
|
768
|
+
const want = new Set(opts.sections.map((s) => s.trim().toLowerCase()));
|
|
769
|
+
candidates = doc.sections.filter((s) => want.has(s.id) || want.has(s.title.toLowerCase()));
|
|
770
|
+
} else if (opts.query?.trim()) {
|
|
771
|
+
candidates = await rankSections(vault, doc, opts.query);
|
|
772
|
+
} else {
|
|
773
|
+
candidates = doc.sections;
|
|
774
|
+
}
|
|
775
|
+
if (candidates.length === 0) return `Ninguna secci\xF3n coincide.
|
|
776
|
+
|
|
777
|
+
${outline(doc)}`;
|
|
778
|
+
const picked = [];
|
|
779
|
+
let used = 0;
|
|
780
|
+
for (const s of candidates) {
|
|
781
|
+
if (used + s.tokens <= budget) {
|
|
782
|
+
picked.push(s);
|
|
783
|
+
used += s.tokens;
|
|
784
|
+
} else if (picked.length === 0) {
|
|
785
|
+
const cut = { ...s, text: s.text.slice(0, budget * 4) + `
|
|
786
|
+
\u2026(recortada: ~${s.tokens} tok; sube max_tokens para verla completa)` };
|
|
787
|
+
picked.push(cut);
|
|
788
|
+
used = budget;
|
|
789
|
+
break;
|
|
790
|
+
}
|
|
791
|
+
if (opts.query && picked.length >= 4) break;
|
|
792
|
+
}
|
|
793
|
+
const order = new Map(doc.sections.map((s, i) => [s.id, i]));
|
|
794
|
+
picked.sort((a, b) => order.get(a.id) - order.get(b.id));
|
|
795
|
+
const omitted = doc.sections.filter((s) => !picked.some((p) => p.id === s.id));
|
|
796
|
+
const body = picked.map((s) => `[${s.id}]
|
|
797
|
+
${s.text}`).join("\n\n");
|
|
798
|
+
const head = `\xAB${doc.title}\xBB \xB7 ${picked.map((s) => s.id).join(", ")} \xB7 \u2248 ${used} de \u2248 ${doc.tokensOriginal.toLocaleString("en")} tokens del original`;
|
|
799
|
+
const tail = omitted.length ? `
|
|
800
|
+
|
|
801
|
+
+${omitted.length} secciones no incluidas: ${omitted.slice(0, 10).map((s) => `${s.id} ${s.title.length > 40 ? s.title.slice(0, 40) + "\u2026" : s.title}`).join(" \xB7 ")}${omitted.length > 10 ? " \u2026" : ""}` : "";
|
|
802
|
+
const text = `${head}
|
|
803
|
+
|
|
804
|
+
${body}${tail}`;
|
|
805
|
+
logDocUse(vault, { op: "read", tokensOriginal: 0, tokensServed: tok2(text) });
|
|
806
|
+
return text;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
export {
|
|
810
|
+
planContext,
|
|
811
|
+
planQualityHints,
|
|
812
|
+
architectBlock,
|
|
813
|
+
distDir,
|
|
814
|
+
registerHooks,
|
|
815
|
+
unregisterHooks,
|
|
816
|
+
projectSettingsPath,
|
|
817
|
+
globalSettingsPath,
|
|
818
|
+
hooksRegistered,
|
|
819
|
+
serverCommand,
|
|
820
|
+
registerMcpProject,
|
|
821
|
+
registerMcpGlobal,
|
|
822
|
+
mcpRegisteredProject,
|
|
823
|
+
pkgVersion,
|
|
824
|
+
outlineFile,
|
|
825
|
+
outlineDir,
|
|
826
|
+
symbolSource,
|
|
827
|
+
listDocs,
|
|
828
|
+
isUrl,
|
|
829
|
+
ingestAndOutline,
|
|
830
|
+
readDoc
|
|
831
|
+
};
|