@ureck/alexandria 0.5.4 → 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
@@ -33,7 +33,7 @@ It lives in the MCP tools themselves — their names and descriptions carry the
33
33
 
34
34
  | MCP tool | What the agent does with it | Token payoff |
35
35
  |---|---|---|
36
- | `plan_create(title, goal, dod, tasks)` | Writes a plan note with a **Definition of Done** and numbered tasks before touching code | No wandering; open plans are re-injected next session so work is resumed, not repeated |
36
+ | `plan_create(title, goal, dod, tasks, design?)` | Plans like an **architect**: clarifies vague goals first, optionally records the architecture (`design` → a `## Design` section), and the response surfaces **similar past plans + relevant lessons** plus quality hints (verifiable DoD, small tasks) — suggestions, never a gate | No wandering; open plans are re-injected next session so work is resumed, not repeated |
37
37
  | `task_verify(plan, task, passed, verify_command)` | **Runs** `verify_command` (e.g. `npm test`) and takes the verdict from the real exit code — not from the agent's word. Flags a **discrepancy** if the agent claimed otherwise; without a command the note is tagged `self-reported` and `ale audit` calls it out | "✅ 12/12 passed" (5 tokens) instead of a 500-line log; on failure it automatically surfaces **past lessons** that match |
38
38
  | `lesson_extract(title, lesson, links)` | Distills the root cause + fix after solving something non-obvious | ~200 tokens today replace ~20,000 tokens of re-debugging next month |
39
39
 
@@ -63,7 +63,7 @@ Verify:
63
63
 
64
64
  ```bash
65
65
  $ ale --version
66
- 0.5.4
66
+ 1.1.0
67
67
  ```
68
68
 
69
69
  ## Getting started
@@ -132,6 +132,36 @@ 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
+
147
+ ### Deep project context (`ale scan`)
148
+
149
+ `ale init --project` already runs it; re-run anytime the project changes:
150
+
151
+ ```bash
152
+ $ ale scan
153
+ ✓ API: 12 rutas · Env: 8 vars (solo nombres) · Datos: 5 · Convenciones: 4 · .gitignore ✓
154
+ ```
155
+
156
+ Four read-only scanners write compact notes (one line per entry) that the agent receives **only when relevant** (per-prompt semantic search — the session digest doesn't grow):
157
+
158
+ - **`API - <project>`** — App Router routes with HTTP methods, Pages Router handlers, `"use server"` actions, Express/Hono routes.
159
+ - **`Env - <project>`** — environment variable **NAMES only, never values** (from `.env.example` / `.env` / `.env.local`).
160
+ - **`Datos - <project>`** — data schema parsed from files (prisma models, drizzle tables, `CREATE TABLE` in migrations) — no DB connection.
161
+ - **`Convenciones - <project>`** — package manager, monorepo, TS strict, import aliases, framework.
162
+
163
+ It never touches your source code, and it guarantees the vault (and personal configs) are gitignored before writing — your notes never reach a shared repo, even if you never ran `ale init`.
164
+
135
165
  ### Create a plan from a file
136
166
 
137
167
  Instead of typing a whole plan into the terminal, keep it as markdown in your repo:
@@ -259,10 +289,12 @@ AI agent session
259
289
  | Command | What it does |
260
290
  |---|---|
261
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 |
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>` |
262
294
  | `ale agents [ids] [--project]` | List agents / register the MCP server |
263
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 |
264
296
  | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
265
- | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done) |
297
+ | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done); surfaces similar past plans + quality hints |
266
298
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
267
299
  | `ale audit` | Protocol health: plans without DoD, failures without lessons, orphan notes |
268
300
  | `ale stats` | Notes, connections, protocol metrics, estimated tokens saved |
@@ -280,6 +312,7 @@ AI agent session
280
312
 
281
313
  - **Everything runs on your machine**: the embedding model is downloaded once (Hugging Face) and then works offline. Your notes never leave your disk. No telemetry.
282
314
  - **No API keys, no accounts, no cost.**
315
+ - **`ale scan` never reads secrets**: it extracts environment variable **names** only (values are never copied), parses schema **files** (no live DB connection), and guarantees the vault is gitignored before writing — your notes never reach a shared repo.
283
316
  - Dependency scanners (Socket, etc.) flag *network/shell/env access* in the dependency tree: those come from the ML runtime (`onnxruntime`/`transformers.js`, which needs filesystem access and the one-time model download) and the official MCP SDK — not from Alexandria's code. The published package runs no install scripts of its own.
284
317
  - Generated per-project configs (`.mcp.json`, `.vault.json`, etc.) point at your machine's install path, so `ale init --project` automatically gitignores them (and untracks any already committed) — they never leak to a shared repo. For a team that *wants* a shared MCP config, run `ale init --project --portable`, which writes an npx-based command that works on any machine.
285
318
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-7G3NPKDO.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
  }
@@ -50,20 +53,41 @@ var VaultIndex = class _VaultIndex {
50
53
  try {
51
54
  const buf = fs.readFileSync(idx.embPath);
52
55
  const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
53
- if (arr.length === meta.chunks.length * meta.dim) idx.emb = arr.slice();
56
+ if (arr.length === meta.chunks.length * meta.dim) {
57
+ idx.emb = arr.slice();
58
+ } else {
59
+ idx.emb = null;
60
+ try {
61
+ fs.rmSync(idx.embPath, { force: true });
62
+ } catch {
63
+ }
64
+ }
54
65
  } catch {
55
66
  idx.emb = null;
56
67
  }
57
68
  }
58
- } catch {
69
+ } catch (e) {
70
+ if (fs.existsSync(idx.metaPath)) {
71
+ try {
72
+ fs.rmSync(idx.metaPath, { force: true });
73
+ fs.rmSync(idx.embPath, { force: true });
74
+ } catch {
75
+ }
76
+ }
59
77
  }
60
78
  return idx;
61
79
  }
80
+ /** Escritura atómica: tmp + rename — un hook y un comando concurrentes nunca dejan el archivo a medias. */
81
+ writeAtomic(file, data) {
82
+ const tmp = `${file}.${process.pid}.tmp`;
83
+ fs.writeFileSync(tmp, data);
84
+ fs.renameSync(tmp, file);
85
+ }
62
86
  save() {
63
87
  fs.mkdirSync(this.vault.cache, { recursive: true });
64
- fs.writeFileSync(this.metaPath, JSON.stringify(this.meta));
88
+ this.writeAtomic(this.metaPath, JSON.stringify(this.meta));
65
89
  if (this.emb) {
66
- fs.writeFileSync(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
90
+ this.writeAtomic(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
67
91
  }
68
92
  }
69
93
  row(i) {
@@ -91,6 +115,7 @@ var VaultIndex = class _VaultIndex {
91
115
  if (changed.length === 0 && removed.length === 0) {
92
116
  return { changed: 0, removed: 0, embedded: this.emb !== null };
93
117
  }
118
+ this._tagIndex = null;
94
119
  const keep = new Set(
95
120
  this.meta.chunks.map((_, i) => i).filter((i) => {
96
121
  const rel = this.meta.chunks[i].note;
@@ -171,7 +196,7 @@ ${c.text}`),
171
196
  this.rebuildLinks();
