ltcai 3.4.1 → 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.
Files changed (60) hide show
  1. package/README.md +206 -247
  2. package/docs/CARRYOVER_AUDIT_v3.6.0.md +61 -0
  3. package/docs/CHANGELOG.md +32 -0
  4. package/docs/HANDOVER_v3.6.0.md +46 -0
  5. package/docs/RUNTIME_HOOK_COVERAGE_v3.5.0.md +56 -0
  6. package/docs/RUNTIME_HOOK_COVERAGE_v3.6.0.md +49 -0
  7. package/docs/architecture.md +13 -12
  8. package/docs/kg-schema.md +55 -0
  9. package/docs/privacy.md +18 -2
  10. package/docs/security-model.md +17 -0
  11. package/kg_schema.py +46 -0
  12. package/knowledge_graph.py +520 -1
  13. package/latticeai/__init__.py +1 -1
  14. package/latticeai/api/auth.py +37 -9
  15. package/latticeai/api/browser.py +217 -0
  16. package/latticeai/api/chat.py +4 -1
  17. package/latticeai/api/computer_use.py +21 -8
  18. package/latticeai/api/portability.py +93 -0
  19. package/latticeai/api/tools.py +29 -26
  20. package/latticeai/core/config.py +3 -0
  21. package/latticeai/core/marketplace.py +1 -1
  22. package/latticeai/core/multi_agent.py +1 -1
  23. package/latticeai/core/oidc.py +205 -0
  24. package/latticeai/core/security.py +59 -5
  25. package/latticeai/core/workspace_os.py +1 -1
  26. package/latticeai/server_app.py +39 -0
  27. package/latticeai/services/ingestion.py +271 -0
  28. package/latticeai/services/kg_portability.py +177 -0
  29. package/package.json +5 -4
  30. package/requirements.txt +1 -0
  31. package/scripts/build_vsix.mjs +72 -0
  32. package/scripts/check_python.py +87 -0
  33. package/static/css/reference/account.css +1 -1
  34. package/static/css/reference/admin.css +1 -1
  35. package/static/css/reference/base.css +8 -5
  36. package/static/css/reference/chat.css +8 -8
  37. package/static/css/reference/graph.css +2 -2
  38. package/static/css/responsive.css +2 -2
  39. package/static/v3/asset-manifest.json +9 -9
  40. package/static/v3/css/{lattice.shell.6ceea7c8.css → lattice.shell.8fcc9d33.css} +2 -1
  41. package/static/v3/css/lattice.shell.css +2 -1
  42. package/static/v3/js/{app.d086489d.js → app.c541f955.js} +1 -1
  43. package/static/v3/js/core/{api.12b568ad.js → api.33d6320e.js} +38 -0
  44. package/static/v3/js/core/api.js +38 -0
  45. package/static/v3/js/core/{routes.d214b399.js → routes.2ce3815a.js} +1 -1
  46. package/static/v3/js/core/routes.js +1 -1
  47. package/static/v3/js/core/{shell.d05266f5.js → shell.8c163e0e.js} +2 -2
  48. package/static/v3/js/views/knowledge-graph.a96040a5.js +513 -0
  49. package/static/v3/js/views/knowledge-graph.js +293 -17
  50. package/static/workspace.css +1 -1
  51. package/tools/__init__.py +276 -0
  52. package/tools/commands.py +188 -0
  53. package/tools/computer.py +185 -0
  54. package/tools/documents.py +243 -0
  55. package/tools/filesystem.py +560 -0
  56. package/tools/knowledge.py +97 -0
  57. package/tools/local_files.py +69 -0
  58. package/tools/network.py +66 -0
  59. package/static/v3/js/views/knowledge-graph.a14ea7e7.js +0 -237
  60. package/tools.py +0 -1525
