@ureck/alexandria 0.5.3 → 1.0.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
@@ -6,6 +6,8 @@
6
6
  [![license](https://img.shields.io/badge/license-MIT-green)](./LICENSE)
7
7
  [![Buy Me a Coffee](https://img.shields.io/badge/☕_Buy_me_a_coffee-ureck-yellow)](https://buymeacoffee.com/ureck)
8
8
 
9
+ [![docs](https://img.shields.io/badge/docs-ES%20%C2%B7%20EN-b8860b)](https://ureckchan.github.io/alexandria/) **[Documentation / Documentación](https://ureckchan.github.io/alexandria/)**
10
+
9
11
  Alexandria automatically captures your AI prompts and sessions, searches that knowledge **before** spending tokens, and connects everything in an Obsidian-style graph. **100% local**: no database, no API keys, no telemetry, no cost.
10
12
 
11
13
  Works with the most popular agents via MCP: **Claude Code · Cursor · OpenCode · Windsurf · Cline · Codex CLI · Gemini CLI · VS Code (Copilot) · OpenClaw · Hermes Agent**.
@@ -31,8 +33,8 @@ It lives in the MCP tools themselves — their names and descriptions carry the
31
33
 
32
34
  | MCP tool | What the agent does with it | Token payoff |
33
35
  |---|---|---|
34
- | `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 |
35
- | `task_verify(plan, task, passed, evidence)` | Records the real verdict of each task (test/build output, compacted) | "✅ 12/12 passed" (5 tokens) instead of a 500-line log; on failure it automatically surfaces **past lessons** that match |
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
+ | `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 |
36
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 |
37
39
 
38
40
  Lessons and solutions get a ranking boost in search, so the most valuable knowledge always surfaces first. The protocol is **on by default**; toggle it anytime:
@@ -61,7 +63,7 @@ Verify:
61
63
 
62
64
  ```bash
63
65
  $ ale --version
64
- 0.5.2
66
+ 1.0.0
65
67
  ```
66
68
 
67
69
  ## Getting started
@@ -130,6 +132,24 @@ ale add "Vercel deploy" -c "Region cdg1, see [[Prisma setup]]" -t deploy
130
132
 
131
133
  (Automatic capture via hooks already does this in every Claude Code session — `add` is for extra knowledge.)
132
134
 
135
+ ### Deep project context (`ale scan`)
136
+
137
+ `ale init --project` already runs it; re-run anytime the project changes:
138
+
139
+ ```bash
140
+ $ ale scan
141
+ ✓ API: 12 rutas · Env: 8 vars (solo nombres) · Datos: 5 · Convenciones: 4 · .gitignore ✓
142
+ ```
143
+
144
+ 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):
145
+
146
+ - **`API - <project>`** — App Router routes with HTTP methods, Pages Router handlers, `"use server"` actions, Express/Hono routes.
147
+ - **`Env - <project>`** — environment variable **NAMES only, never values** (from `.env.example` / `.env` / `.env.local`).
148
+ - **`Datos - <project>`** — data schema parsed from files (prisma models, drizzle tables, `CREATE TABLE` in migrations) — no DB connection.
149
+ - **`Convenciones - <project>`** — package manager, monorepo, TS strict, import aliases, framework.
150
+
151
+ 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`.
152
+
133
153
  ### Create a plan from a file
134
154
 
135
155
  Instead of typing a whole plan into the terminal, keep it as markdown in your repo:
@@ -257,15 +277,16 @@ AI agent session
257
277
  | Command | What it does |
258
278
  |---|---|
259
279
  | `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 |
260
281
  | `ale agents [ids] [--project]` | List agents / register the MCP server |
261
- | `ale search <query> [-k n] [--expand]` | Hybrid search; `--expand` pulls graph neighbors |
282
+ | `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 |
262
283
  | `ale add <title> [-c text] [--file <path>] [-t tags]` | Save a note (inline, from file, or stdin) |
263
- | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done) |
284
+ | `ale plan <file> [--title t]` | Create a Protocol plan from a .md/.txt file (checkboxes → Definition of Done); surfaces similar past plans + quality hints |
264
285
  | `ale graph [--out file.html] [--no-open]` | Live local graph viewer |
265
286
  | `ale audit` | Protocol health: plans without DoD, failures without lessons, orphan notes |
266
287
  | `ale stats` | Notes, connections, protocol metrics, estimated tokens saved |
267
288
  | `ale config <get\|set> <key> [value]` | Configuration (e.g. `protocol` true/false) |
268
- | `ale skills [-y] [--project]` | Recommends & installs Claude skills based on your patterns |
289
+ | `ale skills [-y] [--project]` | Recommends & installs Claude skills — semantic (e5) + keyword detection over your vault. Local source configurable with `ale config set skills.repo <path>`; otherwise installs from skills.sh |
269
290
  | `ale reindex [--force]` | Reindex (incremental by default) |
270
291
  | `ale consolidate [--days n] [--dry]` | Archive old unused prompts — never deletes |
271
292
  | `ale doctor [--project]` | Check & repair: model, hooks, MCP, index |
@@ -278,6 +299,7 @@ AI agent session
278
299
 
279
300
  - **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.
280
301
  - **No API keys, no accounts, no cost.**
302
+ - **`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.
281
303
  - 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.
282
304
  - 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.
283
305
 
@@ -50,20 +50,41 @@ var VaultIndex = class _VaultIndex {
50
50
  try {
51
51
  const buf = fs.readFileSync(idx.embPath);
52
52
  const arr = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);
53
- if (arr.length === meta.chunks.length * meta.dim) idx.emb = arr.slice();
53
+ if (arr.length === meta.chunks.length * meta.dim) {
54
+ idx.emb = arr.slice();
55
+ } else {
56
+ idx.emb = null;
57
+ try {
58
+ fs.rmSync(idx.embPath, { force: true });
59
+ } catch {
60
+ }
61
+ }
54
62
  } catch {
55
63
  idx.emb = null;
56
64
  }
57
65
  }
58
- } catch {
66
+ } catch (e) {
67
+ if (fs.existsSync(idx.metaPath)) {
68
+ try {
69
+ fs.rmSync(idx.metaPath, { force: true });
70
+ fs.rmSync(idx.embPath, { force: true });
71
+ } catch {
72
+ }
73
+ }
59
74
  }
60
75
  return idx;
61
76
  }
77
+ /** Escritura atómica: tmp + rename — un hook y un comando concurrentes nunca dejan el archivo a medias. */
78
+ writeAtomic(file, data) {
79
+ const tmp = `${file}.${process.pid}.tmp`;
80
+ fs.writeFileSync(tmp, data);
81
+ fs.renameSync(tmp, file);
82
+ }
62
83
  save() {
63
84
  fs.mkdirSync(this.vault.cache, { recursive: true });
64
- fs.writeFileSync(this.metaPath, JSON.stringify(this.meta));
85
+ this.writeAtomic(this.metaPath, JSON.stringify(this.meta));
65
86
  if (this.emb) {
66
- fs.writeFileSync(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
87
+ this.writeAtomic(this.embPath, Buffer.from(this.emb.buffer, this.emb.byteOffset, this.emb.byteLength));
67
88
  }
68
89
  }
69
90
  row(i) {
@@ -171,7 +192,7 @@ ${c.text}`),
171
192
  this.rebuildLinks();
172
193
  this.save();
173
194
  try {
174
- const { writeStaticGraph } = await import("./viewer-G3N57646.js");
195
+ const { writeStaticGraph } = await import("./viewer-73ZWPIDC.js");
175
196
  writeStaticGraph(this);
176
197
  } catch {
177
198
  }
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-7G3NPKDO.js";
4
+ } from "./chunk-D5ROL42O.js";
5
5
 
6
6
  // src/graph/viewer.ts
7
7
  import fs from "fs";
@@ -1,4 +1,60 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ hybridSearch
4
+ } from "./chunk-RZI7TYAG.js";
5
+
6
+ // src/core/planning.ts
7
+ async function planContext(vault, query) {
8
+ const out = { similarPlans: [], lessons: [] };
9
+ try {
10
+ const results = await hybridSearch(vault, query, 8);
11
+ 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) {
16
+ out.lessons.push(`\xAB${r.note.title}\xBB: ${excerpt}`);
17
+ }
18
+ }
19
+ } catch {
20
+ }
21
+ return out;
22
+ }
23
+ var FAT_TASK_CHARS = 140;
24
+ function planQualityHints(dod, tasks, design) {
25
+ 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
+ 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;
41
+ }
42
+ function architectBlock(ctx, hints) {
43
+ 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");
57
+ }
2
58
 
3
59
  // src/core/register.ts
4
60
  import fs from "fs";
@@ -128,6 +184,9 @@ function pkgVersion() {
128
184
  }
129
185
 
130
186
  export {
187
+ planContext,
188
+ planQualityHints,
189
+ architectBlock,
131
190
  distDir,
132
191
  registerHooks,
133
192
  unregisterHooks,
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-7G3NPKDO.js";
4
+ } from "./chunk-D5ROL42O.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -118,7 +118,32 @@ async function hybridSearch(vault, query, k = 6, opts = {}) {
118
118
  }
119
119
  return results;
120
120
  }
121
+ function protocolChain(vault, rel, maxNotes = 6) {
122
+ const idx = VaultIndex.load(vault);
123
+ if (!idx.meta.notes[rel]) return [];
124
+ const wanted = /* @__PURE__ */ new Set(["plan", "task", "verification", "lesson", "solution"]);
125
+ const seen = /* @__PURE__ */ new Set([rel]);
126
+ const out = [];
127
+ let frontier = [rel];
128
+ for (let depth = 0; depth < 2 && out.length < maxNotes; depth++) {
129
+ const next = [];
130
+ for (const r of frontier) {
131
+ for (const nb of idx.neighbors(r)) {
132
+ if (seen.has(nb.note.rel)) continue;
133
+ seen.add(nb.note.rel);
134
+ next.push(nb.note.rel);
135
+ if (wanted.has(nb.note.type)) out.push(nb.note);
136
+ if (out.length >= maxNotes) break;
137
+ }
138
+ if (out.length >= maxNotes) break;
139
+ }
140
+ frontier = next;
141
+ }
142
+ const rank = { plan: 0, verification: 1, lesson: 2, solution: 3, task: 4 };
143
+ return out.sort((a, b) => (rank[a.type] ?? 9) - (rank[b.type] ?? 9));
144
+ }
121
145
 
122
146
  export {
123
- hybridSearch
147
+ hybridSearch,
148
+ protocolChain
124
149
  };
package/dist/cli.js CHANGED
@@ -3,25 +3,30 @@ 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-DHXL36RG.js";
17
20
  import {
18
- hybridSearch
19
- } from "./chunk-3ETM6PKR.js";
21
+ hybridSearch,
22
+ protocolChain
23
+ } from "./chunk-RZI7TYAG.js";
20
24
  import {
21
25
  defaultVaultPath,
22
26
  ensureVaultStructure,
23
27
  getConfigKey,
24
28
  globalConfigPath,
29
+ protocolEnabled,
25
30
  resolveVault,
26
31
  setConfigKey,
27
32
  vaultExists,
@@ -30,10 +35,10 @@ import {
30
35
  } from "./chunk-DYCARGQR.js";
31
36
  import {
32
37
  serveGraph
33
- } from "./chunk-UTXUGXDB.js";
38
+ } from "./chunk-DCKYTO4O.js";
34
39
  import {
35
40
  VaultIndex
36
- } from "./chunk-7G3NPKDO.js";
41
+ } from "./chunk-D5ROL42O.js";
37
42
  import {
38
43
  createNote,
39
44
  slugify,
@@ -41,13 +46,15 @@ import {
41
46
  } from "./chunk-XWR74BQ2.js";
42
47
  import {
43
48
  MODEL_ID,
49
+ dot,
50
+ embed,
44
51
  getEmbedder,
45
52
  modelPresent
46
53
  } from "./chunk-EDYBSJSS.js";
47
54
 
48
55
  // src/cli.ts
49
- import fs4 from "fs";
50
- import path4 from "path";
56
+ import fs5 from "fs";
57
+ import path5 from "path";
51
58
  import readline from "readline/promises";
52
59
  import { Command } from "commander";
53
60
  import pc from "picocolors";
@@ -58,27 +65,35 @@ import os from "os";
58
65
  import path from "path";
59
66
  import { execFileSync } from "child_process";
60
67
  var RULES = [
61
- { skill: "pdf-report-gen", keywords: ["pdf", "reporte pdf", "membrete"] },
62
- { skill: "excel-report-gen", keywords: ["excel", "xlsx", "spreadsheet", "hoja de calculo", "hoja de c\xE1lculo"] },
63
- { skill: "qr-checkin", keywords: ["qr", "codigo qr", "c\xF3digo qr", "check-in", "checkin"] },
64
- { skill: "auth-standard", keywords: ["auth", "login", "jwt", "sesion", "autenticacion", "autenticaci\xF3n"] },
65
- { skill: "prisma-workflow", keywords: ["prisma", "migracion", "migraci\xF3n", "orm"] },
66
- { skill: "flutter-offline-scaffold", keywords: ["flutter", "dart", "riverpod", "drift"] },
67
- { skill: "mapbox-geo", keywords: ["mapbox", "geolocalizacion", "geolocalizaci\xF3n", "geocode", "leaflet"] },
68
- { skill: "spanish-form-validation", keywords: ["curp", "rfc", "zod", "validacion", "validaci\xF3n", "formulario"] },
69
- { skill: "testing-ci-setup", keywords: ["vitest", "playwright", "test", "ci", "github actions"] },
70
- { skill: "tiptap-rich-text", keywords: ["tiptap", "editor de texto", "wysiwyg", "rich text"] },
71
- { skill: "signature-upload-optimizer", keywords: ["firma", "signature", "compress", "upload", "subir foto"] },
72
- { skill: "security-headers-baseline", keywords: ["csp", "security headers", "hsts", "seguridad web"] },
73
- { skill: "server-state-standard", keywords: ["react-query", "tanstack", "zustand", "estado"] },
74
- { skill: "nextjs-folder-structure", keywords: ["next.js", "nextjs", "app router"] }
68
+ { skill: "pdf-report-gen", desc: "generar documentos y reportes PDF con membrete", keywords: ["pdf", "reporte pdf", "membrete"] },
69
+ { skill: "excel-report-gen", desc: "exportar e importar hojas de c\xE1lculo Excel xlsx", keywords: ["excel", "xlsx", "spreadsheet", "hoja de calculo", "hoja de c\xE1lculo"] },
70
+ { skill: "qr-checkin", desc: "generar y escanear c\xF3digos QR para check-in y tickets", keywords: ["qr", "codigo qr", "c\xF3digo qr", "check-in", "checkin"] },
71
+ { skill: "auth-standard", desc: "autenticaci\xF3n con login, JWT y sesiones seguras", keywords: ["auth", "login", "jwt", "sesion", "autenticacion", "autenticaci\xF3n"] },
72
+ { skill: "prisma-workflow", desc: "ORM Prisma, modelos, migraciones y seed de base de datos", keywords: ["prisma", "migracion", "migraci\xF3n", "orm"] },
73
+ { skill: "flutter-offline-scaffold", desc: "app Flutter offline-first con riverpod y base de datos local", keywords: ["flutter", "dart", "riverpod", "drift"] },
74
+ { skill: "mapbox-geo", desc: "mapas, marcadores y geolocalizaci\xF3n con Mapbox", keywords: ["mapbox", "geolocalizacion", "geolocalizaci\xF3n", "geocode", "leaflet"] },
75
+ { skill: "spanish-form-validation", desc: "validaci\xF3n de formularios con Zod, CURP, RFC y tel\xE9fono mexicano", keywords: ["curp", "rfc", "zod", "validacion", "validaci\xF3n", "formulario"] },
76
+ { skill: "testing-ci-setup", desc: "pruebas automatizadas con vitest, Playwright y CI en GitHub Actions", keywords: ["vitest", "playwright", "test", "ci", "github actions"] },
77
+ { skill: "tiptap-rich-text", desc: "editor de texto enriquecido WYSIWYG con tiptap y plantillas", keywords: ["tiptap", "editor de texto", "wysiwyg", "rich text"] },
78
+ { skill: "signature-upload-optimizer", desc: "captura de firma en canvas y compresi\xF3n de im\xE1genes antes de subir", keywords: ["firma", "signature", "compress", "upload", "subir foto"] },
79
+ { skill: "security-headers-baseline", desc: "cabeceras de seguridad web CSP, HSTS y X-Frame-Options", keywords: ["csp", "security headers", "hsts", "seguridad web"] },
80
+ { skill: "server-state-standard", desc: "estado del servidor con react-query TanStack y zustand para UI", keywords: ["react-query", "tanstack", "zustand", "estado"] },
81
+ { skill: "nextjs-folder-structure", desc: "estructura de carpetas y organizaci\xF3n de un proyecto Next.js App Router", keywords: ["next.js", "nextjs", "app router"] }
75
82
  ];
76
83
  var MIN_MENTIONS = 3;
84
+ var SEM_Z_STRONG = 1.5;
85
+ var SEM_Z_WEAK = 1;
77
86
  function localSkillsRepo() {
78
- return path.join(os.homedir(), "Documents", "Projects", "Skills");
87
+ const configured = getConfigKey("skills.repo");
88
+ if (typeof configured === "string" && configured.trim()) {
89
+ return configured.trim().replace(/^~(?=$|[/\\])/, os.homedir());
90
+ }
91
+ return null;
79
92
  }
80
- function recommendSkills(vault, installedDirs) {
93
+ async function recommendSkills(vault, installedDirs) {
81
94
  const idx = VaultIndex.load(vault);
95
+ await idx.refresh().catch(() => {
96
+ });
82
97
  const corpus = (idx.meta.chunks.map((c) => c.text).join("\n") + "\n" + Object.values(idx.meta.notes).map((n) => `${n.title} ${n.tags.join(" ")}`).join("\n")).toLowerCase();
83
98
  const installed = /* @__PURE__ */ new Set();
84
99
  for (const dir of installedDirs) {
@@ -87,9 +102,30 @@ function recommendSkills(vault, installedDirs) {
87
102
  } catch {
88
103
  }
89
104
  }
105
+ let semZByRule = null;
106
+ if (idx.emb && idx.meta.chunks.length > 0 && modelPresent()) {
107
+ try {
108
+ const profiles = RULES.map((r) => `${r.skill.replace(/-/g, " ")}. ${r.desc} ${r.keywords.join(" ")}`);
109
+ const vecs = await embed(profiles, "query");
110
+ const best = vecs.map((v) => {
111
+ let m = 0;
112
+ for (let i = 0; i < idx.meta.chunks.length; i++) {
113
+ const s = dot(v, idx.row(i));
114
+ if (s > m) m = s;
115
+ }
116
+ return m;
117
+ });
118
+ const mean = best.reduce((a, b) => a + b, 0) / best.length;
119
+ const std = Math.sqrt(best.reduce((a, b) => a + (b - mean) ** 2, 0) / best.length);
120
+ semZByRule = std > 1e-6 ? best.map((b) => (b - mean) / std) : null;
121
+ } catch {
122
+ semZByRule = null;
123
+ }
124
+ }
125
+ const repo = localSkillsRepo();
90
126
  const out = [];
91
- for (const rule of RULES) {
92
- if (installed.has(rule.skill)) continue;
127
+ RULES.forEach((rule, ri) => {
128
+ if (installed.has(rule.skill)) return;
93
129
  let mentions = 0;
94
130
  const found = [];
95
131
  for (const kw of rule.keywords) {
@@ -98,26 +134,36 @@ function recommendSkills(vault, installedDirs) {
98
134
  if (count > 0) found.push(kw);
99
135
  mentions += count;
100
136
  }
101
- if (mentions >= MIN_MENTIONS) {
102
- const local = fs.existsSync(path.join(localSkillsRepo(), rule.skill));
103
- out.push({
104
- skill: rule.skill,
105
- mentions,
106
- reason: `detect\xE9 ${mentions} menciones de ${found.slice(0, 3).join(", ")} en la b\xF3veda`,
107
- source: local ? "local" : "skills.sh"
108
- });
109
- }
110
- }
111
- return out.sort((a, b) => b.mentions - a.mentions);
137
+ const semZ = semZByRule ? semZByRule[ri] : 0;
138
+ const semStrong = semZ >= SEM_Z_WEAK;
139
+ const qualifies = mentions >= MIN_MENTIONS || mentions >= 1 && semZ >= SEM_Z_WEAK || semZ >= SEM_Z_STRONG;
140
+ if (!qualifies) return;
141
+ const local = repo ? fs.existsSync(path.join(repo, rule.skill)) : false;
142
+ const parts = [];
143
+ if (found.length) parts.push(`${mentions} menciones de ${found.slice(0, 3).join(", ")}`);
144
+ if (semStrong) parts.push(`afinidad sem\xE1ntica alta (z=${semZ.toFixed(1)})`);
145
+ out.push({
146
+ skill: rule.skill,
147
+ mentions,
148
+ // el z-score reordena: una skill que sobresale semánticamente sube aunque
149
+ // tenga pocas menciones literales
150
+ score: mentions + (semStrong ? Math.min(semZ, 4) * 1.5 : 0),
151
+ reason: parts.length ? `detect\xE9 ${parts.join(" + ")} en la b\xF3veda` : `afinidad sem\xE1ntica (z=${semZ.toFixed(1)})`,
152
+ source: local ? "local" : "skills.sh"
153
+ });
154
+ });
155
+ return out.sort((a, b) => b.score - a.score);
112
156
  }
113
157
  function installSkill(rec, targetDir) {
114
158
  fs.mkdirSync(targetDir, { recursive: true });
115
159
  const dest = path.join(targetDir, rec.skill);
116
160
  if (fs.existsSync(dest)) return { ok: true, detail: "ya instalada" };
117
161
  if (rec.source === "local") {
162
+ const repo = localSkillsRepo();
163
+ if (!repo) return { ok: false, detail: "repo local no configurado (ale config set skills.repo <ruta>)" };
118
164
  try {
119
- fs.cpSync(path.join(localSkillsRepo(), rec.skill), dest, { recursive: true });
120
- return { ok: true, detail: `copiada desde ${localSkillsRepo()}` };
165
+ fs.cpSync(path.join(repo, rec.skill), dest, { recursive: true });
166
+ return { ok: true, detail: `copiada desde ${repo}` };
121
167
  } catch (e) {
122
168
  return { ok: false, detail: `error copiando: ${e.message}` };
123
169
  }
@@ -499,6 +545,8 @@ function configureClaudeMd(scope, projectDir) {
499
545
  "- ANTES de explorar c\xF3digo o re-derivar contexto: busca con la tool MCP `vault_search`; si la b\xF3veda ya lo sabe, \xFAsalo.",
500
546
  "- 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.",
501
547
  "- Al descubrir arquitectura o decisiones: `vault_save` (con `[[wikilinks]]`; el t\xEDtulo `Mapa - <proyecto>` actualiza el mapa que se inyecta al iniciar sesi\xF3n).",
548
+ "- 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.",
549
+ "- 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.",
502
550
  "- `vault_related` trae conocimiento conectado sin releer archivos.",
503
551
  CLAUDE_MD_END
504
552
  ].join("\n");
@@ -591,6 +639,247 @@ ${readme.split("\n").slice(0, 15).join("\n")}`);
591
639
  });
592
640
  }