172
197
  this.save();
173
198
  try {
174
- const { writeStaticGraph } = await import("./viewer-G3N57646.js");
199
+ const { writeStaticGraph } = await import("./viewer-2YMJBQRH.js");
175
200
  writeStaticGraph(this);
176
201
  } catch {
177
202
  }
@@ -228,6 +253,24 @@ ${c.text}`),
228
253
  }
229
254
  this.meta.links = links;
230
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
+ }
231
274
  /** Vecinos directos de una nota en el grafo (sin releer archivos). */
232
275
  neighbors(rel) {
233
276
  const out = [];
@@ -1,4 +1,46 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ hybridSearch
4
+ } from "./chunk-AHBSZGSC.js";
5
+
6
+ // src/core/planning.ts
7
+ var MAX_ITEMS = 2;
8
+ var EXCERPT_CHARS = 150;
9
+ async function planContext(vault, query) {
10
+ const out = { similarPlans: [], lessons: [] };
11
+ try {
12
+ const results = await hybridSearch(vault, query, 8);
13
+ for (const r of results) {
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) {
18
+ out.lessons.push(`\xAB${r.note.title}\xBB: ${excerpt}`);
19
+ }
20
+ }
21
+ } catch {
22
+ }
23
+ return out;
24
+ }
25
+ var FAT_TASK_CHARS = 140;
26
+ var MAX_HINTS = 3;
27
+ function planQualityHints(dod, tasks, design) {
28
+ const hints = [];
29
+ const fat = tasks.filter((t) => t.length > FAT_TASK_CHARS);
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);
36
+ }
37
+ function architectBlock(ctx, hints) {
38
+ const parts = [];
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");
43
+ }
2
44
 
3
45
  // src/core/register.ts
4
46
  import fs from "fs";
@@ -128,6 +170,9 @@ function pkgVersion() {
128
170
  }
129
171
 
130
172
  export {
173
+ planContext,
174
+ planQualityHints,
175
+ architectBlock,
131
176
  distDir,
132
177
  registerHooks,
133
178
  unregisterHooks,
@@ -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-7G3NPKDO.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
@@ -3,22 +3,26 @@ import {
3
3
  readStats
4
4
  } from "./chunk-XITAQVOZ.js";
5
5
  import {
6
+ architectBlock,
6
7
  distDir,
7
8
  globalSettingsPath,
8
9
  hooksRegistered,
9
10
  mcpRegisteredProject,
10
11
  pkgVersion,
12
+ planContext,
13
+ planQualityHints,
11
14
  projectSettingsPath,
12
15
  registerHooks,
13
16
  registerMcpGlobal,
14
17
  registerMcpProject,
15
18
  unregisterHooks
16
- } from "./chunk-IQM5S5N4.js";
19
+ } from "./chunk-T5VNBQEC.js";
17
20
  import {
18
21
  hybridSearch,
19
22
  protocolChain
20
- } from "./chunk-MEL3BE65.js";
23
+ } from "./chunk-AHBSZGSC.js";
21
24
  import {
25
+ TOKEN_TOGGLES,
22
26
  defaultVaultPath,
23
27
  ensureVaultStructure,
24
28
  getConfigKey,
@@ -26,16 +30,17 @@ import {
26
30
  protocolEnabled,
27
31
  resolveVault,
28
32
  setConfigKey,
33
+ toggleEnabled,
29
34
  vaultExists,
30
35
  writeGlobalConfig,
31
36
  writeProjectConfig
32
- } from "./chunk-DYCARGQR.js";
37
+ } from "./chunk-TFQ7WSIB.js";
33
38
  import {
34
39
  serveGraph
35
- } from "./chunk-UTXUGXDB.js";
40
+ } from "./chunk-XY7U4CAQ.js";
36
41
  import {
37
42
  VaultIndex
38
- } from "./chunk-7G3NPKDO.js";
43
+ } from "./chunk-AXUEYSNZ.js";
39
44
  import {
40
45
  createNote,
41
46
  slugify,
@@ -50,8 +55,8 @@ import {
50
55
  } from "./chunk-EDYBSJSS.js";
51
56
 
52
57
  // src/cli.ts
53
- import fs4 from "fs";
54
- import path4 from "path";
58
+ import fs5 from "fs";
59
+ import path5 from "path";
55
60
  import readline from "readline/promises";
56
61
  import { Command } from "commander";
57
62
  import pc from "picocolors";
@@ -542,6 +547,8 @@ function configureClaudeMd(scope, projectDir) {
542
547
  "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
543
548
  "- El Protocolo Alexandria es palanca, no l\xEDmite: tareas simples se responden directo, sin ceremonia. En tareas no triviales: `plan_create` (objetivo + Definition of Done) \u2192 ejecutar con toda tu capacidad \u2192 `task_verify` con evidencia real (la evidencia elimina errores, no frena) \u2192 si algo falla, `vault_search` por lecciones previas antes de re-debuggear \u2192 `lesson_extract` al resolver algo no obvio. Soluciones cacheadas se validan contra el c\xF3digo actual antes de reutilizarse.",
544
549
  "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
550
+ "- 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.",
551
+ "- Las notas `API - <proyecto>` / `Env - <proyecto>` / `Datos - <proyecto>` / `Convenciones - <proyecto>` (de `ale scan`) ya traen rutas, variables (solo nombres) y esquema \u2014 cons\xFAltalas por b\xFAsqueda antes de releer esos archivos.",
545
552
  "- `vault_related` trae conocimiento conectado sin releer archivos.",
546
553
  CLAUDE_MD_END
547
554
  ].join("\n");
@@ -634,6 +641,298 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
634
641
  });
635
642
  }
636
643
 
644
+ // src/core/scan.ts
645
+ import fs4 from "fs";
646
+ import path4 from "path";
647
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set([
648
+ "node_modules",
649
+ ".git",
650
+ ".next",
651
+ "dist",
652
+ "build",
653
+ ".vault",
654
+ ".claude",
655
+ "coverage",
656
+ "Alexandria",
657
+ "KnowledgeVault",
658
+ ".turbo",
659
+ ".vercel",
660
+ "out",
661
+ "vendor"
662
+ ]);
663
+ var SOURCE_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
664
+ var MAX_FILES = 800;
665
+ var MAX_FILE_BYTES = 64 * 1024;
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;
683
+ function collectSourceFiles(projectDir) {
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;
705
+ }
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;
726
+ }
727
+ }
728
+ if (!any) break;
729
+ }
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
+ }
742
+ return out;
743
+ }
744
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
745
+ function appRoutePath(rel) {
746
+ const m = rel.match(/(?:^|\/)app\/(.*)route\.[tj]sx?$/);
747
+ if (!m) return "";
748
+ const segs = m[1].split("/").filter((s) => s && !/^\(.*\)$/.test(s));
749
+ return "/" + segs.join("/").replace(/\/$/, "");
750
+ }
751
+ var RAW_SAFETY = 1e3;
752
+ function scanApi(files) {
753
+ const lines = [];
754
+ for (const f of files) {
755
+ if (lines.length >= RAW_SAFETY) break;
756
+ if (/(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel)) {
757
+ const methods = HTTP_METHODS.filter(
758
+ (m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
759
+ );
760
+ if (methods.length) lines.push(`- ${methods.join("/")} ${appRoutePath(f.rel)} \u2014 ${f.rel}`);
761
+ continue;
762
+ }
763
+ const pagesApi = f.rel.match(/(?:^|\/)pages\/api\/(.+)\.[tj]sx?$/);
764
+ if (pagesApi) {
765
+ lines.push(`- handler /api/${pagesApi[1].replace(/\/index$/, "")} \u2014 ${f.rel}`);
766
+ continue;
767
+ }
768
+ if (/^\s*['"]use server['"]/m.test(f.content.slice(0, 400))) {
769
+ const fns = [...f.content.matchAll(/export\s+(?:async\s+)?function\s+(\w+)/g)].map((m) => m[1]);
770
+ if (fns.length) lines.push(`- server actions: ${fns.slice(0, 8).join(", ")} \u2014 ${f.rel}`);
771
+ continue;
772
+ }
773
+ const expressHits = [...f.content.matchAll(/\b(?:app|router|api)\.(get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/g)];
774
+ for (const h of expressHits.slice(0, 12)) {
775
+ lines.push(`- ${h[1].toUpperCase()} ${h[2]} \u2014 ${f.rel}`);
776
+ if (lines.length >= RAW_SAFETY) break;
777
+ }
778
+ }
779
+ return lines;
780
+ }
781
+ function scanEnvNames(projectDir) {
782
+ const seen = /* @__PURE__ */ new Map();
783
+ for (const file of [".env.example", ".env", ".env.local"]) {
784
+ let text;
785
+ try {
786
+ text = fs4.readFileSync(path4.join(projectDir, file), "utf8");
787
+ } catch {
788
+ continue;
789
+ }
790
+ for (const line of text.split("\n")) {
791
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
792
+ if (m && !seen.has(m[1])) seen.set(m[1], file);
793
+ }
794
+ }
795
+ return [...seen.entries()].map(([name, src]) => `- ${name} (${src})`);
796
+ }
797
+ function scanDataSchema(projectDir, files) {
798
+ const lines = [];
799
+ try {
800
+ const schema = fs4.readFileSync(path4.join(projectDir, "prisma", "schema.prisma"), "utf8");
801
+ for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
802
+ const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
803
+ const shown = fields.slice(0, 8).join(", ");
804
+ lines.push(`- model ${m[1]}: ${shown}${fields.length > 8 ? ` (+${fields.length - 8})` : ""} \u2014 prisma/schema.prisma`);
805
+ }
806
+ } catch {
807
+ }
808
+ for (const f of files.filter((x) => /schema/i.test(x.rel))) {
809
+ for (const m of f.content.matchAll(/\b(?:pg|mysql|sqlite)Table\(\s*['"`](\w+)['"`]/g)) {
810
+ lines.push(`- table ${m[1]} (drizzle) \u2014 ${f.rel}`);
811
+ }
812
+ }
813
+ const migDirs = ["migrations", "db/migrations", "drizzle", "supabase/migrations"];
814
+ for (const dir of migDirs) {
815
+ let sqlFiles = [];
816
+ try {
817
+ sqlFiles = fs4.readdirSync(path4.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
818
+ } catch {
819
+ continue;
820
+ }
821
+ const tables = /* @__PURE__ */ new Set();
822
+ for (const f of sqlFiles) {
823
+ try {
824
+ const sql = fs4.readFileSync(path4.join(projectDir, dir, f), "utf8");
825
+ for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
826
+ } catch {
827
+ }
828
+ }
829
+ if (tables.size) lines.push(`- tablas (${dir}/*.sql): ${[...tables].slice(0, 20).join(", ")}`);
830
+ }
831
+ return lines;
832
+ }
833
+ function scanConventions(projectDir) {
834
+ const lines = [];
835
+ const has = (f) => fs4.existsSync(path4.join(projectDir, f));
836
+ const pm = has("bun.lockb") || has("bun.lock") ? "bun" : has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("package-lock.json") ? "npm" : null;
837
+ if (pm) lines.push(`- gestor de paquetes: ${pm}`);
838
+ let pkg = {};
839
+ try {
840
+ pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
841
+ } catch {
842
+ }
843
+ if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
844
+ try {
845
+ const ts = JSON.parse(fs4.readFileSync(path4.join(projectDir, "tsconfig.json"), "utf8"));
846
+ const co = ts.compilerOptions ?? {};
847
+ lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
848
+ const paths = Object.keys(co.paths ?? {}).slice(0, 5);
849
+ if (paths.length) lines.push(`- alias de imports: ${paths.join(", ")}`);
850
+ } catch {
851
+ }
852
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
853
+ const fw = [];
854
+ if (deps?.next) fw.push("Next.js");
855
+ if (deps?.astro) fw.push("Astro");
856
+ if (deps?.expo || deps?.["react-native"]) fw.push("React Native/Expo");
857
+ if (deps?.hono) fw.push("Hono");
858
+ if (deps?.express) fw.push("Express");
859
+ if (deps?.["@nestjs/core"]) fw.push("NestJS");
860
+ if (deps?.vue) fw.push("Vue");
861
+ if (deps?.svelte) fw.push("Svelte");
862
+ if (fw.length) lines.push(`- framework: ${fw.join(", ")}`);
863
+ return lines;
864
+ }
865
+ function linkMapToScans(vault, name, titles) {
866
+ if (titles.length === 0) return;
867
+ const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
868
+ try {
869
+ const text = fs4.readFileSync(mapFile, "utf8");
870
+ if (text.includes("Contexto ampliado:")) return;
871
+ fs4.appendFileSync(mapFile, `
872
+ Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
873
+ `);
874
+ } catch {
875
+ }
876
+ }
877
+ function scanAll(vault, projectDir) {
878
+ const name = path4.basename(projectDir);
879
+ const gitignored = ensureGitignore(projectDir, vault.root) !== null;
880
+ try {
881
+ untrackPersonalConfigs(projectDir);
882
+ } catch {
883
+ }
884
+ try {
885
+ scanProject(vault, projectDir);
886
+ } catch {
887
+ }
888
+ let files = [];
889
+ try {
890
+ files = collectSourceFiles(projectDir);
891
+ } catch {
892
+ }
893
+ const run = (fn) => {
894
+ try {
895
+ return fn();
896
+ } catch {
897
+ return [];
898
+ }
899
+ };
900
+ const api = run(() => scanApi(files));
901
+ const env = run(() => scanEnvNames(projectDir));
902
+ const data = run(() => scanDataSchema(projectDir, files));
903
+ const conventions = run(() => scanConventions(projectDir));
904
+ const notes = [];
905
+ const titles = [];
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);
912
+ notes.push(
913
+ upsertNote(vault.managed, {
914
+ fixedName: `${kind}-${slugify(name)}`,
915
+ title,
916
+ type: "map",
917
+ tags: [name, kind],
918
+ dir: "notes",
919
+ content: `${header}
920
+
921
+ ${lines.join("\n")}
922
+
923
+ Proyecto: [[Mapa - ${name}]]`
924
+ })
925
+ );
926
+ titles.push(title);
927
+ };
928
+ write("api", `API - ${name}`, `Rutas y server actions detectadas por \`ale scan\` (regenerable).`, api);
929
+ write("env", `Env - ${name}`, `Variables de entorno (SOLO nombres \u2014 los valores nunca se guardan).`, env);
930
+ write("datos", `Datos - ${name}`, `Esquema de datos detectado en archivos (sin conexi\xF3n a BD).`, data);
931
+ write("convenciones", `Convenciones - ${name}`, `Convenciones detectadas por \`ale scan\`.`, conventions);
932
+ linkMapToScans(vault, name, titles);
933
+ return { api: api.length, env: env.length, data: data.length, conventions: conventions.length, notes, gitignored, truncated };
934
+ }
935
+
637
936
  // src/cli.ts
