@ureck/alexandria 1.0.0 → 1.1.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 CHANGED
@@ -63,7 +63,7 @@ Verify:
63
63
 
64
64
  ```bash
65
65
  $ ale --version
66
- 1.0.0
66
+ 1.1.0
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -132,6 +132,18 @@ ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
132
132
 
133
133
  (Automatic capture via hooks already does this in every Claude Code session — `add` is for extra knowledge.)
134
134
 
135
+ ### Control what spends tokens (`ale toggles`)
136
+
137
+ Every token-spending behavior is opt-out — before or after installing (the config is global, independent of the vault):
138
+
139
+ ```bash
140
+ $ ale toggles # interactive menu: each toggle with its real approximate cost
141
+ ale init --off architect.enrich,digest.map # disable from the start
142
+ ale config set tokens.solutionCache false # scriptable, one by one
143
+ ```
144
+
145
+ The six toggles: Protocol manifest (~6% of the session digest), Architect enrichment in `plan_create` (~+90 tokens/plan), solution cache (up to ~500 tokens/prompt), per-prompt semantic search (the **main saving mechanism** — up to ~1500 tokens/prompt, disabling it defeats the point), project map in the digest (up to ~1000 tokens), title index (~200 tokens). All on by default; nothing changes unless you touch them.
146
+
135
147
  ### Deep project context (`ale scan`)
136
148
 
137
149
  `ale init --project` already runs it; re-run anytime the project changes:
@@ -277,7 +289,8 @@ AI agent session
277
289
  | Command | What it does |
278
290
  |---|---|
279
291
  | `ale init [--project] [--path <dir>] [--agents <ids>] [--auto\|--manual] [--no-protocol] [--portable]` | Installs everything: vault, hooks, MCP, .gitignore, project scan, CLAUDE.md. `--portable` writes an npx-based MCP command safe to commit for teams |
280
- | `ale scan` | Deep project context: API routes, env var **names**, data schema (file parse), conventions → compact notes. Read-only; ensures .gitignore |
292
+ | `ale scan` | Deep project context: API routes, env var **names**, data schema (file parse), conventions → compact notes (adaptive cap ≤200 entries, fair sampling in monorepos). Read-only; ensures .gitignore |
293
+ | `ale toggles` | Interactive menu to enable/disable every token-spending behavior, each with its real approximate cost. Works before or after install; scriptable via `ale init --off <keys>` |
281
294
  | `ale agents [ids] [--project]` | List agents / register the MCP server |
282
295
  | `ale search <query> [-k n] [--expand]` | Hybrid search; `--expand` pulls graph neighbors. With the Protocol on, appends the **chain** (plan + verification + lesson) connected to the top hit |
283
296
  | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-D5ROL42O.js";
4
+ } from "./chunk-AXUEYSNZ.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -35,6 +35,9 @@ var VaultIndex = class _VaultIndex {
35
35
  meta;
36
36
  /** filas de embeddings alineadas 1:1 con meta.chunks; null = índice sin vectores */
37
37
  emb = null;
38
+ /** diccionario lazy tag/type → rels; la bóveda nunca borra, así que los
39
+ * escaneos lineales sobre TODAS las notas crecen para siempre — esto los evita */
40
+ _tagIndex = null;
38
41
  get metaPath() {
39
42
  return path.join(this.vault.cache, "meta.json");
40
43
  }
@@ -112,6 +115,7 @@ var VaultIndex = class _VaultIndex {
112
115
  if (changed.length === 0 && removed.length === 0) {
113
116
  return { changed: 0, removed: 0, embedded: this.emb !== null };
114
117
  }
118
+ this._tagIndex = null;
115
119
  const keep = new Set(
116
120
  this.meta.chunks.map((_, i) => i).filter((i) => {
117
121
  const rel = this.meta.chunks[i].note;
@@ -192,7 +196,7 @@ ${c.text}`),
192
196
  this.rebuildLinks();
193
197
  this.save();
194
198
  try {
195
- const { writeStaticGraph } = await import("./viewer-73ZWPIDC.js");
199
+ const { writeStaticGraph } = await import("./viewer-2YMJBQRH.js");
196
200
  writeStaticGraph(this);
197
201
  } catch {
198
202
  }
