@ureck/alexandria 0.2.4 → 0.4.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
@@ -38,7 +38,7 @@ Confirma que quedó instalado:
38
38
 
39
39
  ```bash
40
40
  $ ale --version
41
- 0.2.3
41
+ 0.4.0
42
42
  ```
43
43
 
44
44
  ## Primeros pasos
@@ -46,10 +46,10 @@ $ ale --version
46
46
  Un solo comando instala todo (modelo de embeddings ~130MB una única vez, hooks, MCP, índice):
47
47
 
48
48
  ```bash
49
- # Global — una bóveda compartida para todas tus sesiones (~/KnowledgeVault)
49
+ # Global — una bóveda compartida para todas tus sesiones (~/Alexandria)
50
50
  ale init
51
51
 
52
- # Por proyecto — bóveda DENTRO del repo (./KnowledgeVault)
52
+ # Por proyecto — bóveda DENTRO del repo (./Alexandria)
53
53
  cd mi-proyecto
54
54
  ale init --project
55
55
 
@@ -72,7 +72,7 @@ ale init --agents claude,cursor,opencode # solo esos
72
72
 
73
73
  Instalación por proyecto
74
74
 
75
- ✓ Bóveda en /Users/tu/mi-proyecto/KnowledgeVault (vault Obsidian válido)
75
+ ✓ Bóveda en /Users/tu/mi-proyecto/Alexandria (vault Obsidian válido)
76
76
  ✓ Config del proyecto: /Users/tu/mi-proyecto/.vault.json
77
77
  ✓ Hooks registrados en /Users/tu/mi-proyecto/.claude/settings.json
78
78
  SessionStart (digest) · UserPromptSubmit (contexto+captura) · Stop/PreCompact (sesiones)
@@ -88,7 +88,7 @@ Instalación por proyecto
88
88
 
89
89
  Después de `init` no hay nada que reconectar, nunca. Importante: los hooks cargan **al arrancar** una sesión — abre una sesión *nueva* de tu agente en esa carpeta (una que ya estaba abierta no los verá). Desde ahí, cada prompt busca en la bóveda antes de gastar tokens y cada cierre de sesión guarda lo aprendido.
90
90
 
91
- > 💡 **Tip**: si la bóveda vive dentro de un repo git, agrega `KnowledgeVault/` a tu `.gitignore` — los digests de sesión son conocimiento personal tuyo, no del repo.
91
+ > `ale init --project` también agrega la bóveda a tu `.gitignore` automáticamente, escanea el proyecto (stack, estructura, comandos → mapa inicial) y te ofrece configurar en `CLAUDE.md` que Claude use Alexandria por default en cada sesión (`--auto` / `--manual` para decidir sin pregunta).
92
92
 
93
93
  ## Uso diario — ejemplos
94
94
 
@@ -131,19 +131,23 @@ ale add "Deploy en Vercel" -c "Regiones cdg1, ver [[Configuración de Prisma]]"
131
131
 
132
132
  ### Ver el grafo de conexiones
133
133
 
134
+ **El grafo se mantiene solo** — no hay que generarlo: cada vez que la bóveda cambia (captura automática, `ale add`, reindex), se regenera `<bóveda>/grafo.html`. Doble clic y siempre está al día.
135
+
134
136
  ```bash
135
- ale graph # abre visor interactivo en tu navegador (local)
136
- ale graph --out grafo.html # o genera HTML autocontenido para compartir
137
+ ale graph # visor EN VIVO en tu navegador: se actualiza solo cada 3s
138
+ ale graph --out otro.html # copia estática a otra ruta (opcional)
137
139
  ```
138
140
 
139
- Nodos = notas (tamaño = conexiones), líneas sólidas = `[[wikilinks]]`, punteadas = similitud semántica. Arrastra, haz zoom, click para detalle. El grafo brilla a partir de ~20-30 notas — es acumulativo por diseño.
141
+ Nodos = notas (tamaño = conexiones, color = tipo), líneas sólidas = `[[wikilinks]]`, punteadas = similitud semántica. Auto-encuadre, hover resalta vecinos, click muestra detalle y conexiones, caja para filtrar por título/tag, y **filtros por tipo estilo Obsidian** (los prompts vienen ocultos por default — son ruido visual; actívalos con su checkbox). El grafo brilla a partir de ~20-30 notas — es acumulativo por diseño.
142
+
143
+ **En Obsidian**: abre la carpeta de la bóveda como vault y usa su graph view nativo — las notas llevan `aliases` en el frontmatter para que Obsidian resuelva los `[[wikilinks]]` (sin eso los ve como enlaces rotos). Las notas viejas se migran solas en el siguiente reindex. Ojo: `grafo.html` no se abre *dentro* de Obsidian (no renderiza HTML) — es para el navegador.
140
144
 
141
145
  ### Medir cuánto te está ahorrando
142
146
 
143
147
  ```bash
144
148
  $ ale stats