638
937
  function registerAgentsMcp(agents, scope, cwd, portable = false) {
639
938
  for (const agent of agents) {
@@ -690,13 +989,13 @@ async function ensureReady(vault = getVault()) {
690
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(
691
990
  "--path <dir>",
692
991
  "ruta del vault Obsidian (existente o nuevo). Default: ./Alexandria con --project, ~/Alexandria en global"
693
- ).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(
694
993
  "--agents <ids>",
695
994
  `agentes de IA donde registrar el MCP: "all", "detected" o csv de ${AGENTS.map((a) => a.id).join(",")} (default: claude + detectados)`
696
995
  ).action(async (opts) => {
697
996
  const isProject = Boolean(opts.project) && !opts.global;
698
997
  const cwd = process.cwd();
699
- const vaultPath = path4.resolve(opts.path ?? (isProject ? path4.join(cwd, "Alexandria") : defaultVaultPath()));
998
+ const vaultPath = path5.resolve(opts.path ?? (isProject ? path5.join(cwd, "Alexandria") : defaultVaultPath()));
700
999
  await showBanner();
701
1000
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
702
1001
  `));
@@ -753,9 +1052,22 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
753
1052
  console.log(
754
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")
755
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
+ }
756
1068
  if (isProject) {
757
- const map = scanProject(vault, cwd);
758
- if (map) console.log(pc.green(`\u2713 Proyecto escaneado \u2192 ${path4.relative(vault.root, map)} (mapa inicial)`));
1069
+ const s = scanAll(vault, cwd);
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)`));
759
1071
  }
760
1072
  await downloadModelIfMissing();
761
1073
  const idx = VaultIndex.load(vault);
@@ -763,15 +1075,16 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
763
1075
  console.log(pc.green(`\u2713 \xCDndice: ${Object.keys(idx.meta.notes).length} notas, ${idx.meta.links.length} conexiones${res.embedded ? "" : " (keyword-only)"}`));
764
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.")));
765
1077
  console.log(pc.dim(" Hooks (captura autom\xE1tica) solo en Claude Code; los dem\xE1s agentes usan las tools MCP."));
766
- 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"));
767
1080
  if (opts.skills) await runSkills({ yes: false, project: isProject });
768
1081
  });
