@anmol-srv/sigil 0.17.0 → 0.18.1

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.
@@ -61,13 +61,14 @@ function renderKv(node, entries) {
61
61
  node.innerHTML = entries.map(([k, v]) => `<div class="row"><div class="k">${escape(k)}</div><div class="v">${escape(v)}</div></div>`).join('');
62
62
  }
63
63
 
64
- const validRoutes = ['health', 'kb', 'devices', 'activity', 'setup', 'settings', 'methods'];
64
+ const validRoutes = ['health', 'kb', 'graph', 'devices', 'activity', 'setup', 'settings', 'methods'];
65
65
  function setRoute(name) {
66
66
  $$('.view').forEach((v) => v.classList.toggle('active', v.id === `view-${name}`));
67
67
  $$('nav a').forEach((a) => a.classList.toggle('active', a.dataset.route === name));
68
68
  window.location.hash = name;
69
69
  if (name === 'health') refreshHealth();
70
70
  if (name === 'kb') refreshKb();
71
+ if (name === 'graph') initGraphView();
71
72
  if (name === 'methods') refreshMethods();
72
73
  if (name === 'settings') { refreshEnv(); refreshSettingsClients(); }
73
74
  if (name === 'devices') refreshDevices();
@@ -123,26 +124,918 @@ async function refreshHealth() {
123
124
  } catch (err) { setConn('err', err.message); }
124
125
  }
125
126
 