@@ -249,6 +253,24 @@ ${c.text}`),
249
253
  }
250
254
  this.meta.links = links;
251
255
  }
256
+ /**
257
+ * Notas por tag o por tipo (`notesByTag('plan')`, `notesByTag('oauth')`) —
258
+ * lookup O(1) contra el diccionario en vez de filtrar todas las notas.
259
+ */
260
+ notesByTag(key) {
261
+ if (!this._tagIndex) {
262
+ const m = /* @__PURE__ */ new Map();
263
+ for (const n of Object.values(this.meta.notes)) {
264
+ for (const k of [n.type, ...n.tags]) {
265
+ const arr = m.get(k);
266
+ if (arr) arr.push(n.rel);
267
+ else m.set(k, [n.rel]);
268
+ }
269
+ }
270
+ this._tagIndex = m;
271
+ }
272
+ return (this._tagIndex.get(key) ?? []).map((rel) => this.meta.notes[rel]).filter(Boolean);
273
+ }
252
274
  /** Vecinos directos de una nota en el grafo (sin releer archivos). */
253
275
  neighbors(rel) {
254
276
  const out = [];
@@ -1,18 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  hybridSearch
4
- } from "./chunk-RZI7TYAG.js";
4
+ } from "./chunk-AHBSZGSC.js";
5
5
 
6
6
  // src/core/planning.ts
7
+ var MAX_ITEMS = 2;
8
+ var EXCERPT_CHARS = 150;
7
9
  async function planContext(vault, query) {
8
10
  const out = { similarPlans: [], lessons: [] };
9
11
  try {
10
12
  const results = await hybridSearch(vault, query, 8);
11
13
  for (const r of results) {
12
- const excerpt = (r.excerpts[0] ?? "").replace(/\n+/g, " ").slice(0, 300);
13
- if (r.note.type === "plan" && out.similarPlans.length < 3) {
14
- out.similarPlans.push(`\xAB${r.note.title}\xBB (${r.note.status ?? "sin status"}): ${excerpt}`);
15
- } else if ((r.note.type === "lesson" || r.note.type === "solution") && out.lessons.length < 3) {
14
+ const excerpt = (r.excerpts[0] ?? "").replace(/\n+/g, " ").slice(0, EXCERPT_CHARS);
15
+ if (r.note.type === "plan" && out.similarPlans.length < MAX_ITEMS) {
16
+ out.similarPlans.push(`\xAB${r.note.title}\xBB (${r.note.status ?? "?"}): ${excerpt}`);
17
+ } else if ((r.note.type === "lesson" || r.note.type === "solution") && out.lessons.length < MAX_ITEMS) {
16
18
  out.lessons.push(`\xAB${r.note.title}\xBB: ${excerpt}`);
17
19
  }
18
20
  }
@@ -21,39 +23,23 @@ async function planContext(vault, query) {
21
23
  return out;
22
24
  }
23
25
  var FAT_TASK_CHARS = 140;
26
+ var MAX_HINTS = 3;
24
27
  function planQualityHints(dod, tasks, design) {
25
28
  const hints = [];
26
- if (dod.length < 2) {
27
- hints.push("DoD con menos de 2 criterios \u2014 agrega criterios verificables por comando (tests, build, curl).");
28
- }
29
- const vague = dod.filter((d) => /funcione bien|quede bonito|esté listo|sea mejor/i.test(d));
30
- if (vague.length) {
31
- hints.push(`Criterios no verificables (${vague.length}): reescr\xEDbelos como algo que un comando pueda confirmar.`);
32
- }
33
29
  const fat = tasks.filter((t) => t.length > FAT_TASK_CHARS);
34
- if (fat.length) {
35
- hints.push(`${fat.length} tarea(s) muy grandes (>${FAT_TASK_CHARS} chars) \u2014 div\xEDdelas: una tarea = un task_verify.`);
36
- }
37
- if (tasks.length > 5 && !design?.trim()) {
38
- hints.push("Plan grande sin secci\xF3n de dise\xF1o \u2014 considera pasar `design` (stack/decisiones de arquitectura) para fijar el rumbo antes de ejecutar.");
39
- }
40
- return hints;
30
+ if (fat.length) hints.push(`${fat.length} tarea(s) gorda(s) (>${FAT_TASK_CHARS}c) \u2014 1 tarea = 1 task_verify`);
31
+ if (dod.length < 2) hints.push("DoD <2 criterios verificables");
32
+ const vague = dod.filter((d) => /funcione bien|quede bonito|esté listo|sea mejor/i.test(d));
33
+ if (vague.length) hints.push(`${vague.length} criterio(s) no verificable(s) por comando`);
34
+ if (tasks.length > 5 && !design?.trim()) hints.push("sin `design` (plan grande)");
35
+ return hints.slice(0, MAX_HINTS);
41
36
  }
42
37
  function architectBlock(ctx, hints) {
43
38
  const parts = [];
44
- if (ctx.similarPlans.length) {
45
- parts.push(`PLANES SIMILARES PREVIOS (resume, no dupliques):
46
- ${ctx.similarPlans.map((p) => `- ${p}`).join("\n")}`);
47
- }
48
- if (ctx.lessons.length) {
49
- parts.push(`LECCIONES RELEVANTES (consid\xE9ralas al planear):
50
- ${ctx.lessons.map((l) => `- ${l}`).join("\n")}`);
51
- }
52
- if (hints.length) {
53
- parts.push(`SUGERENCIAS DE CALIDAD (el plan qued\xF3 guardado; mej\xF3ralo si aplican):
54
- ${hints.map((h) => `- ${h}`).join("\n")}`);
55
- }
56
- return parts.join("\n\n");
39
+ for (const p of ctx.similarPlans) parts.push(`Similar: ${p}`);
40
+ for (const l of ctx.lessons) parts.push(`Lecci\xF3n: ${l}`);
41
+ if (hints.length) parts.push(`Hints: ${hints.join(" \xB7 ")}`);
42
+ return parts.join("\n");
57
43
  }
58
44
 
59
45
  // src/core/register.ts
@@ -95,6 +95,48 @@ function protocolEnabled() {
95
95
  const v = getConfigKey("protocol");
96
96
  return v !== false && v !== "false";
97
97
  }
98
+ function toggleEnabled(key) {
99
+ const v = getConfigKey(key);
100
+ return v !== false && v !== "false";
101
+ }
102
+ var TOKEN_TOGGLES = [
103
+ {
104
+ key: "protocol",
105
+ label: "Protocolo Alexandria",
106
+ desc: "Ciclo plan \u2192 verificar \u2192 aprender (manifiesto en el digest + tools MCP)",
107
+ impact: "cuesta ~6% del digest (~120 tokens); su ahorro es diferido: lecciones evitan re-debug"
108
+ },
109
+ {
110
+ key: "architect.enrich",
111
+ label: "Arquitecto en plan_create",
112
+ desc: "Planes similares + lecciones + hints de calidad en cada plan nuevo",
113
+ impact: "encarece cada plan_create ~2-3\xD7 (~+90-110 tokens); apuesta a no duplicar trabajo"
114
+ },
115
+ {
116
+ key: "tokens.solutionCache",
117
+ label: "Cach\xE9 de soluciones",
118
+ desc: "Si un prompt casi id\xE9ntico ya se resolvi\xF3, inyecta esa soluci\xF3n",
119
+ impact: "cuesta hasta ~33% del presupuesto por prompt (~500 tokens); evita re-derivar completo"
120
+ },
121
+ {
122
+ key: "tokens.promptSearch",
123
+ label: "B\xFAsqueda sem\xE1ntica por prompt",
124
+ desc: "Inyecta fragmentos relevantes de la b\xF3veda en cada prompt \u2014 el mecanismo PRINCIPAL de ahorro",
125
+ impact: "cuesta hasta ~1500 tokens/prompt; apagarlo apaga la raz\xF3n de ser de Alexandria"
126
+ },
127
+ {
128
+ key: "digest.map",
129
+ label: "Mapa del proyecto al iniciar sesi\xF3n",
130
+ desc: "Inyecta el mapa (stack, estructura, decisiones) en el digest de SessionStart",
131
+ impact: "cuesta hasta ~50% del digest (~1000 tokens); evita re-explorar el proyecto"
132
+ },
133
+ {
134
+ key: "digest.titleIndex",
135
+ label: "\xCDndice de t\xEDtulos en el digest",
136
+ desc: "Lista hasta 25 t\xEDtulos de lo que la b\xF3veda ya sabe",
137
+ impact: "cuesta ~10% del digest (~200 tokens); orienta al agente sobre qu\xE9 buscar"
138
+ }
139
+ ];
98
140
  function writeProjectConfig(projectDir, vaultPath) {
99
141
  const file = path.join(projectDir, ".vault.json");
100
142
  const rel = path.relative(projectDir, vaultPath) || ".";
@@ -113,5 +155,7 @@ export {
113
155
  getConfigKey,
114
156
  setConfigKey,
115
157
  protocolEnabled,
158
+ toggleEnabled,
159
+ TOKEN_TOGGLES,
116
160
  writeProjectConfig
117
161
  };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-D5ROL42O.js";
4
+ } from "./chunk-AXUEYSNZ.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";
package/dist/cli.js CHANGED
@@ -16,12 +16,13 @@ import {
16
16
  registerMcpGlobal,
17
17
  registerMcpProject,
18
18
  unregisterHooks
19
- } from "./chunk-DHXL36RG.js";
19
+ } from "./chunk-T5VNBQEC.js";
20
20
  import {
21
21
  hybridSearch,
22
22
  protocolChain
23
- } from "./chunk-RZI7TYAG.js";
23
+ } from "./chunk-AHBSZGSC.js";
24
24
  import {
25
+ TOKEN_TOGGLES,
25
26
  defaultVaultPath,
26
27
  ensureVaultStructure,
27
28
  getConfigKey,
@@ -29,16 +30,17 @@ import {
29
30
  protocolEnabled,
30
31
  resolveVault,
31
32
  setConfigKey,
33
+ toggleEnabled,
32
34
  vaultExists,
33
35
  writeGlobalConfig,
34
36
  writeProjectConfig
35
- } from "./chunk-DYCARGQR.js";
37
+ } from "./chunk-TFQ7WSIB.js";
36
38
  import {
37
39
  serveGraph
38
- } from "./chunk-DCKYTO4O.js";
40
+ } from "./chunk-XY7U4CAQ.js";
39
41
  import {
40
42
  VaultIndex
41
- } from "./chunk-D5ROL42O.js";
43
+ } from "./chunk-AXUEYSNZ.js";
42
44
  import {
43
45
  createNote,
44
46
  slugify,
@@ -659,38 +661,84 @@ var SKIP_DIRS2 = /* @__PURE__ */ new Set([
659
661
  "vendor"
660
662
  ]);
661
663
  var SOURCE_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
662
- var MAX_FILES = 400;
664
+ var MAX_FILES = 800;
663
665
  var MAX_FILE_BYTES = 64 * 1024;
664
- var MAX_ENTRIES = 80;
666
+ var MAX_DEPTH = 7;
667
+ var BASE_ENTRIES = 80;
668
+ var HARD_ENTRIES = 200;
669
+ function entryCap(rawCount) {
670
+ const cfg = getConfigKey("scan.maxEntries");
671
+ const n = typeof cfg === "number" ? cfg : typeof cfg === "string" ? parseInt(cfg, 10) : NaN;
672
+ if (Number.isFinite(n) && n > 0) return n;
673
+ return Math.min(Math.max(rawCount, BASE_ENTRIES), HARD_ENTRIES);
674
+ }
675
+ function capLines(lines, cap) {
676
+ if (lines.length <= cap) return lines;
677
+ return [
678
+ ...lines.slice(0, cap),
679
+ `\u2026 +${lines.length - cap} m\xE1s (trunca a ${cap}; sube con: ale config set scan.maxEntries <n>)`
680
+ ];
681
+ }
682
+ var TRAVERSE_SAFETY = 2e4;
665
683
  function collectSourceFiles(projectDir) {
666
- const out = [];
667
- const walk = (dir, depth) => {
668
- if (depth > 7 || out.length >= MAX_FILES) return;
669
- let entries = [];
670
- try {
671
- entries = fs4.readdirSync(dir, { withFileTypes: true });
672
- } catch {
673
- return;
684
+ const candidates = [];
685
+ let level = [projectDir];
686
+ for (let depth = 0; depth <= MAX_DEPTH && level.length > 0 && candidates.length < TRAVERSE_SAFETY; depth++) {
687
+ const next = [];
688
+ for (const dir of level) {
689
+ let entries = [];
690
+ try {
691
+ entries = fs4.readdirSync(dir, { withFileTypes: true });
692
+ } catch {
693
+ continue;
694
+ }
695
+ for (const e of entries) {
696
+ if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
697
+ const full = path4.join(dir, e.name);
698
+ if (e.isDirectory()) next.push(full);
699
+ else if (e.isFile() && SOURCE_EXT.has(path4.extname(e.name))) {
700
+ candidates.push(full);
701
+ if (candidates.length >= TRAVERSE_SAFETY) break;
702
+ }
703
+ }
704
+ if (candidates.length >= TRAVERSE_SAFETY) break;
674
705
  }
675
- for (const e of entries) {
676
- if (out.length >= MAX_FILES) return;
677
- if (e.name.startsWith(".") || SKIP_DIRS2.has(e.name)) continue;
678
- const full = path4.join(dir, e.name);
679
- if (e.isDirectory()) {
680
- walk(full, depth + 1);
681
- } else if (e.isFile() && SOURCE_EXT.has(path4.extname(e.name))) {
682
- try {
683
- if (fs4.statSync(full).size > MAX_FILE_BYTES) continue;
684
- out.push({
685
- rel: path4.relative(projectDir, full).split(path4.sep).join("/"),
686
- content: fs4.readFileSync(full, "utf8")
687
- });
688
- } catch {
706
+ level = next;
707
+ }
708
+ let chosen = candidates;
709
+ if (candidates.length > MAX_FILES) {
710
+ const groups = /* @__PURE__ */ new Map();
711
+ for (const c of candidates) {
712
+ const key = path4.relative(projectDir, c).split(path4.sep)[0];
713
+ const g = groups.get(key);
714
+ if (g) g.push(c);
715
+ else groups.set(key, [c]);
716
+ }
717
+ const lists = [...groups.values()];
718
+ chosen = [];
719
+ for (let i = 0; chosen.length < MAX_FILES; i++) {
720
+ let any = false;
721
+ for (const list of lists) {
722
+ if (i < list.length) {
723
+ chosen.push(list[i]);
724
+ any = true;
725
+ if (chosen.length >= MAX_FILES) break;
689
726
  }
690
727
  }
728
+ if (!any) break;
691
729
  }
692
- };
693
- walk(projectDir, 0);
730
+ }
731
+ const out = [];
732
+ for (const full of chosen) {
733
+ try {
734
+ if (fs4.statSync(full).size > MAX_FILE_BYTES) continue;
735
+ out.push({
736
+ rel: path4.relative(projectDir, full).split(path4.sep).join("/"),
737
+ content: fs4.readFileSync(full, "utf8")
738
+ });
739
+ } catch {
740
+ }
741
+ }
694
742
  return out;
695
743
  }
696
744
  var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
@@ -700,10 +748,11 @@ function appRoutePath(rel) {
700
748
  const segs = m[1].split("/").filter((s) => s && !/^\(.*\)$/.test(s));
701
749
  return "/" + segs.join("/").replace(/\/$/, "");
702
750
  }
751
+ var RAW_SAFETY = 1e3;
703
752
  function scanApi(files) {
704
753
  const lines = [];
705
754
  for (const f of files) {
706
- if (lines.length >= MAX_ENTRIES) break;
755
+ if (lines.length >= RAW_SAFETY) break;
707
756
  if (/(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel)) {
708
757
  const methods = HTTP_METHODS.filter(
709
758
  (m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
@@ -724,10 +773,10 @@ function scanApi(files) {
724
773
  const expressHits = [...f.content.matchAll(/\b(?:app|router|api)\.(get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/g)];
725
774
  for (const h of expressHits.slice(0, 12)) {
726
775
  lines.push(`- ${h[1].toUpperCase()} ${h[2]} \u2014 ${f.rel}`);
727
- if (lines.length >= MAX_ENTRIES) break;
776
+ if (lines.length >= RAW_SAFETY) break;
728
777
  }
729
778
  }
730
- return lines.slice(0, MAX_ENTRIES);
779
+ return lines;
731
780
  }
732
781
  function scanEnvNames(projectDir) {
733
782
  const seen = /* @__PURE__ */ new Map();
@@ -743,7 +792,7 @@ function scanEnvNames(projectDir) {
743
792
  if (m && !seen.has(m[1])) seen.set(m[1], file);
744
793
  }
745
794
  }
746
- return [...seen.entries()].slice(0, MAX_ENTRIES).map(([name, src]) => `- ${name} (${src})`);
795
+ return [...seen.entries()].map(([name, src]) => `- ${name} (${src})`);
747
796
  }
748
797
  function scanDataSchema(projectDir, files) {
749
798
  const lines = [];
@@ -779,7 +828,7 @@ function scanDataSchema(projectDir, files) {
779
828
  }
780
829
  if (tables.size) lines.push(`- tablas (${dir}/*.sql): ${[...tables].slice(0, 20).join(", ")}`);
781
830
  }
782
- return lines.slice(0, MAX_ENTRIES);
831
+ return lines;
783
832
  }
784
833
  function scanConventions(projectDir) {
785
834
  const lines = [];
@@ -854,8 +903,12 @@ function scanAll(vault, projectDir) {
854
903
  const conventions = run(() => scanConventions(projectDir));
855
904
  const notes = [];
856
905
  const titles = [];
857
- const write = (kind, title, header, lines) => {
858
- if (lines.length === 0) return;
906
+ const truncated = [];
907
+ const write = (kind, title, header, rawLines) => {
908
+ if (rawLines.length === 0) return;
909
+ const cap = entryCap(rawLines.length);
910
+ if (rawLines.length > cap) truncated.push(kind);
911
+ const lines = capLines(rawLines, cap);
859
912
  notes.push(
860
913
  upsertNote(vault.managed, {
861
914
  fixedName: `${kind}-${slugify(name)}`,
@@ -877,7 +930,7 @@ Proyecto: [[Mapa - ${name}]]`
877
930
  write("datos", `Datos - ${name}`, `Esquema de datos detectado en archivos (sin conexi\xF3n a BD).`, data);
878
931
  write("convenciones", `Convenciones - ${name}`, `Convenciones detectadas por \`ale scan\`.`, conventions);
879
932
  linkMapToScans(vault, name, titles);
880
- return { api: api.length, env: env.length, data: data.length, conventions: conventions.length, notes, gitignored };
933
+ return { api: api.length, env: env.length, data: data.length, conventions: conventions.length, notes, gitignored, truncated };
881
934
  }
882
935
 
883
936
  // src/cli.ts
@@ -936,7 +989,7 @@ async function ensureReady(vault = getVault()) {
936
989
  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
990
  "--path <dir>",
938
991
  "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(
992
+ ).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
993
  "--agents <ids>",
941
994
  `agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
942
995
  ).action(async (opts) => {
@@ -999,6 +1052,19 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
999
1052
  console.log(
1000
1053
  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
1054
  );
1055
+ if (opts.off) {
1056
+ const valid = new Set(TOKEN_TOGGLES.map((t) => t.key));
1057
+ for (const raw of opts.off.split(",")) {
1058
+ const key = raw.trim();
1059
+ if (!key) continue;
1060
+ if (valid.has(key)) {
1061
+ setConfigKey(key, false);
1062
+ console.log(pc.yellow(`\u2717 desactivado: ${key}`));
1063
+ } else {
1064
+ console.log(pc.yellow(` \u26A0 toggle desconocido \xAB${key}\xBB \u2014 lista: ale toggles`));
1065
+ }
1066
+ }
1067
+ }
1002
1068
  if (isProject) {
1003
1069
  const s = scanAll(vault, cwd);
1004
1070
  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)`));
@@ -1009,7 +1075,8 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
1009
1075
  console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
1010
1076
  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
1077
  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\n'));
1078
+ console.log(pc.dim(' Prueba: ale search "algo" \xB7 ale graph \xB7 ale stats \xB7 ale agents'));
1079
+ console.log(pc.dim(" Controla qu\xE9 gasta tokens (antes o despu\xE9s de instalar): ale toggles\n"));
1013
1080
  if (opts.skills) await runSkills({ yes: false, project: isProject });
1014
1081
  });
1015
1082
  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) => {
@@ -1037,8 +1104,9 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
1037
1104
  });
1038
1105
  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
1106
  const { vault, idx } = await ensureReady();
1040
- const notes = Object.values(idx.meta.notes).filter((n) => !n.rel.split("/").includes("archive"));
1041
- const plans = notes.filter((n) => n.type === "plan");
1107
+ const noArchive = (n) => !n.rel.split("/").includes("archive");
1108
+ const notes = Object.values(idx.meta.notes).filter(noArchive);
1109
+ const plans = idx.notesByTag("plan").filter(noArchive);
1042
1110
  const linked = new Set(idx.meta.links.flatMap((l) => [l.from, l.to]));
1043
1111
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Auditor\xEDa del Protocolo Alexandria\n"));
1044
1112
  const openPlans = plans.filter((p) => p.status === "active");
@@ -1051,9 +1119,9 @@ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD
1051
1119
  console.log(pc.yellow(` \u26A0 Planes sin Definition of Done: ${noDod.length}`));
1052
1120
  for (const p of noDod.slice(0, 5)) console.log(pc.dim(` - ${p.title}`));
1053
1121
  }
1054
- const verifs = notes.filter((n) => n.type === "verification");
1122
+ const verifs = idx.notesByTag("verification").filter(noArchive);
1055
1123
  const fails = verifs.filter((n) => n.status === "failed");
1056
- const lessons = notes.filter((n) => n.type === "lesson");
1124
+ const lessons = idx.notesByTag("lesson").filter(noArchive);
1057
1125
  console.log(` Verificaciones: ${verifs.length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
1058
1126
  if (fails.length > lessons.length) {
1059
1127
  console.log(pc.yellow(` \u26A0 Hay m\xE1s fallos (${fails.length}) que lecciones (${lessons.length}) \u2014 fallos resueltos sin destilar aprendizaje.`));
@@ -1202,6 +1270,39 @@ ${pc.bold(pc.cyan(r.note.title))} ${pc.dim(`(${r.note.rel}, ${r.note.type})`)}${
1202
1270
  }
1203
1271
  console.log();
1204
1272
  });
1273
+ program.command("toggles").description("Activa/desactiva comportamientos que gastan tokens (con costo aproximado de cada uno)").action(async () => {
1274
+ const printList = () => {
1275
+ console.log(pc.bold("\n\u26A1 Consumo de tokens \u2014 toggles\n"));
1276
+ TOKEN_TOGGLES.forEach((t, i) => {
1277
+ const on = toggleEnabled(t.key);
1278
+ console.log(` ${i + 1}. ${on ? pc.green("\u2713") : pc.red("\u2717")} ${pc.bold(t.label)} ${pc.dim(`(${t.key})`)}`);
1279
+ console.log(pc.dim(` ${t.desc}`));
1280
+ console.log(pc.dim(` ${t.impact}`));
1281
+ });
1282
+ };
1283
+ printList();
1284
+ if (!process.stdin.isTTY) {
1285
+ console.log(pc.dim("\n (no-TTY: cambia con `ale config set <key> true|false`)\n"));
1286
+ return;
1287
+ }
1288
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1289
+ const ans = (await rl.question(pc.bold("\nN\xFAmeros a cambiar (coma), Enter para salir: "))).trim();
1290
+ rl.close();
1291
+ if (!/^[\d,\s]+$/.test(ans) || !ans) {
1292
+ console.log(pc.dim("Sin cambios.\n"));
1293
+ return;
1294
+ }
1295
+ const nums = ans.split(",").map((n) => parseInt(n.trim(), 10) - 1);
1296
+ for (const i of nums) {
1297
+ const t = TOKEN_TOGGLES[i];
1298
+ if (!t) continue;
1299
+ const next = !toggleEnabled(t.key);
1300
+ setConfigKey(t.key, next);
1301
+ console.log(`${next ? pc.green("\u2713 activado") : pc.yellow("\u2717 desactivado")}: ${t.label}`);
1302
+ }
1303
+ printList();
1304
+ console.log();
1305
+ });
1205
1306
  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
1307
  const vault = getVault();
1207
1308
  ensureVaultStructure(vault);
@@ -1211,6 +1312,9 @@ program.command("scan").description("Escanea el proyecto (API, env-nombres, dato
1211
1312
  await idx.refresh().catch(() => {
1212
1313
  });
1213
1314
  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" : ""}`));
1315
+ if (s.truncated.length) {
1316
+ console.log(pc.yellow(` \u26A0 Notas truncadas por el cap: ${s.truncated.join(", ")} \u2014 s\xFAbelo con: ale config set scan.maxEntries <n>`));
1317
+ }
1214
1318
  if (s.notes.length) {
1215
1319
  for (const n of s.notes) console.log(pc.dim(` ${path5.relative(vault.root, n)}`));
1216
1320
  } else {
@@ -9,12 +9,13 @@ import {
9
9
  } from "../chunk-DEDAOKAV.js";
10
10
  import {
11
11
  hybridSearch
12
- } from "../chunk-RZI7TYAG.js";
12
+ } from "../chunk-AHBSZGSC.js";
13
13
  import {
14
14
  resolveVault,
15
+ toggleEnabled,
15
16
  vaultExists
16
- } from "../chunk-DYCARGQR.js";
17
- import "../chunk-D5ROL42O.js";
17
+ } from "../chunk-TFQ7WSIB.js";
18
+ import "../chunk-AXUEYSNZ.js";
18
19
  import {
19
20
  createNote,
20
21
  touchNote
@@ -45,11 +46,13 @@ runHook(25e3, async (input) => {
45
46
  });
46
47
  const maxCos = results.reduce((m, r) => Math.max(m, r.cosine), 0);
47
48
  const relevant = maxCos > 0 ? results.filter((r) => r.cosine >= RELEVANT_COSINE && r.cosine >= maxCos - RELEVANT_MARGIN) : results.filter((r) => r.score > 0.02);
49
+ const solutionCacheOn = toggleEnabled("tokens.solutionCache");
50
+ const promptSearchOn = toggleEnabled("tokens.promptSearch");
48
51
  let injected = "";
49
- if (relevant.length > 0) {
50
- const cached = relevant.find(
52
+ if (relevant.length > 0 && (solutionCacheOn || promptSearchOn)) {
53
+ const cached = solutionCacheOn ? relevant.find(
51
54
  (r) => (r.note.type === "prompt" || r.note.type === "session") && r.cosine >= SOLUTION_COSINE
52
- );
55
+ ) : void 0;
53
56
  const lines = [];
54
57
  if (cached) {
55
58
  lines.push(
@@ -57,28 +60,32 @@ runHook(25e3, async (input) => {
57
60
  ${truncate(cached.excerpts.join("\n"), 2e3)}`
58
61
  );
59
62
  }
60
- for (const r of relevant) {
61
- if (r === cached) continue;
62
- lines.push(`\u2022 \xAB${r.note.title}\xBB (${r.note.rel}):
63
+ if (promptSearchOn) {
64
+ for (const r of relevant) {
65
+ if (r === cached) continue;
66
+ lines.push(`\u2022 \xAB${r.note.title}\xBB (${r.note.rel}):
63
67
  ${truncate(r.excerpts.join("\n"), 900)}`);
64
- if (lines.join("\n\n").length > MAX_INJECT_CHARS) break;
68
+ if (lines.join("\n\n").length > MAX_INJECT_CHARS) break;
69
+ }
65
70
  }
66
- injected = `<alexandria-contexto>
71
+ if (lines.length > 0) {
72
+ injected = `<alexandria-contexto>
67
73
  Contexto recuperado de la b\xF3veda local (usa esto antes de releer archivos o re-explorar):
68
74
 
69
75
  ` + truncate(lines.join("\n\n"), MAX_INJECT_CHARS) + `
70
76
  </alexandria-contexto>`;
71
- process.stdout.write(injected);
72
- logInjection(vault, {
73
- kind: cached ? "solution-cache" : "inject",
74
- injectedChars: injected.length,
75
- promptChars: prompt.length
76
- });
77
- for (const r of relevant) {
78
- if (r.note.type === "lesson" || r.note.type === "solution") {
79
- try {
80
- touchNote(path.join(vault.root, r.note.rel));
81
- } catch {
77
+ process.stdout.write(injected);
78
+ logInjection(vault, {
79
+ kind: cached ? "solution-cache" : "inject",
80
+ injectedChars: injected.length,
81
+ promptChars: prompt.length
82
+ });
83
+ for (const r of relevant) {
84
+ if (r.note.type === "lesson" || r.note.type === "solution") {
85
+ try {
86
+ touchNote(path.join(vault.root, r.note.rel));
87
+ } catch {
88
+ }
82
89
  }
83
90
  }
84
91
  }
@@ -10,11 +10,12 @@ import {
10
10
  import {
11
11
  protocolEnabled,
12
12
  resolveVault,
13
+ toggleEnabled,
13
14
  vaultExists
14
- } from "../chunk-DYCARGQR.js";
15
+ } from "../chunk-TFQ7WSIB.js";
15
16
  import {
16
17
  VaultIndex
17
- } from "../chunk-D5ROL42O.js";
18
+ } from "../chunk-AXUEYSNZ.js";
18
19
  import "../chunk-XWR74BQ2.js";
19
20
  import "../chunk-EDYBSJSS.js";
20
21
 
@@ -33,7 +34,7 @@ runHook(15e3, async (input) => {
33
34
  const proj = projectName(input.cwd);
34
35
  const parts = [];
35
36
  if (protocolEnabled()) {
36
- const openPlans = notes.filter((n) => n.type === "plan" && n.status === "active");
37
+ const openPlans = idx.notesByTag("plan").filter((n) => n.status === "active");
37
38
  parts.push(
38
39
  `## Protocolo Alexandria (activo)
39
40
  El protocolo es PALANCA, no l\xEDmite: \xFAsalo para rendir m\xE1s con menos tokens, nunca como burocracia. Tareas simples \u2192 responde directo, sin ceremonia. Tareas no triviales \u2192 ciclo con las tools MCP: 1) plan_create (objetivo + Definition of Done) \u2192 2) ejecuta con toda tu capacidad \u2192 3) task_verify con evidencia real (tests/build \u2014 la evidencia elimina errores, no te frena) \u2192 si algo falla, vault_search por lecciones ANTES de re-debuggear (conocimiento previo = tokens gratis) \u2192 4) lesson_extract si resolviste algo no obvio. Reutiliza lo cacheado con criterio: valida que siga aplicando si el c\xF3digo cambi\xF3.` + (openPlans.length > 0 ? `
@@ -43,7 +44,7 @@ El protocolo es PALANCA, no l\xEDmite: \xFAsalo para rendir m\xE1s con menos tok
43
44
  const map = notes.find(
44
45
  (n) => (n.type === "map" || n.title.toLowerCase().startsWith("mapa - ")) && n.title.toLowerCase().includes(proj.toLowerCase())
45
46
  );
46
- if (map) {
47
+ if (map && toggleEnabled("digest.map")) {
47
48
  try {
48
49
  const raw = fs.readFileSync(path.join(vault.root, map.rel), "utf8");
49
50
  const body = raw.replace(/^---[\s\S]*?---\n/, "");
@@ -52,19 +53,19 @@ ${truncate(body.trim(), 4e3)}`);
52
53
  } catch {
53
54
  }
54
55
  }
55
- const sessions = notes.filter((n) => n.type === "session").sort((a, b) => (b.created ?? "").localeCompare(a.created ?? "")).slice(0, 3);
56
+ const sessions = idx.notesByTag("session").sort((a, b) => (b.created ?? "").localeCompare(a.created ?? "")).slice(0, 3);
56
57
  if (sessions.length > 0) {
57
58
  const lines = sessions.map((s) => `- ${s.title} (${(s.created ?? "").slice(0, 10)})`);
58
59
  parts.push(`## Sesiones recientes en la b\xF3veda
59
60
  ${lines.join("\n")}`);
60
61
  }
61
- const distilled = notes.filter((n) => n.type === "note" || n.type === "lesson").length;
62
+ const distilled = idx.notesByTag("note").length + idx.notesByTag("lesson").length;
62
63
  if (map && distilled < 3) {
63
64
  parts.push(
64
65
  `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.`
65
66
  );
66
67
  }
67
- const titles = notes.filter((n) => n.type !== "prompt").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1)).slice(0, 25).map((n) => n.title);
68
+ 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) : [];
68
69
  if (titles.length > 0) {
69
70
  parts.push(`## La b\xF3veda ya tiene conocimiento sobre
70
71
  ${titles.join(" \xB7 ")}`);
@@ -8,7 +8,7 @@ import {
8
8
  ensureVaultStructure,
9
9
  resolveVault,
10
10
  vaultExists
11
- } from "../chunk-DYCARGQR.js";
11
+ } from "../chunk-TFQ7WSIB.js";
12
12
  import {
13
13
  appendToNote
14
14
  } from "../chunk-XWR74BQ2.js";
@@ -4,17 +4,18 @@ import {
4
4
  pkgVersion,
5
5
  planContext,
6
6
  planQualityHints
7
- } from "../chunk-DHXL36RG.js";
7
+ } from "../chunk-T5VNBQEC.js";
8
8
  import {
9
9
  hybridSearch
10
- } from "../chunk-RZI7TYAG.js";
10
+ } from "../chunk-AHBSZGSC.js";
11
11
  import {
12
12
  ensureVaultStructure,
13
- resolveVault
14
- } from "../chunk-DYCARGQR.js";
13
+ resolveVault,
14
+ toggleEnabled
15
+ } from "../chunk-TFQ7WSIB.js";
15
16
  import {
16
17
  VaultIndex
17
- } from "../chunk-D5ROL42O.js";
18
+ } from "../chunk-AXUEYSNZ.js";
18
19
  import {
19
20
  createNote,
20
21
  setNoteStatus,
@@ -145,8 +146,9 @@ server.tool(
145
146
  },
146
147
  async ({ title, goal, dod, tasks, design }) => {
147
148
  ensureVaultStructure(vault);
148
- const ctx = await planContext(vault, `${title} ${goal}`);
149
- const hints = planQualityHints(dod, tasks, design);
149
+ const enrich = toggleEnabled("architect.enrich");
150
+ const ctx = enrich ? await planContext(vault, `${title} ${goal}`) : { similarPlans: [], lessons: [] };
151
+ const hints = enrich ? planQualityHints(dod, tasks, design) : [];
150
152
  const idx = VaultIndex.load(vault);
151
153
  const map = findMap(idx);
152
154
  const content = [
@@ -4,8 +4,8 @@ import {
4
4
  renderGraphHtml,
5
5
  serveGraph,
6
6
  writeStaticGraph
7
- } from "./chunk-DCKYTO4O.js";
8
- import "./chunk-D5ROL42O.js";
7
+ } from "./chunk-XY7U4CAQ.js";
8
+ import "./chunk-AXUEYSNZ.js";
9
9
  import "./chunk-XWR74BQ2.js";
10
10
  import "./chunk-EDYBSJSS.js";
11
11
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ureck/alexandria",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Alexandria — bóveda de conocimiento local para agentes de IA (Claude Code, Cursor, OpenCode, Windsurf y más): captura automática, búsqueda semántica offline y grafo de conexiones estilo Obsidian. Ahorra tokens inyectando solo el contexto relevante.",
5
5
  "type": "module",
6
6
  "license": "MIT",