145
149
 
146
- 🧠 Bóveda: /Users/tu/KnowledgeVault (global)
150
+ 🧠 Bóveda: /Users/tu/Alexandria (global)
147
151
  Notas: 142 {"note":80,"prompt":38,"session":22,"map":2}
148
152
  Chunks indexados: 385 · Conexiones: 91
149
153
  Búsqueda semántica: activa
@@ -238,7 +242,7 @@ En cualquier agente conectado, pídele cosas como *"busca en mi bóveda cómo co
238
242
 
239
243
  | Comando | Qué hace |
240
244
  |---|---|
241
- | `ale init [--project] [--path <dir>] [--agents <ids>] [--skills]` | Instala todo (una vez). Bóveda default: `./KnowledgeVault` con `--project`, `~/KnowledgeVault` en global |
245
+ | `ale init [--project] [--path <dir>] [--agents <ids>] [--auto\|--manual]` | Instala todo: bóveda (default `./Alexandria` / `~/Alexandria`), hooks, MCP, .gitignore, escaneo inicial y CLAUDE.md |
242
246
  | `ale agents [ids] [--project]` | Lista agentes / registra el MCP en ellos |
243
247
  | `ale search <query> [-k n] [--expand]` | Búsqueda híbrida; `--expand` trae vecinos del grafo |
244
248
  | `ale add <título> [-c texto] [-t tags]` | Guardar nota manual (o por stdin) |
@@ -247,6 +251,7 @@ En cualquier agente conectado, pídele cosas como *"busca en mi bóveda cómo co
247
251
  | `ale stats` | Notas, conexiones y tokens ahorrados estimados |
248
252
  | `ale reindex [--force]` | Reindexar (incremental por default) |
249
253
  | `ale doctor [--project]` | Verifica y repara: modelo, hooks, MCP, índice |
254
+ | `ale consolidate [--days n] [--dry]` | Archiva prompts viejos sin reuso — fuera del grafo/inyección, siguen buscables: nada se pierde |
250
255
  | `ale uninstall [--project]` | Quita hooks (las notas quedan intactas) |
251
256
  | `ale --vault <ruta> <comando>` | Cualquier comando contra otra bóveda |
252
257
 
@@ -262,7 +267,7 @@ En cualquier agente conectado, pídele cosas como *"busca en mi bóveda cómo co
262
267
  ## V2 (roadmap)
263
268
 
264
269
  - Bot de Telegram (grammY, polling local — sin servidor público): `/search`, `/save` desde el teléfono.
265
- - `ale consolidate`: detección de duplicados y clusters → notas-resumen.
270
+
266
271
 
267
272
  ## Código y contribuciones