769
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) => {
770
1083
  const { vault } = await ensureReady();
771
- const abs = path4.resolve(file);
772
- const raw = fs4.readFileSync(abs, "utf8");
1084
+ const abs = path5.resolve(file);
1085
+ const raw = fs5.readFileSync(abs, "utf8");
773
1086
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
774
- const title = opts.title ?? heading ?? path4.basename(abs).replace(/\.(md|txt)$/i, "");
1087
+ const title = opts.title ?? heading ?? path5.basename(abs).replace(/\.(md|txt)$/i, "");
775
1088
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
776
1089
  const noteFile = createNote(vault.managed, {
777
1090
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
@@ -781,14 +1094,19 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
781
1094
  content: raw.trim()
782
1095
  });
783
1096
  await VaultIndex.load(vault).refresh();
784
- console.log(pc.green(`\u2713 Plan creado: ${path4.relative(vault.root, noteFile)}`));
1097
+ console.log(pc.green(`\u2713 Plan creado: ${path5.relative(vault.root, noteFile)}`));
785
1098
  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)'}`));
786
1099
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1100
+ const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
1101
+ const ctx = await planContext(vault, title);
1102
+ const block = architectBlock(ctx, planQualityHints(dod, tasks));
1103
+ if (block) console.log(pc.dim("\n" + block.split("\n").map((l) => " " + l).join("\n")));
787
1104
  });
