ltcai 6.0.0 → 6.2.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 (54) hide show
  1. package/README.md +33 -35
  2. package/docs/CHANGELOG.md +68 -0
  3. package/docs/V4_1_FRONTEND_MIGRATION_REPORT.md +1 -1
  4. package/docs/V4_6_1_RELEASE_REFRESH_REPORT.md +1 -1
  5. package/docs/V4_7_0_ADMIN_SEPARATION_REPORT.md +1 -1
  6. package/docs/V4_7_1_ADMIN_OPERATIONS_REPORT.md +1 -1
  7. package/frontend/src/App.tsx +3 -1281
  8. package/frontend/src/components/LanguageSwitcher.tsx +23 -0
  9. package/frontend/src/components/ProductFlow.tsx +32 -662
  10. package/frontend/src/components/onboarding/ProductFlowScreens.tsx +688 -0
  11. package/frontend/src/features/admin/AdminConsole.tsx +294 -0
  12. package/frontend/src/features/brain/BrainHome.tsx +999 -0
  13. package/frontend/src/features/brain/brainData.ts +98 -0
  14. package/frontend/src/features/brain/graphLayout.ts +26 -0
  15. package/frontend/src/features/brain/types.ts +44 -0
  16. package/frontend/src/features/review/ReviewCard.tsx +15 -10
  17. package/frontend/src/i18n.ts +208 -0
  18. package/frontend/src/styles.css +240 -0
  19. package/lattice_brain/__init__.py +1 -1
  20. package/lattice_brain/runtime/multi_agent.py +1 -1
  21. package/latticeai/__init__.py +1 -1
  22. package/latticeai/api/chat.py +52 -33
  23. package/latticeai/api/tools.py +50 -23
  24. package/latticeai/app_factory.py +65 -47
  25. package/latticeai/cli/__init__.py +1 -0
  26. package/latticeai/cli/entrypoint.py +283 -0
  27. package/latticeai/cli/runtime.py +37 -0
  28. package/latticeai/core/marketplace.py +1 -1
  29. package/latticeai/core/workspace_os.py +1 -1
  30. package/latticeai/integrations/__init__.py +0 -0
  31. package/latticeai/integrations/telegram_bot.py +1009 -0
  32. package/latticeai/runtime/lifespan_runtime.py +1 -1
  33. package/latticeai/runtime/platform_runtime_wiring.py +87 -0
  34. package/latticeai/runtime/router_registration.py +49 -30
  35. package/latticeai/services/app_context.py +1 -0
  36. package/latticeai/services/p_reinforce.py +258 -0
  37. package/latticeai/services/router_context.py +52 -0
  38. package/latticeai/services/tool_dispatch.py +82 -25
  39. package/ltcai_cli.py +7 -305
  40. package/p_reinforce.py +4 -255
  41. package/package.json +2 -1
  42. package/scripts/release_smoke.py +133 -0
  43. package/scripts/wheel_smoke.py +4 -0
  44. package/src-tauri/Cargo.lock +1 -1
  45. package/src-tauri/Cargo.toml +1 -1
  46. package/src-tauri/tauri.conf.json +1 -1
  47. package/static/app/asset-manifest.json +5 -5
  48. package/static/app/assets/{index-xRn29gI8.css → index-B2-1Gm0q.css} +1 -1
  49. package/static/app/assets/index-D91Rz5--.js +16 -0
  50. package/static/app/assets/index-D91Rz5--.js.map +1 -0
  51. package/static/app/index.html +2 -2
  52. package/telegram_bot.py +9 -1008
  53. package/static/app/assets/index-D2zafMYb.js +0 -16
  54. package/static/app/assets/index-D2zafMYb.js.map +0 -1
@@ -1,75 +1,11 @@
1
1
  import * as React from "react";
2
- import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
3
- import {
4
- Activity,
5
- Archive,
6
- ArrowLeft,
7
- ChevronDown,
8
- DatabaseBackup,
9
- Download,
10
- Eye,
11
- ImagePlus,
12
- ListFilter,
13
- RotateCcw,
14
- Search,
15
- Send,
16
- ServerCog,
17
- ShieldCheck,
18
- Users,
19
- } from "lucide-react";
20
- import { latticeApi, type AdminAuditFilters, type ApiResult } from "@/api/client";
21
- import { Button } from "@/components/ui/button";
22
- import { type BrainState, LivingBrain, triggerBrainRecall } from "@/components/LivingBrain";
2
+ import { type BrainState } from "@/components/LivingBrain";
23
3
  import { ProductFlow, readProductFlowComplete } from "@/components/ProductFlow";
24
4
  import { useAppStore } from "@/store/appStore";
25
- import { asArray } from "@/lib/utils";
26
- import { LANGUAGE_LABELS, t, type Language } from "@/i18n";
27
5
  import { parseHash } from "@/routes";
28
6
  import { ActPage } from "@/pages/Act";
29
-
30
- type ApiRecord = Record<string, unknown>;
31
- type BrainDepth = 1 | 2 | 3 | 4 | 5;
32
- type AdminFilterState = Required<Pick<AdminAuditFilters, "q" | "actor" | "action" | "severity">> & { limit: number };
33
-
34
- type Message = {
35
- role: "user" | "assistant";
36
- content: string;
37
- };
38
-
39
- type MemoryFragment = {
40
- id: string;
41
- title: string;
42
- kind: string;
43
- };
44
-
45
- type KnowledgeConcept = {
46
- id: string;
47
- label: string;
48
- type: string;
49
- summary: string;
50
- importance: number;
51
- };
52
-
53
- type RelationshipThread = {
54
- id: string;
55
- source: string;
56
- target: string;
57
- label: string;
58
- weight: number;
59
- };
60
-
61
- type KnowledgeGraphModel = {
62
- nodes: KnowledgeConcept[];
63
- edges: RelationshipThread[];
64
- };
65
-
66
- const DEPTHS: Array<{ level: BrainDepth; label: string; state: BrainState }> = [
67
- { level: 1, label: "Living Brain", state: "idle" },
68
- { level: 2, label: "Memory Layer", state: "recalling" },
69
- { level: 3, label: "Knowledge Layer", state: "synthesizing" },
70
- { level: 4, label: "Relationship Layer", state: "planning" },
71
- { level: 5, label: "Knowledge Graph", state: "synthesizing" },
72
- ];
7
+ import { BrainHome } from "@/features/brain/BrainHome";
8
+ import { AdminConsole } from "@/features/admin/AdminConsole";
73
9
 
