memosebui 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENT_INSTALL.md +6 -0
- package/README.md +28 -2
- package/dist/cli/memosebui.d.ts +2 -0
- package/dist/cli/memosebui.js +218 -0
- package/dist/cli/memosebui.js.map +1 -0
- package/dist/cli/setup.d.ts +42 -0
- package/dist/cli/setup.js +215 -0
- package/dist/cli/setup.js.map +1 -0
- package/dist/cli/ui-server.d.ts +25 -0
- package/dist/cli/ui-server.js +1640 -0
- package/dist/cli/ui-server.js.map +1 -0
- package/dist/core/graph-builder.d.ts +3 -0
- package/dist/core/graph-builder.js +312 -0
- package/dist/core/graph-builder.js.map +1 -0
- package/dist/core/vault-bridge.d.ts +62 -0
- package/dist/core/vault-bridge.js +915 -0
- package/dist/core/vault-bridge.js.map +1 -0
- package/dist/core/vault-watcher.d.ts +20 -0
- package/dist/core/vault-watcher.js +78 -0
- package/dist/core/vault-watcher.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/types/mind.d.ts +157 -0
- package/dist/types/mind.js +15 -0
- package/dist/types/mind.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.js +8 -0
- package/dist/version.js.map +1 -0
- package/package.json +57 -4
- package/src/styles/mind.css +643 -0
|
@@ -0,0 +1,1640 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { accessSync, constants, existsSync, readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { buildMindGraph } from "../core/graph-builder.js";
|
|
6
|
+
import { isMemoryCategory, VaultBridge } from "../core/vault-bridge.js";
|
|
7
|
+
import { VaultWatcher } from "../core/vault-watcher.js";
|
|
8
|
+
import { BUNDLE_ID, PACKAGE_ROOT, VERSION } from "../version.js";
|
|
9
|
+
function findExecutableInPath(binName) {
|
|
10
|
+
const pathEnv = process.env.PATH || '';
|
|
11
|
+
const dirs = pathEnv.split(path.delimiter).filter(Boolean);
|
|
12
|
+
const extensions = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
|
|
13
|
+
for (const dir of dirs) {
|
|
14
|
+
for (const ext of extensions) {
|
|
15
|
+
const candidate = path.join(dir, `${binName}${ext}`);
|
|
16
|
+
try {
|
|
17
|
+
if (existsSync(candidate) && statSync(candidate).isFile()) {
|
|
18
|
+
accessSync(candidate, constants.X_OK);
|
|
19
|
+
return candidate;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// Not executable, continue
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
function spawnDetached(command, args) {
|
|
30
|
+
try {
|
|
31
|
+
const child = spawn(command, args, {
|
|
32
|
+
detached: true,
|
|
33
|
+
stdio: 'ignore',
|
|
34
|
+
windowsHide: true,
|
|
35
|
+
});
|
|
36
|
+
child.on('error', () => { });
|
|
37
|
+
child.unref();
|
|
38
|
+
return Boolean(child.pid);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function isMemosebuiServerRunning(port, host = '127.0.0.1') {
|
|
45
|
+
try {
|
|
46
|
+
const res = await fetch(`http://${host}:${port}/api/health`, {
|
|
47
|
+
signal: AbortSignal.timeout(450),
|
|
48
|
+
});
|
|
49
|
+
if (!res.ok)
|
|
50
|
+
return false;
|
|
51
|
+
const data = (await res.json());
|
|
52
|
+
return Boolean(data && typeof data === 'object' && data.status === 'ok');
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function launchStandaloneDesktopWindow(url, forceBrowser = false) {
|
|
59
|
+
if (forceBrowser) {
|
|
60
|
+
if (process.platform === 'darwin') {
|
|
61
|
+
spawnDetached('open', [url]);
|
|
62
|
+
}
|
|
63
|
+
else if (process.platform === 'win32') {
|
|
64
|
+
spawnDetached('cmd.exe', ['/c', 'start', '', url]);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
spawnDetached('xdg-open', [url]);
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const appArgs = [
|
|
72
|
+
`--app=${url}`,
|
|
73
|
+
'--window-size=1360,860',
|
|
74
|
+
'--class=memosebui',
|
|
75
|
+
];
|
|
76
|
+
if (process.platform === 'linux') {
|
|
77
|
+
const omarchyWebapp = findExecutableInPath('omarchy-launch-webapp');
|
|
78
|
+
if (omarchyWebapp) {
|
|
79
|
+
if (spawnDetached(omarchyWebapp, [
|
|
80
|
+
url,
|
|
81
|
+
'--window-size=1360,860',
|
|
82
|
+
'--class=memosebui',
|
|
83
|
+
])) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const candidates = [
|
|
88
|
+
'chromium',
|
|
89
|
+
'google-chrome',
|
|
90
|
+
'google-chrome-stable',
|
|
91
|
+
'brave',
|
|
92
|
+
'brave-browser',
|
|
93
|
+
'microsoft-edge',
|
|
94
|
+
];
|
|
95
|
+
for (const bin of candidates) {
|
|
96
|
+
const resolved = findExecutableInPath(bin);
|
|
97
|
+
if (resolved && spawnDetached(resolved, appArgs)) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
spawnDetached('xdg-open', [url]);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (process.platform === 'darwin') {
|
|
105
|
+
const macCandidates = [
|
|
106
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
107
|
+
'/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
|
|
108
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
109
|
+
];
|
|
110
|
+
for (const bin of macCandidates) {
|
|
111
|
+
if (existsSync(bin) && spawnDetached(bin, appArgs)) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
spawnDetached('open', [url]);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (process.platform === 'win32') {
|
|
119
|
+
const winCandidates = ['msedge', 'chrome', 'brave'];
|
|
120
|
+
for (const bin of winCandidates) {
|
|
121
|
+
const resolved = findExecutableInPath(bin);
|
|
122
|
+
if (resolved && spawnDetached(resolved, appArgs)) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
spawnDetached('cmd.exe', ['/c', 'start', '', url]);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
spawnDetached('xdg-open', [url]);
|
|
130
|
+
}
|
|
131
|
+
export function generateMemosebUiHtml(initialProject = 'all') {
|
|
132
|
+
return `<!DOCTYPE html>
|
|
133
|
+
<html lang="es" data-theme="dark">
|
|
134
|
+
<head>
|
|
135
|
+
<meta charset="UTF-8">
|
|
136
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
137
|
+
<title>memosebui — Visor Neuronal de Memoria para memoseb</title>
|
|
138
|
+
<link rel="stylesheet" href="/styles/mind.css">
|
|
139
|
+
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🧠</text></svg>">
|
|
140
|
+
</head>
|
|
141
|
+
<body>
|
|
142
|
+
<div class="mind-shell">
|
|
143
|
+
<header class="mind-topbar">
|
|
144
|
+
<div class="topbar-left">
|
|
145
|
+
<span class="brand-badge"><span class="brand-mark">M</span>memosebui</span>
|
|
146
|
+
<span id="liveIndicator" class="live-indicator">
|
|
147
|
+
<span id="liveDot" class="live-dot"></span>
|
|
148
|
+
<span id="liveText">Conectando…</span>
|
|
149
|
+
</span>
|
|
150
|
+
</div>
|
|
151
|
+
|
|
152
|
+
<div class="topbar-center">
|
|
153
|
+
<select id="projectSelector" class="mind-select" aria-label="Filtrar por proyecto">
|
|
154
|
+
<option value="all">Todos los proyectos</option>
|
|
155
|
+
</select>
|
|
156
|
+
|
|
157
|
+
<div class="search-box">
|
|
158
|
+
<span class="search-icon">🔍</span>
|
|
159
|
+
<input id="searchInput" type="text" class="search-input" placeholder="Buscar recuerdos…" autocomplete="off" />
|
|
160
|
+
<span class="search-kbd">⌘K</span>
|
|
161
|
+
</div>
|
|
162
|
+
|
|
163
|
+
<button id="groupToggleBtn" class="btn" title="Agrupar por anillos de categoría">
|
|
164
|
+
<span>◎ Categorías</span>
|
|
165
|
+
</button>
|
|
166
|
+
</div>
|
|
167
|
+
|
|
168
|
+
<div class="topbar-right">
|
|
169
|
+
<button id="analyzeBtn" class="btn" title="Analizar un repositorio con memoseb analyze">
|
|
170
|
+
<span>⚡ Analizar</span>
|
|
171
|
+
</button>
|
|
172
|
+
<button id="p2pToggleBtn" class="btn" title="Ver topología de red P2P y Grupos ACL">
|
|
173
|
+
<span>🌐 Red P2P</span>
|
|
174
|
+
</button>
|
|
175
|
+
<button id="themeToggleBtn" class="btn" title="Alternar tema Oscuro / Claro">
|
|
176
|
+
<span id="themeIcon">☀️</span>
|
|
177
|
+
</button>
|
|
178
|
+
<button id="newMemoryBtn" class="btn btn-primary" title="Registrar nuevo recuerdo en memoseb">
|
|
179
|
+
<span>+ Recuerdo</span>
|
|
180
|
+
</button>
|
|
181
|
+
</div>
|
|
182
|
+
</header>
|
|
183
|
+
|
|
184
|
+
<div class="mind-workspace">
|
|
185
|
+
<div class="graph-stage">
|
|
186
|
+
<div class="floating-filters" id="categoryFilters">
|
|
187
|
+
<button class="cat-chip active" data-cat="all">Todas</button>
|
|
188
|
+
<button class="cat-chip" data-cat="architecture"><span class="cat-dot" style="background:#67E8F9"></span>architecture</button>
|
|
189
|
+
<button class="cat-chip" data-cat="convention"><span class="cat-dot" style="background:#A78BFA"></span>convention</button>
|
|
190
|
+
<button class="cat-chip" data-cat="bugfix"><span class="cat-dot" style="background:#FB923C"></span>bugfix</button>
|
|
191
|
+
<button class="cat-chip" data-cat="decision"><span class="cat-dot" style="background:#34D399"></span>decision</button>
|
|
192
|
+
<button class="cat-chip" data-cat="domain"><span class="cat-dot" style="background:#818CF8"></span>domain</button>
|
|
193
|
+
</div>
|
|
194
|
+
|
|
195
|
+
<canvas id="mindCanvas"></canvas>
|
|
196
|
+
|
|
197
|
+
<div class="floating-hud">
|
|
198
|
+
<div class="hud-slider-group">
|
|
199
|
+
<span>Similitud</span>
|
|
200
|
+
<input id="simSlider" type="range" min="0.20" max="0.80" step="0.02" value="0.38" />
|
|
201
|
+
<strong id="simValueLabel">38%</strong>
|
|
202
|
+
</div>
|
|
203
|
+
<span>·</span>
|
|
204
|
+
<button id="resetViewBtn" class="hud-pill-btn">Centrar</button>
|
|
205
|
+
<button id="loadAllBtn" class="hud-pill-btn" style="display:none;">Ver todos</button>
|
|
206
|
+
<span id="graphMetricsLabel">0 nodos · 0 enlaces</span>
|
|
207
|
+
</div>
|
|
208
|
+
|
|
209
|
+
<!-- P2P & ACL Overlay View -->
|
|
210
|
+
<section id="p2pPanel" class="p2p-panel" aria-label="Red P2P y Grupos ACL">
|
|
211
|
+
<div style="display:flex;justify-content:space-between;align-items:center;">
|
|
212
|
+
<div>
|
|
213
|
+
<h2 style="font-size:17px;font-weight:700;">🌐 Topología P2P y Grupos ACL de memoseb</h2>
|
|
214
|
+
<p style="font-size:12px;color:var(--text-secondary);margin-top:2px;">Estado del nodo local, peers federados y permisos de sincronización por proyecto/categoría.</p>
|
|
215
|
+
</div>
|
|
216
|
+
<button id="closeP2pBtn" class="btn">Cerrar vista P2P</button>
|
|
217
|
+
</div>
|
|
218
|
+
<div id="p2pContent" class="p2p-grid"></div>
|
|
219
|
+
</section>
|
|
220
|
+
</div>
|
|
221
|
+
|
|
222
|
+
<!-- Right Inspector Drawer -->
|
|
223
|
+
<aside class="inspector-drawer" id="inspectorDrawer">
|
|
224
|
+
<div class="inspector-header">
|
|
225
|
+
<span class="inspector-title" id="inspectorHeaderTitle">Inspector de Nodo</span>
|
|
226
|
+
<div style="display:flex;gap:6px;" id="inspectorActions"></div>
|
|
227
|
+
</div>
|
|
228
|
+
<div class="inspector-body" id="inspectorBody">
|
|
229
|
+
<p style="color:var(--text-secondary);font-size:13px;">Haz clic en cualquier nodo del grafo o realiza una búsqueda híbrida para inspeccionar su contenido, vectores semánticos y conexiones.</p>
|
|
230
|
+
</div>
|
|
231
|
+
</aside>
|
|
232
|
+
</div>
|
|
233
|
+
|
|
234
|
+
<!-- Modal: Create / Edit Memory -->
|
|
235
|
+
<div id="memoryModal" class="modal-backdrop">
|
|
236
|
+
<form id="memoryForm" class="modal-card">
|
|
237
|
+
<h3 id="modalTitle" style="font-size:16px;font-weight:700;">Nuevo Recuerdo en memoseb</h3>
|
|
238
|
+
<input type="hidden" id="editMemoryId" value="" />
|
|
239
|
+
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
|
|
240
|
+
<div class="form-field">
|
|
241
|
+
<label for="memProjectInput">Proyecto (slug)</label>
|
|
242
|
+
<input id="memProjectInput" class="form-input" type="text" placeholder="ej. memoseb, deckseb, global" required />
|
|
243
|
+
</div>
|
|
244
|
+
<div class="form-field">
|
|
245
|
+
<label for="memCategoryInput">Categoría</label>
|
|
246
|
+
<select id="memCategoryInput" class="form-select">
|
|
247
|
+
<option value="architecture">architecture</option>
|
|
248
|
+
<option value="convention">convention</option>
|
|
249
|
+
<option value="bugfix">bugfix</option>
|
|
250
|
+
<option value="decision">decision</option>
|
|
251
|
+
<option value="domain">domain</option>
|
|
252
|
+
</select>
|
|
253
|
+
</div>
|
|
254
|
+
</div>
|
|
255
|
+
<div class="form-field">
|
|
256
|
+
<label for="memTitleInput">Título del aprendizaje</label>
|
|
257
|
+
<input id="memTitleInput" class="form-input" type="text" placeholder="Ej. Motor de persistencia híbrido SQLite WAL" required />
|
|
258
|
+
</div>
|
|
259
|
+
<div class="form-field">
|
|
260
|
+
<label for="memContentInput">Contenido detallado</label>
|
|
261
|
+
<textarea id="memContentInput" class="form-textarea" placeholder="Describe la decisión arquitectónica, convención o causa raíz…" required></textarea>
|
|
262
|
+
</div>
|
|
263
|
+
<div style="display:grid;grid-template-columns:2fr 1fr;gap:10px;">
|
|
264
|
+
<div class="form-field">
|
|
265
|
+
<label for="memTagsInput">Etiquetas (separadas por coma)</label>
|
|
266
|
+
<input id="memTagsInput" class="form-input" type="text" placeholder="sqlite, fts5, vectors" />
|
|
267
|
+
</div>
|
|
268
|
+
<div class="form-field">
|
|
269
|
+
<label for="memImportanceInput">Importancia (0.1 - 1.0)</label>
|
|
270
|
+
<input id="memImportanceInput" class="form-input" type="number" min="0.1" max="1.0" step="0.05" value="0.8" />
|
|
271
|
+
</div>
|
|
272
|
+
</div>
|
|
273
|
+
<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:4px;">
|
|
274
|
+
<button type="button" id="cancelMemoryModalBtn" class="btn">Cancelar</button>
|
|
275
|
+
<button type="submit" class="btn btn-primary">Guardar en Bóveda</button>
|
|
276
|
+
</div>
|
|
277
|
+
</form>
|
|
278
|
+
</div>
|
|
279
|
+
|
|
280
|
+
<!-- Modal: Analyze Repository -->
|
|
281
|
+
<div id="analyzeModal" class="modal-backdrop">
|
|
282
|
+
<form id="analyzeForm" class="modal-card">
|
|
283
|
+
<h3 style="font-size:16px;font-weight:700;">⚡ Analizar Repositorio con memoseb</h3>
|
|
284
|
+
<p style="font-size:12.5px;color:var(--text-secondary);">Inspecciona manifiestos, scripts y topología del directorio para sintetizar automáticamente sus nodos base (architecture, convention y domain).</p>
|
|
285
|
+
<div class="form-field">
|
|
286
|
+
<label for="analyzePathInput">Ruta absoluta del repositorio</label>
|
|
287
|
+
<input id="analyzePathInput" class="form-input" type="text" placeholder="/home/alan/Documents/projects/mi-proyecto" required />
|
|
288
|
+
</div>
|
|
289
|
+
<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:4px;">
|
|
290
|
+
<button type="button" id="cancelAnalyzeModalBtn" class="btn">Cancelar</button>
|
|
291
|
+
<button type="submit" class="btn btn-primary">Ejecutar Análisis</button>
|
|
292
|
+
</div>
|
|
293
|
+
</form>
|
|
294
|
+
</div>
|
|
295
|
+
</div>
|
|
296
|
+
|
|
297
|
+
<script>
|
|
298
|
+
(function() {
|
|
299
|
+
const INITIAL_PROJECT = ${JSON.stringify(initialProject)};
|
|
300
|
+
const queryProject = new URLSearchParams(window.location.search).get('project');
|
|
301
|
+
let currentProject = queryProject || INITIAL_PROJECT || 'all';
|
|
302
|
+
let currentCategory = 'all';
|
|
303
|
+
let minSimilarity = 0.38;
|
|
304
|
+
let groupByCategory = false;
|
|
305
|
+
let showAllNodes = false;
|
|
306
|
+
const DEFAULT_OVERVIEW_LIMIT = 450;
|
|
307
|
+
|
|
308
|
+
let snapshot = null;
|
|
309
|
+
let simNodes = [];
|
|
310
|
+
let simEdges = [];
|
|
311
|
+
let particles = [];
|
|
312
|
+
let ripples = [];
|
|
313
|
+
let simAlpha = 1;
|
|
314
|
+
let selectedNodeId = null;
|
|
315
|
+
let hoveredNodeId = null;
|
|
316
|
+
let draggedNode = null;
|
|
317
|
+
let searchScoresById = new Map();
|
|
318
|
+
|
|
319
|
+
// Camera transform
|
|
320
|
+
let camX = 0;
|
|
321
|
+
let camY = 0;
|
|
322
|
+
let camScale = 1;
|
|
323
|
+
let targetCamX = 0;
|
|
324
|
+
let targetCamY = 0;
|
|
325
|
+
let targetCamScale = 1;
|
|
326
|
+
let isPanning = false;
|
|
327
|
+
let panStartX = 0;
|
|
328
|
+
let panStartY = 0;
|
|
329
|
+
|
|
330
|
+
const canvas = document.getElementById('mindCanvas');
|
|
331
|
+
const ctx = canvas.getContext('2d');
|
|
332
|
+
const projectSelector = document.getElementById('projectSelector');
|
|
333
|
+
const searchInput = document.getElementById('searchInput');
|
|
334
|
+
const simSlider = document.getElementById('simSlider');
|
|
335
|
+
const simValueLabel = document.getElementById('simValueLabel');
|
|
336
|
+
const graphMetricsLabel = document.getElementById('graphMetricsLabel');
|
|
337
|
+
const liveDot = document.getElementById('liveDot');
|
|
338
|
+
const liveText = document.getElementById('liveText');
|
|
339
|
+
const inspectorHeaderTitle = document.getElementById('inspectorHeaderTitle');
|
|
340
|
+
const inspectorActions = document.getElementById('inspectorActions');
|
|
341
|
+
const inspectorBody = document.getElementById('inspectorBody');
|
|
342
|
+
const groupToggleBtn = document.getElementById('groupToggleBtn');
|
|
343
|
+
const loadAllBtn = document.getElementById('loadAllBtn');
|
|
344
|
+
const p2pToggleBtn = document.getElementById('p2pToggleBtn');
|
|
345
|
+
const p2pPanel = document.getElementById('p2pPanel');
|
|
346
|
+
const p2pContent = document.getElementById('p2pContent');
|
|
347
|
+
|
|
348
|
+
function escapeHtml(str) {
|
|
349
|
+
return String(str || '')
|
|
350
|
+
.replace(/&/g, '&')
|
|
351
|
+
.replace(/</g, '<')
|
|
352
|
+
.replace(/>/g, '>')
|
|
353
|
+
.replace(/"/g, '"')
|
|
354
|
+
.replace(/'/g, ''');
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Theme
|
|
358
|
+
function initTheme() {
|
|
359
|
+
const saved = localStorage.getItem('memosebui-theme') || 'dark';
|
|
360
|
+
applyTheme(saved);
|
|
361
|
+
}
|
|
362
|
+
function applyTheme(theme) {
|
|
363
|
+
document.documentElement.setAttribute('data-theme', theme);
|
|
364
|
+
localStorage.setItem('memosebui-theme', theme);
|
|
365
|
+
const icon = document.getElementById('themeIcon');
|
|
366
|
+
if (icon) icon.textContent = theme === 'dark' ? '☀️' : '🌙';
|
|
367
|
+
}
|
|
368
|
+
document.getElementById('themeToggleBtn').addEventListener('click', () => {
|
|
369
|
+
const cur = document.documentElement.getAttribute('data-theme') || 'dark';
|
|
370
|
+
applyTheme(cur === 'dark' ? 'light' : 'dark');
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
// Resize HiDPI Canvas
|
|
374
|
+
function resizeCanvas() {
|
|
375
|
+
const rect = canvas.parentElement.getBoundingClientRect();
|
|
376
|
+
const dpr = window.devicePixelRatio || 1;
|
|
377
|
+
canvas.width = rect.width * dpr;
|
|
378
|
+
canvas.height = rect.height * dpr;
|
|
379
|
+
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
380
|
+
if (camX === 0 && camY === 0) {
|
|
381
|
+
camX = targetCamX = rect.width / 2;
|
|
382
|
+
camY = targetCamY = rect.height / 2;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
window.addEventListener('resize', resizeCanvas);
|
|
386
|
+
resizeCanvas();
|
|
387
|
+
|
|
388
|
+
function resetCamera() {
|
|
389
|
+
const rect = canvas.parentElement.getBoundingClientRect();
|
|
390
|
+
targetCamX = rect.width / 2;
|
|
391
|
+
targetCamY = rect.height / 2;
|
|
392
|
+
targetCamScale = 1;
|
|
393
|
+
}
|
|
394
|
+
document.getElementById('resetViewBtn').addEventListener('click', resetCamera);
|
|
395
|
+
|
|
396
|
+
// Load Graph Snapshot (with adaptive hybrid limit)
|
|
397
|
+
async function loadGraph(spawnRippleForId) {
|
|
398
|
+
const useLimit = !showAllNodes && currentProject === 'all' && currentCategory === 'all';
|
|
399
|
+
const params = new URLSearchParams({
|
|
400
|
+
project: currentProject,
|
|
401
|
+
category: currentCategory,
|
|
402
|
+
minSimilarity: String(minSimilarity),
|
|
403
|
+
groupByCategory: String(groupByCategory),
|
|
404
|
+
limit: useLimit ? String(DEFAULT_OVERVIEW_LIMIT) : '0',
|
|
405
|
+
});
|
|
406
|
+
const res = await fetch('/api/graph?' + params.toString());
|
|
407
|
+
if (!res.ok) return;
|
|
408
|
+
snapshot = await res.json();
|
|
409
|
+
|
|
410
|
+
updateProjectDropdown(snapshot.projects);
|
|
411
|
+
liveText.textContent =
|
|
412
|
+
'En vivo · ' +
|
|
413
|
+
snapshot.stats.memoryCount.toLocaleString() +
|
|
414
|
+
' recuerdos · ' +
|
|
415
|
+
snapshot.stats.totalTokens.toLocaleString() +
|
|
416
|
+
' tokens';
|
|
417
|
+
|
|
418
|
+
const totalAvail = snapshot.totalAvailableMemories || snapshot.stats.memoryCount;
|
|
419
|
+
if (snapshot.truncated) {
|
|
420
|
+
loadAllBtn.style.display = 'inline-flex';
|
|
421
|
+
loadAllBtn.classList.remove('active');
|
|
422
|
+
loadAllBtn.textContent = 'Ver todos (' + totalAvail.toLocaleString() + ')';
|
|
423
|
+
} else if (showAllNodes && totalAvail > DEFAULT_OVERVIEW_LIMIT && currentProject === 'all' && currentCategory === 'all') {
|
|
424
|
+
loadAllBtn.style.display = 'inline-flex';
|
|
425
|
+
loadAllBtn.classList.add('active');
|
|
426
|
+
loadAllBtn.textContent = 'Vista rápida (' + DEFAULT_OVERVIEW_LIMIT + ')';
|
|
427
|
+
} else {
|
|
428
|
+
loadAllBtn.style.display = 'none';
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
graphMetricsLabel.textContent =
|
|
432
|
+
snapshot.nodes.length + ' nodos · ' + snapshot.edges.length + ' enlaces';
|
|
433
|
+
|
|
434
|
+
syncPhysicsGraph(snapshot, spawnRippleForId);
|
|
435
|
+
renderP2pView(snapshot.p2p);
|
|
436
|
+
|
|
437
|
+
if (selectedNodeId) {
|
|
438
|
+
const found = simNodes.find(n => n.id === selectedNodeId);
|
|
439
|
+
if (found) renderInspectorForNode(found);
|
|
440
|
+
else renderOverviewInspector();
|
|
441
|
+
} else {
|
|
442
|
+
renderOverviewInspector();
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function updateProjectDropdown(projects) {
|
|
447
|
+
const prev = currentProject;
|
|
448
|
+
projectSelector.innerHTML = '<option value="all">Todos los proyectos (' + projects.length + ')</option>';
|
|
449
|
+
projects.forEach(p => {
|
|
450
|
+
const opt = document.createElement('option');
|
|
451
|
+
opt.value = p.id;
|
|
452
|
+
opt.textContent = p.name + ' (' + p.memoryCount + ')';
|
|
453
|
+
if (p.id === prev) opt.selected = true;
|
|
454
|
+
projectSelector.appendChild(opt);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function syncPhysicsGraph(snap, highlightNewId) {
|
|
459
|
+
const oldPos = new Map();
|
|
460
|
+
simNodes.forEach(n => {
|
|
461
|
+
oldPos.set(n.id, { x: n.x, y: n.y, vx: n.vx, vy: n.vy, pinned: n.pinned });
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
const projCount = Math.max(1, snap.nodes.filter(n => n.type === 'project').length);
|
|
465
|
+
let projIndex = 0;
|
|
466
|
+
const projCenters = new Map();
|
|
467
|
+
|
|
468
|
+
simNodes = snap.nodes.map((n, idx) => {
|
|
469
|
+
const existing = oldPos.get(n.id);
|
|
470
|
+
if (existing) {
|
|
471
|
+
return Object.assign({}, n, existing);
|
|
472
|
+
}
|
|
473
|
+
let x = 0;
|
|
474
|
+
let y = 0;
|
|
475
|
+
if (n.type === 'project') {
|
|
476
|
+
const angle = (projIndex / projCount) * Math.PI * 2;
|
|
477
|
+
const ringR = projCount === 1 ? 0 : 190;
|
|
478
|
+
x = Math.cos(angle) * ringR;
|
|
479
|
+
y = Math.sin(angle) * ringR;
|
|
480
|
+
projCenters.set(n.projectId, { x, y });
|
|
481
|
+
projIndex++;
|
|
482
|
+
} else {
|
|
483
|
+
const center = projCenters.get(n.projectId) || { x: 0, y: 0 };
|
|
484
|
+
const a = (idx * 2.39996) % (Math.PI * 2);
|
|
485
|
+
const r = 70 + (idx % 5) * 26;
|
|
486
|
+
x = center.x + Math.cos(a) * r;
|
|
487
|
+
y = center.y + Math.sin(a) * r;
|
|
488
|
+
}
|
|
489
|
+
if (highlightNewId && n.memoryId === highlightNewId) {
|
|
490
|
+
ripples.push({ x, y, r: n.radius, maxR: 95, alpha: 1, color: n.color });
|
|
491
|
+
}
|
|
492
|
+
return Object.assign({}, n, { x, y, vx: 0, vy: 0, pinned: false, phase: Math.random() * Math.PI * 2 });
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
const nodeMap = new Map(simNodes.map(n => [n.id, n]));
|
|
496
|
+
simEdges = snap.edges
|
|
497
|
+
.map(e => ({
|
|
498
|
+
...e,
|
|
499
|
+
sourceNode: nodeMap.get(e.source),
|
|
500
|
+
targetNode: nodeMap.get(e.target),
|
|
501
|
+
}))
|
|
502
|
+
.filter(e => e.sourceNode && e.targetNode);
|
|
503
|
+
|
|
504
|
+
// Rebuild synaptic particles (capped for performance)
|
|
505
|
+
const maxParticles = simNodes.length > 500 ? 35 : 70;
|
|
506
|
+
particles = simEdges.slice(0, maxParticles).map((edge, i) => ({
|
|
507
|
+
edge,
|
|
508
|
+
t: (i * 0.17) % 1,
|
|
509
|
+
speed: edge.kind === 'semantic-similarity' ? 0.0055 : 0.0038,
|
|
510
|
+
}));
|
|
511
|
+
|
|
512
|
+
// Wake simulation & pre-warm layout synchronously
|
|
513
|
+
simAlpha = 1;
|
|
514
|
+
const prewarmTicks = simNodes.length > 600 ? 30 : 45;
|
|
515
|
+
for (let t = 0; t < prewarmTicks; t++) {
|
|
516
|
+
runPhysicsTick();
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// O(N) Spatial Hash Grid Physics Tick
|
|
521
|
+
const GRID_CELL = 180;
|
|
522
|
+
const spatialGrid = new Map();
|
|
523
|
+
function runPhysicsTick() {
|
|
524
|
+
const N = simNodes.length;
|
|
525
|
+
if (N === 0) return;
|
|
526
|
+
const alpha = simAlpha;
|
|
527
|
+
spatialGrid.clear();
|
|
528
|
+
|
|
529
|
+
for (let i = 0; i < N; i++) {
|
|
530
|
+
const n = simNodes[i];
|
|
531
|
+
if (!n.pinned && n !== draggedNode) {
|
|
532
|
+
const grav = n.type === 'project' ? 0.0022 : 0.0008;
|
|
533
|
+
n.vx -= n.x * grav * alpha;
|
|
534
|
+
n.vy -= n.y * grav * alpha;
|
|
535
|
+
}
|
|
536
|
+
const cx = Math.floor(n.x / GRID_CELL);
|
|
537
|
+
const cy = Math.floor(n.y / GRID_CELL);
|
|
538
|
+
const key = (cx + 32768) * 65536 + (cy + 32768);
|
|
539
|
+
let bucket = spatialGrid.get(key);
|
|
540
|
+
if (!bucket) {
|
|
541
|
+
bucket = [];
|
|
542
|
+
spatialGrid.set(key, bucket);
|
|
543
|
+
}
|
|
544
|
+
bucket.push(n);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// Repulsion only against 3x3 neighboring spatial cells
|
|
548
|
+
for (let i = 0; i < N; i++) {
|
|
549
|
+
const a = simNodes[i];
|
|
550
|
+
const cx = Math.floor(a.x / GRID_CELL);
|
|
551
|
+
const cy = Math.floor(a.y / GRID_CELL);
|
|
552
|
+
for (let ox = -1; ox <= 1; ox++) {
|
|
553
|
+
for (let oy = -1; oy <= 1; oy++) {
|
|
554
|
+
const key = (cx + ox + 32768) * 65536 + (cy + oy + 32768);
|
|
555
|
+
const bucket = spatialGrid.get(key);
|
|
556
|
+
if (!bucket) continue;
|
|
557
|
+
for (let k = 0; k < bucket.length; k++) {
|
|
558
|
+
const b = bucket[k];
|
|
559
|
+
if (b === a || a.id >= b.id) continue;
|
|
560
|
+
let dx = b.x - a.x;
|
|
561
|
+
let dy = b.y - a.y;
|
|
562
|
+
let distSq = dx * dx + dy * dy;
|
|
563
|
+
if (distSq < 4) {
|
|
564
|
+
dx = (Math.random() - 0.5) * 2;
|
|
565
|
+
dy = (Math.random() - 0.5) * 2;
|
|
566
|
+
distSq = 4;
|
|
567
|
+
}
|
|
568
|
+
if (distSq < 32400) {
|
|
569
|
+
const dist = Math.sqrt(distSq);
|
|
570
|
+
const minGap = a.radius + b.radius + 22;
|
|
571
|
+
const repulse = (a.type === 'project' || b.type === 'project') ? 2200 : 1050;
|
|
572
|
+
let force = (repulse / distSq) * alpha;
|
|
573
|
+
if (dist < minGap) force += (minGap - dist) * 0.14 * alpha;
|
|
574
|
+
const fx = (dx / dist) * force;
|
|
575
|
+
const fy = (dy / dist) * force;
|
|
576
|
+
if (!a.pinned && a !== draggedNode) { a.vx -= fx; a.vy -= fy; }
|
|
577
|
+
if (!b.pinned && b !== draggedNode) { b.vx += fx; b.vy += fy; }
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// Spring forces on edges
|
|
585
|
+
for (let i = 0; i < simEdges.length; i++) {
|
|
586
|
+
const e = simEdges[i];
|
|
587
|
+
const s = e.sourceNode;
|
|
588
|
+
const t = e.targetNode;
|
|
589
|
+
const dx = t.x - s.x;
|
|
590
|
+
const dy = t.y - s.y;
|
|
591
|
+
const dist = Math.sqrt(dx * dx + dy * dy) || 1;
|
|
592
|
+
const targetLen =
|
|
593
|
+
e.kind === 'project-memory' ? 115 :
|
|
594
|
+
e.kind === 'project-category' ? 85 :
|
|
595
|
+
e.kind === 'category-memory' ? 76 :
|
|
596
|
+
e.kind === 'semantic-similarity' ? 140 : 155;
|
|
597
|
+
const k = (e.kind === 'semantic-similarity' ? 0.014 * e.weight : 0.032) * alpha;
|
|
598
|
+
const f = (dist - targetLen) * k;
|
|
599
|
+
const fx = (dx / dist) * f;
|
|
600
|
+
const fy = (dy / dist) * f;
|
|
601
|
+
if (!s.pinned && s !== draggedNode) { s.vx += fx; s.vy += fy; }
|
|
602
|
+
if (!t.pinned && t !== draggedNode) { t.vx -= fx; t.vy -= fy; }
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
// Integrate velocities
|
|
606
|
+
for (let i = 0; i < N; i++) {
|
|
607
|
+
const n = simNodes[i];
|
|
608
|
+
if (n.pinned || n === draggedNode) {
|
|
609
|
+
n.vx = 0;
|
|
610
|
+
n.vy = 0;
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
n.vx *= 0.80;
|
|
614
|
+
n.vy *= 0.80;
|
|
615
|
+
n.x += n.vx;
|
|
616
|
+
n.y += n.vy;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
if (!draggedNode) {
|
|
620
|
+
simAlpha = Math.max(0, simAlpha * 0.982);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// Physics Step & 60fps Batched Canvas Render
|
|
625
|
+
let frameTick = 0;
|
|
626
|
+
function stepAndRender() {
|
|
627
|
+
frameTick += 0.035;
|
|
628
|
+
const rect = canvas.parentElement.getBoundingClientRect();
|
|
629
|
+
const W = rect.width;
|
|
630
|
+
const H = rect.height;
|
|
631
|
+
|
|
632
|
+
// Smooth camera interpolation
|
|
633
|
+
camX += (targetCamX - camX) * 0.14;
|
|
634
|
+
camY += (targetCamY - camY) * 0.14;
|
|
635
|
+
camScale += (targetCamScale - camScale) * 0.14;
|
|
636
|
+
|
|
637
|
+
// 1. Physics forces (pause when cooled)
|
|
638
|
+
if (simAlpha >= 0.008 || draggedNode) {
|
|
639
|
+
runPhysicsTick();
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// 2. Render Canvas with Viewport Culling & Batching
|
|
643
|
+
ctx.clearRect(0, 0, W, H);
|
|
644
|
+
ctx.save();
|
|
645
|
+
ctx.translate(camX, camY);
|
|
646
|
+
ctx.scale(camScale, camScale);
|
|
647
|
+
|
|
648
|
+
const pad = 80 / camScale;
|
|
649
|
+
const viewMinX = -camX / camScale - pad;
|
|
650
|
+
const viewMaxX = (W - camX) / camScale + pad;
|
|
651
|
+
const viewMinY = -camY / camScale - pad;
|
|
652
|
+
const viewMaxY = (H - camY) / camScale + pad;
|
|
653
|
+
|
|
654
|
+
const N = simNodes.length;
|
|
655
|
+
const activeFocusId = hoveredNodeId || selectedNodeId;
|
|
656
|
+
const neighborIds = new Set();
|
|
657
|
+
if (activeFocusId) {
|
|
658
|
+
neighborIds.add(activeFocusId);
|
|
659
|
+
for (let i = 0; i < simEdges.length; i++) {
|
|
660
|
+
const e = simEdges[i];
|
|
661
|
+
if (e.source === activeFocusId) neighborIds.add(e.target);
|
|
662
|
+
if (e.target === activeFocusId) neighborIds.add(e.source);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// Batched Edges by category (3 draw calls instead of 10,000)
|
|
667
|
+
const isLight = document.documentElement.getAttribute('data-theme') === 'light';
|
|
668
|
+
const highlightedEdges = [];
|
|
669
|
+
|
|
670
|
+
ctx.lineWidth = 1.1;
|
|
671
|
+
ctx.strokeStyle = activeFocusId
|
|
672
|
+
? (isLight ? 'rgba(17,24,39,0.05)' : 'rgba(255,255,255,0.04)')
|
|
673
|
+
: (isLight ? 'rgba(17,24,39,0.12)' : 'rgba(255,255,255,0.09)');
|
|
674
|
+
ctx.beginPath();
|
|
675
|
+
for (let i = 0; i < simEdges.length; i++) {
|
|
676
|
+
const e = simEdges[i];
|
|
677
|
+
if (e.kind === 'semantic-similarity' || e.kind === 'shared-tag') continue;
|
|
678
|
+
const s = e.sourceNode;
|
|
679
|
+
const t = e.targetNode;
|
|
680
|
+
if ((s.x < viewMinX && t.x < viewMinX) || (s.x > viewMaxX && t.x > viewMaxX) ||
|
|
681
|
+
(s.y < viewMinY && t.y < viewMinY) || (s.y > viewMaxY && t.y > viewMaxY)) continue;
|
|
682
|
+
if (activeFocusId && (e.source === activeFocusId || e.target === activeFocusId)) {
|
|
683
|
+
highlightedEdges.push(e);
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
ctx.moveTo(s.x, s.y);
|
|
687
|
+
ctx.lineTo(t.x, t.y);
|
|
688
|
+
}
|
|
689
|
+
ctx.stroke();
|
|
690
|
+
|
|
691
|
+
ctx.strokeStyle = activeFocusId
|
|
692
|
+
? 'rgba(167, 139, 250, 0.06)'
|
|
693
|
+
: 'rgba(167, 139, 250, 0.24)';
|
|
694
|
+
ctx.beginPath();
|
|
695
|
+
for (let i = 0; i < simEdges.length; i++) {
|
|
696
|
+
const e = simEdges[i];
|
|
697
|
+
if (e.kind !== 'semantic-similarity') continue;
|
|
698
|
+
const s = e.sourceNode;
|
|
699
|
+
const t = e.targetNode;
|
|
700
|
+
if ((s.x < viewMinX && t.x < viewMinX) || (s.x > viewMaxX && t.x > viewMaxX) ||
|
|
701
|
+
(s.y < viewMinY && t.y < viewMinY) || (s.y > viewMaxY && t.y > viewMaxY)) continue;
|
|
702
|
+
if (activeFocusId && (e.source === activeFocusId || e.target === activeFocusId)) {
|
|
703
|
+
highlightedEdges.push(e);
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
ctx.moveTo(s.x, s.y);
|
|
707
|
+
ctx.lineTo(t.x, t.y);
|
|
708
|
+
}
|
|
709
|
+
ctx.stroke();
|
|
710
|
+
|
|
711
|
+
ctx.save();
|
|
712
|
+
ctx.setLineDash([4, 4]);
|
|
713
|
+
ctx.strokeStyle = activeFocusId
|
|
714
|
+
? 'rgba(148, 163, 184, 0.05)'
|
|
715
|
+
: 'rgba(148, 163, 184, 0.14)';
|
|
716
|
+
ctx.beginPath();
|
|
717
|
+
for (let i = 0; i < simEdges.length; i++) {
|
|
718
|
+
const e = simEdges[i];
|
|
719
|
+
if (e.kind !== 'shared-tag') continue;
|
|
720
|
+
const s = e.sourceNode;
|
|
721
|
+
const t = e.targetNode;
|
|
722
|
+
if ((s.x < viewMinX && t.x < viewMinX) || (s.x > viewMaxX && t.x > viewMaxX) ||
|
|
723
|
+
(s.y < viewMinY && t.y < viewMinY) || (s.y > viewMaxY && t.y > viewMaxY)) continue;
|
|
724
|
+
if (activeFocusId && (e.source === activeFocusId || e.target === activeFocusId)) {
|
|
725
|
+
highlightedEdges.push(e);
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
ctx.moveTo(s.x, s.y);
|
|
729
|
+
ctx.lineTo(t.x, t.y);
|
|
730
|
+
}
|
|
731
|
+
ctx.stroke();
|
|
732
|
+
ctx.restore();
|
|
733
|
+
|
|
734
|
+
// Draw only highlighted edges individually
|
|
735
|
+
const accentStroke = isLight ? '#65A30D' : '#B8DF52';
|
|
736
|
+
const secondaryStroke = isLight ? '#0284C7' : '#67E8F9';
|
|
737
|
+
for (let i = 0; i < highlightedEdges.length; i++) {
|
|
738
|
+
const e = highlightedEdges[i];
|
|
739
|
+
const s = e.sourceNode;
|
|
740
|
+
const t = e.targetNode;
|
|
741
|
+
ctx.beginPath();
|
|
742
|
+
ctx.moveTo(s.x, s.y);
|
|
743
|
+
ctx.lineTo(t.x, t.y);
|
|
744
|
+
ctx.strokeStyle = e.kind === 'semantic-similarity' ? accentStroke : secondaryStroke;
|
|
745
|
+
ctx.lineWidth = 2.0;
|
|
746
|
+
ctx.stroke();
|
|
747
|
+
if (e.label) {
|
|
748
|
+
const mx = (s.x + t.x) / 2;
|
|
749
|
+
const my = (s.y + t.y) / 2;
|
|
750
|
+
ctx.fillStyle = isLight ? 'rgba(255,255,255,0.92)' : 'rgba(20, 23, 29, 0.9)';
|
|
751
|
+
ctx.fillRect(mx - 18, my - 8, 36, 16);
|
|
752
|
+
ctx.fillStyle = isLight ? '#111827' : '#B8DF52';
|
|
753
|
+
ctx.font = '600 9.5px sans-serif';
|
|
754
|
+
ctx.textAlign = 'center';
|
|
755
|
+
ctx.textBaseline = 'middle';
|
|
756
|
+
ctx.fillText(e.label, mx, my);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// Draw Synaptic Particles
|
|
761
|
+
if (N <= 800 || activeFocusId) {
|
|
762
|
+
for (let i = 0; i < particles.length; i++) {
|
|
763
|
+
const p = particles[i];
|
|
764
|
+
p.t = (p.t + p.speed) % 1;
|
|
765
|
+
const e = p.edge;
|
|
766
|
+
if (activeFocusId && e.source !== activeFocusId && e.target !== activeFocusId) {
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
const px = e.sourceNode.x + (e.targetNode.x - e.sourceNode.x) * p.t;
|
|
770
|
+
const py = e.sourceNode.y + (e.targetNode.y - e.sourceNode.y) * p.t;
|
|
771
|
+
if (px < viewMinX || px > viewMaxX || py < viewMinY || py > viewMaxY) continue;
|
|
772
|
+
ctx.beginPath();
|
|
773
|
+
ctx.arc(px, py, e.kind === 'semantic-similarity' ? 2.1 : 1.6, 0, Math.PI * 2);
|
|
774
|
+
ctx.fillStyle = e.kind === 'semantic-similarity' ? '#B8DF52' : '#67E8F9';
|
|
775
|
+
ctx.fill();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
// Draw Ripples
|
|
780
|
+
for (let i = ripples.length - 1; i >= 0; i--) {
|
|
781
|
+
const rp = ripples[i];
|
|
782
|
+
rp.r += 1.4;
|
|
783
|
+
rp.alpha -= 0.018;
|
|
784
|
+
if (rp.alpha <= 0) {
|
|
785
|
+
ripples.splice(i, 1);
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
ctx.save();
|
|
789
|
+
ctx.beginPath();
|
|
790
|
+
ctx.arc(rp.x, rp.y, rp.r, 0, Math.PI * 2);
|
|
791
|
+
ctx.strokeStyle = rp.color;
|
|
792
|
+
ctx.globalAlpha = rp.alpha;
|
|
793
|
+
ctx.lineWidth = 2.2;
|
|
794
|
+
ctx.stroke();
|
|
795
|
+
ctx.restore();
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Draw Nodes (with Viewport Culling & LOD)
|
|
799
|
+
const isSearchActive = searchScoresById.size > 0;
|
|
800
|
+
const showSecondaryLabels = camScale >= (N > 350 ? 0.85 : 0.52);
|
|
801
|
+
const labelColor = isLight ? '#111827' : '#F3F5F7';
|
|
802
|
+
|
|
803
|
+
for (let i = 0; i < N; i++) {
|
|
804
|
+
const n = simNodes[i];
|
|
805
|
+
if (n.x + n.radius < viewMinX || n.x - n.radius > viewMaxX ||
|
|
806
|
+
n.y + n.radius < viewMinY || n.y - n.radius > viewMaxY) {
|
|
807
|
+
continue;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
const searchHit = n.memoryId ? searchScoresById.get(n.memoryId) : null;
|
|
811
|
+
const isFocused = n.id === selectedNodeId || n.id === hoveredNodeId;
|
|
812
|
+
const isNeighbor = neighborIds.has(n.id);
|
|
813
|
+
|
|
814
|
+
let alpha = 1;
|
|
815
|
+
if (isSearchActive) {
|
|
816
|
+
alpha = (searchHit || n.type === 'project') ? 1 : 0.14;
|
|
817
|
+
} else if (activeFocusId && !isNeighbor) {
|
|
818
|
+
alpha = 0.18;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
ctx.globalAlpha = alpha;
|
|
822
|
+
|
|
823
|
+
// Subtle halo only for focused, search hit, or project nodes (keeps 2000-node render crisp)
|
|
824
|
+
if (n.type === 'project' || searchHit || isFocused) {
|
|
825
|
+
const pulse = Math.sin(frameTick + (n.phase || 0)) * 2.0;
|
|
826
|
+
ctx.beginPath();
|
|
827
|
+
ctx.arc(n.x, n.y, n.radius + 5 + Math.max(0, pulse), 0, Math.PI * 2);
|
|
828
|
+
ctx.fillStyle = isFocused || searchHit
|
|
829
|
+
? (isLight ? 'rgba(101, 163, 13, 0.22)' : 'rgba(184, 223, 82, 0.24)')
|
|
830
|
+
: n.color + '24';
|
|
831
|
+
ctx.fill();
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// Node circle
|
|
835
|
+
ctx.beginPath();
|
|
836
|
+
ctx.arc(n.x, n.y, n.radius, 0, Math.PI * 2);
|
|
837
|
+
ctx.fillStyle = n.color;
|
|
838
|
+
ctx.fill();
|
|
839
|
+
|
|
840
|
+
if (isFocused || searchHit || n.type === 'project') {
|
|
841
|
+
ctx.lineWidth = isFocused ? 2.6 : searchHit ? 2.2 : 1.4;
|
|
842
|
+
ctx.strokeStyle = isFocused || searchHit
|
|
843
|
+
? (isLight ? '#4D7C0F' : '#B8DF52')
|
|
844
|
+
: (isLight ? 'rgba(17,24,39,0.28)' : 'rgba(255,255,255,0.35)');
|
|
845
|
+
ctx.stroke();
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// Inner badge for project nodes
|
|
849
|
+
if (n.type === 'project') {
|
|
850
|
+
ctx.fillStyle = '#0D0F13';
|
|
851
|
+
ctx.font = '700 10px sans-serif';
|
|
852
|
+
ctx.textAlign = 'center';
|
|
853
|
+
ctx.textBaseline = 'middle';
|
|
854
|
+
ctx.fillText(n.label.slice(0, 3).toUpperCase(), n.x, n.y);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// Node label (LOD)
|
|
858
|
+
if (showSecondaryLabels || n.type === 'project' || isFocused || searchHit || (activeFocusId && isNeighbor)) {
|
|
859
|
+
const labelText = n.label.length > 26 ? n.label.slice(0, 24) + '…' : n.label;
|
|
860
|
+
ctx.font = (n.type === 'project' ? '700 11.5px ' : '500 10.5px ') + 'sans-serif';
|
|
861
|
+
ctx.textAlign = 'center';
|
|
862
|
+
ctx.textBaseline = 'top';
|
|
863
|
+
ctx.fillStyle = labelColor;
|
|
864
|
+
ctx.fillText(labelText, n.x, n.y + n.radius + 5);
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
ctx.globalAlpha = 1;
|
|
868
|
+
|
|
869
|
+
ctx.restore();
|
|
870
|
+
requestAnimationFrame(stepAndRender);
|
|
871
|
+
}
|
|
872
|
+
requestAnimationFrame(stepAndRender);
|
|
873
|
+
|
|
874
|
+
// Screen to World coordinates
|
|
875
|
+
function screenToWorld(clientX, clientY) {
|
|
876
|
+
const rect = canvas.getBoundingClientRect();
|
|
877
|
+
const sx = clientX - rect.left;
|
|
878
|
+
const sy = clientY - rect.top;
|
|
879
|
+
return {
|
|
880
|
+
x: (sx - camX) / camScale,
|
|
881
|
+
y: (sy - camY) / camScale,
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
function findNodeAt(wx, wy) {
|
|
886
|
+
for (let i = simNodes.length - 1; i >= 0; i--) {
|
|
887
|
+
const n = simNodes[i];
|
|
888
|
+
const dx = wx - n.x;
|
|
889
|
+
const dy = wy - n.y;
|
|
890
|
+
if (dx * dx + dy * dy <= (n.radius + 4) * (n.radius + 4)) {
|
|
891
|
+
return n;
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
return null;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
canvas.addEventListener('mousedown', (e) => {
|
|
898
|
+
const pt = screenToWorld(e.clientX, e.clientY);
|
|
899
|
+
const hit = findNodeAt(pt.x, pt.y);
|
|
900
|
+
if (hit) {
|
|
901
|
+
draggedNode = hit;
|
|
902
|
+
selectedNodeId = hit.id;
|
|
903
|
+
renderInspectorForNode(hit);
|
|
904
|
+
} else {
|
|
905
|
+
isPanning = true;
|
|
906
|
+
panStartX = e.clientX - targetCamX;
|
|
907
|
+
panStartY = e.clientY - targetCamY;
|
|
908
|
+
}
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
window.addEventListener('mousemove', (e) => {
|
|
912
|
+
const pt = screenToWorld(e.clientX, e.clientY);
|
|
913
|
+
if (draggedNode) {
|
|
914
|
+
draggedNode.x = pt.x;
|
|
915
|
+
draggedNode.y = pt.y;
|
|
916
|
+
simAlpha = Math.max(simAlpha, 0.35);
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
if (isPanning) {
|
|
920
|
+
targetCamX = e.clientX - panStartX;
|
|
921
|
+
targetCamY = e.clientY - panStartY;
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
const hit = findNodeAt(pt.x, pt.y);
|
|
925
|
+
hoveredNodeId = hit ? hit.id : null;
|
|
926
|
+
canvas.style.cursor = hit ? 'pointer' : 'grab';
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
window.addEventListener('mouseup', () => {
|
|
930
|
+
draggedNode = null;
|
|
931
|
+
isPanning = false;
|
|
932
|
+
});
|
|
933
|
+
|
|
934
|
+
canvas.addEventListener('dblclick', (e) => {
|
|
935
|
+
const pt = screenToWorld(e.clientX, e.clientY);
|
|
936
|
+
const hit = findNodeAt(pt.x, pt.y);
|
|
937
|
+
if (hit) {
|
|
938
|
+
hit.pinned = !hit.pinned;
|
|
939
|
+
if (!hit.pinned) simAlpha = Math.max(simAlpha, 0.25);
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
|
|
943
|
+
canvas.addEventListener('wheel', (e) => {
|
|
944
|
+
e.preventDefault();
|
|
945
|
+
if (e.deltaY === 0) return;
|
|
946
|
+
const factor = e.deltaY < 0 ? 1.12 : 0.89;
|
|
947
|
+
targetCamScale = Math.min(3.2, Math.max(0.28, targetCamScale * factor));
|
|
948
|
+
}, { passive: false });
|
|
949
|
+
|
|
950
|
+
function focusCameraOnNode(node) {
|
|
951
|
+
const rect = canvas.parentElement.getBoundingClientRect();
|
|
952
|
+
targetCamScale = Math.max(1.15, targetCamScale);
|
|
953
|
+
targetCamX = rect.width / 2 - node.x * targetCamScale;
|
|
954
|
+
targetCamY = rect.height / 2 - node.y * targetCamScale;
|
|
955
|
+
ripples.push({ x: node.x, y: node.y, r: node.radius, maxR: 80, alpha: 1, color: node.color });
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
// Inspector Rendering
|
|
959
|
+
function renderOverviewInspector() {
|
|
960
|
+
if (!snapshot) return;
|
|
961
|
+
inspectorHeaderTitle.textContent = 'Resumen de Bóveda';
|
|
962
|
+
inspectorActions.innerHTML = '';
|
|
963
|
+
inspectorBody.innerHTML =
|
|
964
|
+
'<div class="meta-grid">' +
|
|
965
|
+
'<div class="meta-stat"><div class="meta-stat-label">Proyectos</div><div class="meta-stat-value">' + snapshot.stats.projectCount + '</div></div>' +
|
|
966
|
+
'<div class="meta-stat"><div class="meta-stat-label">Recuerdos</div><div class="meta-stat-value">' + snapshot.stats.memoryCount + '</div></div>' +
|
|
967
|
+
'<div class="meta-stat"><div class="meta-stat-label">Tokens</div><div class="meta-stat-value">' + snapshot.stats.totalTokens + '</div></div>' +
|
|
968
|
+
'</div>' +
|
|
969
|
+
'<p style="font-size:12.5px;color:var(--text-secondary);">Selecciona un nodo en el lienzo para explorar su contenido, editarlo o navegar por sus conexiones vectoriales.</p>' +
|
|
970
|
+
'<div style="font-size:11.5px;font-weight:600;color:var(--text-secondary);margin-top:4px;">Recuerdos más recientes / importantes</div>' +
|
|
971
|
+
'<div class="related-list">' +
|
|
972
|
+
snapshot.memories.slice(0, 8).map(m =>
|
|
973
|
+
'<div class="related-item" data-jump-mem="' + escapeHtml(m.id) + '">' +
|
|
974
|
+
'<span class="related-item-title">' + escapeHtml(m.title) + '</span>' +
|
|
975
|
+
'<span class="badge">' + escapeHtml(m.projectId) + '</span>' +
|
|
976
|
+
'</div>'
|
|
977
|
+
).join('') +
|
|
978
|
+
'</div>';
|
|
979
|
+
|
|
980
|
+
bindJumpListeners();
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
function renderInspectorForNode(node) {
|
|
984
|
+
if (!snapshot) return;
|
|
985
|
+
if (node.type === 'project') {
|
|
986
|
+
const projMems = snapshot.memories.filter(m => m.projectId === node.projectId);
|
|
987
|
+
const pageSize = 40;
|
|
988
|
+
const visibleMems = projMems.slice(0, pageSize);
|
|
989
|
+
inspectorHeaderTitle.textContent = 'Nodo Proyecto';
|
|
990
|
+
inspectorActions.innerHTML = '';
|
|
991
|
+
inspectorBody.innerHTML =
|
|
992
|
+
'<div class="node-card-title">📦 ' + escapeHtml(node.label) + '</div>' +
|
|
993
|
+
'<div class="badge-row"><span class="badge">' + escapeHtml(node.subtitle || '') + '</span></div>' +
|
|
994
|
+
'<div style="font-size:11.5px;color:var(--text-muted);font-family:var(--font-mono);">' + escapeHtml((node.meta && node.meta.rootPath) || '') + '</div>' +
|
|
995
|
+
'<div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-top:6px;">Nodos aprendidos (' + projMems.length + ')</div>' +
|
|
996
|
+
'<div class="related-list" id="projMemList">' +
|
|
997
|
+
visibleMems.map(m =>
|
|
998
|
+
'<div class="related-item" data-jump-mem="' + escapeHtml(m.id) + '">' +
|
|
999
|
+
'<span class="related-item-title">' + escapeHtml(m.title) + '</span>' +
|
|
1000
|
+
'<span class="badge">' + escapeHtml(m.category) + '</span>' +
|
|
1001
|
+
'</div>'
|
|
1002
|
+
).join('') +
|
|
1003
|
+
'</div>' +
|
|
1004
|
+
(projMems.length > pageSize
|
|
1005
|
+
? '<button id="showMoreProjMemsBtn" class="btn" style="width:100%;justify-content:center;">Mostrar más (' + (projMems.length - pageSize) + ' restantes)</button>'
|
|
1006
|
+
: '');
|
|
1007
|
+
bindJumpListeners();
|
|
1008
|
+
const moreBtn = document.getElementById('showMoreProjMemsBtn');
|
|
1009
|
+
if (moreBtn) {
|
|
1010
|
+
moreBtn.addEventListener('click', () => {
|
|
1011
|
+
const listEl = document.getElementById('projMemList');
|
|
1012
|
+
if (listEl) {
|
|
1013
|
+
listEl.innerHTML = projMems.slice(0, 200).map(m =>
|
|
1014
|
+
'<div class="related-item" data-jump-mem="' + escapeHtml(m.id) + '">' +
|
|
1015
|
+
'<span class="related-item-title">' + escapeHtml(m.title) + '</span>' +
|
|
1016
|
+
'<span class="badge">' + escapeHtml(m.category) + '</span>' +
|
|
1017
|
+
'</div>'
|
|
1018
|
+
).join('');
|
|
1019
|
+
bindJumpListeners();
|
|
1020
|
+
}
|
|
1021
|
+
moreBtn.remove();
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (node.type !== 'memory') {
|
|
1028
|
+
inspectorHeaderTitle.textContent = 'Categoría';
|
|
1029
|
+
inspectorActions.innerHTML = '';
|
|
1030
|
+
inspectorBody.innerHTML = '<div class="node-card-title">' + escapeHtml(node.label) + '</div>';
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
const mem = snapshot.memories.find(m => m.id === node.memoryId);
|
|
1035
|
+
if (!mem) return;
|
|
1036
|
+
|
|
1037
|
+
const related = snapshot.relatedByMemoryId[mem.id] || [];
|
|
1038
|
+
const searchScore = searchScoresById.get(mem.id);
|
|
1039
|
+
|
|
1040
|
+
inspectorHeaderTitle.textContent = 'Recuerdo · ' + mem.category;
|
|
1041
|
+
inspectorActions.innerHTML =
|
|
1042
|
+
'<button class="btn" id="editMemBtn" style="height:26px;padding:0 8px;font-size:11px;">Editar</button>' +
|
|
1043
|
+
'<button class="btn btn-danger" id="deleteMemBtn" style="height:26px;padding:0 8px;font-size:11px;">Olvidar</button>';
|
|
1044
|
+
|
|
1045
|
+
let scoreHtml = '';
|
|
1046
|
+
if (searchScore) {
|
|
1047
|
+
scoreHtml =
|
|
1048
|
+
'<div class="badge-row">' +
|
|
1049
|
+
'<span class="sim-pill">RRF: ' + searchScore.score.toFixed(3) + '</span>' +
|
|
1050
|
+
'<span class="badge">Vec: ' + Math.round(searchScore.vectorScore * 100) + '%</span>' +
|
|
1051
|
+
'<span class="badge">FTS5: ' + searchScore.ftsScore.toFixed(2) + '</span>' +
|
|
1052
|
+
'</div>';
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
inspectorBody.innerHTML =
|
|
1056
|
+
'<div class="node-card-title">' + escapeHtml(mem.title) + '</div>' +
|
|
1057
|
+
'<div class="badge-row">' +
|
|
1058
|
+
'<span class="badge" style="border-color:' + node.color + ';color:' + node.color + ';">' + escapeHtml(mem.category) + '</span>' +
|
|
1059
|
+
'<span class="badge">📦 ' + escapeHtml(mem.projectId) + '</span>' +
|
|
1060
|
+
(mem.sourceAgent ? '<span class="badge">🤖 ' + escapeHtml(mem.sourceAgent) + '</span>' : '') +
|
|
1061
|
+
'</div>' +
|
|
1062
|
+
scoreHtml +
|
|
1063
|
+
'<div class="meta-grid">' +
|
|
1064
|
+
'<div class="meta-stat"><div class="meta-stat-label">Importancia</div><div class="meta-stat-value">' + Math.round(mem.importance * 100) + '%</div></div>' +
|
|
1065
|
+
'<div class="meta-stat"><div class="meta-stat-label">Tokens</div><div class="meta-stat-value">' + mem.tokenCount + '</div></div>' +
|
|
1066
|
+
'<div class="meta-stat"><div class="meta-stat-label">Accesos</div><div class="meta-stat-value">' + mem.accessCount + '</div></div>' +
|
|
1067
|
+
'</div>' +
|
|
1068
|
+
'<div class="memory-content-box">' + escapeHtml(mem.content) + '</div>' +
|
|
1069
|
+
(mem.tags && mem.tags.length > 0
|
|
1070
|
+
? '<div class="tag-list">' + mem.tags.map(t => '<span class="tag-pill">#' + escapeHtml(t) + '</span>').join('') + '</div>'
|
|
1071
|
+
: '') +
|
|
1072
|
+
'<div style="font-size:12px;font-weight:600;color:var(--text-secondary);margin-top:4px;">Conexiones Semánticas (' + related.length + ')</div>' +
|
|
1073
|
+
'<div class="related-list">' +
|
|
1074
|
+
(related.length === 0
|
|
1075
|
+
? '<span style="font-size:12px;color:var(--text-muted);">Sin enlaces semánticos cercanos.</span>'
|
|
1076
|
+
: related.map(r =>
|
|
1077
|
+
'<div class="related-item" data-jump-mem="' + escapeHtml(r.memoryId) + '">' +
|
|
1078
|
+
'<span class="related-item-title">' + escapeHtml(r.title) + '</span>' +
|
|
1079
|
+
'<span class="sim-pill">' + Math.round(r.similarity * 100) + '%</span>' +
|
|
1080
|
+
'</div>'
|
|
1081
|
+
).join('')) +
|
|
1082
|
+
'</div>';
|
|
1083
|
+
|
|
1084
|
+
bindJumpListeners();
|
|
1085
|
+
|
|
1086
|
+
const editBtn = document.getElementById('editMemBtn');
|
|
1087
|
+
if (editBtn) {
|
|
1088
|
+
editBtn.addEventListener('click', () => openMemoryModal(mem));
|
|
1089
|
+
}
|
|
1090
|
+
const delBtn = document.getElementById('deleteMemBtn');
|
|
1091
|
+
if (delBtn) {
|
|
1092
|
+
delBtn.addEventListener('click', async () => {
|
|
1093
|
+
await fetch('/api/memories/' + encodeURIComponent(mem.id), { method: 'DELETE' });
|
|
1094
|
+
selectedNodeId = null;
|
|
1095
|
+
await loadGraph();
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function bindJumpListeners() {
|
|
1101
|
+
inspectorBody.querySelectorAll('[data-jump-mem]').forEach(el => {
|
|
1102
|
+
el.addEventListener('click', () => {
|
|
1103
|
+
const memId = el.getAttribute('data-jump-mem');
|
|
1104
|
+
const target = simNodes.find(n => n.memoryId === memId);
|
|
1105
|
+
if (target) {
|
|
1106
|
+
selectedNodeId = target.id;
|
|
1107
|
+
focusCameraOnNode(target);
|
|
1108
|
+
renderInspectorForNode(target);
|
|
1109
|
+
}
|
|
1110
|
+
});
|
|
1111
|
+
});
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
// P2P & ACL Renderer
|
|
1115
|
+
function renderP2pView(p2p) {
|
|
1116
|
+
if (!p2p || !p2pContent) return;
|
|
1117
|
+
const nc = p2p.nodeConfig;
|
|
1118
|
+
const peers = p2p.peers || [];
|
|
1119
|
+
const groups = p2p.groups || [];
|
|
1120
|
+
|
|
1121
|
+
let html =
|
|
1122
|
+
'<div class="p2p-card">' +
|
|
1123
|
+
'<div style="font-weight:700;font-size:14px;">🖥️ Nodo Local: ' + escapeHtml(nc.nodeName) + '</div>' +
|
|
1124
|
+
'<div class="badge-row">' +
|
|
1125
|
+
'<span class="badge">Rol: ' + escapeHtml(nc.role) + '</span>' +
|
|
1126
|
+
'<span class="badge">' + (nc.enabled ? '🟢 Activo' : '⚪ Standalone') + '</span>' +
|
|
1127
|
+
'</div>' +
|
|
1128
|
+
'<div style="font-size:12px;color:var(--text-secondary);">Puerto P2P: ' + nc.listenHost + ':' + nc.listenPort + ' · Política sin grupo: ' + escapeHtml(nc.unassignedGroupPolicy) + '</div>' +
|
|
1129
|
+
'</div>';
|
|
1130
|
+
|
|
1131
|
+
peers.forEach(peer => {
|
|
1132
|
+
html +=
|
|
1133
|
+
'<div class="p2p-card">' +
|
|
1134
|
+
'<div style="font-weight:700;font-size:14px;">🔗 Peer (' + escapeHtml(peer.role) + '): ' + escapeHtml(peer.name) + '</div>' +
|
|
1135
|
+
'<div style="font-size:12px;font-family:var(--font-mono);color:var(--accent-primary);">' + escapeHtml(peer.url) + '</div>' +
|
|
1136
|
+
'<div style="font-size:11.5px;color:var(--text-secondary);">Estado: ' + escapeHtml(peer.lastStatus || 'sin sincronizar') + '</div>' +
|
|
1137
|
+
'</div>';
|
|
1138
|
+
});
|
|
1139
|
+
|
|
1140
|
+
groups.forEach(g => {
|
|
1141
|
+
html +=
|
|
1142
|
+
'<div class="p2p-card">' +
|
|
1143
|
+
'<div style="font-weight:700;font-size:14px;">🛡️ Grupo ACL: ' + escapeHtml(g.name) + '</div>' +
|
|
1144
|
+
'<div class="badge-row">' +
|
|
1145
|
+
'<span class="badge">' + escapeHtml(g.permissions) + '</span>' +
|
|
1146
|
+
'<span class="badge">Miembros: ' + g.memberNodeIds.length + '</span>' +
|
|
1147
|
+
'</div>' +
|
|
1148
|
+
'<div style="font-size:12px;color:var(--text-secondary);">Proyectos: ' + escapeHtml(g.projects.join(', ')) + ' · Categorías: ' + escapeHtml(g.categories.join(', ')) + '</div>' +
|
|
1149
|
+
'</div>';
|
|
1150
|
+
});
|
|
1151
|
+
|
|
1152
|
+
p2pContent.innerHTML = html;
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// Filters & Search Events
|
|
1156
|
+
projectSelector.addEventListener('change', (e) => {
|
|
1157
|
+
currentProject = e.target.value;
|
|
1158
|
+
loadGraph();
|
|
1159
|
+
});
|
|
1160
|
+
|
|
1161
|
+
document.querySelectorAll('#categoryFilters .cat-chip').forEach(btn => {
|
|
1162
|
+
btn.addEventListener('click', () => {
|
|
1163
|
+
document.querySelectorAll('#categoryFilters .cat-chip').forEach(b => b.classList.remove('active'));
|
|
1164
|
+
btn.classList.add('active');
|
|
1165
|
+
currentCategory = btn.getAttribute('data-cat') || 'all';
|
|
1166
|
+
loadGraph();
|
|
1167
|
+
});
|
|
1168
|
+
});
|
|
1169
|
+
|
|
1170
|
+
let simTimer = null;
|
|
1171
|
+
simSlider.addEventListener('input', (e) => {
|
|
1172
|
+
minSimilarity = parseFloat(e.target.value);
|
|
1173
|
+
simValueLabel.textContent = Math.round(minSimilarity * 100) + '%';
|
|
1174
|
+
if (simTimer) clearTimeout(simTimer);
|
|
1175
|
+
simTimer = setTimeout(() => loadGraph(), 140);
|
|
1176
|
+
});
|
|
1177
|
+
|
|
1178
|
+
loadAllBtn.addEventListener('click', () => {
|
|
1179
|
+
showAllNodes = !showAllNodes;
|
|
1180
|
+
loadGraph();
|
|
1181
|
+
});
|
|
1182
|
+
|
|
1183
|
+
groupToggleBtn.addEventListener('click', () => {
|
|
1184
|
+
groupByCategory = !groupByCategory;
|
|
1185
|
+
groupToggleBtn.classList.toggle('active', groupByCategory);
|
|
1186
|
+
loadGraph();
|
|
1187
|
+
});
|
|
1188
|
+
|
|
1189
|
+
p2pToggleBtn.addEventListener('click', () => {
|
|
1190
|
+
const isOpen = p2pPanel.classList.toggle('open');
|
|
1191
|
+
p2pToggleBtn.classList.toggle('active', isOpen);
|
|
1192
|
+
});
|
|
1193
|
+
document.getElementById('closeP2pBtn').addEventListener('click', () => {
|
|
1194
|
+
p2pPanel.classList.remove('open');
|
|
1195
|
+
p2pToggleBtn.classList.remove('active');
|
|
1196
|
+
});
|
|
1197
|
+
|
|
1198
|
+
// Hybrid RRF Search
|
|
1199
|
+
let searchTimer = null;
|
|
1200
|
+
searchInput.addEventListener('input', () => {
|
|
1201
|
+
if (searchTimer) clearTimeout(searchTimer);
|
|
1202
|
+
searchTimer = setTimeout(async () => {
|
|
1203
|
+
const q = searchInput.value.trim();
|
|
1204
|
+
if (!q) {
|
|
1205
|
+
searchScoresById.clear();
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
const params = new URLSearchParams({
|
|
1209
|
+
q,
|
|
1210
|
+
project: currentProject,
|
|
1211
|
+
category: currentCategory,
|
|
1212
|
+
});
|
|
1213
|
+
const res = await fetch('/api/search?' + params.toString());
|
|
1214
|
+
if (!res.ok) return;
|
|
1215
|
+
const data = await res.json();
|
|
1216
|
+
searchScoresById.clear();
|
|
1217
|
+
(data.memories || []).forEach(m => {
|
|
1218
|
+
searchScoresById.set(m.id, m);
|
|
1219
|
+
});
|
|
1220
|
+
if (data.memories && data.memories.length > 0) {
|
|
1221
|
+
const topMem = data.memories[0];
|
|
1222
|
+
const topNode = simNodes.find(n => n.memoryId === topMem.id);
|
|
1223
|
+
if (topNode) {
|
|
1224
|
+
selectedNodeId = topNode.id;
|
|
1225
|
+
focusCameraOnNode(topNode);
|
|
1226
|
+
renderInspectorForNode(topNode);
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
}, 180);
|
|
1230
|
+
});
|
|
1231
|
+
|
|
1232
|
+
window.addEventListener('keydown', (e) => {
|
|
1233
|
+
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
|
|
1234
|
+
e.preventDefault();
|
|
1235
|
+
searchInput.focus();
|
|
1236
|
+
searchInput.select();
|
|
1237
|
+
}
|
|
1238
|
+
});
|
|
1239
|
+
|
|
1240
|
+
// Modals CRUD & Analyze
|
|
1241
|
+
const memoryModal = document.getElementById('memoryModal');
|
|
1242
|
+
const memoryForm = document.getElementById('memoryForm');
|
|
1243
|
+
function openMemoryModal(mem) {
|
|
1244
|
+
document.getElementById('modalTitle').textContent = mem ? 'Editar Recuerdo' : 'Nuevo Recuerdo en memoseb';
|
|
1245
|
+
document.getElementById('editMemoryId').value = mem ? mem.id : '';
|
|
1246
|
+
document.getElementById('memProjectInput').value = mem ? mem.projectId : (currentProject !== 'all' ? currentProject : 'memosebui');
|
|
1247
|
+
document.getElementById('memCategoryInput').value = mem ? mem.category : 'architecture';
|
|
1248
|
+
document.getElementById('memTitleInput').value = mem ? mem.title : '';
|
|
1249
|
+
document.getElementById('memContentInput').value = mem ? mem.content : '';
|
|
1250
|
+
document.getElementById('memTagsInput').value = mem && mem.tags ? mem.tags.join(', ') : '';
|
|
1251
|
+
document.getElementById('memImportanceInput').value = mem ? mem.importance : 0.8;
|
|
1252
|
+
memoryModal.classList.add('open');
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
document.getElementById('newMemoryBtn').addEventListener('click', () => openMemoryModal(null));
|
|
1256
|
+
document.getElementById('cancelMemoryModalBtn').addEventListener('click', () => memoryModal.classList.remove('open'));
|
|
1257
|
+
|
|
1258
|
+
memoryForm.addEventListener('submit', async (e) => {
|
|
1259
|
+
e.preventDefault();
|
|
1260
|
+
const editId = document.getElementById('editMemoryId').value;
|
|
1261
|
+
const payload = {
|
|
1262
|
+
projectId: document.getElementById('memProjectInput').value.trim(),
|
|
1263
|
+
category: document.getElementById('memCategoryInput').value,
|
|
1264
|
+
title: document.getElementById('memTitleInput').value.trim(),
|
|
1265
|
+
content: document.getElementById('memContentInput').value.trim(),
|
|
1266
|
+
tags: document.getElementById('memTagsInput').value.split(',').map(s => s.trim()).filter(Boolean),
|
|
1267
|
+
importance: parseFloat(document.getElementById('memImportanceInput').value) || 0.8,
|
|
1268
|
+
};
|
|
1269
|
+
const url = editId ? '/api/memories/' + encodeURIComponent(editId) : '/api/memories';
|
|
1270
|
+
const method = editId ? 'PUT' : 'POST';
|
|
1271
|
+
const res = await fetch(url, {
|
|
1272
|
+
method,
|
|
1273
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1274
|
+
body: JSON.stringify(payload),
|
|
1275
|
+
});
|
|
1276
|
+
memoryModal.classList.remove('open');
|
|
1277
|
+
if (res.ok) {
|
|
1278
|
+
const data = await res.json();
|
|
1279
|
+
await loadGraph(data.memory ? data.memory.id : undefined);
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1282
|
+
|
|
1283
|
+
const analyzeModal = document.getElementById('analyzeModal');
|
|
1284
|
+
document.getElementById('analyzeBtn').addEventListener('click', () => analyzeModal.classList.add('open'));
|
|
1285
|
+
document.getElementById('cancelAnalyzeModalBtn').addEventListener('click', () => analyzeModal.classList.remove('open'));
|
|
1286
|
+
document.getElementById('analyzeForm').addEventListener('submit', async (e) => {
|
|
1287
|
+
e.preventDefault();
|
|
1288
|
+
const targetPath = document.getElementById('analyzePathInput').value.trim();
|
|
1289
|
+
if (!targetPath) return;
|
|
1290
|
+
const res = await fetch('/api/analyze', {
|
|
1291
|
+
method: 'POST',
|
|
1292
|
+
headers: { 'Content-Type': 'application/json' },
|
|
1293
|
+
body: JSON.stringify({ path: targetPath }),
|
|
1294
|
+
});
|
|
1295
|
+
analyzeModal.classList.remove('open');
|
|
1296
|
+
if (res.ok) {
|
|
1297
|
+
const data = await res.json();
|
|
1298
|
+
currentProject = data.projectId || 'all';
|
|
1299
|
+
await loadGraph();
|
|
1300
|
+
}
|
|
1301
|
+
});
|
|
1302
|
+
|
|
1303
|
+
// Server-Sent Events (Live Updates)
|
|
1304
|
+
function connectSse() {
|
|
1305
|
+
const es = new EventSource('/api/events');
|
|
1306
|
+
es.onopen = () => {
|
|
1307
|
+
liveDot.classList.remove('disconnected');
|
|
1308
|
+
};
|
|
1309
|
+
es.onmessage = (ev) => {
|
|
1310
|
+
try {
|
|
1311
|
+
const data = JSON.parse(ev.data);
|
|
1312
|
+
if (data.type === 'vault:changed' || data.type === 'memory:created' || data.type === 'memory:updated' || data.type === 'memory:deleted') {
|
|
1313
|
+
loadGraph(data.memoryId);
|
|
1314
|
+
}
|
|
1315
|
+
} catch {}
|
|
1316
|
+
};
|
|
1317
|
+
es.onerror = () => {
|
|
1318
|
+
liveDot.classList.add('disconnected');
|
|
1319
|
+
liveText.textContent = 'Reconectando…';
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
initTheme();
|
|
1324
|
+
loadGraph();
|
|
1325
|
+
connectSse();
|
|
1326
|
+
})();
|
|
1327
|
+
</script>
|
|
1328
|
+
</body>
|
|
1329
|
+
</html>`;
|
|
1330
|
+
}
|
|
1331
|
+
async function readJsonBody(req) {
|
|
1332
|
+
return new Promise((resolve, reject) => {
|
|
1333
|
+
let raw = '';
|
|
1334
|
+
req.on('data', (chunk) => {
|
|
1335
|
+
raw += String(chunk);
|
|
1336
|
+
if (raw.length > 1_000_000) {
|
|
1337
|
+
reject(new Error('Payload too large'));
|
|
1338
|
+
}
|
|
1339
|
+
});
|
|
1340
|
+
req.on('end', () => {
|
|
1341
|
+
if (!raw.trim()) {
|
|
1342
|
+
resolve({});
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
try {
|
|
1346
|
+
resolve(JSON.parse(raw));
|
|
1347
|
+
}
|
|
1348
|
+
catch (err) {
|
|
1349
|
+
reject(err);
|
|
1350
|
+
}
|
|
1351
|
+
});
|
|
1352
|
+
req.on('error', reject);
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
function sendJson(res, statusCode, payload) {
|
|
1356
|
+
res.writeHead(statusCode, {
|
|
1357
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
1358
|
+
'Cache-Control': 'no-store',
|
|
1359
|
+
});
|
|
1360
|
+
res.end(JSON.stringify(payload));
|
|
1361
|
+
}
|
|
1362
|
+
export async function startUiServer(options) {
|
|
1363
|
+
const port = options?.port ?? 4322;
|
|
1364
|
+
const host = options?.host ?? '127.0.0.1';
|
|
1365
|
+
const bridge = new VaultBridge({ dbPath: options?.dbPath });
|
|
1366
|
+
const sseClients = new Set();
|
|
1367
|
+
const graphCache = new Map();
|
|
1368
|
+
let cacheEpoch = 0;
|
|
1369
|
+
function invalidateGraphCache() {
|
|
1370
|
+
cacheEpoch++;
|
|
1371
|
+
graphCache.clear();
|
|
1372
|
+
}
|
|
1373
|
+
function broadcastEvent(type, payload) {
|
|
1374
|
+
const msg = JSON.stringify({
|
|
1375
|
+
type,
|
|
1376
|
+
timestamp: new Date().toISOString(),
|
|
1377
|
+
...(payload ?? {}),
|
|
1378
|
+
});
|
|
1379
|
+
for (const client of sseClients) {
|
|
1380
|
+
try {
|
|
1381
|
+
client.write(`data: ${msg}\n\n`);
|
|
1382
|
+
}
|
|
1383
|
+
catch {
|
|
1384
|
+
sseClients.delete(client);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
let watcher = null;
|
|
1389
|
+
if (!options?.disableWatcher) {
|
|
1390
|
+
watcher = new VaultWatcher({
|
|
1391
|
+
bridge,
|
|
1392
|
+
onChange: (fingerprint) => {
|
|
1393
|
+
invalidateGraphCache();
|
|
1394
|
+
broadcastEvent('vault:changed', { fingerprint });
|
|
1395
|
+
},
|
|
1396
|
+
});
|
|
1397
|
+
watcher.start();
|
|
1398
|
+
}
|
|
1399
|
+
const cssPath = path.join(PACKAGE_ROOT, 'src', 'styles', 'mind.css');
|
|
1400
|
+
const server = http.createServer(async (req, res) => {
|
|
1401
|
+
try {
|
|
1402
|
+
const parsedUrl = new URL(req.url ?? '/', `http://${host}:${port}`);
|
|
1403
|
+
const pathname = parsedUrl.pathname;
|
|
1404
|
+
const method = req.method ?? 'GET';
|
|
1405
|
+
if (method === 'GET' && pathname === '/') {
|
|
1406
|
+
const html = generateMemosebUiHtml(options?.initialProject ?? 'all');
|
|
1407
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
1408
|
+
res.end(html);
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
if (method === 'GET' && pathname === '/styles/mind.css') {
|
|
1412
|
+
const css = existsSync(cssPath) ? readFileSync(cssPath, 'utf8') : '';
|
|
1413
|
+
res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8' });
|
|
1414
|
+
res.end(css);
|
|
1415
|
+
return;
|
|
1416
|
+
}
|
|
1417
|
+
if (method === 'GET' && pathname === '/api/events') {
|
|
1418
|
+
res.writeHead(200, {
|
|
1419
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
1420
|
+
'Cache-Control': 'no-cache, no-transform',
|
|
1421
|
+
Connection: 'keep-alive',
|
|
1422
|
+
});
|
|
1423
|
+
res.write(`data: ${JSON.stringify({
|
|
1424
|
+
type: 'init',
|
|
1425
|
+
stats: bridge.getStats(),
|
|
1426
|
+
})}\n\n`);
|
|
1427
|
+
sseClients.add(res);
|
|
1428
|
+
req.on('close', () => {
|
|
1429
|
+
sseClients.delete(res);
|
|
1430
|
+
});
|
|
1431
|
+
return;
|
|
1432
|
+
}
|
|
1433
|
+
if (method === 'GET' && pathname === '/api/health') {
|
|
1434
|
+
sendJson(res, 200, {
|
|
1435
|
+
status: 'ok',
|
|
1436
|
+
bundleId: BUNDLE_ID,
|
|
1437
|
+
version: VERSION,
|
|
1438
|
+
stats: bridge.getStats(),
|
|
1439
|
+
});
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1442
|
+
if (method === 'GET' && pathname === '/api/graph') {
|
|
1443
|
+
const projectParam = parsedUrl.searchParams.get('project') ?? undefined;
|
|
1444
|
+
const catParam = parsedUrl.searchParams.get('category') ?? undefined;
|
|
1445
|
+
const minSimParam = Number(parsedUrl.searchParams.get('minSimilarity') ?? '0.38');
|
|
1446
|
+
const groupParam = parsedUrl.searchParams.get('groupByCategory') === 'true';
|
|
1447
|
+
const limitRaw = parsedUrl.searchParams.get('limit');
|
|
1448
|
+
const limitParsed = limitRaw !== null ? Number(limitRaw) : undefined;
|
|
1449
|
+
const maxMemoryNodes = limitParsed !== undefined &&
|
|
1450
|
+
!Number.isNaN(limitParsed) &&
|
|
1451
|
+
limitParsed > 0
|
|
1452
|
+
? Math.floor(limitParsed)
|
|
1453
|
+
: undefined;
|
|
1454
|
+
const category = catParam && isMemoryCategory(catParam) ? catParam : undefined;
|
|
1455
|
+
const minSimilarity = Number.isNaN(minSimParam) ? 0.38 : minSimParam;
|
|
1456
|
+
const effectiveProject = projectParam && projectParam !== 'all' ? projectParam : undefined;
|
|
1457
|
+
const cacheKey = `${cacheEpoch}|${effectiveProject ?? 'all'}|${category ?? 'all'}|${minSimilarity.toFixed(2)}|${groupParam}|${maxMemoryNodes ?? 'all'}`;
|
|
1458
|
+
let snapshot = graphCache.get(cacheKey);
|
|
1459
|
+
if (!snapshot) {
|
|
1460
|
+
snapshot = buildMindGraph(bridge, {
|
|
1461
|
+
projectId: effectiveProject,
|
|
1462
|
+
category,
|
|
1463
|
+
minSimilarity,
|
|
1464
|
+
groupByCategory: groupParam,
|
|
1465
|
+
maxMemoryNodes,
|
|
1466
|
+
});
|
|
1467
|
+
if (graphCache.size >= 16) {
|
|
1468
|
+
const oldestKey = graphCache.keys().next().value;
|
|
1469
|
+
if (oldestKey !== undefined)
|
|
1470
|
+
graphCache.delete(oldestKey);
|
|
1471
|
+
}
|
|
1472
|
+
graphCache.set(cacheKey, snapshot);
|
|
1473
|
+
}
|
|
1474
|
+
sendJson(res, 200, snapshot);
|
|
1475
|
+
return;
|
|
1476
|
+
}
|
|
1477
|
+
if (method === 'GET' && pathname === '/api/search') {
|
|
1478
|
+
const q = parsedUrl.searchParams.get('q') ?? '';
|
|
1479
|
+
const projectParam = parsedUrl.searchParams.get('project') ?? undefined;
|
|
1480
|
+
const catParam = parsedUrl.searchParams.get('category') ?? undefined;
|
|
1481
|
+
const maxTokens = Number(parsedUrl.searchParams.get('maxTokens') ?? '4000');
|
|
1482
|
+
const category = catParam && isMemoryCategory(catParam) ? catParam : undefined;
|
|
1483
|
+
const result = bridge.searchMemories(q, {
|
|
1484
|
+
projectId: projectParam && projectParam !== 'all' ? projectParam : undefined,
|
|
1485
|
+
category,
|
|
1486
|
+
maxTokens: Number.isNaN(maxTokens) ? 4000 : maxTokens,
|
|
1487
|
+
});
|
|
1488
|
+
sendJson(res, 200, result);
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
if (method === 'POST' && pathname === '/api/memories') {
|
|
1492
|
+
const body = await readJsonBody(req);
|
|
1493
|
+
const content = typeof body.content === 'string' ? body.content : '';
|
|
1494
|
+
if (!content.trim()) {
|
|
1495
|
+
sendJson(res, 400, { error: 'Memory content is required.' });
|
|
1496
|
+
return;
|
|
1497
|
+
}
|
|
1498
|
+
const category = typeof body.category === 'string' && isMemoryCategory(body.category)
|
|
1499
|
+
? body.category
|
|
1500
|
+
: 'domain';
|
|
1501
|
+
const tags = Array.isArray(body.tags)
|
|
1502
|
+
? body.tags.filter((t) => typeof t === 'string')
|
|
1503
|
+
: [];
|
|
1504
|
+
const outcome = bridge.createMemory({
|
|
1505
|
+
projectId: typeof body.projectId === 'string' ? body.projectId : undefined,
|
|
1506
|
+
projectName: typeof body.projectName === 'string' ? body.projectName : undefined,
|
|
1507
|
+
rootPath: typeof body.rootPath === 'string' ? body.rootPath : undefined,
|
|
1508
|
+
category,
|
|
1509
|
+
title: typeof body.title === 'string' ? body.title : undefined,
|
|
1510
|
+
content,
|
|
1511
|
+
tags,
|
|
1512
|
+
importance: typeof body.importance === 'number' ? body.importance : undefined,
|
|
1513
|
+
});
|
|
1514
|
+
invalidateGraphCache();
|
|
1515
|
+
broadcastEvent('memory:created', { memoryId: outcome.memory.id });
|
|
1516
|
+
sendJson(res, 201, outcome);
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
if (method === 'GET' && pathname.startsWith('/api/memories/')) {
|
|
1520
|
+
const id = decodeURIComponent(pathname.slice('/api/memories/'.length));
|
|
1521
|
+
if (!id) {
|
|
1522
|
+
sendJson(res, 400, { error: 'Memory ID is required.' });
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
const memory = bridge.getMemoryById(id);
|
|
1526
|
+
if (!memory) {
|
|
1527
|
+
sendJson(res, 404, { error: 'Memory not found.' });
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
sendJson(res, 200, { memory });
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
if ((method === 'PUT' || method === 'DELETE') &&
|
|
1534
|
+
pathname.startsWith('/api/memories/')) {
|
|
1535
|
+
const id = decodeURIComponent(pathname.slice('/api/memories/'.length));
|
|
1536
|
+
if (!id) {
|
|
1537
|
+
sendJson(res, 400, { error: 'Memory ID is required.' });
|
|
1538
|
+
return;
|
|
1539
|
+
}
|
|
1540
|
+
if (method === 'DELETE') {
|
|
1541
|
+
const deleted = bridge.deleteMemory(id);
|
|
1542
|
+
if (!deleted) {
|
|
1543
|
+
sendJson(res, 404, { error: 'Memory not found.' });
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
invalidateGraphCache();
|
|
1547
|
+
broadcastEvent('memory:deleted', { memoryId: id });
|
|
1548
|
+
sendJson(res, 200, { deleted: true, id });
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
const body = await readJsonBody(req);
|
|
1552
|
+
const category = typeof body.category === 'string' && isMemoryCategory(body.category)
|
|
1553
|
+
? body.category
|
|
1554
|
+
: undefined;
|
|
1555
|
+
const tags = Array.isArray(body.tags)
|
|
1556
|
+
? body.tags.filter((t) => typeof t === 'string')
|
|
1557
|
+
: undefined;
|
|
1558
|
+
const updated = bridge.updateMemory(id, {
|
|
1559
|
+
title: typeof body.title === 'string' ? body.title : undefined,
|
|
1560
|
+
content: typeof body.content === 'string' ? body.content : undefined,
|
|
1561
|
+
category,
|
|
1562
|
+
tags,
|
|
1563
|
+
importance: typeof body.importance === 'number' ? body.importance : undefined,
|
|
1564
|
+
projectId: typeof body.projectId === 'string' ? body.projectId : undefined,
|
|
1565
|
+
});
|
|
1566
|
+
if (!updated) {
|
|
1567
|
+
sendJson(res, 404, { error: 'Memory not found.' });
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
invalidateGraphCache();
|
|
1571
|
+
broadcastEvent('memory:updated', { memoryId: updated.id });
|
|
1572
|
+
sendJson(res, 200, { memory: updated });
|
|
1573
|
+
return;
|
|
1574
|
+
}
|
|
1575
|
+
if (method === 'POST' && pathname === '/api/analyze') {
|
|
1576
|
+
const body = await readJsonBody(req);
|
|
1577
|
+
const targetPath = typeof body.path === 'string' ? body.path.trim() : '';
|
|
1578
|
+
if (!targetPath) {
|
|
1579
|
+
sendJson(res, 400, { error: 'Repository path is required.' });
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
const report = bridge.analyzeProjectDirectory(targetPath);
|
|
1583
|
+
invalidateGraphCache();
|
|
1584
|
+
broadcastEvent('vault:changed', { projectId: report.projectId });
|
|
1585
|
+
sendJson(res, 200, report);
|
|
1586
|
+
return;
|
|
1587
|
+
}
|
|
1588
|
+
if (method === 'GET' && pathname === '/api/p2p') {
|
|
1589
|
+
sendJson(res, 200, {
|
|
1590
|
+
nodeConfig: bridge.getNodeConfig(),
|
|
1591
|
+
peers: bridge.listPeers(),
|
|
1592
|
+
groups: bridge.listGroups(),
|
|
1593
|
+
});
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
sendJson(res, 404, { error: 'Not Found' });
|
|
1597
|
+
}
|
|
1598
|
+
catch (err) {
|
|
1599
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1600
|
+
sendJson(res, 500, { error: message });
|
|
1601
|
+
}
|
|
1602
|
+
});
|
|
1603
|
+
await new Promise((resolve, reject) => {
|
|
1604
|
+
server.once('error', reject);
|
|
1605
|
+
server.listen(port, host, () => resolve());
|
|
1606
|
+
});
|
|
1607
|
+
const addr = server.address();
|
|
1608
|
+
const actualPort = typeof addr === 'object' && addr ? addr.port : port;
|
|
1609
|
+
const url = `http://${host}:${actualPort}`;
|
|
1610
|
+
if (options?.openWindow) {
|
|
1611
|
+
launchStandaloneDesktopWindow(url, false);
|
|
1612
|
+
}
|
|
1613
|
+
else if (options?.openBrowser) {
|
|
1614
|
+
launchStandaloneDesktopWindow(url, true);
|
|
1615
|
+
}
|
|
1616
|
+
return {
|
|
1617
|
+
server,
|
|
1618
|
+
port: actualPort,
|
|
1619
|
+
url,
|
|
1620
|
+
bridge,
|
|
1621
|
+
broadcastEvent,
|
|
1622
|
+
getSnapshot: (projectId, category) => buildMindGraph(bridge, { projectId, category }),
|
|
1623
|
+
close: async () => {
|
|
1624
|
+
if (watcher)
|
|
1625
|
+
watcher.stop();
|
|
1626
|
+
for (const client of sseClients) {
|
|
1627
|
+
try {
|
|
1628
|
+
client.end();
|
|
1629
|
+
}
|
|
1630
|
+
catch { }
|
|
1631
|
+
}
|
|
1632
|
+
sseClients.clear();
|
|
1633
|
+
await new Promise((resolve) => {
|
|
1634
|
+
server.close(() => resolve());
|
|
1635
|
+
});
|
|
1636
|
+
bridge.close();
|
|
1637
|
+
},
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
//# sourceMappingURL=ui-server.js.map
|