788
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 () => {
789
1106
  const { vault, idx } = await ensureReady();
790
- const notes = Object.values(idx.meta.notes).filter((n) => !n.rel.split("/").includes("archive"));
791
- 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);
792
1110
  const linked = new Set(idx.meta.links.flatMap((l) => [l.from, l.to]));
793
1111
  console.log(pc.bold("\n\u{1F3DB}\uFE0F Auditor\xEDa del Protocolo Alexandria\n"));
794
1112
  const openPlans = plans.filter((p) => p.status === "active");
@@ -801,9 +1119,9 @@ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD
801
1119
  console.log(pc.yellow(` \u26A0 Planes sin Definition of Done: ${noDod.length}`));
802
1120
  for (const p of noDod.slice(0, 5)) console.log(pc.dim(` - ${p.title}`));
803
1121
  }
804
- const verifs = notes.filter((n) => n.type === "verification");
1122
+ const verifs = idx.notesByTag("verification").filter(noArchive);
805
1123
  const fails = verifs.filter((n) => n.status === "failed");
806
- const lessons = notes.filter((n) => n.type === "lesson");
1124
+ const lessons = idx.notesByTag("lesson").filter(noArchive);
807
1125
  console.log(` Verificaciones: ${verifs.length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
808
1126
  if (fails.length > lessons.length) {
809
1127
  console.log(pc.yellow(` \u26A0 Hay m\xE1s fallos (${fails.length}) que lecciones (${lessons.length}) \u2014 fallos resueltos sin destilar aprendizaje.`));
@@ -848,21 +1166,21 @@ program.command("consolidate").description("Archiva prompts viejos sin reuso: sa
848
1166
  console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
849
1167
  return;
850
1168
  }
851
- const archiveDir = path4.join(vault.managed, "archive");
852
- if (!opts.dry) fs4.mkdirSync(archiveDir, { recursive: true });
1169
+ const archiveDir = path5.join(vault.managed, "archive");
1170
+ if (!opts.dry) fs5.mkdirSync(archiveDir, { recursive: true });
853
1171
  for (const n of stale) {
854
1172
  console.log(
855
1173
  `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
856
1174
  );
