@ureck/alexandria 1.0.0 → 1.2.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 +17 -2
- package/dist/chunk-53SIGH5A.js +69 -0
- package/dist/{chunk-DYCARGQR.js → chunk-CIOCSIB5.js} +50 -0
- package/dist/{chunk-DCKYTO4O.js → chunk-FBGIFNIO.js} +1 -1
- package/dist/chunk-QB37UGO6.js +490 -0
- package/dist/{chunk-RZI7TYAG.js → chunk-UWB6RKVN.js} +2 -1
- package/dist/{chunk-DHXL36RG.js → chunk-ZIQYAQCF.js} +19 -33
- package/dist/cli.js +574 -159
- package/dist/hooks/on-prompt.js +41 -27
- package/dist/hooks/on-session-start.js +9 -9
- package/dist/hooks/on-stop.js +27 -3
- package/dist/mcp/server.js +10 -10
- package/dist/{viewer-73ZWPIDC.js → viewer-JQCSWJ3C.js} +2 -3
- package/package.json +1 -1
- package/dist/chunk-D5ROL42O.js +0 -267
- package/dist/chunk-DEDAOKAV.js +0 -44
- package/dist/chunk-XWR74BQ2.js +0 -170
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,6 @@ import {
|
|
|
4
4
|
} from "./chunk-XITAQVOZ.js";
|
|
5
5
|
import {
|
|
6
6
|
architectBlock,
|
|
7
|
-
distDir,
|
|
8
7
|
globalSettingsPath,
|
|
9
8
|
hooksRegistered,
|
|
10
9
|
mcpRegisteredProject,
|
|
@@ -15,13 +14,15 @@ import {
|
|
|
15
14
|
registerHooks,
|
|
16
15
|
registerMcpGlobal,
|
|
17
16
|
registerMcpProject,
|
|
17
|
+
serverCommand,
|
|
18
18
|
unregisterHooks
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-ZIQYAQCF.js";
|
|
20
20
|
import {
|
|
21
21
|
hybridSearch,
|
|
22
22
|
protocolChain
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-UWB6RKVN.js";
|
|
24
24
|
import {
|
|
25
|
+
TOKEN_TOGGLES,
|
|
25
26
|
defaultVaultPath,
|
|
26
27
|
ensureVaultStructure,
|
|
27
28
|
getConfigKey,
|
|
@@ -29,21 +30,20 @@ import {
|
|
|
29
30
|
protocolEnabled,
|
|
30
31
|
resolveVault,
|
|
31
32
|
setConfigKey,
|
|
33
|
+
toggleEnabled,
|
|
32
34
|
vaultExists,
|
|
33
35
|
writeGlobalConfig,
|
|
34
36
|
writeProjectConfig
|
|
35
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-CIOCSIB5.js";
|
|
36
38
|
import {
|
|
37
39
|
serveGraph
|
|
38
|
-
} from "./chunk-
|
|
39
|
-
import {
|
|
40
|
-
VaultIndex
|
|
41
|
-
} from "./chunk-D5ROL42O.js";
|
|
40
|
+
} from "./chunk-FBGIFNIO.js";
|
|
42
41
|
import {
|
|
42
|
+
VaultIndex,
|
|
43
43
|
createNote,
|
|
44
44
|
slugify,
|
|
45
45
|
upsertNote
|
|
46
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-QB37UGO6.js";
|
|
47
47
|
import {
|
|
48
48
|
MODEL_ID,
|
|
49
49
|
dot,
|
|
@@ -53,8 +53,8 @@ import {
|
|
|
53
53
|
} from "./chunk-EDYBSJSS.js";
|
|
54
54
|
|
|
55
55
|
// src/cli.ts
|
|
56
|
-
import
|
|
57
|
-
import
|
|
56
|
+
import fs6 from "fs";
|
|
57
|
+
import path6 from "path";
|
|
58
58
|
import readline from "readline/promises";
|
|
59
59
|
import { Command } from "commander";
|
|
60
60
|
import pc from "picocolors";
|
|
@@ -183,29 +183,182 @@ function installSkill(rec, targetDir) {
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
|
|
186
|
-
// src/
|
|
186
|
+
// src/skills/evolve.ts
|
|
187
187
|
import fs2 from "fs";
|
|
188
188
|
import os2 from "os";
|
|
189
189
|
import path2 from "path";
|
|
190
|
+
var MAX_BODY_CHARS = 6e3;
|
|
191
|
+
var MAX_LESSONS = 12;
|
|
192
|
+
function skillTargetDir(projectDir, global) {
|
|
193
|
+
return global ? path2.join(os2.homedir(), ".claude", "skills") : path2.join(projectDir, ".claude", "skills");
|
|
194
|
+
}
|
|
195
|
+
function noteBody(vault, rel) {
|
|
196
|
+
try {
|
|
197
|
+
return fs2.readFileSync(path2.join(vault.root, rel), "utf8").replace(/^---[\s\S]*?---\n/, "").trim();
|
|
198
|
+
} catch {
|
|
199
|
+
return "";
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
function cleanScanNote(text) {
|
|
203
|
+
return text.replace(/^[^\n]*`ale scan`[^\n]*\n+/g, "").replace(/\n*Proyecto: \[\[[^\]]+\]\]\s*$/g, "").trim();
|
|
204
|
+
}
|
|
205
|
+
function buildSkill(vault, projectName) {
|
|
206
|
+
const idx = VaultIndex.load(vault);
|
|
207
|
+
const slug = slugify(projectName);
|
|
208
|
+
const byTitle = (prefix) => idx.notesByTag("map").find((n) => n.title.toLowerCase() === `${prefix} - ${projectName}`.toLowerCase());
|
|
209
|
+
const flujoNote = byTitle("Flujo");
|
|
210
|
+
const convNote = byTitle("Convenciones");
|
|
211
|
+
const mapaNote = byTitle("Mapa");
|
|
212
|
+
const apiNote = byTitle("API");
|
|
213
|
+
const todasLecciones = idx.notesByTag("lesson").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1));
|
|
214
|
+
const propias = todasLecciones.filter((n) => n.tags.includes(projectName) || n.rel.includes(slug));
|
|
215
|
+
const lecciones = (propias.length > 0 ? propias : todasLecciones).slice(0, MAX_LESSONS);
|
|
216
|
+
if (!flujoNote && !convNote && !mapaNote && lecciones.length === 0) return null;
|
|
217
|
+
const parts = [];
|
|
218
|
+
parts.push(`# ${projectName}
|
|
219
|
+
`);
|
|
220
|
+
parts.push(
|
|
221
|
+
`Conocimiento vivo de este proyecto, destilado por Alexandria desde su b\xF3veda. Refl\xE9jalo al trabajar aqu\xED: evita re-explorar lo que ya est\xE1 mapeado.
|
|
222
|
+
`
|
|
223
|
+
);
|
|
224
|
+
if (convNote) {
|
|
225
|
+
const t = cleanScanNote(noteBody(vault, convNote.rel));
|
|
226
|
+
if (t) parts.push(`## Stack y convenciones
|
|
227
|
+
|
|
228
|
+
${t}
|
|
229
|
+
`);
|
|
230
|
+
}
|
|
231
|
+
if (flujoNote) {
|
|
232
|
+
const t = cleanScanNote(noteBody(vault, flujoNote.rel));
|
|
233
|
+
if (t) parts.push(`## Flujo de la aplicaci\xF3n
|
|
234
|
+
|
|
235
|
+
C\xF3mo recorre una petici\xF3n el sistema:
|
|
236
|
+
|
|
237
|
+
${t}
|
|
238
|
+
`);
|
|
239
|
+
} else if (apiNote) {
|
|
240
|
+
const t = cleanScanNote(noteBody(vault, apiNote.rel));
|
|
241
|
+
if (t) parts.push(`## Superficie de API
|
|
242
|
+
|
|
243
|
+
${t}
|
|
244
|
+
`);
|
|
245
|
+
}
|
|
246
|
+
if (lecciones.length) {
|
|
247
|
+
const items = lecciones.map((l) => {
|
|
248
|
+
const cuerpo = cleanScanNote(noteBody(vault, l.rel)).split("\n").filter(Boolean).slice(0, 2).join(" ");
|
|
249
|
+
const titulo = l.title.replace(/^Lección\s*-\s*/i, "");
|
|
250
|
+
return `- **${titulo}** \u2014 ${cuerpo.slice(0, 240)}`;
|
|
251
|
+
}).join("\n");
|
|
252
|
+
parts.push(`## Lecciones aprendidas aqu\xED
|
|
253
|
+
|
|
254
|
+
Errores ya pagados: no los repitas.
|
|
255
|
+
|
|
256
|
+
${items}
|
|
257
|
+
`);
|
|
258
|
+
}
|
|
259
|
+
let body = parts.join("\n");
|
|
260
|
+
if (body.length > MAX_BODY_CHARS) body = body.slice(0, MAX_BODY_CHARS) + "\n\n\u2026(truncado)\n";
|
|
261
|
+
const skillName = `proyecto-${slug}`;
|
|
262
|
+
const desc = `Conocimiento vivo del proyecto ${projectName}: stack, convenciones, flujo de la aplicaci\xF3n y lecciones ya aprendidas. \xDAsala al trabajar en ${projectName} \u2014 antes de explorar el c\xF3digo o decidir arquitectura.`;
|
|
263
|
+
const front = [
|
|
264
|
+
"---",
|
|
265
|
+
`name: ${skillName}`,
|
|
266
|
+
`description: ${desc}`,
|
|
267
|
+
"metadata:",
|
|
268
|
+
" author: alexandria",
|
|
269
|
+
` version: "${nextVersion(null)}"`,
|
|
270
|
+
` generated: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`,
|
|
271
|
+
" source: ale skills evolve",
|
|
272
|
+
"---",
|
|
273
|
+
""
|
|
274
|
+
].join("\n");
|
|
275
|
+
const file = path2.join("SKILL.md");
|
|
276
|
+
return {
|
|
277
|
+
skillName,
|
|
278
|
+
file,
|
|
279
|
+
content: front + body.trimEnd() + "\n",
|
|
280
|
+
previous: null,
|
|
281
|
+
changed: true,
|
|
282
|
+
sources: {
|
|
283
|
+
flujo: Boolean(flujoNote),
|
|
284
|
+
convenciones: Boolean(convNote),
|
|
285
|
+
mapa: Boolean(mapaNote),
|
|
286
|
+
lecciones: lecciones.length
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
function nextVersion(previous) {
|
|
291
|
+
if (!previous) return "1.0.0";
|
|
292
|
+
const m = previous.match(/version:\s*["']?(\d+)\.(\d+)\.(\d+)/);
|
|
293
|
+
if (!m) return "1.0.0";
|
|
294
|
+
return `${m[1]}.${Number(m[2]) + 1}.0`;
|
|
295
|
+
}
|
|
296
|
+
function evolveSkill(vault, projectName, targetDir) {
|
|
297
|
+
const built = buildSkill(vault, projectName);
|
|
298
|
+
if (!built) return null;
|
|
299
|
+
const dir = path2.join(targetDir, built.skillName);
|
|
300
|
+
const file = path2.join(dir, "SKILL.md");
|
|
301
|
+
let previous = null;
|
|
302
|
+
try {
|
|
303
|
+
previous = fs2.readFileSync(file, "utf8");
|
|
304
|
+
} catch {
|
|
305
|
+
}
|
|
306
|
+
let content = built.content;
|
|
307
|
+
if (previous) {
|
|
308
|
+
content = content.replace(/(\n {2}version: ")[^"]+(")/, `$1${nextVersion(previous)}$2`);
|
|
309
|
+
}
|
|
310
|
+
const norm = (s) => s.replace(/^ {2}(?:version|generated):.*$/gm, "").trim();
|
|
311
|
+
return {
|
|
312
|
+
...built,
|
|
313
|
+
file,
|
|
314
|
+
content,
|
|
315
|
+
previous,
|
|
316
|
+
changed: !previous || norm(previous) !== norm(content)
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
function writeSkill(result) {
|
|
320
|
+
fs2.mkdirSync(path2.dirname(result.file), { recursive: true });
|
|
321
|
+
fs2.writeFileSync(result.file, result.content);
|
|
322
|
+
}
|
|
323
|
+
function simpleDiff(previous, next) {
|
|
324
|
+
if (!previous) return next.split("\n").map((l) => `+ ${l}`);
|
|
325
|
+
const a = previous.split("\n");
|
|
326
|
+
const b = next.split("\n");
|
|
327
|
+
const setA = new Set(a);
|
|
328
|
+
const setB = new Set(b);
|
|
329
|
+
const out = [];
|
|
330
|
+
for (const l of a) if (!setB.has(l)) out.push(`- ${l}`);
|
|
331
|
+
for (const l of b) if (!setA.has(l)) out.push(`+ ${l}`);
|
|
332
|
+
return out;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// src/core/agents.ts
|
|
336
|
+
import fs3 from "fs";
|
|
337
|
+
import os3 from "os";
|
|
338
|
+
import path3 from "path";
|
|
190
339
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
191
|
-
var
|
|
340
|
+
var portableMode = false;
|
|
341
|
+
function setPortableMode(on) {
|
|
342
|
+
portableMode = on;
|
|
343
|
+
}
|
|
344
|
+
var serverCmd = () => serverCommand(portableMode);
|
|
192
345
|
function readJsonSafe(file) {
|
|
193
346
|
try {
|
|
194
|
-
return JSON.parse(
|
|
347
|
+
return JSON.parse(fs3.readFileSync(file, "utf8"));
|
|
195
348
|
} catch {
|
|
196
|
-
if (
|
|
349
|
+
if (fs3.existsSync(file)) throw new Error(`no pude parsear ${file} \u2014 rev\xEDsalo manualmente`);
|
|
197
350
|
return {};
|
|
198
351
|
}
|
|
199
352
|
}
|
|
200
353
|
function writeJson(file, data) {
|
|
201
|
-
|
|
202
|
-
|
|
354
|
+
fs3.mkdirSync(path3.dirname(file), { recursive: true });
|
|
355
|
+
fs3.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");
|
|
203
356
|
}
|
|
204
357
|
function mergeMcpServers(file, key = "mcpServers") {
|
|
205
358
|
try {
|
|
206
359
|
const cfg = readJsonSafe(file);
|
|
207
360
|
const servers = cfg[key] ?? {};
|
|
208
|
-
servers["alexandria"] =
|
|
361
|
+
servers["alexandria"] = serverCmd();
|
|
209
362
|
cfg[key] = servers;
|
|
210
363
|
writeJson(file, cfg);
|
|
211
364
|
return { ok: true, file };
|
|
@@ -214,21 +367,59 @@ function mergeMcpServers(file, key = "mcpServers") {
|
|
|
214
367
|
}
|
|
215
368
|
}
|
|
216
369
|
function home(...p) {
|
|
217
|
-
return
|
|
370
|
+
return path3.join(os3.homedir(), ...p);
|
|
371
|
+
}
|
|
372
|
+
function replaceTomlTable(text, table, block) {
|
|
373
|
+
const lines = text.split("\n");
|
|
374
|
+
const isHeader = (l) => /^\s*\[/.test(l);
|
|
375
|
+
const belongsToTable = (l) => {
|
|
376
|
+
const m = l.match(/^\s*\[+\s*([^\]]+?)\s*\]+/);
|
|
377
|
+
if (!m) return false;
|
|
378
|
+
const name = m[1].trim();
|
|
379
|
+
return name === table || name.startsWith(`${table}.`);
|
|
380
|
+
};
|
|
381
|
+
const out = [];
|
|
382
|
+
let i = 0;
|
|
383
|
+
let replaced = false;
|
|
384
|
+
while (i < lines.length) {
|
|
385
|
+
if (belongsToTable(lines[i])) {
|
|
386
|
+
if (!replaced) {
|
|
387
|
+
out.push(...block.replace(/\n+$/, "").split("\n"));
|
|
388
|
+
replaced = true;
|
|
389
|
+
}
|
|
390
|
+
i++;
|
|
391
|
+
while (i < lines.length && !isHeader(lines[i])) i++;
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
out.push(lines[i]);
|
|
395
|
+
i++;
|
|
396
|
+
}
|
|
397
|
+
let result = out.join("\n");
|
|
398
|
+
if (!replaced) {
|
|
399
|
+
result = result.trimEnd() + (result.trim() ? "\n\n" : "") + block;
|
|
400
|
+
}
|
|
401
|
+
return result.replace(/\n{3,}/g, "\n\n");
|
|
218
402
|
}
|
|
219
403
|
function vscodeUserDir() {
|
|
220
404
|
if (process.platform === "darwin") return home("Library", "Application Support", "Code", "User");
|
|
221
|
-
if (process.platform === "win32") return
|
|
405
|
+
if (process.platform === "win32") return path3.join(process.env.APPDATA ?? home("AppData", "Roaming"), "Code", "User");
|
|
222
406
|
return home(".config", "Code", "User");
|
|
223
407
|
}
|
|
408
|
+
function hasCopilotChatExtension() {
|
|
409
|
+
try {
|
|
410
|
+
return fs3.readdirSync(home(".vscode", "extensions")).some((d) => d.toLowerCase().startsWith("github.copilot-chat"));
|
|
411
|
+
} catch {
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
224
415
|
var AGENTS = [
|
|
225
416
|
{
|
|
226
417
|
id: "claude",
|
|
227
418
|
name: "Claude Code",
|
|
228
419
|
supportsProject: true,
|
|
229
|
-
detect: () =>
|
|
420
|
+
detect: () => fs3.existsSync(home(".claude")),
|
|
230
421
|
register(scope, projectDir) {
|
|
231
|
-
if (scope === "project") return mergeMcpServers(
|
|
422
|
+
if (scope === "project") return mergeMcpServers(path3.join(projectDir, ".mcp.json"));
|
|
232
423
|
return mergeMcpServers(home(".claude.json"));
|
|
233
424
|
}
|
|
234
425
|
},
|
|
@@ -236,9 +427,9 @@ var AGENTS = [
|
|
|
236
427
|
id: "cursor",
|
|
237
428
|
name: "Cursor",
|
|
238
429
|
supportsProject: true,
|
|
239
|
-
detect: () =>
|
|
430
|
+
detect: () => fs3.existsSync(home(".cursor")),
|
|
240
431
|
register(scope, projectDir) {
|
|
241
|
-
const file = scope === "project" ?
|
|
432
|
+
const file = scope === "project" ? path3.join(projectDir, ".cursor", "mcp.json") : home(".cursor", "mcp.json");
|
|
242
433
|
return mergeMcpServers(file);
|
|
243
434
|
}
|
|
244
435
|
},
|
|
@@ -246,14 +437,14 @@ var AGENTS = [
|
|
|
246
437
|
id: "opencode",
|
|
247
438
|
name: "OpenCode",
|
|
248
439
|
supportsProject: true,
|
|
249
|
-
detect: () =>
|
|
440
|
+
detect: () => fs3.existsSync(home(".config", "opencode")) || fs3.existsSync(home(".opencode")),
|
|
250
441
|
register(scope, projectDir) {
|
|
251
|
-
const file = scope === "project" ?
|
|
442
|
+
const file = scope === "project" ? path3.join(projectDir, "opencode.json") : home(".config", "opencode", "opencode.json");
|
|
252
443
|
try {
|
|
253
444
|
const cfg = readJsonSafe(file);
|
|
254
445
|
cfg["$schema"] ??= "https://opencode.ai/config.json";
|
|
255
446
|
const mcp = cfg["mcp"] ?? {};
|
|
256
|
-
mcp["alexandria"] = { type: "local", command: [
|
|
447
|
+
mcp["alexandria"] = { type: "local", command: [serverCmd().command, ...serverCmd().args], enabled: true };
|
|
257
448
|
cfg["mcp"] = mcp;
|
|
258
449
|
writeJson(file, cfg);
|
|
259
450
|
return { ok: true, file };
|
|
@@ -266,7 +457,7 @@ var AGENTS = [
|
|
|
266
457
|
id: "windsurf",
|
|
267
458
|
name: "Windsurf",
|
|
268
459
|
supportsProject: false,
|
|
269
|
-
detect: () =>
|
|
460
|
+
detect: () => fs3.existsSync(home(".codeium", "windsurf")),
|
|
270
461
|
register() {
|
|
271
462
|
return mergeMcpServers(home(".codeium", "windsurf", "mcp_config.json"));
|
|
272
463
|
}
|
|
@@ -275,9 +466,9 @@ var AGENTS = [
|
|
|
275
466
|
id: "cline",
|
|
276
467
|
name: "Cline (VS Code)",
|
|
277
468
|
supportsProject: false,
|
|
278
|
-
detect: () =>
|
|
469
|
+
detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "globalStorage", "saoudrizwan.claude-dev")),
|
|
279
470
|
register() {
|
|
280
|
-
const file =
|
|
471
|
+
const file = path3.join(
|
|
281
472
|
vscodeUserDir(),
|
|
282
473
|
"globalStorage",
|
|
283
474
|
"saoudrizwan.claude-dev",
|
|
@@ -291,26 +482,24 @@ var AGENTS = [
|
|
|
291
482
|
id: "codex",
|
|
292
483
|
name: "Codex CLI (OpenAI)",
|
|
293
484
|
supportsProject: false,
|
|
294
|
-
detect: () =>
|
|
485
|
+
detect: () => fs3.existsSync(home(".codex")),
|
|
295
486
|
register() {
|
|
296
487
|
const file = home(".codex", "config.toml");
|
|
488
|
+
const { command, args } = serverCmd();
|
|
489
|
+
const tomlArgs = args.map((a) => `"${a.replace(/\\/g, "\\\\")}"`).join(", ");
|
|
297
490
|
const block = `[mcp_servers.alexandria]
|
|
298
|
-
command = "
|
|
299
|
-
args = [
|
|
491
|
+
command = "${command}"
|
|
492
|
+
args = [${tomlArgs}]
|
|
300
493
|
`;
|
|
301
494
|
try {
|
|
302
495
|
let text = "";
|
|
303
496
|
try {
|
|
304
|
-
text =
|
|
497
|
+
text = fs3.readFileSync(file, "utf8");
|
|
305
498
|
} catch {
|
|
306
499
|
}
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
text = text.trimEnd() + (text.trim() ? "\n\n" : "") + block;
|
|
311
|
-
}
|
|
312
|
-
fs2.mkdirSync(path2.dirname(file), { recursive: true });
|
|
313
|
-
fs2.writeFileSync(file, text);
|
|
500
|
+
text = replaceTomlTable(text, "mcp_servers.alexandria", block);
|
|
501
|
+
fs3.mkdirSync(path3.dirname(file), { recursive: true });
|
|
502
|
+
fs3.writeFileSync(file, text);
|
|
314
503
|
return { ok: true, file };
|
|
315
504
|
} catch (e) {
|
|
316
505
|
return { ok: false, file, detail: e.message };
|
|
@@ -321,9 +510,9 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
|
|
|
321
510
|
id: "gemini",
|
|
322
511
|
name: "Gemini CLI",
|
|
323
512
|
supportsProject: true,
|
|
324
|
-
detect: () =>
|
|
513
|
+
detect: () => fs3.existsSync(home(".gemini")),
|
|
325
514
|
register(scope, projectDir) {
|
|
326
|
-
const file = scope === "project" ?
|
|
515
|
+
const file = scope === "project" ? path3.join(projectDir, ".gemini", "settings.json") : home(".gemini", "settings.json");
|
|
327
516
|
return mergeMcpServers(file);
|
|
328
517
|
}
|
|
329
518
|
},
|
|
@@ -331,13 +520,13 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
|
|
|
331
520
|
id: "openclaw",
|
|
332
521
|
name: "OpenClaw",
|
|
333
522
|
supportsProject: false,
|
|
334
|
-
detect: () =>
|
|
523
|
+
detect: () => fs3.existsSync(home(".openclaw")),
|
|
335
524
|
register() {
|
|
336
525
|
const file = home(".openclaw", "openclaw.json");
|
|
337
526
|
try {
|
|
338
527
|
const cfg = readJsonSafe(file);
|
|
339
528
|
const servers = cfg["mcpServers"] ?? {};
|
|
340
|
-
servers["alexandria"] = {
|
|
529
|
+
servers["alexandria"] = { ...serverCmd(), transport: "stdio" };
|
|
341
530
|
cfg["mcpServers"] = servers;
|
|
342
531
|
writeJson(file, cfg);
|
|
343
532
|
return { ok: true, file, detail: "reinicia el gateway de OpenClaw para que lo tome" };
|
|
@@ -350,11 +539,11 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
|
|
|
350
539
|
id: "hermes",
|
|
351
540
|
name: "Hermes Agent (Nous)",
|
|
352
541
|
supportsProject: false,
|
|
353
|
-
detect: () =>
|
|
542
|
+
detect: () => fs3.existsSync(home(".hermes")),
|
|
354
543
|
register() {
|
|
355
544
|
const file = home(".hermes", "config.yaml");
|
|
356
545
|
try {
|
|
357
|
-
execFileSync2("hermes", ["mcp", "add", "alexandria", "--command",
|
|
546
|
+
execFileSync2("hermes", ["mcp", "add", "alexandria", "--command", serverCmd().command, "--args", serverCmd().args.join(" ")], {
|
|
358
547
|
stdio: "pipe",
|
|
359
548
|
timeout: 15e3
|
|
360
549
|
});
|
|
@@ -364,15 +553,16 @@ args = ["${serverScript().replace(/\\/g, "\\\\")}"]
|
|
|
364
553
|
try {
|
|
365
554
|
let text = "";
|
|
366
555
|
try {
|
|
367
|
-
text =
|
|
556
|
+
text = fs3.readFileSync(file, "utf8");
|
|
368
557
|
} catch {
|
|
369
558
|
}
|
|
370
559
|
if (/^\s*alexandria:/m.test(text)) return { ok: true, file, detail: "ya registrado" };
|
|
560
|
+
const hc = serverCmd();
|
|
371
561
|
const entry = ` alexandria:
|
|
372
562
|
type: stdio
|
|
373
|
-
command:
|
|
563
|
+
command: ${hc.command}
|
|
374
564
|
args:
|
|
375
|
-
- "${
|
|
565
|
+
${hc.args.map((a) => ` - "${a}"`).join("\n")}
|
|
376
566
|
`;
|
|
377
567
|
if (/^mcp_servers:\s*$/m.test(text)) {
|
|
378
568
|
text = text.replace(/^mcp_servers:\s*$/m, (m) => `${m}
|
|
@@ -382,8 +572,8 @@ ${entry.trimEnd()}`);
|
|
|
382
572
|
} else {
|
|
383
573
|
text = text.trimEnd() + (text.trim() ? "\n\n" : "") + "mcp_servers:\n" + entry;
|
|
384
574
|
}
|
|
385
|
-
|
|
386
|
-
|
|
575
|
+
fs3.mkdirSync(path3.dirname(file), { recursive: true });
|
|
576
|
+
fs3.writeFileSync(file, text);
|
|
387
577
|
return { ok: true, file };
|
|
388
578
|
} catch (e) {
|
|
389
579
|
return { ok: false, file, detail: e.message };
|
|
@@ -394,13 +584,16 @@ ${entry.trimEnd()}`);
|
|
|
394
584
|
id: "vscode",
|
|
395
585
|
name: "VS Code (Copilot)",
|
|
396
586
|
supportsProject: true,
|
|
397
|
-
|
|
587
|
+
// Señal REAL de soporte MCP: un mcp.json existente o la extensión de Copilot
|
|
588
|
+
// Chat instalada. Antes bastaba con que existiera el User dir, así que
|
|
589
|
+
// cualquiera con VS Code aparecía como agente detectado aunque no use MCP.
|
|
590
|
+
detect: () => fs3.existsSync(path3.join(vscodeUserDir(), "mcp.json")) || hasCopilotChatExtension(),
|
|
398
591
|
register(scope, projectDir) {
|
|
399
|
-
const file = scope === "project" ?
|
|
592
|
+
const file = scope === "project" ? path3.join(projectDir, ".vscode", "mcp.json") : path3.join(vscodeUserDir(), "mcp.json");
|
|
400
593
|
try {
|
|
401
594
|
const cfg = readJsonSafe(file);
|
|
402
595
|
const servers = cfg["servers"] ?? {};
|
|
403
|
-
servers["alexandria"] = { type: "stdio",
|
|
596
|
+
servers["alexandria"] = { type: "stdio", ...serverCmd() };
|
|
404
597
|
cfg["servers"] = servers;
|
|
405
598
|
writeJson(file, cfg);
|
|
406
599
|
return { ok: true, file };
|
|
@@ -481,9 +674,9 @@ async function showBanner(animate) {
|
|
|
481
674
|
}
|
|
482
675
|
|
|
483
676
|
// src/core/setup.ts
|
|
484
|
-
import
|
|
485
|
-
import
|
|
486
|
-
import
|
|
677
|
+
import fs4 from "fs";
|
|
678
|
+
import os4 from "os";
|
|
679
|
+
import path4 from "path";
|
|
487
680
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
488
681
|
var PERSONAL_CONFIG_FILES = [
|
|
489
682
|
".vault.json",
|
|
@@ -494,15 +687,15 @@ var PERSONAL_CONFIG_FILES = [
|
|
|
494
687
|
".gemini/settings.json"
|
|
495
688
|
];
|
|
496
689
|
function ensureGitignore(projectDir, vaultRoot) {
|
|
497
|
-
if (!
|
|
690
|
+
if (!fs4.existsSync(path4.join(projectDir, ".git"))) return null;
|
|
498
691
|
const entries = [];
|
|
499
|
-
const rel =
|
|
500
|
-
if (!rel.startsWith("..")) entries.push(`${rel.split(
|
|
692
|
+
const rel = path4.relative(projectDir, vaultRoot);
|
|
693
|
+
if (!rel.startsWith("..")) entries.push(`${rel.split(path4.sep).join("/")}/`);
|
|
501
694
|
entries.push(...PERSONAL_CONFIG_FILES);
|
|
502
|
-
const file =
|
|
695
|
+
const file = path4.join(projectDir, ".gitignore");
|
|
503
696
|
let text = "";
|
|
504
697
|
try {
|
|
505
|
-
text =
|
|
698
|
+
text = fs4.readFileSync(file, "utf8");
|
|
506
699
|
} catch {
|
|
507
700
|
}
|
|
508
701
|
const has = (e) => text.split("\n").some((l) => l.trim() === e || l.trim() === e.replace(/\/$/, ""));
|
|
@@ -513,14 +706,14 @@ function ensureGitignore(projectDir, vaultRoot) {
|
|
|
513
706
|
# Alexandria (conocimiento y config personal \u2014 no del repo)
|
|
514
707
|
${missing.join("\n")}
|
|
515
708
|
`;
|
|
516
|
-
|
|
709
|
+
fs4.writeFileSync(file, text.trim() ? block : block.trimStart());
|
|
517
710
|
return file;
|
|
518
711
|
}
|
|
519
712
|
function untrackPersonalConfigs(projectDir) {
|
|
520
|
-
if (!
|
|
713
|
+
if (!fs4.existsSync(path4.join(projectDir, ".git"))) return [];
|
|
521
714
|
const untracked = [];
|
|
522
715
|
for (const f of PERSONAL_CONFIG_FILES) {
|
|
523
|
-
if (!
|
|
716
|
+
if (!fs4.existsSync(path4.join(projectDir, f))) continue;
|
|
524
717
|
try {
|
|
525
718
|
const tracked = execFileSync3("git", ["ls-files", "--error-unmatch", f], {
|
|
526
719
|
cwd: projectDir,
|
|
@@ -538,7 +731,7 @@ function untrackPersonalConfigs(projectDir) {
|
|
|
538
731
|
var CLAUDE_MD_START = "<!-- alexandria:start -->";
|
|
539
732
|
var CLAUDE_MD_END = "<!-- alexandria:end -->";
|
|
540
733
|
function configureClaudeMd(scope, projectDir) {
|
|
541
|
-
const file = scope === "project" ?
|
|
734
|
+
const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
|
|
542
735
|
const block = [
|
|
543
736
|
CLAUDE_MD_START,
|
|
544
737
|
"## Alexandria \u2014 b\xF3veda de conocimiento y Protocolo (uso por default)",
|
|
@@ -550,10 +743,10 @@ function configureClaudeMd(scope, projectDir) {
|
|
|
550
743
|
"- `vault_related` trae conocimiento conectado sin releer archivos.",
|
|
551
744
|
CLAUDE_MD_END
|
|
552
745
|
].join("\n");
|
|
553
|
-
|
|
746
|
+
fs4.mkdirSync(path4.dirname(file), { recursive: true });
|
|
554
747
|
let text = "";
|
|
555
748
|
try {
|
|
556
|
-
text =
|
|
749
|
+
text = fs4.readFileSync(file, "utf8");
|
|
557
750
|
} catch {
|
|
558
751
|
}
|
|
559
752
|
if (text.includes(CLAUDE_MD_START)) {
|
|
@@ -562,14 +755,14 @@ function configureClaudeMd(scope, projectDir) {
|
|
|
562
755
|
} else {
|
|
563
756
|
text = (text.trimEnd() + "\n\n" + block + "\n").trimStart();
|
|
564
757
|
}
|
|
565
|
-
|
|
758
|
+
fs4.writeFileSync(file, text);
|
|
566
759
|
return file;
|
|
567
760
|
}
|
|
568
761
|
function removeClaudeMd(scope, projectDir) {
|
|
569
|
-
const file = scope === "project" ?
|
|
762
|
+
const file = scope === "project" ? path4.join(projectDir, "CLAUDE.md") : path4.join(os4.homedir(), ".claude", "CLAUDE.md");
|
|
570
763
|
let text;
|
|
571
764
|
try {
|
|
572
|
-
text =
|
|
765
|
+
text = fs4.readFileSync(file, "utf8");
|
|
573
766
|
} catch {
|
|
574
767
|
return null;
|
|
575
768
|
}
|
|
@@ -577,20 +770,20 @@ function removeClaudeMd(scope, projectDir) {
|
|
|
577
770
|
const re = new RegExp(`\\n*${CLAUDE_MD_START}[\\s\\S]*?${CLAUDE_MD_END}\\n*`);
|
|
578
771
|
const cleaned = text.replace(re, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
579
772
|
if (cleaned === "") {
|
|
580
|
-
|
|
773
|
+
fs4.rmSync(file, { force: true });
|
|
581
774
|
} else {
|
|
582
|
-
|
|
775
|
+
fs4.writeFileSync(file, cleaned + "\n");
|
|
583
776
|
}
|
|
584
777
|
return file;
|
|
585
778
|
}
|
|
586
779
|
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", ".vault", ".claude", "coverage", "Alexandria", "KnowledgeVault"]);
|
|
587
780
|
function scanProject(vault, projectDir) {
|
|
588
|
-
const name =
|
|
589
|
-
const mapFile =
|
|
590
|
-
if (
|
|
781
|
+
const name = path4.basename(projectDir);
|
|
782
|
+
const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
|
|
783
|
+
if (fs4.existsSync(mapFile)) return null;
|
|
591
784
|
const parts = [`Mapa inicial generado por \`ale init\` (escaneo autom\xE1tico). Actual\xEDzalo con vault_save.`];
|
|
592
785
|
try {
|
|
593
|
-
const pkg = JSON.parse(
|
|
786
|
+
const pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
|
|
594
787
|
const deps = Object.keys({ ...pkg.dependencies }).slice(0, 18);
|
|
595
788
|
const dev = Object.keys({ ...pkg.devDependencies }).slice(0, 10);
|
|
596
789
|
parts.push(`## Stack
|
|
@@ -609,13 +802,13 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
|
|
|
609
802
|
if (depth > 2 || tree.length > 60) return;
|
|
610
803
|
let entries = [];
|
|
611
804
|
try {
|
|
612
|
-
entries =
|
|
805
|
+
entries = fs4.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !SKIP_DIRS.has(e.name));
|
|
613
806
|
} catch {
|
|
614
807
|
return;
|
|
615
808
|
}
|
|
616
809
|
for (const e of entries.filter((x) => x.isDirectory()).slice(0, 14)) {
|
|
617
810
|
tree.push(`${prefix}${e.name}/`);
|
|
618
|
-
walk(
|
|
811
|
+
walk(path4.join(dir, e.name), depth + 1, prefix + " ");
|
|
619
812
|
}
|
|
620
813
|
};
|
|
621
814
|
walk(projectDir, 1, "");
|
|
@@ -624,7 +817,7 @@ ${scripts.map(([k, v]) => `- \`npm run ${k}\` \u2014 ${v}`).join("\n")}`);
|
|
|
624
817
|
${tree.join("\n")}
|
|
625
818
|
\`\`\``);
|
|
626
819
|
try {
|
|
627
|
-
const readme =
|
|
820
|
+
const readme = fs4.readFileSync(path4.join(projectDir, "README.md"), "utf8");
|
|
628
821
|
parts.push(`## README (extracto)
|
|
629
822
|
${readme.split("\n").slice(0, 15).join("\n")}`);
|
|
630
823
|
} catch {
|
|
@@ -640,8 +833,8 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
|
|
|
640
833
|
}
|
|
641
834
|
|
|
642
835
|
// src/core/scan.ts
|
|
643
|
-
import
|
|
644
|
-
import
|
|
836
|
+
import fs5 from "fs";
|
|
837
|
+
import path5 from "path";
|
|
645
838
|
var SKIP_DIRS2 = /* @__PURE__ */ new Set([
|
|
646
839
|
"node_modules",
|
|
647
840
|
".git",
|
|
@@ -659,38 +852,84 @@ var SKIP_DIRS2 = /* @__PURE__ */ new Set([
|
|
|
659
852
|
"vendor"
|
|
660
853
|
]);
|
|
661
854
|
var SOURCE_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
|
|
662
|
-
var MAX_FILES =
|
|
855
|
+
var MAX_FILES = 800;
|
|
663
856
|
var MAX_FILE_BYTES = 64 * 1024;
|
|
664
|
-
var
|
|
857
|
+
var MAX_DEPTH = 7;
|
|
858
|
+
var BASE_ENTRIES = 80;
|
|
859
|
+
var HARD_ENTRIES = 200;
|
|
860
|
+
function entryCap(rawCount) {
|
|
861
|
+
const cfg = getConfigKey("scan.maxEntries");
|
|
862
|
+
const n = typeof cfg === "number" ? cfg : typeof cfg === "string" ? parseInt(cfg, 10) : NaN;
|
|
863
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
864
|
+
return Math.min(Math.max(rawCount, BASE_ENTRIES), HARD_ENTRIES);
|
|
865
|
+
}
|
|
866
|
+
function capLines(lines, cap) {
|
|
867
|
+
if (lines.length <= cap) return lines;
|
|
868
|
+
return [
|
|
869
|
+
...lines.slice(0, cap),
|
|
870
|
+
`\u2026 +${lines.length - cap} m\xE1s (trunca a ${cap}; sube con: ale config set scan.maxEntries <n>)`
|
|
871
|
+
];
|
|
872
|
+
}
|
|
873
|
+
var TRAVERSE_SAFETY = 2e4;
|
|
665
874
|
function collectSourceFiles(projectDir) {
|
|
666
|
-
const
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
entries =
|
|
672
|
-
|
|
673
|
-
|
|
875
|
+
const candidates = [];
|
|
876
|
+
let level = [projectDir];
|
|
877
|
+
for (let depth = 0; depth <= MAX_DEPTH && level.length > 0 && candidates.length < TRAVERSE_SAFETY; depth++) {
|
|
878
|
+
const next = [];
|
|
879
|
+
for (const dir of level) {
|
|
880
|
+
let entries = [];
|
|
881
|
+
try {
|
|
882
|
+
entries = fs5.readdirSync(dir, { withFileTypes: true });
|
|
883
|
+
} catch {
|
|
884
|
+
continue;
|
|
885
|
+
}
|
|
886
|
+
for (const e of entries) {
|
|
887
|
+
if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
|
|
888
|
+
const full = path5.join(dir, e.name);
|
|
889
|
+
if (e.isDirectory()) next.push(full);
|
|
890
|
+
else if (e.isFile() && SOURCE_EXT.has(path5.extname(e.name))) {
|
|
891
|
+
candidates.push(full);
|
|
892
|
+
if (candidates.length >= TRAVERSE_SAFETY) break;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
if (candidates.length >= TRAVERSE_SAFETY) break;
|
|
674
896
|
}
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
897
|
+
level = next;
|
|
898
|
+
}
|
|
899
|
+
let chosen = candidates;
|
|
900
|
+
if (candidates.length > MAX_FILES) {
|
|
901
|
+
const groups = /* @__PURE__ */ new Map();
|
|
902
|
+
for (const c of candidates) {
|
|
903
|
+
const key = path5.relative(projectDir, c).split(path5.sep)[0];
|
|
904
|
+
const g = groups.get(key);
|
|
905
|
+
if (g) g.push(c);
|
|
906
|
+
else groups.set(key, [c]);
|
|
907
|
+
}
|
|
908
|
+
const lists = [...groups.values()];
|
|
909
|
+
chosen = [];
|
|
910
|
+
for (let i = 0; chosen.length < MAX_FILES; i++) {
|
|
911
|
+
let any = false;
|
|
912
|
+
for (const list of lists) {
|
|
913
|
+
if (i < list.length) {
|
|
914
|
+
chosen.push(list[i]);
|
|
915
|
+
any = true;
|
|
916
|
+
if (chosen.length >= MAX_FILES) break;
|
|
689
917
|
}
|
|
690
918
|
}
|
|
919
|
+
if (!any) break;
|
|
691
920
|
}
|
|
692
|
-
}
|
|
693
|
-
|
|
921
|
+
}
|
|
922
|
+
const out = [];
|
|
923
|
+
for (const full of chosen) {
|
|
924
|
+
try {
|
|
925
|
+
if (fs5.statSync(full).size > MAX_FILE_BYTES) continue;
|
|
926
|
+
out.push({
|
|
927
|
+
rel: path5.relative(projectDir, full).split(path5.sep).join("/"),
|
|
928
|
+
content: fs5.readFileSync(full, "utf8")
|
|
929
|
+
});
|
|
930
|
+
} catch {
|
|
931
|
+
}
|
|
932
|
+
}
|
|
694
933
|
return out;
|
|
695
934
|
}
|
|
696
935
|
var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
@@ -700,10 +939,11 @@ function appRoutePath(rel) {
|
|
|
700
939
|
const segs = m[1].split("/").filter((s) => s && !/^\(.*\)$/.test(s));
|
|
701
940
|
return "/" + segs.join("/").replace(/\/$/, "");
|
|
702
941
|
}
|
|
942
|
+
var RAW_SAFETY = 1e3;
|
|
703
943
|
function scanApi(files) {
|
|
704
944
|
const lines = [];
|
|
705
945
|
for (const f of files) {
|
|
706
|
-
if (lines.length >=
|
|
946
|
+
if (lines.length >= RAW_SAFETY) break;
|
|
707
947
|
if (/(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel)) {
|
|
708
948
|
const methods = HTTP_METHODS.filter(
|
|
709
949
|
(m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
|
|
@@ -724,17 +964,66 @@ function scanApi(files) {
|
|
|
724
964
|
const expressHits = [...f.content.matchAll(/\b(?:app|router|api)\.(get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/g)];
|
|
725
965
|
for (const h of expressHits.slice(0, 12)) {
|
|
726
966
|
lines.push(`- ${h[1].toUpperCase()} ${h[2]} \u2014 ${f.rel}`);
|
|
727
|
-
if (lines.length >=
|
|
967
|
+
if (lines.length >= RAW_SAFETY) break;
|
|
728
968
|
}
|
|
729
969
|
}
|
|
730
|
-
return lines
|
|
970
|
+
return lines;
|
|
971
|
+
}
|
|
972
|
+
function scanFlow(files) {
|
|
973
|
+
const lines = [];
|
|
974
|
+
for (const f of files) {
|
|
975
|
+
if (!/(^|\/)(middleware|proxy)\.[tj]sx?$/.test(f.rel)) continue;
|
|
976
|
+
const matcher = f.content.match(/matcher:\s*\[([^\]]+)\]/)?.[1] ?? f.content.match(/matcher:\s*['"`]([^'"`]+)/)?.[1];
|
|
977
|
+
const rutas = matcher ? matcher.replace(/['"`\s]/g, " ").trim().split(/\s+/).slice(0, 6).join(", ") : "todas las rutas";
|
|
978
|
+
const auth = /auth|session|token|jwt|cookie/i.test(f.content) ? " (verifica sesi\xF3n)" : "";
|
|
979
|
+
lines.push(`- middleware protege: ${rutas}${auth} \u2014 ${f.rel}`);
|
|
980
|
+
}
|
|
981
|
+
for (const f of files) {
|
|
982
|
+
if (lines.length >= RAW_SAFETY) break;
|
|
983
|
+
const body = f.content.replace(/^\s*import[\s\S]*?from\s+['"][^'"]+['"];?\s*$/gm, "");
|
|
984
|
+
const isRoute = /(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel);
|
|
985
|
+
const isPagesApi = /(?:^|\/)pages\/api\//.test(f.rel);
|
|
986
|
+
const isAction = /^\s*['"]use server['"]/m.test(f.content.slice(0, 400));
|
|
987
|
+
if (!isRoute && !isPagesApi && !isAction) continue;
|
|
988
|
+
const parts = [];
|
|
989
|
+
if (isRoute) {
|
|
990
|
+
const methods = HTTP_METHODS.filter(
|
|
991
|
+
(m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
|
|
992
|
+
);
|
|
993
|
+
parts.push(`${methods.join("/") || "handler"} ${appRoutePath(f.rel)}`);
|
|
994
|
+
} else if (isPagesApi) {
|
|
995
|
+
parts.push(`handler /api/${f.rel.replace(/.*pages\/api\//, "").replace(/\.[tj]sx?$/, "")}`);
|
|
996
|
+
} else {
|
|
997
|
+
const fns = [...f.content.matchAll(/export\s+(?:async\s+)?function\s+(\w+)/g)].map((m) => m[1]);
|
|
998
|
+
parts.push(`action ${fns.slice(0, 3).join("/") || "(an\xF3nima)"}`);
|
|
999
|
+
}
|
|
1000
|
+
const authCall = body.match(
|
|
1001
|
+
/\b(require(?:Auth|User|Permiso|Permission|Role|Session)\w*|getServerSession|getSession|currentUser|verifyToken|getToken|auth)\s*\(\s*(["'`]([^"'`]+)["'`])?/
|
|
1002
|
+
);
|
|
1003
|
+
if (authCall) {
|
|
1004
|
+
parts.push(authCall[3] ? `auth: ${authCall[1]}(${authCall[3]})` : `auth: ${authCall[1]}`);
|
|
1005
|
+
}
|
|
1006
|
+
const datos = /* @__PURE__ */ new Set();
|
|
1007
|
+
for (const m of body.matchAll(/\bprisma\.(\w+)\.(\w+)/g)) datos.add(`${m[1]}.${m[2]}`);
|
|
1008
|
+
if (/\bdb\s*\.\s*(?:select|insert|update|delete)\s*\(/.test(body)) datos.add("drizzle");
|
|
1009
|
+
for (const m of body.matchAll(/\b(?:FROM|INTO|UPDATE|JOIN)\s+["'`]?(\w{3,})["'`]?/g)) datos.add(m[1].toLowerCase());
|
|
1010
|
+
for (const imp of f.content.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"][^'"]*(?:queries|db|repository|dal|models?)['"]/g)) {
|
|
1011
|
+
for (const fn of imp[1].split(",").map((x) => x.trim().split(/\s+as\s+/)[0]).filter(Boolean)) datos.add(fn);
|
|
1012
|
+
}
|
|
1013
|
+
if (datos.size) parts.push(`datos: ${[...datos].slice(0, 4).join(", ")}${datos.size > 4 ? "\u2026" : ""}`);
|
|
1014
|
+
if (/\b(?:auditar|audit|logEvent)\s*\(/.test(body)) parts.push("audita");
|
|
1015
|
+
if (/\b(?:fetch|axios)\s*\(/.test(body)) parts.push("llama API externa");
|
|
1016
|
+
if (/\b(?:revalidatePath|revalidateTag|updateTag)\s*\(/.test(body)) parts.push("revalida cach\xE9");
|
|
1017
|
+
lines.push(`- ${parts.join(" \u2192 ")} \u2014 ${f.rel}`);
|
|
1018
|
+
}
|
|
1019
|
+
return lines;
|
|
731
1020
|
}
|
|
732
1021
|
function scanEnvNames(projectDir) {
|
|
733
1022
|
const seen = /* @__PURE__ */ new Map();
|
|
734
1023
|
for (const file of [".env.example", ".env", ".env.local"]) {
|
|
735
1024
|
let text;
|
|
736
1025
|
try {
|
|
737
|
-
text =
|
|
1026
|
+
text = fs5.readFileSync(path5.join(projectDir, file), "utf8");
|
|
738
1027
|
} catch {
|
|
739
1028
|
continue;
|
|
740
1029
|
}
|
|
@@ -743,12 +1032,12 @@ function scanEnvNames(projectDir) {
|
|
|
743
1032
|
if (m && !seen.has(m[1])) seen.set(m[1], file);
|
|
744
1033
|
}
|
|
745
1034
|
}
|
|
746
|
-
return [...seen.entries()].
|
|
1035
|
+
return [...seen.entries()].map(([name, src]) => `- ${name} (${src})`);
|
|
747
1036
|
}
|
|
748
1037
|
function scanDataSchema(projectDir, files) {
|
|
749
1038
|
const lines = [];
|
|
750
1039
|
try {
|
|
751
|
-
const schema =
|
|
1040
|
+
const schema = fs5.readFileSync(path5.join(projectDir, "prisma", "schema.prisma"), "utf8");
|
|
752
1041
|
for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
|
|
753
1042
|
const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
|
|
754
1043
|
const shown = fields.slice(0, 8).join(", ");
|
|
@@ -765,35 +1054,35 @@ function scanDataSchema(projectDir, files) {
|
|
|
765
1054
|
for (const dir of migDirs) {
|
|
766
1055
|
let sqlFiles = [];
|
|
767
1056
|
try {
|
|
768
|
-
sqlFiles =
|
|
1057
|
+
sqlFiles = fs5.readdirSync(path5.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
|
|
769
1058
|
} catch {
|
|
770
1059
|
continue;
|
|
771
1060
|
}
|
|
772
1061
|
const tables = /* @__PURE__ */ new Set();
|
|
773
1062
|
for (const f of sqlFiles) {
|
|
774
1063
|
try {
|
|
775
|
-
const sql =
|
|
1064
|
+
const sql = fs5.readFileSync(path5.join(projectDir, dir, f), "utf8");
|
|
776
1065
|
for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
|
|
777
1066
|
} catch {
|
|
778
1067
|
}
|
|
779
1068
|
}
|
|
780
1069
|
if (tables.size) lines.push(`- tablas (${dir}/*.sql): ${[...tables].slice(0, 20).join(", ")}`);
|
|
781
1070
|
}
|
|
782
|
-
return lines
|
|
1071
|
+
return lines;
|
|
783
1072
|
}
|
|
784
1073
|
function scanConventions(projectDir) {
|
|
785
1074
|
const lines = [];
|
|
786
|
-
const has = (f) =>
|
|
1075
|
+
const has = (f) => fs5.existsSync(path5.join(projectDir, f));
|
|
787
1076
|
const pm = has("bun.lockb") || has("bun.lock") ? "bun" : has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("package-lock.json") ? "npm" : null;
|
|
788
1077
|
if (pm) lines.push(`- gestor de paquetes: ${pm}`);
|
|
789
1078
|
let pkg = {};
|
|
790
1079
|
try {
|
|
791
|
-
pkg = JSON.parse(
|
|
1080
|
+
pkg = JSON.parse(fs5.readFileSync(path5.join(projectDir, "package.json"), "utf8"));
|
|
792
1081
|
} catch {
|
|
793
1082
|
}
|
|
794
1083
|
if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
|
|
795
1084
|
try {
|
|
796
|
-
const ts = JSON.parse(
|
|
1085
|
+
const ts = JSON.parse(fs5.readFileSync(path5.join(projectDir, "tsconfig.json"), "utf8"));
|
|
797
1086
|
const co = ts.compilerOptions ?? {};
|
|
798
1087
|
lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
|
|
799
1088
|
const paths = Object.keys(co.paths ?? {}).slice(0, 5);
|
|
@@ -815,18 +1104,18 @@ function scanConventions(projectDir) {
|
|
|
815
1104
|
}
|
|
816
1105
|
function linkMapToScans(vault, name, titles) {
|
|
817
1106
|
if (titles.length === 0) return;
|
|
818
|
-
const mapFile =
|
|
1107
|
+
const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
|
|
819
1108
|
try {
|
|
820
|
-
const text =
|
|
1109
|
+
const text = fs5.readFileSync(mapFile, "utf8");
|
|
821
1110
|
if (text.includes("Contexto ampliado:")) return;
|
|
822
|
-
|
|
1111
|
+
fs5.appendFileSync(mapFile, `
|
|
823
1112
|
Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
|
|
824
1113
|
`);
|
|
825
1114
|
} catch {
|
|
826
1115
|
}
|
|
827
1116
|
}
|
|
828
1117
|
function scanAll(vault, projectDir) {
|
|
829
|
-
const name =
|
|
1118
|
+
const name = path5.basename(projectDir);
|
|
830
1119
|
const gitignored = ensureGitignore(projectDir, vault.root) !== null;
|
|
831
1120
|
try {
|
|
832
1121
|
untrackPersonalConfigs(projectDir);
|
|
@@ -852,10 +1141,15 @@ function scanAll(vault, projectDir) {
|
|
|
852
1141
|
const env = run(() => scanEnvNames(projectDir));
|
|
853
1142
|
const data = run(() => scanDataSchema(projectDir, files));
|
|
854
1143
|
const conventions = run(() => scanConventions(projectDir));
|
|
1144
|
+
const flow = run(() => scanFlow(files));
|
|
855
1145
|
const notes = [];
|
|
856
1146
|
const titles = [];
|
|
857
|
-
const
|
|
858
|
-
|
|
1147
|
+
const truncated = [];
|
|
1148
|
+
const write = (kind, title, header, rawLines) => {
|
|
1149
|
+
if (rawLines.length === 0) return;
|
|
1150
|
+
const cap = entryCap(rawLines.length);
|
|
1151
|
+
if (rawLines.length > cap) truncated.push(kind);
|
|
1152
|
+
const lines = capLines(rawLines, cap);
|
|
859
1153
|
notes.push(
|
|
860
1154
|
upsertNote(vault.managed, {
|
|
861
1155
|
fixedName: `${kind}-${slugify(name)}`,
|
|
@@ -876,12 +1170,28 @@ Proyecto: [[Mapa - ${name}]]`
|
|
|
876
1170
|
write("env", `Env - ${name}`, `Variables de entorno (SOLO nombres \u2014 los valores nunca se guardan).`, env);
|
|
877
1171
|
write("datos", `Datos - ${name}`, `Esquema de datos detectado en archivos (sin conexi\xF3n a BD).`, data);
|
|
878
1172
|
write("convenciones", `Convenciones - ${name}`, `Convenciones detectadas por \`ale scan\`.`, conventions);
|
|
1173
|
+
write(
|
|
1174
|
+
"flujo",
|
|
1175
|
+
`Flujo - ${name}`,
|
|
1176
|
+
`Flujo de la app: qu\xE9 recorre una petici\xF3n (entrada \u2192 auth \u2192 datos). Detectado por \`ale scan\`.`,
|
|
1177
|
+
flow
|
|
1178
|
+
);
|
|
879
1179
|
linkMapToScans(vault, name, titles);
|
|
880
|
-
return {
|
|
1180
|
+
return {
|
|
1181
|
+
api: api.length,
|
|
1182
|
+
env: env.length,
|
|
1183
|
+
data: data.length,
|
|
1184
|
+
conventions: conventions.length,
|
|
1185
|
+
flow: flow.length,
|
|
1186
|
+
notes,
|
|
1187
|
+
gitignored,
|
|
1188
|
+
truncated
|
|
1189
|
+
};
|
|
881
1190
|
}
|
|
882
1191
|
|
|
883
1192
|
// src/cli.ts
|
|
884
1193
|
function registerAgentsMcp(agents, scope, cwd, portable = false) {
|
|
1194
|
+
setPortableMode(portable);
|
|
885
1195
|
for (const agent of agents) {
|
|
886
1196
|
if (agent.id === "claude") {
|
|
887
1197
|
if (scope === "project") {
|
|
@@ -936,13 +1246,13 @@ async function ensureReady(vault = getVault()) {
|
|
|
936
1246
|
program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: modelo, hooks (Claude Code) y MCP en tus agentes de IA (una sola vez, persiste entre sesiones)").option("--project", "registrar para este proyecto (cwd): .vault.json + .claude/settings.json + .mcp.json").option("--global", "registrar para todas las sesiones del usuario (default)").option(
|
|
937
1247
|
"--path <dir>",
|
|
938
1248
|
"ruta del vault Obsidian (existente o nuevo). Default: ./Alexandria con --project, ~/Alexandria en global"
|
|
939
|
-
).option("--auto", "configurar el uso autom\xE1tico en CLAUDE.md sin preguntar").option("--manual", "no tocar CLAUDE.md (config\xFAralo t\xFA)").option("--no-protocol", "instalar sin el Protocolo Alexandria (solo b\xF3veda cl\xE1sica)").option("--portable", "MCP con comando npx (commiteable en repos de equipo) en vez de ruta local").option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option(
|
|
1249
|
+
).option("--auto", "configurar el uso autom\xE1tico en CLAUDE.md sin preguntar").option("--manual", "no tocar CLAUDE.md (config\xFAralo t\xFA)").option("--no-protocol", "instalar sin el Protocolo Alexandria (solo b\xF3veda cl\xE1sica)").option("--portable", "MCP con comando npx (commiteable en repos de equipo) en vez de ruta local").option("--skills", "al final, recomendar e instalar skills seg\xFAn el contenido").option("--off <keys>", "desactivar desde el inicio comportamientos que gastan tokens (csv, ej. architect.enrich,digest.map \u2014 lista: ale toggles)").option(
|
|
940
1250
|
"--agents <ids>",
|
|
941
1251
|
`agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
|
|
942
1252
|
).action(async (opts) => {
|
|
943
1253
|
const isProject = Boolean(opts.project) && !opts.global;
|
|
944
1254
|
const cwd = process.cwd();
|
|
945
|
-
const vaultPath =
|
|
1255
|
+
const vaultPath = path6.resolve(opts.path ?? (isProject ? path6.join(cwd, "Alexandria") : defaultVaultPath()));
|
|
946
1256
|
await showBanner();
|
|
947
1257
|
console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
|
|
948
1258
|
`));
|
|
@@ -999,9 +1309,22 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
|
|
|
999
1309
|
console.log(
|
|
1000
1310
|
opts.protocol !== false ? pc.green("\u2713 Protocolo Alexandria activo (plan_create \xB7 task_verify \xB7 lesson_extract) \u2014 ap\xE1galo con: ale config set protocol false") : pc.dim(" Protocolo desactivado (b\xF3veda cl\xE1sica) \u2014 act\xEDvalo con: ale config set protocol true")
|
|
1001
1311
|
);
|
|
1312
|
+
if (opts.off) {
|
|
1313
|
+
const valid = new Set(TOKEN_TOGGLES.map((t) => t.key));
|
|
1314
|
+
for (const raw of opts.off.split(",")) {
|
|
1315
|
+
const key = raw.trim();
|
|
1316
|
+
if (!key) continue;
|
|
1317
|
+
if (valid.has(key)) {
|
|
1318
|
+
setConfigKey(key, false);
|
|
1319
|
+
console.log(pc.yellow(`\u2717 desactivado: ${key}`));
|
|
1320
|
+
} else {
|
|
1321
|
+
console.log(pc.yellow(` \u26A0 toggle desconocido \xAB${key}\xBB \u2014 lista: ale toggles`));
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1002
1325
|
if (isProject) {
|
|
1003
1326
|
const s = scanAll(vault, cwd);
|
|
1004
|
-
console.log(pc.green(`\u2713 Proyecto escaneado \u2192 API: ${s.api} \xB7 Env: ${s.env} \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions} (re-ejecuta con: ale scan)`));
|
|
1327
|
+
console.log(pc.green(`\u2713 Proyecto escaneado \u2192 API: ${s.api} \xB7 Env: ${s.env} \xB7 Datos: ${s.data} \xB7 Flujo: ${s.flow} \xB7 Convenciones: ${s.conventions} (re-ejecuta con: ale scan)`));
|
|
1005
1328
|
}
|
|
1006
1329
|
await downloadModelIfMissing();
|
|
1007
1330
|
const idx = VaultIndex.load(vault);
|
|
@@ -1009,15 +1332,16 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
|
|
|
1009
1332
|
console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
|
|
1010
1333
|
console.log(pc.bold(pc.green("\n\u2705 Listo. Abre una sesi\xF3n de tu agente y todo funciona solo \u2014 nada que reconectar nunca.")));
|
|
1011
1334
|
console.log(pc.dim(" Hooks (captura autom\xE1tica) solo en Claude Code; los dem\xE1s agentes usan las tools MCP."));
|
|
1012
|
-
console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents
|
|
1335
|
+
console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents'));
|
|
1336
|
+
console.log(pc.dim(" Controla qu\xE9 gasta tokens (antes o despu\xE9s de instalar): ale toggles\n"));
|
|
1013
1337
|
if (opts.skills) await runSkills({ yes: false, project: isProject });
|
|
1014
1338
|
});
|
|
1015
1339
|
program.command("plan").description("Crear un plan del Protocolo desde un archivo .md/.txt (en vez de escribirlo en la terminal)").argument("<file>", 'archivo con el plan (los checkboxes "- [ ]" se toman como Definition of Done)').option("--title <t>", "t\xEDtulo del plan (default: nombre del archivo o primer heading)").action(async (file, opts) => {
|
|
1016
1340
|
const { vault } = await ensureReady();
|
|
1017
|
-
const abs =
|
|
1018
|
-
const raw =
|
|
1341
|
+
const abs = path6.resolve(file);
|
|
1342
|
+
const raw = fs6.readFileSync(abs, "utf8");
|
|
1019
1343
|
const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
|
|
1020
|
-
const title = opts.title ?? heading ??
|
|
1344
|
+
const title = opts.title ?? heading ?? path6.basename(abs).replace(/\.(md|txt)$/i, "");
|
|
1021
1345
|
const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
|
|
1022
1346
|
const noteFile = createNote(vault.managed, {
|
|
1023
1347
|
title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
|
|
@@ -1027,7 +1351,7 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
|
|
|
1027
1351
|
content: raw.trim()
|
|
1028
1352
|
});
|
|
1029
1353
|
await VaultIndex.load(vault).refresh();
|
|
1030
|
-
console.log(pc.green(`\u2713 Plan creado: ${
|
|
1354
|
+
console.log(pc.green(`\u2713 Plan creado: ${path6.relative(vault.root, noteFile)}`));
|
|
1031
1355
|
console.log(pc.dim(` DoD detectada: ${dod.length} criterios${dod.length ? " \u2014 " + dod.slice(0, 3).join(" \xB7 ") + (dod.length > 3 ? " \u2026" : "") : ' (agrega checkboxes "- [ ]" para criterios verificables)'}`));
|
|
1032
1356
|
console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
|
|
1033
1357
|
const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
|
|
@@ -1037,8 +1361,9 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
|
|
|
1037
1361
|
});
|
|
1038
1362
|
program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD, planes abiertos, fallos sin lecci\xF3n, verificaciones auto-reportadas, notas sueltas").action(async () => {
|
|
1039
1363
|
const { vault, idx } = await ensureReady();
|
|
1040
|
-
const
|
|
1041
|
-
const
|
|
1364
|
+
const noArchive = (n) => !n.rel.split("/").includes("archive");
|
|
1365
|
+
const notes = Object.values(idx.meta.notes).filter(noArchive);
|
|
1366
|
+
const plans = idx.notesByTag("plan").filter(noArchive);
|
|
1042
1367
|
const linked = new Set(idx.meta.links.flatMap((l) => [l.from, l.to]));
|
|
1043
1368
|
console.log(pc.bold("\n\u{1F3DB}\uFE0F Auditor\xEDa del Protocolo Alexandria\n"));
|
|
1044
1369
|
const openPlans = plans.filter((p) => p.status === "active");
|
|
@@ -1051,9 +1376,9 @@ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD
|
|
|
1051
1376
|
console.log(pc.yellow(` \u26A0 Planes sin Definition of Done: ${noDod.length}`));
|
|
1052
1377
|
for (const p of noDod.slice(0, 5)) console.log(pc.dim(` - ${p.title}`));
|
|
1053
1378
|
}
|
|
1054
|
-
const verifs =
|
|
1379
|
+
const verifs = idx.notesByTag("verification").filter(noArchive);
|
|
1055
1380
|
const fails = verifs.filter((n) => n.status === "failed");
|
|
1056
|
-
const lessons =
|
|
1381
|
+
const lessons = idx.notesByTag("lesson").filter(noArchive);
|
|
1057
1382
|
console.log(` Verificaciones: ${verifs.length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
|
|
1058
1383
|
if (fails.length > lessons.length) {
|
|
1059
1384
|
console.log(pc.yellow(` \u26A0 Hay m\xE1s fallos (${fails.length}) que lecciones (${lessons.length}) \u2014 fallos resueltos sin destilar aprendizaje.`));
|
|
@@ -1098,21 +1423,21 @@ program.command("consolidate").description("Archiva prompts viejos sin reuso: sa
|
|
|
1098
1423
|
console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
|
|
1099
1424
|
return;
|
|
1100
1425
|
}
|
|
1101
|
-
const archiveDir =
|
|
1102
|
-
if (!opts.dry)
|
|
1426
|
+
const archiveDir = path6.join(vault.managed, "archive");
|
|
1427
|
+
if (!opts.dry) fs6.mkdirSync(archiveDir, { recursive: true });
|
|
1103
1428
|
for (const n of stale) {
|
|
1104
1429
|
console.log(
|
|
1105
1430
|
`${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
|
|
1106
1431
|
);
|
|
1107
1432
|
if (!opts.dry) {
|
|
1108
|
-
|
|
1433
|
+
fs6.renameSync(path6.join(vault.root, n.rel), path6.join(archiveDir, path6.basename(n.rel)));
|
|
1109
1434
|
}
|
|
1110
1435
|
}
|
|
1111
1436
|
if (!opts.dry) {
|
|
1112
1437
|
await VaultIndex.load(vault).refresh();
|
|
1113
1438
|
console.log(
|
|
1114
1439
|
pc.green(`
|
|
1115
|
-
\u2713 ${stale.length} prompts archivados en ${
|
|
1440
|
+
\u2713 ${stale.length} prompts archivados en ${path6.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
|
|
1116
1441
|
);
|
|
1117
1442
|
} else {
|
|
1118
1443
|
console.log(pc.dim(`
|
|
@@ -1143,10 +1468,10 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
|
|
|
1143
1468
|
const { vault } = await ensureReady();
|
|
1144
1469
|
let content = opts.content;
|
|
1145
1470
|
if (!content && opts.file) {
|
|
1146
|
-
content =
|
|
1471
|
+
content = fs6.readFileSync(path6.resolve(opts.file), "utf8");
|
|
1147
1472
|
}
|
|
1148
1473
|
if (!content && !process.stdin.isTTY) {
|
|
1149
|
-
content =
|
|
1474
|
+
content = fs6.readFileSync(0, "utf8");
|
|
1150
1475
|
}
|
|
1151
1476
|
const file = createNote(vault.managed, {
|
|
1152
1477
|
title,
|
|
@@ -1154,7 +1479,7 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
|
|
|
1154
1479
|
tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
|
|
1155
1480
|
});
|
|
1156
1481
|
await VaultIndex.load(vault).refresh();
|
|
1157
|
-
console.log(pc.green(`\u2713 ${
|
|
1482
|
+
console.log(pc.green(`\u2713 ${path6.relative(vault.root, file)}`));
|
|
1158
1483
|
});
|
|
1159
1484
|
program.command("search").description("B\xFAsqueda h\xEDbrida (sem\xE1ntica + keyword) en la b\xF3veda").argument("<query...>", "qu\xE9 buscar").option("-k <n>", "n\xFAmero de resultados", "6").option("--expand", "incluir vecinos del grafo").action(async (query, opts) => {
|
|
1160
1485
|
const vault = getVault();
|
|
@@ -1202,6 +1527,39 @@ ${pc.bold(pc.cyan(r.note.title))} ${pc.dim(`(${r.note.rel}, ${r.note.type})`)}${
|
|
|
1202
1527
|
}
|
|
1203
1528
|
console.log();
|
|
1204
1529
|
});
|
|
1530
|
+
program.command("toggles").description("Activa/desactiva comportamientos que gastan tokens (con costo aproximado de cada uno)").action(async () => {
|
|
1531
|
+
const printList = () => {
|
|
1532
|
+
console.log(pc.bold("\n\u26A1 Consumo de tokens \u2014 toggles\n"));
|
|
1533
|
+
TOKEN_TOGGLES.forEach((t, i) => {
|
|
1534
|
+
const on = toggleEnabled(t.key);
|
|
1535
|
+
console.log(` ${i + 1}. ${on ? pc.green("\u2713") : pc.red("\u2717")} ${pc.bold(t.label)} ${pc.dim(`(${t.key})`)}`);
|
|
1536
|
+
console.log(pc.dim(` ${t.desc}`));
|
|
1537
|
+
console.log(pc.dim(` ${t.impact}`));
|
|
1538
|
+
});
|
|
1539
|
+
};
|
|
1540
|
+
printList();
|
|
1541
|
+
if (!process.stdin.isTTY) {
|
|
1542
|
+
console.log(pc.dim("\n (no-TTY: cambia con `ale config set <key> true|false`)\n"));
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
1546
|
+
const ans = (await rl.question(pc.bold("\nN\xFAmeros a cambiar (coma), Enter para salir: "))).trim();
|
|
1547
|
+
rl.close();
|
|
1548
|
+
if (!/^[\d,\s]+$/.test(ans) || !ans) {
|
|
1549
|
+
console.log(pc.dim("Sin cambios.\n"));
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
const nums = ans.split(",").map((n) => parseInt(n.trim(), 10) - 1);
|
|
1553
|
+
for (const i of nums) {
|
|
1554
|
+
const t = TOKEN_TOGGLES[i];
|
|
1555
|
+
if (!t) continue;
|
|
1556
|
+
const next = !toggleEnabled(t.key);
|
|
1557
|
+
setConfigKey(t.key, next);
|
|
1558
|
+
console.log(`${next ? pc.green("\u2713 activado") : pc.yellow("\u2717 desactivado")}: ${t.label}`);
|
|
1559
|
+
}
|
|
1560
|
+
printList();
|
|
1561
|
+
console.log();
|
|
1562
|
+
});
|
|
1205
1563
|
program.command("scan").description("Escanea el proyecto (API, env-nombres, datos, convenciones) \u2192 notas de contexto en la b\xF3veda. Re-ejecutable; solo-lectura del c\xF3digo; garantiza .gitignore").action(async () => {
|
|
1206
1564
|
const vault = getVault();
|
|
1207
1565
|
ensureVaultStructure(vault);
|
|
@@ -1210,9 +1568,12 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
|
|
|
1210
1568
|
const idx = VaultIndex.load(vault);
|
|
1211
1569
|
await idx.refresh().catch(() => {
|
|
1212
1570
|
});
|
|
1213
|
-
console.log(pc.green(`\u2713 API: ${s.api} rutas \xB7 Env: ${s.env} vars (solo nombres) \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions}${s.gitignored ? " \xB7 .gitignore \u2713" : ""}`));
|
|
1571
|
+
console.log(pc.green(`\u2713 API: ${s.api} rutas \xB7 Env: ${s.env} vars (solo nombres) \xB7 Datos: ${s.data} \xB7 Flujo: ${s.flow} \xB7 Convenciones: ${s.conventions}${s.gitignored ? " \xB7 .gitignore \u2713" : ""}`));
|
|
1572
|
+
if (s.truncated.length) {
|
|
1573
|
+
console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
|
|
1574
|
+
}
|
|
1214
1575
|
if (s.notes.length) {
|
|
1215
|
-
for (const n of s.notes) console.log(pc.dim(` ${
|
|
1576
|
+
for (const n of s.notes) console.log(pc.dim(` ${path6.relative(vault.root, n)}`));
|
|
1216
1577
|
} else {
|
|
1217
1578
|
console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
|
|
1218
1579
|
}
|
|
@@ -1273,7 +1634,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
|
|
|
1273
1634
|
async function runSkills(opts) {
|
|
1274
1635
|
const { vault } = await ensureReady();
|
|
1275
1636
|
const cwd = process.cwd();
|
|
1276
|
-
const targetDir = opts.project ?
|
|
1637
|
+
const targetDir = opts.project ? path6.join(cwd, ".claude", "skills") : path6.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
|
|
1277
1638
|
const recs = await recommendSkills(vault, [targetDir]);
|
|
1278
1639
|
if (recs.length === 0) {
|
|
1279
1640
|
console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
|
|
@@ -1312,6 +1673,54 @@ async function runSkills(opts) {
|
|
|
1312
1673
|
}
|
|
1313
1674
|
}
|
|
1314
1675
|
program.command("skills").description("Analiza la b\xF3veda y recomienda/instala skills de Claude (skills.sh o repo local)").option("-y, --yes", "instalar sin preguntar").option("--project", "instalar en .claude/skills del proyecto (default: global del usuario)").action(runSkills);
|
|
1676
|
+
program.command("skills:evolve").alias("evolve").description("Genera/actualiza una skill VIVA del proyecto con lo que la b\xF3veda sabe (flujo, convenciones, lecciones). Muestra el diff y pide aprobaci\xF3n").option("-y, --yes", "escribir sin preguntar (para scripts)").option("--global", "guardar en ~/.claude/skills en vez de .claude/skills del proyecto").action(async (opts) => {
|
|
1677
|
+
const { vault } = await ensureReady();
|
|
1678
|
+
const cwd = process.cwd();
|
|
1679
|
+
const proj = path6.basename(cwd);
|
|
1680
|
+
const targetDir = skillTargetDir(cwd, Boolean(opts.global));
|
|
1681
|
+
const result = evolveSkill(vault, proj, targetDir);
|
|
1682
|
+
if (!result) {
|
|
1683
|
+
console.log(pc.yellow(`Sin material todav\xEDa para \xAB${proj}\xBB.`));
|
|
1684
|
+
console.log(pc.dim(" Corre `ale scan` (flujo/convenciones) y acumula lecciones con el Protocolo; luego repite."));
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
const s = result.sources;
|
|
1688
|
+
console.log(pc.bold(`
|
|
1689
|
+
\u{1F9EC} Skill del proyecto: ${result.skillName}`));
|
|
1690
|
+
console.log(pc.dim(` fuentes \u2192 flujo:${s.flujo ? "\u2713" : "\u2014"} convenciones:${s.convenciones ? "\u2713" : "\u2014"} lecciones:${s.lecciones}`));
|
|
1691
|
+
console.log(pc.dim(` destino \u2192 ${result.file}`));
|
|
1692
|
+
if (!result.changed) {
|
|
1693
|
+
console.log(pc.green("\n\u2713 La skill ya est\xE1 al d\xEDa \u2014 nada que cambiar.\n"));
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
const diff = simpleDiff(result.previous, result.content);
|
|
1697
|
+
console.log(pc.bold(`
|
|
1698
|
+
${result.previous ? "Cambios" : "Contenido nuevo"} (${diff.length} l\xEDneas):
|
|
1699
|
+
`));
|
|
1700
|
+
for (const l of diff.slice(0, 40)) {
|
|
1701
|
+
console.log(l.startsWith("+") ? pc.green(l) : pc.red(l));
|
|
1702
|
+
}
|
|
1703
|
+
if (diff.length > 40) console.log(pc.dim(` \u2026 +${diff.length - 40} l\xEDneas m\xE1s`));
|
|
1704
|
+
let ok = Boolean(opts.yes);
|
|
1705
|
+
if (!ok) {
|
|
1706
|
+
if (!process.stdin.isTTY) {
|
|
1707
|
+
console.log(pc.yellow("\n(no interactivo: no se escribi\xF3 nada \u2014 usa `--yes` para aplicar)\n"));
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
1711
|
+
const ans = (await rl.question(pc.bold("\n\xBFEscribir esta skill? [s/N] "))).trim().toLowerCase();
|
|
1712
|
+
rl.close();
|
|
1713
|
+
ok = ans === "s" || ans === "si" || ans === "s\xED" || ans === "y";
|
|
1714
|
+
}
|
|
1715
|
+
if (!ok) {
|
|
1716
|
+
console.log(pc.dim("Sin cambios.\n"));
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
writeSkill(result);
|
|
1720
|
+
console.log(pc.green(`
|
|
1721
|
+
\u2713 Skill escrita en ${result.file}`));
|
|
1722
|
+
console.log(pc.dim(" Se recarga al abrir una sesi\xF3n nueva del agente en este proyecto.\n"));
|
|
1723
|
+
});
|
|
1315
1724
|
program.command("doctor").description("Verifica y repara la instalaci\xF3n (modelo, hooks, MCP, \xEDndice)").option("--project", "revisar registros del proyecto (cwd) en vez de los globales").action(async (opts) => {
|
|
1316
1725
|
const vault = getVault();
|
|
1317
1726
|
const cwd = process.cwd();
|
|
@@ -1346,12 +1755,18 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
|
|
|
1346
1755
|
console.log(pc.yellow("\u26A0 Embeddings desalineados con el \xEDndice \u2014 corre `ale reindex --force`"));
|
|
1347
1756
|
} else if (idx.emb) {
|
|
1348
1757
|
console.log(`${pc.green("\u2713")} Embeddings alineados (${idx.meta.chunks.length} chunks)`);
|
|
1758
|
+
} else if (idx.meta.chunks.length > 0 && model) {
|
|
1759
|
+
console.log(pc.yellow(`\u26A0 \xCDndice SIN vectores (${idx.meta.chunks.length} chunks) \u2014 b\xFAsqueda degradada a keyword. Reconstruyendo\u2026`));
|
|
1760
|
+
const rebuilt = await idx.refresh(true, true);
|
|
1761
|
+
console.log(
|
|
1762
|
+
idx.emb ? `${pc.green("\u2713")} \xCDndice sem\xE1ntico reconstruido (${rebuilt.changed} notas)` : pc.yellow("\u26A0 No se pudo reconstruir \u2014 corre `ale reindex --force` y revisa el modelo")
|
|
1763
|
+
);
|
|
1349
1764
|
}
|
|
1350
1765
|
try {
|
|
1351
|
-
const name =
|
|
1352
|
-
const mapFile =
|
|
1353
|
-
const pkgM =
|
|
1354
|
-
const mapM =
|
|
1766
|
+
const name = path6.basename(cwd);
|
|
1767
|
+
const mapFile = path6.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
|
|
1768
|
+
const pkgM = fs6.statSync(path6.join(cwd, "package.json")).mtimeMs;
|
|
1769
|
+
const mapM = fs6.statSync(mapFile).mtimeMs;
|
|
1355
1770
|
if (pkgM > mapM) {
|
|
1356
1771
|
console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
|
|
1357
1772
|
} else {
|
|
@@ -1360,7 +1775,7 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
|
|
|
1360
1775
|
} catch {
|
|
1361
1776
|
}
|
|
1362
1777
|
const skillsRepoCfg = localSkillsRepo();
|
|
1363
|
-
if (skillsRepoCfg && !
|
|
1778
|
+
if (skillsRepoCfg && !fs6.existsSync(skillsRepoCfg)) {
|
|
1364
1779
|
console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
|
|
1365
1780
|
}
|
|
1366
1781
|
console.log();
|
|
@@ -1374,14 +1789,14 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
|
|
|
1374
1789
|
const claudeMd = removeClaudeMd(scope, cwd);
|
|
1375
1790
|
if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
|
|
1376
1791
|
if (opts.project) {
|
|
1377
|
-
const mcpFile =
|
|
1792
|
+
const mcpFile = path6.join(cwd, ".mcp.json");
|
|
1378
1793
|
try {
|
|
1379
|
-
const cfg = JSON.parse(
|
|
1794
|
+
const cfg = JSON.parse(fs6.readFileSync(mcpFile, "utf8"));
|
|
1380
1795
|
if (cfg.mcpServers?.alexandria) {
|
|
1381
1796
|
delete cfg.mcpServers.alexandria;
|
|
1382
1797
|
if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
|
|
1383
|
-
if (Object.keys(cfg).length === 0)
|
|
1384
|
-
else
|
|
1798
|
+
if (Object.keys(cfg).length === 0) fs6.rmSync(mcpFile, { force: true });
|
|
1799
|
+
else fs6.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
|
|
1385
1800
|
console.log(pc.green("\u2713 MCP removido de .mcp.json"));
|
|
1386
1801
|
}
|
|
1387
1802
|
} catch {
|