@@ -507,6 +507,44 @@ export const api = {
507
507
  // Hooks dispatch (real backend: POST /api/hooks/run + GET /api/hooks/runs)
508
508
  hookRun(body) { return raw("/api/hooks/run", { method: "POST", body }); },
509
509
  hookRuns(limit = 50, kind) { return withFallback(`/api/hooks/runs?limit=${encodeURIComponent(limit)}${kind ? "&kind=" + encodeURIComponent(kind) : ""}`, {}, { runs: [], total: 0 }); },
510
+
511
+ /* ── v3.6 Knowledge Graph First: ingestion provenance + portability ─────
512
+ * The graph is the durable asset; these surface its health, where every node
513
+ * came from, and local export/import/backup. All fallback-safe; never fake. */
514
+
515
+ /** GET /api/knowledge-graph/portability — schema versions + stats + provenance counts. */
516
+ async kgPortability() {
517
+ const res = await raw("/api/knowledge-graph/portability");
518
+ if (res.ok && res.data && res.data.available) {
519
+ return { ok: true, status: res.status, data: res.data, source: "live" };
520
+ }
521
+ return {
522
+ ok: false, status: res.status, source: "unavailable",
523
+ data: { available: false, graph_schema_version: null, embed_dim: null,
524
+ stats: { nodes: {}, edges: {} },
525
+ provenance: { total: 0, by_source_type: {}, embedded: 0, duplicates: 0, last_ingested_at: null } },
526
+ };
527
+ },
528
+
529
+ /** GET /api/knowledge-graph/provenance — recent ingestions (newest first). */
530
+ kgProvenance(limit = 50, sourceType) {
531
+ const qs = `?limit=${encodeURIComponent(limit)}${sourceType ? "&source_type=" + encodeURIComponent(sourceType) : ""}`;
532
+ return withFallback(`/api/knowledge-graph/provenance${qs}`, {}, { items: [], count: 0 });
533
+ },
534
+
535
+ /** POST /api/knowledge-graph/export — logical JSON export of the whole graph. */
536
+ graphExport() { return raw("/api/knowledge-graph/export", { method: "POST", body: {} }); },
537
+
538
+ /** POST /api/knowledge-graph/import — import an export artifact (merge|replace). */
539
+ graphImport(artifact, mode = "merge", dryRun = false) {
540
+ return raw("/api/knowledge-graph/import", { method: "POST", body: { artifact, mode, dry_run: dryRun } });
541
+ },
542
+
543
+ /** POST /api/knowledge-graph/backup — binary backup (sqlite + blobs) to a local zip. */
544
+ graphBackup() { return raw("/api/knowledge-graph/backup", { method: "POST", body: {} }); },
545
+
546
+ /** POST /api/browser/read-url — fetch a public URL locally into the graph. */
547
+ browserReadUrl(url) { return raw("/api/browser/read-url", { method: "POST", body: { url } }); },
510
548
  };
511
549
 
512
550
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -507,6 +507,44 @@ export const api = {
507
507
  // Hooks dispatch (real backend: POST /api/hooks/run + GET /api/hooks/runs)
508
508
  hookRun(body) { return raw("/api/hooks/run", { method: "POST", body }); },
509
509
  hookRuns(limit = 50, kind) { return withFallback(`/api/hooks/runs?limit=${encodeURIComponent(limit)}${kind ? "&kind=" + encodeURIComponent(kind) : ""}`, {}, { runs: [], total: 0 }); },
510
+
511
+ /* ── v3.6 Knowledge Graph First: ingestion provenance + portability ─────
512
+ * The graph is the durable asset; these surface its health, where every node
513
+ * came from, and local export/import/backup. All fallback-safe; never fake. */
514
+
515
+ /** GET /api/knowledge-graph/portability — schema versions + stats + provenance counts. */
516
+ async kgPortability() {
517
+ const res = await raw("/api/knowledge-graph/portability");
518
+ if (res.ok && res.data && res.data.available) {
519
+ return { ok: true, status: res.status, data: res.data, source: "live" };
520
+ }
521
+ return {
522
+ ok: false, status: res.status, source: "unavailable",
523
+ data: { available: false, graph_schema_version: null, embed_dim: null,
524
+ stats: { nodes: {}, edges: {} },
525
+ provenance: { total: 0, by_source_type: {}, embedded: 0, duplicates: 0, last_ingested_at: null } },
526
+ };
527
+ },
528
+
529
+ /** GET /api/knowledge-graph/provenance — recent ingestions (newest first). */
530
+ kgProvenance(limit = 50, sourceType) {
531
+ const qs = `?limit=${encodeURIComponent(limit)}${sourceType ? "&source_type=" + encodeURIComponent(sourceType) : ""}`;
532
+ return withFallback(`/api/knowledge-graph/provenance${qs}`, {}, { items: [], count: 0 });
533
+ },
534
+
535
+ /** POST /api/knowledge-graph/export — logical JSON export of the whole graph. */
536
+ graphExport() { return raw("/api/knowledge-graph/export", { method: "POST", body: {} }); },
537
+
538
+ /** POST /api/knowledge-graph/import — import an export artifact (merge|replace). */
539
+ graphImport(artifact, mode = "merge", dryRun = false) {
540
+ return raw("/api/knowledge-graph/import", { method: "POST", body: { artifact, mode, dry_run: dryRun } });
541
+ },
542
+
543
+ /** POST /api/knowledge-graph/backup — binary backup (sqlite + blobs) to a local zip. */
544
+ graphBackup() { return raw("/api/knowledge-graph/backup", { method: "POST", body: {} }); },
545
+
546
+ /** POST /api/browser/read-url — fetch a public URL locally into the graph. */
547
+ browserReadUrl(url) { return raw("/api/browser/read-url", { method: "POST", body: { url } }); },
510
548
  };