127
+ // ════════════════════════════════════════════════════════════════════
128
+ // KNOWLEDGE BASE — master-detail browser (facts · entities · pods + graph)
129
+ // ════════════════════════════════════════════════════════════════════
130
+ const kb = {
131
+ tab: 'facts',
132
+ loaded: false,
133
+ facts: [], // full fetched set (cross-namespace)
134
+ factNs: null, // active namespace filter (null = all)
135
+ factCat: null, // active category filter (null = all)
136
+ factSearch: '',
137
+ selectedFactUid: null,
138
+ entityType: null, // active entity-type filter
139
+ entitySearch: '',
140
+ entities: [],
141
+ selectedEntityId: null,
142
+ pods: null,
143
+ };
144
+
145
+ const ENTITY_TYPES = ['person', 'topic', 'document'];
146
+
147
+ // Confidence carries the only semantic color; importance/category stay neutral
148
+ // to keep the surface restrained (brand rule: accent for state, not decoration).
149
+ function confidenceClass(c) {
150
+ if (c === 'high') return 'ok';
151
+ if (c === 'low') return 'warn';
152
+ return 'info'; // medium / unknown
153
+ }
154
+ function titleCase(s) {
155
+ return String(s || '').replace(/_/g, ' ');
156
+ }
157
+
126
158
  async function refreshKb() {
159
+ kbLoadStats();
160
+ if (!kb.loaded || kb.tab === 'facts') await kbLoadFacts();
161
+ kb.loaded = true;
162
+ kbSetTab(kb.tab, { force: true });
163
+ }
164
+
165
+ async function kbLoadStats() {
166
+ const strip = $('#kb-stats');
127
167
  try {
128
- const data = await rpc('status', {});
129
- renderKv($('#kb-pane'), [
130
- ['documents', data.documents], ['chunks', data.chunks], ['facts', data.facts],
131
- ['entities (docs)', data.entities.documents],
132
- ['entities (people)', data.entities.people],
133
- ['entities (topics)', data.entities.topics],
134
- ['relations', data.relations],
135
- ['hebbian edges', data.hebbian?.edgeCount ?? '—'],
136
- ]);
137
- const hot = data.hotFacts || [];
138
- $('#hot-facts').innerHTML = hot.length
139
- ? hot.map((f) => `<li>${escape(f.content.slice(0, 140))}<span class="muted" style="margin-left:var(--s-2);">${f.accessCount}×</span></li>`).join('')
140
- : '<li class="muted">no hot facts yet</li>';
168
+ const d = await rpc('status', {});
169
+ const ents = (d.entities?.documents || 0) + (d.entities?.people || 0) + (d.entities?.topics || 0);
170
+ const stats = [
171
+ ['Facts', d.facts], ['Entities', ents], ['Relations', d.relations],
172
+ ['Documents', d.documents], ['Chunks', d.chunks],
173
+ ['Hebbian edges', d.hebbian?.edgeCount ?? 0],
174
+ ];
175
+ strip.innerHTML = stats.map(([k, v]) =>
176
+ `<div class="kb-stat"><span class="kb-stat-v">${escape(v)}</span><span class="kb-stat-k">${escape(k)}</span></div>`).join('');
177
+ } catch (err) {
178
+ strip.innerHTML = `<div class="kb-stat-err">Couldn’t load totals: ${escape(err.message)}</div>`;
179
+ }
180
+ }
181
+
182
+ function kbSetTab(name, { force = false } = {}) {
183
+ if (!force && kb.tab === name) return;
184
+ kb.tab = name;
185
+ $$('.kb-tab').forEach((t) => {
186
+ const on = t.dataset.kbtab === name;
187
+ t.classList.toggle('active', on);
188
+ t.setAttribute('aria-selected', on ? 'true' : 'false');
189
+ });
190
+ $('#kb-tab-facts').hidden = name !== 'facts';
191
+ $('#kb-tab-entities').hidden = name !== 'entities';
192
+ $('#kb-tab-pods').hidden = name !== 'pods';
193
+ if (name === 'facts') kbRenderFacts();
194
+ if (name === 'entities' && !kb.entities.length && !kb.entitySearch) kbSearchEntities();
195
+ if (name === 'pods' && !kb.pods) kbLoadPods();
196
+ }
197
+
198
+ // ── Facts ────────────────────────────────────────────────────────────
199
+ async function kbLoadFacts() {
200
+ const list = $('#kb-fact-list');
201
+ list.innerHTML = kbSkeleton(7);
202
+ try {
203
+ const { facts } = await rpc('listFacts', { limit: 200 });
204
+ kb.facts = facts || [];
205
+ kbRenderFactFilters();
206
+ kbRenderFacts();
207
+ } catch (err) {
208
+ list.innerHTML = `<div class="empty">Couldn’t load facts: ${escape(err.message)}</div>`;
209
+ }
210
+ }
211
+
212
+ function kbRenderFactFilters() {
213
+ const namespaces = [...new Set(kb.facts.map((f) => f.namespace).filter(Boolean))].sort();
214
+ const categories = [...new Set(kb.facts.map((f) => f.category).filter(Boolean))].sort();
215
+ const chip = (label, active, val, group) =>
216
+ `<button class="chip${active ? ' active' : ''}" data-kbfilter="${group}" data-val="${val === null ? '' : escape(val)}" type="button">${escape(label)}</button>`;
217
+ $('#kb-fact-ns').innerHTML = namespaces.length > 1
218
+ ? [chip('All namespaces', kb.factNs === null, null, 'ns'),
219
+ ...namespaces.map((n) => chip(n, kb.factNs === n, n, 'ns'))].join('')
220
+ : '';
221
+ $('#kb-fact-cat').innerHTML = categories.length
222
+ ? [chip('All categories', kb.factCat === null, null, 'cat'),
223
+ ...categories.map((c) => chip(titleCase(c), kb.factCat === c, c, 'cat'))].join('')
224
+ : '';
225
+ }
226
+
227
+ function kbFilteredFacts() {
228
+ const q = kb.factSearch.trim().toLowerCase();
229
+ return kb.facts.filter((f) => {
230
+ if (kb.factNs && f.namespace !== kb.factNs) return false;
231
+ if (kb.factCat && f.category !== kb.factCat) return false;
232
+ if (q && !(f.content || '').toLowerCase().includes(q)) return false;
233
+ return true;
234
+ });
235
+ }
236
+
237
+ function kbRenderFacts() {
238
+ const list = $('#kb-fact-list');
239
+ const facts = kbFilteredFacts();
240
+ $('#kb-fact-count').textContent = `${facts.length} fact${facts.length === 1 ? '' : 's'}`;
241
+ if (!facts.length) {
242
+ list.innerHTML = kb.facts.length
243
+ ? `<div class="empty">No facts match this filter. Clear the search or pick a different category.</div>`
244
+ : `<div class="empty">No facts stored yet. Sigil fills this as your agents work — or run <code>sigil remember "…"</code>.</div>`;
245
+ return;
246
+ }
247
+ list.innerHTML = facts.map((f) => {
248
+ const sel = f.uid === kb.selectedFactUid ? ' selected' : '';
249
+ const cat = f.category ? `<span class="kb-tag">${escape(titleCase(f.category))}</span>` : '';
250
+ const conf = f.confidence ? `<span class="kb-dot ${confidenceClass(f.confidence)}" title="confidence: ${escape(f.confidence)}"></span>` : '';
251
+ return `<button class="kb-row${sel}" role="option" aria-selected="${sel ? 'true' : 'false'}" data-uid="${escape(f.uid)}" type="button">
252
+ <span class="kb-row-main">${conf}<span class="kb-row-text">${escape(f.content)}</span></span>
253
+ <span class="kb-row-meta">${cat}</span>
254
+ </button>`;
255
+ }).join('');
256
+ }
257
+
258
+ async function kbSelectFact(uid) {
259
+ kb.selectedFactUid = uid;
260
+ $$('#kb-fact-list .kb-row').forEach((r) => {
261
+ const on = r.dataset.uid === uid;
262
+ r.classList.toggle('selected', on);
263
+ r.setAttribute('aria-selected', on ? 'true' : 'false');
264
+ });
265
+ const pane = $('#kb-fact-detail');
266
+ pane.classList.add('open');
267
+ pane.innerHTML = `<div class="kb-detail-pad">${kbSkeleton(4)}</div>`;
268
+ try {
269
+ const ctx = await rpc('getFactContext', { uid });
270
+ if (ctx.notFound) { pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Fact not found.</div></div>`; return; }
271
+ pane.innerHTML = kbRenderFactDetail(ctx);
141
272
  } catch (err) {
142
- $('#kb-pane').innerHTML = `<div class="row"><div class="k">error</div><div class="v">${escape(err.message)}</div></div>`;
273
+ pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Couldn’t load detail: ${escape(err.message)}</div></div>`;
143
274
  }
144
275
  }
276
+
277
+ function kbRenderFactDetail(ctx) {
278
+ const f = ctx.fact;
279
+ const badges = [];
280
+ if (f.confidence) badges.push(`<span class="badge ${confidenceClass(f.confidence)}">${escape(f.confidence)} confidence</span>`);
281
+ if (f.category) badges.push(`<span class="badge">${escape(titleCase(f.category))}</span>`);
282
+ if (f.status) badges.push(`<span class="badge ${f.status === 'active' ? 'ok' : 'warn'}">${escape(f.status)}</span>`);
283
+
284
+ const meta = [];
285
+ if (f.sourceSection) meta.push(['source section', f.sourceSection]);
286
+ if (f.uid) meta.push(['uid', f.uid]);
287
+ const metaBlock = meta.length
288
+ ? `<div class="kb-block"><div class="trace-block-h">Provenance</div><div class="kv kb-kv">${meta.map(([k, v]) =>
289
+ `<div class="row"><div class="k">${escape(k)}</div><div class="v">${escape(v)}</div></div>`).join('')}</div></div>`
290
+ : '';
291
+
292
+ const docs = (ctx.documents || []).length
293
+ ? `<div class="kb-block"><div class="trace-block-h">Source documents</div>${ctx.documents.map((d) =>
294
+ `<div class="kb-link-row"><span class="kb-link-name">${escape(d.title || `document #${d.id}`)}</span><span class="kb-tag">${escape(d.sourceType || 'doc')}</span></div>`).join('')}</div>`
295
+ : '';
296
+
297
+ const ents = (ctx.entities || []).length
298
+ ? `<div class="kb-block"><div class="trace-block-h">Linked entities</div><div class="kb-chip-wrap">${ctx.entities.map((e) =>
299
+ `<button class="kb-entity-chip" data-entity-id="${e.id}" type="button"><span class="kb-etype ${escape(e.entityType)}"></span>${escape(e.name)}</button>`).join('')}</div></div>`
300
+ : '';
301
+
302
+ const rels = (ctx.relations || []).length
303
+ ? `<div class="kb-block"><div class="trace-block-h">Relations</div>${ctx.relations.map((r) =>
304
+ `<div class="kb-rel"><span class="kb-rel-node">${escape(r.sourceName)}</span><span class="kb-rel-type">${escape(titleCase(r.relationType))}</span><span class="kb-rel-node">${escape(r.targetName)}</span></div>`).join('')}</div>`
305
+ : '';
306
+
307
+ return `<div class="kb-detail-pad">
308
+ <div class="kb-detail-head">
309
+ <div class="kb-badges">${badges.join('')}</div>
310
+ <button class="btn ghost small kb-forget" data-uid="${escape(f.uid)}" type="button" title="Forget this fact">Forget</button>
311
+ </div>
312
+ <p class="kb-fact-body">${escape(f.content)}</p>
313
+ ${metaBlock}${docs}${ents}${rels}
314
+ </div>`;
315
+ }
316
+
317
+ async function kbForgetFact(uid) {
318
+ if (!window.confirm('Forget this fact? It will be removed from memory and stop being recalled.')) return;
319
+ try {
320
+ await rpc('forgetFact', { uid });
321
+ toast({ variant: 'success', message: 'Fact forgotten.' });
322
+ kb.facts = kb.facts.filter((f) => f.uid !== uid);
323
+ kb.selectedFactUid = null;
324
+ $('#kb-fact-detail').classList.remove('open');
325
+ $('#kb-fact-detail').innerHTML = '';
326
+ kbRenderFactFilters();
327
+ kbRenderFacts();
328
+ kbLoadStats();
329
+ } catch (err) {
330
+ toast({ variant: 'error', message: `Couldn’t forget fact: ${err.message}` });
331
+ }
332
+ }
333
+
334
+ // ── Entities ─────────────────────────────────────────────────────────
335
+ function kbRenderEntityTypeChips() {
336
+ const chip = (label, active, val) =>
337
+ `<button class="chip${active ? ' active' : ''}" data-kbetype="${val === null ? '' : val}" type="button">${escape(label)}</button>`;
338
+ $('#kb-entity-type').innerHTML = [
339
+ chip('All', kb.entityType === null, null),
340
+ ...ENTITY_TYPES.map((t) => chip(titleCase(t), kb.entityType === t, t)),
341
+ ].join('');
342
+ }
343
+
344
+ async function kbSearchEntities() {
345
+ kbRenderEntityTypeChips();
346
+ const list = $('#kb-entity-list');
347
+ list.innerHTML = kbSkeleton(6);
348
+ const params = {};
349
+ if (kb.entitySearch.trim()) params.query = kb.entitySearch.trim();
350
+ if (kb.entityType) params.entityType = kb.entityType;
351
+ if (!params.query && !params.entityType) params.entityType = 'topic'; // a sensible default browse
352
+ try {
353
+ const { entities } = await rpc('searchEntity', { ...params, limit: 50 });
354
+ kb.entities = entities || [];
355
+ kbRenderEntityList();
356
+ } catch (err) {
357
+ list.innerHTML = `<div class="empty">Couldn’t load entities: ${escape(err.message)}</div>`;
358
+ }
359
+ }
360
+
361
+ function kbRenderEntityList() {
362
+ const list = $('#kb-entity-list');
363
+ if (!kb.entities.length) {
364
+ list.innerHTML = `<div class="empty">No entities found${kb.entitySearch ? ` for “${escape(kb.entitySearch)}”` : ''}. Try another name or type.</div>`;
365
+ return;
366
+ }
367
+ list.innerHTML = kb.entities.map((e) => {
368
+ const sel = e.id === kb.selectedEntityId ? ' selected' : '';
369
+ return `<button class="kb-row${sel}" role="option" aria-selected="${sel ? 'true' : 'false'}" data-entity-id="${e.id}" type="button">
370
+ <span class="kb-row-main"><span class="kb-etype ${escape(e.entityType)}"></span><span class="kb-row-text">${escape(e.name)}</span></span>
371
+ <span class="kb-row-meta"><span class="kb-mentions">${escape(e.mentionCount || 0)}×</span></span>
372
+ </button>`;
373
+ }).join('');
374
+ }
375
+
376
+ async function kbSelectEntity(id) {
377
+ kb.selectedEntityId = Number(id);
378
+ // If entity isn't on the entities tab list, still highlight when present.
379
+ $$('#kb-entity-list .kb-row').forEach((r) => r.classList.toggle('selected', Number(r.dataset.entityId) === kb.selectedEntityId));
380
+ const pane = $('#kb-entity-detail');
381
+ pane.classList.add('open');
382
+ pane.innerHTML = `<div class="kb-detail-pad">${kbSkeleton(4)}</div>`;
383
+ try {
384
+ const ctx = await rpc('getEntityContext', { entityId: Number(id) });
385
+ if (ctx.notFound) { pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Entity not found.</div></div>`; return; }
386
+ pane.innerHTML = kbRenderEntityDetail(ctx);
387
+ } catch (err) {
388
+ pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Couldn’t load detail: ${escape(err.message)}</div></div>`;
389
+ }
390
+ }
391
+
392
+ function kbRenderEntityDetail(ctx) {
393
+ const e = ctx.entity;
394
+ const facts = (ctx.facts || []).length
395
+ ? `<div class="kb-block"><div class="trace-block-h">Facts (${ctx.facts.length})</div>${ctx.facts.map((f) =>
396
+ `<div class="kb-mini-fact">${escape(f.content)}</div>`).join('')}</div>`
397
+ : '';
398
+ const rels = (ctx.relations || []).length
399
+ ? `<div class="kb-block"><div class="trace-block-h">Relations (${ctx.relations.length})</div>${ctx.relations.map((r) =>
400
+ `<button class="kb-rel kb-rel-btn" data-entity-id="${r.entityId}" type="button"><span class="kb-rel-type">${escape(titleCase(r.relationType))}</span><span class="kb-rel-node"><span class="kb-etype ${escape(r.entityType)}"></span>${escape(r.name)}</span></button>`).join('')}</div>`
401
+ : '';
402
+ return `<div class="kb-detail-pad">
403
+ <div class="kb-detail-head">
404
+ <div>
405
+ <div class="kb-entity-title"><span class="kb-etype ${escape(e.entityType)}"></span>${escape(e.name)}</div>
406
+ <div class="kb-entity-sub">${escape(titleCase(e.entityType))} · ${escape(e.mentionCount || 0)} mention${e.mentionCount === 1 ? '' : 's'}</div>
407
+ </div>
408
+ <button class="btn small kb-graph-open" data-entity-id="${e.id}" data-name="${escape(e.name)}" type="button">View graph</button>
409
+ </div>
410
+ ${e.description ? `<p class="kb-fact-body">${escape(e.description)}</p>` : ''}
411
+ <div class="kb-graph-mount" id="kb-graph-mount" hidden></div>
412
+ ${rels}${facts}
413
+ </div>`;
414
+ }
415
+
416
+ // ── Pods ─────────────────────────────────────────────────────────────
417
+ async function kbLoadPods() {
418
+ const list = $('#kb-pod-list');
419
+ list.innerHTML = kbSkeleton(5);
420
+ try {
421
+ const { pods } = await rpc('listPods', { limit: 50 });
422
+ kb.pods = pods || [];
423
+ if (!kb.pods.length) {
424
+ list.innerHTML = `<div class="empty">No pods yet. Pods group facts by session and project as your agents work.</div>`;
425
+ return;
426
+ }
427
+ list.innerHTML = `<div class="kb-pod-head"><span>Pod</span><span>Type</span><span>Facts</span><span>Docs</span><span>Updated</span></div>` +
428
+ kb.pods.map((p) =>
429
+ `<div class="kb-pod-row">
430
+ <span class="kb-pod-name">${escape(p.name || p.uid)}</span>
431
+ <span class="kb-tag">${escape(p.podType || '—')}</span>
432
+ <span class="kb-pod-num">${escape(p.memberFactCount)}</span>
433
+ <span class="kb-pod-num">${escape(p.memberDocCount)}</span>
434
+ <span class="kb-pod-when">${escape(p.updatedAt ? formatTime(p.updatedAt) : '—')}</span>
435
+ </div>`).join('');
436
+ } catch (err) {
437
+ list.innerHTML = `<div class="empty">Couldn’t load pods: ${escape(err.message)}</div>`;
438
+ }
439
+ }
440
+
441
+ // ── Interactive relationship graph (hand-rolled SVG) ─────────────────
442
+ async function kbOpenGraph(entityId, name) {
443
+ const mount = $('#kb-graph-mount');
444
+ if (!mount) return;
445
+ mount.hidden = false;
446
+ mount.innerHTML = `<div class="kb-graph-loading">${kbSkeleton(2)}</div>`;
447
+ try {
448
+ const res = await rpc('traverseGraph', { startEntityId: Number(entityId), action: 'neighbors', maxDepth: 1, limit: 14 });
449
+ if (res.notFound) { mount.innerHTML = `<div class="empty">No graph for this entity.</div>`; return; }
450
+ kbRenderGraph(mount, res.start || { id: Number(entityId), name }, res.relations || []);
451
+ } catch (err) {
452
+ mount.innerHTML = `<div class="empty">Couldn’t build graph: ${escape(err.message)}</div>`;
453
+ }
454
+ }
455
+
456
+ function kbRenderGraph(mount, center, relations) {
457
+ const W = mount.clientWidth || 520;
458
+ const H = 320;
459
+ const cx = W / 2, cy = H / 2;
460
+ const R = Math.min(W, H) / 2 - 56;
461
+ const neighbors = relations.slice(0, 12);
462
+
463
+ if (!neighbors.length) {
464
+ mount.innerHTML = `<div class="kb-graph-empty"><div class="kb-node focal"><span>${escape(center.name)}</span></div><p class="muted">No relations recorded for this entity yet.</p></div>`;
465
+ return;
466
+ }
467
+
468
+ const nodes = [{ id: center.id, name: center.name, type: center.entityType, x: cx, y: cy, focal: true }];
469
+ const edges = [];
470
+ neighbors.forEach((r, i) => {
471
+ const ang = (i / neighbors.length) * Math.PI * 2 - Math.PI / 2;
472
+ const x = cx + Math.cos(ang) * R;
473
+ const y = cy + Math.sin(ang) * R;
474
+ nodes.push({ id: r.entityId, name: r.name, type: r.entityType, x, y, focal: false });
475
+ edges.push({ from: 0, to: nodes.length - 1, label: titleCase(r.relationType) });
476
+ });
477
+
478
+ const ns = 'http://www.w3.org/2000/svg';
479
+ const svg = document.createElementNS(ns, 'svg');
480
+ svg.setAttribute('class', 'kb-graph-svg');
481
+ svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
482
+ svg.setAttribute('width', '100%');
483
+ svg.setAttribute('height', String(H));
484
+ svg.setAttribute('role', 'img');
485
+ svg.setAttribute('aria-label', `Relationship graph for ${center.name}`);
486
+
487
+ const edgeLayer = document.createElementNS(ns, 'g');
488
+ const labelLayer = document.createElementNS(ns, 'g');
489
+ const nodeLayer = document.createElementNS(ns, 'g');
490
+ svg.append(edgeLayer, labelLayer, nodeLayer);
491
+
492
+ function draw() {
493
+ edgeLayer.replaceChildren();
494
+ labelLayer.replaceChildren();
495
+ for (const e of edges) {
496
+ const a = nodes[e.from], b = nodes[e.to];
497
+ const line = document.createElementNS(ns, 'line');
498
+ line.setAttribute('x1', a.x); line.setAttribute('y1', a.y);
499
+ line.setAttribute('x2', b.x); line.setAttribute('y2', b.y);
500
+ line.setAttribute('class', 'kb-edge');
501
+ edgeLayer.appendChild(line);
502
+ const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
503
+ const t = document.createElementNS(ns, 'text');
504
+ t.setAttribute('x', mx); t.setAttribute('y', my - 3);
505
+ t.setAttribute('class', 'kb-edge-label');
506
+ t.setAttribute('text-anchor', 'middle');
507
+ t.textContent = e.label;
508
+ labelLayer.appendChild(t);
509
+ }
510
+ }
511
+
512
+ function nodeEl(n, idx) {
513
+ const g = document.createElementNS(ns, 'g');
514
+ g.setAttribute('class', `kb-node-g${n.focal ? ' focal' : ''}`);
515
+ g.setAttribute('tabindex', '0');
516
+ g.setAttribute('role', 'button');
517
+ g.setAttribute('aria-label', n.focal ? `${n.name} (focus)` : `${n.name}, expand`);
518
+ const label = (n.name || '').length > 16 ? n.name.slice(0, 15) + '…' : n.name;
519
+ const w = Math.max(54, label.length * 7.4 + 20);
520
+ const rect = document.createElementNS(ns, 'rect');
521
+ rect.setAttribute('x', -w / 2); rect.setAttribute('y', -13);
522
+ rect.setAttribute('width', w); rect.setAttribute('height', 26);
523
+ rect.setAttribute('rx', '2');
524
+ rect.setAttribute('class', `kb-node-box type-${n.type || 'topic'}`);
525
+ const text = document.createElementNS(ns, 'text');
526
+ text.setAttribute('class', 'kb-node-label');
527
+ text.setAttribute('text-anchor', 'middle');
528
+ text.setAttribute('dy', '4');
529
+ text.textContent = label;
530
+ g.append(rect, text);
531
+ positionNode(g, n);
532
+
533
+ // drag
534
+ let dragging = false, moved = false, ox = 0, oy = 0;
535
+ g.addEventListener('pointerdown', (ev) => {
536
+ dragging = true; moved = false;
537
+ ox = ev.clientX; oy = ev.clientY;
538
+ g.setPointerCapture(ev.pointerId);
539
+ g.classList.add('dragging');
540
+ });
541
+ g.addEventListener('pointermove', (ev) => {
542
+ if (!dragging) return;
543
+ const scale = W / svg.getBoundingClientRect().width;
544
+ const dx = (ev.clientX - ox) * scale, dy = (ev.clientY - oy) * scale;
545
+ if (Math.abs(dx) > 2 || Math.abs(dy) > 2) moved = true;
546
+ n.x += dx; n.y += dy; ox = ev.clientX; oy = ev.clientY;
547
+ positionNode(g, n); draw();
548
+ });
549
+ g.addEventListener('pointerup', (ev) => {
550
+ dragging = false; g.classList.remove('dragging');
551
+ g.releasePointerCapture(ev.pointerId);
552
+ if (!moved && !n.focal) kbOpenGraph(n.id, n.name); // click neighbor → re-center
553
+ });
554
+ g.addEventListener('keydown', (ev) => {
555
+ if ((ev.key === 'Enter' || ev.key === ' ') && !n.focal) { ev.preventDefault(); kbOpenGraph(n.id, n.name); }
556
+ });
557
+ return g;
558
+ }
559
+ function positionNode(g, n) { g.setAttribute('transform', `translate(${n.x},${n.y})`); }
560
+
561
+ draw();
562
+ nodes.forEach((n, i) => nodeLayer.appendChild(nodeEl(n, i)));
563
+ mount.replaceChildren(svg);
564
+ const hint = document.createElement('p');
565
+ hint.className = 'kb-graph-hint muted';
566
+ hint.textContent = 'Drag to rearrange · click a neighbor to expand it';
567
+ mount.appendChild(hint);
568
+ }
569
+
570
+ // ── KB event wiring (delegated) ──────────────────────────────────────
571
+ function kbSkeleton(n) {
572
+ return `<div class="kb-skel-wrap">${Array.from({ length: n }, () => '<div class="kb-skel"></div>').join('')}</div>`;
573
+ }
574
+
145
575
  $('#kb-refresh')?.addEventListener('click', refreshKb);
576
+ $$('.kb-tab').forEach((t) => t.addEventListener('click', () => kbSetTab(t.dataset.kbtab)));
577
+
578
+ $('#kb-fact-search')?.addEventListener('input', (e) => { kb.factSearch = e.target.value; kbRenderFacts(); });
579
+ $('#kb-fact-ns')?.addEventListener('click', (e) => {
580
+ const b = e.target.closest('[data-kbfilter="ns"]'); if (!b) return;
581
+ kb.factNs = b.dataset.val || null; kbRenderFactFilters(); kbRenderFacts();
582
+ });
583
+ $('#kb-fact-cat')?.addEventListener('click', (e) => {
584
+ const b = e.target.closest('[data-kbfilter="cat"]'); if (!b) return;
585
+ kb.factCat = b.dataset.val || null; kbRenderFactFilters(); kbRenderFacts();
586
+ });
587
+ $('#kb-fact-list')?.addEventListener('click', (e) => {
588
+ const row = e.target.closest('.kb-row'); if (row) kbSelectFact(row.dataset.uid);
589
+ });
590
+ $('#kb-fact-detail')?.addEventListener('click', (e) => {
591
+ const forget = e.target.closest('.kb-forget'); if (forget) { kbForgetFact(forget.dataset.uid); return; }
592
+ const ent = e.target.closest('[data-entity-id]');
593
+ if (ent) { kbSetTab('entities'); kbSelectEntity(ent.dataset.entityId); }
594
+ });
595
+
596
+ let entitySearchTimer = null;
597
+ $('#kb-entity-search')?.addEventListener('input', (e) => {
598
+ kb.entitySearch = e.target.value;
599
+ clearTimeout(entitySearchTimer);
600
+ entitySearchTimer = setTimeout(kbSearchEntities, 220);
601
+ });
602
+ $('#kb-entity-type')?.addEventListener('click', (e) => {
603
+ const b = e.target.closest('[data-kbetype]'); if (!b) return;
604
+ kb.entityType = b.dataset.kbetype || null; kbSearchEntities();
605
+ });
606
+ $('#kb-entity-list')?.addEventListener('click', (e) => {
607
+ const row = e.target.closest('.kb-row'); if (row) kbSelectEntity(row.dataset.entityId);
608
+ });
609
+ $('#kb-entity-detail')?.addEventListener('click', (e) => {
610
+ const g = e.target.closest('.kb-graph-open');
611
+ if (g) { kbOpenGraph(g.dataset.entityId, g.dataset.name); return; }
612
+ const rel = e.target.closest('.kb-rel-btn');
613
+ if (rel) kbSelectEntity(rel.dataset.entityId);
614
+ });
615
+
616
+ // ════════════════════════════════════════════════════════════════════
617
+ // GRAPH VIEW — whole-KB force-directed graph on canvas (Obsidian-style)
618
+ // Hand-rolled spring-electrical simulation (velocity Verlet + cooling),
619
+ // no dependencies. Facts + entities as nodes; fact→entity mentions and
620
+ // entity→entity relations as edges.
621
+ // ════════════════════════════════════════════════════════════════════
622
+ const graph = {
623
+ loaded: false,
624
+ raw: null, // { nodes, edges, counts, truncated }
625
+ sim: null, // running simulation handle
626
+ view: { x: 0, y: 0, k: 1 }, // pan (x,y) + zoom (k)
627
+ hover: null,
628
+ dragNode: null,
629
+ panning: false,
630
+ };
631
+
632
+ // Entity-type palette — a cohesive cool triad, distinct on the near-black
633
+ // canvas. Used by both the graph nodes and the KB browser's type dots/legend.
634
+ const ENTITY_COLORS = { person: '#4ea1ff', topic: '#9a86ff', document: '#43c9b0' };
635
+ const reducedMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
636
+
637
+ async function initGraphView() {
638
+ if (graph.loaded) { graph.hover = null; hideTooltip(); graphFit(); return; }
639
+ await loadGraph();
640
+ }
641
+
642
+ async function loadGraph() {
643
+ const overlay = $('#graph-overlay');
644
+ overlay.innerHTML = `<div class="graph-status">Building graph…</div>`;
645
+ overlay.style.display = 'flex';
646
+ try {
647
+ const data = await fetchGraphData();
648
+ graph.raw = data;
649
+ $('#graph-meta').textContent =
650
+ `${data.counts.facts} facts · ${data.counts.entities} entities · ${data.counts.edges} links${data.truncated ? ' (capped)' : ''}`;
651
+ if (!data.nodes.length) {
652
+ overlay.innerHTML = `<div class="graph-status">No memory to graph yet. As your agents store facts, the map fills in.</div>`;
653
+ return;
654
+ }
655
+ overlay.style.display = 'none';
656
+ buildSimulation(data);
657
+ graph.loaded = true;
658
+ } catch (err) {
659
+ overlay.innerHTML = `<div class="graph-status err">Couldn’t build the graph: ${escape(err.message)}</div>`;
660
+ }
661
+ }
662
+
663
+ // Primary: single graphSnapshot RPC. Fallback (older daemons without it):
664
+ // compose from listFacts + per-fact getFactContext + searchEntity.
665
+ async function fetchGraphData() {
666
+ try {
667
+ return await rpc('graphSnapshot', { limit: 600 });
668
+ } catch (err) {
669
+ // Older daemons don't have graphSnapshot — compose from existing RPCs.
670
+ // Any other error (DB down, etc.) should surface, not silently degrade.
671
+ if (err.code === 'unknown_method') return composeGraphData();
672
+ throw err;
673
+ }
674
+ }
675
+
676
+ async function composeGraphData() {
677
+ const FACT_CAP = 150;
678
+ const [{ facts }, ...entityGroups] = await Promise.all([
679
+ rpc('listFacts', { limit: FACT_CAP }),
680
+ rpc('searchEntity', { entityType: 'person', limit: 200 }).catch(() => ({ entities: [] })),
681
+ rpc('searchEntity', { entityType: 'topic', limit: 200 }).catch(() => ({ entities: [] })),
682
+ rpc('searchEntity', { entityType: 'document', limit: 200 }).catch(() => ({ entities: [] })),
683
+ ]);
684
+ const entityMap = new Map();
685
+ for (const g of entityGroups) for (const e of g.entities) entityMap.set(e.id, e);
686
+
687
+ const edges = [];
688
+ const relSeen = new Set();
689
+ const degree = new Map();
690
+ const bump = (k) => degree.set(k, (degree.get(k) || 0) + 1);
691
+
692
+ // Fetch each fact's context with bounded concurrency.
693
+ const contexts = await mapLimit(facts, 8, (f) => rpc('getFactContext', { uid: f.uid }).catch(() => null));
694
+ facts.forEach((f, i) => {
695
+ const ctx = contexts[i];
696
+ if (!ctx || ctx.notFound) return;
697
+ for (const e of ctx.entities || []) {
698
+ if (!entityMap.has(e.id)) entityMap.set(e.id, { id: e.id, name: e.name, entityType: e.entityType, mentionCount: 0 });
699
+ const s = `f${f.id}`, t = `e${e.id}`;
700
+ edges.push({ source: s, target: t, kind: 'mentions' }); bump(s); bump(t);
701
+ }
702
+ for (const r of ctx.relations || []) {
703
+ // relations come keyed by names here; skip if we can't resolve to ids cheaply
704
+ const key = `${r.relationType}:${r.sourceName}->${r.targetName}`;
705
+ if (relSeen.has(key)) continue;
706
+ relSeen.add(key);
707
+ }
708
+ });
709
+
710
+ const nodes = [
711
+ ...[...entityMap.values()].map((e) => ({
712
+ id: `e${e.id}`, refId: e.id, kind: 'entity', label: e.name,
713
+ entityType: e.entityType || 'topic', mentions: e.mentionCount || 0, degree: degree.get(`e${e.id}`) || 0,
714
+ })),
715
+ ...facts.map((f) => ({
716
+ id: `f${f.id}`, refId: f.id, kind: 'fact', label: (f.content || '').slice(0, 160),
717
+ category: f.category || null, degree: degree.get(`f${f.id}`) || 0,
718
+ })),
719
+ ];
720
+ return { nodes, edges, truncated: facts.length >= FACT_CAP, counts: { facts: facts.length, entities: entityMap.size, edges: edges.length, relations: 0 } };
721
+ }
722
+
723
+ async function mapLimit(items, limit, fn) {
724
+ const out = new Array(items.length);
725
+ let i = 0;
726
+ async function worker() { while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx], idx); } }
727
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
728
+ return out;
729
+ }
730
+
731
+ function buildSimulation(data) {
732
+ const canvas = $('#graph-canvas');
733
+ const stage = $('#graph-stage');
734
+ const W = stage.clientWidth, H = stage.clientHeight;
735
+
736
+ // node radius: entities scale with degree+mentions; facts are small dots
737
+ const nodes = data.nodes.map((n, idx) => {
738
+ const deg = n.degree || 0;
739
+ const r = n.kind === 'entity' ? Math.min(4 + Math.sqrt(deg + (n.mentions || 0)) * 3.2, 22) : 3.2;
740
+ // seed on a spiral so the layout opens consistently (no Math.random reliance for repeatability)
741
+ const ang = idx * 2.399963229, rad = 14 * Math.sqrt(idx);
742
+ return { ...n, r, x: W / 2 + Math.cos(ang) * rad, y: H / 2 + Math.sin(ang) * rad, vx: 0, vy: 0 };
743
+ });
744
+ const byId = new Map(nodes.map((n) => [n.id, n]));
745
+ const links = data.edges
746
+ .map((e) => ({ ...e, s: byId.get(e.source), t: byId.get(e.target) }))
747
+ .filter((l) => l.s && l.t);
748
+
749
+ // adjacency for hover-highlight
750
+ const adj = new Map();
751
+ for (const n of nodes) adj.set(n.id, new Set());
752
+ for (const l of links) { adj.get(l.s.id).add(l.t.id); adj.get(l.t.id).add(l.s.id); }
753
+
754
+ graph.nodes = nodes; graph.links = links; graph.byId = byId; graph.adj = adj;
755
+
756
+ setupCanvas();
757
+ if (graph.sim) cancelAnimationFrame(graph.sim);
758
+
759
+ // simulation params
760
+ const REPULSION = 1400, LINK_DIST = 64, LINK_K = 0.04, GRAVITY = 0.018, DAMP = 0.86;
761
+ let alpha = 1;
762
+
763
+ function tick() {
764
+ const cx = W / 2, cy = H / 2;
765
+ // repulsion (O(n²) — fine for a few hundred nodes)
766
+ for (let a = 0; a < nodes.length; a++) {
767
+ const na = nodes[a];
768
+ for (let b = a + 1; b < nodes.length; b++) {
769
+ const nb = nodes[b];
770
+ let dx = na.x - nb.x, dy = na.y - nb.y;
771
+ let d2 = dx * dx + dy * dy; if (d2 < 0.01) { d2 = 0.01; dx = (a - b) * 0.1; }
772
+ const f = (REPULSION * alpha) / d2;
773
+ const d = Math.sqrt(d2);
774
+ const fx = (dx / d) * f, fy = (dy / d) * f;
775
+ na.vx += fx; na.vy += fy; nb.vx -= fx; nb.vy -= fy;
776
+ }
777
+ }
778
+ // springs
779
+ for (const l of links) {
780
+ let dx = l.t.x - l.s.x, dy = l.t.y - l.s.y;
781
+ const d = Math.sqrt(dx * dx + dy * dy) || 0.01;
782
+ const f = LINK_K * (d - LINK_DIST) * alpha;
783
+ const fx = (dx / d) * f, fy = (dy / d) * f;
784
+ l.s.vx += fx; l.s.vy += fy; l.t.vx -= fx; l.t.vy -= fy;
785
+ }
786
+ // gravity to center (contains orphans) + integrate
787
+ for (const n of nodes) {
788
+ if (n === graph.dragNode || n.pinned) { n.vx = 0; n.vy = 0; continue; }
789
+ n.vx += (cx - n.x) * GRAVITY * alpha;
790
+ n.vy += (cy - n.y) * GRAVITY * alpha;
791
+ n.vx *= DAMP; n.vy *= DAMP;
792
+ n.x += n.vx; n.y += n.vy;
793
+ }
794
+ // forceCenter: snap the free cluster's centroid back to canvas center each
795
+ // tick (Obsidian-style center of gravity) so the layout settles centered
796
+ // instead of drifting off into a corner. Pinned / dragged nodes are excluded
797
+ // so a deliberate placement isn't yanked around.
798
+ let mx = 0, my = 0, cnt = 0;
799
+ for (const n of nodes) { if (n === graph.dragNode || n.pinned) continue; mx += n.x; my += n.y; cnt++; }
800
+ if (cnt) {
801
+ const sx = cx - mx / cnt, sy = cy - my / cnt;
802
+ for (const n of nodes) { if (n === graph.dragNode || n.pinned) continue; n.x += sx; n.y += sy; }
803
+ }
804
+ alpha *= 0.985;
805
+ }
806
+
807
+ if (reducedMotion) {
808
+ for (let i = 0; i < 320; i++) tick();
809
+ graphFit(); render();
810
+ } else {
811
+ function loop() {
812
+ tick();
813
+ render();
814
+ if (alpha > 0.02 || graph.dragNode) { graph.sim = requestAnimationFrame(loop); }
815
+ else graph.sim = null;
816
+ }
817
+ graphFit(false);
818
+ graph.sim = requestAnimationFrame(loop);
819
+ }
820
+ graph._reheat = () => { alpha = Math.max(alpha, 0.5); if (!graph.sim && !reducedMotion) graph.sim = requestAnimationFrame(function l() { tick(); render(); if (alpha > 0.02 || graph.dragNode) graph.sim = requestAnimationFrame(l); else graph.sim = null; }); };
821
+ }
822
+
823
+ function setupCanvas() {
824
+ const canvas = $('#graph-canvas');
825
+ const stage = $('#graph-stage');
826
+ const dpr = window.devicePixelRatio || 1;
827
+ canvas.width = stage.clientWidth * dpr;
828
+ canvas.height = stage.clientHeight * dpr;
829
+ canvas.style.width = stage.clientWidth + 'px';
830
+ canvas.style.height = stage.clientHeight + 'px';
831
+ graph.ctx = canvas.getContext('2d');
832
+ graph.dpr = dpr;
833
+ }
834
+
835
+ function render() {
836
+ const ctx = graph.ctx; if (!ctx) return;
837
+ const canvas = $('#graph-canvas');
838
+ const { x: px, y: py, k } = graph.view;
839
+ ctx.save();
840
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
841
+ ctx.scale(graph.dpr, graph.dpr);
842
+ ctx.translate(px, py); ctx.scale(k, k);
843
+
844
+ const hoverId = graph.hover?.id;
845
+ const lit = hoverId ? graph.adj.get(hoverId) : null;
846
+ const isLit = (id) => !hoverId || id === hoverId || lit.has(id);
847
+
848
+ // edges — three tiers: incident-to-hover (bright), idle (legible at rest),
849
+ // non-incident-while-hovering (faded so the focused subgraph reads clearly)
850
+ for (const l of graph.links) {
851
+ const incident = l.s.id === hoverId || l.t.id === hoverId;
852
+ const faded = hoverId && !incident;
853
+ ctx.beginPath();
854
+ ctx.moveTo(l.s.x, l.s.y); ctx.lineTo(l.t.x, l.t.y);
855
+ if (l.kind === 'relation') {
856
+ ctx.strokeStyle = incident ? 'rgba(0,132,255,0.7)' : faded ? 'rgba(0,132,255,0.06)' : 'rgba(0,132,255,0.3)';
857
+ ctx.lineWidth = 1.3 / k;
858
+ } else {
859
+ ctx.strokeStyle = incident ? 'rgba(164,167,179,0.6)' : faded ? 'rgba(140,142,150,0.05)' : 'rgba(146,149,171,0.2)';
860
+ ctx.lineWidth = 1 / k;
861
+ }
862
+ ctx.stroke();
863
+ }
864
+ // nodes
865
+ for (const n of graph.nodes) {
866
+ const on = isLit(n.id);
867
+ ctx.globalAlpha = on ? 1 : 0.22;
868
+ ctx.beginPath();
869
+ ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
870
+ if (n.kind === 'entity') {
871
+ ctx.fillStyle = ENTITY_COLORS[n.entityType] || ENTITY_COLORS.topic;
872
+ ctx.fill();
873
+ if (n.id === hoverId) { ctx.lineWidth = 2 / k; ctx.strokeStyle = '#f4f5f6'; ctx.stroke(); }
874
+ } else {
875
+ ctx.fillStyle = '#5b5f67'; // visible-but-secondary on the near-black canvas
876
+ ctx.fill();
877
+ if (n.id === hoverId) { ctx.lineWidth = 2 / k; ctx.strokeStyle = '#0084ff'; ctx.stroke(); }
878
+ }
879
+ ctx.globalAlpha = 1;
880
+ // labels: hubs (high-degree entities) read at any zoom; leaf entities only
881
+ // when zoomed in or hovered; facts only on hover. Keeps dense graphs legible.
882
+ const isHub = n.kind === 'entity' && n.degree >= 2;
883
+ const showLabel = n.id === hoverId || (n.kind === 'entity' && on && (isHub || k > 1.45));
884
+ if (showLabel) {
885
+ const label = n.label.length > 26 ? n.label.slice(0, 25) + '…' : n.label;
886
+ ctx.font = `${n.kind === 'entity' ? 600 : 400} ${11 / k}px 'Geist', ui-sans-serif, system-ui, sans-serif`;
887
+ ctx.fillStyle = on ? '#f4f5f6' : '#74777d';
888
+ ctx.textAlign = 'center'; ctx.textBaseline = 'top';
889
+ ctx.fillText(label, n.x, n.y + n.r + 2 / k);
890
+ }
891
+ }
892
+ ctx.restore();
893
+ }
894
+
895
+ // fit all nodes into view (with padding)
896
+ function graphFit(doRender = true) {
897
+ const nodes = graph.nodes; if (!nodes?.length) return;
898
+ const stage = $('#graph-stage');
899
+ const W = stage.clientWidth, H = stage.clientHeight;
900
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
901
+ for (const n of nodes) { minX = Math.min(minX, n.x); minY = Math.min(minY, n.y); maxX = Math.max(maxX, n.x); maxY = Math.max(maxY, n.y); }
902
+ const gw = (maxX - minX) || 1, gh = (maxY - minY) || 1;
903
+ const pad = 96; // generous margin so edge nodes' labels stay in frame
904
+ // Cap below the leaf-label threshold (1.45) so the default view labels only
905
+ // hubs; zooming in past that reveals every entity label.
906
+ const k = Math.min((W - pad) / gw, (H - pad) / gh, 1.35);
907
+ graph.view.k = k;
908
+ graph.view.x = W / 2 - ((minX + maxX) / 2) * k;
909
+ graph.view.y = H / 2 - ((minY + maxY) / 2) * k;
910
+ if (doRender) render();
911
+ }
912
+
913
+ // screen → world coords
914
+ function toWorld(sx, sy) {
915
+ return { x: (sx - graph.view.x) / graph.view.k, y: (sy - graph.view.y) / graph.view.k };
916
+ }
917
+ function nodeAt(sx, sy) {
918
+ const { x, y } = toWorld(sx, sy);
919
+ // topmost (facts drawn last but entities are bigger targets) — iterate reverse
920
+ for (let i = graph.nodes.length - 1; i >= 0; i--) {
921
+ const n = graph.nodes[i];
922
+ const dx = n.x - x, dy = n.y - y;
923
+ const hitR = Math.max(n.r, 6); // generous hit target in world units
924
+ if (dx * dx + dy * dy <= hitR * hitR) return n;
925
+ }
926
+ return null;
927
+ }
928
+
929
+ // ── graph interactions ───────────────────────────────────────────────
930
+ (function wireGraph() {
931
+ const stage = () => $('#graph-stage');
932
+ const canvas = () => $('#graph-canvas');
933
+ let down = null;
934
+
935
+ $('#graph-stage')?.addEventListener('pointerdown', (e) => {
936
+ const rect = canvas().getBoundingClientRect();
937
+ const sx = e.clientX - rect.left, sy = e.clientY - rect.top;
938
+ const n = nodeAt(sx, sy);
939
+ down = { sx, sy, vx: graph.view.x, vy: graph.view.y, node: n, moved: false };
940
+ if (n) { graph.dragNode = n; } else { graph.panning = true; }
941
+ canvas().setPointerCapture(e.pointerId);
942
+ });
943
+ $('#graph-stage')?.addEventListener('pointermove', (e) => {
944
+ const rect = canvas().getBoundingClientRect();
945
+ const sx = e.clientX - rect.left, sy = e.clientY - rect.top;
946
+ if (!down) {
947
+ const n = nodeAt(sx, sy);
948
+ if (n !== graph.hover) { graph.hover = n; showTooltip(n, sx, sy); render(); }
949
+ else if (n) showTooltip(n, sx, sy);
950
+ canvas().style.cursor = n ? 'pointer' : 'grab';
951
+ return;
952
+ }
953
+ const ddx = sx - down.sx, ddy = sy - down.sy;
954
+ if (Math.abs(ddx) > 3 || Math.abs(ddy) > 3) down.moved = true;
955
+ if (down.node) {
956
+ const w = toWorld(sx, sy);
957
+ down.node.x = w.x; down.node.y = w.y;
958
+ graph._reheat?.(); render();
959
+ } else if (graph.panning) {
960
+ graph.view.x = down.vx + ddx; graph.view.y = down.vy + ddy;
961
+ render();
962
+ }
963
+ });
964
+ function endDrag(e) {
965
+ if (down && down.node && !down.moved) openGraphNode(down.node);
966
+ else if (down && down.node && down.moved) down.node.pinned = true; // keep a deliberately-placed node put
967
+ graph.dragNode = null; graph.panning = false; down = null;
968
+ if (canvas()) canvas().style.cursor = 'grab';
969
+ }
970
+ $('#graph-stage')?.addEventListener('pointerup', endDrag);
971
+ $('#graph-stage')?.addEventListener('pointerleave', () => { if (!down) { graph.hover = null; hideTooltip(); render(); } });
972
+
973
+ $('#graph-stage')?.addEventListener('wheel', (e) => {
974
+ e.preventDefault();
975
+ const rect = canvas().getBoundingClientRect();
976
+ const sx = e.clientX - rect.left, sy = e.clientY - rect.top;
977
+ const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
978
+ const k0 = graph.view.k, k1 = Math.max(0.15, Math.min(k0 * factor, 6));
979
+ // zoom toward cursor
980
+ graph.view.x = sx - (sx - graph.view.x) * (k1 / k0);
981
+ graph.view.y = sy - (sy - graph.view.y) * (k1 / k0);
982
+ graph.view.k = k1;
983
+ render();
984
+ }, { passive: false });
985
+
986
+ $('#graph-zoom-in')?.addEventListener('click', () => zoomBy(1.25));
987
+ $('#graph-zoom-out')?.addEventListener('click', () => zoomBy(1 / 1.25));
988
+ $('#graph-zoom-fit')?.addEventListener('click', () => graphFit());
989
+ $('#graph-refresh')?.addEventListener('click', () => { graph.loaded = false; loadGraph(); });
990
+ $('#graph-relayout')?.addEventListener('click', () => { if (graph.raw) buildSimulation(graph.raw); });
991
+
992
+ function zoomBy(f) {
993
+ const stageEl = stage(); const sx = stageEl.clientWidth / 2, sy = stageEl.clientHeight / 2;
994
+ const k0 = graph.view.k, k1 = Math.max(0.15, Math.min(k0 * f, 6));
995
+ graph.view.x = sx - (sx - graph.view.x) * (k1 / k0);
996
+ graph.view.y = sy - (sy - graph.view.y) * (k1 / k0);
997
+ graph.view.k = k1; render();
998
+ }
999
+ })();
1000
+
1001
+ function showTooltip(n, sx, sy) {
1002
+ const tip = $('#graph-tooltip');
1003
+ if (!n) { hideTooltip(); return; }
1004
+ tip.hidden = false;
1005
+ tip.innerHTML = n.kind === 'entity'
1006
+ ? `<span class="gt-kind">${escape(titleCase(n.entityType))}</span>${escape(n.label)}<span class="gt-meta">${n.mentions} mentions · ${n.degree} links</span>`
1007
+ : `<span class="gt-kind">Fact</span>${escape(n.label)}`;
1008
+ const stage = $('#graph-stage');
1009
+ const tw = tip.offsetWidth || 220, th = tip.offsetHeight || 64;
1010
+ tip.style.left = Math.max(4, Math.min(sx + 14, stage.clientWidth - tw - 4)) + 'px';
1011
+ tip.style.top = Math.max(4, Math.min(sy + 14, stage.clientHeight - th - 4)) + 'px';
1012
+ }
1013
+ function hideTooltip() { const t = $('#graph-tooltip'); if (t) t.hidden = true; }
1014
+
1015
+ function openGraphNode(n) {
1016
+ setRoute('kb');
1017
+ if (n.kind === 'entity') { kbSetTab('entities'); kbSelectEntity(n.refId); }
1018
+ else {
1019
+ kbSetTab('facts');
1020
+ // ensure facts are loaded, then select the row
1021
+ if (kb.facts.length) kbSelectFactById(n.refId);
1022
+ else kbLoadFacts().then(() => kbSelectFactById(n.refId));
1023
+ }
1024
+ }
1025
+ function kbSelectFactById(factId) {
1026
+ const f = kb.facts.find((x) => x.refId === factId || x.id === factId);
1027
+ if (f) kbSelectFact(f.uid);
1028
+ else rpc('getFactContext', { factId }).then((ctx) => {
1029
+ if (ctx?.fact?.uid) kbSelectFact(ctx.fact.uid);
1030
+ }).catch(() => {});
1031
+ }
1032
+
1033
+ let _graphResizeT = null;
1034
+ window.addEventListener('resize', () => {
1035
+ if (location.hash !== '#graph' || !graph.loaded) return;
1036
+ clearTimeout(_graphResizeT);
1037
+ _graphResizeT = setTimeout(() => { setupCanvas(); graphFit(); }, 150);
1038
+ });
146
1039
 
147
1040
  async function refreshMethods() {
148
1041
  try {