ltcai 3.5.0 → 3.6.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.
@@ -1,7 +1,10 @@
1
1
  /* ============================================================================
2
- * View: Knowledge Graph — entity/relation explorer.
3
- * Renders the graph as an SVG mesh against /api/graph with a live inspector.
4
- * Missing graph data renders an empty unavailable state.
2
+ * View: Knowledge Graph — the user's digital brain (v3.6.0 Knowledge Graph First).
3
+ * Tabs: Explore (entity/relation mesh) · Status (graph + ingestion health) ·
4
+ * Sources (where every node came from) · Capture (web/URL into the graph) ·
5
+ * Backup (local export / import / backup). Everything you ingest converges here;
6
+ * models read this graph; local-first keeps it yours. Missing data renders an
7
+ * honest unavailable state — never fabricated counters.
5
8
  * ========================================================================== */
6
9
 
7
10
  import { escapeHtml } from "../core/dom.js";
@@ -12,6 +15,8 @@ const TYPE_COLOR = {
12
15
  Method: "var(--lt3-pillar-hybrid)",
13
16
  Model: "var(--accent-3)",
14
17
  File: "var(--faint)",
18
+ Source: "var(--lt3-pillar-hybrid)",
19
+ Document: "var(--accent)",
15
20
  Decision: "var(--accent-3)",
16
21
  Task: "var(--accent-2)",
17
22
  Person: "var(--accent-pink)",
@@ -19,27 +24,84 @@ const TYPE_COLOR = {
19
24
  };
20
25
  const colorFor = (t) => TYPE_COLOR[t] || TYPE_COLOR.default;
21
26
 
27
+ const TABS = [
28
+ { key: "explore", label: "Explore", icon: "chart-dots-3" },
29
+ { key: "status", label: "Status", icon: "activity-heartbeat" },
30
+ { key: "sources", label: "Sources", icon: "database" },
31
+ { key: "capture", label: "Capture", icon: "world-www" },
32
+ { key: "portability", label: "Backup", icon: "archive" },
33
+ ];
34
+
22
35
  export async function render(ctx) {
23
- const { h, icon, api, store, c } = ctx;
36
+ const { h, icon, api, c } = ctx;
37
+ let active = "explore";
24
38
 
25
- const state = { selected: null, query: "", data: { nodes: [], edges: [] }, source: "pending" };
39
+ const tabBar = h("div.lt3-row-2");
40
+ const panelHost = h("div.lt3-stack-4");
26
41
 
27
- const canvasHost = h("div", c.loading({ lines: 0, block: true }));
28
- const inspectorHost = h("div", c.loading({ lines: 4 }));
29
- const statHost = h("div.lt3-statrow", c.loading({ lines: 1 }));
30
- const srcSlot = h("span", c.sourceBadge("pending"));
42
+ function renderTabs() {
43
+ tabBar.replaceChildren(...TABS.map((t) =>
44
+ h("button.lt3-btn" + (t.key === active ? ".lt3-btn--primary" : ".lt3-btn--ghost"),
45
+ { on: { click: () => switchTab(t.key) } }, icon(t.icon), t.label)));
46
+ }
47
+
48
+ function switchTab(key) {
49
+ if (active === key) return;
50
+ active = key;
51
+ renderTabs();
52
+ renderActive();
53
+ }
54
+
55
+ let exploreNode = null;
56
+ function renderActive() {
57
+ if (active === "explore") {
58
+ if (!exploreNode) exploreNode = buildExplore(ctx);
59
+ panelHost.replaceChildren(exploreNode);
60
+ } else if (active === "status") {
61
+ renderStatus(ctx, panelHost);
62
+ } else if (active === "sources") {
63
+ renderSources(ctx, panelHost);
64
+ } else if (active === "capture") {
65
+ panelHost.replaceChildren(buildCapture(ctx));
66
+ } else if (active === "portability") {
67
+ renderPortability(ctx, panelHost);
68
+ }
69
+ }
31
70
 
32
71
  const root = h("div.lt3-stack-6",
33
72
  c.viewHeader({
34
- eyebrow: "Retrieval · structure",
73
+ eyebrow: "Your digital brain",
35
74
  title: "Knowledge Graph",
36
- sub: "Entities and the relations the workspace extracted between them. Click a node to trace its neighborhood.",
75
+ sub: "Everything you ingest converges here files, folders, web pages, browser tabs. Models read this graph; local-first keeps it yours.",
37
76
  actions: [
38
- srcSlot,
39
- h("button.lt3-btn.lt3-btn--ghost", { on: { click: () => load() } }, icon("refresh"), "Rebuild view"),
77
+ h("button.lt3-btn.lt3-btn--ghost", { on: { click: () => ctx.navigate("files") } }, icon("upload"), "Add sources"),
40
78
  h("button.lt3-btn.lt3-btn--primary", { on: { click: () => ctx.navigate("hybrid-search") } }, icon("arrows-join"), "Search graph"),
41
79
  ],
42
80
  }),
81
+ tabBar,
82
+ panelHost,
83
+ );
84
+
85
+ renderTabs();
86
+ renderActive();
87
+ return root;
88
+ }
89
+
90
+ /* ── Explore tab (entity/relation mesh) ─────────────────────────────────── */
91
+ function buildExplore(ctx) {
92
+ const { h, icon, api, c } = ctx;
93
+ const state = { selected: null, query: "", data: { nodes: [], edges: [] }, source: "pending" };
94
+
95
+ const canvasHost = h("div", c.loading({ lines: 0, block: true }));
96
+ const inspectorHost = h("div", c.loading({ lines: 4 }));
97
+ const statHost = h("div.lt3-statrow", c.loading({ lines: 1 }));
98
+ const srcSlot = h("span", c.sourceBadge("pending"));
99
+
100
+ const root = h("div.lt3-stack-3",
101
+ h("div.lt3-row-2",
102
+ srcSlot,
103
+ h("button.lt3-btn.lt3-btn--ghost.lt3-btn--sm", { on: { click: () => load() } }, icon("refresh"), "Rebuild view"),
104
+ ),
43
105
  statHost,
44
106
  h("div.lt3-split",
45
107
  h("div.lt3-stack-3",
@@ -69,7 +131,7 @@ export async function render(ctx) {
69
131
  renderInspector();
70
132
  }
71
133
 
72
- function renderStats(stats, graphData) {
134
+ function renderStats(stats) {
73
135
  const nodes = state.data.nodes.length;
74
136
  const edges = state.data.edges.length;
75
137
  const types = stats && stats.nodes ? Object.keys(stats.nodes).length : new Set(state.data.nodes.map((n) => n.type)).size;
@@ -185,7 +247,221 @@ export async function render(ctx) {
185
247
  return root;
186
248
  }
187
249
 
250
+ /* ── Status tab (graph + ingestion health) ──────────────────────────────── */
251
+ async function renderStatus(ctx, host) {
252
+ const { h, icon, api, c } = ctx;
253
+ host.replaceChildren(c.loading({ lines: 3 }));
254
+ const [port, gs, idx] = await Promise.all([api.kgPortability(), api.graphStats(), api.indexStatus()]);
255
+ const p = port.data || {};
256
+ const prov = p.provenance || {};
257
+ const nodes = sumCounts((gs.data && gs.data.nodes) || {});
258
+ const edges = sumCounts((gs.data && gs.data.edges) || {});
259
+ const pipelines = (idx.data && idx.data.pipelines) || {};
260
+
261
+ host.replaceChildren(
262
+ h("div.lt3-row-2", c.sourceBadge(port.source), h("span.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } },
263
+ p.graph_schema_version != null ? `Schema v${p.graph_schema_version} · embed dim ${p.embed_dim ?? "—"}` : "Knowledge Graph status")),
264
+ h("div.lt3-statrow",
265
+ c.stat({ label: "Entities", value: c.fmtNum(nodes), icon: "circles" }),
266
+ c.stat({ label: "Relations", value: c.fmtNum(edges), icon: "vector-triangle" }),
267
+ c.stat({ label: "Ingested items", value: c.fmtNum(prov.total || 0), icon: "package-import" }),
268
+ c.stat({ label: "Embedded (RAG-ready)", value: c.fmtNum(prov.embedded || 0), icon: "vector" }),
269
+ ),
270
+ c.card(
271
+ h("div.lt3-stack-3",
272
+ h("div.lt3-eyebrow", "Pipelines"),
273
+ pipelineRow(ctx, "Knowledge graph", pipelines.knowledge_graph),
274
+ pipelineRow(ctx, "Vector index", pipelines.vector_index),
275
+ pipelineRow(ctx, "Hybrid retrieval", pipelines.hybrid),
276
+ ),
277
+ ),
278
+ prov.last_ingested_at
279
+ ? h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, `Last ingestion: ${fmtWhen(prov.last_ingested_at)} · ${prov.duplicates || 0} duplicate(s) linked, not re-stored.`)
280
+ : c.emptyState({ icon: "package-import", title: "Nothing ingested yet", body: "Add files or capture a page to populate the graph." }),
281
+ );
282
+ }
283
+
284
+ function pipelineRow(ctx, label, pipe) {
285
+ const { h, c } = ctx;
286
+ const stateStr = (pipe && pipe.state) || "unavailable";
287
+ const detail = pipe && (pipe.entities != null ? `${pipe.entities} entities` : pipe.vectors != null ? `${pipe.vectors} vectors` : pipe.strategy || "");
288
+ return h("div.lt3-row-2", { style: { "justify-content": "space-between" } },
289
+ h("div", label, detail ? h("span.lt3-muted", { style: { "margin-left": "var(--lt3-space-2)", "font-size": "var(--lt3-text-sm)" } }, detail) : null),
290
+ c.statePill(stateStr),
291
+ );
292
+ }
293
+
294
+ /* ── Sources tab (provenance: where every node came from) ────────────────── */
295
+ async function renderSources(ctx, host) {
296
+ const { h, icon, api, c } = ctx;
297
+ host.replaceChildren(c.loading({ lines: 3 }));
298
+ const [port, recent] = await Promise.all([api.kgPortability(), api.kgProvenance(40)]);
299
+ const bySource = (port.data && port.data.provenance && port.data.provenance.by_source_type) || {};
300
+ const items = (recent.data && recent.data.items) || [];
301
+
302
+ const sourceCards = Object.keys(bySource).length
303
+ ? h("div.lt3-statrow", Object.entries(bySource).map(([k, v]) =>
304
+ c.stat({ label: prettySource(k), value: c.fmtNum(v), icon: iconForSource(k) })))
305
+ : c.emptyState({ icon: "database", title: "No sources yet", body: "Connect a folder, upload a file, or capture a page." });
306
+
307
+ const recentList = items.length
308
+ ? h("div.lt3-stack-2", items.map((it) =>
309
+ h("div.lt3-entity",
310
+ h("div.lt3-entity__type", { style: { background: "var(--surface-3)", color: colorFor("Source") } }, icon(iconForSource(it.source_type))),
311
+ h("div.lt3-entity__body",
312
+ h("div.lt3-entity__name", it.title || it.source_uri || it.node_id),
313
+ h("div.lt3-entity__meta", `${prettySource(it.source_type)} · ${fmtWhen(it.created_at)}${it.embedded ? " · embedded" : ""}${it.duplicate ? " · duplicate" : ""}`),
314
+ ),
315
+ )))
316
+ : c.emptyState({ icon: "history", title: "No recent ingestions", body: "Ingested items will appear here with full provenance." });
317
+
318
+ host.replaceChildren(
319
+ h("div.lt3-row-2", c.sourceBadge(port.source), h("span.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, "Every node records where it came from (provenance).")),
320
+ sourceCards,
321
+ c.card(h("div.lt3-stack-3", h("div.lt3-eyebrow", "Recent ingestions"), recentList)),
322
+ );
323
+ }
324
+
325
+ /* ── Capture tab (web/URL into the graph) ───────────────────────────────── */
326
+ function buildCapture(ctx) {
327
+ const { h, icon, api, c } = ctx;
328
+ const input = h("input", { type: "url", placeholder: "https://example.com/article", "aria-label": "URL to capture",
329
+ style: { flex: "1" } });
330
+ const result = h("div");
331
+
332
+ async function run() {
333
+ const url = (input.value || "").trim();
334
+ if (!url) { result.replaceChildren(c.banner({ tone: "warn", text: "Enter a URL first." })); return; }
335
+ result.replaceChildren(c.loading({ lines: 1 }));
336
+ const res = await api.browserReadUrl(url);
337
+ const d = res.data || {};
338
+ if (res.ok && d.status === "ok") {
339
+ result.replaceChildren(c.banner({ tone: "ok", text: `Added to your Knowledge Graph${d.duplicate ? " (already present — linked)" : ""}. ${d.chunk_count || 0} chunk(s) indexed.` }));
340
+ ctx.toast && ctx.toast("Page added to Knowledge Graph");
341
+ } else if (d.status === "empty") {
342
+ result.replaceChildren(c.banner({ tone: "warn", text: "No readable text was found on that page." }));
343
+ } else {
344
+ const detail = d.detail || (res.status === 422 ? "The page is blocked or login-required." : "Could not read that URL.");
345
+ result.replaceChildren(c.banner({ tone: "err", text: detail }));
346
+ }
347
+ }
348
+
349
+ return h("div.lt3-stack-4",
350
+ c.card(h("div.lt3-stack-3",
351
+ h("div.lt3-eyebrow", "Capture a web page"),
352
+ h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, "The local runtime fetches the page, extracts readable text, and indexes it into your graph as a web source. Nothing is sent to a cloud service."),
353
+ h("div.lt3-row-2",
354
+ input,
355
+ h("button.lt3-btn.lt3-btn--primary", { on: { click: run } }, icon("world-download"), "Read into graph"),
356
+ ),
357
+ result,
358
+ )),
359
+ c.card(h("div.lt3-stack-2",
360
+ h("div.lt3-eyebrow", "Browser extension"),
361
+ h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, "Install the local Manifest V3 extension (browser-extension/) to send the current tab to your Knowledge Graph with one click. It posts only to 127.0.0.1 — never to a cloud server."),
362
+ )),
363
+ );
364
+ }
365
+
366
+ /* ── Portability tab (export / import / backup) ─────────────────────────── */
367
+ async function renderPortability(ctx, host) {
368
+ const { h, icon, api, c } = ctx;
369
+ host.replaceChildren(c.loading({ lines: 2 }));
370
+ const port = await api.kgPortability();
371
+ const status = h("div");
372
+
373
+ function note(tone, text) { status.replaceChildren(c.banner({ tone, text })); }
374
+
375
+ async function doExport() {
376
+ note("info", "Exporting…");
377
+ const res = await api.graphExport();
378
+ if (!res.ok || !res.data || res.data.raw) { note("err", "Export is unavailable."); return; }
379
+ try {
380
+ const blob = new Blob([JSON.stringify(res.data, null, 2)], { type: "application/json" });
381
+ const url = URL.createObjectURL(blob);
382
+ const a = document.createElement("a");
383
+ a.href = url; a.download = "lattice-kg-export.json"; a.click();
384
+ URL.revokeObjectURL(url);
385
+ note("ok", `Exported ${(res.data.counts && res.data.counts.nodes) || 0} nodes. Download started.`);
386
+ } catch (e) { note("err", "Could not build the download."); }
387
+ }
388
+
389
+ async function doBackup() {
390
+ note("info", "Backing up…");
391
+ const res = await api.graphBackup();
392
+ if (res.ok && res.data && res.data.path) {
393
+ note("ok", `Backup written locally: ${res.data.path}`);
394
+ } else {
395
+ note("err", (res.data && (res.data.detail || res.data.error)) || "Backup requires admin and a running runtime.");
396
+ }
397
+ }
398
+
399
+ const importArea = h("textarea", { rows: 5, placeholder: "Paste a Knowledge Graph export (JSON) to validate, then import…",
400
+ "aria-label": "Import artifact", style: { width: "100%", "font-family": "var(--lt3-font-mono)", "font-size": "var(--lt3-text-sm)" } });
401
+
402
+ async function doImport(dryRun) {
403
+ let artifact;
404
+ try { artifact = JSON.parse(importArea.value || ""); }
405
+ catch { note("err", "That is not valid JSON."); return; }
406
+ note("info", dryRun ? "Validating…" : "Importing…");
407
+ const res = await api.graphImport(artifact, "merge", dryRun);
408
+ if (res.ok && res.data && !res.data.detail) {
409
+ const d = res.data;
410
+ note("ok", dryRun
411
+ ? `Valid — would import ${d.nodes || 0} nodes, ${d.edges || 0} edges.`
412
+ : `Imported ${d.nodes || 0} nodes, ${d.edges || 0} edges.`);
413
+ } else {
414
+ note("err", (res.data && (res.data.detail || res.data.error)) || "Import requires admin.");
415
+ }
416
+ }
417
+
418
+ const p = port.data || {};
419
+ host.replaceChildren(
420
+ h("div.lt3-row-2", c.sourceBadge(port.source), h("span.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, "The Knowledge Graph is your durable asset — portable with no cloud.")),
421
+ c.card(h("div.lt3-stack-3",
422
+ h("div.lt3-eyebrow", "Export & backup"),
423
+ h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)" } }, "Export a portable JSON of nodes/edges/provenance, or write a full local binary backup (DB + blobs)."),
424
+ h("div.lt3-row-2",
425
+ h("button.lt3-btn.lt3-btn--primary", { on: { click: doExport } }, icon("download"), "Export JSON"),
426
+ h("button.lt3-btn.lt3-btn--ghost", { on: { click: doBackup } }, icon("archive"), "Backup (admin)"),
427
+ ),
428
+ )),
429
+ c.card(h("div.lt3-stack-3",
430
+ h("div.lt3-eyebrow", "Import"),
431
+ importArea,
432
+ h("div.lt3-row-2",
433
+ h("button.lt3-btn.lt3-btn--ghost", { on: { click: () => doImport(true) } }, icon("checks"), "Validate (dry-run)"),
434
+ h("button.lt3-btn.lt3-btn--primary", { on: { click: () => doImport(false) } }, icon("file-import"), "Import (merge, admin)"),
435
+ ),
436
+ )),
437
+ status,
438
+ );
439
+ }
440
+
188
441
  /* ── helpers ─────────────────────────────────────────────────────────────── */
442
+ function sumCounts(obj) {
443
+ return Object.values(obj || {}).reduce((a, b) => a + (Number(b) || 0), 0);
444
+ }
445
+
446
+ function prettySource(k) {
447
+ return ({ web_url: "Web URL", browser_tab: "Browser tab", file: "Files", local_file: "Local files",
448
+ note: "Notes", text: "Text", markdown: "Markdown", code: "Code", upload: "Uploads" })[k] || k;
449
+ }
450
+
451
+ function iconForSource(k) {
452
+ return ({ web_url: "world", browser_tab: "browser", file: "file", local_file: "folder",
453
+ note: "note", text: "text-caption", markdown: "markdown", code: "code", upload: "upload" })[k] || "database";
454
+ }
455
+
456
+ function fmtWhen(iso) {
457
+ if (!iso) return "—";
458
+ try {
459
+ const d = new Date(iso);
460
+ if (isNaN(d.getTime())) return String(iso);
461
+ return d.toLocaleString();
462
+ } catch { return String(iso); }
463
+ }
464
+
189
465
  function normalize(data) {
190
466
  const nodes = (data.nodes || []).map((n) => ({
191
467
  id: n.id,
@@ -208,7 +484,6 @@ function layout(nodes) {
208
484
  if (hasCoords) {
209
485
  return nodes.map((n) => ({ ...n, px: Math.round(60 + n.x * (W - 120)), py: Math.round(50 + n.y * (H - 100)) }));
210
486
  }
211
- // Sunflower (Vogel) spread — even spacing, highest-weight entity centered.
212
487
  const order = nodes.map((n, i) => ({ n, i })).sort((a, b) => (b.n.weight || 0) - (a.n.weight || 0));
213
488
  const maxR = Math.min(W, H) * 0.42;
214
489
  const placed = {};
@@ -226,11 +501,12 @@ function layout(nodes) {
226
501
  function truncate(s, n) { s = String(s || ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; }
227
502
 
228
503
  function iconForType(t) {
229
- return ({ Topic: "bulb", Concept: "atom", Method: "function", Model: "cpu", File: "file", Decision: "gavel", Task: "checkbox", Person: "user" })[t] || "point";
504
+ return ({ Topic: "bulb", Concept: "atom", Method: "function", Model: "cpu", File: "file", Source: "world",
505
+ Document: "file-text", Decision: "gavel", Task: "checkbox", Person: "user" })[t] || "point";
230
506
  }
231
507
 
232
508
  function buildLegend({ h }) {
233
- const types = ["Topic", "Concept", "Method", "Model", "File"];
509
+ const types = ["Source", "Document", "Concept", "Person", "Decision"];
234
510
  return h("div.lt3-graph-legend",
235
511
  types.map((t) => h("span", h("i", { style: { background: colorFor(t) } }), t)),
236
512
  );
@@ -1,237 +0,0 @@
1
- /* ============================================================================
2
- * View: Knowledge Graph — entity/relation explorer.
3
- * Renders the graph as an SVG mesh against /api/graph with a live inspector.
4
- * Missing graph data renders an empty unavailable state.
5
- * ========================================================================== */
6
-
7
- import { escapeHtml } from "../core/dom.a2773eb0.js";
8
-
9
- const TYPE_COLOR = {
10
- Topic: "var(--lt3-pillar-graph)",
11
- Concept: "var(--lt3-pillar-vector)",
12
- Method: "var(--lt3-pillar-hybrid)",
13
- Model: "var(--accent-3)",
14
- File: "var(--faint)",
15
- Decision: "var(--accent-3)",
16
- Task: "var(--accent-2)",
17
- Person: "var(--accent-pink)",
18
- default: "var(--accent)",
19
- };
20
- const colorFor = (t) => TYPE_COLOR[t] || TYPE_COLOR.default;
21
-
22
- export async function render(ctx) {
23
- const { h, icon, api, store, c } = ctx;
24
-
25
- const state = { selected: null, query: "", data: { nodes: [], edges: [] }, source: "pending" };
26
-
27
- const canvasHost = h("div", c.loading({ lines: 0, block: true }));
28
- const inspectorHost = h("div", c.loading({ lines: 4 }));
29
- const statHost = h("div.lt3-statrow", c.loading({ lines: 1 }));
30
- const srcSlot = h("span", c.sourceBadge("pending"));
31
-
32
- const root = h("div.lt3-stack-6",
33
- c.viewHeader({
34
- eyebrow: "Retrieval · structure",
35
- title: "Knowledge Graph",
36
- sub: "Entities and the relations the workspace extracted between them. Click a node to trace its neighborhood.",
37
- actions: [
38
- srcSlot,
39
- h("button.lt3-btn.lt3-btn--ghost", { on: { click: () => load() } }, icon("refresh"), "Rebuild view"),
40
- h("button.lt3-btn.lt3-btn--primary", { on: { click: () => ctx.navigate("hybrid-search") } }, icon("arrows-join"), "Search graph"),
41
- ],
42
- }),
43
- statHost,
44
- h("div.lt3-split",
45
- h("div.lt3-stack-3",
46
- c.card(canvasHost, { attrs: { style: "padding:0;overflow:hidden" } }),
47
- buildLegend(ctx),
48
- ),
49
- h("aside.lt3-panel",
50
- h("div.lt3-panel__head", h("div", h("div.lt3-eyebrow", "Inspector"), h("h3.lt3-panel__title", "Entities"))),
51
- h("div.lt3-search", { style: { "margin-bottom": "var(--lt3-space-4)" } },
52
- icon("search"),
53
- h("input", { type: "text", placeholder: "Filter entities…", "aria-label": "Filter entities",
54
- on: { input: (e) => { state.query = e.target.value.toLowerCase(); renderInspector(); } } }),
55
- ),
56
- inspectorHost,
57
- ),
58
- ),
59
- );
60
-
61
- async function load() {
62
- canvasHost.replaceChildren(c.loading({ lines: 0, block: true }));
63
- const [g, stats] = await Promise.all([api.graph(), api.graphStats()]);
64
- state.data = normalize(g.data);
65
- state.source = g.source;
66
- srcSlot.replaceChildren(c.sourceBadge(g.source));
67
- renderStats(stats.data, g.data);
68
- renderCanvas();
69
- renderInspector();
70
- }
71
-
72
- function renderStats(stats, graphData) {
73
- const nodes = state.data.nodes.length;
74
- const edges = state.data.edges.length;
75
- const types = stats && stats.nodes ? Object.keys(stats.nodes).length : new Set(state.data.nodes.map((n) => n.type)).size;
76
- const density = nodes > 1 ? (edges / (nodes * (nodes - 1) / 2)) : 0;
77
- statHost.replaceChildren(
78
- c.stat({ label: "Entities", value: c.fmtNum(nodes), icon: "circles" }),
79
- c.stat({ label: "Relations", value: c.fmtNum(edges), icon: "vector-triangle" }),
80
- c.stat({ label: "Entity types", value: types, icon: "category" }),
81
- c.stat({ label: "Density", value: density.toFixed(2), icon: "chart-dots" }),
82
- );
83
- }
84
-
85
- function renderCanvas() {
86
- const { nodes, edges } = state.data;
87
- if (!nodes.length) { canvasHost.replaceChildren(c.emptyState({ icon: "chart-dots-3", title: "No entities yet", body: "Index a source to populate the graph." })); return; }
88
- const laidOut = layout(nodes);
89
- const pos = Object.fromEntries(laidOut.map((n) => [n.id, n]));
90
- const W = 1000, H = 600;
91
- const edgeSvg = edges.map((e) => {
92
- const a = pos[e.from], b = pos[e.to];
93
- if (!a || !b) return "";
94
- return `<line class="lt3-gedge" x1="${a.px}" y1="${a.py}" x2="${b.px}" y2="${b.py}" stroke-width="${1 + (e.weight || 1) * 0.6}"></line>`;
95
- }).join("");
96
- const nodeSvg = laidOut.map((n) => {
97
- const r = 10 + (n.weight || 0.5) * 16;
98
- const sel = state.selected === n.id;
99
- return `<g class="lt3-gnode" data-id="${escapeHtml(n.id)}" opacity="${state.selected && !sel && !isNeighbor(n.id) ? 0.35 : 1}">
100
- <circle cx="${n.px}" cy="${n.py}" r="${sel ? r + 3 : r}" fill="${colorFor(n.type)}" stroke-width="${sel ? 3 : 2}"></circle>
101
- <text x="${n.px}" y="${n.py + r + 13}" text-anchor="middle">${escapeHtml(truncate(n.label, 18))}</text>
102
- </g>`;
103
- }).join("");
104
- canvasHost.replaceChildren(
105
- h("div.lt3-graph-canvas", {
106
- html: `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Knowledge graph">${edgeSvg}${nodeSvg}</svg>`,
107
- on: { click: onCanvasClick },
108
- }),
109
- );
110
- }
111
-
112
- function onCanvasClick(e) {
113
- const g = e.target.closest(".lt3-gnode");
114
- if (!g) return;
115
- state.selected = g.dataset.id === state.selected ? null : g.dataset.id;
116
- renderCanvas();
117
- renderInspector();
118
- }
119
-
120
- function isNeighbor(id) {
121
- if (!state.selected) return false;
122
- return state.data.edges.some((e) =>
123
- (e.from === state.selected && e.to === id) || (e.to === state.selected && e.from === id));
124
- }
125
-
126
- function renderInspector() {
127
- if (state.selected) { inspectorHost.replaceChildren(detailView()); return; }
128
- const q = state.query;
129
- const list = state.data.nodes
130
- .filter((n) => !q || (n.label || "").toLowerCase().includes(q) || (n.type || "").toLowerCase().includes(q))
131
- .sort((a, b) => (b.weight || 0) - (a.weight || 0));
132
- inspectorHost.replaceChildren(
133
- list.length
134
- ? h("div.lt3-stack-2", list.slice(0, 60).map((n) => entityRow(n)))
135
- : c.emptyState({ icon: "search-off", title: "No matches", body: "Try a different entity name." }),
136
- );
137
- }
138
-
139
- function entityRow(n) {
140
- return h("button.lt3-entity", { on: { click: () => { state.selected = n.id; renderCanvas(); renderInspector(); } } },
141
- h("div.lt3-entity__type", { style: { background: `color-mix(in srgb, ${colorFor(n.type)} 18%, transparent)`, color: colorFor(n.type) } }, icon(iconForType(n.type))),
142
- h("div.lt3-entity__body",
143
- h("div.lt3-entity__name", n.label),
144
- h("div.lt3-entity__meta", `${n.type || "Entity"} · weight ${(n.weight || 0).toFixed(2)}`),
145
- ),
146
- );
147
- }
148
-
149
- function detailView() {
150
- const n = state.data.nodes.find((x) => x.id === state.selected);
151
- if (!n) { state.selected = null; return c.emptyState({ title: "Not found" }); }
152
- const rels = state.data.edges
153
- .filter((e) => e.from === n.id || e.to === n.id)
154
- .map((e) => {
155
- const otherId = e.from === n.id ? e.to : e.from;
156
- const other = state.data.nodes.find((x) => x.id === otherId);
157
- return { type: e.type, dir: e.from === n.id ? "→" : "←", other };
158
- })
159
- .filter((r) => r.other);
160
- return h("div.lt3-stack-4",
161
- h("button.lt3-btn.lt3-btn--subtle.lt3-btn--sm", { on: { click: () => { state.selected = null; renderCanvas(); renderInspector(); } } }, icon("arrow-left"), "All entities"),
162
- h("div.lt3-card.lt3-card--flat",
163
- h("div.lt3-row-2", { style: { "margin-bottom": "var(--lt3-space-2)" } },
164
- h("span.lt3-pill", { style: { color: colorFor(n.type) } }, n.type || "Entity"),
165
- ),
166
- h("div", { style: { "font-size": "var(--lt3-text-lg)", "font-weight": 700 } }, n.label),
167
- n.summary && h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)", "margin-top": "var(--lt3-space-2)" } }, n.summary),
168
- ),
169
- h("div",
170
- h("div.lt3-eyebrow", { style: { "margin-bottom": "var(--lt3-space-2)" } }, `Relations (${rels.length})`),
171
- rels.length
172
- ? h("div.lt3-stack-2", rels.map((r) => h("button.lt3-entity", { on: { click: () => { state.selected = r.other.id; renderCanvas(); renderInspector(); } } },
173
- h("div.lt3-entity__type", { style: { background: "var(--surface-3)" } }, h("span.lt3-mono", { style: { "font-size": "var(--lt3-text-sm)" } }, r.dir)),
174
- h("div.lt3-entity__body",
175
- h("div.lt3-entity__name", r.other.label),
176
- h("div.lt3-entity__meta", r.type),
177
- ),
178
- )))
179
- : c.emptyState({ icon: "unlink", title: "No relations", body: "This entity is currently isolated." }),
180
- ),
181
- );
182
- }
183
-
184
- load();
185
- return root;
186
- }
187
-
188
- /* ── helpers ─────────────────────────────────────────────────────────────── */
189
- function normalize(data) {
190
- const nodes = (data.nodes || []).map((n) => ({
191
- id: n.id,
192
- label: n.label || n.title || n.id,
193
- type: n.type || "Entity",
194
- weight: n.weight ?? n.importance_norm ?? (n.metadata && n.metadata.graph_metrics && n.metadata.graph_metrics.importance_norm) ?? 0.5,
195
- summary: n.summary || "",
196
- x: n.x, y: n.y,
197
- }));
198
- const ids = new Set(nodes.map((n) => n.id));
199
- const edges = (data.edges || []).filter((e) => ids.has(e.from) && ids.has(e.to))
200
- .map((e) => ({ from: e.from, to: e.to, type: e.type || "related", weight: e.weight || 1 }));
201
- return { nodes, edges };
202
- }
203
-
204
- function layout(nodes) {
205
- const W = 1000, H = 600, cx = W / 2, cy = H / 2;
206
- const golden = Math.PI * (3 - Math.sqrt(5));
207
- const hasCoords = nodes.length && nodes.every((n) => typeof n.x === "number" && typeof n.y === "number");
208
- if (hasCoords) {
209
- return nodes.map((n) => ({ ...n, px: Math.round(60 + n.x * (W - 120)), py: Math.round(50 + n.y * (H - 100)) }));
210
- }
211
- // Sunflower (Vogel) spread — even spacing, highest-weight entity centered.
212
- const order = nodes.map((n, i) => ({ n, i })).sort((a, b) => (b.n.weight || 0) - (a.n.weight || 0));
213
- const maxR = Math.min(W, H) * 0.42;
214
- const placed = {};
215
- order.forEach((o, rank) => {
216
- const radius = rank === 0 ? 0 : maxR * Math.sqrt(rank / Math.max(1, nodes.length - 1));
217
- const angle = rank * golden;
218
- placed[o.i] = {
219
- px: Math.round(cx + Math.cos(angle) * radius),
220
- py: Math.round(cy + Math.sin(angle) * radius * 0.66),
221
- };
222
- });
223
- return nodes.map((n, i) => ({ ...n, ...placed[i] }));
224
- }
225
-
226
- function truncate(s, n) { s = String(s || ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; }
227
-
228
- function iconForType(t) {
229
- return ({ Topic: "bulb", Concept: "atom", Method: "function", Model: "cpu", File: "file", Decision: "gavel", Task: "checkbox", Person: "user" })[t] || "point";
230
- }
231
-
232
- function buildLegend({ h }) {
233
- const types = ["Topic", "Concept", "Method", "Model", "File"];
234
- return h("div.lt3-graph-legend",
235
- types.map((t) => h("span", h("i", { style: { background: colorFor(t) } }), t)),
236
- );
237
- }