@anmol-srv/sigil 0.18.2 → 0.22.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.
Files changed (47) hide show
  1. package/README.md +37 -25
  2. package/dist/cli.js +1191 -790
  3. package/dist/daemon.js +664 -302
  4. package/dist/hooks/post-tool-use.js +1 -69
  5. package/dist/hooks/session-end.js +13 -236
  6. package/dist/hooks/stop.js +36 -246
  7. package/dist/hooks/user-prompt-submit.js +25 -288
  8. package/dist/mcp/worker-server.js +6 -0
  9. package/dist/npm-entry.js +10 -0
  10. package/dist/server.js +64 -56
  11. package/install.sh +207 -0
  12. package/integrations/hermes/README.md +30 -24
  13. package/integrations/hermes/plugin/README.md +1 -1
  14. package/integrations/hermes/plugin/__init__.py +68 -24
  15. package/knexfile.js +19 -22
  16. package/package.json +9 -28
  17. package/prompts/audm-decision.md +26 -1
  18. package/prompts/entity-extraction.md +32 -30
  19. package/prompts/graph-extraction.md +20 -2
  20. package/src/db/drivers/index.js +38 -15
  21. package/src/db/migrations/20260629120000_add-trace-event-attribution.cjs +29 -0
  22. package/src/db/migrations/20260629120001_add-llm-log-session-correlation.cjs +29 -0
  23. package/src/db/migrations/20260806120000_add-document-content.cjs +27 -0
  24. package/src/db/migrations/20260806120001_llm-log-model-nullable.cjs +36 -0
  25. package/src/db/migrations/20260811120000_add-relation-provenance.cjs +42 -0
  26. package/src/db/migrations/20260811130000_add-fact-visibility.cjs +67 -0
  27. package/src/db/migrations/20260813090000_rescore-defaulted-vital.cjs +57 -0
  28. package/src/db/migrations/20260814120000_create-ingestion-job.cjs +52 -0
  29. package/src/db/migrations/20260814120100_add-llm-log-queued-ms.cjs +8 -0
  30. package/src/db/migrations/20260814120200_add-active-fact-content-hash-index.cjs +16 -0
  31. package/src/db/migrations/20260814120300_create-relation-candidate-judgment.cjs +25 -0
  32. package/src/gui/web/app.css +851 -84
  33. package/src/gui/web/app.js +796 -383
  34. package/src/gui/web/cmdk.js +238 -0
  35. package/src/gui/web/components.js +64 -0
  36. package/src/gui/web/design/colors_and_type.css +6 -1
  37. package/src/gui/web/graph/GraphIsland.jsx +450 -0
  38. package/src/gui/web/graph/cluster.js +305 -0
  39. package/src/gui/web/graph/cluster.test.js +219 -0
  40. package/src/gui/web/health.js +117 -0
  41. package/src/gui/web/health.test.js +159 -0
  42. package/src/gui/web/icons.js +65 -0
  43. package/src/gui/web/index.html +310 -115
  44. package/src/gui/web/settings.js +386 -0
  45. package/src/gui/web/setup.js +2 -2
  46. package/src/gui/web/toast.js +6 -3
  47. package/src/gui/web/vendor/graph-island.js +52 -0
@@ -1,7 +1,12 @@
1
1
  // Sigil GUI — vanilla JS. Onboarding wizard + dashboard.
2
2
  import { toast } from './toast.js';
3
- import { connectorCard } from './components.js';
3
+ import { connectorCard , fieldControl, confirmDialog } from './components.js';
4
4
  import { initSetup } from './setup.js';
5
+ import { icon, hydrateIcons } from './icons.js';
6
+ import { initCmdk } from './cmdk.js';
7
+ import { systemAlert, systemCells, engineBlocker } from './health.js';
8
+ import { initSettings } from './settings.js';
9
+ import { mountGraph } from './vendor/graph-island.js';
5
10
 
6
11
  const $ = (sel, root = document) => root.querySelector(sel);
7
12
  const $$ = (sel, root = document) => root.querySelectorAll(sel);
@@ -49,6 +54,54 @@ async function copyToClipboard(text) {
49
54
  }
50
55
  }
51
56
 
57
+
58
+ /**
59
+ * Resolve once the daemon answers again after a restart.
60
+ *
61
+ * Both restart paths used to guess a fixed delay — the provider switcher 1.5s,
62
+ * the engine toggle 3s — and neither checked. A boot that took longer left the
63
+ * UI stuck on "Restarting daemon…" with the first poll failing against a socket
64
+ * that wasn't listening yet. Warm workers make that routine: a cold `claude`
65
+ * handshake alone is ~10s. Returns false if it never comes back, so callers can
66
+ * say so instead of hanging.
67
+ */
68
+ async function waitForDaemon({ timeoutMs = 45000, everyMs = 700 } = {}) {
69
+ // Let the process actually go down first, or the first ping hits the OUTGOING
70
+ // daemon and we conclude it never restarted.
71
+ await new Promise((r) => setTimeout(r, 500));
72
+ const deadline = Date.now() + timeoutMs;
73
+ while (Date.now() < deadline) {
74
+ try { await rpc('ping'); return true; }
75
+ catch { await new Promise((r) => setTimeout(r, everyMs)); }
76
+ }
77
+ return false;
78
+ }
79
+
80
+ /**
81
+ * Run an async action with the button showing it. Every Refresh button fired
82
+ * silently — on a fast reload nothing appeared to happen, and on a slow one
83
+ * there was no sign it was working, so people clicked again. MIN_BUSY keeps the
84
+ * state visible long enough to read on a fast response.
85
+ */
86
+ const MIN_BUSY = 320;
87
+ async function withBusy(btn, fn) {
88
+ if (!btn) return fn();
89
+ if (btn.dataset.busy) return undefined; // already running — ignore re-clicks
90
+ btn.dataset.busy = '1';
91
+ btn.classList.add('is-busy');
92
+ btn.setAttribute('aria-busy', 'true');
93
+ const started = Date.now();
94
+ try {
95
+ return await fn();
96
+ } finally {
97
+ const left = MIN_BUSY - (Date.now() - started);
98
+ if (left > 0) await new Promise((r) => setTimeout(r, left));
99
+ delete btn.dataset.busy;
100
+ btn.classList.remove('is-busy');
101
+ btn.removeAttribute('aria-busy');
102
+ }
103
+ }
104
+
52
105
  // ════════════════════════════════════════════════════════════════════
53
106
  // DASHBOARD (unchanged behavior)
54
107
  // ════════════════════════════════════════════════════════════════════
@@ -61,18 +114,30 @@ function renderKv(node, entries) {
61
114
  node.innerHTML = entries.map(([k, v]) => `<div class="row"><div class="k">${escape(k)}</div><div class="v">${escape(v)}</div></div>`).join('');
62
115
  }
63
116
 
64
- const validRoutes = ['health', 'kb', 'graph', 'devices', 'activity', 'setup', 'settings', 'methods'];
117
+ const validRoutes = ['health', 'kb', 'graph', 'agents', 'devices', 'activity', 'engine', 'setup', 'settings'];
118
+ const ROUTE_TITLES = {
119
+ health: 'Home', kb: 'Knowledge Base', graph: 'Graph', agents: 'Agents', devices: 'Devices',
120
+ activity: 'Activity', engine: 'Engine', setup: 'Database', settings: 'Settings',
121
+ };
65
122
  function setRoute(name) {
66
123
  $$('.view').forEach((v) => v.classList.toggle('active', v.id === `view-${name}`));
67
- $$('nav a').forEach((a) => a.classList.toggle('active', a.dataset.route === name));
124
+ $$('nav a').forEach((a) => {
125
+ const on = a.dataset.route === name;
126
+ a.classList.toggle('active', on);
127
+ if (on) a.setAttribute('aria-current', 'page');
128
+ else a.removeAttribute('aria-current');
129
+ });
130
+ const h1 = $('#route-title');
131
+ if (h1) h1.textContent = ROUTE_TITLES[name] || 'Sigil';
68
132
  window.location.hash = name;
69
133
  if (name === 'health') refreshHealth();
70
134
  if (name === 'kb') refreshKb();
71
135
  if (name === 'graph') initGraphView();
72
- if (name === 'methods') refreshMethods();
73
- if (name === 'settings') { refreshEnv(); refreshSettingsClients(); }
136
+ if (name === 'settings') { refreshEnv(); refreshMethods(); settingsPanel?.refresh(); }
137
+ if (name === 'agents') refreshAgents();
74
138
  if (name === 'devices') refreshDevices();
75
139
  if (name === 'activity') { ensureActivityWs(); loadTraces(); }
140
+ if (name === 'engine') startEnginePolling(); else stopEnginePolling();
76
141
  }
