claude-brain 0.17.13 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/VERSION +1 -1
  2. package/package.json +3 -1
  3. package/scripts/postinstall.mjs +80 -104
  4. package/src/cli/auto-setup.ts +1 -9
  5. package/src/cli/bin.ts +23 -2
  6. package/src/cli/commands/export.ts +130 -0
  7. package/src/cli/commands/reindex.ts +107 -0
  8. package/src/cli/commands/serve.ts +54 -0
  9. package/src/cli/commands/status.ts +158 -0
  10. package/src/code-intelligence/indexer.ts +315 -0
  11. package/src/code-intelligence/linker.ts +178 -0
  12. package/src/code-intelligence/parser.ts +484 -0
  13. package/src/code-intelligence/query.ts +291 -0
  14. package/src/code-intelligence/schema.ts +83 -0
  15. package/src/code-intelligence/types.ts +95 -0
  16. package/src/config/defaults.ts +3 -3
  17. package/src/config/loader.ts +6 -0
  18. package/src/config/schema.ts +28 -2
  19. package/src/health/index.ts +5 -2
  20. package/src/hooks/brain-hook.ts +4 -1
  21. package/src/hooks/context-hook.ts +69 -10
  22. package/src/hooks/installer.ts +4 -7
  23. package/src/intelligence/cross-project/index.ts +1 -7
  24. package/src/intelligence/prediction/index.ts +1 -7
  25. package/src/intelligence/reasoning/index.ts +1 -7
  26. package/src/memory/compression.ts +105 -0
  27. package/src/memory/fts5-search.ts +456 -0
  28. package/src/memory/index.ts +342 -38
  29. package/src/memory/migrations/add-fts5.ts +98 -0
  30. package/src/memory/pruning.ts +60 -0
  31. package/src/routing/intent-classifier.ts +58 -1
  32. package/src/routing/response-filter.ts +128 -0
  33. package/src/routing/router.ts +457 -54
  34. package/src/server/http-api.ts +319 -1
  35. package/src/server/providers/resources.ts +1 -42
  36. package/src/server/services.ts +113 -12
  37. package/src/server/web-viewer.ts +1115 -0
  38. package/src/setup/index.ts +12 -22
  39. package/src/tools/schemas.ts +1 -1
  40. package/src/intelligence/cross-project/affinity.ts +0 -159
  41. package/src/intelligence/cross-project/transfer.ts +0 -201
  42. package/src/intelligence/prediction/context-anticipator.ts +0 -198
  43. package/src/intelligence/prediction/decision-predictor.ts +0 -184
  44. package/src/intelligence/reasoning/counterfactual.ts +0 -248
  45. package/src/intelligence/reasoning/synthesizer.ts +0 -167
  46. package/src/setup/wizard.ts +0 -459