268
273
 
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  VaultIndex
4
- } from "./chunk-UWAIMIG2.js";
4
+ } from "./chunk-ZW7XY3EN.js";
5
5
  import {
6
6
  dot,
7
7
  embed,
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/notes.ts
4
+ import fs from "fs";
5
+ import path from "path";
6
+ import matter from "gray-matter";
7
+ var SKIP_DIRS = /* @__PURE__ */ new Set([".obsidian", ".vault", ".trash", ".git", "node_modules"]);
8
+ function extractWikilinks(content) {
9
+ const out = /* @__PURE__ */ new Set();
10
+ const re = /\[\[([^\]|#\n]+)(?:[|#][^\]]*)?\]\]/g;
11
+ let m;
12
+ while ((m = re.exec(content)) !== null) {
13
+ const target = m[1].trim();
14
+ if (target) out.add(target);
15
+ }
16
+ return [...out];
17
+ }
18
+ function slugify(text) {
19
+ return text.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "nota";
20
+ }
21
+ function listMarkdownFiles(root) {
22
+ const out = [];
23
+ const walk = (dir) => {
24
+ let entries;
25
+ try {
26
+ entries = fs.readdirSync(dir, { withFileTypes: true });
27
+ } catch {
28
+ return;
29
+ }
30
+ for (const e of entries) {
31
+ if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue;
32
+ const full = path.join(dir, e.name);
33
+ if (e.isDirectory()) walk(full);
34
+ else if (e.isFile() && e.name.endsWith(".md")) out.push(full);
35
+ }
36
+ };
37
+ walk(root);
38
+ return out;
39
+ }
40
+ function parseNote(root, absPath) {
41
+ const raw = fs.readFileSync(absPath, "utf8");
42
+ const { data, content } = matter(raw);
43
+ const rel = path.relative(root, absPath).split(path.sep).join("/");
44
+ const title = typeof data.title === "string" && data.title || path.basename(absPath, ".md");
45
+ const type = ["note", "prompt", "session", "map"].includes(data.type) ? data.type : "note";
46
+ const tags = Array.isArray(data.tags) ? data.tags.map(String) : [];
47
+ return {
48
+ rel,
49
+ title,
50
+ type,
51
+ tags,
52
+ created: data.created ? String(data.created) : void 0,
53
+ hits: typeof data.hits === "number" ? data.hits : 1,
54
+ content,
55
+ links: extractWikilinks(content)
56
+ };
57
+ }
58
+ function frontmatter(n) {
59
+ const lines = [
60
+ "---",
61
+ `title: ${JSON.stringify(n.title)}`,
62
+ // aliases: Obsidian resuelve [[wikilinks]] contra alias, no contra el title
63
+ // del frontmatter — sin esto su graph view muestra los enlaces como rotos
64
+ `aliases: [${JSON.stringify(n.title)}]`,
65
+ `type: ${n.type}`,
66
+ `tags: [${n.tags.map((t) => JSON.stringify(t)).join(", ")}]`,
67
+ `created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
68
+ `hits: ${n.hits ?? 1}`,
69
+ "---",
70
+ ""
71
+ ];
72
+ return lines.join("\n");
73
+ }
74
+ function ensureAlias(absPath) {
75
+ try {
76
+ const raw = fs.readFileSync(absPath, "utf8");
77
+ const { data, content } = matter(raw);
78
+ if (!data.title || data.aliases) return false;
79
+ data.aliases = [String(data.title)];
80
+ fs.writeFileSync(absPath, matter.stringify(content, data));
81
+ return true;
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+ function createNote(managed, n) {
87
+ const dir = path.join(managed, n.dir ?? "notes");
88
+ fs.mkdirSync(dir, { recursive: true });
89
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
90
+ const base = `${date}-${slugify(n.title)}`;
91
+ let file = path.join(dir, `${base}.md`);
92
+ let i = 2;
93
+ while (fs.existsSync(file)) file = path.join(dir, `${base}-${i++}.md`);
94
+ fs.writeFileSync(
95
+ file,
96
+ frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [] }) + n.content.trim() + "\n"
97
+ );
98
+ return file;
99
+ }
100
+ function touchNote(absPath) {
101
+ const raw = fs.readFileSync(absPath, "utf8");
102
+ const { data, content } = matter(raw);
103
+ data.hits = (typeof data.hits === "number" ? data.hits : 1) + 1;
104
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
105
+ fs.writeFileSync(absPath, matter.stringify(content, data));
106
+ }
107
+ function upsertNote(managed, n) {
108
+ const dir = path.join(managed, n.dir ?? "notes");
109
+ fs.mkdirSync(dir, { recursive: true });
110
+ const file = path.join(dir, `${n.fixedName}.md`);
111
+ if (fs.existsSync(file)) {
112
+ const raw = fs.readFileSync(file, "utf8");
113
+ const { data } = matter(raw);
114
+ data.updated = (/* @__PURE__ */ new Date()).toISOString();
115
+ fs.writeFileSync(file, matter.stringify(n.content.trim() + "\n", data));
116
+ } else {
117
+ fs.writeFileSync(
118
+ file,
119
+ frontmatter({ title: n.title, type: n.type ?? "note", tags: n.tags ?? [] }) + n.content.trim() + "\n"
120
+ );
121
+ }
122
+ return file;
123
+ }
124
+ function appendToNote(managed, n) {
125
+ const dir = path.join(managed, n.dir ?? "sessions");
126
+ fs.mkdirSync(dir, { recursive: true });
127
+ const file = path.join(dir, `${n.fixedName}.md`);
128
+ if (fs.existsSync(file)) {
129
+ fs.appendFileSync(file, "\n" + n.content.trim() + "\n");
130
+ } else {
131
+ fs.writeFileSync(
132
+ file,
133
+ frontmatter({ title: n.title, type: n.type ?? "session", tags: n.tags ?? [] }) + n.content.trim() + "\n"
134
+ );
135
+ }
136
+ return file;
137
+ }
138
+
139
+ export {
140
+ slugify,
141
+ listMarkdownFiles,
142
+ parseNote,
143
+ ensureAlias,
144
+ createNote,
145
+ touchNote,
146
+ upsertNote,
147
+ appendToNote
148
+ };
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/vault.ts
4
+ import fs from "fs";
5
+ import os from "os";
6
+ import path from "path";
7
+ var MANAGED_DIR = "Alexandria";
8
+ function configDir() {
9
+ if (process.platform === "win32" && process.env.APPDATA) {
10
+ return path.join(process.env.APPDATA, "alexandria");
11
+ }
12
+ return path.join(os.homedir(), ".config", "alexandria");
13
+ }
14
+ function globalConfigPath() {
15
+ return path.join(configDir(), "config.json");
16
+ }
17
+ function defaultVaultPath() {
18
+ const legacy = path.join(os.homedir(), "KnowledgeVault");
19
+ if (fs.existsSync(legacy)) return legacy;
20
+ return path.join(os.homedir(), "Alexandria");
21
+ }
22
+ function readJson(file) {
23
+ try {
24
+ return JSON.parse(fs.readFileSync(file, "utf8"));
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ function findProjectConfig(from) {
30
+ let dir = path.resolve(from);
31
+ for (; ; ) {
32
+ const candidate = path.join(dir, ".vault.json");
33
+ if (fs.existsSync(candidate)) return candidate;
34
+ const parent = path.dirname(dir);
35
+ if (parent === dir) return null;
36
+ dir = parent;
37
+ }
38
+ }
39
+ function build(root, source, projectConfig) {
40
+ const managed = path.basename(root).toLowerCase() === MANAGED_DIR.toLowerCase() ? root : path.join(root, MANAGED_DIR);
41
+ return {
42
+ root,
43
+ managed,
44
+ cache: path.join(root, ".vault"),
45
+ source,
46
+ projectConfig
47
+ };
48
+ }
49
+ function resolveVault(opts = {}) {
50
+ if (opts.flag) return build(path.resolve(opts.flag), "flag");
51
+ const cwd = opts.cwd ?? process.cwd();
52
+ const projectFile = findProjectConfig(cwd);
53
+ if (projectFile) {
54
+ const cfg = readJson(projectFile);
55
+ if (cfg?.vaultPath) {
56
+ const base = path.dirname(projectFile);
57
+ return build(path.resolve(base, cfg.vaultPath), "project", projectFile);
58
+ }
59
+ }
60
+ const globalCfg = readJson(globalConfigPath());
61
+ if (globalCfg?.vaultPath) return build(globalCfg.vaultPath, "global");
62
+ return build(defaultVaultPath(), "default");
63
+ }
64
+ function vaultExists(v) {
65
+ return fs.existsSync(v.managed) || fs.existsSync(v.cache);
66
+ }
67
+ function ensureVaultStructure(v) {
68
+ for (const dir of [
69
+ v.root,
70
+ v.managed,
71
+ path.join(v.managed, "notes"),
72
+ path.join(v.managed, "prompts"),
73
+ path.join(v.managed, "sessions"),
74
+ v.cache
75
+ ]) {
76
+ fs.mkdirSync(dir, { recursive: true });
77
+ }
78
+ }
79
+ function writeGlobalConfig(vaultPath) {
80
+ fs.mkdirSync(configDir(), { recursive: true });
81
+ fs.writeFileSync(globalConfigPath(), JSON.stringify({ vaultPath }, null, 2) + "\n");
82
+ }
83
+ function writeProjectConfig(projectDir, vaultPath) {
84
+ const file = path.join(projectDir, ".vault.json");
85
+ const rel = path.relative(projectDir, vaultPath) || ".";
86
+ const stored = rel.startsWith("..") ? vaultPath : rel;
87
+ fs.writeFileSync(file, JSON.stringify({ vaultPath: stored }, null, 2) + "\n");
88
+ return file;
89
+ }
90
+
91
+ export {
92
+ globalConfigPath,
93
+ defaultVaultPath,
94
+ resolveVault,
95
+ vaultExists,
96
+ ensureVaultStructure,
97
+ writeGlobalConfig,
98
+ writeProjectConfig
99
+ };
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ VaultIndex
4
+ } from "./chunk-ZW7XY3EN.js";
5
+
6
+ // src/graph/viewer.ts
7
+ import fs from "fs";
8
+ import http from "http";
9
+ import path from "path";
10
+ import { spawn } from "child_process";
11
+ function buildGraphData(idx) {
12
+ const deg = /* @__PURE__ */ new Map();
13
+ for (const l of idx.meta.links) {
14
+ deg.set(l.from, (deg.get(l.from) ?? 0) + 1);
15
+ deg.set(l.to, (deg.get(l.to) ?? 0) + 1);
16
+ }
17
+ return {
18
+ nodes: Object.values(idx.meta.notes).filter((n) => !n.rel.split("/").includes("archive")).map((n) => ({
19
+ id: n.rel,
20
+ title: n.title,
21
+ type: n.type,
22
+ deg: deg.get(n.rel) ?? 0,
23
+ hits: n.hits ?? 1,
24
+ tags: n.tags
25
+ })),
26
+ edges: idx.meta.links.map((l) => ({ s: l.from, t: l.to, type: l.type, w: l.w })),
27
+ generated: (/* @__PURE__ */ new Date()).toISOString()
28
+ };
29
+ }
30
+ function renderGraphHtml(data, live) {
31
+ return `<!doctype html>
32
+ <html lang="es">
33
+ <head>
34
+ <meta charset="utf-8">
35
+ <title>Alexandria \u2014 grafo de conocimiento</title>
36
+ <style>
37
+ :root { --bg:#0b0d13; --panel:#141826f2; --line:#232a3d; --txt:#dde3f4; --dim:#8b93ad; }
38
+ html,body{margin:0;height:100%;background:var(--bg);color:var(--txt);font:14px/1.45 -apple-system,system-ui,sans-serif;overflow:hidden}
39
+ canvas{display:block;cursor:grab}
40
+ canvas.dragging{cursor:grabbing}
41
+ .card{position:fixed;background:var(--panel);border:1px solid var(--line);border-radius:14px;backdrop-filter:blur(12px);box-shadow:0 8px 30px #0008}
42
+ #hud{top:14px;left:14px;padding:12px 16px;max-width:330px}
43
+ #hud h1{font-size:15px;margin:0 0 2px;letter-spacing:.3px}
44
+ #hud .sub{color:var(--dim);font-size:12px}
45
+ .leg{display:flex;gap:12px;flex-wrap:wrap;margin-top:8px;font-size:12px;color:var(--dim)}
46
+ .leg b{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:5px;vertical-align:-1px}
47
+ .leg label{cursor:pointer;user-select:none}
48
+ .leg input{accent-color:#7aa2f7;margin-right:4px;vertical-align:-2px}
49
+ #hint{color:var(--dim);font-size:11px;margin-top:6px}
50
+ #info{bottom:14px;left:14px;padding:12px 16px;max-width:440px;display:none}
51
+ #info b{font-size:14px}
52
+ #info .meta{color:var(--dim);font-size:12px;margin-top:2px}
53
+ #tip{padding:6px 10px;font-size:12px;pointer-events:none;display:none;border-radius:8px;white-space:nowrap}
54
+ #live{top:14px;right:14px;padding:6px 12px;font-size:11px;color:var(--dim);display:${live ? "block" : "none"}}
55
+ #live b{color:#9ece6a}
56
+ #search{position:fixed;top:14px;left:50%;transform:translateX(-50%);}
57
+ #search input{background:var(--panel);border:1px solid var(--line);border-radius:10px;color:var(--txt);padding:7px 12px;width:230px;font-size:13px;outline:none}
58
+ #search input:focus{border-color:#7aa2f7}
59
+ </style>
60
+ </head>
61
+ <body>
62
+ <div id="hud" class="card">
63
+ <h1>\u{1F3DB}\uFE0F Alexandria</h1>
64
+ <div class="sub" id="counts"></div>
65
+ <div class="leg" id="leg">
66
+ <label><input type="checkbox" data-type="note" checked><b style="background:#7aa2f7"></b>nota</label>
67
+ <label><input type="checkbox" data-type="map" checked><b style="background:#f7768e"></b>mapa</label>
68
+ <label><input type="checkbox" data-type="session" checked><b style="background:#9ece6a"></b>sesi\xF3n</label>
69
+ <label><input type="checkbox" data-type="prompt"><b style="background:#e0af68"></b>prompt</label>
70
+ </div>
71
+ <div id="hint">filtros por tipo (prompts ocultos por default \u2014 ruido) \xB7 arrastra \xB7 rueda = zoom<br>hover = conexiones \xB7 click = detalle \xB7 \u2014 s\xF3lida = [[wikilink]] \xB7 \u2025 punteada = sem\xE1ntica</div>
72
+ </div>
73
+ <div id="search"><input id="q" placeholder="filtrar notas\u2026" autocomplete="off"></div>
74
+ <div id="live" class="card">\u25CF <b>en vivo</b> \u2014 se actualiza solo</div>
75
+ <div id="info" class="card"></div>
76
+ <div id="tip" class="card"></div>
77
+ <canvas id="c"></canvas>
78
+ <script>
79
+ 'use strict';
80
+ const LIVE = ${live};
81
+ let DATA = ${JSON.stringify(data)};
82
+ const COLORS = { note:'#7aa2f7', session:'#9ece6a', prompt:'#e0af68', map:'#f7768e' };
83
+ const cv = document.getElementById('c'), ctx = cv.getContext('2d');
84
+ const DPR = Math.min(devicePixelRatio || 1, 2);
85
+ let W, H;
86
+ function fit(){ W = innerWidth; H = innerHeight; cv.width = W*DPR; cv.height = H*DPR; cv.style.width = W+'px'; cv.style.height = H+'px'; }
87
+ fit(); addEventListener('resize', () => { fit(); fitView(); });
88
+
89
+ // Estado global ANTES de loadData: asigna heat/hot al cargar (evita TDZ)
90
+ let nodes = [], byId = new Map(), edges = [];
91
+ let zoom = 1, panX = 0, panY = 0, dragNode = null, hot = true, heat = 300;
92
+ let didFit = false, hover = null, filter = '';
93
+ // filtros por tipo (estilo Obsidian) \u2014 prompts ocultos por default: son ruido visual
94
+ const typeOn = { note: true, map: true, session: true, prompt: false };
95
+ document.querySelectorAll('#leg input').forEach(cb => cb.addEventListener('change', e => {
96
+ typeOn[e.target.dataset.type] = e.target.checked; heat = Math.max(heat, 30); hot = true;
97
+ }));
98
+ function radius(n){ return 5 + Math.min(n.deg,14)*1.1 + Math.min(n.hits,8)*0.6; }
99
+ function loadData(data, keepPositions){
100
+ const old = keepPositions ? byId : new Map();
101
+ nodes = data.nodes.map((n,i) => {
102
+ const prev = old.get(n.id);
103
+ const angle = i/Math.max(data.nodes.length,1)*6.283;
104
+ return Object.assign({}, n, {
105
+ x: prev ? prev.x : W/2 + Math.cos(angle)*Math.min(W,H)*0.28 + (Math.random()-.5)*30,
106
+ y: prev ? prev.y : H/2 + Math.sin(angle)*Math.min(W,H)*0.28 + (Math.random()-.5)*30,
107
+ vx: 0, vy: 0, r: radius(n)
108
+ });
109
+ });
110
+ byId = new Map(nodes.map(n => [n.id, n]));
111
+ edges = data.edges.filter(e => byId.has(e.s) && byId.has(e.t)).map(e => ({ a: byId.get(e.s), b: byId.get(e.t), type: e.type, w: e.w || 0.5 }));
112
+ document.getElementById('counts').textContent = nodes.length + ' notas \xB7 ' + edges.length + ' conexiones';
113
+ heat = 280; hot = true;
114
+ }
115
+ loadData(DATA, false);
116
+
117
+ // ---------- f\xEDsica ----------
118
+ function step(){
119
+ if (!hot) return;
120
+ for (let i = 0; i < nodes.length; i++) for (let j = i+1; j < nodes.length; j++){
121
+ const a = nodes[i], b = nodes[j];
122
+ let dx = b.x-a.x, dy = b.y-a.y;
123
+ const d2 = dx*dx + dy*dy + 0.01, d = Math.sqrt(d2);
124
+ // repulsi\xF3n + colisi\xF3n suave (nunca encimados)
125
+ let f = Math.min(2600/d2, 10);
126
+ const minD = a.r + b.r + 14;
127
+ if (d < minD) f += (minD - d) * 0.06;
128
+ dx /= d; dy /= d;
129
+ a.vx -= dx*f; a.vy -= dy*f; b.vx += dx*f; b.vy += dy*f;
130
+ }
131
+ for (const e of edges){
132
+ let dx = e.b.x-e.a.x, dy = e.b.y-e.a.y;
133
+ const d = Math.sqrt(dx*dx+dy*dy) + 0.01;
134
+ const want = e.type === 'wikilink' ? 120 : 175;
135
+ // resorte lineal ACOTADO \u2014 jam\xE1s multiplicar por d otra vez (explota a NaN)
136
+ const f = Math.max(-6, Math.min(6, (d - want) * (e.type === 'wikilink' ? 0.03 : 0.015)));
137
+ dx /= d; dy /= d;
138
+ e.a.vx += dx*f; e.a.vy += dy*f; e.b.vx -= dx*f; e.b.vy -= dy*f;
139
+ }
140
+ const VMAX = 14;
141
+ for (const n of nodes){
142
+ n.vx += (W/2 - n.x) * 0.0005; n.vy += (H/2 - n.y) * 0.0005;
143
+ n.vx *= 0.86; n.vy *= 0.86;
144
+ // velocidad acotada + saneo: la simulaci\xF3n no puede reventar con ning\xFAn grafo
145
+ n.vx = Math.max(-VMAX, Math.min(VMAX, n.vx)) || 0;
146
+ n.vy = Math.max(-VMAX, Math.min(VMAX, n.vy)) || 0;
147
+ if (n !== dragNode){ n.x += n.vx; n.y += n.vy; }
148
+ if (!Number.isFinite(n.x) || !Number.isFinite(n.y)){ n.x = W/2; n.y = H/2; n.vx = n.vy = 0; }
149
+ }
150
+ if (--heat <= 0 && !dragNode) { hot = false; if (!didFit) fitView(); }
151
+ }
152
+
153
+ // ---------- auto-encuadre ----------
154
+ function fitView(){
155
+ if (!nodes.length) return;
156
+ didFit = true;
157
+ let x0=1e9, y0=1e9, x1=-1e9, y1=-1e9;
158
+ for (const n of nodes){ x0=Math.min(x0,n.x); y0=Math.min(y0,n.y); x1=Math.max(x1,n.x); y1=Math.max(y1,n.y); }
159
+ const pad = 90, w = Math.max(x1-x0, 60), h = Math.max(y1-y0, 60);
160
+ zoom = Math.min((W-pad*2)/w, (H-pad*2)/h, 1.6);
161
+ panX = W/2 - (x0+x1)/2 * zoom;
162
+ panY = H/2 - (y0+y1)/2 * zoom;
163
+ }
164
+ setTimeout(fitView, 900); // encuadre inicial tras estabilizar
165
+
166
+ // ---------- render ----------
167
+ function draw(){
168
+ ctx.setTransform(DPR,0,0,DPR,0,0);
169
+ ctx.clearRect(0,0,W,H);
170
+ const g = ctx.createRadialGradient(W/2,H/2,80, W/2,H/2,Math.max(W,H)*0.7);
171
+ g.addColorStop(0,'#11141d'); g.addColorStop(1,'#0b0d13');
172
+ ctx.fillStyle = g; ctx.fillRect(0,0,W,H);
173
+ ctx.setTransform(DPR*zoom,0,0,DPR*zoom,DPR*panX,DPR*panY);
174
+
175
+ const active = hover ? new Set([hover, ...edges.filter(e=>e.a===hover||e.b===hover).flatMap(e=>[e.a,e.b])]) : null;
176
+ const match = filter ? new Set(nodes.filter(n => n.title.toLowerCase().includes(filter) || n.tags.join(' ').toLowerCase().includes(filter))) : null;
177
+ const shown = (n) => typeOn[n.type] !== false;
178
+ const visible = (n) => (!active || active.has(n)) && (!match || match.has(n));
179
+
180
+ for (const e of edges){
181
+ if (!shown(e.a) || !shown(e.b)) continue;
182
+ const on = visible(e.a) && visible(e.b) && (!active || e.a===hover || e.b===hover);
183
+ ctx.beginPath();
184
+ ctx.setLineDash(e.type === 'semantic' ? [5,5] : []);
185
+ ctx.strokeStyle = e.type === 'semantic' ? '#3d4560' : '#57648f';
186
+ ctx.globalAlpha = on ? (e.type==='semantic'?0.55:0.8) : 0.07;
187
+ ctx.lineWidth = on && active ? 2 : 1.2;
188
+ const mx = (e.a.x+e.b.x)/2 - (e.b.y-e.a.y)*0.08;
189
+ const my = (e.a.y+e.b.y)/2 + (e.b.x-e.a.x)*0.08;
190
+ ctx.moveTo(e.a.x, e.a.y); ctx.quadraticCurveTo(mx, my, e.b.x, e.b.y); ctx.stroke();
191
+ }
192
+ ctx.setLineDash([]);
193
+
194
+ for (const n of nodes){
195
+ if (!shown(n)) continue;
196
+ const on = visible(n);
197
+ const color = COLORS[n.type] || '#7aa2f7';
198
+ ctx.globalAlpha = on ? 1 : 0.12;
199
+ ctx.shadowColor = color; ctx.shadowBlur = on ? (n === hover ? 26 : 12) : 0;
200
+ ctx.beginPath();
201
+ ctx.fillStyle = color;
202
+ ctx.arc(n.x, n.y, n === hover ? n.r*1.25 : n.r, 0, 6.283); ctx.fill();
203
+ ctx.shadowBlur = 0;
204
+ ctx.beginPath();
205
+ ctx.strokeStyle = '#ffffff2e'; ctx.lineWidth = 1;
206
+ ctx.arc(n.x, n.y, n === hover ? n.r*1.25 : n.r, 0, 6.283); ctx.stroke();
207
+ }
208
+
209
+ // etiquetas con halo para legibilidad
210
+ const showAll = nodes.length <= 40 || zoom > 1.15;
211
+ ctx.font = (12/Math.max(zoom,0.8)) + 'px -apple-system,system-ui,sans-serif';
212
+ ctx.lineWidth = 3/Math.max(zoom,0.8); ctx.strokeStyle = '#0b0d13';
213
+ for (const n of nodes){
214
+ if (!shown(n) || !visible(n)) continue;
215
+ if (!(showAll || n.deg > 1 || n === hover)) continue;
216
+ const label = n.title.length > 34 ? n.title.slice(0,33)+'\u2026' : n.title;
217
+ ctx.globalAlpha = n === hover ? 1 : 0.85;
218
+ ctx.strokeText(label, n.x + n.r + 5, n.y + 4);
219
+ ctx.fillStyle = '#cdd6f4';
220
+ ctx.fillText(label, n.x + n.r + 5, n.y + 4);
221
+ }
222
+ ctx.globalAlpha = 1;
223
+ }
224
+ (function loop(){ step(); draw(); requestAnimationFrame(loop); })();
225
+
226
+ // ---------- interacci\xF3n ----------
227
+ const toWorld = (x,y) => [(x-panX)/zoom, (y-panY)/zoom];
228
+ const pick = (x,y) => { const [wx,wy] = toWorld(x,y); return nodes.find(n => { if (typeOn[n.type] === false) return false; const dx=n.x-wx, dy=n.y-wy; return dx*dx+dy*dy <= (n.r+6)*(n.r+6); }); };
229
+ let panning = false, px = 0, py = 0, moved = false;
230
+ const tip = document.getElementById('tip');
231
+ cv.addEventListener('mousedown', e => { moved = false; const n = pick(e.clientX, e.clientY); if (n){ dragNode = n; hot = true; heat = 120; } else { panning = true; px = e.clientX; py = e.clientY; } cv.classList.add('dragging'); });
232
+ addEventListener('mousemove', e => {
233
+ if (dragNode){ const [wx,wy] = toWorld(e.clientX, e.clientY); dragNode.x = wx; dragNode.y = wy; moved = true; hot = true; heat = Math.max(heat, 40); return; }
234
+ if (panning){ panX += e.clientX-px; panY += e.clientY-py; px = e.clientX; py = e.clientY; moved = true; return; }
235
+ const n = pick(e.clientX, e.clientY);
236
+ if (n !== hover){ hover = n; }
237
+ if (n){ tip.style.display='block'; tip.style.left = (e.clientX+14)+'px'; tip.style.top = (e.clientY+14)+'px'; tip.textContent = n.title; }
238
+ else tip.style.display = 'none';
239
+ });
240
+ addEventListener('mouseup', () => { dragNode = null; panning = false; cv.classList.remove('dragging'); });
241
+ cv.addEventListener('click', e => {
242
+ if (moved) return;
243
+ const n = pick(e.clientX, e.clientY);
244
+ const info = document.getElementById('info');
245
+ if (n){
246
+ const nbs = edges.filter(x => x.a===n || x.b===n).map(x => (x.a===n?x.b:x.a).title);
247
+ info.style.display = 'block';
248
+ info.innerHTML = '<b>' + n.title + '</b><div class="meta">' + n.id + '<br>tipo: ' + n.type + ' \xB7 usos: ' + n.hits + (n.tags.length ? ' \xB7 #' + n.tags.join(' #') : '') + '</div>' +
249
+ (nbs.length ? '<div class="meta" style="margin-top:6px">conecta con: ' + nbs.slice(0,6).join(' \xB7 ') + (nbs.length>6 ? ' +' + (nbs.length-6) : '') + '</div>' : '');
250
+ } else info.style.display = 'none';
251
+ });
252
+ cv.addEventListener('wheel', e => {
253
+ e.preventDefault();
254
+ const f = e.deltaY < 0 ? 1.12 : 0.89;
255
+ panX = e.clientX - (e.clientX - panX)*f; panY = e.clientY - (e.clientY - panY)*f; zoom *= f;
256
+ }, { passive: false });
257
+ document.getElementById('q').addEventListener('input', e => { filter = e.target.value.trim().toLowerCase(); });
258
+
259
+ // ---------- modo en vivo: el grafo se actualiza solo ----------
260
+ if (LIVE) setInterval(async () => {
261
+ try {
262
+ const res = await fetch('/data.json');
263
+ const fresh = await res.json();
264
+ if (fresh.generated !== DATA.generated && (fresh.nodes.length !== DATA.nodes.length || fresh.edges.length !== DATA.edges.length)){
265
+ DATA = fresh; loadData(fresh, true);
266
+ } else { DATA = fresh; }
267
+ } catch { /* server cerrado */ }
268
+ }, 3000);
269
+ </script>
270
+ </body>
271
+ </html>`;
272
+ }
273
+ function writeStaticGraph(idx) {
274
+ const file = path.join(idx.vault.root, "grafo.html");
275
+ fs.writeFileSync(file, renderGraphHtml(buildGraphData(idx), false));
276
+ return file;
277
+ }
278
+ function openBrowser(url) {
279
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
280
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
281
+ try {
282
+ spawn(cmd, args, { detached: true, stdio: "ignore" }).unref();
283
+ } catch {
284
+ }
285
+ }
286
+ async function serveGraph(vault, opts = {}) {
287
+ const fresh = async () => {
288
+ const idx = VaultIndex.load(vault);
289
+ await idx.refresh(false).catch(() => {
290
+ });
291
+ return idx;
292
+ };
293
+ if (opts.out) {
294
+ const file = path.resolve(opts.out);
295
+ fs.writeFileSync(file, renderGraphHtml(buildGraphData(await fresh()), false));
296
+ return file;
297
+ }
298
+ return new Promise((resolve) => {
299
+ const server = http.createServer(async (req, res) => {
300
+ try {
301
+ if (req.url?.startsWith("/data.json")) {
302
+ res.writeHead(200, { "content-type": "application/json" });
303
+ res.end(JSON.stringify(buildGraphData(await fresh())));
304
+ return;
305
+ }
306
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
307
+ res.end(renderGraphHtml(buildGraphData(await fresh()), true));
308
+ } catch (e) {
309
+ res.writeHead(500);
310
+ res.end(String(e));
311
+ }
312
+ });
313
+ server.listen(0, "127.0.0.1", () => {
314
+ const addr = server.address();
315
+ const port = typeof addr === "object" && addr ? addr.port : 0;
316
+ const url = `http://127.0.0.1:${port}`;
317
+ if (opts.open !== false) openBrowser(url);
318
+ resolve(url);
319
+ });
320
+ });
321
+ }
322
+
323
+ export {
324
+ buildGraphData,
325
+ renderGraphHtml,
326
+ writeStaticGraph,
327
+ serveGraph
328
+ };