511
549
 
512
550
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -33,7 +33,7 @@ export const ROUTES = [
33
33
 
34
34
  // Retrieval (the product identity)
35
35
  { key: "hybrid-search", label: "Search", icon: "arrows-join", group: "retrieval", minMode: "basic", view: "hybrid-search", title: "Hybrid Search", desc: "Graph structure fused with vector similarity." },
36
- { key: "knowledge-graph", label: "Knowledge", icon: "chart-dots-3", group: "retrieval", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Entities and relations extracted from your workspace." },
36
+ { key: "knowledge-graph", label: "Knowledge", icon: "chart-dots-3", group: "retrieval", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Your digital brain every source converges here. Explore, ingest, and export." },
37
37
  { key: "memory", label: "Memory", icon: "brain", group: "retrieval", minMode: "basic", view: "memory", title: "Memory", desc: "Long-term workspace, project, agent, and conversation memory." },
38
38
 
39
39
  // Compute
@@ -33,7 +33,7 @@ export const ROUTES = [
33
33
 
34
34
  // Retrieval (the product identity)
35
35
  { key: "hybrid-search", label: "Search", icon: "arrows-join", group: "retrieval", minMode: "basic", view: "hybrid-search", title: "Hybrid Search", desc: "Graph structure fused with vector similarity." },
36
- { key: "knowledge-graph", label: "Knowledge", icon: "chart-dots-3", group: "retrieval", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Entities and relations extracted from your workspace." },
36
+ { key: "knowledge-graph", label: "Knowledge", icon: "chart-dots-3", group: "retrieval", minMode: "basic", view: "knowledge-graph", title: "Knowledge Graph", desc: "Your digital brain every source converges here. Explore, ingest, and export." },
37
37
  { key: "memory", label: "Memory", icon: "brain", group: "retrieval", minMode: "basic", view: "memory", title: "Memory", desc: "Long-term workspace, project, agent, and conversation memory." },
38
38
 
39
39
  // Compute
@@ -7,10 +7,10 @@
7
7
 
8
8
  import { h, icon, $, $$ } from "./dom.a2773eb0.js";
9
9
  import { store } from "./store.34ebd5e6.js";
10
- import { api } from "./api.12b568ad.js";
10
+ import { api } from "./api.33d6320e.js";
11
11
  import * as c from "./components.f25b3b93.js";
12
12
  import { createRouter } from "./router.584570f2.js";
13
- import { GROUPS, ROUTES, ROUTE_BY_KEY, MODE_RANK, visibleRoutes, loadView } from "./routes.d214b399.js";
13
+ import { GROUPS, ROUTES, ROUTE_BY_KEY, MODE_RANK, visibleRoutes, loadView } from "./routes.2ce3815a.js";
14
14
 
15
15
  const MODES = [
16
16
  { key: "basic", label: "Basic", icon: "circle" },
@@ -0,0 +1,513 @@
1
+ /* ============================================================================
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.
8
+ * ========================================================================== */
9
+
10
+ import { escapeHtml } from "../core/dom.a2773eb0.js";
11
+
12
+ const TYPE_COLOR = {
13
+ Topic: "var(--lt3-pillar-graph)",
14
+ Concept: "var(--lt3-pillar-vector)",
15
+ Method: "var(--lt3-pillar-hybrid)",
16
+ Model: "var(--accent-3)",
17
+ File: "var(--faint)",
18
+ Source: "var(--lt3-pillar-hybrid)",
19
+ Document: "var(--accent)",
20
+ Decision: "var(--accent-3)",
21
+ Task: "var(--accent-2)",
22
+ Person: "var(--accent-pink)",
23
+ default: "var(--accent)",
24
+ };
25
+ const colorFor = (t) => TYPE_COLOR[t] || TYPE_COLOR.default;
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
+
35
+ export async function render(ctx) {
36
+ const { h, icon, api, c } = ctx;
37
+ let active = "explore";
38
+
39
+ const tabBar = h("div.lt3-row-2");
40
+ const panelHost = h("div.lt3-stack-4");
41
+
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
+ }
70
+
71
+ const root = h("div.lt3-stack-6",
72
+ c.viewHeader({
73
+ eyebrow: "Your digital brain",
74
+ title: "Knowledge Graph",
75
+ sub: "Everything you ingest converges here — files, folders, web pages, browser tabs. Models read this graph; local-first keeps it yours.",
76
+ actions: [
77
+ h("button.lt3-btn.lt3-btn--ghost", { on: { click: () => ctx.navigate("files") } }, icon("upload"), "Add sources"),
78
+ h("button.lt3-btn.lt3-btn--primary", { on: { click: () => ctx.navigate("hybrid-search") } }, icon("arrows-join"), "Search graph"),
79
+ ],
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
+ ),
105
+ statHost,
106
+ h("div.lt3-split",
107
+ h("div.lt3-stack-3",
108
+ c.card(canvasHost, { attrs: { style: "padding:0;overflow:hidden" } }),
109
+ buildLegend(ctx),
110
+ ),
111
+ h("aside.lt3-panel",
112
+ h("div.lt3-panel__head", h("div", h("div.lt3-eyebrow", "Inspector"), h("h3.lt3-panel__title", "Entities"))),
113
+ h("div.lt3-search", { style: { "margin-bottom": "var(--lt3-space-4)" } },
114
+ icon("search"),
115
+ h("input", { type: "text", placeholder: "Filter entities…", "aria-label": "Filter entities",
116
+ on: { input: (e) => { state.query = e.target.value.toLowerCase(); renderInspector(); } } }),
117
+ ),
118
+ inspectorHost,
119
+ ),
120
+ ),
121
+ );
122
+
123
+ async function load() {
124
+ canvasHost.replaceChildren(c.loading({ lines: 0, block: true }));
125
+ const [g, stats] = await Promise.all([api.graph(), api.graphStats()]);
126
+ state.data = normalize(g.data);
127
+ state.source = g.source;
128
+ srcSlot.replaceChildren(c.sourceBadge(g.source));
129
+ renderStats(stats.data, g.data);
130
+ renderCanvas();
131
+ renderInspector();
132
+ }
133
+
134
+ function renderStats(stats) {
135
+ const nodes = state.data.nodes.length;
136
+ const edges = state.data.edges.length;
137
+ const types = stats && stats.nodes ? Object.keys(stats.nodes).length : new Set(state.data.nodes.map((n) => n.type)).size;
138
+ const density = nodes > 1 ? (edges / (nodes * (nodes - 1) / 2)) : 0;
139
+ statHost.replaceChildren(
140
+ c.stat({ label: "Entities", value: c.fmtNum(nodes), icon: "circles" }),
141
+ c.stat({ label: "Relations", value: c.fmtNum(edges), icon: "vector-triangle" }),
142
+ c.stat({ label: "Entity types", value: types, icon: "category" }),
143
+ c.stat({ label: "Density", value: density.toFixed(2), icon: "chart-dots" }),
144
+ );
145
+ }
146
+
147
+ function renderCanvas() {
148
+ const { nodes, edges } = state.data;
149
+ if (!nodes.length) { canvasHost.replaceChildren(c.emptyState({ icon: "chart-dots-3", title: "No entities yet", body: "Index a source to populate the graph." })); return; }
150
+ const laidOut = layout(nodes);
151
+ const pos = Object.fromEntries(laidOut.map((n) => [n.id, n]));
152
+ const W = 1000, H = 600;
153
+ const edgeSvg = edges.map((e) => {
154
+ const a = pos[e.from], b = pos[e.to];
155
+ if (!a || !b) return "";
156
+ 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>`;
157
+ }).join("");
158
+ const nodeSvg = laidOut.map((n) => {
159
+ const r = 10 + (n.weight || 0.5) * 16;
160
+ const sel = state.selected === n.id;
161
+ return `<g class="lt3-gnode" data-id="${escapeHtml(n.id)}" opacity="${state.selected && !sel && !isNeighbor(n.id) ? 0.35 : 1}">
162
+ <circle cx="${n.px}" cy="${n.py}" r="${sel ? r + 3 : r}" fill="${colorFor(n.type)}" stroke-width="${sel ? 3 : 2}"></circle>
163
+ <text x="${n.px}" y="${n.py + r + 13}" text-anchor="middle">${escapeHtml(truncate(n.label, 18))}</text>
164
+ </g>`;
165
+ }).join("");
166
+ canvasHost.replaceChildren(
167
+ h("div.lt3-graph-canvas", {
168
+ html: `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="xMidYMid meet" role="img" aria-label="Knowledge graph">${edgeSvg}${nodeSvg}</svg>`,
169
+ on: { click: onCanvasClick },
170
+ }),
171
+ );
172
+ }
173
+
174
+ function onCanvasClick(e) {
175
+ const g = e.target.closest(".lt3-gnode");
176
+ if (!g) return;
177
+ state.selected = g.dataset.id === state.selected ? null : g.dataset.id;
178
+ renderCanvas();
179
+ renderInspector();
180
+ }
181
+
182
+ function isNeighbor(id) {
183
+ if (!state.selected) return false;
184
+ return state.data.edges.some((e) =>
185
+ (e.from === state.selected && e.to === id) || (e.to === state.selected && e.from === id));
186
+ }
187
+
188
+ function renderInspector() {
189
+ if (state.selected) { inspectorHost.replaceChildren(detailView()); return; }
190
+ const q = state.query;
191
+ const list = state.data.nodes
192
+ .filter((n) => !q || (n.label || "").toLowerCase().includes(q) || (n.type || "").toLowerCase().includes(q))
193
+ .sort((a, b) => (b.weight || 0) - (a.weight || 0));
194
+ inspectorHost.replaceChildren(
195
+ list.length
196
+ ? h("div.lt3-stack-2", list.slice(0, 60).map((n) => entityRow(n)))
197
+ : c.emptyState({ icon: "search-off", title: "No matches", body: "Try a different entity name." }),
198
+ );
199
+ }
200
+
201
+ function entityRow(n) {
202
+ return h("button.lt3-entity", { on: { click: () => { state.selected = n.id; renderCanvas(); renderInspector(); } } },
203
+ h("div.lt3-entity__type", { style: { background: `color-mix(in srgb, ${colorFor(n.type)} 18%, transparent)`, color: colorFor(n.type) } }, icon(iconForType(n.type))),
204
+ h("div.lt3-entity__body",
205
+ h("div.lt3-entity__name", n.label),
206
+ h("div.lt3-entity__meta", `${n.type || "Entity"} · weight ${(n.weight || 0).toFixed(2)}`),
207
+ ),
208
+ );
209
+ }
210
+
211
+ function detailView() {
212
+ const n = state.data.nodes.find((x) => x.id === state.selected);
213
+ if (!n) { state.selected = null; return c.emptyState({ title: "Not found" }); }
214
+ const rels = state.data.edges
215
+ .filter((e) => e.from === n.id || e.to === n.id)
216
+ .map((e) => {
217
+ const otherId = e.from === n.id ? e.to : e.from;
218
+ const other = state.data.nodes.find((x) => x.id === otherId);
219
+ return { type: e.type, dir: e.from === n.id ? "→" : "←", other };
220
+ })
221
+ .filter((r) => r.other);
222
+ return h("div.lt3-stack-4",
223
+ h("button.lt3-btn.lt3-btn--subtle.lt3-btn--sm", { on: { click: () => { state.selected = null; renderCanvas(); renderInspector(); } } }, icon("arrow-left"), "All entities"),
224
+ h("div.lt3-card.lt3-card--flat",
225
+ h("div.lt3-row-2", { style: { "margin-bottom": "var(--lt3-space-2)" } },
226
+ h("span.lt3-pill", { style: { color: colorFor(n.type) } }, n.type || "Entity"),
227
+ ),
228
+ h("div", { style: { "font-size": "var(--lt3-text-lg)", "font-weight": 700 } }, n.label),
229
+ n.summary && h("p.lt3-muted", { style: { "font-size": "var(--lt3-text-sm)", "margin-top": "var(--lt3-space-2)" } }, n.summary),
230
+ ),
231
+ h("div",
232
+ h("div.lt3-eyebrow", { style: { "margin-bottom": "var(--lt3-space-2)" } }, `Relations (${rels.length})`),
233
+ rels.length
234
+ ? h("div.lt3-stack-2", rels.map((r) => h("button.lt3-entity", { on: { click: () => { state.selected = r.other.id; renderCanvas(); renderInspector(); } } },
235
+ h("div.lt3-entity__type", { style: { background: "var(--surface-3)" } }, h("span.lt3-mono", { style: { "font-size": "var(--lt3-text-sm)" } }, r.dir)),
236
+ h("div.lt3-entity__body",
237
+ h("div.lt3-entity__name", r.other.label),
238
+ h("div.lt3-entity__meta", r.type),
239
+ ),
240
+ )))
241
+ : c.emptyState({ icon: "unlink", title: "No relations", body: "This entity is currently isolated." }),
242
+ ),
243
+ );
244
+ }
245
+
246
+ load();
247
+ return root;
248
+ }
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
+
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
+
465
+ function normalize(data) {
466
+ const nodes = (data.nodes || []).map((n) => ({
467
+ id: n.id,
468
+ label: n.label || n.title || n.id,
469
+ type: n.type || "Entity",
470
+ weight: n.weight ?? n.importance_norm ?? (n.metadata && n.metadata.graph_metrics && n.metadata.graph_metrics.importance_norm) ?? 0.5,
471
+ summary: n.summary || "",
472
+ x: n.x, y: n.y,
473
+ }));
474
+ const ids = new Set(nodes.map((n) => n.id));
475
+ const edges = (data.edges || []).filter((e) => ids.has(e.from) && ids.has(e.to))
476
+ .map((e) => ({ from: e.from, to: e.to, type: e.type || "related", weight: e.weight || 1 }));
477
+ return { nodes, edges };
478
+ }
479
+
480
+ function layout(nodes) {
481
+ const W = 1000, H = 600, cx = W / 2, cy = H / 2;
482
+ const golden = Math.PI * (3 - Math.sqrt(5));
483
+ const hasCoords = nodes.length && nodes.every((n) => typeof n.x === "number" && typeof n.y === "number");
484
+ if (hasCoords) {
485
+ return nodes.map((n) => ({ ...n, px: Math.round(60 + n.x * (W - 120)), py: Math.round(50 + n.y * (H - 100)) }));
486
+ }
487
+ const order = nodes.map((n, i) => ({ n, i })).sort((a, b) => (b.n.weight || 0) - (a.n.weight || 0));
488
+ const maxR = Math.min(W, H) * 0.42;
489
+ const placed = {};
490
+ order.forEach((o, rank) => {
491
+ const radius = rank === 0 ? 0 : maxR * Math.sqrt(rank / Math.max(1, nodes.length - 1));
492
+ const angle = rank * golden;
493
+ placed[o.i] = {
494
+ px: Math.round(cx + Math.cos(angle) * radius),
495
+ py: Math.round(cy + Math.sin(angle) * radius * 0.66),
496
+ };
497
+ });
498
+ return nodes.map((n, i) => ({ ...n, ...placed[i] }));
499
+ }
500
+
501
+ function truncate(s, n) { s = String(s || ""); return s.length > n ? s.slice(0, n - 1) + "…" : s; }
502
+
503
+ function iconForType(t) {
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";
506
+ }
507
+
508
+ function buildLegend({ h }) {
509
+ const types = ["Source", "Document", "Concept", "Person", "Decision"];
510
+ return h("div.lt3-graph-legend",
511
+ types.map((t) => h("span", h("i", { style: { background: colorFor(t) } }), t)),
512
+ );
513
+ }