74
10
  export default function App() {
75
11
  const theme = useAppStore((state) => state.theme);
@@ -145,1220 +81,6 @@ function useBrainState() {
145
81
  return { state, intensity, setBrain };
146
82
  }
147
83
 
148
- function BrainHome({
149
- brainState,
150
- intensity,
151
- onBrainChange,
152
- }: {
153
- brainState: BrainState;
154
- intensity: number;
155
- onBrainChange: (state: BrainState, intensity?: number) => void;
156
- }) {
157
- const qc = useQueryClient();
158
- const language = useAppStore((state) => state.language);
159
- const [messages, setMessages] = React.useState<Message[]>([]);
160
- const [draft, setDraft] = React.useState("");
161
- const [imageData, setImageData] = React.useState<string | null>(null);
162
- const [streaming, setStreaming] = React.useState(false);
163
- const [conversationId, setConversationId] = React.useState<string | null>(null);
164
- const [explorationDepth, setExplorationDepth] = React.useState<BrainDepth>(1);
165
- const [graphSearch, setGraphSearch] = React.useState("");
166
- const [selectedGraphId, setSelectedGraphId] = React.useState<string | null>(null);
167
- const [memoryFeedback, setMemoryFeedback] = React.useState<string | null>(null);
168
- const streamRef = React.useRef<HTMLDivElement>(null);
169
- const recallTimerRef = React.useRef<number | null>(null);
170
-
171
- const memoriesQ = useQuery({ queryKey: ["memoryManager"], queryFn: latticeApi.memoryManager });
172
- const historyQ = useQuery({ queryKey: ["chatHistory"], queryFn: latticeApi.chatHistory });
173
- const graphQ = useQuery({ queryKey: ["graph"], queryFn: latticeApi.graph });
174
- const modelsQ = useQuery({ queryKey: ["models"], queryFn: latticeApi.models });
175
-
176
- const memoryFragments = React.useMemo(
177
- () => buildMemoryFragments(memoriesQ.data?.data, historyQ.data?.data),
178
- [memoriesQ.data, historyQ.data],
179
- );
180
- const graphModel = React.useMemo(() => parseKnowledgeGraph(graphQ.data?.data), [graphQ.data]);
181
- const knowledgeConcepts = React.useMemo(
182
- () => graphModel.nodes.slice(0, 10),
183
- [graphModel.nodes],
184
- );
185
- const relationshipThreads = React.useMemo(
186
- () => graphModel.edges.slice(0, 10),
187
- [graphModel.edges],
188
- );
189
- const modelName = React.useMemo(() => currentModelName(modelsQ.data?.data), [modelsQ.data]);
190
- const currentDepth = DEPTHS[explorationDepth - 1];
191
- const starterPrompts = React.useMemo(
192
- () => [
193
- t(language, "brain.prompt.remember"),
194
- t(language, "brain.prompt.know"),
195
- t(language, "brain.prompt.plan"),
196
- ],
197
- [language],
198
- );
199
-
200
- React.useEffect(() => {
201
- if (streaming) onBrainChange("thinking", 0.94);
202
- else if (draft.trim().length > 4) onBrainChange("listening", 0.76);
203
- else onBrainChange(currentDepth.state, explorationDepth === 1 ? 0.58 : 0.66 + explorationDepth * 0.06);
204
- }, [streaming, draft, currentDepth.state, explorationDepth, onBrainChange]);
205
-
206
- React.useEffect(() => {
207
- const stream = streamRef.current;
208
- if (stream) stream.scrollTop = stream.scrollHeight;
209
- }, [messages]);
210
-
211
- React.useEffect(() => {
212
- return () => {
213
- if (recallTimerRef.current !== null) window.clearTimeout(recallTimerRef.current);
214
- };
215
- }, []);
216
-
217
- async function send() {
218
- const text = draft.trim();
219
- if (!text || streaming) return;
220
- const activeConversationId = conversationId || `brain-${Date.now()}`;
221
- if (!conversationId) setConversationId(activeConversationId);
222
-
223
- setMessages((items) => [...items, { role: "user", content: text }, { role: "assistant", content: "" }]);
224
- setDraft("");
225
- setImageData(null);
226
- setStreaming(true);
227
- setMemoryFeedback(null);
228
- onBrainChange("thinking", 0.96);
229
-
230
- try {
231
- const result = await latticeApi.streamChat(
232
- { message: text, conversation_id: activeConversationId, image_data: imageData || undefined },
233
- {
234
- onChunk: (_delta, fullText) => {
235
- setMessages((items) => {
236
- const next = [...items];
237
- next[next.length - 1] = { role: "assistant", content: fullText };
238
- return next;
239
- });
240
- },
241
- onTrace: (trace) => {
242
- if (!trace) return;
243
- onBrainChange("recalling", 0.9);
244
- triggerBrainRecall();
245
- if (recallTimerRef.current !== null) window.clearTimeout(recallTimerRef.current);
246
- recallTimerRef.current = window.setTimeout(() => onBrainChange("thinking", 0.9), 900);
247
- },
248
- },
249
- );
250
- if (result.error) {
251
- setMessages((items) => {
252
- const next = [...items];
253
- next[next.length - 1] = { role: "assistant", content: `${t(language, "brain.unavailable")}: ${result.error}` };
254
- return next;
255
- });
256
- } else {
257
- setMemoryFeedback(t(language, "brain.saved", { topics: knowledgeConcepts.length, memories: memoryFragments.length }));
258
- }
259
- } finally {
260
- setStreaming(false);
261
- void qc.invalidateQueries({ queryKey: ["chatHistory"] });
262
- void qc.invalidateQueries({ queryKey: ["memoryManager"] });
263
- void qc.invalidateQueries({ queryKey: ["graph"] });
264
- }
265
- }
266
-
267
- function deepen() {
268
- setExplorationDepth((depth) => {
269
- const next = Math.min(5, depth + 1) as BrainDepth;
270
- const nextDepth = DEPTHS[next - 1];
271
- onBrainChange(nextDepth.state, 0.66 + next * 0.06);
272
- if (next >= 2) triggerBrainRecall();
273
- return next;
274
- });
275
- }
276
-
277
- function jumpToDepth(next: BrainDepth) {
278
- setExplorationDepth(next);
279
- const nextDepth = DEPTHS[next - 1];
280
- onBrainChange(nextDepth.state, next === 1 ? 0.58 : 0.66 + next * 0.06);
281
- if (next >= 2) triggerBrainRecall();
282
- }
283
-
284
- function surface() {
285
- setExplorationDepth(1);
286
- setSelectedGraphId(null);
287
- setGraphSearch("");
288
- onBrainChange("idle", 0.58);
289
- }
290
-
291
- function recallMemory(fragment: MemoryFragment) {
292
- triggerBrainRecall();
293
- setExplorationDepth((depth) => Math.max(depth, 2) as BrainDepth);
294
- setMessages((items) => [
295
- ...items,
296
- { role: "assistant", content: t(language, "brain.recalled", { title: fragment.title }) },
297
- ]);
298
- }
299
-
300
- return (
301
- <main className="brain-home" aria-label="Lattice Brain">
302
- <section className="brain-presence" aria-label="Brain exploration">
303
- <div className="brain-exploration" data-depth={explorationDepth}>
304
- <LivingBrain
305
- state={brainState}
306
- intensity={intensity + explorationDepth * 0.035}
307
- size="large"
308
- depth={explorationDepth}
309
- showLabel={false}
310
- onInteract={deepen}
311
- />
312
-
313
- <div className="brain-depth-badge" aria-live="polite">
314
- <span>{t(language, "brain.level")} {explorationDepth}</span>
315
- <strong>{t(language, `brain.depth.${explorationDepth}`)}</strong>
316
- </div>
317
-
318
- <div className="brain-depth-actions" aria-label="Brain quick views">
319
- <button type="button" className={explorationDepth === 2 ? "is-active" : ""} onClick={() => jumpToDepth(2)}>{t(language, "brain.view.memories")}</button>
320
- <button type="button" className={explorationDepth === 3 ? "is-active" : ""} onClick={() => jumpToDepth(3)}>{t(language, "brain.view.topics")}</button>
321
- <button type="button" className={explorationDepth === 4 ? "is-active" : ""} onClick={() => jumpToDepth(4)}>{t(language, "brain.view.relationships")}</button>
322
- <button type="button" className={explorationDepth === 5 ? "is-active" : ""} onClick={() => jumpToDepth(5)}>{t(language, "brain.view.graph")}</button>
323
- </div>
324
-
325
- <div className="brain-field-layer" aria-hidden={explorationDepth < 2}>
326
- <DepthEmergence
327
- depth={explorationDepth}
328
- memories={memoryFragments}
329
- concepts={knowledgeConcepts}
330
- relationships={relationshipThreads}
331
- graphModel={graphModel}
332
- graphSearch={graphSearch}
333
- selectedGraphId={selectedGraphId}
334
- onGraphSearch={setGraphSearch}
335
- onSelectGraphNode={setSelectedGraphId}
336
- onRecallMemory={recallMemory}
337
- />
338
- </div>
339
-
340
- {explorationDepth > 1 ? (
341
- <button className="brain-surface-control" type="button" onClick={surface}>
342
- {t(language, "brain.surface")}
343
- </button>
344
- ) : null}
345
- </div>
346
- </section>
347
-
348
- <section className="brain-conversation" aria-label="Conversation">
349
- <div className="brain-conversation-header">
350
- <div>
351
- <h1>{t(language, "brain.title")}</h1>
352
- <span>{t(language, `brain.depth.${explorationDepth}`)}</span>
353
- </div>
354
- <LanguageSwitcher compact />
355
- <div className="brain-ownership-strip" aria-label="Brain ownership guarantees">
356
- <span>{t(language, "brain.local")}</span>
357
- <span>{t(language, "brain.portable")}</span>
358
- <span>{t(language, "brain.private")}</span>
359
- </div>
360
- <div>{modelName}</div>
361
- <button className="brain-admin-link" type="button" onClick={() => navigateHash("/admin")}>
362
- <ShieldCheck className="h-3.5 w-3.5" />
363
- {t(language, "brain.admin")}
364
- </button>
365
- </div>
366
-
367
- <div ref={streamRef} className="brain-stream">
368
- <BrainOverviewPanel
369
- memories={memoryFragments}
370
- concepts={knowledgeConcepts}
371
- onOpenDepth={jumpToDepth}
372
- />
373
- {messages.length === 0 ? (
374
- <div className="mind-empty">
375
- <div className="mind-empty-kicker">{t(language, "brain.empty.kicker")}</div>
376
- <div className="mind-empty-title">{t(language, "brain.empty.title")}</div>
377
- <p>{t(language, "brain.empty.body")}</p>
378
- <div className="mind-empty-prompts" aria-label="Starter prompts">
379
- {starterPrompts.map((prompt) => (
380
- <button key={prompt} type="button" onClick={() => setDraft(prompt)}>
381
- {prompt}
382
- </button>
383
- ))}
384
- </div>
385
- </div>
386
- ) : (
387
- messages.map((message, index) => (
388
- <div key={`${message.role}-${index}`} className={`brain-message ${message.role}`}>
389
- <div className="brain-message-bubble">{message.content}</div>
390
- </div>
391
- ))
392
- )}
393
- </div>
394
-
395
- {memoryFeedback ? <div className="brain-save-feedback" role="status">{memoryFeedback}</div> : null}
396
-
397
- <BrainCarePanel language={language} />
398
-
399
- <div className="brain-composer">
400
- <textarea
401
- value={draft}
402
- onChange={(event) => setDraft(event.target.value)}
403
- onKeyDown={(event) => {
404
- if (event.key === "Enter" && !event.shiftKey) {
405
- event.preventDefault();
406
- void send();
407
- }
408
- }}
409
- placeholder={t(language, "brain.placeholder")}
410
- />
411
- <div className="brain-composer-actions">
412
- <label className="brain-image-input">
413
- <ImagePlus className="h-3.5 w-3.5" />
414
- <span>{t(language, "brain.image")}</span>
415
- <input
416
- type="file"
417
- accept="image/*"
418
- className="sr-only"
419
- onChange={async (event) => {
420
- const file = event.target.files?.[0];
421
- if (file) setImageData(await fileToDataUrl(file));
422
- }}
423
- />
424
- </label>
425
- {imageData ? <span className="brain-quiet-success">{t(language, "brain.imageAttached")}</span> : null}
426
- <Button onClick={() => void send()} disabled={!draft.trim() || streaming} className="rounded-full px-5">
427
- <Send className="h-4 w-4" /> {t(language, "brain.send")}
428
- </Button>
429
- </div>
430
- </div>
431
- </section>
432
- </main>
433
- );
434
- }
435
-
436
- function LanguageSwitcher({ compact = false }: { compact?: boolean }) {
437
- const language = useAppStore((state) => state.language);
438
- const setLanguage = useAppStore((state) => state.setLanguage);
439
-
440
- return (
441
- <div className={compact ? "language-switcher compact" : "language-switcher"} aria-label={t(language, "language.label")}>
442
- {(["ko", "en"] as Language[]).map((item) => (
443
- <button
444
- key={item}
445
- type="button"
446
- className={language === item ? "is-active" : ""}
447
- onClick={() => setLanguage(item)}
448
- aria-pressed={language === item}
449
- >
450
- {LANGUAGE_LABELS[item]}
451
- </button>
452
- ))}
453
- </div>
454
- );
455
- }
456
-
457
- function AdminConsole({ onBack }: { onBack: () => void }) {
458
- const qc = useQueryClient();
459
- const language = useAppStore((state) => state.language);
460
- const [filters, setFilters] = React.useState<AdminFilterState>({ q: "", actor: "", action: "", severity: "", limit: 50 });
461
- const { summaryQ, statsQ, usersQ, auditQ, securityQ, securityEventsQ, policiesQ, rolesQ, retentionQ, indexQ } = useAdminConsoleData(filters);
462
- const rebuildIndex = useMutation({
463
- mutationFn: latticeApi.rebuildIndex,
464
- onSuccess: () => void qc.invalidateQueries({ queryKey: ["indexStatus"] }),
465
- });
466
-
467
- const users = asArray(usersQ.data?.data);
468
- const auditEvents = asArray((auditQ.data?.data as ApiRecord | undefined)?.recent_events);
469
- const securityEvents = asArray((securityEventsQ.data?.data as ApiRecord | undefined)?.events);
470
- const policies = asArray((policiesQ.data?.data as ApiRecord | undefined)?.policies);
471
- const roles = asArray((rolesQ.data?.data as ApiRecord | undefined)?.roles);
472
- const retention = (retentionQ.data?.data || {}) as ApiRecord;
473
-
474
- return (
475
- <main className="admin-console" aria-label="Lattice Admin">
476
- <header className="admin-console-header">
477
- <button className="admin-back-button" type="button" onClick={onBack}>
478
- <ArrowLeft className="h-4 w-4" />
479
- {t(language, "admin.back")}
480
- </button>
481
- <div>
482
- <span>{t(language, "admin.kicker")}</span>
483
- <h1>{t(language, "admin.title")}</h1>
484
- <p>{t(language, "admin.body")}</p>
485
- </div>
486
- <LanguageSwitcher compact />
487
- </header>
488
-
489
- <section className="admin-metrics" aria-label="Admin overview">
490
- <AdminMetric icon={<Users className="h-4 w-4" />} label="Users" value={String(users.length)} detail={sourceLabel(usersQ.data)} />
491
- <AdminMetric
492
- icon={<Activity className="h-4 w-4" />}
493
- label="Recent logs"
494
- value={String(auditEvents.length + securityEvents.length)}
495
- detail={sourceLabel(auditQ.data)}
496
- />
497
- <AdminMetric
498
- icon={<ShieldCheck className="h-4 w-4" />}
499
- label="Security"
500
- value={adminStatusLabel(securityQ.data?.data, "status") || (securityQ.data?.ok ? "Ready" : "Unavailable")}
501
- detail={sourceLabel(securityQ.data)}
502
- />
503
- <AdminMetric
504
- icon={<ServerCog className="h-4 w-4" />}
505
- label="Brain index"
506
- value={adminStatusLabel(indexQ.data?.data, "status") || (indexQ.data?.ok ? "Indexed" : "Unknown")}
507
- detail={indexDetail(indexQ.data?.data)}
508
- />
509
- </section>
510
-
511
- <section className="admin-grid">
512
- <AdminPanel title="User Directory" eyebrow="People">
513
- <AdminList
514
- items={users.slice(0, 8)}
515
- empty="No users reported by the admin API."
516
- render={(item) => {
517
- const user = item as ApiRecord;
518
- return (
519
- <>
520
- <strong>{stringValue(user.name || user.email || user.id, "Local user")}</strong>
521
- <span>{stringValue(user.role || user.status || user.workspace_id, "member")}</span>
522
- </>
523
- );
524
- }}
525
- />
526
- </AdminPanel>
527
-
528
- <AdminPanel title="Role Permissions" eyebrow="Access">
529
- <AdminList
530
- items={roles.slice(0, 6)}
531
- empty="No role matrix reported."
532
- render={(item) => {
533
- const role = item as ApiRecord;
534
- return (
535
- <>
536
- <strong>{stringValue(role.role, "role")} · {stringValue(role.members, "0")} users</strong>
537
- <span>{asArray(role.caps).slice(0, 4).map((cap) => stringValue(cap, "")).filter(Boolean).join(", ") || "No caps"}</span>
538
- </>
539
- );
540
- }}
541
- />
542
- </AdminPanel>
543
-
544
- <AdminPanel title="Activity Logs" eyebrow="Audit">
545
- <AdminLogFilters filters={filters} onChange={setFilters} matched={(auditQ.data?.data as ApiRecord | undefined)?.filters as ApiRecord | undefined} />
546
- <AdminList
547
- items={auditEvents.slice(0, 8)}
548
- empty="No recent audit events."
549
- render={(item) => renderLogRow(item as ApiRecord)}
550
- />
551
- </AdminPanel>
552
-
553
- <AdminPanel title="Security Events" eyebrow="Protection">
554
- <AdminList
555
- items={securityEvents.slice(0, 8)}
556
- empty="No security events reported."
557
- render={(item) => renderLogRow(item as ApiRecord)}
558
- />
559
- </AdminPanel>
560
-
561
- <AdminPanel title="Brain Operations" eyebrow="Maintenance">
562
- <div className="admin-operation">
563
- <div>
564
- <strong>{indexDetail(indexQ.data?.data)}</strong>
565
- <span>{summaryText(summaryQ.data?.data) || summaryText(statsQ.data?.data) || "Local Brain services are separated from user chat."}</span>
566
- </div>
567
- <Button variant="outline" size="sm" disabled={rebuildIndex.isPending} onClick={() => rebuildIndex.mutate()}>
568
- <RotateCcw className="h-3.5 w-3.5" />
569
- {rebuildIndex.isPending ? "Rebuilding" : "Rebuild index"}
570
- </Button>
571
- </div>
572
- <div className="admin-policy-strip">
573
- {policies.slice(0, 5).map((item, index) => {
574
- const policy = item as ApiRecord;
575
- return <span key={`${stringValue(policy.id || policy.name, "policy")}-${index}`}>{stringValue(policy.label || policy.name || policy.id, "Policy")}</span>;
576
- })}
577
- {!policies.length ? <span>Policy API quiet</span> : null}
578
- </div>
579
- <div className="admin-retention">
580
- <strong>{stringValue(retention.retention_days, "90")} day retention</strong>
581
- <span>{stringValue(retention.retained_events, "0")} retained · {stringValue(retention.prune_candidates, "0")} ready for export/prune review</span>
582
- </div>
583
- </AdminPanel>
584
-
585
- </section>
586
- </main>
587
- );
588
- }
589
-
590
- function useAdminConsoleData(filters: AdminFilterState) {
591
- const auditFilters = React.useMemo<AdminAuditFilters>(() => ({
592
- q: filters.q || undefined,
593
- actor: filters.actor || undefined,
594
- action: filters.action || undefined,
595
- severity: filters.severity || undefined,
596
- limit: filters.limit,
597
- }), [filters]);
598
-
599
- return {
600
- summaryQ: useQuery({ queryKey: ["adminSummary"], queryFn: latticeApi.adminSummary }),
601
- statsQ: useQuery({ queryKey: ["adminStats"], queryFn: latticeApi.adminStats }),
602
- usersQ: useQuery({ queryKey: ["adminUsers"], queryFn: latticeApi.adminUsers }),
603
- auditQ: useQuery({ queryKey: ["adminAudit", auditFilters], queryFn: () => latticeApi.adminAudit(auditFilters) }),
604
- securityQ: useQuery({ queryKey: ["adminSecurity"], queryFn: latticeApi.adminSecurity }),
605
- securityEventsQ: useQuery({ queryKey: ["adminSecurityEvents"], queryFn: () => latticeApi.adminSecurityEvents(50) }),
606
- policiesQ: useQuery({ queryKey: ["adminPolicies"], queryFn: latticeApi.adminPolicies }),
607
- rolesQ: useQuery({ queryKey: ["adminRoles"], queryFn: latticeApi.adminRoles }),
608
- retentionQ: useQuery({ queryKey: ["adminLogRetention"], queryFn: latticeApi.adminLogRetention }),
609
- indexQ: useQuery({ queryKey: ["indexStatus"], queryFn: latticeApi.indexStatus }),
610
- };
611
- }
612
-
613
- function AdminLogFilters({
614
- filters,
615
- matched,
616
- onChange,
617
- }: {
618
- filters: AdminFilterState;
619
- matched?: ApiRecord;
620
- onChange: React.Dispatch<React.SetStateAction<AdminFilterState>>;
621
- }) {
622
- return (
623
- <div className="admin-log-filters" aria-label="Audit log filters">
624
- <label>
625
- <Search className="h-3.5 w-3.5" />
626
- <input
627
- value={filters.q}
628
- onChange={(event) => onChange((current) => ({ ...current, q: event.target.value }))}
629
- placeholder="Search logs"
630
- aria-label="Search audit logs"
631
- />
632
- </label>
633
- <label>
634
- <ListFilter className="h-3.5 w-3.5" />
635
- <select
636
- value={filters.severity}
637
- onChange={(event) => onChange((current) => ({ ...current, severity: event.target.value }))}
638
- aria-label="Filter by severity"
639
- >
640
- <option value="">All severities</option>
641
- <option value="informational">Informational</option>
642
- <option value="notice">Notice</option>
643
- <option value="warning">Warning</option>
644
- <option value="high">High</option>
645
- </select>
646
- </label>
647
- <span>{stringValue(matched?.matched_events, "0")} matched</span>
648
- </div>
649
- );
650
- }
651
-
652
- function AdminMetric({ icon, label, value, detail }: { icon: React.ReactNode; label: string; value: string; detail: string }) {
653
- return (
654
- <div className="admin-metric">
655
- <div>{icon}</div>
656
- <span>{label}</span>
657
- <strong>{value}</strong>
658
- <small>{detail}</small>
659
- </div>
660
- );
661
- }
662
-
663
- function AdminPanel({ eyebrow, title, children }: { eyebrow: string; title: string; children: React.ReactNode }) {
664
- return (
665
- <section className="admin-panel">
666
- <div className="admin-panel-head">
667
- <span>{eyebrow}</span>
668
- <h2>{title}</h2>
669
- </div>
670
- {children}
671
- </section>
672
- );
673
- }
674
-
675
- function AdminList({ items, empty, render }: { items: unknown[]; empty: string; render: (item: unknown) => React.ReactNode }) {
676
- if (!items.length) return <div className="admin-empty">{empty}</div>;
677
- return <div className="admin-list">{items.map((item, index) => <div key={index} className="admin-list-row">{render(item)}</div>)}</div>;
678
- }
679
-
680
- function BrainCarePanel({ language }: { language: Language }) {
681
- const qc = useQueryClient();
682
- const [expanded, setExpanded] = React.useState(false);
683
- const [archivePath, setArchivePath] = React.useState("");
684
- const [passphrase, setPassphrase] = React.useState("");
685
- const [latestResult, setLatestResult] = React.useState<ApiResult | null>(null);
686
- const portabilityQ = useQuery({ queryKey: ["portability"], queryFn: latticeApi.graphPortability });
687
- const backupHealthQ = useQuery({ queryKey: ["backupHealth"], queryFn: latticeApi.backupHealth });
688
- const rememberResult = React.useCallback((result: ApiResult) => setLatestResult(result), []);
689
-
690
- const exportGraph = useCareMutation(() => latticeApi.graphExport(), undefined, rememberResult);
691
- const backupGraph = useCareMutation(() => latticeApi.graphBackup(), () => {
692
- void qc.invalidateQueries({ queryKey: ["backupHealth"] });
693
- void qc.invalidateQueries({ queryKey: ["portability"] });
694
- }, rememberResult);
695
- const archiveBrain = useCareMutation(
696
- () => latticeApi.brainArchive({ path: archivePath.trim() || null, passphrase }),
697
- () => void qc.invalidateQueries({ queryKey: ["backupHealth"] }),
698
- rememberResult,
699
- );
700
- const inspectArchive = useCareMutation(() => latticeApi.brainArchiveInspect({
701
- path: archivePath.trim(),
702
- passphrase: passphrase || null,
703
- }), undefined, rememberResult);
704
- const restorePreview = useCareMutation(() => latticeApi.brainArchiveRestore({
705
- path: archivePath.trim(),
706
- passphrase,
707
- dry_run: true,
708
- confirm: false,
709
- }), undefined, rememberResult);
710
-
711
- const portableFormat = portabilityLabel(portabilityQ.data?.data);
712
- const backupStatus = backupHealthLabel(backupHealthQ.data?.data);
713
-
714
- return (
715
- <section className={`brain-care-panel ${expanded ? "is-expanded" : "is-collapsed"}`} aria-label={t(language, "care.title")}>
716
- <button
717
- className="brain-care-summary"
718
- type="button"
719
- aria-expanded={expanded}
720
- aria-controls="brain-care-details"
721
- onClick={() => setExpanded((value) => !value)}
722
- >
723
- <span className="brain-care-summary-main">
724
- <span><ShieldCheck className="h-3.5 w-3.5" /> {t(language, "care.title")}</span>
725
- <strong>{t(language, "care.subtitle")}</strong>
726
- </span>
727
- <div className="brain-care-proof" aria-label="Ownership model">
728
- <span>{t(language, "care.private")}</span>
729
- <span>{portableFormat}</span>
730
- <span>{backupStatus}</span>
731
- </div>
732
- <ChevronDown className="brain-care-toggle h-4 w-4" aria-hidden="true" />
733
- </button>
734
-
735
- {expanded ? (
736
- <div id="brain-care-details" className="brain-care-details">
737
- <div className="brain-care-actions">
738
- <CareButton
739
- icon={<Download className="h-3.5 w-3.5" />}
740
- label={t(language, "care.export")}
741
- detail={t(language, "care.export.detail")}
742
- pendingLabel={t(language, "care.working")}
743
- pending={exportGraph.isPending}
744
- onClick={() => exportGraph.mutate()}
745
- />
746
- <CareButton
747
- icon={<DatabaseBackup className="h-3.5 w-3.5" />}
748
- label={t(language, "care.backup")}
749
- detail={t(language, "care.backup.detail")}
750
- pendingLabel={t(language, "care.working")}
751
- pending={backupGraph.isPending}
752
- onClick={() => backupGraph.mutate()}
753
- />
754
- <CareButton
755
- icon={<Archive className="h-3.5 w-3.5" />}
756
- label={t(language, "care.archive")}
757
- detail={t(language, "care.archive.detail")}
758
- pendingLabel={t(language, "care.working")}
759
- pending={archiveBrain.isPending}
760
- disabled={!passphrase.trim()}
761
- onClick={() => archiveBrain.mutate()}
762
- />
763
- </div>
764
-
765
- <div className="brain-care-archive">
766
- <input
767
- value={archivePath}
768
- onChange={(event) => setArchivePath(event.target.value)}
769
- placeholder={t(language, "care.path.placeholder")}
770
- aria-label={t(language, "care.path.label")}
771
- />
772
- <input
773
- type="password"
774
- value={passphrase}
775
- onChange={(event) => setPassphrase(event.target.value)}
776
- placeholder={t(language, "care.passphrase.placeholder")}
777
- aria-label={t(language, "care.passphrase.label")}
778
- />
779
- <div className="brain-care-archive-actions">
780
- <Button
781
- variant="outline"
782
- size="sm"
783
- disabled={!archivePath.trim() || inspectArchive.isPending}
784
- onClick={() => inspectArchive.mutate()}
785
- >
786
- <Eye className="h-3.5 w-3.5" /> {t(language, "care.inspect")}
787
- </Button>
788
- <Button
789
- variant="outline"
790
- size="sm"
791
- disabled={!archivePath.trim() || !passphrase.trim() || restorePreview.isPending}
792
- onClick={() => restorePreview.mutate()}
793
- >
794
- <RotateCcw className="h-3.5 w-3.5" /> {t(language, "care.restorePreview")}
795
- </Button>
796
- </div>
797
- </div>
798
-
799
- {latestResult ? (
800
- <div className={`brain-care-result ${latestResult.ok ? "is-ok" : "is-error"}`} role="status">
801
- {summarizeCareResult(latestResult)}
802
- </div>
803
- ) : (
804
- <p className="brain-care-note">
805
- {t(language, "care.note")}
806
- </p>
807
- )}
808
- </div>
809
- ) : null}
810
- </section>
811
- );
812
- }
813
-
814
- function useCareMutation<T extends ApiResult>(
815
- mutationFn: () => Promise<T>,
816
- onSuccess?: () => void,
817
- onResult?: (result: T) => void,
818
- ) {
819
- return useMutation({
820
- mutationFn,
821
- onSuccess: (result) => {
822
- onResult?.(result);
823
- onSuccess?.();
824
- },
825
- });
826
- }
827
-
828
- function CareButton({
829
- icon,
830
- label,
831
- detail,
832
- pendingLabel,
833
- pending,
834
- disabled,
835
- onClick,
836
- }: {
837
- icon: React.ReactNode;
838
- label: string;
839
- detail: string;
840
- pendingLabel: string;
841
- pending?: boolean;
842
- disabled?: boolean;
843
- onClick: () => void;
844
- }) {
845
- return (
846
- <button className="brain-care-button" type="button" disabled={disabled || pending} onClick={onClick}>
847
- {icon}
848
- <span>
849
- <strong>{pending ? pendingLabel : label}</strong>
850
- <small>{detail}</small>
851
- </span>
852
- </button>
853
- );
854
- }
855
-
856
- function DepthEmergence({
857
- depth,
858
- memories,
859
- concepts,
860
- relationships,
861
- graphModel,
862
- graphSearch,
863
- selectedGraphId,
864
- onGraphSearch,
865
- onSelectGraphNode,
866
- onRecallMemory,
867
- }: {
868
- depth: BrainDepth;
869
- memories: MemoryFragment[];
870
- concepts: KnowledgeConcept[];
871
- relationships: RelationshipThread[];
872
- graphModel: KnowledgeGraphModel;
873
- graphSearch: string;
874
- selectedGraphId: string | null;
875
- onGraphSearch: (value: string) => void;
876
- onSelectGraphNode: (id: string | null) => void;
877
- onRecallMemory: (fragment: MemoryFragment) => void;
878
- }) {
879
- if (depth === 1) return null;
880
-
881
- return (
882
- <>
883
- {depth >= 2 ? (
884
- <MemoryLayer memories={memories} depth={depth} onRecallMemory={onRecallMemory} />
885
- ) : null}
886
- {depth >= 3 && depth < 5 ? (
887
- <KnowledgeLayer concepts={concepts} depth={depth} />
888
- ) : null}
889
- {depth >= 4 && depth < 5 ? (
890
- <RelationshipLayer concepts={concepts} relationships={relationships} />
891
- ) : null}
892
- {depth >= 5 ? (
893
- <EmergentKnowledgeGraph
894
- model={graphModel}
895
- search={graphSearch}
896
- selectedId={selectedGraphId}
897
- onSearch={onGraphSearch}
898
- onSelect={onSelectGraphNode}
899
- />
900
- ) : null}
901
- </>
902
- );
903
- }
904
-
905
- function BrainOverviewPanel({
906
- memories,
907
- concepts,
908
- onOpenDepth,
909
- }: {
910
- memories: MemoryFragment[];
911
- concepts: KnowledgeConcept[];
912
- onOpenDepth: (depth: BrainDepth) => void;
913
- }) {
914
- const language = useAppStore((state) => state.language);
915
- const recent = memories.slice(0, 3);
916
- const older = memories.slice(3, 6);
917
- const topics = concepts.slice(0, 4);
918
-
919
- return (
920
- <section className="brain-overview-panel" aria-label="Brain overview">
921
- <div className="brain-overview-head">
922
- <div>
923
- <span>{t(language, "brain.overview.kicker")}</span>
924
- <strong>{t(language, "brain.overview.title")}</strong>
925
- </div>
926
- <button type="button" onClick={() => onOpenDepth(5)}>{t(language, "brain.overview.graph")}</button>
927
- </div>
928
- <div className="brain-overview-grid">
929
- <BrainOverviewColumn
930
- title={t(language, "brain.overview.recent")}
931
- empty={t(language, "brain.overview.recentEmpty")}
932
- items={recent.map((memory) => memory.title)}
933
- onOpen={() => onOpenDepth(2)}
934
- />
935
- <BrainOverviewColumn
936
- title={t(language, "brain.overview.older")}
937
- empty={t(language, "brain.overview.olderEmpty")}
938
- items={older.map((memory) => memory.title)}
939
- onOpen={() => onOpenDepth(2)}
940
- />
941
- <BrainOverviewColumn
942
- title={t(language, "brain.overview.topics")}
943
- empty={t(language, "brain.overview.topicsEmpty")}
944
- items={topics.map((concept) => concept.label)}
945
- onOpen={() => onOpenDepth(3)}
946
- />
947
- </div>
948
- </section>
949
- );
950
- }
951
-
952
- function BrainOverviewColumn({
953
- title,
954
- empty,
955
- items,
956
- onOpen,
957
- }: {
958
- title: string;
959
- empty: string;
960
- items: string[];
961
- onOpen: () => void;
962
- }) {
963
- return (
964
- <button type="button" className="brain-overview-column" onClick={onOpen}>
965
- <span>{title}</span>
966
- {items.length ? (
967
- items.slice(0, 3).map((item) => <strong key={item}>{item}</strong>)
968
- ) : (
969
- <em>{empty}</em>
970
- )}
971
- </button>
972
- );
973
- }
974
-
975
- function MemoryLayer({
976
- memories,
977
- depth,
978
- onRecallMemory,
979
- }: {
980
- memories: MemoryFragment[];
981
- depth: BrainDepth;
982
- onRecallMemory: (fragment: MemoryFragment) => void;
983
- }) {
984
- const visible = memories.slice(0, depth >= 3 ? 8 : 6);
985
- if (!visible.length) return <div className="memory-fragment is-empty">Memory is quiet</div>;
986
-
987
- return (
988
- <>
989
- {visible.map((memory, index) => {
990
- const point = polarPoint(index, visible.length, depth >= 3 ? 39 : 31, depth >= 3 ? 24 : 18, -112);
991
- return (
992
- <button
993
- key={memory.id}
994
- type="button"
995
- className="memory-fragment"
996
- style={layerStyle({ "--x": `${point.x}%`, "--y": `${point.y}%`, "--delay": `${index * 55}ms` })}
997
- onClick={() => onRecallMemory(memory)}
998
- >
999
- <span>{memory.kind}</span>
1000
- <strong>{memory.title}</strong>
1001
- </button>
1002
- );
1003
- })}
1004
- </>
1005
- );
1006
- }
1007
-
1008
- function KnowledgeLayer({ concepts, depth }: { concepts: KnowledgeConcept[]; depth: BrainDepth }) {
1009
- const visible = concepts.slice(0, depth >= 4 ? 10 : 7);
1010
- if (!visible.length) return <div className="concept-signal is-empty">Knowledge is forming</div>;
1011
-
1012
- return (
1013
- <>
1014
- {visible.map((concept, index) => {
1015
- const point = polarPoint(index, visible.length, 24, 15, -70);
1016
- return (
1017
- <button
1018
- key={concept.id}
1019
- type="button"
1020
- className="concept-signal"
1021
- style={layerStyle({ "--x": `${point.x}%`, "--y": `${point.y}%`, "--delay": `${index * 45}ms` })}
1022
- title={concept.summary || concept.type}
1023
- >
1024
- <span>{concept.type}</span>
1025
- {concept.label}
1026
- </button>
1027
- );
1028
- })}
1029
- </>
1030
- );
1031
- }
1032
-
1033
- function RelationshipLayer({
1034
- concepts,
1035
- relationships,
1036
- }: {
1037
- concepts: KnowledgeConcept[];
1038
- relationships: RelationshipThread[];
1039
- }) {
1040
- const visibleConcepts = concepts.slice(0, 10);
1041
- const layout = layoutGraphNodes(visibleConcepts, 30, 20);
1042
- const positionById = new Map(layout.map((item) => [item.node.id, item]));
1043
- const visibleRelationships = relationships
1044
- .map((relationship, index) => {
1045
- const source = positionById.get(relationship.source) || layout[index % Math.max(layout.length, 1)];
1046
- const target = positionById.get(relationship.target) || layout[(index + 3) % Math.max(layout.length, 1)];
1047
- return source && target && source.node.id !== target.node.id ? { relationship, source, target } : null;
1048
- })
1049
- .filter(Boolean)
1050
- .slice(0, 8) as Array<{
1051
- relationship: RelationshipThread;
1052
- source: ReturnType<typeof layoutGraphNodes>[number];
1053
- target: ReturnType<typeof layoutGraphNodes>[number];
1054
- }>;
1055
-
1056
- if (!visibleRelationships.length) return null;
1057
-
1058
- return (
1059
- <svg className="relationship-weave" viewBox="0 0 100 100" aria-hidden>
1060
- {visibleRelationships.map(({ relationship, source, target }, index) => (
1061
- <line
1062
- key={`${relationship.id}-${index}`}
1063
- x1={source.x}
1064
- y1={source.y}
1065
- x2={target.x}
1066
- y2={target.y}
1067
- style={{ animationDelay: `${index * 80}ms` }}
1068
- />
1069
- ))}
1070
- </svg>
1071
- );
1072
- }
1073
-
1074
- function EmergentKnowledgeGraph({
1075
- model,
1076
- search,
1077
- selectedId,
1078
- onSearch,
1079
- onSelect,
1080
- }: {
1081
- model: KnowledgeGraphModel;
1082
- search: string;
1083
- selectedId: string | null;
1084
- onSearch: (value: string) => void;
1085
- onSelect: (id: string | null) => void;
1086
- }) {
1087
- const language = useAppStore((state) => state.language);
1088
- const query = search.trim().toLowerCase();
1089
- const visibleNodes = React.useMemo(() => {
1090
- const filtered = model.nodes.filter((node) => {
1091
- if (!query) return true;
1092
- return `${node.label} ${node.type} ${node.summary}`.toLowerCase().includes(query);
1093
- });
1094
- return filtered.slice(0, 18);
1095
- }, [model.nodes, query]);
1096
- const layout = React.useMemo(() => layoutGraphNodes(visibleNodes, 38, 24), [visibleNodes]);
1097
- const positionById = React.useMemo(() => new Map(layout.map((item) => [item.node.id, item])), [layout]);
1098
- const visibleEdges = React.useMemo(
1099
- () => model.edges.filter((edge) => positionById.has(edge.source) && positionById.has(edge.target)).slice(0, 36),
1100
- [model.edges, positionById],
1101
- );
1102
- const selected = visibleNodes.find((node) => node.id === selectedId) || visibleNodes[0] || null;
1103
-
1104
- return (
1105
- <section className="mind-core-graph" data-testid="emergent-knowledge-graph" aria-label="Knowledge Graph">
1106
- <div className="brain-graph-head">
1107
- <div>
1108
- <span>Level 5</span>
1109
- <strong>Knowledge Graph</strong>
1110
- </div>
1111
- <label className="brain-graph-search">
1112
- <Search className="h-3.5 w-3.5" />
1113
- <input
1114
- value={search}
1115
- onChange={(event) => onSearch(event.target.value)}
1116
- placeholder="Search"
1117
- aria-label="Search knowledge graph"
1118
- />
1119
- </label>
1120
- </div>
1121
-
1122
- {visibleNodes.length ? (
1123
- <div className="brain-graph-canvas">
1124
- <svg className="brain-graph-edges" viewBox="0 0 100 100" aria-hidden>
1125
- {visibleEdges.map((edge, index) => {
1126
- const source = positionById.get(edge.source);
1127
- const target = positionById.get(edge.target);
1128
- if (!source || !target) return null;
1129
- return (
1130
- <line
1131
- key={`${edge.id}-${index}`}
1132
- x1={source.x}
1133
- y1={source.y}
1134
- x2={target.x}
1135
- y2={target.y}
1136
- style={{ "--weight": String(clamp(edge.weight, 0.4, 2.8)) } as React.CSSProperties}
1137
- />
1138
- );
1139
- })}
1140
- </svg>
1141
- {layout.map(({ node, x, y }, index) => (
1142
- <button
1143
- key={node.id}
1144
- type="button"
1145
- className={`graph-node ${selected?.id === node.id ? "is-selected" : ""}`}
1146
- style={layerStyle({ "--x": `${x}%`, "--y": `${y}%`, "--delay": `${index * 35}ms` })}
1147
- onClick={() => onSelect(node.id)}
1148
- >
1149
- <span>{node.type}</span>
1150
- {node.label}
1151
- </button>
1152
- ))}
1153
- </div>
1154
- ) : (
1155
- <div className="brain-graph-empty">{t(language, "brain.graph.empty")}</div>
1156
- )}
1157
-
1158
- <div className="brain-graph-focus">
1159
- {selected ? (
1160
- <>
1161
- <span>{selected.type}</span>
1162
- <strong>{selected.label}</strong>
1163
- <p>{selected.summary || t(language, "brain.graph.summaryFallback")}</p>
1164
- <p>{t(language, "brain.graph.focused")}</p>
1165
- </>
1166
- ) : (
1167
- <p>{t(language, "brain.graph.emptyFocus")}</p>
1168
- )}
1169
- </div>
1170
- </section>
1171
- );
1172
- }
1173
-
1174
- function buildMemoryFragments(memoryData: unknown, historyData: unknown): MemoryFragment[] {
1175
- const memory = isRecord(memoryData) ? memoryData : {};
1176
- const sourceRows = asArray<ApiRecord>(memory.sources).length
1177
- ? asArray<ApiRecord>(memory.sources)
1178
- : asArray<ApiRecord>(memory.tiers);
1179
- const sourceFragments = sourceRows.map((item, index) => ({
1180
- id: textValue(item, ["id", "source", "label"], `memory-${index}`),
1181
- title: textValue(item, ["title", "label", "source", "path", "name"], "Workspace memory"),
1182
- kind: titleValue(item, ["type", "source_type", "kind", "health"], "Memory"),
1183
- }));
1184
- const conversationFragments = asArray<ApiRecord>(historyData).map((item, index) => ({
1185
- id: textValue(item, ["id", "conversation_id"], `conversation-${index}`),
1186
- title: textValue(item, ["title", "summary", "id"], "Conversation"),
1187
- kind: "Conversation",
1188
- }));
1189
-
1190
- return uniqueById([...sourceFragments, ...conversationFragments]).slice(0, 10);
1191
- }
1192
-
1193
- function parseKnowledgeGraph(data: unknown): KnowledgeGraphModel {
1194
- const graph = isRecord(data) ? data : {};
1195
- const rawNodes = asArray<ApiRecord>(graph.nodes);
1196
- const rawEdges = asArray<ApiRecord>(graph.edges);
1197
- const nodes = rawNodes.flatMap((node): KnowledgeConcept[] => {
1198
- const id = textValue(node, ["id", "node_id", "title", "label"]);
1199
- if (!id) return [];
1200
- const metadata = isRecord(node.metadata) ? node.metadata : {};
1201
- const type = titleValue(node, ["type", "kind", "category"], "Concept");
1202
- const label = textValue(node, ["title", "label", "name"], id.replace(/^[^:]+:/, ""));
1203
- const summary = textValue(node, ["summary", "description", "snippet"]) || textValue(metadata, ["summary", "description", "relative_path", "filename"]);
1204
- const importance = clamp(numberValue(node, ["importance_norm", "importance", "score"]) || 0.5, 0.08, 1);
1205
- return [{ id, label, type, summary, importance }];
1206
- }).sort((left, right) => right.importance - left.importance);
1207
- const ids = new Set(nodes.map((node) => node.id));
1208
- const edges = rawEdges.flatMap((edge, index): RelationshipThread[] => {
1209
- const source = textValue(edge, ["from", "source", "source_id"]);
1210
- const target = textValue(edge, ["to", "target", "target_id"]);
1211
- if (!source || !target || !ids.has(source) || !ids.has(target)) return [];
1212
- return [{
1213
- id: textValue(edge, ["id"], `edge-${index}`),
1214
- source,
1215
- target,
1216
- label: titleValue(edge, ["type", "label", "relationship"], "Relates"),
1217
- weight: numberValue(edge, ["weight", "score", "confidence"]) || 1,
1218
- }];
1219
- });
1220
- return { nodes, edges };
1221
- }
1222
-
1223
- function currentModelName(data: unknown) {
1224
- const record = isRecord(data) ? data : {};
1225
- const current = textValue(record, ["current", "current_model", "local_model"]);
1226
- if (current) return current;
1227
- const loaded = asArray<ApiRecord>(record.loaded || record.loaded_models);
1228
- const firstLoaded = loaded.find((item) => item.id || item.name || item.model_id);
1229
- return firstLoaded ? textValue(firstLoaded, ["name", "id", "model_id"], "local mind") : "local mind";
1230
- }
1231
-
1232
- function portabilityLabel(data: unknown) {
1233
- const record = isRecord(data) ? data : {};
1234
- return textValue(record, ["archive_format", "format", "graph_schema_version", "schema_version"], ".latticebrain");
1235
- }
1236
-
1237
- function backupHealthLabel(data: unknown) {
1238
- const record = isRecord(data) ? data : {};
1239
- const count = record.count || record.backups || record.available;
1240
- if (count !== undefined && count !== null && count !== "") return `${count} backups`;
1241
- return "Backups ready";
1242
- }
1243
-
1244
- function summarizeCareResult(result: ApiResult) {
1245
- if (!result.ok) return result.error || "Brain care action could not complete.";
1246
- const data = isRecord(result.data) ? result.data : {};
1247
- const directMessage = textValue(data, ["message", "status", "path", "archive_path", "backup_path", "export_path"]);
1248
- if (directMessage) return directMessage;
1249
- return "Brain care action completed.";
1250
- }
1251
-
1252
- function renderLogRow(event: ApiRecord) {
1253
- const action = stringValue(event.action || event.event || event.type || event.name, "Event");
1254
- const actor = stringValue(event.actor || event.user || event.user_id || event.workspace_id, "system");
1255
- const when = stringValue(event.timestamp || event.time || event.created_at || event.ts, "recently");
1256
- return (
1257
- <>
1258
- <strong>{action}</strong>
1259
- <span>{actor} · {when}</span>
1260
- </>
1261
- );
1262
- }
1263
-
1264
- function sourceLabel(result?: ApiResult<unknown>) {
1265
- if (!result) return "Loading";
1266
- return result.ok ? "Live" : result.error || "Unavailable";
1267
- }
1268
-
1269
- function adminStatusLabel(data: unknown, key: string) {
1270
- const record = isRecord(data) ? data : {};
1271
- return textValue(record, [key, "health", "state", "overall_status"]);
1272
- }
1273
-
1274
- function indexDetail(data: unknown) {
1275
- const record = isRecord(data) ? data : {};
1276
- const docs = record.documents ?? record.document_count ?? record.docs;
1277
- const chunks = record.chunks ?? record.chunk_count ?? record.vectors;
1278
- if (docs !== undefined || chunks !== undefined) {
1279
- return `${stringValue(docs, "0")} docs · ${stringValue(chunks, "0")} chunks`;
1280
- }
1281
- return textValue(record, ["message", "detail", "status"], "Index status ready");
1282
- }
1283
-
1284
- function summaryText(data: unknown) {
1285
- const record = isRecord(data) ? data : {};
1286
- return textValue(record, ["summary", "message", "status", "detail"]);
1287
- }
1288
-
1289
- function stringValue(value: unknown, fallback = "") {
1290
- if (typeof value === "string" && value.trim()) return value;
1291
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
1292
- if (typeof value === "boolean") return value ? "true" : "false";
1293
- return fallback;
1294
- }
1295
-
1296
- function fileToDataUrl(file: File) {
1297
- return new Promise<string>((resolve, reject) => {
1298
- const reader = new FileReader();
1299
- reader.onload = () => resolve(String(reader.result || ""));
1300
- reader.onerror = () => reject(reader.error);
1301
- reader.readAsDataURL(file);
1302
- });
1303
- }
1304
-
1305
- function layoutGraphNodes(nodes: KnowledgeConcept[], radiusX: number, radiusY: number) {
1306
- return nodes.map((node, index) => {
1307
- const point = polarPoint(index, nodes.length, radiusX, radiusY, -88);
1308
- return { node, x: point.x, y: point.y };
1309
- });
1310
- }
1311
-
1312
- function polarPoint(index: number, total: number, radiusX: number, radiusY: number, offsetDegrees = -90) {
1313
- const count = Math.max(total, 1);
1314
- const angle = ((360 / count) * index + offsetDegrees) * Math.PI / 180;
1315
- return {
1316
- x: 50 + Math.cos(angle) * radiusX,
1317
- y: 50 + Math.sin(angle) * radiusY,
1318
- };
1319
- }
1320
-
1321
- function layerStyle(values: Record<string, string>) {
1322
- return values as React.CSSProperties;
1323
- }
1324
-
1325
- function uniqueById<T extends { id: string }>(items: T[]) {
1326
- const seen = new Set<string>();
1327
- return items.filter((item) => {
1328
- if (seen.has(item.id)) return false;
1329
- seen.add(item.id);
1330
- return true;
1331
- });
1332
- }
1333
-
1334
- function isRecord(value: unknown): value is ApiRecord {
1335
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
1336
- }
1337
-
1338
- function textValue(record: ApiRecord, keys: string[], fallback = "") {
1339
- for (const key of keys) {
1340
- const value = record[key];
1341
- if (typeof value === "string" && value.trim()) return value;
1342
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
1343
- }
1344
- return fallback;
1345
- }
1346
-
1347
- function titleValue(record: ApiRecord, keys: string[], fallback = "") {
1348
- const value = textValue(record, keys, fallback);
1349
- return value
1350
- .replace(/[_-]+/g, " ")
1351
- .replace(/\b\w/g, (character) => character.toUpperCase());
1352
- }
1353
-
1354
- function numberValue(record: ApiRecord, keys: string[]) {
1355
- for (const key of keys) {
1356
- const value = Number(record[key]);
1357
- if (Number.isFinite(value)) return value;
1358
- }
1359
- return 0;
1360
- }
1361
-
1362
84
  function clamp(value: number, min: number, max: number) {
1363
85
  return Math.max(min, Math.min(max, value));
1364
86
  }