@@ -0,0 +1,1115 @@
1
+ /**
2
+ * Web Viewer for Claude Brain — Phase 30
3
+ * Single-page dashboard served at localhost:3333/
4
+ * Inline HTML/CSS/JS, no build step, no external dependencies.
5
+ */
6
+
7
+ import type { Hono } from 'hono'
8
+ import { getMemoryService, getVaultService, isServicesInitialized } from '@/server/services'
9
+ import type { CodeQuery } from '@/code-intelligence/query'
10
+
11
+ let _codeQuery: CodeQuery | null = null
12
+
13
+ export function setWebViewerCodeQuery(cq: CodeQuery): void {
14
+ _codeQuery = cq
15
+ }
16
+
17
+ export function setupWebViewer(app: Hono): void {
18
+ // Serve the viewer HTML
19
+ app.get('/', (c) => {
20
+ c.header('Content-Type', 'text/html; charset=utf-8')
21
+ return c.html(viewerHTML)
22
+ })
23
+ app.get('/viewer', (c) => {
24
+ c.header('Content-Type', 'text/html; charset=utf-8')
25
+ return c.html(viewerHTML)
26
+ })
27
+
28
+ // --- API endpoints for the web viewer ---
29
+
30
+ // Search endpoint — queries FTS5
31
+ app.get('/api/memory/search', async (c) => {
32
+ try {
33
+ const query = c.req.query('q') || ''
34
+ const project = c.req.query('project') || undefined
35
+ const category = c.req.query('category') || undefined
36
+ const limit = parseInt(c.req.query('limit') || '20', 10)
37
+
38
+ if (!query.trim()) {
39
+ return c.json({ success: true, data: [] })
40
+ }
41
+
42
+ if (!isServicesInitialized()) {
43
+ return c.json({ success: true, data: [] })
44
+ }
45
+
46
+ const memoryService = getMemoryService()
47
+ if (!memoryService?.isInitialized()) {
48
+ return c.json({ success: true, data: [] })
49
+ }
50
+
51
+ const fts5 = memoryService.fts5
52
+ if (fts5) {
53
+ let results = fts5.searchWithConfidence(query, project, limit)
54
+ if (category) {
55
+ results = results.filter(r => r.category === category)
56
+ }
57
+ return c.json({ success: true, data: results })
58
+ }
59
+
60
+ // Fallback to searchRaw
61
+ const results = await memoryService.searchRaw(query, { project, limit })
62
+ return c.json({ success: true, data: results })
63
+ } catch (error) {
64
+ return c.json({ success: false, error: 'Search failed' }, 500)
65
+ }
66
+ })
67
+
68
+ // Timeline endpoint — observations grouped by day
69
+ app.get('/api/memory/timeline', async (c) => {
70
+ try {
71
+ const project = c.req.query('project') || undefined
72
+ const days = parseInt(c.req.query('days') || '7', 10)
73
+
74
+ if (!isServicesInitialized()) {
75
+ return c.json({ success: true, data: {} })
76
+ }
77
+
78
+ const memoryService = getMemoryService()
79
+ if (!memoryService?.isInitialized() || !memoryService.fts5) {
80
+ return c.json({ success: true, data: {} })
81
+ }
82
+
83
+ const end = new Date()
84
+ const start = new Date(Date.now() - days * 86400000)
85
+
86
+ // We need a project for fetchByTimeRange; if none, list all projects and merge
87
+ let observations: any[] = []
88
+ if (project) {
89
+ observations = memoryService.fts5.fetchByTimeRange(project, start, end, 200)
90
+ } else {
91
+ // Fetch from all projects by doing a broad LIKE query on the db directly
92
+ try {
93
+ const db = memoryService.database.getDb()
94
+ const rows = db.prepare(`
95
+ SELECT * FROM observations
96
+ WHERE archived = 0 AND created_at >= ? AND created_at <= ?
97
+ ORDER BY created_at DESC
98
+ LIMIT 200
99
+ `).all(start.toISOString(), end.toISOString()) as any[]
100
+ observations = rows.map((row: any) => ({
101
+ id: row.id,
102
+ project: row.project,
103
+ category: row.category,
104
+ content: row.content,
105
+ reasoning: row.reasoning || null,
106
+ context: row.context || null,
107
+ confidence: row.confidence ?? 0.8,
108
+ source: row.source || 'explicit',
109
+ tags: row.tags ? safeParseJson(row.tags) : [],
110
+ file_paths: row.file_paths ? safeParseJson(row.file_paths) : [],
111
+ symbols: row.symbols ? safeParseJson(row.symbols) : [],
112
+ access_count: row.access_count ?? 0,
113
+ last_accessed: row.last_accessed || null,
114
+ created_at: row.created_at,
115
+ updated_at: row.updated_at,
116
+ archived: row.archived === 1
117
+ }))
118
+ } catch {
119
+ observations = []
120
+ }
121
+ }
122
+
123
+ // Group by day
124
+ const grouped: Record<string, any[]> = {}
125
+ for (const obs of observations) {
126
+ const day = obs.created_at?.slice(0, 10) || 'unknown'
127
+ if (!grouped[day]) grouped[day] = []
128
+ grouped[day].push(obs)
129
+ }
130
+
131
+ return c.json({ success: true, data: grouped })
132
+ } catch (error) {
133
+ return c.json({ success: false, error: 'Timeline failed' }, 500)
134
+ }
135
+ })
136
+
137
+ // Stats endpoint
138
+ app.get('/api/stats', async (c) => {
139
+ try {
140
+ if (!isServicesInitialized()) {
141
+ return c.json({
142
+ success: true,
143
+ data: {
144
+ totalObservations: 0,
145
+ projects: [],
146
+ categories: {},
147
+ activityLast24h: 0,
148
+ codeIndex: null
149
+ }
150
+ })
151
+ }
152
+
153
+ const memoryService = getMemoryService()
154
+ if (!memoryService?.isInitialized()) {
155
+ return c.json({
156
+ success: true,
157
+ data: {
158
+ totalObservations: 0,
159
+ projects: [],
160
+ categories: {},
161
+ activityLast24h: 0,
162
+ codeIndex: null
163
+ }
164
+ })
165
+ }
166
+
167
+ const db = memoryService.database.getDb()
168
+
169
+ // Total observations
170
+ const totalRow = db.prepare('SELECT COUNT(*) as cnt FROM observations WHERE archived = 0').get() as any
171
+ const totalObservations = totalRow?.cnt || 0
172
+
173
+ // Projects
174
+ const projectRows = db.prepare('SELECT DISTINCT project FROM observations WHERE archived = 0').all() as any[]
175
+ const projects = projectRows.map((p: any) => p.project).filter(Boolean)
176
+
177
+ // Categories breakdown
178
+ const catRows = db.prepare(
179
+ 'SELECT category, COUNT(*) as cnt FROM observations WHERE archived = 0 GROUP BY category'
180
+ ).all() as any[]
181
+ const categories: Record<string, number> = {}
182
+ for (const row of catRows) {
183
+ categories[row.category] = row.cnt
184
+ }
185
+
186
+ // Activity last 24h
187
+ const cutoff = new Date(Date.now() - 86400000).toISOString()
188
+ const activityRow = db.prepare(
189
+ 'SELECT COUNT(*) as cnt FROM observations WHERE created_at > ? AND archived = 0'
190
+ ).get(cutoff) as any
191
+ const activityLast24h = activityRow?.cnt || 0
192
+
193
+ // Code index stats (if available)
194
+ let codeIndex = null
195
+ if (_codeQuery) {
196
+ try {
197
+ // Try to get stats for the first project
198
+ const firstProject = projects[0]
199
+ if (firstProject) {
200
+ codeIndex = _codeQuery.getStats(firstProject)
201
+ }
202
+ } catch {
203
+ // Code intelligence may not be available
204
+ }
205
+ }
206
+
207
+ return c.json({
208
+ success: true,
209
+ data: {
210
+ totalObservations,
211
+ projects,
212
+ categories,
213
+ activityLast24h,
214
+ codeIndex
215
+ }
216
+ })
217
+ } catch (error) {
218
+ return c.json({ success: false, error: 'Stats failed' }, 500)
219
+ }
220
+ })
221
+
222
+ // Projects list (for filter dropdown)
223
+ app.get('/api/viewer/projects', async (c) => {
224
+ try {
225
+ if (!isServicesInitialized()) {
226
+ return c.json({ success: true, data: [] })
227
+ }
228
+
229
+ const memoryService = getMemoryService()
230
+ if (!memoryService?.isInitialized()) {
231
+ return c.json({ success: true, data: [] })
232
+ }
233
+
234
+ const db = memoryService.database.getDb()
235
+ const rows = db.prepare(
236
+ 'SELECT DISTINCT project FROM observations WHERE archived = 0 ORDER BY project'
237
+ ).all() as any[]
238
+ const projects = rows.map((r: any) => r.project).filter(Boolean)
239
+
240
+ return c.json({ success: true, data: projects })
241
+ } catch {
242
+ return c.json({ success: true, data: [] })
243
+ }
244
+ })
245
+ }
246
+
247
+ function safeParseJson(val: string): string[] {
248
+ try {
249
+ const parsed = JSON.parse(val)
250
+ return Array.isArray(parsed) ? parsed : []
251
+ } catch {
252
+ return val.split(',').map((s: string) => s.trim()).filter(Boolean)
253
+ }
254
+ }
255
+
256
+ // ─── The single-page HTML viewer ───────────────────────────────
257
+
258
+ const viewerHTML = `<!DOCTYPE html>
259
+ <html lang="en">
260
+ <head>
261
+ <meta charset="UTF-8">
262
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
263
+ <title>Claude Brain — Memory Viewer</title>
264
+ <style>
265
+ :root {
266
+ --bg: #0d1117;
267
+ --bg-card: #161b22;
268
+ --bg-input: #0d1117;
269
+ --bg-hover: #1c2333;
270
+ --border: #30363d;
271
+ --text: #e6edf3;
272
+ --text-dim: #8b949e;
273
+ --text-muted: #484f58;
274
+ --accent: #58a6ff;
275
+ --accent-dim: #1f6feb;
276
+ --green: #3fb950;
277
+ --orange: #d29922;
278
+ --red: #f85149;
279
+ --purple: #bc8cff;
280
+ --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
281
+ --mono: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
282
+ --radius: 6px;
283
+ }
284
+
285
+ * { margin: 0; padding: 0; box-sizing: border-box; }
286
+
287
+ body {
288
+ background: var(--bg);
289
+ color: var(--text);
290
+ font-family: var(--font);
291
+ font-size: 14px;
292
+ line-height: 1.5;
293
+ min-height: 100vh;
294
+ }
295
+
296
+ /* Header */
297
+ .header {
298
+ background: var(--bg-card);
299
+ border-bottom: 1px solid var(--border);
300
+ padding: 16px 24px;
301
+ display: flex;
302
+ align-items: center;
303
+ justify-content: space-between;
304
+ position: sticky;
305
+ top: 0;
306
+ z-index: 100;
307
+ }
308
+
309
+ .header-left {
310
+ display: flex;
311
+ align-items: center;
312
+ gap: 12px;
313
+ }
314
+
315
+ .logo {
316
+ font-size: 18px;
317
+ font-weight: 600;
318
+ color: var(--accent);
319
+ }
320
+
321
+ .version {
322
+ font-size: 12px;
323
+ color: var(--text-dim);
324
+ background: var(--bg);
325
+ padding: 2px 8px;
326
+ border-radius: 12px;
327
+ border: 1px solid var(--border);
328
+ }
329
+
330
+ .header-right {
331
+ display: flex;
332
+ align-items: center;
333
+ gap: 12px;
334
+ }
335
+
336
+ .status-dot {
337
+ width: 8px;
338
+ height: 8px;
339
+ border-radius: 50%;
340
+ background: var(--green);
341
+ display: inline-block;
342
+ }
343
+
344
+ .status-dot.offline { background: var(--red); }
345
+
346
+ /* Tabs */
347
+ .tabs {
348
+ display: flex;
349
+ background: var(--bg-card);
350
+ border-bottom: 1px solid var(--border);
351
+ padding: 0 24px;
352
+ }
353
+
354
+ .tab {
355
+ padding: 10px 16px;
356
+ cursor: pointer;
357
+ color: var(--text-dim);
358
+ border-bottom: 2px solid transparent;
359
+ font-size: 13px;
360
+ font-weight: 500;
361
+ transition: all 0.15s;
362
+ }
363
+
364
+ .tab:hover { color: var(--text); }
365
+ .tab.active { color: var(--accent); border-bottom-color: var(--accent); }
366
+
367
+ /* Main layout */
368
+ .main {
369
+ max-width: 1200px;
370
+ margin: 0 auto;
371
+ padding: 24px;
372
+ }
373
+
374
+ /* Stats bar */
375
+ .stats-bar {
376
+ display: grid;
377
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
378
+ gap: 16px;
379
+ margin-bottom: 24px;
380
+ }
381
+
382
+ .stat-card {
383
+ background: var(--bg-card);
384
+ border: 1px solid var(--border);
385
+ border-radius: var(--radius);
386
+ padding: 16px;
387
+ }
388
+
389
+ .stat-label {
390
+ color: var(--text-dim);
391
+ font-size: 12px;
392
+ text-transform: uppercase;
393
+ letter-spacing: 0.5px;
394
+ margin-bottom: 4px;
395
+ }
396
+
397
+ .stat-value {
398
+ font-size: 28px;
399
+ font-weight: 600;
400
+ color: var(--text);
401
+ }
402
+
403
+ .stat-sub {
404
+ font-size: 12px;
405
+ color: var(--text-muted);
406
+ margin-top: 4px;
407
+ }
408
+
409
+ /* Search section */
410
+ .search-section {
411
+ margin-bottom: 24px;
412
+ }
413
+
414
+ .search-row {
415
+ display: flex;
416
+ gap: 12px;
417
+ align-items: center;
418
+ }
419
+
420
+ .search-input {
421
+ flex: 1;
422
+ background: var(--bg-input);
423
+ border: 1px solid var(--border);
424
+ border-radius: var(--radius);
425
+ padding: 10px 14px;
426
+ color: var(--text);
427
+ font-size: 14px;
428
+ font-family: var(--font);
429
+ outline: none;
430
+ transition: border-color 0.15s;
431
+ }
432
+
433
+ .search-input:focus { border-color: var(--accent); }
434
+
435
+ .search-input::placeholder { color: var(--text-muted); }
436
+
437
+ select.filter-select {
438
+ background: var(--bg-input);
439
+ border: 1px solid var(--border);
440
+ border-radius: var(--radius);
441
+ padding: 10px 14px;
442
+ color: var(--text);
443
+ font-size: 13px;
444
+ font-family: var(--font);
445
+ outline: none;
446
+ cursor: pointer;
447
+ min-width: 140px;
448
+ }
449
+
450
+ select.filter-select:focus { border-color: var(--accent); }
451
+
452
+ .search-meta {
453
+ margin-top: 8px;
454
+ font-size: 12px;
455
+ color: var(--text-muted);
456
+ }
457
+
458
+ /* Results / Timeline */
459
+ .results-container {
460
+ display: flex;
461
+ flex-direction: column;
462
+ gap: 8px;
463
+ }
464
+
465
+ .observation-card {
466
+ background: var(--bg-card);
467
+ border: 1px solid var(--border);
468
+ border-radius: var(--radius);
469
+ padding: 16px;
470
+ cursor: pointer;
471
+ transition: all 0.15s;
472
+ }
473
+
474
+ .observation-card:hover {
475
+ border-color: var(--accent-dim);
476
+ background: var(--bg-hover);
477
+ }
478
+
479
+ .obs-header {
480
+ display: flex;
481
+ align-items: center;
482
+ justify-content: space-between;
483
+ margin-bottom: 8px;
484
+ }
485
+
486
+ .obs-badges {
487
+ display: flex;
488
+ gap: 6px;
489
+ align-items: center;
490
+ }
491
+
492
+ .badge {
493
+ font-size: 11px;
494
+ padding: 2px 8px;
495
+ border-radius: 12px;
496
+ font-weight: 500;
497
+ text-transform: uppercase;
498
+ letter-spacing: 0.3px;
499
+ }
500
+
501
+ .badge-decision { background: #1f3a5f; color: var(--accent); }
502
+ .badge-pattern { background: #2a1f3f; color: var(--purple); }
503
+ .badge-correction { background: #3f1f1f; color: var(--red); }
504
+ .badge-insight { background: #2a3f1f; color: var(--green); }
505
+ .badge-preference { background: #3f2a1f; color: var(--orange); }
506
+
507
+ .badge-project {
508
+ background: var(--bg);
509
+ color: var(--text-dim);
510
+ border: 1px solid var(--border);
511
+ }
512
+
513
+ .obs-date {
514
+ font-size: 12px;
515
+ color: var(--text-muted);
516
+ }
517
+
518
+ .obs-content {
519
+ color: var(--text);
520
+ font-size: 14px;
521
+ line-height: 1.6;
522
+ }
523
+
524
+ .obs-detail {
525
+ display: none;
526
+ margin-top: 12px;
527
+ padding-top: 12px;
528
+ border-top: 1px solid var(--border);
529
+ }
530
+
531
+ .obs-detail.open { display: block; }
532
+
533
+ .detail-row {
534
+ display: flex;
535
+ gap: 8px;
536
+ margin-bottom: 6px;
537
+ font-size: 13px;
538
+ }
539
+
540
+ .detail-label {
541
+ color: var(--text-dim);
542
+ min-width: 80px;
543
+ font-weight: 500;
544
+ }
545
+
546
+ .detail-value {
547
+ color: var(--text);
548
+ word-break: break-word;
549
+ }
550
+
551
+ .obs-score {
552
+ font-size: 12px;
553
+ color: var(--text-muted);
554
+ font-family: var(--mono);
555
+ }
556
+
557
+ /* Day group for timeline */
558
+ .day-group {
559
+ margin-bottom: 24px;
560
+ }
561
+
562
+ .day-header {
563
+ font-size: 13px;
564
+ font-weight: 600;
565
+ color: var(--text-dim);
566
+ padding: 8px 0;
567
+ border-bottom: 1px solid var(--border);
568
+ margin-bottom: 12px;
569
+ display: flex;
570
+ align-items: center;
571
+ gap: 8px;
572
+ }
573
+
574
+ .day-count {
575
+ background: var(--bg);
576
+ border: 1px solid var(--border);
577
+ border-radius: 12px;
578
+ padding: 1px 8px;
579
+ font-size: 11px;
580
+ color: var(--text-muted);
581
+ font-weight: 400;
582
+ }
583
+
584
+ /* Code map */
585
+ .code-file {
586
+ background: var(--bg-card);
587
+ border: 1px solid var(--border);
588
+ border-radius: var(--radius);
589
+ padding: 12px 16px;
590
+ margin-bottom: 6px;
591
+ font-family: var(--mono);
592
+ font-size: 13px;
593
+ display: flex;
594
+ align-items: center;
595
+ justify-content: space-between;
596
+ }
597
+
598
+ .code-file-path { color: var(--accent); }
599
+ .code-file-symbols { color: var(--text-dim); font-size: 12px; }
600
+
601
+ /* Empty state */
602
+ .empty-state {
603
+ text-align: center;
604
+ padding: 60px 20px;
605
+ color: var(--text-dim);
606
+ }
607
+
608
+ .empty-state-icon {
609
+ font-size: 40px;
610
+ margin-bottom: 16px;
611
+ opacity: 0.5;
612
+ }
613
+
614
+ .empty-state-title {
615
+ font-size: 16px;
616
+ font-weight: 600;
617
+ margin-bottom: 8px;
618
+ color: var(--text);
619
+ }
620
+
621
+ /* Loading */
622
+ .loading {
623
+ text-align: center;
624
+ padding: 40px;
625
+ color: var(--text-muted);
626
+ }
627
+
628
+ .spinner {
629
+ display: inline-block;
630
+ width: 20px;
631
+ height: 20px;
632
+ border: 2px solid var(--border);
633
+ border-top-color: var(--accent);
634
+ border-radius: 50%;
635
+ animation: spin 0.6s linear infinite;
636
+ }
637
+
638
+ @keyframes spin { to { transform: rotate(360deg); } }
639
+
640
+ /* Panel hidden */
641
+ .panel { display: none; }
642
+ .panel.active { display: block; }
643
+
644
+ /* Responsive */
645
+ @media (max-width: 768px) {
646
+ .main { padding: 16px; }
647
+ .stats-bar { grid-template-columns: repeat(2, 1fr); }
648
+ .search-row { flex-direction: column; }
649
+ select.filter-select { min-width: 100%; }
650
+ }
651
+ </style>
652
+ </head>
653
+ <body>
654
+
655
+ <div class="header">
656
+ <div class="header-left">
657
+ <span class="logo">Claude Brain</span>
658
+ <span class="version" id="version-badge">loading...</span>
659
+ </div>
660
+ <div class="header-right">
661
+ <span class="status-dot" id="status-dot"></span>
662
+ <span id="status-text" style="font-size:12px;color:var(--text-dim)">Connecting...</span>
663
+ </div>
664
+ </div>
665
+
666
+ <div class="tabs">
667
+ <div class="tab active" data-tab="dashboard" onclick="switchTab('dashboard')">Dashboard</div>
668
+ <div class="tab" data-tab="search" onclick="switchTab('search')">Search</div>
669
+ <div class="tab" data-tab="timeline" onclick="switchTab('timeline')">Timeline</div>
670
+ <div class="tab" data-tab="codemap" onclick="switchTab('codemap')">Code Map</div>
671
+ </div>
672
+
673
+ <div class="main">
674
+ <!-- Dashboard panel -->
675
+ <div class="panel active" id="panel-dashboard">
676
+ <div class="stats-bar" id="stats-bar">
677
+ <div class="stat-card">
678
+ <div class="stat-label">Total Observations</div>
679
+ <div class="stat-value" id="stat-total">--</div>
680
+ </div>
681
+ <div class="stat-card">
682
+ <div class="stat-label">Last 24 Hours</div>
683
+ <div class="stat-value" id="stat-24h">--</div>
684
+ </div>
685
+ <div class="stat-card">
686
+ <div class="stat-label">Projects</div>
687
+ <div class="stat-value" id="stat-projects">--</div>
688
+ </div>
689
+ <div class="stat-card">
690
+ <div class="stat-label">Code Index</div>
691
+ <div class="stat-value" id="stat-code">--</div>
692
+ <div class="stat-sub" id="stat-code-sub"></div>
693
+ </div>
694
+ </div>
695
+
696
+ <h3 style="margin-bottom:12px;color:var(--text-dim);font-size:13px;text-transform:uppercase;letter-spacing:0.5px">Category Breakdown</h3>
697
+ <div id="category-bars" style="margin-bottom:24px"></div>
698
+
699
+ <h3 style="margin-bottom:12px;color:var(--text-dim);font-size:13px;text-transform:uppercase;letter-spacing:0.5px">Recent Activity</h3>
700
+ <div id="recent-activity"></div>
701
+ </div>
702
+
703
+ <!-- Search panel -->
704
+ <div class="panel" id="panel-search">
705
+ <div class="search-section">
706
+ <div class="search-row">
707
+ <input class="search-input" id="search-input" type="text" placeholder="Search observations..." autocomplete="off">
708
+ <select class="filter-select" id="project-filter" onchange="doSearch()">
709
+ <option value="">All Projects</option>
710
+ </select>
711
+ <select class="filter-select" id="category-filter" onchange="doSearch()">
712
+ <option value="">All Categories</option>
713
+ <option value="decision">Decision</option>
714
+ <option value="pattern">Pattern</option>
715
+ <option value="correction">Correction</option>
716
+ <option value="insight">Insight</option>
717
+ <option value="preference">Preference</option>
718
+ </select>
719
+ </div>
720
+ <div class="search-meta" id="search-meta"></div>
721
+ </div>
722
+ <div class="results-container" id="search-results"></div>
723
+ </div>
724
+
725
+ <!-- Timeline panel -->
726
+ <div class="panel" id="panel-timeline">
727
+ <div class="search-section">
728
+ <div class="search-row">
729
+ <select class="filter-select" id="timeline-project" onchange="loadTimeline()">
730
+ <option value="">All Projects</option>
731
+ </select>
732
+ <select class="filter-select" id="timeline-days" onchange="loadTimeline()">
733
+ <option value="3">Last 3 days</option>
734
+ <option value="7" selected>Last 7 days</option>
735
+ <option value="14">Last 14 days</option>
736
+ <option value="30">Last 30 days</option>
737
+ </select>
738
+ </div>
739
+ </div>
740
+ <div id="timeline-container"></div>
741
+ </div>
742
+
743
+ <!-- Code Map panel -->
744
+ <div class="panel" id="panel-codemap">
745
+ <div class="search-section">
746
+ <div class="search-row">
747
+ <select class="filter-select" id="codemap-project" onchange="loadCodeMap()">
748
+ <option value="">Select project...</option>
749
+ </select>
750
+ </div>
751
+ </div>
752
+ <div id="codemap-container"></div>
753
+ </div>
754
+ </div>
755
+
756
+ <script>
757
+ // ─── State ──────────────────────────────────────────
758
+ let searchDebounce = null;
759
+
760
+ // ─── Tab switching ──────────────────────────────────
761
+ function switchTab(name) {
762
+ document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t.dataset.tab === name));
763
+ document.querySelectorAll('.panel').forEach(p => p.classList.toggle('active', p.id === 'panel-' + name));
764
+
765
+ if (name === 'timeline') loadTimeline();
766
+ if (name === 'codemap') loadCodeMap();
767
+ if (name === 'dashboard') loadDashboard();
768
+ }
769
+
770
+ // ─── API helpers ────────────────────────────────────
771
+ async function api(url) {
772
+ try {
773
+ const res = await fetch(url);
774
+ const data = await res.json();
775
+ return data;
776
+ } catch (err) {
777
+ console.error('API error:', url, err);
778
+ return { success: false, error: err.message };
779
+ }
780
+ }
781
+
782
+ // ─── Health check ───────────────────────────────────
783
+ async function checkHealth() {
784
+ const data = await api('/api/health');
785
+ const dot = document.getElementById('status-dot');
786
+ const text = document.getElementById('status-text');
787
+ if (data.success && data.initialized) {
788
+ dot.className = 'status-dot';
789
+ text.textContent = 'Connected';
790
+ } else if (data.success) {
791
+ dot.className = 'status-dot';
792
+ dot.style.background = 'var(--orange)';
793
+ text.textContent = 'Initializing...';
794
+ } else {
795
+ dot.className = 'status-dot offline';
796
+ text.textContent = 'Disconnected';
797
+ }
798
+ }
799
+
800
+ // ─── Load projects into filter dropdowns ────────────
801
+ async function loadProjects() {
802
+ const data = await api('/api/viewer/projects');
803
+ if (!data.success) return;
804
+
805
+ const selects = ['project-filter', 'timeline-project', 'codemap-project'];
806
+ for (const id of selects) {
807
+ const el = document.getElementById(id);
808
+ if (!el) continue;
809
+ const current = el.value;
810
+ // Keep first option
811
+ while (el.options.length > 1) el.remove(1);
812
+ for (const p of data.data) {
813
+ const opt = document.createElement('option');
814
+ opt.value = p;
815
+ opt.textContent = p;
816
+ el.appendChild(opt);
817
+ }
818
+ if (current) el.value = current;
819
+ }
820
+ }
821
+
822
+ // ─── Dashboard ──────────────────────────────────────
823
+ async function loadDashboard() {
824
+ const data = await api('/api/stats');
825
+ if (!data.success) return;
826
+
827
+ const d = data.data;
828
+ document.getElementById('stat-total').textContent = d.totalObservations || 0;
829
+ document.getElementById('stat-24h').textContent = d.activityLast24h || 0;
830
+ document.getElementById('stat-projects').textContent = d.projects?.length || 0;
831
+
832
+ if (d.codeIndex) {
833
+ document.getElementById('stat-code').textContent = d.codeIndex.totalFiles || 0;
834
+ document.getElementById('stat-code-sub').textContent =
835
+ (d.codeIndex.totalSymbols || 0) + ' symbols';
836
+ } else {
837
+ document.getElementById('stat-code').textContent = 'N/A';
838
+ document.getElementById('stat-code-sub').textContent = 'Not indexed';
839
+ }
840
+
841
+ // Category bars
842
+ const cats = d.categories || {};
843
+ const total = Object.values(cats).reduce((a, b) => a + b, 0) || 1;
844
+ const barsEl = document.getElementById('category-bars');
845
+ const catColors = {
846
+ decision: 'var(--accent)',
847
+ pattern: 'var(--purple)',
848
+ correction: 'var(--red)',
849
+ insight: 'var(--green)',
850
+ preference: 'var(--orange)'
851
+ };
852
+
853
+ let barsHTML = '';
854
+ for (const [cat, count] of Object.entries(cats).sort((a, b) => b[1] - a[1])) {
855
+ const pct = Math.round((count / total) * 100);
856
+ const color = catColors[cat] || 'var(--text-dim)';
857
+ barsHTML += '<div style="display:flex;align-items:center;gap:12px;margin-bottom:8px">' +
858
+ '<span style="min-width:90px;font-size:13px;color:var(--text-dim);text-transform:capitalize">' + esc(cat) + '</span>' +
859
+ '<div style="flex:1;height:20px;background:var(--bg);border-radius:4px;overflow:hidden;border:1px solid var(--border)">' +
860
+ '<div style="width:' + pct + '%;height:100%;background:' + color + ';opacity:0.7;border-radius:4px;transition:width 0.3s"></div>' +
861
+ '</div>' +
862
+ '<span style="min-width:60px;text-align:right;font-size:13px;color:var(--text);font-family:var(--mono)">' + count + '</span>' +
863
+ '</div>';
864
+ }
865
+ barsEl.innerHTML = barsHTML || '<div class="empty-state"><div class="empty-state-title">No observations yet</div></div>';
866
+
867
+ // Recent activity
868
+ const tData = await api('/api/memory/timeline?days=2');
869
+ const recentEl = document.getElementById('recent-activity');
870
+ if (tData.success) {
871
+ const all = [];
872
+ for (const [day, items] of Object.entries(tData.data)) {
873
+ for (const item of items) all.push(item);
874
+ }
875
+ all.sort((a, b) => b.created_at.localeCompare(a.created_at));
876
+ recentEl.innerHTML = renderObservations(all.slice(0, 10));
877
+ }
878
+ }
879
+
880
+ // ─── Search ─────────────────────────────────────────
881
+ const searchInput = document.getElementById('search-input');
882
+ searchInput.addEventListener('input', () => {
883
+ clearTimeout(searchDebounce);
884
+ searchDebounce = setTimeout(doSearch, 300);
885
+ });
886
+ searchInput.addEventListener('keydown', (e) => {
887
+ if (e.key === 'Enter') { clearTimeout(searchDebounce); doSearch(); }
888
+ });
889
+
890
+ async function doSearch() {
891
+ const query = searchInput.value.trim();
892
+ const project = document.getElementById('project-filter').value;
893
+ const category = document.getElementById('category-filter').value;
894
+ const resultsEl = document.getElementById('search-results');
895
+ const metaEl = document.getElementById('search-meta');
896
+
897
+ if (!query) {
898
+ resultsEl.innerHTML = '<div class="empty-state"><div class="empty-state-icon">&#128269;</div><div class="empty-state-title">Type to search</div><div>Search across all your observations, decisions, patterns, and corrections.</div></div>';
899
+ metaEl.textContent = '';
900
+ return;
901
+ }
902
+
903
+ resultsEl.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
904
+
905
+ const start = performance.now();
906
+ let url = '/api/memory/search?q=' + encodeURIComponent(query) + '&limit=30';
907
+ if (project) url += '&project=' + encodeURIComponent(project);
908
+ if (category) url += '&category=' + encodeURIComponent(category);
909
+
910
+ const data = await api(url);
911
+ const elapsed = Math.round(performance.now() - start);
912
+
913
+ if (!data.success || !data.data.length) {
914
+ resultsEl.innerHTML = '<div class="empty-state"><div class="empty-state-title">No results</div><div>Try different keywords or broaden your filters.</div></div>';
915
+ metaEl.textContent = 'Searched in ' + elapsed + 'ms';
916
+ return;
917
+ }
918
+
919
+ metaEl.textContent = data.data.length + ' result' + (data.data.length !== 1 ? 's' : '') + ' in ' + elapsed + 'ms';
920
+ resultsEl.innerHTML = renderObservations(data.data);
921
+ }
922
+
923
+ // ─── Timeline ───────────────────────────────────────
924
+ async function loadTimeline() {
925
+ const project = document.getElementById('timeline-project').value;
926
+ const days = document.getElementById('timeline-days').value;
927
+ const container = document.getElementById('timeline-container');
928
+
929
+ container.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
930
+
931
+ let url = '/api/memory/timeline?days=' + days;
932
+ if (project) url += '&project=' + encodeURIComponent(project);
933
+
934
+ const data = await api(url);
935
+
936
+ if (!data.success || !Object.keys(data.data).length) {
937
+ container.innerHTML = '<div class="empty-state"><div class="empty-state-title">No activity</div><div>No observations found for this period.</div></div>';
938
+ return;
939
+ }
940
+
941
+ // Sort days descending
942
+ const days_sorted = Object.keys(data.data).sort().reverse();
943
+ let html = '';
944
+
945
+ for (const day of days_sorted) {
946
+ const items = data.data[day];
947
+ const dateLabel = formatDayLabel(day);
948
+ html += '<div class="day-group">';
949
+ html += '<div class="day-header">' + esc(dateLabel) + ' <span class="day-count">' + items.length + '</span></div>';
950
+ html += renderObservations(items);
951
+ html += '</div>';
952
+ }
953
+
954
+ container.innerHTML = html;
955
+ }
956
+
957
+ // ─── Code Map ───────────────────────────────────────
958
+ async function loadCodeMap() {
959
+ const project = document.getElementById('codemap-project').value;
960
+ const container = document.getElementById('codemap-container');
961
+
962
+ if (!project) {
963
+ container.innerHTML = '<div class="empty-state"><div class="empty-state-title">Select a project</div><div>Choose a project to view its code map.</div></div>';
964
+ return;
965
+ }
966
+
967
+ container.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
968
+
969
+ const data = await api('/api/code/file-map?project=' + encodeURIComponent(project));
970
+
971
+ if (!data.success || !data.data?.map) {
972
+ container.innerHTML = '<div class="empty-state"><div class="empty-state-title">No code index</div><div>This project has not been indexed yet. Run the indexer first.</div></div>';
973
+ return;
974
+ }
975
+
976
+ const lines = data.data.map.split('\\n').filter(Boolean);
977
+ let html = '';
978
+ for (const line of lines) {
979
+ html += '<div class="code-file"><span class="code-file-path">' + esc(line) + '</span></div>';
980
+ }
981
+
982
+ container.innerHTML = html || '<div class="empty-state"><div class="empty-state-title">Empty index</div></div>';
983
+ }
984
+
985
+ // ─── Render helpers ─────────────────────────────────
986
+ function renderObservations(items) {
987
+ if (!items || items.length === 0) {
988
+ return '<div class="empty-state"><div class="empty-state-title">Nothing here</div></div>';
989
+ }
990
+
991
+ let html = '';
992
+ for (const item of items) {
993
+ const cat = item.category || 'insight';
994
+ const proj = item.project || '';
995
+ const content = item.content || '';
996
+ const reasoning = item.reasoning || '';
997
+ const context = item.context || '';
998
+ const score = item.score != null ? item.score.toFixed(2) : '';
999
+ const date = item.created_at ? formatDate(item.created_at) : '';
1000
+ const tags = item.tags || [];
1001
+ const id = item.id || '';
1002
+
1003
+ html += '<div class="observation-card" onclick="toggleDetail(this)">';
1004
+ html += '<div class="obs-header">';
1005
+ html += '<div class="obs-badges">';
1006
+ html += '<span class="badge badge-' + esc(cat) + '">' + esc(cat) + '</span>';
1007
+ if (proj) html += '<span class="badge badge-project">' + esc(proj) + '</span>';
1008
+ if (score) html += '<span class="obs-score">' + score + '</span>';
1009
+ html += '</div>';
1010
+ html += '<span class="obs-date">' + esc(date) + '</span>';
1011
+ html += '</div>';
1012
+ html += '<div class="obs-content">' + esc(truncate(content, 200)) + '</div>';
1013
+
1014
+ // Expandable detail
1015
+ html += '<div class="obs-detail">';
1016
+ if (content.length > 200) {
1017
+ html += '<div class="detail-row"><span class="detail-label">Full text</span><span class="detail-value">' + esc(content) + '</span></div>';
1018
+ }
1019
+ if (reasoning) {
1020
+ html += '<div class="detail-row"><span class="detail-label">Reasoning</span><span class="detail-value">' + esc(reasoning) + '</span></div>';
1021
+ }
1022
+ if (context) {
1023
+ html += '<div class="detail-row"><span class="detail-label">Context</span><span class="detail-value">' + esc(context) + '</span></div>';
1024
+ }
1025
+ if (tags.length > 0) {
1026
+ html += '<div class="detail-row"><span class="detail-label">Tags</span><span class="detail-value">' + tags.map(t => esc(t)).join(', ') + '</span></div>';
1027
+ }
1028
+ if (id) {
1029
+ html += '<div class="detail-row"><span class="detail-label">ID</span><span class="detail-value" style="font-family:var(--mono);font-size:12px;color:var(--text-muted)">' + esc(id) + '</span></div>';
1030
+ }
1031
+ html += '</div>';
1032
+
1033
+ html += '</div>';
1034
+ }
1035
+ return html;
1036
+ }
1037
+
1038
+ function toggleDetail(card) {
1039
+ const detail = card.querySelector('.obs-detail');
1040
+ if (detail) detail.classList.toggle('open');
1041
+ }
1042
+
1043
+ function esc(str) {
1044
+ if (!str) return '';
1045
+ return String(str)
1046
+ .replace(/&/g, '&amp;')
1047
+ .replace(/</g, '&lt;')
1048
+ .replace(/>/g, '&gt;')
1049
+ .replace(/"/g, '&quot;');
1050
+ }
1051
+
1052
+ function truncate(str, len) {
1053
+ if (!str) return '';
1054
+ return str.length > len ? str.slice(0, len) + '...' : str;
1055
+ }
1056
+
1057
+ function formatDate(iso) {
1058
+ try {
1059
+ const d = new Date(iso);
1060
+ const now = new Date();
1061
+ const diffMs = now - d;
1062
+ const diffMin = Math.floor(diffMs / 60000);
1063
+ if (diffMin < 1) return 'just now';
1064
+ if (diffMin < 60) return diffMin + 'm ago';
1065
+ const diffH = Math.floor(diffMin / 60);
1066
+ if (diffH < 24) return diffH + 'h ago';
1067
+ const diffD = Math.floor(diffH / 24);
1068
+ if (diffD === 1) return 'yesterday';
1069
+ if (diffD < 30) return diffD + 'd ago';
1070
+ return d.toLocaleDateString();
1071
+ } catch { return iso; }
1072
+ }
1073
+
1074
+ function formatDayLabel(dayStr) {
1075
+ try {
1076
+ const d = new Date(dayStr + 'T00:00:00');
1077
+ const today = new Date();
1078
+ today.setHours(0,0,0,0);
1079
+ const yesterday = new Date(today);
1080
+ yesterday.setDate(yesterday.getDate() - 1);
1081
+
1082
+ if (d.getTime() === today.getTime()) return 'Today';
1083
+ if (d.getTime() === yesterday.getTime()) return 'Yesterday';
1084
+
1085
+ return d.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' });
1086
+ } catch { return dayStr; }
1087
+ }
1088
+
1089
+ // ─── Init ───────────────────────────────────────────
1090
+ async function init() {
1091
+ await checkHealth();
1092
+ await loadProjects();
1093
+ await loadDashboard();
1094
+
1095
+ // Version badge
1096
+ try {
1097
+ const health = await api('/api/health');
1098
+ document.getElementById('version-badge').textContent = health.version || 'v0';
1099
+ } catch {
1100
+ document.getElementById('version-badge').textContent = '';
1101
+ }
1102
+
1103
+ // Set initial search state
1104
+ document.getElementById('search-results').innerHTML =
1105
+ '<div class="empty-state"><div class="empty-state-icon">&#128269;</div><div class="empty-state-title">Type to search</div><div>Search across all your observations, decisions, patterns, and corrections.</div></div>';
1106
+
1107
+ // Refresh health every 30s
1108
+ setInterval(checkHealth, 30000);
1109
+ }
1110
+
1111
+ init();
1112
+ </script>
1113
+ </body>
1114
+ </html>`
1115
+