857
1175
  if (!opts.dry) {
858
- fs4.renameSync(path4.join(vault.root, n.rel), path4.join(archiveDir, path4.basename(n.rel)));
1176
+ fs5.renameSync(path5.join(vault.root, n.rel), path5.join(archiveDir, path5.basename(n.rel)));
859
1177
  }
860
1178
  }
861
1179
  if (!opts.dry) {
862
1180
  await VaultIndex.load(vault).refresh();
863
1181
  console.log(
864
1182
  pc.green(`
865
- \u2713 ${stale.length} prompts archivados en ${path4.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1183
+ \u2713 ${stale.length} prompts archivados en ${path5.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
866
1184
  );
867
1185
  } else {
868
1186
  console.log(pc.dim(`
@@ -893,10 +1211,10 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
893
1211
  const { vault } = await ensureReady();
894
1212
  let content = opts.content;
895
1213
  if (!content && opts.file) {
896
- content = fs4.readFileSync(path4.resolve(opts.file), "utf8");
1214
+ content = fs5.readFileSync(path5.resolve(opts.file), "utf8");
897
1215
  }
898
1216
  if (!content && !process.stdin.isTTY) {
899
- content = fs4.readFileSync(0, "utf8");
1217
+ content = fs5.readFileSync(0, "utf8");
900
1218
  }
901
1219
  const file = createNote(vault.managed, {
902
1220
  title,
@@ -904,7 +1222,7 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
904
1222
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
905
1223
  });
906
1224
  await VaultIndex.load(vault).refresh();
907
- console.log(pc.green(`\u2713 ${path4.relative(vault.root, file)}`));
1225
+ console.log(pc.green(`\u2713 ${path5.relative(vault.root, file)}`));
908
1226
  });
909
1227
  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) => {
910
1228
  const vault = getVault();
@@ -952,6 +1270,57 @@ ${pc.bold(pc.cyan(r.note.title))} ${pc.dim(`(${r.note.rel}, ${r.note.type})`)}${
952
1270
  }
953
1271
  console.log();
954
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
+ });
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 () => {
1307
+ const vault = getVault();
1308
+ ensureVaultStructure(vault);
1309
+ const cwd = process.cwd();
1310
+ const s = scanAll(vault, cwd);
1311
+ const idx = VaultIndex.load(vault);
1312
+ await idx.refresh().catch(() => {
1313
+ });
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
+ }
1318
+ if (s.notes.length) {
1319
+ for (const n of s.notes) console.log(pc.dim(` ${path5.relative(vault.root, n)}`));
1320
+ } else {
1321
+ console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1322
+ }
1323
+ });
955
1324
  program.command("reindex").description("Reindexar la b\xF3veda (incremental; --force para todo)").option("--force", "reindexar todo desde cero").action(async (opts) => {
956
1325
  const vault = getVault();
957
1326
  ensureVaultStructure(vault);
@@ -1008,7 +1377,7 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
1008
1377
  async function runSkills(opts) {
1009
1378
  const { vault } = await ensureReady();
1010
1379
  const cwd = process.cwd();
1011
- const targetDir = opts.project ? path4.join(cwd, ".claude", "skills") : path4.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1380
+ const targetDir = opts.project ? path5.join(cwd, ".claude", "skills") : path5.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1012
1381
  const recs = await recommendSkills(vault, [targetDir]);
1013
1382
  if (recs.length === 0) {
1014
1383
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
@@ -1076,8 +1445,29 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1076
1445
  }
1077
1446
  const idx = VaultIndex.load(vault);
1078
1447
  const res = await idx.refresh();
1079
- console.log(`${pc.green("\u2713")} \xCDndice al d\xEDa (${res.changed} reindexadas, ${Object.keys(idx.meta.notes).length} notas)
1080
- `);
1448
+ console.log(`${pc.green("\u2713")} \xCDndice al d\xEDa (${res.changed} reindexadas, ${Object.keys(idx.meta.notes).length} notas)`);
1449
+ if (idx.emb && idx.emb.length !== idx.meta.chunks.length * idx.meta.dim) {
1450
+ console.log(pc.yellow("\u26A0 Embeddings desalineados con el \xEDndice \u2014 corre `ale reindex --force`"));
1451
+ } else if (idx.emb) {
1452
+ console.log(`${pc.green("\u2713")} Embeddings alineados (${idx.meta.chunks.length} chunks)`);
1453
+ }
1454
+ try {
1455
+ const name = path5.basename(cwd);
1456
+ const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1457
+ const pkgM = fs5.statSync(path5.join(cwd, "package.json")).mtimeMs;
1458
+ const mapM = fs5.statSync(mapFile).mtimeMs;
1459
+ if (pkgM > mapM) {
1460
+ console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1461
+ } else {
1462
+ console.log(`${pc.green("\u2713")} Contexto del proyecto al d\xEDa (ale scan)`);
1463
+ }
1464
+ } catch {
1465
+ }
1466
+ const skillsRepoCfg = localSkillsRepo();
1467
+ if (skillsRepoCfg && !fs5.existsSync(skillsRepoCfg)) {
1468
+ console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1469
+ }
1470
+ console.log();
1081
1471
  });
1082
1472
  program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloque de CLAUDE.md y MCP del proyecto (no borra la b\xF3veda ni las notas)").option("--project", "quitar del proyecto (cwd)").action((opts) => {
1083
1473
  const cwd = process.cwd();
@@ -1088,14 +1478,14 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
1088
1478
  const claudeMd = removeClaudeMd(scope, cwd);
1089
1479
  if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
1090
1480
  if (opts.project) {
1091
- const mcpFile = path4.join(cwd, ".mcp.json");
1481
+ const mcpFile = path5.join(cwd, ".mcp.json");
1092
1482
  try {
1093
- const cfg = JSON.parse(fs4.readFileSync(mcpFile, "utf8"));
1483
+ const cfg = JSON.parse(fs5.readFileSync(mcpFile, "utf8"));
1094
1484
  if (cfg.mcpServers?.alexandria) {
1095
1485
  delete cfg.mcpServers.alexandria;
1096
1486
  if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
1097
- if (Object.keys(cfg).length === 0) fs4.rmSync(mcpFile, { force: true });
1098
- else fs4.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1487
+ if (Object.keys(cfg).length === 0) fs5.rmSync(mcpFile, { force: true });
1488
+ else fs5.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1099
1489
  console.log(pc.green("\u2713 MCP removido de .mcp.json"));
1100
1490
  }
1101
1491
  } catch {
@@ -9,12 +9,13 @@ import {
9
9
  } from "../chunk-DEDAOKAV.js";
10
10
  import {
11
11
  hybridSearch
12
- } from "../chunk-MEL3BE65.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-7G3NPKDO.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-7G3NPKDO.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,13 +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 titles = notes.filter((n) => n.type !== "prompt").sort((a, b) => (b.hits ?? 1) - (a.hits ?? 1)).slice(0, 25).map((n) => n.title);
62
+ const distilled = idx.notesByTag("note").length + idx.notesByTag("lesson").length;
63
+ if (map && distilled < 3) {
64
+ parts.push(
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.`
66
+ );
67
+ }
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) : [];
62
69
  if (titles.length > 0) {
63
70
  parts.push(`## La b\xF3veda ya tiene conocimiento sobre
64
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";
@@ -1,17 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- pkgVersion
4
- } from "../chunk-IQM5S5N4.js";
3
+ architectBlock,
4
+ pkgVersion,
5
+ planContext,
6
+ planQualityHints
7
+ } from "../chunk-T5VNBQEC.js";
5
8
  import {
6
9
  hybridSearch
7
- } from "../chunk-MEL3BE65.js";
10
+ } from "../chunk-AHBSZGSC.js";
8
11
  import {
9
12
  ensureVaultStructure,
10
- resolveVault
11
- } from "../chunk-DYCARGQR.js";
13
+ resolveVault,
14
+ toggleEnabled
15
+ } from "../chunk-TFQ7WSIB.js";
12
16
  import {
13
17
  VaultIndex
14
- } from "../chunk-7G3NPKDO.js";
18
+ } from "../chunk-AXUEYSNZ.js";
15
19
  import {
16
20
  createNote,
17
21
  setNoteStatus,
@@ -132,26 +136,32 @@ server.tool(
132
136
  );
133
137
  server.tool(
134
138
  "plan_create",
135
- 'PROTOCOLO paso 1 (solo tareas NO triviales \u2014 las simples resp\xF3ndelas directo, sin ceremonia): crea el plan con Definition of Done (criterios verificables de "terminado") y tareas numeradas. Verifica cada tarea con task_verify. El plan enfoca tu capacidad, no la limita; y deja huella reutilizable.',
139
+ "PROTOCOLO paso 1 (solo tareas NO triviales \u2014 las simples resp\xF3ndelas directo, sin ceremonia): crea el plan como un ARQUITECTO. Si el objetivo es vago, haz 2-3 preguntas de aclaraci\xF3n al usuario ANTES de crear el plan (qu\xE9 es \xE9xito, restricciones, alcance). DoD = criterios verificables por comando; tareas chicas y en orden de construcci\xF3n. Para planes grandes pasa `design` (stack/decisiones de arquitectura). La respuesta trae planes similares previos y lecciones \u2014 \xFAsalos para planear mejor. Verifica cada tarea con task_verify.",
136
140
  {
137
141
  title: z.string().describe('Nombre corto del objetivo, ej. "Login con Google"'),
138
142
  goal: z.string().describe("Qu\xE9 se quiere lograr, en una o dos frases"),
139
143
  dod: z.array(z.string()).describe("Definition of Done: criterios verificables de \xE9xito"),
140
- tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables")
144
+ tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables, en orden de construcci\xF3n"),
145
+ design: z.string().optional().describe('Decisiones de arquitectura/stack del plan (el "blueprint"): qu\xE9 se eligi\xF3 y por qu\xE9. Recomendado en planes de >5 tareas.')
141
146
  },
142
- async ({ title, goal, dod, tasks }) => {
147
+ async ({ title, goal, dod, tasks, design }) => {
143
148
  ensureVaultStructure(vault);
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) : [];
144
152
  const idx = VaultIndex.load(vault);
145
153
  const map = findMap(idx);
146
154
  const content = [
147
155
  `## Objetivo
148
156
  ${goal}`,
157
+ design?.trim() ? `## Dise\xF1o
158
+ ${design.trim()}` : "",
149
159
  `## Definition of Done
150
160
  ${dod.map((d) => `- [ ] ${d}`).join("\n")}`,
151
161
  `## Tareas
152
162
  ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
153
163
  map ? `Proyecto: [[${map.title}]]` : ""
154
- ].join("\n\n");
164
+ ].filter(Boolean).join("\n\n");
155
165
  const file = createNote(vault.managed, {
156
166
  title: `Plan - ${title}`,
157
167
  type: "plan",
@@ -162,8 +172,11 @@ ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
162
172
  });
163
173
  await VaultIndex.load(vault).refresh().catch(() => {
164
174
  });
175
+ const extra = architectBlock(ctx, hints);
165
176
  return text(
166
- `Plan guardado en ${path.relative(vault.root, file)}. Ejecuta las tareas UNA por una; tras cada una llama task_verify con evidencia real (salida de tests/build). Al terminar todo, llama lesson_extract.`
177
+ `Plan guardado en ${path.relative(vault.root, file)}. Ejecuta las tareas UNA por una; tras cada una llama task_verify con evidencia real (salida de tests/build). Al terminar todo, llama lesson_extract.` + (extra ? `
178
+
179
+ ${extra}` : "")
167
180
  );
168
181
  }
169
182
  );
@@ -4,8 +4,8 @@ import {
4
4
  renderGraphHtml,
5
5
  serveGraph,
6
6
  writeStaticGraph
7
- } from "./chunk-UTXUGXDB.js";
8
- import "./chunk-7G3NPKDO.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": "0.5.4",
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",