77
142
  function routeFromHash() {
78
143
  const r = (window.location.hash || '#health').slice(1);
@@ -82,28 +147,36 @@ window.addEventListener('hashchange', () => setRoute(routeFromHash()));
82
147
  $$('nav a').forEach((a) => {
83
148
  a.addEventListener('click', (e) => { e.preventDefault(); setRoute(a.dataset.route); });
84
149
  });
150
+ $('#home-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, refreshHealth));
151
+ $('#agents-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, refreshAgents));
152
+
153
+ const fmtNum = (x) => (typeof x === 'number' ? x.toLocaleString() : '—');
85
154
 
86
155
  async function refreshHealth() {
87
156
  try {
88
- const [ping, nodeInfo, mode] = await Promise.all([
157
+ const [ping, nodeInfo, mode, status] = await Promise.all([
89
158
  rpc('ping'),
90
159
  rpc('nodeInfo').catch(() => ({ enabled: false })),
91
160
  rpc('mode').catch(() => ({})),
161
+ // A failed `status` is itself a health signal — don't swallow it into an
162
+ // empty object, or the readout below cheerfully reports "connected".
163
+ rpc('status', { hotFactsLimit: 6 })
164
+ .catch((err) => ({ unavailable: true, db: { healthy: false, error: err.message } })),
92
165
  ]);
93
- $('#hc-pid').textContent = `pid ${ping.pid}`;
94
- $('#hc-uptime').textContent = `up ${formatUptime(ping.uptimeMs)} · ${ping.node}`;
95
- $('#hc-mode').textContent = mode.mode || '—';
96
- $('#hc-driver').textContent = mode.memoryClient ? `memory client: ${mode.memoryClient}` : '—';
97
- if (nodeInfo.enabled && nodeInfo.nodeId) {
98
- $('#hc-nodeid').textContent = nodeInfo.nodeId.slice(0, 12) + '…';
99
- $('#hc-nodeid').title = nodeInfo.nodeId;
100
- $('#hc-relay').textContent = nodeInfo.relayUrl ? new URL(nodeInfo.relayUrl).hostname : 'no relay';
101
- } else {
102
- $('#hc-nodeid').textContent = '—';
103
- $('#hc-relay').textContent = 'Iroh disabled';
104
- }
105
- $('#brand-badge').textContent = mode.mode || 'solo';
106
166
 
167
+ // The store being unreachable is NOT the same as memory being empty. When
168
+ // `status` says so, every count comes back null — render "unavailable",
169
+ // never a zero, and let the banner carry the reason.
170
+ renderSystem(status);
171
+
172
+ // ── stat strip: memory as the hero (real counts from status) ──
173
+ const ents = status.unavailable ? null
174
+ : (status.entities?.documents || 0) + (status.entities?.people || 0) + (status.entities?.topics || 0);
175
+ $('#hm-facts').textContent = fmtNum(status.facts);
176
+ $('#hm-entities').textContent = fmtNum(ents);
177
+ $('#hm-relations').textContent = fmtNum(status.relations);
178
+
179
+ // ── diagnostics drawer: the daemon plumbing, demoted ──
107
180
  const rows = [
108
181
  ['daemon pid', ping.pid], ['version', ping.version], ['node.js', ping.node],
109
182
  ['uptime', formatUptime(ping.uptimeMs)], ['mode', mode.mode || '—'],
@@ -114,6 +187,8 @@ async function refreshHealth() {
114
187
  rows.push(['this nodeId', nodeInfo.nodeId || nodeInfo.error || '—']);
115
188
  if (nodeInfo.relayUrl) rows.push(['relay', nodeInfo.relayUrl]);
116
189
  if (nodeInfo.addresses?.length) rows.push(['addresses', nodeInfo.addresses.join(', ')]);
190
+ } else {
191
+ rows.push(['identity', 'Iroh disabled']);
117
192
  }
118
193
  renderKv($('#health-pane'), rows);
119
194
 
@@ -122,6 +197,109 @@ async function refreshHealth() {
122
197
 
123
198
  setConn('ok', 'connected');
124
199
  } catch (err) { setConn('err', err.message); }
200
+
201
+ // recall health + recent activity are independent of the daemon ping;
202
+ // load them in one fetch so one failing doesn't blank the other.
203
+ loadHomeActivity();
204
+ }
205
+
206
+ // ── System health: banner + readout + most-recalled ──────────────────
207
+ // `status` already carries every probe result the daemon has (DB reachability
208
+ // and schema, the boot provider probe, the write-queue depth, the hottest
209
+ // facts). None of it reached the dashboard before, so a dead Postgres or a
210
+ // revoked API key rendered as an empty-looking memory — the exact soft failure
211
+ // DESIGN.md forbids. One render pass turns all of it into a visible state.
212
+ function renderSystem(status) {
213
+ const banner = $('#sys-banner');
214
+ const alert = systemAlert(status);
215
+
216
+ if (!alert) {
217
+ banner.hidden = true;
218
+ banner.innerHTML = '';
219
+ } else {
220
+ banner.hidden = false;
221
+ banner.className = `sysbanner ${alert.level}`;
222
+ banner.innerHTML = `
223
+ <span class="sysbanner-ic">${icon(alert.level === 'err' ? 'alert' : 'alert')}</span>
224
+ <span class="sysbanner-text"><strong>${escape(alert.title)}</strong> ${escape(alert.body)}</span>
225
+ <button class="btn small" type="button" data-banner-route="${alert.action.route}">${escape(alert.action.label)}</button>`;
226
+ }
227
+
228
+ // ── readout: four rows, each a live probe, never a config echo ──
229
+ const row = $('#hm-sysrow');
230
+ if (!row) return;
231
+ row.innerHTML = systemCells(status).map((c) => `
232
+ <div class="syscell">
233
+ <span class="syscell-k">${escape(c.k)}</span>
234
+ <span class="syscell-v ${c.s}"><i class="sq"></i>${escape(c.v)}</span>
235
+ ${c.sub ? `<span class="syscell-sub">${escape(c.sub)}</span>` : ''}
236
+ </div>`).join('');
237
+
238
+ // ── most recalled ──
239
+ const hot = $('#hm-hot');
240
+ if (!hot) return;
241
+ const facts = status.hotFacts || [];
242
+ hot.innerHTML = facts.length
243
+ ? facts.map((f) => `<li class="hotrow">
244
+ <button class="hotrow-btn" type="button"${f.id != null ? ` data-fact-id="${f.id}"` : ''}>
245
+ <span class="hotrow-text">${escape(f.content)}</span>
246
+ <span class="hotrow-n" title="times recalled">${escape(f.accessCount)}×</span>
247
+ </button>
248
+ </li>`).join('')
249
+ : `<li class="muted text-sm">Nothing recalled yet. Counts appear here once your agents start searching — try <code>⌘K</code> above.</li>`;
250
+ }
251
+
252
+ $('#sys-banner')?.addEventListener('click', (e) => {
253
+ const b = e.target.closest('[data-banner-route]');
254
+ if (b) setRoute(b.dataset.bannerRoute);
255
+ });
256
+ $('#hm-hot')?.addEventListener('click', (e) => {
257
+ const r = e.target.closest('[data-fact-id]');
258
+ if (r) { setRoute('kb'); kbSetTab('facts'); kbSelectFactById(Number(r.dataset.factId)); }
259
+ });
260
+
261
+ // One trace.list call feeds both the recall metrics and the activity feed.
262
+ // Recall hit-rate, avg results, and median latency are computed CLIENT-SIDE
263
+ // from the search traces in the recent window — no backend metric needed.
264
+ // A "hit" is any search whose ranking returned ≥1 fact (detail.ranking.facts).
265
+ async function loadHomeActivity() {
266
+ let traces;
267
+ try { ({ traces } = await rpc('trace.list', { limit: 50 })); } catch { return; }
268
+
269
+ const searches = traces.filter((t) => t.kind === 'search');
270
+ const n = searches.length;
271
+ const factCount = (t) => (t.detail?.ranking?.facts?.length || 0);
272
+ const withHits = searches.filter((t) => factCount(t) > 0).length;
273
+ const hitRate = n ? Math.round((withHits / n) * 100) : null;
274
+ const avgFacts = n ? (searches.reduce((s, t) => s + factCount(t), 0) / n) : null;
275
+ const durs = searches.map((t) => t.durationMs).filter((x) => x != null).sort((a, b) => a - b);
276
+ const med = durs.length ? durs[Math.floor(durs.length / 2)] : null;
277
+
278
+ $('#hm-recall').textContent = hitRate != null ? `${hitRate}%` : '—';
279
+ $('#hm-recall-sub').textContent = n ? `${n} recent searches` : 'no searches yet';
280
+ const dot = $('#hm-recall-dot');
281
+ dot.className = 'hm-dot' + (hitRate == null ? '' : hitRate >= 80 ? ' ok' : hitRate >= 50 ? ' warn' : ' err');
282
+
283
+ $('#hm-searches').textContent = fmtNum(n);
284
+ $('#hm-hitrate').textContent = hitRate != null ? `${hitRate}%` : '—';
285
+ $('#hm-hitbar').style.transform = `scaleX(${hitRate != null ? hitRate / 100 : 0})`;
286
+ $('#hm-avgfacts').textContent = avgFacts != null ? avgFacts.toFixed(1) : '—';
287
+ $('#hm-latency').textContent = med != null ? `${med}ms` : '—';
288
+
289
+ const feed = $('#hm-feed');
290
+ feed.innerHTML = traces.length
291
+ ? traces.slice(0, 6).map(homeFeedRow).join('')
292
+ : '<li class="muted text-sm">no activity yet — run a search or remember a fact</li>';
293
+ }
294
+
295
+ function homeFeedRow(t) {
296
+ const agent = t.agent ? `<span class="badge ${agentBadge(t.agent)}">${escape(t.agent)}</span>` : '';
297
+ return `<li class="home-feed-row">
298
+ <span class="badge ${traceBadge(t.kind)}">${escape(t.kind)}</span>
299
+ <span class="home-feed-summary">${escape(t.summary)}</span>
300
+ ${agent}
301
+ <span class="home-feed-time">${escape(clock(t.ts))}</span>
302
+ </li>`;
125
303
  }
126
304
 
127
305
  // ════════════════════════════════════════════════════════════════════
@@ -131,6 +309,7 @@ const kb = {
131
309
  tab: 'facts',
132
310
  loaded: false,
133
311
  facts: [], // full fetched set (cross-namespace)
312
+ factTotal: null, // true total from the stat strip; null = not loaded yet
134
313
  factNs: null, // active namespace filter (null = all)
135
314
  factCat: null, // active category filter (null = all)
136
315
  factSearch: '',
@@ -139,6 +318,9 @@ const kb = {
139
318
  entitySearch: '',
140
319
  entities: [],
141
320
  selectedEntityId: null,
321
+ documents: null, // null = not fetched yet
322
+ docSearch: '',
323
+ selectedDocUid: null,
142
324
  pods: null,
143
325
  };
144
326
 
@@ -167,6 +349,8 @@ async function kbLoadStats() {
167
349
  try {
168
350
  const d = await rpc('status', {});
169
351
  const ents = (d.entities?.documents || 0) + (d.entities?.people || 0) + (d.entities?.topics || 0);
352
+ kb.factTotal = d.facts ?? null;
353
+ if (kb.facts.length) kbRenderFacts();
170
354
  const stats = [
171
355
  ['Facts', d.facts], ['Entities', ents], ['Relations', d.relations],
172
356
  ['Documents', d.documents], ['Chunks', d.chunks],
@@ -187,20 +371,23 @@ function kbSetTab(name, { force = false } = {}) {
187
371
  t.classList.toggle('active', on);
188
372
  t.setAttribute('aria-selected', on ? 'true' : 'false');
189
373
  });
190
- $('#kb-tab-facts').hidden = name !== 'facts';
191
- $('#kb-tab-entities').hidden = name !== 'entities';
192
- $('#kb-tab-pods').hidden = name !== 'pods';
374
+ $$('.kb-panel').forEach((p) => { p.hidden = p.id !== `kb-tab-${name}`; });
193
375
  if (name === 'facts') kbRenderFacts();
194
376
  if (name === 'entities' && !kb.entities.length && !kb.entitySearch) kbSearchEntities();
377
+ if (name === 'documents' && !kb.documents) kbLoadDocuments();
195
378
  if (name === 'pods' && !kb.pods) kbLoadPods();
196
379
  }
197
380
 
198
381
  // ── Facts ────────────────────────────────────────────────────────────
382
+ // The list is capped; the stat strip above it is not. Saying "200 of 203"
383
+ // beats silently showing 200 and letting the two disagree on screen.
384
+ const FACT_LIST_LIMIT = 200;
385
+
199
386
  async function kbLoadFacts() {
200
387
  const list = $('#kb-fact-list');
201
388
  list.innerHTML = kbSkeleton(7);
202
389
  try {
203
- const { facts } = await rpc('listFacts', { limit: 200 });
390
+ const { facts } = await rpc('listFacts', { limit: FACT_LIST_LIMIT });
204
391
  kb.facts = facts || [];
205
392
  kbRenderFactFilters();
206
393
  kbRenderFacts();
@@ -237,7 +424,11 @@ function kbFilteredFacts() {
237
424
  function kbRenderFacts() {
238
425
  const list = $('#kb-fact-list');
239
426
  const facts = kbFilteredFacts();
240
- $('#kb-fact-count').textContent = `${facts.length} fact${facts.length === 1 ? '' : 's'}`;
427
+ const total = kb.factTotal;
428
+ const capped = Number.isFinite(total) && kb.facts.length < total && facts.length === kb.facts.length;
429
+ $('#kb-fact-count').textContent = capped
430
+ ? `${facts.length} of ${total} facts`
431
+ : `${facts.length} fact${facts.length === 1 ? '' : 's'}`;
241
432
  if (!facts.length) {
242
433
  list.innerHTML = kb.facts.length
243
434
  ? `<div class="empty">No facts match this filter. Clear the search or pick a different category.</div>`
@@ -315,7 +506,13 @@ function kbRenderFactDetail(ctx) {
315
506
  }
316
507
 
317
508
  async function kbForgetFact(uid) {
318
- if (!window.confirm('Forget this fact? It will be removed from memory and stop being recalled.')) return;
509
+ const ok = await confirmDialog({
510
+ title: 'Forget this fact?',
511
+ message: 'It will be removed from memory and stop being recalled.',
512
+ confirmLabel: 'Forget',
513
+ danger: true,
514
+ });
515
+ if (!ok) return;
319
516
  try {
320
517
  await rpc('forgetFact', { uid });
321
518
  toast({ variant: 'success', message: 'Fact forgotten.' });
@@ -413,6 +610,99 @@ function kbRenderEntityDetail(ctx) {
413
610
  </div>`;
414
611
  }
415
612
 
613
+ // ── Documents ────────────────────────────────────────────────────────
614
+ // The whole-document layer: `sigil ingest` keeps the full source text, and
615
+ // facts/chunks are derived from it. That store had no dashboard surface at all,
616
+ // so "what did I ingest, and what did it produce?" was a CLI-only question.
617
+ // podScope 'global' because the dashboard has no cwd to scope to.
618
+ async function kbLoadDocuments() {
619
+ const list = $('#kb-doc-list');
620
+ list.innerHTML = kbSkeleton(6);
621
+ try {
622
+ const { documents } = await rpc('listDocuments', { limit: 100, podScope: 'global' });
623
+ kb.documents = documents || [];
624
+ kbRenderDocs();
625
+ } catch (err) {
626
+ kb.documents = [];
627
+ list.innerHTML = `<div class="empty">Couldn’t load documents: ${escape(err.message)}</div>`;
628
+ }
629
+ }
630
+
631
+ function kbRenderDocs() {
632
+ const list = $('#kb-doc-list');
633
+ const q = kb.docSearch.trim().toLowerCase();
634
+ const docs = (kb.documents || []).filter((d) =>
635
+ !q || `${d.title || ''} ${d.sourcePath || ''}`.toLowerCase().includes(q));
636
+ $('#kb-doc-count').textContent = `${docs.length} doc${docs.length === 1 ? '' : 's'}`;
637
+ if (!docs.length) {
638
+ list.innerHTML = kb.documents?.length
639
+ ? `<div class="empty">No document matches that filter.</div>`
640
+ : `<div class="empty">No documents ingested yet. Store a whole file, glob, or URL with <code>sigil ingest ./DESIGN.md</code> — the full text is kept and searchable facts are extracted from it.</div>`;
641
+ return;
642
+ }
643
+ list.innerHTML = docs.map((d) => {
644
+ const sel = d.uid === kb.selectedDocUid ? ' selected' : '';
645
+ return `<button class="kb-row${sel}" role="option" aria-selected="${sel ? 'true' : 'false'}" data-doc-uid="${escape(d.uid)}" type="button">
646
+ <span class="kb-row-main">
647
+ <span class="kb-row-text">${escape(d.title || d.sourcePath || d.uid)}</span>
648
+ </span>
649
+ <span class="kb-row-meta">
650
+ <span class="kb-tag">${escape(d.sourceType || 'doc')}</span>
651
+ <span class="kb-mentions" title="${d.factCount} facts · ${d.chunkCount} chunks">${escape(d.factCount)}f · ${escape(d.chunkCount)}c</span>
652
+ </span>
653
+ </button>`;
654
+ }).join('');
655
+ }
656
+
657
+ async function kbSelectDoc(uid) {
658
+ kb.selectedDocUid = uid;
659
+ $$('#kb-doc-list .kb-row').forEach((r) => {
660
+ const on = r.dataset.docUid === uid;
661
+ r.classList.toggle('selected', on);
662
+ r.setAttribute('aria-selected', on ? 'true' : 'false');
663
+ });
664
+ const pane = $('#kb-doc-detail');
665
+ pane.classList.add('open');
666
+ pane.innerHTML = `<div class="kb-detail-pad">${kbSkeleton(4)}</div>`;
667
+ try {
668
+ const doc = await rpc('getDocument', { uid });
669
+ if (doc.notFound) { pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Document not found.</div></div>`; return; }
670
+ pane.innerHTML = kbRenderDocDetail(doc);
671
+ } catch (err) {
672
+ pane.innerHTML = `<div class="kb-detail-pad"><div class="empty">Couldn’t load document: ${escape(err.message)}</div></div>`;
673
+ }
674
+ }
675
+
676
+ function kbRenderDocDetail(d) {
677
+ const meta = [
678
+ ['source', d.sourcePath || d.sourceType || '—'],
679
+ ['ingested', d.lastIngestedAt ? formatTime(d.lastIngestedAt) : '—'],
680
+ ['derived', `${d.factCount ?? 0} facts · ${d.chunkCount ?? 0} chunks`],
681
+ ['uid', d.uid],
682
+ ];
683
+ const pods = (d.pods || []).length
684
+ ? `<div class="kb-block"><div class="trace-block-h">Pods</div><div class="kb-chip-wrap">${d.pods.map((p) =>
685
+ `<span class="kb-tag">${escape(p.name || p.uid)}</span>`).join('')}</div></div>`
686
+ : '';
687
+ const body = d.content || '';
688
+ return `<div class="kb-detail-pad">
689
+ <div class="kb-detail-head">
690
+ <div>
691
+ <div class="kb-entity-title">${icon('doc')}${escape(d.title || d.sourcePath || 'Untitled')}</div>
692
+ <div class="kb-entity-sub">${escape(d.sourceType || 'document')}${d.truncated ? ` · first ${fmtNum(body.length)} of ${fmtNum(d.totalChars)} characters` : ''}</div>
693
+ </div>
694
+ ${body ? '<button class="btn small" type="button" data-copy="kb-doc-text">Copy text</button>' : ''}
695
+ </div>
696
+ <div class="kb-block"><div class="trace-block-h">Provenance</div>
697
+ <div class="kv kb-kv">${meta.map(([k, v]) =>
698
+ `<div class="row"><div class="k">${escape(k)}</div><div class="v">${escape(v)}</div></div>`).join('')}</div></div>
699
+ ${pods}
700
+ <div class="kb-block"><div class="trace-block-h">Source text</div>
701
+ ${body ? `<pre class="kb-doc-body" id="kb-doc-text">${escape(body)}</pre>`
702
+ : '<p class="muted text-sm">This document has no stored body.</p>'}</div>
703
+ </div>`;
704
+ }
705
+
416
706
  // ── Pods ─────────────────────────────────────────────────────────────
417
707
  async function kbLoadPods() {
418
708
  const list = $('#kb-pod-list');
@@ -509,7 +799,7 @@ function kbRenderGraph(mount, center, relations) {
509
799
  }
510
800
  }
511
801
 
512
- function nodeEl(n, idx) {
802
+ function nodeEl(n, _idx) {
513
803
  const g = document.createElementNS(ns, 'g');
514
804
  g.setAttribute('class', `kb-node-g${n.focal ? ' focal' : ''}`);
515
805
  g.setAttribute('tabindex', '0');
@@ -572,7 +862,7 @@ function kbSkeleton(n) {
572
862
  return `<div class="kb-skel-wrap">${Array.from({ length: n }, () => '<div class="kb-skel"></div>').join('')}</div>`;
573
863
  }
574
864
 
575
- $('#kb-refresh')?.addEventListener('click', refreshKb);
865
+ $('#kb-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, refreshKb));
576
866
  $$('.kb-tab').forEach((t) => t.addEventListener('click', () => kbSetTab(t.dataset.kbtab)));
577
867
 
578
868
  $('#kb-fact-search')?.addEventListener('input', (e) => { kb.factSearch = e.target.value; kbRenderFacts(); });
@@ -593,6 +883,11 @@ $('#kb-fact-detail')?.addEventListener('click', (e) => {
593
883
  if (ent) { kbSetTab('entities'); kbSelectEntity(ent.dataset.entityId); }
594
884
  });
595
885
 
886
+ $('#kb-doc-search')?.addEventListener('input', (e) => { kb.docSearch = e.target.value; kbRenderDocs(); });
887
+ $('#kb-doc-list')?.addEventListener('click', (e) => {
888
+ const row = e.target.closest('.kb-row'); if (row) kbSelectDoc(row.dataset.docUid);
889
+ });
890
+
596
891
  let entitySearchTimer = null;
597
892
  $('#kb-entity-search')?.addEventListener('input', (e) => {
598
893
  kb.entitySearch = e.target.value;
@@ -614,28 +909,23 @@ $('#kb-entity-detail')?.addEventListener('click', (e) => {
614
909
  });
615
910
 
616
911
  // ════════════════════════════════════════════════════════════════════
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.
912
+ // GRAPH VIEW — whole-KB force-directed graph (Obsidian-style)
913
+ // Rendering lives in a React island (graph/GraphIsland.jsx, bundled to
914
+ // vendor/graph-island.js) built on react-force-graph-2d. This module keeps what
915
+ // is genuinely dashboard logic — fetching the snapshot, the older-daemon
916
+ // fallback, and routing a clicked node into the Knowledge Base — so React stays
917
+ // contained to one view and never leaks into the rest of the app.
918
+ // Facts + entities are nodes; fact→entity mentions and entity→entity relations
919
+ // are edges.
621
920
  // ════════════════════════════════════════════════════════════════════
622
921
  const graph = {
623
922
  loaded: false,
624
923
  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,
924
+ island: null, // imperative handle from mountGraph()
630
925
  };
631
926
 
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
927
  async function initGraphView() {
638
- if (graph.loaded) { graph.hover = null; hideTooltip(); graphFit(); return; }
928
+ if (graph.loaded) { graph.island?.refit(); return; }
639
929
  await loadGraph();
640
930
  }
641
931
 
@@ -653,13 +943,37 @@ async function loadGraph() {
653
943
  return;
654
944
  }
655
945
  overlay.style.display = 'none';
656
- buildSimulation(data);
946
+ if (!graph.island) {
947
+ graph.island = mountGraph($('#graph-canvas'));
948
+ graph.island.onNodeClick = (n) => openGraphNode(n);
949
+ graph.island.onClusters = renderGraphLegend;
950
+ }
951
+ graph.island.setData(data);
657
952
  graph.loaded = true;
658
953
  } catch (err) {
659
954
  overlay.innerHTML = `<div class="graph-status err">Couldn’t build the graph: ${escape(err.message)}</div>`;
660
955
  }
661
956
  }
662
957
 
958
+
959
+ // The legend is an ENCODING KEY, not a region list. Colour is generated per
960
+ // region rank, so the honest thing to show is the set of hues in play plus what
961
+ // grey means — too few links to be a region at all. Which region is which comes
962
+ // from the hub label on canvas, not from memorising eleven swatches.
963
+ function renderGraphLegend(clusters) {
964
+ const el = $('#graph-legend');
965
+ if (!el) return;
966
+ const regions = clusters.filter((c) => !c.minor && !c.unconnected);
967
+ if (!regions.length) { el.innerHTML = ''; return; }
968
+ const ramp = regions.map((c) => c.color).filter(Boolean);
969
+ const quiet = clusters.reduce((n, c) => (c.minor || c.unconnected ? n + c.size : n), 0);
970
+ el.innerHTML = [
971
+ `<span class="gl-item">${ramp.map((h) => `<span class="gl-dot" style="background:${escape(h)}"></span>`).join('')}`
972
+ + `<span class="gl-k">${regions.length} regions</span></span>`,
973
+ `<span class="gl-item"><span class="gl-dot other"></span><span class="gl-k">few links</span> <span class="gl-n">${quiet}</span></span>`,
974
+ ].join('');
975
+ }
976
+
663
977
  // Primary: single graphSnapshot RPC. Fallback (older daemons without it):
664
978
  // compose from listFacts + per-fact getFactContext + searchEntity.
665
979
  async function fetchGraphData() {
@@ -728,289 +1042,11 @@ async function mapLimit(items, limit, fn) {
728
1042
  return out;
729
1043
  }
730
1044
 
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; }
1045
+ // Toolbar — the island owns rendering, hover and sizing; these just drive it.
1046
+ $('#graph-zoom-in')?.addEventListener('click', () => graph.island?.zoomBy(1.25));
1047
+ $('#graph-zoom-out')?.addEventListener('click', () => graph.island?.zoomBy(1 / 1.25));
1048
+ $('#graph-zoom-fit')?.addEventListener('click', () => graph.island?.fit());
1049
+ $('#graph-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, () => { graph.loaded = false; return loadGraph(); }));
1014
1050
 
1015
1051
  function openGraphNode(n) {
1016
1052
  setRoute('kb');
@@ -1030,13 +1066,6 @@ function kbSelectFactById(factId) {
1030
1066
  }).catch(() => {});
1031
1067
  }
1032
1068
 
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
- });
1039
-
1040
1069
  async function refreshMethods() {
1041
1070
  try {
1042
1071
  const res = await fetch('/api/v1/methods', { credentials: 'same-origin' });
@@ -1055,12 +1084,16 @@ async function refreshEnv() {
1055
1084
  const dbDesc = db.mode === 'url' ? `connection URL (${db.urlHost || '—'})`
1056
1085
  : db.mode === 'docker' ? `Docker container (localhost:${db.port})`
1057
1086
  : db.mode === 'local' ? `local Postgres (${db.host}:${db.port})`
1087
+ : db.mode === 'embedded' ? 'built-in (embedded)'
1058
1088
  : 'not configured';
1059
1089
  $('#cfg-db').textContent = `${dbDesc}${c.setup?.steps?.database === 'done' ? ' · ready' : ''}`;
1060
1090
  $('#cfg-llm').textContent = c.llm?.provider ? `${c.llm.provider}${c.llm.model ? ` · ${c.llm.model}` : ''}` : 'not configured';
1061
1091
  $('#cfg-emb').textContent = c.embedding?.provider
1062
1092
  ? `${c.embedding.provider} · ${c.embedding.model} · ${c.embedding.dim}d`
1063
1093
  : 'not configured';
1094
+ $('#cfg-jev').textContent = c.jev?.hasKey
1095
+ ? `${c.jev.model || 'jev-1.13.0'} · ${c.jev.enabled ? 'enabled' : 'configured — enable under Jev enhancements'}`
1096
+ : 'not configured';
1064
1097
  const tbody = $('#env-table tbody');
1065
1098
  if (tbody) {
1066
1099
  const rows = [
@@ -1072,6 +1105,9 @@ async function refreshEnv() {
1072
1105
  ['Embedding model', c.embedding?.model || '—'],
1073
1106
  ['Embedding dim', String(c.embedding?.dim || '—')],
1074
1107
  ['Embedding key', c.embedding?.hasKey ? 'configured' : '—'],
1108
+ ['Jev model', c.jev?.model || '—'],
1109
+ ['Jev key', c.jev?.hasKey ? 'configured' : '—'],
1110
+ ['Jev enhancements', c.jev?.enabled ? 'enabled' : 'disabled'],
1075
1111
  ['Name', c.identity?.name || '—'],
1076
1112
  ];
1077
1113
  tbody.innerHTML = rows.map(([k, v]) => `<tr><td class="mono">${escape(k)}</td><td>${escape(v)}</td></tr>`).join('');
@@ -1086,40 +1122,70 @@ async function refreshEnv() {
1086
1122
  // Same flow as the onboarding CONNECTORS step, surfaced post-onboarding so
1087
1123
  // users who skipped the step (or completed setup before this card existed)
1088
1124
  // can still wire up Claude Code / Cursor / Codex / Kiro / Hermes.
1089
- async function refreshSettingsClients() {
1090
- const host = $('#settings-connectors');
1091
- if (!host) return;
1092
- try {
1093
- const { connectors } = await rpc('listConnectors');
1094
- host.innerHTML = '';
1095
- if (!connectors.length) {
1096
- host.innerHTML = '<div class="muted">no agents registered</div>';
1097
- return;
1125
+ // ════════════════════════════════════════════════════════════════════
1126
+ // AGENTS — connect coding tools to this memory + per-agent activity
1127
+ // ════════════════════════════════════════════════════════════════════
1128
+ async function refreshAgents() {
1129
+ const host = $('#agents-connectors');
1130
+ if (host) {
1131
+ try {
1132
+ const { connectors } = await rpc('listConnectors');
1133
+ host.innerHTML = '';
1134
+ if (!connectors.length) host.innerHTML = '<div class="muted">no coding tools detected on this machine</div>';
1135
+ else connectors.forEach((c) => host.appendChild(connectorCard(c, onAgentAction)));
1136
+ } catch (err) {
1137
+ host.innerHTML = `<div class="muted">could not load agents: ${escape(err.message)}</div>`;
1098
1138
  }
1099
- connectors.forEach((c) => host.appendChild(connectorCard(c, onSettingsClientAction)));
1100
- } catch (err) {
1101
- host.innerHTML = `<div class="muted">could not load agents: ${escape(err.message)}</div>`;
1102
1139
  }
1140
+ loadAgentActivity();
1103
1141
  }
1104
1142
 
1105
- async function onSettingsClientAction(id, action) {
1106
- const host = $('#settings-connectors');
1143
+ async function onAgentAction(id, action) {
1144
+ const host = $('#agents-connectors');
1107
1145
  const card = host?.querySelector(`[data-id="${id}"]`);
1108
1146
  if (action === 'disconnect') {
1109
1147
  try {
1110
1148
  await rpc('disconnectConnector', { id });
1111
1149
  toast({ variant: 'success', message: `${id} disconnected` });
1112
1150
  } catch (err) { toast({ variant: 'error', message: err.message, hint: err.hint, code: err.code }); }
1113
- return refreshSettingsClients();
1151
+ return refreshAgents();
1114
1152
  }
1115
- if (card) card.replaceWith(connectorCard({ id, label: id, hint: '', uiState: 'connecting' }, onSettingsClientAction));
1153
+ if (card) card.replaceWith(connectorCard({ id, label: id, hint: '', uiState: 'connecting' }, onAgentAction));
1116
1154
  try {
1117
1155
  await rpc('connectConnector', { id });
1118
1156
  toast({ variant: 'success', message: `${id} connected` });
1119
1157
  } catch (err) {
1120
1158
  toast({ variant: 'error', message: err.message || `could not connect ${id}`, hint: err.hint, code: err.code });
1121
1159
  }
1122
- return refreshSettingsClients();
1160
+ return refreshAgents();
1161
+ }
1162
+
1163
+ // Per-agent reads/writes from recent traces (newest-first), attributed by the
1164
+ // trace's `agent` field — no backend metric needed. Same approach as Home.
1165
+ async function loadAgentActivity() {
1166
+ const tbody = $('#agents-activity tbody');
1167
+ if (!tbody) return;
1168
+ let traces;
1169
+ try { ({ traces } = await rpc('trace.list', { limit: 200 })); }
1170
+ catch (err) { tbody.innerHTML = `<tr><td colspan="4" class="empty">could not load activity: ${escape(err.message)}</td></tr>`; return; }
1171
+
1172
+ const byAgent = new Map();
1173
+ for (const t of traces) {
1174
+ if (!t.agent) continue;
1175
+ if (!byAgent.has(t.agent)) byAgent.set(t.agent, { searches: 0, writes: 0, last: t.ts }); // first seen = latest
1176
+ const rec = byAgent.get(t.agent);
1177
+ if (t.kind === 'search') rec.searches++;
1178
+ else if (t.kind === 'ingest') rec.writes++;
1179
+ }
1180
+ const rows = [...byAgent.entries()].sort((a, b) => (b[1].searches + b[1].writes) - (a[1].searches + a[1].writes));
1181
+ tbody.innerHTML = rows.length
1182
+ ? rows.map(([agent, r]) => `<tr>
1183
+ <td><span class="badge ${agentBadge(agent)}">${escape(agent)}</span></td>
1184
+ <td class="num">${r.searches}</td>
1185
+ <td class="num">${r.writes}</td>
1186
+ <td class="num">${escape(clock(r.last))}</td>
1187
+ </tr>`).join('')
1188
+ : '<tr><td colspan="4" class="empty">no agent activity yet</td></tr>';
1123
1189
  }
1124
1190
 
1125
1191
  // ── Settings: live provider switcher (LLM + embedding) ───────────────
@@ -1168,8 +1234,8 @@ function selectSwitchProvider(id) {
1168
1234
  if (!p) return;
1169
1235
  const fields = cfgSwitchFields(p);
1170
1236
  $('#cfg-switch-fields').innerHTML = fields.length
1171
- ? fields.map((f) => `<label class="field"><span class="label">${escape(f.label)}</span>
1172
- <input type="${escape(f.type)}" data-cfg-field="${escape(f.name)}" placeholder="${escape(f.placeholder || '')}" autocomplete="off"></label>`).join('')
1237
+ ? fields.map((f) => `<label class="field"><span class="label">${escape(f.label)}${f.optional ? ' <span class="muted text-xs">(optional)</span>' : ''}</span>
1238
+ ${fieldControl(f, 'data-cfg-field')}</label>`).join('')
1173
1239
  : '<p class="muted text-sm">No additional configuration needed.</p>';
1174
1240
  $('#cfg-switch-conflict').innerHTML = '';
1175
1241
  }
@@ -1206,42 +1272,72 @@ $('#cfg-switch-apply')?.addEventListener('click', async () => {
1206
1272
  }
1207
1273
  });
1208
1274
 
1275
+ // Jev has a dedicated credential flow rather than the generic setting setter:
1276
+ // saving is local-only, so no search data is sent until the user separately
1277
+ // enables the schema-driven feature switch. The key is never returned.
1278
+ $('#cfg-jev-save')?.addEventListener('click', async (e) => {
1279
+ const key = $('#cfg-jev-key')?.value?.trim();
1280
+ const model = $('#cfg-jev-model')?.value?.trim() || 'jev-1.13.0';
1281
+ const out = $('#cfg-jev-result');
1282
+ if (!key) {
1283
+ out.style.display = 'block'; out.className = 'result err'; out.textContent = 'Enter a Jev API key to save it locally.';
1284
+ return;
1285
+ }
1286
+ const btn = e.currentTarget;
1287
+ btn.disabled = true;
1288
+ out.style.display = 'block'; out.className = 'result'; out.textContent = 'Saving Jev key locally…';
1289
+ try {
1290
+ const result = await rpc('jev.configure', { apiKey: key, model });
1291
+ $('#cfg-jev-key').value = '';
1292
+ out.classList.add('ok');
1293
+ out.textContent = result.warning
1294
+ ? `⚠ ${result.warning} Enable it under Memory pipeline › Jev enhancements.`
1295
+ : `✓ Jev key verified and saved · ${result.model}. Enable it under Memory pipeline › Jev enhancements.`;
1296
+ await Promise.all([refreshEnv(), settingsPanel.refresh()]);
1297
+ } catch (err) {
1298
+ out.classList.add('err');
1299
+ out.textContent = `✗ ${err.message}${err.hint ? `\n → ${err.hint}` : ''}`;
1300
+ } finally {
1301
+ btn.disabled = false;
1302
+ }
1303
+ });
1304
+
1209
1305
  // ── Settings: danger zone — factory reset ────────────────────────────
1210
- $('#cfg-reset')?.addEventListener('click', () => {
1211
- const host = $('#reset-confirm');
1212
- if (!host) return;
1306
+ $('#cfg-reset')?.addEventListener('click', async (e) => {
1213
1307
  const wipeMemory = $('#reset-wipe-memory')?.checked !== false;
1214
- host.innerHTML = `
1215
- <div class="result err" style="margin:0;">
1216
- <strong>Reset Sigil?</strong>
1217
- <div class="muted" style="margin:6px 0;">Disconnects every agent${wipeMemory ? ', wipes all stored memory,' : ''} and clears your config. You'll go back to setup. (The database itself is kept — use <code>sigil reset</code> in a terminal for a full DB teardown.)</div>
1218
- <div class="flex-row" style="margin-top:8px;">
1219
- <button type="button" class="btn danger" data-reset-go>Yes, reset</button>
1220
- <button type="button" class="btn" data-reset-cancel>Cancel</button>
1221
- </div>
1222
- </div>`;
1223
- host.querySelector('[data-reset-cancel]').addEventListener('click', () => { host.innerHTML = ''; });
1224
- host.querySelector('[data-reset-go]').addEventListener('click', async (e) => {
1225
- e.target.disabled = true; e.target.textContent = 'Resetting…';
1226
- try {
1227
- const r = await rpc('setup.factoryReset', { wipeMemory });
1228
- toast({ variant: 'success', message: `Reset complete — disconnected ${r.disconnected?.length || 0} agent(s)${wipeMemory ? `, wiped ${r.tablesWiped || 0} tables` : ''}.` });
1229
- setTimeout(() => window.location.reload(), 800);
1230
- } catch (err) {
1231
- host.innerHTML = `<div class="result err" style="margin:0;">✗ ${escape(err.message)}</div>`;
1232
- }
1308
+ const ok = await confirmDialog({
1309
+ title: 'Reset Sigil?',
1310
+ message: `Disconnects every agent${wipeMemory ? ', wipes all stored memory,' : ''} and clears your config. You'll go back to setup. The database itself is kept — run \`sigil reset\` in a terminal for a full teardown.`,
1311
+ confirmLabel: 'Yes, reset',
1312
+ danger: true,
1233
1313
  });
1314
+ if (!ok) return;
1315
+ const btn = e.currentTarget;
1316
+ btn.disabled = true;
1317
+ try {
1318
+ const r = await rpc('setup.factoryReset', { wipeMemory });
1319
+ toast({ variant: 'success', message: `Reset complete — disconnected ${r.disconnected?.length || 0} agent(s)${wipeMemory ? `, wiped ${r.tablesWiped || 0} tables` : ''}.` });
1320
+ setTimeout(() => window.location.reload(), 800);
1321
+ } catch (err) {
1322
+ toast({ variant: 'error', message: `Reset failed: ${err.message}` });
1323
+ btn.disabled = false;
1324
+ }
1234
1325
  });
1235
1326
 
1236
1327
  async function restartAndClose(out) {
1237
1328
  out.textContent += '\nApplying — restarting daemon…';
1238
1329
  try { await rpc('restartDaemon', {}); } catch { /* expected: connection drops on exit */ }
1239
- setTimeout(() => { $('#cfg-switch').style.display = 'none'; refreshEnv(); refreshHealth(); }, 1500);
1330
+ const back = await waitForDaemon();
1331
+ out.textContent += back ? '\n✓ daemon restarted' : '\n⚠ daemon is slow to come back — check `sigil daemon status`';
1332
+ $('#cfg-switch').style.display = 'none';
1333
+ refreshEnv();
1334
+ refreshHealth();
1240
1335
  }
1241
1336
 
1242
1337
  // ── Activity / causal trace log ──────────────────────────────────────
1243
1338
  let ws = null;
1244
1339
  let traceFilter = '';
1340
+ let traceAgentFilter = '';
1245
1341
  const seenTraceUids = new Set();
1246
1342
 
1247
1343
  function ensureActivityWs() {
@@ -1261,8 +1357,9 @@ function setActivityStatus(state, label) { const el = $('#activity-status'); if
1261
1357
  function onLiveEvent(evt) {
1262
1358
  if (evt.type === 'trace') {
1263
1359
  if (traceFilter && evt.kind !== traceFilter) return;
1360
+ if (traceAgentFilter && evt.agent !== traceAgentFilter) return;
1264
1361
  prependTrace(evt, true);
1265
- } else if (!traceFilter) {
1362
+ } else if (!traceFilter && !traceAgentFilter) {
1266
1363
  // operational events (rpc/pair/device) only shown in the unfiltered view
1267
1364
  prependOpEvent(evt);
1268
1365
  }
@@ -1272,7 +1369,7 @@ async function loadTraces() {
1272
1369
  const list = $('#trace-list');
1273
1370
  if (!list) return;
1274
1371
  try {
1275
- const { traces } = await rpc('trace.list', { kind: traceFilter || undefined, limit: 50 });
1372
+ const { traces } = await rpc('trace.list', { kind: traceFilter || undefined, agent: traceAgentFilter || undefined, limit: 50 });
1276
1373
  seenTraceUids.clear();
1277
1374
  list.innerHTML = '';
1278
1375
  if (!traces.length) { $('#activity-empty').style.display = 'block'; return; }
@@ -1311,12 +1408,20 @@ function traceCard(t) {
1311
1408
  li.className = 'trace-card';
1312
1409
  const dur = t.durationMs != null ? `${t.durationMs}ms` : '';
1313
1410
  const ns = t.namespace ? `<span class="trace-ns">${escape(t.namespace)}</span>` : '';
1411
+ // Attribution: who made this call. agent answers "which agent", sessionId
1412
+ // "which session" — the pair that was previously unrecorded.
1413
+ const agent = t.agent ? `<span class="badge ${agentBadge(t.agent)}" title="originating agent">${escape(t.agent)}</span>` : '';
1414
+ const sess = t.sessionId
1415
+ ? `<span class="trace-sess" title="session ${escape(t.sessionId)}">${escape(shortId(t.sessionId))}</span>`
1416
+ : '';
1314
1417
  li.innerHTML = `
1315
1418
  <button class="trace-head" type="button" aria-expanded="false">
1316
1419
  <span class="trace-caret">▸</span>
1317
1420
  <span class="trace-ts">${escape(clock(t.ts))}</span>
1318
1421
  <span class="badge ${traceBadge(t.kind)}">${escape(t.kind)}</span>
1422
+ ${agent}
1319
1423
  <span class="trace-summary">${escape(t.summary)}</span>
1424
+ ${sess}
1320
1425
  ${ns}
1321
1426
  <span class="trace-dur">${escape(dur)}</span>
1322
1427
  </button>
@@ -1335,9 +1440,43 @@ function traceCard(t) {
1335
1440
  // ── Detail renderers ─────────────────────────────────────────────────
1336
1441
  function renderTraceDetail(t) {
1337
1442
  const d = t.detail || {};
1338
- if (t.kind === 'search') return renderSearchTrace(d);
1339
- if (t.kind === 'ingest') return renderIngestTrace(d);
1340
- return `<pre class="trace-json">${escape(JSON.stringify(d, null, 2))}</pre>`;
1443
+ const source = renderSourceBlock(t, d);
1444
+ if (t.kind === 'search') return source + renderSearchTrace(d);
1445
+ if (t.kind === 'ingest') return source + renderIngestTrace(d);
1446
+ if (t.kind === 'engine') return source + renderEngineTrace(d);
1447
+ return source + `<pre class="trace-json">${escape(JSON.stringify(d, null, 2))}</pre>`;
1448
+ }
1449
+
1450
+ // Who made this call — the attribution block. Surfaced on every trace so an
1451
+ // unexplained search/expansion can be traced to a specific agent + session.
1452
+ function renderSourceBlock(t, d) {
1453
+ const rows = [
1454
+ ['agent', t.agent],
1455
+ ['session', t.sessionId],
1456
+ ['transport', t.transport],
1457
+ ['device', t.deviceId],
1458
+ ['cwd', d.cwd],
1459
+ ].filter(([, v]) => v != null && v !== '');
1460
+ if (!rows.length) return '';
1461
+ return traceBlock('Source', rows.map(([k, v]) => kvline(k, v)).join(' '));
1462
+ }
1463
+
1464
+ // Managed-session engine event (dispatch/result/fallback/recycle/ready).
1465
+ function renderEngineTrace(d) {
1466
+ const rows = [
1467
+ ['event', d.type],
1468
+ ['worker', d.workerId],
1469
+ ['tmux session', d.session],
1470
+ ['reqId', d.reqId],
1471
+ ['caller', d.caller],
1472
+ ['reason', d.reason],
1473
+ ['viaFallback', d.type === 'fallback' ? true : undefined],
1474
+ ['durationMs', d.durationMs],
1475
+ ['inputTokens', d.inputTokens],
1476
+ ['outputTokens', d.outputTokens],
1477
+ ['tokensUsed', d.tokensUsed],
1478
+ ].filter(([, v]) => v !== null && v !== undefined && v !== '');
1479
+ return traceBlock('Engine event', rows.map(([k, v]) => kvline(k, v)).join(' '));
1341
1480
  }
1342
1481
 
1343
1482
  const sc = (v) => (v === null || v === undefined ? '—' : String(v));
@@ -1457,9 +1596,21 @@ function clock(iso) { return (iso || '').slice(11, 19) || (iso || '').slice(0, 1
1457
1596
  function traceBadge(kind) {
1458
1597
  if (kind === 'search') return 'info';
1459
1598
  if (kind === 'ingest') return 'ok';
1599
+ if (kind === 'engine') return 'accent';
1460
1600
  if (kind === 'lifecycle') return 'warn';
1461
1601
  return 'info';
1462
1602
  }
1603
+ function agentBadge(agent) {
1604
+ if (agent === 'claude-code') return 'info';
1605
+ if (agent === 'mcp') return 'ok';
1606
+ if (agent === 'codex') return 'warn';
1607
+ if (agent === 'cursor') return 'accent';
1608
+ return ''; // cli + unknown → neutral
1609
+ }
1610
+ function shortId(id) {
1611
+ const s = String(id);
1612
+ return s.length > 10 ? s.slice(0, 8) + '…' : s;
1613
+ }
1463
1614
  function audmBadge(action) {
1464
1615
  const a = String(action || '').toUpperCase();
1465
1616
  if (a === 'ADD') return 'ok';
@@ -1493,13 +1644,167 @@ $('#trace-filters')?.addEventListener('click', (e) => {
1493
1644
  $$('#trace-filters .chip').forEach((c) => c.classList.toggle('active', c === chip));
1494
1645
  loadTraces();
1495
1646
  });
1496
- $('#trace-refresh')?.addEventListener('click', loadTraces);
1647
+ $('#trace-agent-filters')?.addEventListener('click', (e) => {
1648
+ const chip = e.target.closest('[data-agent-filter]');
1649
+ if (!chip) return;
1650
+ traceAgentFilter = chip.dataset.agentFilter || '';
1651
+ $$('#trace-agent-filters .chip').forEach((c) => c.classList.toggle('active', c === chip));
1652
+ loadTraces();
1653
+ });
1654
+ $('#trace-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, loadTraces));
1497
1655
  $('#trace-clear')?.addEventListener('click', async () => {
1498
- if (!confirm('Clear the entire trace log? This deletes persisted history.')) return;
1656
+ const ok = await confirmDialog({
1657
+ title: 'Clear the trace log?',
1658
+ message: 'This deletes the persisted history for every agent. It cannot be undone.',
1659
+ confirmLabel: 'Clear log',
1660
+ danger: true,
1661
+ });
1662
+ if (!ok) return;
1499
1663
  try { await rpc('trace.clear'); } catch {}
1500
1664
  loadTraces();
1501
1665
  });
1502
1666
 
1667
+ // ── Engine (managed-session warm tmux workers) ──────────────────────
1668
+ let engineTimer = null;
1669
+ function startEnginePolling() {
1670
+ loadEngine();
1671
+ if (engineTimer) return;
1672
+ engineTimer = setInterval(() => { if (location.hash === '#engine') loadEngine(); }, 5000);
1673
+ }
1674
+ function stopEnginePolling() { if (engineTimer) { clearInterval(engineTimer); engineTimer = null; } }
1675
+
1676
+ const STATE_PILL = { ready: 'ok', busy: 'info', booting: 'warn', unhealthy: 'err' };
1677
+
1678
+ async function loadEngine() {
1679
+ const setStatus = (state, label) => { const el = $('#engine-status'); if (el) { el.className = `conn-status ${state}`; el.textContent = label; } };
1680
+ let s;
1681
+ try { s = await rpc('engine.status'); }
1682
+ catch (err) { setStatus('err', 'error'); $('#engine-workers').innerHTML = `<div class="empty">could not load engine status: ${escape(err.message)}</div>`; return; }
1683
+
1684
+ // `enabled` is intent (the config flag) and `running` is reality (a live
1685
+ // pool). They diverge legitimately — a pool keeps serving until it is torn
1686
+ // down, and tmux sessions outlive a daemon restart — but the page used to
1687
+ // render mode from `running` alone while the toggle rendered from `enabled`.
1688
+ // Switch warm workers off with a worker still up and you got "Managed" next
1689
+ // to a button offering to turn them on: two truths, no explanation. Report
1690
+ // the pair.
1691
+ const running = !!s.running;
1692
+ const enabled = !!s.enabled;
1693
+
1694
+ // "Starting" has to be able to END. The pool is built once, at daemon boot,
1695
+ // so enabling the flag on an already-running daemon leaves enabled=true with
1696
+ // no pool and nothing that will ever change that — the page sat on "Starting"
1697
+ // indefinitely while the real answer was "this daemon predates the change".
1698
+ // Uptime tells the two apart: a worker takes ~13s to hand shake (measured
1699
+ // 11-17s), and the pool boots serially, so budget per worker.
1700
+ let bootBudgetMs = 45000;
1701
+ let uptimeMs = null;
1702
+ if (enabled && !running) {
1703
+ try { uptimeMs = (await rpc('ping')).uptimeMs; } catch { /* leave unknown */ }
1704
+ bootBudgetMs = 20000 + Math.max(1, Number(s.poolSize) || 1) * 25000;
1705
+ }
1706
+ const staleDaemon = enabled && !running && uptimeMs != null && uptimeMs > bootBudgetMs;
1707
+
1708
+ const mode = enabled
1709
+ ? (running ? { label: 'Managed', sub: 'warm tmux workers', pill: 'ok', tag: 'managed' }
1710
+ : staleDaemon ? { label: 'Restart needed', sub: 'enabled after this daemon started', pill: 'warn', tag: 'restart needed' }
1711
+ : { label: 'Starting', sub: 'enabled — pool booting', pill: 'warn', tag: 'starting' })
1712
+ : (running ? { label: 'Draining', sub: 'switched off — workers still alive', pill: 'warn', tag: 'draining' }
1713
+ : { label: 'One-shot', sub: 'claude -p per call', pill: '', tag: 'one-shot' });
1714
+ setStatus(mode.pill, mode.tag);
1715
+
1716
+ $('#eng-mode').textContent = mode.label;
1717
+ $('#eng-mode-sub').textContent = mode.sub;
1718
+ $('#eng-pool').textContent = sc(s.poolSize);
1719
+ $('#eng-budget').textContent = s.tokenBudget != null ? `${s.tokenBudget.toLocaleString()} tok budget` : '—';
1720
+ const queued = Object.values(s.queued || {}).reduce((a, b) => a + b, 0);
1721
+ $('#eng-queued').textContent = sc(queued);
1722
+ $('#eng-pending').textContent = sc(s.pending);
1723
+
1724
+ const host = $('#engine-workers');
1725
+ if (!running) {
1726
+ // Explain WHY the engine isn't warm so the empty state is actionable.
1727
+ let why;
1728
+ if (!s.enabled) why = 'Managed-session engine is off. Every LLM call uses the proven one-shot <code>claude -p</code> path.';
1729
+ else if (!s.tmuxAvailable) why = '<code>SIGIL_MANAGED_SESSION=true</code> is set, but <code>tmux</code> was not found on PATH — staying on one-shot.';
1730
+ else if (s.provider && s.provider !== 'claude-cli') why = `LLM provider is <code>${escape(s.provider)}</code> (not <code>claude-cli</code>) — API providers don't need warm sessions.`;
1731
+ else if (staleDaemon) why = 'Warm workers are enabled, but the pool is built once at daemon boot and this daemon started before the setting changed — so nothing is booting and nothing will.';
1732
+ else why = `Engine enabled — the pool is booting. A worker takes about 13s to hand shake${(Number(s.poolSize) || 1) > 1 ? ', and they boot one after another' : ''}.`;
1733
+ const how = engineBlocker(s)
1734
+ || (staleDaemon ? 'Restart to bring it up: `sigil daemon restart` (or toggle it off and on again here).'
1735
+ : 'Use the button above — Sigil restarts the daemon and brings the pool up.');
1736
+ host.innerHTML = `<div class="empty">${why}<br><span class="muted">${escape(how)}</span></div>`;
1737
+ } else if (!s.workers || !s.workers.length) {
1738
+ host.innerHTML = `<div class="empty">No live workers — the pool is spinning up or has yielded to one-shot after repeated boot failures. Check <code>~/.sigil/sigild.log</code>.</div>`;
1739
+ } else {
1740
+ // Switched off while a pool is still serving: say so above the table, or
1741
+ // the live workers below read as though the toggle did nothing.
1742
+ const drainNote = !enabled
1743
+ ? '<div class="empty" style="padding: var(--s-3) var(--s-4); text-align: left;">Warm workers are switched <strong>off</strong>, but this pool is still alive and serving — a <code>tmux</code> session outlives the daemon that started it. It stops when the session ends; <code>tmux kill-session -t sigil-&lt;worker&gt;</code> ends it now.</div>'
1744
+ : '';
1745
+ const rows = s.workers.map((w) => {
1746
+ const session = `${escape(s.sessionPrefix || 'sigil-')}${escape(w.id)}`;
1747
+ const pct = s.tokenBudget ? Math.min(100, Math.round((w.tokensUsed / s.tokenBudget) * 100)) : null;
1748
+ return `<tr>
1749
+ <td class="mono">${escape(w.id)}</td>
1750
+ <td class="mono">${session}</td>
1751
+ <td><span class="pill ${STATE_PILL[w.state] || ''}">${escape(w.state)}</span></td>
1752
+ <td class="num">${w.tokensUsed.toLocaleString()}${pct != null ? ` <span class="muted">(${pct}%)</span>` : ''}</td>
1753
+ </tr>`;
1754
+ }).join('');
1755
+ host.innerHTML = drainNote + `<div class="trace-table-wrap"><table class="trace-table">
1756
+ <thead><tr><th>worker</th><th>tmux session</th><th>state</th><th>tokens used</th></tr></thead>
1757
+ <tbody>${rows}</tbody></table></div>`;
1758
+ }
1759
+
1760
+ $('#engine-hint').innerHTML = running
1761
+ ? 'Inspect a worker pane directly: <code>tmux attach -t sigil-&lt;worker&gt;</code> (detach with <code>Ctrl-b d</code>) or <code>tmux capture-pane -t sigil-&lt;worker&gt; -p</code>. Per-task events stream into <a href="#activity" data-route="activity">Activity → Engine</a>.'
1762
+ : '';
1763
+
1764
+ renderEngineToggle(s);
1765
+ }
1766
+
1767
+ /**
1768
+ * The on/off control. A disabled button that says WHY it is disabled beats an
1769
+ * enabled one that writes a flag the host can't honour — that is exactly how
1770
+ * this feature spent its first life "enabled" and dead.
1771
+ */
1772
+ function renderEngineToggle(s) {
1773
+ const btn = $('#engine-toggle');
1774
+ if (!btn) return;
1775
+ const blocked = !s.enabled && engineBlocker(s);
1776
+ btn.textContent = s.enabled ? 'Turn off warm workers' : 'Turn on warm workers';
1777
+ btn.classList.toggle('primary', !s.enabled && !blocked);
1778
+ btn.disabled = !!blocked;
1779
+ btn.title = blocked || '';
1780
+ btn.dataset.next = s.enabled ? 'off' : 'on';
1781
+ }
1782
+
1783
+ $('#engine-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, loadEngine));
1784
+
1785
+ $('#engine-toggle')?.addEventListener('click', async (e) => {
1786
+ const btn = e.currentTarget;
1787
+ const enabled = btn.dataset.next === 'on';
1788
+ const out = $('#engine-toggle-result');
1789
+ out.style.display = 'block'; out.className = 'result'; out.textContent = 'saving…';
1790
+ btn.disabled = true;
1791
+ try {
1792
+ const res = await rpc('engine.setEnabled', { enabled });
1793
+ if (!res.ok) { out.classList.add('err'); out.textContent = `✗ ${res.error}`; btn.disabled = false; return; }
1794
+ out.classList.add('ok');
1795
+ // The pool is built once at daemon boot, so the flag alone changes nothing.
1796
+ out.textContent = `✓ warm workers ${enabled ? 'on' : 'off'}\nRestarting daemon…`;
1797
+ try { await rpc('restartDaemon', {}); } catch { /* expected: the socket drops on exit */ }
1798
+ // A cold `claude` needs ~10s to hand shake, so the first poll would still
1799
+ // read "no workers" and look like a failure.
1800
+ setTimeout(loadEngine, 3000);
1801
+ setTimeout(loadEngine, 15000);
1802
+ } catch (err) {
1803
+ out.classList.add('err'); out.textContent = `✗ ${err.message}`;
1804
+ btn.disabled = false;
1805
+ }
1806
+ });
1807
+
1503
1808
  // ── Setup tab (legacy DB form) ──────────────────────────────────────
1504
1809
  $('#db-mode')?.addEventListener('change', (e) => {
1505
1810
  $('#db-url-pane').style.display = e.target.value === 'url' ? '' : 'none';
@@ -1624,7 +1929,7 @@ async function refreshDevices() {
1624
1929
  }
1625
1930
  } catch (err) { $('#dev-codes tbody').innerHTML = `<tr><td colspan="6" class="empty">${escape(err.message)}</td></tr>`; }
1626
1931
  }
1627
- $('#dev-refresh')?.addEventListener('click', refreshDevices);
1932
+ $('#dev-refresh')?.addEventListener('click', (e) => withBusy(e.currentTarget, refreshDevices));
1628
1933
 
1629
1934
  document.addEventListener('click', (e) => {
1630
1935
  const r = e.target.closest('[data-revoke]');
@@ -1711,6 +2016,114 @@ async function runLanding() {
1711
2016
  setTimeout(dismissLanding, Math.max(0, MIN_MS - (Date.now() - started)));
1712
2017
  }
1713
2018
 
2019
+ hydrateIcons();
2020
+ // The hand-written halves of Settings, handed to the rail as categories so the
2021
+ // page has ONE organisation instead of a rail wedged between stacked panels.
2022
+ const SETTINGS_EXTRAS = [
2023
+ { id: 'providers', tier: 'system', title: 'Providers',
2024
+ help: 'The database, LLM and embedding model this memory runs on. Switching one restarts the daemon.',
2025
+ node: '#settings-extra-providers' },
2026
+ { id: 'developer', tier: 'admin', title: 'Developer',
2027
+ help: 'The resolved config file and the RPC surface every client dispatches through. Read-only.',
2028
+ node: '#settings-extra-developer' },
2029
+ { id: 'danger', tier: 'admin', title: 'Danger zone',
2030
+ help: 'Irreversible. Read the confirmation before you accept it.',
2031
+ node: '#settings-extra-danger' },
2032
+ ];
2033
+
2034
+ const settingsPanel = initSettings({
2035
+ rpc,
2036
+ toast,
2037
+ mount: '#settings-host',
2038
+ extras: SETTINGS_EXTRAS,
2039
+ // Jev is a memory-pipeline setting, so its credential form belongs alongside
2040
+ // the switch and tuning knobs rather than among LLM/embedding providers.
2041
+ sectionExtras: { jev: '#settings-section-jev' },
2042
+ });
2043
+
2044
+ /**
2045
+ * Ingest one or more documents from the machine.
2046
+ *
2047
+ * A FILE PICKER, not a path box, and the browser reads the bytes. The daemon's
2048
+ * cwd is `/`, so a path typed here would resolve against the wrong root — the
2049
+ * exact failure that made `ingest` reject files from any project but the first
2050
+ * one. Sending `content` + the real `sourcePath` sidesteps resolution entirely,
2051
+ * and sourcePath still keys the upsert so re-ingesting a file updates it rather
2052
+ * than duplicating it.
2053
+ *
2054
+ * No cwd is sent: the browser has no project context, so documents added here
2055
+ * land unpodded — which scoped search treats as visible everywhere, the right
2056
+ * default for something filed by hand.
2057
+ */
2058
+ const INGEST_MAX_BYTES = 2 * 1024 * 1024;
2059
+
2060
+ async function ingestDocumentsFromDisk(files) {
2061
+ const picked = [...(files || [])];
2062
+ if (!picked.length) return;
2063
+
2064
+ let ok = 0;
2065
+ let skipped = 0;
2066
+ const failed = [];
2067
+
2068
+ for (const file of picked) {
2069
+ if (file.size > INGEST_MAX_BYTES) {
2070
+ failed.push(`${file.name} (${(file.size / 1024 / 1024).toFixed(1)} MB — over the ${INGEST_MAX_BYTES / 1024 / 1024} MB limit)`);
2071
+ continue;
2072
+ }
2073
+ try {
2074
+ const content = await file.text();
2075
+ if (!content.trim()) { failed.push(`${file.name} (empty)`); continue; }
2076
+ const r = await rpc('ingestDoc', {
2077
+ content,
2078
+ title: file.name,
2079
+ // webkitRelativePath is set when a folder was picked; it keeps the
2080
+ // upsert key stable and distinguishes same-named files in subfolders.
2081
+ sourcePath: file.webkitRelativePath || file.name,
2082
+ sourceType: 'file',
2083
+ });
2084
+ if (r?.skipped) skipped += 1; else ok += 1;
2085
+ } catch (err) {
2086
+ failed.push(`${file.name} (${err.message})`);
2087
+ }
2088
+ }
2089
+
2090
+ const parts = [];
2091
+ if (ok) parts.push(`${ok} ingested`);
2092
+ if (skipped) parts.push(`${skipped} unchanged`);
2093
+ if (failed.length) parts.push(`${failed.length} failed`);
2094
+ toast({
2095
+ variant: failed.length && !ok ? 'error' : ok ? 'success' : 'info',
2096
+ message: parts.join(' · ') || 'Nothing to ingest.',
2097
+ hint: failed.length ? failed.slice(0, 3).join('; ') : undefined,
2098
+ });
2099
+
2100
+ if (ok) { refreshHealth(); if (location.hash === '#kb') refreshKb(); }
2101
+ }
2102
+
2103
+ /** Open the OS file picker, then ingest whatever comes back. */
2104
+ function pickDocumentsToIngest() {
2105
+ const el = $('#kb-ingest-file');
2106
+ if (!el) return;
2107
+ el.value = ''; // re-picking the same file must still fire `change`
2108
+ el.click();
2109
+ }
2110
+
2111
+ $('#kb-ingest-file')?.addEventListener('change', (e) => {
2112
+ ingestDocumentsFromDisk(e.target.files);
2113
+ });
2114
+
2115
+ // ⌘K — navigate, act, and (the point) run a live memory search from anywhere.
2116
+ const cmdk = initCmdk({
2117
+ rpc, setRoute, toast,
2118
+ openFact: (uid) => { setRoute('kb'); kbSetTab('facts'); kbSelectFact(uid); },
2119
+ // A fact saved from the bar should be visible immediately, not next poll.
2120
+ onRemembered: () => { refreshHealth(); if (location.hash === '#kb') refreshKb(); },
2121
+ onIngest: pickDocumentsToIngest,
2122
+ });
2123
+ $('#home-remember')?.addEventListener('click', () => cmdk.compose?.());
2124
+ $('#kb-remember')?.addEventListener('click', () => cmdk.compose?.());
2125
+ $('#kb-ingest')?.addEventListener('click', pickDocumentsToIngest);
2126
+
1714
2127
  const initial = (window.location.hash || '#health').slice(1);
1715
2128
  setRoute(validRoutes.includes(initial) ? initial : 'health');
1716
2129
  runLanding();