593
641
 
642
+ // src/core/scan.ts
643
+ import fs4 from "fs";
644
+ import path4 from "path";
645
+ var SKIP_DIRS2 = /* @__PURE__ */ new Set([
646
+ "node_modules",
647
+ ".git",
648
+ ".next",
649
+ "dist",
650
+ "build",
651
+ ".vault",
652
+ ".claude",
653
+ "coverage",
654
+ "Alexandria",
655
+ "KnowledgeVault",
656
+ ".turbo",
657
+ ".vercel",
658
+ "out",
659
+ "vendor"
660
+ ]);
661
+ var SOURCE_EXT = /* @__PURE__ */ new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"]);
662
+ var MAX_FILES = 400;
663
+ var MAX_FILE_BYTES = 64 * 1024;
664
+ var MAX_ENTRIES = 80;
665
+ 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;
674
+ }
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 {
689
+ }
690
+ }
691
+ }
692
+ };
693
+ walk(projectDir, 0);
694
+ return out;
695
+ }
696
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
697
+ function appRoutePath(rel) {
698
+ const m = rel.match(/(?:^|\/)app\/(.*)route\.[tj]sx?$/);
699
+ if (!m) return "";
700
+ const segs = m[1].split("/").filter((s) => s && !/^\(.*\)$/.test(s));
701
+ return "/" + segs.join("/").replace(/\/$/, "");
702
+ }
703
+ function scanApi(files) {
704
+ const lines = [];
705
+ for (const f of files) {
706
+ if (lines.length >= MAX_ENTRIES) break;
707
+ if (/(^|\/)route\.[tj]sx?$/.test(f.rel) && /(^|\/)app\//.test(f.rel)) {
708
+ const methods = HTTP_METHODS.filter(
709
+ (m) => new RegExp(`export\\s+(?:async\\s+)?(?:function\\s+${m}\\b|const\\s+${m}\\s*=)`).test(f.content)
710
+ );
711
+ if (methods.length) lines.push(`- ${methods.join("/")} ${appRoutePath(f.rel)} \u2014 ${f.rel}`);
712
+ continue;
713
+ }
714
+ const pagesApi = f.rel.match(/(?:^|\/)pages\/api\/(.+)\.[tj]sx?$/);
715
+ if (pagesApi) {
716
+ lines.push(`- handler /api/${pagesApi[1].replace(/\/index$/, "")} \u2014 ${f.rel}`);
717
+ continue;
718
+ }
719
+ if (/^\s*['"]use server['"]/m.test(f.content.slice(0, 400))) {
720
+ const fns = [...f.content.matchAll(/export\s+(?:async\s+)?function\s+(\w+)/g)].map((m) => m[1]);
721
+ if (fns.length) lines.push(`- server actions: ${fns.slice(0, 8).join(", ")} \u2014 ${f.rel}`);
722
+ continue;
723
+ }
724
+ const expressHits = [...f.content.matchAll(/\b(?:app|router|api)\.(get|post|put|patch|delete)\(\s*['"`]([^'"`]+)['"`]/g)];
725
+ for (const h of expressHits.slice(0, 12)) {
726
+ lines.push(`- ${h[1].toUpperCase()} ${h[2]} \u2014 ${f.rel}`);
727
+ if (lines.length >= MAX_ENTRIES) break;
728
+ }
729
+ }
730
+ return lines.slice(0, MAX_ENTRIES);
731
+ }
732
+ function scanEnvNames(projectDir) {
733
+ const seen = /* @__PURE__ */ new Map();
734
+ for (const file of [".env.example", ".env", ".env.local"]) {
735
+ let text;
736
+ try {
737
+ text = fs4.readFileSync(path4.join(projectDir, file), "utf8");
738
+ } catch {
739
+ continue;
740
+ }
741
+ for (const line of text.split("\n")) {
742
+ const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
743
+ if (m && !seen.has(m[1])) seen.set(m[1], file);
744
+ }
745
+ }
746
+ return [...seen.entries()].slice(0, MAX_ENTRIES).map(([name, src]) => `- ${name} (${src})`);
747
+ }
748
+ function scanDataSchema(projectDir, files) {
749
+ const lines = [];
750
+ try {
751
+ const schema = fs4.readFileSync(path4.join(projectDir, "prisma", "schema.prisma"), "utf8");
752
+ for (const m of schema.matchAll(/model\s+(\w+)\s*\{([^}]*)\}/g)) {
753
+ const fields = m[2].split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("@@") && !l.startsWith("//")).map((l) => l.split(/\s+/)[0]);
754
+ const shown = fields.slice(0, 8).join(", ");
755
+ lines.push(`- model ${m[1]}: ${shown}${fields.length > 8 ? ` (+${fields.length - 8})` : ""} \u2014 prisma/schema.prisma`);
756
+ }
757
+ } catch {
758
+ }
759
+ for (const f of files.filter((x) => /schema/i.test(x.rel))) {
760
+ for (const m of f.content.matchAll(/\b(?:pg|mysql|sqlite)Table\(\s*['"`](\w+)['"`]/g)) {
761
+ lines.push(`- table ${m[1]} (drizzle) \u2014 ${f.rel}`);
762
+ }
763
+ }
764
+ const migDirs = ["migrations", "db/migrations", "drizzle", "supabase/migrations"];
765
+ for (const dir of migDirs) {
766
+ let sqlFiles = [];
767
+ try {
768
+ sqlFiles = fs4.readdirSync(path4.join(projectDir, dir)).filter((f) => f.endsWith(".sql")).slice(0, 30);
769
+ } catch {
770
+ continue;
771
+ }
772
+ const tables = /* @__PURE__ */ new Set();
773
+ for (const f of sqlFiles) {
774
+ try {
775
+ const sql = fs4.readFileSync(path4.join(projectDir, dir, f), "utf8");
776
+ for (const m of sql.matchAll(/CREATE TABLE (?:IF NOT EXISTS )?["'`]?(\w+)/gi)) tables.add(m[1]);
777
+ } catch {
778
+ }
779
+ }
780
+ if (tables.size) lines.push(`- tablas (${dir}/*.sql): ${[...tables].slice(0, 20).join(", ")}`);
781
+ }
782
+ return lines.slice(0, MAX_ENTRIES);
783
+ }
784
+ function scanConventions(projectDir) {
785
+ const lines = [];
786
+ const has = (f) => fs4.existsSync(path4.join(projectDir, f));
787
+ const pm = has("bun.lockb") || has("bun.lock") ? "bun" : has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("package-lock.json") ? "npm" : null;
788
+ if (pm) lines.push(`- gestor de paquetes: ${pm}`);
789
+ let pkg = {};
790
+ try {
791
+ pkg = JSON.parse(fs4.readFileSync(path4.join(projectDir, "package.json"), "utf8"));
792
+ } catch {
793
+ }
794
+ if (pkg.workspaces || has("pnpm-workspace.yaml") || has("turbo.json")) lines.push("- monorepo: s\xED (workspaces)");
795
+ try {
796
+ const ts = JSON.parse(fs4.readFileSync(path4.join(projectDir, "tsconfig.json"), "utf8"));
797
+ const co = ts.compilerOptions ?? {};
798
+ lines.push(`- TypeScript${co.strict ? " strict" : ""}`);
799
+ const paths = Object.keys(co.paths ?? {}).slice(0, 5);
800
+ if (paths.length) lines.push(`- alias de imports: ${paths.join(", ")}`);
801
+ } catch {
802
+ }
803
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
804
+ const fw = [];
805
+ if (deps?.next) fw.push("Next.js");
806
+ if (deps?.astro) fw.push("Astro");
807
+ if (deps?.expo || deps?.["react-native"]) fw.push("React Native/Expo");
808
+ if (deps?.hono) fw.push("Hono");
809
+ if (deps?.express) fw.push("Express");
810
+ if (deps?.["@nestjs/core"]) fw.push("NestJS");
811
+ if (deps?.vue) fw.push("Vue");
812
+ if (deps?.svelte) fw.push("Svelte");
813
+ if (fw.length) lines.push(`- framework: ${fw.join(", ")}`);
814
+ return lines;
815
+ }
816
+ function linkMapToScans(vault, name, titles) {
817
+ if (titles.length === 0) return;
818
+ const mapFile = path4.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
819
+ try {
820
+ const text = fs4.readFileSync(mapFile, "utf8");
821
+ if (text.includes("Contexto ampliado:")) return;
822
+ fs4.appendFileSync(mapFile, `
823
+ Contexto ampliado: ${titles.map((t) => `[[${t}]]`).join(" \xB7 ")}
824
+ `);
825
+ } catch {
826
+ }
827
+ }
828
+ function scanAll(vault, projectDir) {
829
+ const name = path4.basename(projectDir);
830
+ const gitignored = ensureGitignore(projectDir, vault.root) !== null;
831
+ try {
832
+ untrackPersonalConfigs(projectDir);
833
+ } catch {
834
+ }
835
+ try {
836
+ scanProject(vault, projectDir);
837
+ } catch {
838
+ }
839
+ let files = [];
840
+ try {
841
+ files = collectSourceFiles(projectDir);
842
+ } catch {
843
+ }
844
+ const run = (fn) => {
845
+ try {
846
+ return fn();
847
+ } catch {
848
+ return [];
849
+ }
850
+ };
851
+ const api = run(() => scanApi(files));
852
+ const env = run(() => scanEnvNames(projectDir));
853
+ const data = run(() => scanDataSchema(projectDir, files));
854
+ const conventions = run(() => scanConventions(projectDir));
855
+ const notes = [];
856
+ const titles = [];
857
+ const write = (kind, title, header, lines) => {
858
+ if (lines.length === 0) return;
859
+ notes.push(
860
+ upsertNote(vault.managed, {
861
+ fixedName: `${kind}-${slugify(name)}`,
862
+ title,
863
+ type: "map",
864
+ tags: [name, kind],
865
+ dir: "notes",
866
+ content: `${header}
867
+
868
+ ${lines.join("\n")}
869
+
870
+ Proyecto: [[Mapa - ${name}]]`
871
+ })
872
+ );
873
+ titles.push(title);
874
+ };
875
+ write("api", `API - ${name}`, `Rutas y server actions detectadas por \`ale scan\` (regenerable).`, api);
876
+ write("env", `Env - ${name}`, `Variables de entorno (SOLO nombres \u2014 los valores nunca se guardan).`, env);
877
+ write("datos", `Datos - ${name}`, `Esquema de datos detectado en archivos (sin conexi\xF3n a BD).`, data);
878
+ write("convenciones", `Convenciones - ${name}`, `Convenciones detectadas por \`ale scan\`.`, conventions);
879
+ linkMapToScans(vault, name, titles);
880
+ return { api: api.length, env: env.length, data: data.length, conventions: conventions.length, notes, gitignored };
881
+ }
882
+
594
883
  // src/cli.ts
595
884
  function registerAgentsMcp(agents, scope, cwd, portable = false) {
596
885
  for (const agent of agents) {
@@ -653,7 +942,7 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
653
942
  ).action(async (opts) => {
654
943
  const isProject = Boolean(opts.project) && !opts.global;
655
944
  const cwd = process.cwd();
656
- const vaultPath = path4.resolve(opts.path ?? (isProject ? path4.join(cwd, "Alexandria") : defaultVaultPath()));
945
+ const vaultPath = path5.resolve(opts.path ?? (isProject ? path5.join(cwd, "Alexandria") : defaultVaultPath()));
657
946
  await showBanner();
658
947
  console.log(pc.bold(`Instalaci\xF3n ${isProject ? "por proyecto" : "global"}
659
948
  `));
@@ -711,8 +1000,8 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
711
1000
  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")
712
1001
  );
713
1002
  if (isProject) {
714
- const map = scanProject(vault, cwd);
715
- if (map) console.log(pc.green(`\u2713 Proyecto escaneado \u2192 ${path4.relative(vault.root, map)} (mapa inicial)`));
1003
+ const s = scanAll(vault, cwd);
1004
+ console.log(pc.green(`\u2713 Proyecto escaneado \u2192 API: ${s.api} \xB7 Env: ${s.env} \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions} (re-ejecuta con: ale scan)`));
716
1005
  }
717
1006
  await downloadModelIfMissing();
718
1007
  const idx = VaultIndex.load(vault);
@@ -725,10 +1014,10 @@ program.command("init").description("Crea/conecta la b\xF3veda e instala TODO: m
725
1014
  });
726
1015
  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) => {
727
1016
  const { vault } = await ensureReady();
728
- const abs = path4.resolve(file);
729
- const raw = fs4.readFileSync(abs, "utf8");
1017
+ const abs = path5.resolve(file);
1018
+ const raw = fs5.readFileSync(abs, "utf8");
730
1019
  const heading = raw.match(/^#\s+(.+)$/m)?.[1]?.trim();
731
- const title = opts.title ?? heading ?? path4.basename(abs).replace(/\.(md|txt)$/i, "");
1020
+ const title = opts.title ?? heading ?? path5.basename(abs).replace(/\.(md|txt)$/i, "");
732
1021
  const dod = [...raw.matchAll(/^[-*]\s*\[[ x]\]\s*(.+)$/gim)].map((m) => m[1].trim());
733
1022
  const noteFile = createNote(vault.managed, {
734
1023
  title: title.startsWith("Plan - ") ? title : `Plan - ${title}`,
@@ -738,11 +1027,15 @@ program.command("plan").description("Crear un plan del Protocolo desde un archiv
738
1027
  content: raw.trim()
739
1028
  });
740
1029
  await VaultIndex.load(vault).refresh();
741
- console.log(pc.green(`\u2713 Plan creado: ${path4.relative(vault.root, noteFile)}`));
1030
+ console.log(pc.green(`\u2713 Plan creado: ${path5.relative(vault.root, noteFile)}`));
742
1031
  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)'}`));
743
1032
  console.log(pc.dim(" El agente lo ver\xE1 como plan abierto al iniciar sesi\xF3n y lo retomar\xE1 con task_verify."));
1033
+ const tasks = [...raw.matchAll(/^\s*\d+[.)]\s+(.+)$/gm)].map((m) => m[1].trim());
1034
+ const ctx = await planContext(vault, title);
1035
+ const block = architectBlock(ctx, planQualityHints(dod, tasks));
1036
+ if (block) console.log(pc.dim("\n" + block.split("\n").map((l) => " " + l).join("\n")));
744
1037
  });
745
- program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD, planes abiertos, fallos sin lecci\xF3n, notas sueltas").action(async () => {
1038
+ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD, planes abiertos, fallos sin lecci\xF3n, verificaciones auto-reportadas, notas sueltas").action(async () => {
746
1039
  const { vault, idx } = await ensureReady();
747
1040
  const notes = Object.values(idx.meta.notes).filter((n) => !n.rel.split("/").includes("archive"));
748
1041
  const plans = notes.filter((n) => n.type === "plan");
@@ -758,19 +1051,25 @@ program.command("audit").description("Auditor\xEDa del Protocolo: planes sin DoD
758
1051
  console.log(pc.yellow(` \u26A0 Planes sin Definition of Done: ${noDod.length}`));
759
1052
  for (const p of noDod.slice(0, 5)) console.log(pc.dim(` - ${p.title}`));
760
1053
  }
761
- const fails = notes.filter((n) => n.type === "verification" && n.status === "failed");
1054
+ const verifs = notes.filter((n) => n.type === "verification");
1055
+ const fails = verifs.filter((n) => n.status === "failed");
762
1056
  const lessons = notes.filter((n) => n.type === "lesson");
763
- console.log(` Verificaciones: ${notes.filter((n) => n.type === "verification").length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
1057
+ console.log(` Verificaciones: ${verifs.length} (${pc.red(`${fails.length} fallos`)}) \xB7 Lecciones: ${pc.green(String(lessons.length))}`);
764
1058
  if (fails.length > lessons.length) {
765
1059
  console.log(pc.yellow(` \u26A0 Hay m\xE1s fallos (${fails.length}) que lecciones (${lessons.length}) \u2014 fallos resueltos sin destilar aprendizaje.`));
766
1060
  }
1061
+ const selfReported = verifs.filter((n) => n.tags.includes("auto-reportado"));
1062
+ if (selfReported.length > 0) {
1063
+ console.log(pc.yellow(` \u26A0 Verificaciones auto-reportadas (sin ejecutar \u2014 no comprobadas): ${selfReported.length} \u2014 re-verifica con task_verify + verify_command.`));
1064
+ for (const v of selfReported.slice(0, 5)) console.log(pc.dim(` - ${v.title}`));
1065
+ }
767
1066
  const loose = notes.filter((n) => n.type !== "prompt" && n.type !== "session" && !linked.has(n.rel));
768
1067
  if (loose.length > 0) {
769
1068
  console.log(pc.yellow(` \u26A0 Notas sin conexiones (invisibles para vault_related): ${loose.length}`));
770
1069
  for (const n of loose.slice(0, 5)) console.log(pc.dim(` - ${n.title} \u2192 con\xE9ctala con vault_link o [[wikilinks]]`));
771
1070
  }
772
- if (noDod.length === 0 && loose.length === 0 && fails.length <= lessons.length) {
773
- console.log(pc.green("\n \u2713 B\xF3veda sana: planes con DoD, conocimiento conectado, fallos con lecci\xF3n."));
1071
+ if (noDod.length === 0 && loose.length === 0 && fails.length <= lessons.length && selfReported.length === 0) {
1072
+ console.log(pc.green("\n \u2713 B\xF3veda sana: planes con DoD, verificaciones reales, conocimiento conectado, fallos con lecci\xF3n."));
774
1073
  }
775
1074
  console.log();
776
1075
  });
@@ -799,21 +1098,21 @@ program.command("consolidate").description("Archiva prompts viejos sin reuso: sa
799
1098
  console.log(pc.dim("Nada que consolidar: sin prompts viejos sin uso."));
800
1099
  return;
801
1100
  }
802
- const archiveDir = path4.join(vault.managed, "archive");
803
- if (!opts.dry) fs4.mkdirSync(archiveDir, { recursive: true });
1101
+ const archiveDir = path5.join(vault.managed, "archive");
1102
+ if (!opts.dry) fs5.mkdirSync(archiveDir, { recursive: true });
804
1103
  for (const n of stale) {
805
1104
  console.log(
806
1105
  `${opts.dry ? pc.yellow("se archivar\xEDa") : pc.cyan("archivado")} ${n.rel} ${pc.dim(`(${(n.created ?? "").slice(0, 10)}, hits ${n.hits})`)}`
807
1106
  );
808
1107
  if (!opts.dry) {
809
- fs4.renameSync(path4.join(vault.root, n.rel), path4.join(archiveDir, path4.basename(n.rel)));
1108
+ fs5.renameSync(path5.join(vault.root, n.rel), path5.join(archiveDir, path5.basename(n.rel)));
810
1109
  }
811
1110
  }
812
1111
  if (!opts.dry) {
813
1112
  await VaultIndex.load(vault).refresh();
814
1113
  console.log(
815
1114
  pc.green(`
816
- \u2713 ${stale.length} prompts archivados en ${path4.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
1115
+ \u2713 ${stale.length} prompts archivados en ${path5.relative(vault.root, archiveDir)}/ \u2014 fuera del grafo, siguen buscables. Nada se pierde.`)
817
1116
  );
818
1117
  } else {
819
1118
  console.log(pc.dim(`
@@ -844,10 +1143,10 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
844
1143
  const { vault } = await ensureReady();
845
1144
  let content = opts.content;
846
1145
  if (!content && opts.file) {
847
- content = fs4.readFileSync(path4.resolve(opts.file), "utf8");
1146
+ content = fs5.readFileSync(path5.resolve(opts.file), "utf8");
848
1147
  }
849
1148
  if (!content && !process.stdin.isTTY) {
850
- content = fs4.readFileSync(0, "utf8");
1149
+ content = fs5.readFileSync(0, "utf8");
851
1150
  }
852
1151
  const file = createNote(vault.managed, {
853
1152
  title,
@@ -855,7 +1154,7 @@ program.command("add").description("Guardar una nota manualmente").argument("<ti
855
1154
  tags: opts.tags ? opts.tags.split(",").map((t) => t.trim()) : []
856
1155
  });
857
1156
  await VaultIndex.load(vault).refresh();
858
- console.log(pc.green(`\u2713 ${path4.relative(vault.root, file)}`));
1157
+ console.log(pc.green(`\u2713 ${path5.relative(vault.root, file)}`));
859
1158
  });
860
1159
  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) => {
861
1160
  const vault = getVault();
@@ -884,8 +1183,40 @@ ${pc.bold(pc.cyan(r.note.title))} ${pc.dim(`(${r.note.rel}, ${r.note.type})`)}${
884
1183
  console.log(pc.dim(" " + e.replace(/\n+/g, " ").slice(0, 220)));
885
1184
  }
886
1185
  }
1186
+ if (protocolEnabled()) {
1187
+ const chain = protocolChain(vault, results[0].note.rel);
1188
+ if (chain.length > 0) {
1189
+ const label = {
1190
+ plan: "Plan",
1191
+ verification: "Verificaci\xF3n",
1192
+ lesson: "Lecci\xF3n",
1193
+ solution: "Soluci\xF3n",
1194
+ task: "Tarea"
1195
+ };
1196
+ console.log(pc.bold("\n \u{1F517} Cadena del Protocolo (hilo conectado al mejor resultado):"));
1197
+ for (const n of chain) {
1198
+ const mark = n.type === "verification" ? n.status === "failed" ? pc.red(" \u2717") : n.status === "completed" ? pc.green(" \u2713") : "" : "";
1199
+ console.log(` ${pc.dim((label[n.type] ?? n.type) + ":")} ${n.title}${mark} ${pc.dim(`(${n.rel})`)}`);
1200
+ }
1201
+ }
1202
+ }
887
1203
  console.log();
888
1204
  });
1205
+ 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
+ const vault = getVault();
1207
+ ensureVaultStructure(vault);
1208
+ const cwd = process.cwd();
1209
+ const s = scanAll(vault, cwd);
1210
+ const idx = VaultIndex.load(vault);
1211
+ await idx.refresh().catch(() => {
1212
+ });
1213
+ console.log(pc.green(`\u2713 API: ${s.api} rutas \xB7 Env: ${s.env} vars (solo nombres) \xB7 Datos: ${s.data} \xB7 Convenciones: ${s.conventions}${s.gitignored ? " \xB7 .gitignore \u2713" : ""}`));
1214
+ if (s.notes.length) {
1215
+ for (const n of s.notes) console.log(pc.dim(` ${path5.relative(vault.root, n)}`));
1216
+ } else {
1217
+ console.log(pc.dim(" Nada detectado (\xBFproyecto sin package.json/api/env?)"));
1218
+ }
1219
+ });
889
1220
  program.command("reindex").description("Reindexar la b\xF3veda (incremental; --force para todo)").option("--force", "reindexar todo desde cero").action(async (opts) => {
890
1221
  const vault = getVault();
891
1222
  ensureVaultStructure(vault);
@@ -942,8 +1273,8 @@ program.command("stats").description("Estado de la b\xF3veda y tokens ahorrados"
942
1273
  async function runSkills(opts) {
943
1274
  const { vault } = await ensureReady();
944
1275
  const cwd = process.cwd();
945
- const targetDir = opts.project ? path4.join(cwd, ".claude", "skills") : path4.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
946
- const recs = recommendSkills(vault, [targetDir]);
1276
+ const targetDir = opts.project ? path5.join(cwd, ".claude", "skills") : path5.join(process.env.HOME ?? process.env.USERPROFILE ?? cwd, ".claude", "skills");
1277
+ const recs = await recommendSkills(vault, [targetDir]);
947
1278
  if (recs.length === 0) {
948
1279
  console.log(pc.dim("Sin recomendaciones nuevas: la b\xF3veda a\xFAn no tiene suficientes patrones (o ya est\xE1 todo instalado)."));
949
1280
  return;
@@ -954,6 +1285,12 @@ async function runSkills(opts) {
954
1285
  for (const r of recs) {
955
1286
  console.log(` ${pc.cyan(r.skill)} ${pc.dim(`[${r.source}]`)} \u2014 ${r.reason}`);
956
1287
  }
1288
+ const skillsRepo = localSkillsRepo();
1289
+ console.log(pc.dim(
1290
+ skillsRepo ? `
1291
+ Repo local de skills: ${skillsRepo} (c\xE1mbialo con: ale config set skills.repo <ruta>)` : `
1292
+ Origen: registro p\xFAblico skills.sh. \xBFRepo local propio? ale config set skills.repo <ruta>`
1293
+ ));
957
1294
  let selected = recs;
958
1295
  if (!opts.yes) {
959
1296
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
@@ -1004,8 +1341,29 @@ program.command("doctor").description("Verifica y repara la instalaci\xF3n (mode
1004
1341
  }
1005
1342
  const idx = VaultIndex.load(vault);
1006
1343
  const res = await idx.refresh();
1007
- console.log(`${pc.green("\u2713")} \xCDndice al d\xEDa (${res.changed} reindexadas, ${Object.keys(idx.meta.notes).length} notas)
1008
- `);
1344
+ console.log(`${pc.green("\u2713")} \xCDndice al d\xEDa (${res.changed} reindexadas, ${Object.keys(idx.meta.notes).length} notas)`);
1345
+ if (idx.emb && idx.emb.length !== idx.meta.chunks.length * idx.meta.dim) {
1346
+ console.log(pc.yellow("\u26A0 Embeddings desalineados con el \xEDndice \u2014 corre `ale reindex --force`"));
1347
+ } else if (idx.emb) {
1348
+ console.log(`${pc.green("\u2713")} Embeddings alineados (${idx.meta.chunks.length} chunks)`);
1349
+ }
1350
+ try {
1351
+ const name = path5.basename(cwd);
1352
+ const mapFile = path5.join(vault.managed, "notes", `mapa-${slugify(name)}.md`);
1353
+ const pkgM = fs5.statSync(path5.join(cwd, "package.json")).mtimeMs;
1354
+ const mapM = fs5.statSync(mapFile).mtimeMs;
1355
+ if (pkgM > mapM) {
1356
+ console.log(pc.yellow("\u26A0 package.json cambi\xF3 despu\xE9s del \xFAltimo escaneo \u2014 corre `ale scan` para refrescar el contexto"));
1357
+ } else {
1358
+ console.log(`${pc.green("\u2713")} Contexto del proyecto al d\xEDa (ale scan)`);
1359
+ }
1360
+ } catch {
1361
+ }
1362
+ const skillsRepoCfg = localSkillsRepo();
1363
+ if (skillsRepoCfg && !fs5.existsSync(skillsRepoCfg)) {
1364
+ console.log(pc.yellow(`\u26A0 skills.repo apunta a ${skillsRepoCfg} y no existe \u2014 corr\xEDgelo: ale config set skills.repo <ruta>`));
1365
+ }
1366
+ console.log();
1009
1367
  });
1010
1368
  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) => {
1011
1369
  const cwd = process.cwd();
@@ -1016,14 +1374,14 @@ program.command("uninstall").description("Reversi\xF3n limpia: quita hooks, bloq
1016
1374
  const claudeMd = removeClaudeMd(scope, cwd);
1017
1375
  if (claudeMd) console.log(pc.green(`\u2713 Bloque de Alexandria removido de ${claudeMd}`));
1018
1376
  if (opts.project) {
1019
- const mcpFile = path4.join(cwd, ".mcp.json");
1377
+ const mcpFile = path5.join(cwd, ".mcp.json");
1020
1378
  try {
1021
- const cfg = JSON.parse(fs4.readFileSync(mcpFile, "utf8"));
1379
+ const cfg = JSON.parse(fs5.readFileSync(mcpFile, "utf8"));
1022
1380
  if (cfg.mcpServers?.alexandria) {
1023
1381
  delete cfg.mcpServers.alexandria;
1024
1382
  if (Object.keys(cfg.mcpServers).length === 0) delete cfg.mcpServers;
1025
- if (Object.keys(cfg).length === 0) fs4.rmSync(mcpFile, { force: true });
1026
- else fs4.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1383
+ if (Object.keys(cfg).length === 0) fs5.rmSync(mcpFile, { force: true });
1384
+ else fs5.writeFileSync(mcpFile, JSON.stringify(cfg, null, 2) + "\n");
1027
1385
  console.log(pc.green("\u2713 MCP removido de .mcp.json"));
1028
1386
  }
1029
1387
  } catch {
@@ -9,12 +9,12 @@ import {
9
9
  } from "../chunk-DEDAOKAV.js";
10
10
  import {
11
11
  hybridSearch
12
- } from "../chunk-3ETM6PKR.js";
12
+ } from "../chunk-RZI7TYAG.js";
13
13
  import {
14
14
  resolveVault,
15
15
  vaultExists
16
16
  } from "../chunk-DYCARGQR.js";
17
- import "../chunk-7G3NPKDO.js";
17
+ import "../chunk-D5ROL42O.js";
18
18
  import {
19
19
  createNote,
20
20
  touchNote
@@ -14,7 +14,7 @@ import {
14
14
  } from "../chunk-DYCARGQR.js";
15
15
  import {
16
16
  VaultIndex
17
- } from "../chunk-7G3NPKDO.js";
17
+ } from "../chunk-D5ROL42O.js";
18
18
  import "../chunk-XWR74BQ2.js";
19
19
  import "../chunk-EDYBSJSS.js";
20
20
 
@@ -58,6 +58,12 @@ ${truncate(body.trim(), 4e3)}`);
58
58
  parts.push(`## Sesiones recientes en la b\xF3veda
59
59
  ${lines.join("\n")}`);
60
60
  }
61
+ const distilled = notes.filter((n) => n.type === "note" || n.type === "lesson").length;
62
+ if (map && distilled < 3) {
63
+ parts.push(
64
+ `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
+ }
61
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);
62
68
  if (titles.length > 0) {
63
69
  parts.push(`## La b\xF3veda ya tiene conocimiento sobre
@@ -1,17 +1,20 @@
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-DHXL36RG.js";
5
8
  import {
6
9
  hybridSearch
7
- } from "../chunk-3ETM6PKR.js";
10
+ } from "../chunk-RZI7TYAG.js";
8
11
  import {
9
12
  ensureVaultStructure,
10
13
  resolveVault
11
14
  } from "../chunk-DYCARGQR.js";
12
15
  import {
13
16
  VaultIndex
14
- } from "../chunk-7G3NPKDO.js";
17
+ } from "../chunk-D5ROL42O.js";
15
18
  import {
16
19
  createNote,
17
20
  setNoteStatus,
@@ -23,12 +26,14 @@ import "../chunk-EDYBSJSS.js";
23
26
  // src/mcp/server.ts
24
27
  import path from "path";
25
28
  import fs from "fs";
29
+ import { execSync } from "child_process";
26
30
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
27
31
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
28
32
  import { z } from "zod";
29
33
  var vault = resolveVault({ cwd: process.cwd() });
30
34
  var server = new McpServer({ name: "alexandria", version: pkgVersion() });
31
35
  var text = (t) => ({ content: [{ type: "text", text: t }] });
36
+ var tail = (s, n) => s.length > n ? "\u2026\n" + s.slice(-n) : s;
32
37
  function findMap(idx) {
33
38
  return Object.values(idx.meta.notes).find((n) => n.type === "map" || n.title.startsWith("Mapa - "));
34
39
  }
@@ -130,26 +135,31 @@ server.tool(
130
135
  );
131
136
  server.tool(
132
137
  "plan_create",
133
- '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.',
138
+ "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.",
134
139
  {
135
140
  title: z.string().describe('Nombre corto del objetivo, ej. "Login con Google"'),
136
141
  goal: z.string().describe("Qu\xE9 se quiere lograr, en una o dos frases"),
137
142
  dod: z.array(z.string()).describe("Definition of Done: criterios verificables de \xE9xito"),
138
- tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables")
143
+ tasks: z.array(z.string()).describe("Tareas numeradas, chicas y verificables, en orden de construcci\xF3n"),
144
+ 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.')
139
145
  },
140
- async ({ title, goal, dod, tasks }) => {
146
+ async ({ title, goal, dod, tasks, design }) => {
141
147
  ensureVaultStructure(vault);
148
+ const ctx = await planContext(vault, `${title} ${goal}`);
149
+ const hints = planQualityHints(dod, tasks, design);
142
150
  const idx = VaultIndex.load(vault);
143
151
  const map = findMap(idx);
144
152
  const content = [
145
153
  `## Objetivo
146
154
  ${goal}`,
155
+ design?.trim() ? `## Dise\xF1o
156
+ ${design.trim()}` : "",
147
157
  `## Definition of Done
148
158
  ${dod.map((d) => `- [ ] ${d}`).join("\n")}`,
149
159
  `## Tareas
150
160
  ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
151
161
  map ? `Proyecto: [[${map.title}]]` : ""
152
- ].join("\n\n");
162
+ ].filter(Boolean).join("\n\n");
153
163
  const file = createNote(vault.managed, {
154
164
  title: `Plan - ${title}`,
155
165
  type: "plan",
@@ -160,62 +170,107 @@ ${tasks.map((t, i) => `${i + 1}. ${t}`).join("\n")}`,
160
170
  });
161
171
  await VaultIndex.load(vault).refresh().catch(() => {
162
172
  });
173
+ const extra = architectBlock(ctx, hints);
163
174
  return text(
164
- `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.`
175
+ `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 ? `
176
+
177
+ ${extra}` : "")
165
178
  );
166
179
  }
167
180
  );
168
181
  server.tool(
169
182
  "task_verify",
170
- "PROTOCOLO paso 2: registra el resultado VERIFICADO de una tarea con evidencia real (salida de tests, build, curl \u2014 no lo des por hecho sin correrlo). Guarda el veredicto compacto; si fall\xF3, busca lecciones previas con vault_search antes de improvisar.",
183
+ 'PROTOCOLO paso 2: verifica una tarea con EVIDENCIA REAL, no con tu palabra. Pasa verify_command (ej. "npm test", "npm run build", "curl -sf localhost:3000") y Alexandria lo EJECUTA \u2014 el veredicto sale del exit code real. Si no puedes correr un comando, pasa evidence textual, pero se marca como auto-reportado (m\xE1s d\xE9bil). Si falla, busca lecciones previas antes de improvisar.',
171
184
  {
172
185
  plan: z.string().describe('T\xEDtulo del plan al que pertenece (ej. "Plan - Login con Google")'),
173
186
  task: z.string().describe("Qu\xE9 tarea se verific\xF3"),
174
- passed: z.boolean().describe("true si la evidencia confirma que funciona"),
175
- evidence: z.string().describe('Evidencia compacta: "npm test \u2192 12/12 passed", c\xF3digo de error, etc.'),
187
+ passed: z.boolean().describe("Lo que T\xDA crees que pas\xF3 (se compara contra el resultado real del comando)"),
188
+ verify_command: z.string().optional().describe('Comando a EJECUTAR para verificar de verdad; exit 0 = pas\xF3. Ej. "npm test", "npm run build". Preferido sobre evidence.'),
189
+ evidence: z.string().optional().describe("Solo si NO hay comando: evidencia textual (queda marcada como auto-reportada, sin verificar)."),
176
190
  completes_plan: z.boolean().optional().describe("true si esta era la \xFAltima tarea y el plan queda completado")
177
191
  },
178
- async ({ plan, task, passed, evidence, completes_plan }) => {
192
+ async ({ plan, task, passed, verify_command, evidence, completes_plan }) => {
179
193
  ensureVaultStructure(vault);
180
194
  const idx = VaultIndex.load(vault);
181
195
  const planNote = findByTitle(idx, plan);
196
+ let realPassed = passed;
197
+ let realEvidence;
198
+ let verified = false;
199
+ let discrepancy = "";
200
+ if (verify_command && verify_command.trim()) {
201
+ verified = true;
202
+ try {
203
+ const out = execSync(verify_command, {
204
+ cwd: process.cwd(),
205
+ timeout: 18e4,
206
+ encoding: "utf8",
207
+ stdio: ["ignore", "pipe", "pipe"],
208
+ maxBuffer: 10 * 1024 * 1024
209
+ });
210
+ realPassed = true;
211
+ realEvidence = `$ ${verify_command}
212
+ (exit 0)
213
+ ${tail(out, 1500)}`;
214
+ } catch (e) {
215
+ const err = e;
216
+ realPassed = false;
217
+ const output = ((err.stdout ?? "") + "\n" + (err.stderr ?? "")).trim() || err.message;
218
+ realEvidence = `$ ${verify_command}
219
+ (exit ${err.status ?? "\u22600"})
220
+ ${tail(output, 1500)}`;
221
+ }
222
+ if (passed !== realPassed) {
223
+ discrepancy = `
224
+
225
+ \u26A0 DISCREPANCIA: afirmaste passed=${passed}, pero el comando dio ${realPassed ? "\xC9XITO" : "FALLO"}. Alexandria registr\xF3 el resultado REAL (${realPassed}). Revisa lo que hiciste \u2014 no des por hecho lo que no corriste.`;
226
+ }
227
+ } else {
228
+ realEvidence = `(auto-reportado, SIN comando de verificaci\xF3n \u2014 no ejecutado)
229
+ ${tail(evidence ?? "sin evidencia", 1500)}`;
230
+ }
182
231
  const file = createNote(vault.managed, {
183
- title: `${passed ? "OK" : "FALLO"} - ${task.slice(0, 60)}`,
232
+ title: `${realPassed ? "OK" : "FALLO"} - ${task.slice(0, 60)}`,
184
233
  type: "verification",
185
- status: passed ? "completed" : "failed",
186
- tags: ["verificacion"],
234
+ status: realPassed ? "completed" : "failed",
235
+ tags: verified ? ["verificacion", "verificado"] : ["verificacion", "auto-reportado"],
187
236
  dir: "notes",
188
237
  content: `**Tarea:** ${task}
189
238
 
190
- **Veredicto:** ${passed ? "\u2705 pas\xF3" : "\u274C fall\xF3"}
239
+ **Veredicto:** ${realPassed ? "\u2705 pas\xF3" : "\u274C fall\xF3"} ${verified ? "(verificado ejecutando el comando)" : "(\u26A0 auto-reportado, sin ejecutar)"}
191
240
 
192
241
  **Evidencia:**
193
242
  \`\`\`
194
- ${evidence.slice(0, 1500)}
243
+ ${realEvidence}
195
244
  \`\`\`
196
245
 
197
246
  ${planNote ? `Plan: [[${planNote.title}]]` : ""}`
198
247
  });
199
248
  if (completes_plan && planNote) {
200
249
  try {
201
- setNoteStatus(path.join(vault.root, planNote.rel), passed ? "completed" : "failed");
250
+ setNoteStatus(path.join(vault.root, planNote.rel), realPassed ? "completed" : "failed");
202
251
  } catch {
203
252
  }
204
253
  }
205
254
  await VaultIndex.load(vault).refresh().catch(() => {
206
255
  });
207
- if (!passed) {
208
- const lessons = await hybridSearch(vault, `${task} ${evidence.slice(0, 200)}`, 3);
256
+ if (!realPassed) {
257
+ const lessons = await hybridSearch(vault, `${task} ${realEvidence.slice(0, 200)}`, 3);
209
258
  const useful = lessons.filter((l) => l.note.type === "lesson" || l.note.type === "solution");
259
+ const head = `Fallo ${verified ? "CONFIRMADO por el comando" : "registrado (auto-reportado)"} (${path.relative(vault.root, file)}).${discrepancy}`;
210
260
  if (useful.length > 0) {
211
261
  return text(
212
- `Fallo registrado (${path.relative(vault.root, file)}). LECCIONES PREVIAS que podr\xEDan aplicar \u2014 \xFAsalas antes de improvisar:
262
+ `${head}
263
+ LECCIONES PREVIAS que podr\xEDan aplicar \u2014 \xFAsalas antes de improvisar:
213
264
  ` + useful.map((l) => `- \xAB${l.note.title}\xBB: ${l.excerpts[0]?.slice(0, 300) ?? ""}`).join("\n")
214
265
  );
215
266
  }
216
- return text(`Fallo registrado. Sin lecciones previas para esto \u2014 cuando lo resuelvas, guarda la lecci\xF3n con lesson_extract.`);
267
+ return text(`${head}
268
+ Sin lecciones previas \u2014 cuando lo resuelvas, gu\xE1rdala con lesson_extract.`);
217
269
  }
218
- return text(`Verificaci\xF3n guardada${completes_plan ? " y plan marcado como completado" : ""}. ${completes_plan ? "Cierra con lesson_extract si hubo aprendizaje." : "Siguiente tarea."}`);
270
+ const verdictHint = verified ? "Verificaci\xF3n REAL guardada (comando ejecutado, exit 0)." : "\u26A0 Verificaci\xF3n auto-reportada guardada \u2014 sin comando, no se comprob\xF3 de verdad. Pasa verify_command la pr\xF3xima.";
271
+ return text(
272
+ `${verdictHint}${completes_plan ? " Plan marcado como completado." : ""}${discrepancy} ${completes_plan ? "Cierra con lesson_extract si hubo aprendizaje." : "Siguiente tarea."}`
273
+ );
219
274
  }
220
275
  );
221
276
  server.tool(
@@ -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-DCKYTO4O.js";
8
+ import "./chunk-D5ROL42O.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.3",
3
+ "version": "1.0.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",