@ureck/alexandria 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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-BXVNQVLX.js +831 -0
- package/dist/{chunk-UU4MGB2C.js → chunk-I5H4BN3F.js} +3 -2
- 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/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/package.json +1 -1
- package/dist/chunk-POA77JSS.js +0 -76
- package/dist/chunk-SAKIVZMP.js +0 -495
package/dist/cli.js
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
serveGraph
|
|
4
|
+
} from "./chunk-SSTG2NOO.js";
|
|
2
5
|
import {
|
|
3
6
|
architectBlock,
|
|
4
7
|
distDir,
|
|
5
8
|
globalSettingsPath,
|
|
6
9
|
hooksRegistered,
|
|
7
10
|
ingestAndOutline,
|
|
11
|
+
isUrl,
|
|
8
12
|
listDocs,
|
|
9
13
|
mcpRegisteredProject,
|
|
14
|
+
outlineDir,
|
|
15
|
+
outlineFile,
|
|
10
16
|
pkgVersion,
|
|
11
17
|
planContext,
|
|
12
18
|
planQualityHints,
|
|
@@ -16,12 +22,13 @@ import {
|
|
|
16
22
|
registerMcpGlobal,
|
|
17
23
|
registerMcpProject,
|
|
18
24
|
serverCommand,
|
|
25
|
+
symbolSource,
|
|
19
26
|
unregisterHooks
|
|
20
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-BXVNQVLX.js";
|
|
21
28
|
import {
|
|
22
29
|
hybridSearch,
|
|
23
30
|
protocolChain
|
|
24
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-47S5I3D3.js";
|
|
25
32
|
import {
|
|
26
33
|
ARCHIVE_DIR,
|
|
27
34
|
applyClean,
|
|
@@ -29,13 +36,29 @@ import {
|
|
|
29
36
|
markCleaned,
|
|
30
37
|
planClean,
|
|
31
38
|
searchArchive
|
|
32
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-WSVNMMNN.js";
|
|
33
40
|
import {
|
|
34
|
-
|
|
35
|
-
|
|
41
|
+
VaultIndex,
|
|
42
|
+
createNote,
|
|
43
|
+
slugify,
|
|
44
|
+
supersedeNote,
|
|
45
|
+
upsertNote
|
|
46
|
+
} from "./chunk-44QPE5IM.js";
|
|
36
47
|
import {
|
|
37
48
|
formatOf
|
|
38
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-I5H4BN3F.js";
|
|
50
|
+
import {
|
|
51
|
+
listRuns,
|
|
52
|
+
runCommand,
|
|
53
|
+
saveRun,
|
|
54
|
+
shouldFoldOutput,
|
|
55
|
+
showRun
|
|
56
|
+
} from "./chunk-OGVWOBYH.js";
|
|
57
|
+
import {
|
|
58
|
+
logFold,
|
|
59
|
+
readSessionUsage,
|
|
60
|
+
readStats
|
|
61
|
+
} from "./chunk-X4V6SYYA.js";
|
|
39
62
|
import {
|
|
40
63
|
TOKEN_TOGGLES,
|
|
41
64
|
defaultVaultPath,
|
|
@@ -50,16 +73,7 @@ import {
|
|
|
50
73
|
vaultExists,
|
|
51
74
|
writeGlobalConfig,
|
|
52
75
|
writeProjectConfig
|
|
53
|
-
} from "./chunk-
|
|
54
|
-
import {
|
|
55
|
-
serveGraph
|
|
56
|
-
} from "./chunk-GP5A2GWI.js";
|
|
57
|
-
import {
|
|
58
|
-
VaultIndex,
|
|
59
|
-
createNote,
|
|
60
|
-
slugify,
|
|
61
|
-
upsertNote
|
|
62
|
-
} from "./chunk-BV2KJV5W.js";
|
|
76
|
+
} from "./chunk-YICWI3U3.js";
|
|
63
77
|
import {
|
|
64
78
|
MODEL_ID,
|
|
65
79
|
dot,
|
|
@@ -830,6 +844,7 @@ function opencodePlugin() {
|
|
|
830
844
|
import { execFile } from 'node:child_process';
|
|
831
845
|
|
|
832
846
|
const SCRIPTS = ${JSON.stringify(scripts, null, 2)};
|
|
847
|
+
const CLI = ${JSON.stringify(path4.join(distDir(), "cli.js"))};
|
|
833
848
|
|
|
834
849
|
function run(script, payload, timeoutMs) {
|
|
835
850
|
return new Promise((resolve) => {
|
|
@@ -882,6 +897,24 @@ const AlexandriaPlugin = async ({ directory }) => {
|
|
|
882
897
|
/* sin contexto este turno */
|
|
883
898
|
}
|
|
884
899
|
},
|
|
900
|
+
// Salida grande de bash \u2192 plegada (errores + resumen + final; completa en disco).
|
|
901
|
+
// Aqu\xED s\xED cubre comandos que fallan: OpenCode deja reescribir output.output.
|
|
902
|
+
'tool.execute.after': async (input, output) => {
|
|
903
|
+
try {
|
|
904
|
+
if (input?.tool !== 'bash' || typeof output?.output !== 'string' || output.output.length <= 2048) return;
|
|
905
|
+
const command = String(input.args?.command ?? '');
|
|
906
|
+
const exit = Number(output.metadata?.exit ?? output.metadata?.exitCode ?? 0) || 0;
|
|
907
|
+
const folded = await new Promise((resolve) => {
|
|
908
|
+
const child = execFile('node', [CLI, 'run', '--stdin', '--command', command, '--exit', String(exit)], { cwd: directory, timeout: 8000, windowsHide: true, maxBuffer: 1 << 20 }, (_e, stdout) =>
|
|
909
|
+
resolve(typeof stdout === 'string' ? stdout.trim() : '')
|
|
910
|
+
);
|
|
911
|
+
child.stdin?.end(output.output);
|
|
912
|
+
});
|
|
913
|
+
if (folded && folded.length < output.output.length) output.output = folded;
|
|
914
|
+
} catch {
|
|
915
|
+
/* sin plegado: la salida original sigue intacta */
|
|
916
|
+
}
|
|
917
|
+
},
|
|
885
918
|
'experimental.chat.system.transform': async (input, output) => {
|
|
886
919
|
if (!Array.isArray(output?.system) || !input?.sessionID) return;
|
|
887
920
|
const d = digest.get(input.sessionID);
|
|
@@ -1028,6 +1061,7 @@ var BLOCK = [
|
|
|
1028
1061
|
"- Enriquece la b\xF3veda cuando el trabajo lo revele (no como tarea aparte): decisiones de arquitectura con su porqu\xE9 (por qu\xE9 X y no Y), qu\xE9 hace cada m\xF3dulo/feature al tocarlo, vocabulario propio del dominio, y errores no obvios con su fix (`lesson_extract`). Notas compactas: el objetivo es ahorrar tokens futuros, no escribir prosa.",
|
|
1029
1062
|
"- Las notas `API - <proyecto>` / `Env - <proyecto>` / `Datos - <proyecto>` / `Convenciones - <proyecto>` / `Flujo - <proyecto>` (de `ale scan`) ya traen rutas, variables (solo nombres), esquema y flujo de peticiones \u2014 cons\xFAltalas por b\xFAsqueda antes de releer esos archivos.",
|
|
1030
1063
|
"- `vault_related` trae conocimiento conectado sin releer archivos.",
|
|
1064
|
+
"- Tests/builds/installs con salida larga: `ale run -- <comando>` (devuelve errores + resumen + final y el mismo c\xF3digo de salida; lo completo con `ale run show <id> --grep \u2026`). Para explorar c\xF3digo: `code_outline` / `code_symbol` antes de leer archivos enteros.",
|
|
1031
1065
|
"- PDF/DOCX/XLSX/CSV/HTML: nunca leas el archivo completo \u2014 `doc_ingest` (\xEDndice de secciones, ~200 tokens) y luego `doc_read` con las secciones o una pregunta.",
|
|
1032
1066
|
CLAUDE_MD_END
|
|
1033
1067
|
].join("\n");
|
|
@@ -1742,7 +1776,10 @@ async function runClean(opts) {
|
|
|
1742
1776
|
};
|
|
1743
1777
|
const plan = planClean(vault, Object.values(idx.meta.notes), {
|
|
1744
1778
|
days: parseInt(opts.days, 10) || 45,
|
|
1745
|
-
keepNoise: opts.keepNoise
|
|
1779
|
+
keepNoise: opts.keepNoise,
|
|
1780
|
+
dedupe: !opts.promptsOnly && !opts.quiet,
|
|
1781
|
+
// la limpieza automática ni siquiera los busca
|
|
1782
|
+
idx
|
|
1746
1783
|
});
|
|
1747
1784
|
if (opts.promptsOnly) {
|
|
1748
1785
|
plan.tmpFiles = [];
|
|
@@ -1758,8 +1795,14 @@ async function runClean(opts) {
|
|
|
1758
1795
|
log(` \u2022 ${plan.noise.length} prompts que inyect\xF3 el arn\xE9s (notificaciones/recordatorios) \u2192 ${opts.keepNoise ? "se compactan" : "se descartan"}`);
|
|
1759
1796
|
if (plan.tmpFiles.length) log(` \u2022 ${plan.tmpFiles.length} temporales hu\xE9rfanos del \xEDndice`);
|
|
1760
1797
|
if (plan.staleModels.length) log(` \u2022 ${plan.staleModels.length} modelos viejos en cach\xE9: ${plan.staleModels.map((m) => path7.basename(m)).join(", ")}`);
|
|
1798
|
+
if (plan.duplicates.length) {
|
|
1799
|
+
log(
|
|
1800
|
+
` \u2022 ${plan.duplicates.length} posibles duplicados ${opts.dedupe ? "\u2192 la m\xE1s vieja se marca como reemplazada por la m\xE1s nueva (no se borra)" : pc.dim("(sugerencia: rev\xEDsalos; se aplican solo con --dedupe, o uno por uno con ale supersede)")}:`
|
|
1801
|
+
);
|
|
1802
|
+
for (const d of plan.duplicates.slice(0, 10)) log(pc.dim(` \xAB${d.older.title}\xBB \u2192 \xAB${d.newer.title}\xBB (coseno ${d.cos})`));
|
|
1803
|
+
}
|
|
1761
1804
|
if (plan.statsLinesToRotate) log(` \u2022 stats.jsonl: ${plan.statsLinesToRotate} l\xEDneas de >90 d\xEDas \u2192 resumen (los totales de \`ale stats\` no cambian)`);
|
|
1762
|
-
const nothing = nPrompts + plan.noise.length + plan.tmpFiles.length + plan.staleModels.length + plan.statsLinesToRotate === 0;
|
|
1805
|
+
const nothing = nPrompts + plan.noise.length + plan.tmpFiles.length + plan.staleModels.length + plan.statsLinesToRotate + (opts.dedupe ? plan.duplicates.length : 0) === 0;
|
|
1763
1806
|
if (nothing) {
|
|
1764
1807
|
log(pc.dim("\n Nada que limpiar."));
|
|
1765
1808
|
markCleaned(vault);
|
|
@@ -1774,20 +1817,20 @@ async function runClean(opts) {
|
|
|
1774
1817
|
execFileSync4("tar", ["-czf", out, "-C", vault.root, path7.relative(vault.root, vault.managed) || "."], { stdio: "ignore" });
|
|
1775
1818
|
log(pc.green(`\u2713 Respaldo en ${out}`));
|
|
1776
1819
|
}
|
|
1777
|
-
const res = applyClean(vault, plan);
|
|
1820
|
+
const res = applyClean(vault, plan, { applyDuplicates: opts.dedupe });
|
|
1778
1821
|
await VaultIndex.load(vault).refresh();
|
|
1779
1822
|
markCleaned(vault);
|
|
1780
1823
|
const after = { vault: dirBytes(vault.root, vault.cache), cache: dirBytes(vault.cache) };
|
|
1781
1824
|
log(
|
|
1782
1825
|
pc.green(
|
|
1783
1826
|
`
|
|
1784
|
-
\u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados`
|
|
1827
|
+
\u2713 ${res.compacted} prompts compactados en ${res.bundlesWritten} archivos \xB7 ${res.dropped} de ruido descartados \xB7 ${res.removedDerived} derivados eliminados \xB7 ${res.superseded} duplicados marcados`
|
|
1785
1828
|
)
|
|
1786
1829
|
);
|
|
1787
1830
|
log(pc.dim(` B\xF3veda ${mb(before.vault)} \u2192 ${mb(after.vault)} \xB7 \xEDndice ${mb(before.cache)} \u2192 ${mb(after.cache)}`));
|
|
1788
1831
|
log(pc.dim(' Lo compactado sigue buscable: ale search --archive "<texto>"\n'));
|
|
1789
1832
|
}
|
|
1790
|
-
program.command("clean").description("Limpieza segura: compacta prompts viejos sin reuso (texto \xEDntegro, fuera del \xEDndice), descarta ruido del arn\xE9s y purga cach\xE9s regenerables. Nunca toca lecciones, planes, mapas ni sesiones").option("--days <n>", "antig\xFCedad m\xEDnima de un prompt para compactarlo", "45").option("-y, --yes", "aplicar (sin esto solo muestra la vista previa)").option("--keep-noise", "compactar tambi\xE9n los prompts inyectados por el arn\xE9s en vez de descartarlos").option("--prompts-only", "solo compactar prompts (sin tocar cach\xE9s)").option("--backup <file>", "respaldo .tar.gz de la b\xF3veda antes de aplicar").option("--quiet", "sin salida (lo usa la limpieza autom\xE1tica)").action(runClean);
|
|
1833
|
+
program.command("clean").description("Limpieza segura: compacta prompts viejos sin reuso (texto \xEDntegro, fuera del \xEDndice), descarta ruido del arn\xE9s y purga cach\xE9s regenerables. Nunca toca lecciones, planes, mapas ni sesiones").option("--days <n>", "antig\xFCedad m\xEDnima de un prompt para compactarlo", "45").option("-y, --yes", "aplicar (sin esto solo muestra la vista previa)").option("--keep-noise", "compactar tambi\xE9n los prompts inyectados por el arn\xE9s en vez de descartarlos").option("--prompts-only", "solo compactar prompts (sin tocar cach\xE9s)").option("--dedupe", "aplicar tambi\xE9n los duplicados sugeridos (la m\xE1s vieja queda reemplazada por la m\xE1s nueva)").option("--backup <file>", "respaldo .tar.gz de la b\xF3veda antes de aplicar").option("--quiet", "sin salida (lo usa la limpieza autom\xE1tica)").action(runClean);
|
|
1791
1834
|
program.command("consolidate").description("(alias de `ale clean --prompts-only`) compacta prompts viejos sin reuso").option("--days <n>", "antig\xFCedad m\xEDnima en d\xEDas", "45").option("--dry", "solo mostrar qu\xE9 se har\xEDa").action((opts) => runClean({ days: opts.days, yes: !opts.dry, promptsOnly: true }));
|
|
1792
1835
|
program.command("agents").description("Lista los agentes de IA soportados y registra el MCP de Alexandria en los que elijas").argument("[ids]", `"all", "detected" o csv (${AGENTS.map((a) => a.id).join(",")})`).option("--project", "registrar a nivel proyecto (cwd) cuando el agente lo soporte").option("--no-hooks", "solo MCP, sin hooks de captura autom\xE1tica").action((ids, opts) => {
|
|
1793
1836
|
if (!ids) {
|
|
@@ -1980,6 +2023,13 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
|
|
|
1980
2023
|
console.log(` Inyecciones de contexto: ${s.injections}`);
|
|
1981
2024
|
console.log(` Aciertos de cach\xE9 de soluci\xF3n: ${s.solutionCacheHits} (${s.cacheHitTokens.toLocaleString()} tokens \u2014 el ahorro m\xE1s claro: soluciones no re-derivadas)`);
|
|
1982
2025
|
console.log(` Tokens inyectados (costo): ~${s.injectedTokens.toLocaleString()}`);
|
|
2026
|
+
if (s.dedupSavedTokens > 0) console.log(` No reinyectado (ya estaba en contexto): ~${s.dedupSavedTokens.toLocaleString()} tokens`);
|
|
2027
|
+
if (s.folds > 0) {
|
|
2028
|
+
const saved = Math.max(0, s.foldTokensOriginal - s.foldTokensServed);
|
|
2029
|
+
console.log(
|
|
2030
|
+
` Salida de comandos plegada: ${s.folds} corridas \xB7 ~${s.foldTokensServed.toLocaleString()} tokens entregados vs ~${s.foldTokensOriginal.toLocaleString()} originales \u2192 ${pc.green(`~${saved.toLocaleString()} ahorrados`)}`
|
|
2031
|
+
);
|
|
2032
|
+
}
|
|
1983
2033
|
if (s.docIngests + s.docReads > 0) {
|
|
1984
2034
|
const saved = Math.max(0, s.docTokensOriginal - s.docTokensServed);
|
|
1985
2035
|
const pct = s.docTokensOriginal ? Math.round(saved / s.docTokensOriginal * 100) : 0;
|
|
@@ -2168,11 +2218,55 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
|
|
|
2168
2218
|
program.command("serve-mcp").description("Correr el servidor MCP por stdio (lo usa Claude Code internamente)").action(async () => {
|
|
2169
2219
|
await import("./mcp/server.js");
|
|
2170
2220
|
});
|
|
2171
|
-
program.command("
|
|
2221
|
+
program.command("context").description("Medidor de contexto: qu\xE9 inyect\xF3 Alexandria por sesi\xF3n, cu\xE1nto cost\xF3 y cu\xE1nto ahorr\xF3 (plegado, no-reinyecci\xF3n)").option("--session <id>", "detalle de una sesi\xF3n (id o prefijo)").option("--last <n>", "sesiones a mostrar", "10").action((o) => {
|
|
2222
|
+
const vault = getVault();
|
|
2223
|
+
const all = readSessionUsage(vault);
|
|
2224
|
+
const list = o.session ? all.filter((u) => u.session.startsWith(o.session)) : all.slice(0, parseInt(o.last, 10) || 10);
|
|
2225
|
+
if (list.length === 0) return console.log(pc.dim("Sin datos por sesi\xF3n todav\xEDa (se registran desde 1.6)."));
|
|
2226
|
+
let saved = 0;
|
|
2227
|
+
console.log(pc.bold("\n\u{1F4CF} Contexto por sesi\xF3n\n"));
|
|
2228
|
+
for (const u of list) {
|
|
2229
|
+
const fold = Math.max(0, u.foldTokensOriginal - u.foldTokensServed);
|
|
2230
|
+
saved += fold + u.dedupSavedTokens;
|
|
2231
|
+
console.log(
|
|
2232
|
+
` ${pc.cyan(u.session.slice(0, 8))} ${pc.dim(u.last.slice(0, 16).replace("T", " "))} inyecciones ${u.injections} (~${u.injectedTokens.toLocaleString()} tok)` + (u.dedupSavedTokens ? ` \xB7 no reinyectado ~${u.dedupSavedTokens.toLocaleString()}` : "") + (u.folds ? ` \xB7 plegado ${u.folds}\xD7 ~${u.foldTokensOriginal.toLocaleString()}\u2192${u.foldTokensServed.toLocaleString()}` : "")
|
|
2233
|
+
);
|
|
2234
|
+
if (o.session) for (const [rel, n] of u.topNotes) console.log(pc.dim(` ${n}\xD7 ${rel}`));
|
|
2235
|
+
}
|
|
2236
|
+
console.log(pc.green(`
|
|
2237
|
+
Ahorro medido en estas sesiones: ~${saved.toLocaleString()} tokens (plegado + no reinyecci\xF3n)
|
|
2238
|
+
`));
|
|
2239
|
+
});
|
|
2240
|
+
program.command("supersede").description("Marca una nota como reemplazada por otra: deja de inyectarse y rankea abajo (no se borra)").argument("<vieja>", "t\xEDtulo o ruta de la nota desactualizada").argument("<nueva>", "t\xEDtulo o ruta de la nota que la reemplaza").action(async (oldRef, newRef) => {
|
|
2241
|
+
const { vault, idx } = await ensureReady();
|
|
2242
|
+
const find = (r) => Object.values(idx.meta.notes).find((n) => [n.title.toLowerCase(), n.rel.toLowerCase()].includes(r.toLowerCase().trim()));
|
|
2243
|
+
const a = find(oldRef);
|
|
2244
|
+
const b = find(newRef);
|
|
2245
|
+
if (!a || !b) return console.log(pc.yellow(`No encontr\xE9 ${!a ? `\xAB${oldRef}\xBB` : `\xAB${newRef}\xBB`}.`));
|
|
2246
|
+
supersedeNote(path7.join(vault.root, a.rel), b.title);
|
|
2247
|
+
await VaultIndex.load(vault).refresh();
|
|
2248
|
+
console.log(pc.green(`\u2713 \xAB${a.title}\xBB reemplazada por \xAB${b.title}\xBB \u2014 ya no se inyecta; sigue buscable.`));
|
|
2249
|
+
});
|
|
2250
|
+
var codeCmd = program.command("code").description("Mapa de c\xF3digo por s\xEDmbolos: firmas sin cuerpos y cuerpo de un s\xEDmbolo puntual");
|
|
2251
|
+
codeCmd.command("outline").description("Firmas de un archivo (con rangos de l\xEDnea) o resumen de una carpeta").argument("<ruta>", "archivo o carpeta").option("--max-tokens <n>", "tope para carpetas", "2500").action((p, o) => {
|
|
2252
|
+
const abs = path7.resolve(p);
|
|
2253
|
+
if (!fs7.existsSync(abs)) return console.log(pc.yellow(`No existe: ${abs}`));
|
|
2254
|
+
console.log(fs7.statSync(abs).isDirectory() ? outlineDir(abs, parseInt(o.maxTokens, 10) || 2500) : outlineFile(abs));
|
|
2255
|
+
});
|
|
2256
|
+
codeCmd.command("symbol").description("Cuerpo de un s\xEDmbolo (funci\xF3n, clase o Clase.metodo) con n\xFAmeros de l\xEDnea").argument("<archivo>").argument("<nombre>").action((f, name) => {
|
|
2257
|
+
const abs = path7.resolve(f);
|
|
2258
|
+
if (!fs7.existsSync(abs)) return console.log(pc.yellow(`No existe: ${abs}`));
|
|
2259
|
+
console.log(symbolSource(abs, name));
|
|
2260
|
+
});
|
|
2261
|
+
program.command("ingest").description("Convierte documentos (PDF, DOCX, XLSX, CSV, HTML, MD) a markdown por secciones y los indexa: el agente lee solo lo que necesita").argument("<paths...>", "archivos, carpetas o URLs de documentaci\xF3n").option("--force", "reconvertir aunque el archivo no haya cambiado").action(async (paths, opts) => {
|
|
2172
2262
|
const vault = getVault();
|
|
2173
2263
|
ensureVaultStructure(vault);
|
|
2174
2264
|
const files = [];
|
|
2175
2265
|
for (const p of paths) {
|
|
2266
|
+
if (isUrl(p)) {
|
|
2267
|
+
files.push(p.trim());
|
|
2268
|
+
continue;
|
|
2269
|
+
}
|
|
2176
2270
|
const abs = path7.resolve(p);
|
|
2177
2271
|
if (!fs7.existsSync(abs)) {
|
|
2178
2272
|
console.log(pc.yellow(`\u26A0 No existe: ${abs}`));
|
|
@@ -2227,15 +2321,64 @@ docsCmd.command("read").description("Lee secciones de un documento (por id o por
|
|
|
2227
2321
|
});
|
|
2228
2322
|
console.log("\n" + text + "\n");
|
|
2229
2323
|
});
|
|
2230
|
-
program.command("hook").description("Corre un hook (lo usan los plugins de Claude Code/Codex): session-start | prompt | stop | read").argument("<event>", "session-start | prompt | stop | read").option("--harness <id>", "claude | codex | gemini | cursor | opencode", "claude").action(async (event) => {
|
|
2324
|
+
program.command("hook").description("Corre un hook (lo usan los plugins de Claude Code/Codex): session-start | prompt | stop | read | bash").argument("<event>", "session-start | prompt | stop | read | bash").option("--harness <id>", "claude | codex | gemini | cursor | opencode", "claude").action(async (event) => {
|
|
2231
2325
|
const i = process.argv.indexOf("--harness");
|
|
2232
2326
|
if (i > -1 && process.argv[i + 1]) process.argv.push(`--harness=${process.argv[i + 1]}`);
|
|
2233
2327
|
if (event === "session-start") await import("./hooks/on-session-start.js");
|
|
2234
2328
|
else if (event === "prompt") await import("./hooks/on-prompt.js");
|
|
2235
2329
|
else if (event === "stop") await import("./hooks/on-stop.js");
|
|
2236
2330
|
else if (event === "read") await import("./hooks/on-read.js");
|
|
2331
|
+
else if (event === "bash") await import("./hooks/on-bash.js");
|
|
2237
2332
|
});
|
|
2238
|
-
|
|
2333
|
+
program.command("run").description("Ejecuta un comando y le entrega al agente su salida PLEGADA (errores, resumen, final); la completa queda en disco. Uso: ale run -- <comando>").addCommand(
|
|
2334
|
+
new Command("show").description("Muestra una corrida guardada (completa, por l\xEDneas o filtrada)").argument("<id>", 'id de la corrida, o "last"').option("--grep <regex>", "solo l\xEDneas que coinciden").option("--lines <a-b>", "rango de l\xEDneas").option("--max-tokens <n>", "presupuesto", "2000").action((id, o) => {
|
|
2335
|
+
console.log(showRun(id, { grep: o.grep, lines: o.lines, maxTokens: parseInt(o.maxTokens, 10) || 2e3 }));
|
|
2336
|
+
})
|
|
2337
|
+
).addCommand(
|
|
2338
|
+
new Command("list").description("\xDAltimas corridas guardadas").action(() => {
|
|
2339
|
+
const runs = listRuns(15);
|
|
2340
|
+
if (runs.length === 0) console.log(pc.dim("Sin corridas guardadas."));
|
|
2341
|
+
for (const r of runs) {
|
|
2342
|
+
console.log(` ${pc.cyan(r.id)} exit ${r.exitCode} ${(r.ms / 1e3).toFixed(1)}s ${Math.ceil(r.chars / 4).toLocaleString()} tok ${pc.dim(r.command.slice(0, 70))}`);
|
|
2343
|
+
}
|
|
2344
|
+
})
|
|
2345
|
+
);
|
|
2346
|
+
async function runDispatch(args) {
|
|
2347
|
+
const vault = getVault();
|
|
2348
|
+
const log = (originalChars, servedChars) => {
|
|
2349
|
+
if (vaultExists(vault)) logFold(vault, { originalChars, servedChars, session: process.env.ALEXANDRIA_SESSION });
|
|
2350
|
+
};
|
|
2351
|
+
if (args[0] === "--stdin") {
|
|
2352
|
+
const ci = args.indexOf("--command");
|
|
2353
|
+
const ei = args.indexOf("--exit");
|
|
2354
|
+
const command3 = ci > -1 ? args[ci + 1] ?? "" : "";
|
|
2355
|
+
const chunks = [];
|
|
2356
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
2357
|
+
const output = Buffer.concat(chunks).toString("utf8");
|
|
2358
|
+
if (!shouldFoldOutput(command3, output.length)) {
|
|
2359
|
+
process.stdout.write(output);
|
|
2360
|
+
return;
|
|
2361
|
+
}
|
|
2362
|
+
const { fold: fold2 } = saveRun({ command: command3, cwd: process.cwd(), output, exitCode: ei > -1 ? Number(args[ei + 1]) || 0 : 0, ms: 0 });
|
|
2363
|
+
if (fold2.folded) log(fold2.originalChars, fold2.text.length);
|
|
2364
|
+
process.stdout.write(fold2.text);
|
|
2365
|
+
return;
|
|
2366
|
+
}
|
|
2367
|
+
const rest = args[0] === "--" ? args.slice(1) : args;
|
|
2368
|
+
if (rest.length === 0) {
|
|
2369
|
+
console.log("Uso: ale run -- <comando> \xB7 ale run show <id|last> \xB7 ale run list");
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
const command2 = rest.length === 1 ? rest[0] : rest.map((a) => /[\s"'$`\\]/.test(a) ? JSON.stringify(a) : a).join(" ");
|
|
2373
|
+
const { meta, fold } = await runCommand(command2);
|
|
2374
|
+
if (fold.folded) log(fold.originalChars, fold.text.length);
|
|
2375
|
+
process.stdout.write(fold.text.endsWith("\n") ? fold.text : fold.text + "\n");
|
|
2376
|
+
process.exitCode = meta.exitCode;
|
|
2377
|
+
}
|
|
2378
|
+
var runArgs = process.argv.slice(3);
|
|
2379
|
+
if (process.argv[2] === "run" && !["show", "list", "--help", "-h"].includes(runArgs[0] ?? "--help")) {
|
|
2380
|
+
await runDispatch(runArgs);
|
|
2381
|
+
} else if (process.argv.length <= 2) {
|
|
2239
2382
|
await showBanner();
|
|
2240
2383
|
program.outputHelp();
|
|
2241
2384
|
} else {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
runHook
|
|
4
|
+
} from "../chunk-WVZQGLRI.js";
|
|
5
|
+
import {
|
|
6
|
+
saveRun,
|
|
7
|
+
shouldFoldOutput
|
|
8
|
+
} from "../chunk-OGVWOBYH.js";
|
|
9
|
+
import {
|
|
10
|
+
logFold
|
|
11
|
+
} from "../chunk-X4V6SYYA.js";
|
|
12
|
+
import {
|
|
13
|
+
resolveVault,
|
|
14
|
+
toggleEnabled,
|
|
15
|
+
vaultExists
|
|
16
|
+
} from "../chunk-YICWI3U3.js";
|
|
17
|
+
import "../chunk-EDYBSJSS.js";
|
|
18
|
+
|
|
19
|
+
// src/hooks/on-bash.ts
|
|
20
|
+
runHook(3e3, async (input) => {
|
|
21
|
+
if (!toggleEnabled("run.fold")) return;
|
|
22
|
+
if (input.toolName && input.toolName !== "Bash") return;
|
|
23
|
+
const res = input.toolResponse;
|
|
24
|
+
if (!input.command || !res || res.interrupted || res.isImage) return;
|
|
25
|
+
const stdout = typeof res.stdout === "string" ? res.stdout : "";
|
|
26
|
+
const stderr = typeof res.stderr === "string" ? res.stderr : "";
|
|
27
|
+
const output = stderr ? `${stdout}
|
|
28
|
+
${stderr}` : stdout;
|
|
29
|
+
if (!shouldFoldOutput(input.command, output.length)) return;
|
|
30
|
+
const { fold } = saveRun({ command: input.command, cwd: input.cwd ?? process.cwd(), output, exitCode: 0, ms: input.durationMs ?? 0 });
|
|
31
|
+
if (!fold.folded) return;
|
|
32
|
+
process.stdout.write(
|
|
33
|
+
JSON.stringify({
|
|
34
|
+
hookSpecificOutput: {
|
|
35
|
+
hookEventName: "PostToolUse",
|
|
36
|
+
updatedToolOutput: { stdout: fold.text, stderr: "", interrupted: false, isImage: false }
|
|
37
|
+
}
|
|
38
|
+
})
|
|
39
|
+
);
|
|
40
|
+
try {
|
|
41
|
+
const vault = resolveVault({ cwd: input.cwd });
|
|
42
|
+
if (vaultExists(vault)) logFold(vault, { originalChars: fold.originalChars, servedChars: fold.text.length, session: input.session_id });
|
|
43
|
+
} catch {
|
|
44
|
+
}
|
|
45
|
+
});
|
package/dist/hooks/on-prompt.js
CHANGED
|
@@ -1,26 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
injectedInSession,
|
|
4
|
+
rememberInjected
|
|
5
|
+
} from "../chunk-ADA25MTF.js";
|
|
2
6
|
import {
|
|
3
7
|
emitContext,
|
|
4
8
|
projectName,
|
|
5
9
|
runHook,
|
|
6
10
|
truncate
|
|
7
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-WVZQGLRI.js";
|
|
8
12
|
import {
|
|
9
13
|
hybridSearch
|
|
10
|
-
} from "../chunk-
|
|
14
|
+
} from "../chunk-47S5I3D3.js";
|
|
15
|
+
import {
|
|
16
|
+
createNote,
|
|
17
|
+
touchNote
|
|
18
|
+
} from "../chunk-44QPE5IM.js";
|
|
11
19
|
import {
|
|
12
20
|
logInjection
|
|
13
|
-
} from "../chunk-
|
|
21
|
+
} from "../chunk-X4V6SYYA.js";
|
|
14
22
|
import {
|
|
15
23
|
isHarnessInjected,
|
|
16
24
|
resolveVault,
|
|
17
25
|
toggleEnabled,
|
|
18
26
|
vaultExists
|
|
19
|
-
} from "../chunk-
|
|
20
|
-
import {
|
|
21
|
-
createNote,
|
|
22
|
-
touchNote
|
|
23
|
-
} from "../chunk-BV2KJV5W.js";
|
|
27
|
+
} from "../chunk-YICWI3U3.js";
|
|
24
28
|
import "../chunk-EDYBSJSS.js";
|
|
25
29
|
|
|
26
30
|
// src/hooks/on-prompt.ts
|
|
@@ -41,6 +45,7 @@ runHook(5e3, async (input) => {
|
|
|
41
45
|
const rawResults = await hybridSearch(vault, prompt, 5, { expand: true, refresh: false });
|
|
42
46
|
const STALE_DAYS = 60;
|
|
43
47
|
const results = rawResults.filter((r) => {
|
|
48
|
+
if (r.note.status === "superseded") return false;
|
|
44
49
|
if (r.note.type !== "prompt" && r.note.type !== "session") return true;
|
|
45
50
|
if ((r.note.hits ?? 1) > 1) return true;
|
|
46
51
|
const age = r.note.created ? (Date.now() - Date.parse(r.note.created)) / 864e5 : 0;
|
|
@@ -69,14 +74,24 @@ runHook(5e3, async (input) => {
|
|
|
69
74
|
${truncate(cached.excerpts.join("\n"), 2e3)}`
|
|
70
75
|
);
|
|
71
76
|
}
|
|
77
|
+
const session = input.session_id;
|
|
78
|
+
const dedupe = Boolean(session) && toggleEnabled("context.dedupe");
|
|
79
|
+
const already = dedupe ? injectedInSession(vault.cache, session) : /* @__PURE__ */ new Set();
|
|
80
|
+
let skipped = 0;
|
|
72
81
|
if (promptSearchOn) {
|
|
73
82
|
for (const r of relevant) {
|
|
74
83
|
if (r === cached) continue;
|
|
84
|
+
if (already.has(r.note.rel)) {
|
|
85
|
+
lines.push(`\u21BA ya en contexto: \xAB${r.note.title}\xBB`);
|
|
86
|
+
skipped += Math.min(900, r.excerpts.join("\n").length);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
75
89
|
lines.push(`\u2022 \xAB${r.note.title}\xBB (${r.note.rel}):
|
|
76
90
|
${truncate(r.excerpts.join("\n"), 900)}`);
|
|
77
91
|
if (lines.join("\n\n").length > MAX_INJECT_CHARS) break;
|
|
78
92
|
}
|
|
79
93
|
}
|
|
94
|
+
if (lines.length > 0 && lines.every((l) => l.startsWith("\u21BA"))) lines.length = 0;
|
|
80
95
|
if (lines.length > 0) {
|
|
81
96
|
injected = `<alexandria-contexto>
|
|
82
97
|
Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o re-explorar):
|
|
@@ -84,11 +99,18 @@ Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o r
|
|
|
84
99
|
` + truncate(lines.join("\n\n"), MAX_INJECT_CHARS) + `
|
|
85
100
|
</alexandria-contexto>`;
|
|
86
101
|
const written = emitContext("prompt", injected);
|
|
87
|
-
if (written > 0)
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
102
|
+
if (written > 0) {
|
|
103
|
+
const rels = relevant.filter((r) => !already.has(r.note.rel)).map((r) => r.note.rel);
|
|
104
|
+
logInjection(vault, {
|
|
105
|
+
kind: cached ? "solution-cache" : "inject",
|
|
106
|
+
injectedChars: injected.length,
|
|
107
|
+
promptChars: prompt.length,
|
|
108
|
+
session,
|
|
109
|
+
rels,
|
|
110
|
+
dedupSkippedChars: skipped || void 0
|
|
111
|
+
});
|
|
112
|
+
if (dedupe) rememberInjected(vault.cache, session, rels);
|
|
113
|
+
}
|
|
92
114
|
for (const r of relevant) {
|
|
93
115
|
if (r.note.type === "lesson" || r.note.type === "solution") {
|
|
94
116
|
try {
|
package/dist/hooks/on-read.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
runHook
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-WVZQGLRI.js";
|
|
5
5
|
import {
|
|
6
6
|
PDF_TOKENS_PER_PAGE,
|
|
7
7
|
formatOf
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-I5H4BN3F.js";
|
|
9
9
|
import {
|
|
10
10
|
resolveVault,
|
|
11
11
|
toggleEnabled,
|
|
12
12
|
vaultExists
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-YICWI3U3.js";
|
|
14
14
|
|
|
15
15
|
// src/hooks/on-read.ts
|
|
16
16
|
import fs from "fs";
|
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
forgetInjected,
|
|
4
|
+
loadCapsule
|
|
5
|
+
} from "../chunk-ADA25MTF.js";
|
|
2
6
|
import {
|
|
3
7
|
emitContext,
|
|
4
8
|
projectName,
|
|
5
9
|
runHook,
|
|
6
10
|
truncate
|
|
7
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-WVZQGLRI.js";
|
|
12
|
+
import {
|
|
13
|
+
VaultIndex
|
|
14
|
+
} from "../chunk-44QPE5IM.js";
|
|
8
15
|
import {
|
|
9
16
|
logInjection
|
|
10
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-X4V6SYYA.js";
|
|
11
18
|
import {
|
|
12
19
|
protocolEnabled,
|
|
13
20
|
resolveVault,
|
|
14
21
|
toggleEnabled,
|
|
15
22
|
vaultExists
|
|
16
|
-
} from "../chunk-
|
|
17
|
-
import {
|
|
18
|
-
VaultIndex
|
|
19
|
-
} from "../chunk-BV2KJV5W.js";
|
|
23
|
+
} from "../chunk-YICWI3U3.js";
|
|
20
24
|
import "../chunk-EDYBSJSS.js";
|
|
21
25
|
|
|
22
26
|
// src/hooks/on-session-start.ts
|
|
@@ -69,16 +73,21 @@ ${lines.join("\n")}`);
|
|
|
69
73
|
`B\xF3veda joven (${distilled} notas destiladas): al descubrir decisiones, m\xF3dulos o vocabulario del dominio, gu\xE1rdalos compactos con vault_save \u2014 tokens gratis en sesiones futuras.`
|
|
70
74
|
);
|
|
71
75
|
}
|
|
72
|
-
const titles = toggleEnabled("digest.titleIndex") ? notes.filter((n) => n.type !== "prompt").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1)).slice(0, 25).map((n) => n.title) : [];
|
|
76
|
+
const titles = toggleEnabled("digest.titleIndex") ? notes.filter((n) => n.type !== "prompt" && n.status !== "superseded").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1)).slice(0, 25).map((n) => n.title) : [];
|
|
73
77
|
if (titles.length > 0) {
|
|
74
78
|
parts.push(`## La b\xF3veda ya tiene conocimiento sobre
|
|
75
79
|
${titles.join(" \xB7 ")}`);
|
|
76
80
|
}
|
|
77
81
|
if (parts.length === 0) return;
|
|
78
|
-
|
|
82
|
+
let capsule = "";
|
|
83
|
+
if (input.session_id && (input.source === "compact" || input.source === "resume")) {
|
|
84
|
+
capsule = loadCapsule(vault.cache, input.session_id) ?? "";
|
|
85
|
+
if (input.source === "compact") forgetInjected(vault.cache, input.session_id);
|
|
86
|
+
}
|
|
87
|
+
const digest = (capsule ? capsule + "\n\n" : "") + `<alexandria-digest>
|
|
79
88
|
B\xF3veda de conocimiento local activa (${notes.length} notas). ANTES de explorar c\xF3digo o re-derivar contexto, usa la herramienta MCP vault_search \u2014 ahorra tokens. Cuando descubras arquitectura o decisiones nuevas, gu\xE1rdalas con vault_save (title: "Mapa - ${proj}").
|
|
80
89
|
|
|
81
90
|
` + truncate(parts.join("\n\n"), MAX_CHARS) + `
|
|
82
91
|
</alexandria-digest>`;
|
|
83
|
-
if (emitContext("session", digest) > 0) logInjection(vault, { kind: "session-start", injectedChars: digest.length });
|
|
92
|
+
if (emitContext("session", digest) > 0) logInjection(vault, { kind: "session-start", injectedChars: digest.length, session: input.session_id });
|
|
84
93
|
}, "session");
|
package/dist/hooks/on-stop.js
CHANGED
|
@@ -1,25 +1,31 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
buildCapsule,
|
|
4
|
+
extractSession,
|
|
5
|
+
forgetInjected,
|
|
6
|
+
saveCapsule
|
|
7
|
+
} from "../chunk-ADA25MTF.js";
|
|
2
8
|
import {
|
|
3
9
|
projectName,
|
|
4
10
|
runHook,
|
|
5
11
|
truncate
|
|
6
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-WVZQGLRI.js";
|
|
7
13
|
import {
|
|
8
14
|
autoCleanDue,
|
|
9
15
|
markCleaned
|
|
10
|
-
} from "../chunk-
|
|
11
|
-
import
|
|
16
|
+
} from "../chunk-WSVNMMNN.js";
|
|
17
|
+
import {
|
|
18
|
+
VaultIndex,
|
|
19
|
+
appendToNote
|
|
20
|
+
} from "../chunk-44QPE5IM.js";
|
|
21
|
+
import "../chunk-X4V6SYYA.js";
|
|
12
22
|
import {
|
|
13
23
|
ensureVaultStructure,
|
|
14
24
|
lastExchange,
|
|
15
25
|
resolveVault,
|
|
16
26
|
toggleEnabled,
|
|
17
27
|
vaultExists
|
|
18
|
-
} from "../chunk-
|
|
19
|
-
import {
|
|
20
|
-
VaultIndex,
|
|
21
|
-
appendToNote
|
|
22
|
-
} from "../chunk-BV2KJV5W.js";
|
|
28
|
+
} from "../chunk-YICWI3U3.js";
|
|
23
29
|
import "../chunk-EDYBSJSS.js";
|
|
24
30
|
|
|
25
31
|
// src/hooks/on-stop.ts
|
|
@@ -32,6 +38,18 @@ runHook(25e3, async (input) => {
|
|
|
32
38
|
if (!vaultExists(vault)) return;
|
|
33
39
|
let lastUser = input.prompt?.trim() ?? "";
|
|
34
40
|
let lastAssistant = input.answer?.trim() ?? "";
|
|
41
|
+
if (input.compact && input.session_id) {
|
|
42
|
+
forgetInjected(vault.cache, input.session_id);
|
|
43
|
+
if (input.transcript_path && fs.existsSync(input.transcript_path)) {
|
|
44
|
+
try {
|
|
45
|
+
const all = fs.readFileSync(input.transcript_path, "utf8").split("\n").filter(Boolean);
|
|
46
|
+
const proj2 = projectName(input.cwd);
|
|
47
|
+
const openPlans = VaultIndex.load(vault).notesByTag("plan").filter((n) => n.status === "active" && n.tags.some((t) => t.toLowerCase() === proj2.toLowerCase())).map((n) => n.title);
|
|
48
|
+
saveCapsule(vault.cache, input.session_id, buildCapsule(extractSession(all), { cwd: input.cwd, openPlans }));
|
|
49
|
+
} catch {
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
35
53
|
if (!lastAssistant && input.transcript_path && fs.existsSync(input.transcript_path)) {
|
|
36
54
|
const lines = fs.readFileSync(input.transcript_path, "utf8").split("\n").filter(Boolean);
|
|
37
55
|
const ex = lastExchange(lines.slice(-200));
|