neuralbrain 0.0.0-stage → 0.0.1

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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +106 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,4208 @@
1
+ export const dashboardJs = `
2
+ // Neuralbrain - Operator Command Center Frontend Logic
3
+ // Built with 100% safe DOM methods (createElement, textContent, replaceChildren)
4
+ // ZERO innerHTML, ZERO outerHTML, ZERO localStorage, ZERO alert/confirm/prompt
5
+
6
+ (function () {
7
+ 'use strict';
8
+
9
+ // State
10
+ let statsData = null;
11
+ let activeTab = 'overview';
12
+ let activeSubTab = 'trajectories';
13
+ let activeNotesCategory = 'all';
14
+ let activeShortSubTab = 'sessions';
15
+ let graphData = null;
16
+ let selectedGraphNodeId = null;
17
+ let isReembedding = false;
18
+
19
+ // In-memory authentication state (zero localStorage per SecureCoder rules)
20
+ let inMemoryApiKey = '';
21
+ let isBootstrapRequired = false;
22
+ let isSessionAuthenticated = false;
23
+ let sessionKeyName = '';
24
+
25
+ async function apiFetch(url, options = {}) {
26
+ const headers = new Headers(options.headers || {});
27
+ if (inMemoryApiKey && !headers.has('Authorization')) {
28
+ headers.set('Authorization', 'Bearer ' + inMemoryApiKey);
29
+ }
30
+ if (!headers.has('X-Requested-With')) {
31
+ headers.set('X-Requested-With', 'XMLHttpRequest');
32
+ }
33
+ const resp = await fetch(url, { credentials: 'same-origin', ...options, headers });
34
+ if (resp.status === 401 && !url.includes('/dashboard/api/session')) {
35
+ isSessionAuthenticated = false;
36
+ updateAuthStatusUI();
37
+ }
38
+ return resp;
39
+ }
40
+
41
+ async function checkAuthStatus() {
42
+ try {
43
+ const resp = await fetch('/dashboard/api/auth-status', {
44
+ headers: { 'X-Requested-With': 'XMLHttpRequest' }
45
+ });
46
+ if (resp.ok) {
47
+ const data = await resp.json();
48
+ isBootstrapRequired = Boolean(data.bootstrap_required);
49
+ if (data.authenticated) {
50
+ isSessionAuthenticated = true;
51
+ sessionKeyName = data.session_key_name || 'Active';
52
+ } else {
53
+ isSessionAuthenticated = false;
54
+ }
55
+ updateAuthStatusUI();
56
+ }
57
+ } catch {
58
+ // ignore
59
+ }
60
+ }
61
+
62
+ function updateAuthStatusUI() {
63
+ const apiKeyForm = document.getElementById('formDashboardApiKey');
64
+ const apiKeyInput = document.getElementById('inputDashboardApiKey');
65
+ const btnSubmit = document.getElementById('btnSubmitApiKey');
66
+ const btnGenApiKey = document.getElementById('btnGenerateApiKey');
67
+ const sessionCluster = document.getElementById('authSessionCluster');
68
+ const sessionText = document.getElementById('authSessionText');
69
+
70
+ if (isBootstrapRequired) {
71
+ if (sessionCluster) sessionCluster.classList.add('hidden');
72
+ if (apiKeyForm) apiKeyForm.classList.remove('hidden');
73
+ if (apiKeyInput) {
74
+ apiKeyInput.placeholder = 'Click "+ Claim First Key"';
75
+ apiKeyInput.disabled = true;
76
+ }
77
+ if (btnSubmit) btnSubmit.classList.add('hidden');
78
+ if (btnGenApiKey) {
79
+ btnGenApiKey.textContent = '+ Claim First API Key';
80
+ btnGenApiKey.className = 'btn btn-primary';
81
+ btnGenApiKey.title = 'Initial Setup: Claim initial operator API key';
82
+ }
83
+ } else if (isSessionAuthenticated || inMemoryApiKey) {
84
+ // Authenticated! Hide the input field and form, clear the input, and display session cluster
85
+ if (apiKeyForm) apiKeyForm.classList.add('hidden');
86
+ if (apiKeyInput) {
87
+ apiKeyInput.value = '';
88
+ apiKeyInput.disabled = false;
89
+ }
90
+ if (sessionCluster) sessionCluster.classList.remove('hidden');
91
+ if (sessionText) {
92
+ sessionText.textContent = 'KEY: ' + (sessionKeyName || 'Active');
93
+ }
94
+ if (btnGenApiKey) {
95
+ btnGenApiKey.textContent = '+ Generate API Key';
96
+ btnGenApiKey.className = 'btn btn-emerald';
97
+ btnGenApiKey.title = 'Generate client API key';
98
+ }
99
+ } else {
100
+ // Unauthenticated: Show input form and Apply button, hide session cluster
101
+ if (sessionCluster) sessionCluster.classList.add('hidden');
102
+ if (apiKeyForm) apiKeyForm.classList.remove('hidden');
103
+ if (apiKeyInput) {
104
+ apiKeyInput.disabled = false;
105
+ apiKeyInput.placeholder = 'Paste API Key to Authenticate';
106
+ }
107
+ if (btnSubmit) {
108
+ btnSubmit.classList.remove('hidden');
109
+ btnSubmit.textContent = 'Apply';
110
+ }
111
+ if (btnGenApiKey) {
112
+ btnGenApiKey.textContent = '+ Generate API Key';
113
+ btnGenApiKey.className = 'btn btn-emerald';
114
+ btnGenApiKey.title = 'Generate client API key (requires authenticated window)';
115
+ }
116
+ }
117
+ }
118
+
119
+ // DOM Helper: Safe Element Construction
120
+ function el(tag, attrs, ...children) {
121
+ const node = document.createElement(tag);
122
+ if (attrs) {
123
+ for (const [key, val] of Object.entries(attrs)) {
124
+ if (key === 'className' || key === 'class') {
125
+ node.className = val;
126
+ } else if (key === 'textContent') {
127
+ node.textContent = val;
128
+ } else if (key.startsWith('on') && typeof val === 'function') {
129
+ node.addEventListener(key.slice(2).toLowerCase(), val);
130
+ } else if (key === 'style' && typeof val === 'object') {
131
+ Object.assign(node.style, val);
132
+ } else if (val !== null && val !== undefined && val !== false) {
133
+ node.setAttribute(key, val === true ? '' : String(val));
134
+ }
135
+ }
136
+ }
137
+ for (const child of children) {
138
+ if (child === null || child === undefined || child === false) continue;
139
+ if (typeof child === 'string' || typeof child === 'number') {
140
+ node.appendChild(document.createTextNode(String(child)));
141
+ } else if (child instanceof Node) {
142
+ node.appendChild(child);
143
+ } else if (Array.isArray(child)) {
144
+ for (const c of child) {
145
+ if (c instanceof Node) node.appendChild(c);
146
+ else if (typeof c === 'string' || typeof c === 'number') {
147
+ node.appendChild(document.createTextNode(String(c)));
148
+ }
149
+ }
150
+ }
151
+ }
152
+ return node;
153
+ }
154
+
155
+ // Safe Badge Helper
156
+ function createBadge(text, variant = 'subtle', isMono = false) {
157
+ const b = el('span', { className: 'badge badge-' + variant + (isMono ? ' badge-mono' : '') },
158
+ el('span', { className: 'badge-dot' }),
159
+ text
160
+ );
161
+ return b;
162
+ }
163
+
164
+ // Toast Notification System (replaces native alert/confirm)
165
+ function showToast(message, variant = 'emerald', durationMs = 4500) {
166
+ const container = document.getElementById('toastContainer');
167
+ if (!container) return;
168
+
169
+ const toast = el('div', { className: 'toast toast-' + variant });
170
+ const textSpan = el('span', { textContent: message });
171
+ const closeBtn = el('button', {
172
+ className: 'toast-close-btn',
173
+ title: 'Dismiss',
174
+ onClick: () => toast.remove()
175
+ }, '×');
176
+
177
+ toast.appendChild(textSpan);
178
+ toast.appendChild(closeBtn);
179
+ container.appendChild(toast);
180
+
181
+ setTimeout(() => {
182
+ if (toast.parentElement) {
183
+ toast.remove();
184
+ }
185
+ }, durationMs);
186
+ }
187
+
188
+ // Modal Dialog System (replaces native alert/confirm/prompt)
189
+ function showModal(title, bodyNodes, footerButtons = []) {
190
+ const container = document.getElementById('modalContainer');
191
+ if (!container) return;
192
+
193
+ container.replaceChildren();
194
+
195
+ const dialog = el('div', { className: 'modal-dialog' });
196
+
197
+ // Header
198
+ const header = el('div', { className: 'modal-header' },
199
+ el('h3', { className: 'modal-title', textContent: title }),
200
+ el('button', {
201
+ className: 'btn',
202
+ style: { height: '32px', width: '32px', padding: '0' },
203
+ onClick: closeModal
204
+ }, '✕')
205
+ );
206
+
207
+ // Body
208
+ const body = el('div', { className: 'modal-body' });
209
+ if (Array.isArray(bodyNodes)) {
210
+ body.append(...bodyNodes);
211
+ } else if (bodyNodes instanceof Node) {
212
+ body.appendChild(bodyNodes);
213
+ }
214
+
215
+ // Footer
216
+ const footer = el('div', { className: 'modal-footer' });
217
+ const defaultCancel = el('button', { className: 'btn', onClick: closeModal }, 'Cancel');
218
+ footer.appendChild(defaultCancel);
219
+
220
+ for (const btnDef of footerButtons) {
221
+ const btn = el('button', {
222
+ className: 'btn ' + (btnDef.variant ? 'btn-' + btnDef.variant : 'btn-primary'),
223
+ textContent: btnDef.label,
224
+ onClick: async (e) => {
225
+ if (btnDef.onClick) {
226
+ await btnDef.onClick(e, closeModal);
227
+ }
228
+ }
229
+ });
230
+ footer.appendChild(btn);
231
+ }
232
+
233
+ dialog.appendChild(header);
234
+ dialog.appendChild(body);
235
+ dialog.appendChild(footer);
236
+
237
+ container.appendChild(dialog);
238
+ container.classList.add('open');
239
+ container.style.display = 'flex';
240
+ }
241
+
242
+ function closeModal() {
243
+ const container = document.getElementById('modalContainer');
244
+ if (container) {
245
+ container.classList.remove('open');
246
+ container.style.display = 'none';
247
+ container.replaceChildren();
248
+ }
249
+ }
250
+
251
+ // Format Unix Timestamp or ISO/SQLite Datetime String
252
+ function formatTimestamp(ts) {
253
+ if (ts === null || ts === undefined || ts === '') return 'never';
254
+ let d;
255
+ if (typeof ts === 'number') {
256
+ d = new Date(ts * 1000);
257
+ } else if (typeof ts === 'string') {
258
+ const trimmed = ts.trim();
259
+ if (!trimmed) return 'never';
260
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
261
+ d = new Date(Number(trimmed) * 1000);
262
+ } else if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(trimmed)) {
263
+ const normalized = trimmed.replace(' ', 'T');
264
+ d = new Date(/[zZ]|[+-]\d{2}:?\d{2}$/.test(normalized) ? normalized : normalized + 'Z');
265
+ } else {
266
+ d = new Date(trimmed);
267
+ }
268
+ } else {
269
+ return String(ts);
270
+ }
271
+ if (Number.isNaN(d.getTime())) return String(ts);
272
+ return d.toLocaleString(undefined, {
273
+ month: 'short',
274
+ day: 'numeric',
275
+ hour: '2-digit',
276
+ minute: '2-digit',
277
+ second: '2-digit'
278
+ });
279
+ }
280
+
281
+ // Tab Navigation Handling
282
+ function initTabs() {
283
+ const tabButtons = document.querySelectorAll('.nav-tab-btn');
284
+ tabButtons.forEach((btn) => {
285
+ btn.addEventListener('click', () => {
286
+ const tabKey = btn.getAttribute('data-tab');
287
+ if (!tabKey) return;
288
+ switchTab(tabKey);
289
+ });
290
+ });
291
+
292
+ const subTabButtons = document.querySelectorAll('#paneTrajectories button[data-subtab]');
293
+ subTabButtons.forEach((btn) => {
294
+ btn.addEventListener('click', () => {
295
+ const subTabKey = btn.getAttribute('data-subtab');
296
+ if (!subTabKey) return;
297
+ switchSubTab(subTabKey);
298
+ });
299
+ });
300
+
301
+ const shortSubTabButtons = document.querySelectorAll('#paneShortTerm button[data-short-subtab]');
302
+ shortSubTabButtons.forEach((btn) => {
303
+ btn.addEventListener('click', () => {
304
+ const subTabKey = btn.getAttribute('data-short-subtab');
305
+ if (!subTabKey) return;
306
+ switchShortSubTab(subTabKey);
307
+ });
308
+ });
309
+
310
+ const btnScopeRepair = document.getElementById('btnScopeGoRepair');
311
+ if (btnScopeRepair) {
312
+ btnScopeRepair.addEventListener('click', () => {
313
+ switchTab('notes');
314
+ activeNotesCategory = 'unknown';
315
+ updateNotesCategoryPills();
316
+ const filterSelect = document.getElementById('notesFilterScope');
317
+ if (filterSelect) filterSelect.value = 'unknown';
318
+ applyNotesFilter();
319
+ });
320
+ }
321
+
322
+ const btnShowRepairQueue = document.getElementById('btnShowRepairQueue');
323
+ if (btnShowRepairQueue) {
324
+ btnShowRepairQueue.addEventListener('click', () => {
325
+ activeNotesCategory = 'unknown';
326
+ updateNotesCategoryPills();
327
+ const filterSelect = document.getElementById('notesFilterScope');
328
+ if (filterSelect) filterSelect.value = 'unknown';
329
+ applyNotesFilter();
330
+ });
331
+ }
332
+ }
333
+
334
+ function switchTab(tabKey) {
335
+ activeTab = tabKey;
336
+ document.querySelectorAll('.nav-tab-btn').forEach((btn) => {
337
+ if (btn.getAttribute('data-tab') === tabKey) {
338
+ btn.classList.add('active');
339
+ } else {
340
+ btn.classList.remove('active');
341
+ }
342
+ });
343
+
344
+ document.querySelectorAll('.tab-pane').forEach((pane) => {
345
+ pane.classList.remove('active');
346
+ });
347
+
348
+ const targetPane = document.getElementById('pane' + tabKey.charAt(0).toUpperCase() + tabKey.slice(1));
349
+ if (targetPane) {
350
+ targetPane.classList.add('active');
351
+ }
352
+
353
+ if (tabKey === 'notes') {
354
+ renderNotesTab();
355
+ } else if (tabKey === 'shortTerm') {
356
+ renderShortTermSubView();
357
+ } else if (tabKey === 'trajectories') {
358
+ renderTrajectoriesSubView();
359
+ } else if (tabKey === 'graph') {
360
+ loadGraph();
361
+ } else if (tabKey === 'conformance') {
362
+ renderFailurePatternsTable();
363
+ renderDeadLettersSection();
364
+ }
365
+ }
366
+
367
+ function refreshActiveTab() {
368
+ if (activeTab === 'notes') {
369
+ renderNotesTab();
370
+ } else if (activeTab === 'shortTerm') {
371
+ renderShortTermSubView();
372
+ } else if (activeTab === 'trajectories') {
373
+ renderTrajectoriesSubView();
374
+ } else if (activeTab === 'graph') {
375
+ loadGraph();
376
+ } else if (activeTab === 'conformance') {
377
+ renderFailurePatternsTable();
378
+ renderDeadLettersSection();
379
+ }
380
+ }
381
+
382
+ function switchSubTab(subTabKey, highlightId = null) {
383
+ activeSubTab = subTabKey;
384
+ const subTabButtons = document.querySelectorAll('#paneTrajectories button[data-subtab]');
385
+ subTabButtons.forEach((btn) => {
386
+ if (btn.getAttribute('data-subtab') === subTabKey) {
387
+ btn.className = 'btn btn-primary';
388
+ } else {
389
+ btn.className = 'btn';
390
+ }
391
+ });
392
+ renderTrajectoriesSubView(highlightId);
393
+ }
394
+
395
+ // Fetch Full Dashboard Stats Snapshot
396
+ let isFetchingStats = false;
397
+ async function fetchStats() {
398
+ if (isFetchingStats) return;
399
+ isFetchingStats = true;
400
+ try {
401
+ const resp = await apiFetch('/dashboard/api/stats');
402
+ if (resp.status === 401) {
403
+ isSessionAuthenticated = false;
404
+ updateAuthStatusUI();
405
+ showToast('Authentication required: Enter Bearer API key in the top header.', 'amber', 8000);
406
+ const apiKeyInput = document.getElementById('inputDashboardApiKey');
407
+ if (apiKeyInput) {
408
+ apiKeyInput.focus();
409
+ }
410
+ return;
411
+ }
412
+ if (!resp.ok) {
413
+ throw new Error('Stats request failed: ' + resp.status + ' ' + resp.statusText);
414
+ }
415
+ statsData = await resp.json();
416
+ syncKnownProjects();
417
+ syncTaskTypes();
418
+ renderHeaderAndOverview();
419
+ } catch (err) {
420
+ showToast('Error fetching dashboard stats: ' + err.message, 'rose');
421
+ } finally {
422
+ isFetchingStats = false;
423
+ }
424
+ }
425
+
426
+ // Render Header & Tab 1 Overview
427
+ function renderHeaderAndOverview() {
428
+ if (!statsData) return;
429
+
430
+ const health = statsData.health || {};
431
+ const counts = statsData.counts || {};
432
+ const storeMeta = health.store_meta || {};
433
+
434
+ // 1. Header Badges
435
+ const healthBadge = document.getElementById('healthBadge');
436
+ const healthText = document.getElementById('healthText');
437
+ if (healthBadge && healthText) {
438
+ if (health.status === 'ok') {
439
+ healthBadge.className = 'badge badge-emerald';
440
+ healthText.textContent = 'HEALTH: OK';
441
+ } else {
442
+ healthBadge.className = 'badge badge-rose';
443
+ healthText.textContent = 'HEALTH: DEGRADED';
444
+ }
445
+ }
446
+
447
+ const storeMetaBadge = document.getElementById('storeMetaBadge');
448
+ const storeMetaText = document.getElementById('storeMetaText');
449
+ if (storeMetaBadge && storeMetaText) {
450
+ const tier = storeMeta.embed_tier || 'none';
451
+ const dim = storeMeta.embed_dim || 0;
452
+ const modelId = storeMeta.embed_model_id || 'none';
453
+ storeMetaText.textContent = 'STORE: ' + tier + ' (' + dim + 'd: ' + modelId + ')';
454
+ if (storeMeta.match === false) {
455
+ storeMetaBadge.className = 'badge badge-rose badge-mono';
456
+ } else {
457
+ storeMetaBadge.className = 'badge badge-cyan badge-mono';
458
+ }
459
+ }
460
+
461
+ const qdrantBadge = document.getElementById('qdrantBadge');
462
+ const qdrantText = document.getElementById('qdrantText');
463
+ if (qdrantBadge && qdrantText) {
464
+ const qStatus = health.qdrant || 'offline';
465
+ qdrantText.textContent = 'QDRANT: ' + qStatus.toUpperCase();
466
+ qdrantBadge.className = qStatus === 'ok' ? 'badge badge-emerald badge-mono' : 'badge badge-amber badge-mono';
467
+ qdrantBadge.title = qStatus === 'ok'
468
+ ? 'Qdrant vector index is connected on port 6333'
469
+ : 'Qdrant is offline (BM25 + SQL search active). For vector search, run: docker compose up -d qdrant';
470
+ }
471
+
472
+ // 1b. Re-embed Status Badge & Auto-resume Polling
473
+ const reembedStatus = health.reembed_status || null;
474
+ updateReembedUI(reembedStatus);
475
+ if (reembedStatus && reembedStatus.status === 'running' && !isReembedding) {
476
+ pollReembedProgress();
477
+ }
478
+
479
+ // 2. Loud Mismatch Warning Banner
480
+ const mismatchBanner = document.getElementById('mismatchBanner');
481
+ const mismatchReasonText = document.getElementById('mismatchReasonText');
482
+ if (mismatchBanner && mismatchReasonText) {
483
+ if (storeMeta.match === false) {
484
+ mismatchBanner.classList.add('visible');
485
+ mismatchBanner.style.display = 'flex';
486
+ mismatchReasonText.textContent = storeMeta.mismatch_reason ||
487
+ 'Configured embedder differs from pinned store_meta. Vector search is disabled (SQL and BM25 remain active).';
488
+ } else {
489
+ mismatchBanner.classList.remove('visible');
490
+ mismatchBanner.style.display = 'none';
491
+ }
492
+ }
493
+
494
+ // 3. Tab Badge for Repair Queue
495
+ const repairBadge = document.getElementById('repairQueueBadge');
496
+ const unknownNotesCount = counts.notes ? counts.notes.unknown : 0;
497
+ if (repairBadge) {
498
+ repairBadge.textContent = String(unknownNotesCount);
499
+ if (unknownNotesCount > 0) {
500
+ repairBadge.classList.add('visible');
501
+ repairBadge.style.display = 'inline-block';
502
+ } else {
503
+ repairBadge.classList.remove('visible');
504
+ repairBadge.style.display = 'none';
505
+ }
506
+ }
507
+
508
+ // 4. KPI Grid Cards
509
+ const kpiGrid = document.getElementById('overviewKpiGrid');
510
+ if (kpiGrid) {
511
+ kpiGrid.replaceChildren();
512
+
513
+ // Helper for type_distribution counts
514
+ const typeDist = Array.isArray(statsData.type_distribution) ? statsData.type_distribution : [];
515
+ const sumTypes = (types) => typeDist
516
+ .filter((t) => types.includes(t.type))
517
+ .reduce((acc, t) => acc + (Number(t.count) || 0), 0);
518
+
519
+ // Card 0a: Short-Term (Sessions & Next Actions)
520
+ const activeSessions = (statsData.sessions && typeof statsData.sessions.active === 'number')
521
+ ? statsData.sessions.active
522
+ : (counts.sessions && typeof counts.sessions.active === 'number')
523
+ ? counts.sessions.active
524
+ : (statsData.short_term && typeof statsData.short_term.active_sessions === 'number' ? statsData.short_term.active_sessions : 0);
525
+ const readyActions = (statsData.actions && typeof statsData.actions.ready === 'number')
526
+ ? statsData.actions.ready
527
+ : (counts.actions && typeof counts.actions.ready === 'number')
528
+ ? counts.actions.ready
529
+ : (statsData.short_term && typeof statsData.short_term.ready_actions === 'number' ? statsData.short_term.ready_actions : 0);
530
+
531
+ kpiGrid.appendChild(createKpiCard(
532
+ 'Short-Term (Working)',
533
+ activeSessions + readyActions,
534
+ [
535
+ el('span', { className: 'badge ' + (activeSessions > 0 ? 'badge-emerald' : 'badge-subtle') + ' badge-mono' }, activeSessions + ' active sessions'),
536
+ el('span', { className: 'badge ' + (readyActions > 0 ? 'badge-amber' : 'badge-subtle') + ' badge-mono' }, readyActions + ' ready next actions')
537
+ ]
538
+ ));
539
+
540
+ // Card 0b: Long-Term (Memories & Lessons)
541
+ const memoriesCount = (counts.notes && typeof counts.notes.memories === 'number')
542
+ ? counts.notes.memories
543
+ : (statsData.long_term && typeof statsData.long_term.memories === 'number'
544
+ ? statsData.long_term.memories
545
+ : sumTypes(['fact', 'architecture', 'pattern', 'workflow', 'preference']));
546
+ const lessonsCount = (counts.notes && typeof counts.notes.lessons === 'number')
547
+ ? counts.notes.lessons
548
+ : (statsData.long_term && typeof statsData.long_term.lessons === 'number'
549
+ ? statsData.long_term.lessons
550
+ : sumTypes(['lesson', 'bug']));
551
+
552
+ kpiGrid.appendChild(createKpiCard(
553
+ 'Long-Term (Curated)',
554
+ memoriesCount + lessonsCount,
555
+ [
556
+ el('span', { className: 'badge badge-cyan badge-mono' }, memoriesCount + ' memories'),
557
+ el('span', { className: 'badge badge-amber badge-mono' }, lessonsCount + ' lessons')
558
+ ]
559
+ ));
560
+
561
+ // Card 1: Notes
562
+ const notesTotal = counts.notes ? counts.notes.total : 0;
563
+ const notesProject = counts.notes ? counts.notes.project : 0;
564
+ const notesGlobal = counts.notes ? counts.notes.global : 0;
565
+ const notesUnknown = counts.notes ? counts.notes.unknown : 0;
566
+
567
+ kpiGrid.appendChild(createKpiCard(
568
+ 'Notes (Curated)',
569
+ notesTotal,
570
+ [
571
+ el('span', { className: 'badge badge-emerald badge-mono' }, notesProject + ' project'),
572
+ el('span', { className: 'badge badge-cyan badge-mono' }, notesGlobal + ' global'),
573
+ el('span', { className: 'badge ' + (notesUnknown > 0 ? 'badge-rose' : 'badge-subtle') + ' badge-mono' }, notesUnknown + ' unknown')
574
+ ]
575
+ ));
576
+
577
+ // Card 2: Trajectories
578
+ const trajTotal = counts.trajectories ? counts.trajectories.total : 0;
579
+ const trajSuccess = counts.trajectories ? counts.trajectories.success : 0;
580
+ const trajFailed = counts.trajectories ? counts.trajectories.failed : 0;
581
+ const trajArchived = counts.trajectories ? counts.trajectories.archived : 0;
582
+
583
+ kpiGrid.appendChild(createKpiCard(
584
+ 'Trajectories (Tasks)',
585
+ trajTotal,
586
+ [
587
+ el('span', { className: 'badge badge-emerald badge-mono' }, trajSuccess + ' success'),
588
+ el('span', { className: 'badge ' + (trajFailed > 0 ? 'badge-rose' : 'badge-subtle') + ' badge-mono' }, trajFailed + ' failed'),
589
+ el('span', { className: 'badge badge-subtle badge-mono' }, trajArchived + ' archived')
590
+ ]
591
+ ));
592
+
593
+ // Card 3: Observations
594
+ const obsTotal = counts.observations ? counts.observations.total : 0;
595
+ const obsFailed = counts.observations ? counts.observations.failed : 0;
596
+ const obsArchived = counts.observations ? counts.observations.archived : 0;
597
+
598
+ kpiGrid.appendChild(createKpiCard(
599
+ 'Observations (Hot-Path)',
600
+ obsTotal,
601
+ [
602
+ el('span', { className: 'badge ' + (obsFailed > 0 ? 'badge-amber' : 'badge-subtle') + ' badge-mono' }, obsFailed + ' failed'),
603
+ el('span', { className: 'badge badge-subtle badge-mono' }, obsArchived + ' archived')
604
+ ]
605
+ ));
606
+
607
+ // Card 4: Summaries
608
+ const sumTotal = counts.summaries ? counts.summaries.total : 0;
609
+ const sumVerified = counts.summaries ? counts.summaries.verified : 0;
610
+ const sumExpired = counts.summaries ? counts.summaries.sources_expired : 0;
611
+
612
+ kpiGrid.appendChild(createKpiCard(
613
+ 'Extractive Summaries',
614
+ sumTotal,
615
+ [
616
+ el('span', { className: 'badge badge-emerald badge-mono' }, sumVerified + ' verified'),
617
+ el('span', { className: 'badge ' + (sumExpired > 0 ? 'badge-amber' : 'badge-subtle') + ' badge-mono' }, sumExpired + ' src expired')
618
+ ]
619
+ ));
620
+
621
+ // Card 5: Failure Patterns
622
+ const fpCount = counts.failure_patterns || 0;
623
+ kpiGrid.appendChild(createKpiCard(
624
+ 'Failure Patterns',
625
+ fpCount,
626
+ [el('span', { className: 'badge badge-amber badge-mono' }, 'Atomic SQL UPSERT')]
627
+ ));
628
+
629
+ // Card 6: Embed Queue
630
+ const eqPending = health.embed_queue_pending || 0;
631
+ const eqStats = health.embed_queue_stats || {};
632
+ const eqBadges = [
633
+ el('span', { className: 'badge ' + (eqPending > 0 ? 'badge-amber' : 'badge-subtle') + ' badge-mono' }, eqPending + ' pending'),
634
+ el('span', { className: 'badge badge-subtle badge-mono' }, (eqStats.done || 0) + ' indexed'),
635
+ el('span', { className: 'badge ' + ((eqStats.failed || 0) > 0 ? 'badge-rose' : 'badge-subtle') + ' badge-mono' }, (eqStats.failed || 0) + ' failed')
636
+ ];
637
+ if (reembedStatus && reembedStatus.status !== 'idle') {
638
+ const total = reembedStatus.total || 0;
639
+ const processed = reembedStatus.processed || 0;
640
+ const badgeCls = reembedStatus.status === 'running'
641
+ ? 'badge-amber'
642
+ : reembedStatus.status === 'completed'
643
+ ? 'badge-emerald'
644
+ : 'badge-rose';
645
+ const label = reembedStatus.status === 'failed'
646
+ ? 'reembed: failed'
647
+ : 'reembed: ' + processed + '/' + total;
648
+ eqBadges.push(el('span', { className: 'badge ' + badgeCls + ' badge-mono' }, label));
649
+ }
650
+ kpiGrid.appendChild(createKpiCard(
651
+ 'Embed Queue (Live)',
652
+ eqPending,
653
+ eqBadges
654
+ ));
655
+
656
+ // Card 7: Dead Letters
657
+ const dlCount = counts.dead_letters || 0;
658
+ kpiGrid.appendChild(createKpiCard(
659
+ 'Dead Letters (Malformed)',
660
+ dlCount,
661
+ [el('span', { className: 'badge ' + (dlCount > 0 ? 'badge-rose' : 'badge-subtle') + ' badge-mono' }, 'Rule 3: 0 volume drops')]
662
+ ));
663
+ }
664
+
665
+ // 5. Scope Progress Bar (Rule 4 Telemetry)
666
+ const progressBar = document.getElementById('scopeProgressBar');
667
+ const legendProject = document.getElementById('legendCountProject');
668
+ const legendGlobal = document.getElementById('legendCountGlobal');
669
+ const legendUnknown = document.getElementById('legendCountUnknown');
670
+
671
+ const pCount = counts.notes ? counts.notes.project : 0;
672
+ const gCount = counts.notes ? counts.notes.global : 0;
673
+ const uCount = counts.notes ? counts.notes.unknown : 0;
674
+ const totalNotes = pCount + gCount + uCount;
675
+
676
+ if (legendProject) legendProject.textContent = String(pCount);
677
+ if (legendGlobal) legendGlobal.textContent = String(gCount);
678
+ if (legendUnknown) legendUnknown.textContent = String(uCount);
679
+
680
+ if (progressBar) {
681
+ progressBar.replaceChildren();
682
+ if (totalNotes > 0) {
683
+ const pPct = ((pCount / totalNotes) * 100).toFixed(1);
684
+ const gPct = ((gCount / totalNotes) * 100).toFixed(1);
685
+ const uPct = ((uCount / totalNotes) * 100).toFixed(1);
686
+
687
+ if (pCount > 0) {
688
+ progressBar.appendChild(el('div', {
689
+ className: 'scope-bar-segment scope-bar-project',
690
+ style: { width: pPct + '%' },
691
+ title: 'Project Scoped: ' + pCount + ' (' + pPct + '%)'
692
+ }));
693
+ }
694
+ if (gCount > 0) {
695
+ progressBar.appendChild(el('div', {
696
+ className: 'scope-bar-segment scope-bar-global',
697
+ style: { width: gPct + '%' },
698
+ title: 'Global Scoped: ' + gCount + ' (' + gPct + '%)'
699
+ }));
700
+ }
701
+ if (uCount > 0) {
702
+ progressBar.appendChild(el('div', {
703
+ className: 'scope-bar-segment scope-bar-unknown',
704
+ style: { width: uPct + '%' },
705
+ title: 'Unknown Scoped (Repair Queue): ' + uCount + ' (' + uPct + '%)'
706
+ }));
707
+ }
708
+ }
709
+ }
710
+
711
+ // 6. Note Type Distribution
712
+ const typeContainer = document.getElementById('typeDistributionContainer');
713
+ if (typeContainer && statsData.type_distribution) {
714
+ typeContainer.replaceChildren();
715
+ const list = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } });
716
+
717
+ const maxCount = Math.max(...statsData.type_distribution.map((t) => t.count), 1);
718
+
719
+ statsData.type_distribution.forEach((item) => {
720
+ const pct = ((item.count / maxCount) * 100).toFixed(0);
721
+ const row = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
722
+ el('div', { style: { display: 'flex', justifyContent: 'space-between', fontSize: '13px' } },
723
+ el('span', { style: { fontWeight: '600', textTransform: 'capitalize' } }, item.type),
724
+ el('span', { className: 'code-pill' }, item.count + ' notes')
725
+ ),
726
+ el('div', { style: { height: '8px', background: 'var(--bg-subtle)', borderRadius: '4px', overflow: 'hidden' } },
727
+ el('div', {
728
+ style: {
729
+ height: '100%',
730
+ width: pct + '%',
731
+ background: getTypeColor(item.type),
732
+ borderRadius: '4px'
733
+ }
734
+ })
735
+ )
736
+ );
737
+ list.appendChild(row);
738
+ });
739
+ typeContainer.appendChild(list);
740
+ }
741
+
742
+ // 7. Client Spool Telemetry
743
+ const spoolContainer = document.getElementById('spoolStatsContainer');
744
+ if (spoolContainer && statsData.spool) {
745
+ spoolContainer.replaceChildren();
746
+ const spool = statsData.spool;
747
+ const kbSize = (spool.bytes / 1024).toFixed(1);
748
+ const maxMb = (spool.maxBytes / (1024 * 1024)).toFixed(0);
749
+
750
+ const grid = el('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '12px' } },
751
+ createSubMetricCard('Spool Records', String(spool.count), 'Pending flush'),
752
+ createSubMetricCard('Buffer Size', kbSize + ' KB / ' + maxMb + ' MB', 'Max disk cap'),
753
+ createSubMetricCard('Max Retention', spool.maxAgeHours + ' hours', 'Auto-prune window'),
754
+ createSubMetricCard('Oldest Buffer Age', formatTimestamp(spool.oldestTimestamp), 'Spool epoch')
755
+ );
756
+ spoolContainer.appendChild(grid);
757
+ }
758
+
759
+ // 8. Discovered Projects Breakdown Table
760
+ const projectsContainer = document.getElementById('projectsTableContainer');
761
+ if (projectsContainer && statsData.projects) {
762
+ projectsContainer.replaceChildren();
763
+ const table = el('table', { className: 'data-table' },
764
+ el('thead', {},
765
+ el('tr', {},
766
+ el('th', {}, 'Project Identifier'),
767
+ el('th', {}, 'Notes'),
768
+ el('th', {}, 'Trajectories'),
769
+ el('th', {}, 'Observations'),
770
+ el('th', {}, 'Total Records'),
771
+ el('th', {}, 'Actions')
772
+ )
773
+ ),
774
+ el('tbody', {},
775
+ ...statsData.projects.map((proj) => {
776
+ const totalGrains = proj.notes_count + proj.trajectories_count + proj.observations_count;
777
+ return el('tr', {},
778
+ el('td', {},
779
+ el('strong', { className: 'text-mono', style: { color: 'var(--accent-cyan)' } }, proj.project_id)
780
+ ),
781
+ el('td', {}, el('span', { className: 'code-pill' }, String(proj.notes_count))),
782
+ el('td', {}, el('span', { className: 'code-pill' }, String(proj.trajectories_count))),
783
+ el('td', {}, el('span', { className: 'code-pill' }, String(proj.observations_count))),
784
+ el('td', {}, el('span', { className: 'badge badge-subtle badge-mono' }, String(totalGrains))),
785
+ el('td', {},
786
+ el('button', {
787
+ className: 'btn',
788
+ style: { height: '30px', padding: '0 10px', fontSize: '12px' },
789
+ onClick: () => {
790
+ switchTab('notes');
791
+ const projInput = document.getElementById('notesFilterProject');
792
+ if (projInput) projInput.value = proj.project_id;
793
+ const scopeSelect = document.getElementById('notesFilterScope');
794
+ if (scopeSelect) scopeSelect.value = 'project';
795
+ applyNotesFilter();
796
+ }
797
+ }, 'Explore Notes')
798
+ )
799
+ );
800
+ })
801
+ )
802
+ );
803
+ projectsContainer.appendChild(table);
804
+ }
805
+ }
806
+
807
+ function createKpiCard(label, value, breakdownNodes = []) {
808
+ const card = el('div', { className: 'kpi-card' });
809
+ const top = el('div', { className: 'kpi-top' },
810
+ el('span', { className: 'kpi-label', textContent: label })
811
+ );
812
+ const val = el('div', { className: 'kpi-value', textContent: String(value) });
813
+ const breakdown = el('div', { className: 'kpi-breakdown' });
814
+ breakdown.append(...breakdownNodes);
815
+
816
+ card.appendChild(top);
817
+ card.appendChild(val);
818
+ card.appendChild(breakdown);
819
+ return card;
820
+ }
821
+
822
+ function createSubMetricCard(title, value, sub) {
823
+ return el('div', {
824
+ style: {
825
+ backgroundColor: 'var(--bg-subtle)',
826
+ padding: '12px',
827
+ borderRadius: '8px',
828
+ border: '1px solid var(--border-color)'
829
+ }
830
+ },
831
+ el('div', { style: { fontSize: '11px', color: 'var(--text-muted)', textTransform: 'uppercase' } }, title),
832
+ el('div', { style: { fontSize: '18px', fontWeight: '700', color: '#fff', margin: '4px 0' } }, value),
833
+ el('div', { style: { fontSize: '11px', color: 'var(--text-secondary)' } }, sub)
834
+ );
835
+ }
836
+
837
+ function getTypeColor(type) {
838
+ switch (type) {
839
+ case 'bug': return 'var(--accent-rose)';
840
+ case 'pattern': return 'var(--accent-cyan)';
841
+ case 'architecture': return 'var(--accent-purple)';
842
+ case 'preference': return 'var(--accent-amber)';
843
+ case 'workflow': return '#3b82f6';
844
+ case 'fact':
845
+ default: return 'var(--accent-emerald)';
846
+ }
847
+ }
848
+
849
+ // Reusable Searchable Project Dropdown Controller & Known Projects Registry
850
+ const knownProjects = new Map(); // project_id -> { notes_count, total }
851
+ const activeDropdownControllers = new Set();
852
+
853
+ function notifyDropdowns() {
854
+ activeDropdownControllers.forEach((ctrl) => {
855
+ try {
856
+ if (ctrl.wrapper && document.body.contains(ctrl.wrapper)) {
857
+ ctrl.render();
858
+ } else {
859
+ activeDropdownControllers.delete(ctrl);
860
+ }
861
+ } catch {
862
+ activeDropdownControllers.delete(ctrl);
863
+ }
864
+ });
865
+ }
866
+
867
+ function renderProjectDropdown() {
868
+ notifyDropdowns();
869
+ }
870
+
871
+ function attachSearchableProjectDropdown(wrapperEl, inputEl, options = {}) {
872
+ if (!wrapperEl || !inputEl) return null;
873
+
874
+ wrapperEl.classList.add('searchable-dropdown');
875
+
876
+ inputEl.setAttribute('autocomplete', 'off');
877
+ inputEl.setAttribute('role', 'combobox');
878
+ inputEl.setAttribute('aria-autocomplete', 'list');
879
+ inputEl.setAttribute('aria-expanded', 'false');
880
+
881
+ let chevron = wrapperEl.querySelector('.dropdown-chevron');
882
+ if (!chevron) {
883
+ chevron = el('span', { className: 'dropdown-chevron', title: 'Toggle project dropdown' }, '▼');
884
+ wrapperEl.appendChild(chevron);
885
+ }
886
+
887
+ let menu = wrapperEl.querySelector('.dropdown-menu');
888
+ if (!menu) {
889
+ menu = el('div', { className: 'dropdown-menu' });
890
+ wrapperEl.appendChild(menu);
891
+ }
892
+
893
+ const includeAllOption = Boolean(options.includeAllOption);
894
+ const allOptionLabel = options.allOptionLabel || 'All Projects';
895
+
896
+ function renderMenu(filterText = '') {
897
+ menu.replaceChildren();
898
+ const currentVal = inputEl.value.trim();
899
+ const normFilter = filterText.trim().toLowerCase();
900
+
901
+ // 1. "All Projects" option
902
+ if (includeAllOption) {
903
+ const isAllSelected = !currentVal || currentVal.toLowerCase() === allOptionLabel.toLowerCase() || currentVal.toLowerCase() === 'all projects';
904
+ const allItem = el('div', {
905
+ className: 'dropdown-item' + (isAllSelected ? ' selected' : ''),
906
+ onClick: (e) => {
907
+ e.stopPropagation();
908
+ inputEl.value = '';
909
+ closeDropdown();
910
+ if (options.onSelect) options.onSelect('');
911
+ }
912
+ },
913
+ el('span', { className: 'font-semibold' }, allOptionLabel),
914
+ el('span', { className: 'badge badge-subtle badge-clear' }, 'Clear')
915
+ );
916
+ menu.appendChild(allItem);
917
+ }
918
+
919
+ // 2. Filter distinct project IDs from knownProjects
920
+ const projectIds = Array.from(knownProjects.keys()).sort();
921
+ let matches = 0;
922
+
923
+ for (const pid of projectIds) {
924
+ if (normFilter && normFilter !== 'all projects' && normFilter !== allOptionLabel.toLowerCase() && !pid.toLowerCase().includes(normFilter)) {
925
+ continue;
926
+ }
927
+ matches++;
928
+ const meta = knownProjects.get(pid);
929
+ const isSelected = currentVal.toLowerCase() === pid.toLowerCase();
930
+
931
+ const item = el('div', {
932
+ className: 'dropdown-item' + (isSelected ? ' selected' : ''),
933
+ onClick: (e) => {
934
+ e.stopPropagation();
935
+ inputEl.value = pid;
936
+ closeDropdown();
937
+ if (options.onSelect) options.onSelect(pid);
938
+ }
939
+ },
940
+ el('span', { className: 'text-mono' }, pid),
941
+ meta && meta.notes_count ? el('span', { className: 'badge badge-subtle badge-count' }, meta.notes_count + ' notes') : null
942
+ );
943
+ menu.appendChild(item);
944
+ }
945
+
946
+ if (normFilter && normFilter !== 'all projects' && normFilter !== allOptionLabel.toLowerCase() && matches === 0) {
947
+ menu.appendChild(
948
+ el('div', { className: 'dropdown-empty' }, 'No matching projects (type to create)')
949
+ );
950
+ }
951
+ }
952
+
953
+ function openDropdown() {
954
+ // Close other open dropdowns first to prevent overlap
955
+ document.querySelectorAll('.searchable-dropdown.open').forEach((w) => {
956
+ if (w !== wrapperEl) {
957
+ w.classList.remove('open');
958
+ const m = w.querySelector('.dropdown-menu');
959
+ if (m) m.classList.remove('open');
960
+ const inp = w.querySelector('input');
961
+ if (inp) inp.setAttribute('aria-expanded', 'false');
962
+ }
963
+ });
964
+
965
+ wrapperEl.classList.add('open');
966
+ menu.classList.add('open');
967
+ inputEl.setAttribute('aria-expanded', 'true');
968
+ const val = inputEl.value.trim();
969
+ renderMenu(val.toLowerCase() === 'all projects' || val.toLowerCase() === allOptionLabel.toLowerCase() ? '' : val);
970
+ }
971
+
972
+ function closeDropdown() {
973
+ wrapperEl.classList.remove('open');
974
+ menu.classList.remove('open');
975
+ inputEl.setAttribute('aria-expanded', 'false');
976
+ }
977
+
978
+ function toggleDropdown() {
979
+ if (wrapperEl.classList.contains('open')) {
980
+ closeDropdown();
981
+ } else {
982
+ openDropdown();
983
+ }
984
+ }
985
+
986
+ chevron.addEventListener('click', (e) => {
987
+ e.stopPropagation();
988
+ toggleDropdown();
989
+ });
990
+
991
+ inputEl.addEventListener('focus', () => {
992
+ openDropdown();
993
+ });
994
+
995
+ inputEl.addEventListener('click', (e) => {
996
+ e.stopPropagation();
997
+ openDropdown();
998
+ });
999
+
1000
+ inputEl.addEventListener('input', () => {
1001
+ openDropdown();
1002
+ renderMenu(inputEl.value.trim());
1003
+ if (options.onInput) options.onInput(inputEl.value.trim());
1004
+ });
1005
+
1006
+ inputEl.addEventListener('keydown', (e) => {
1007
+ if (e.key === 'Escape') {
1008
+ closeDropdown();
1009
+ } else if (e.key === 'Enter') {
1010
+ closeDropdown();
1011
+ if (options.onEnter) options.onEnter(inputEl.value.trim());
1012
+ }
1013
+ });
1014
+
1015
+ const controller = {
1016
+ open: openDropdown,
1017
+ close: closeDropdown,
1018
+ render: () => renderMenu(inputEl.value.trim()),
1019
+ input: inputEl,
1020
+ wrapper: wrapperEl,
1021
+ };
1022
+ activeDropdownControllers.add(controller);
1023
+ return controller;
1024
+ }
1025
+
1026
+ function syncKnownProjects() {
1027
+ if (statsData && Array.isArray(statsData.projects)) {
1028
+ statsData.projects.forEach((p) => {
1029
+ if (p.project_id) {
1030
+ knownProjects.set(p.project_id, {
1031
+ notes_count: p.notes_count || 0,
1032
+ total: (p.notes_count || 0) + (p.trajectories_count || 0) + (p.observations_count || 0)
1033
+ });
1034
+ }
1035
+ });
1036
+ }
1037
+ notifyDropdowns();
1038
+ }
1039
+
1040
+ const standardTaskTypes = [
1041
+ 'general',
1042
+ 'implementation',
1043
+ 'bugfix',
1044
+ 'refactor',
1045
+ 'migration',
1046
+ 'testing',
1047
+ 'security',
1048
+ 'deployment'
1049
+ ];
1050
+
1051
+ function syncTaskTypes() {
1052
+ const select = document.getElementById('injectInputTaskType');
1053
+ if (!select) return;
1054
+ const currentVal = select.value || 'migration';
1055
+ const discovered = new Set(standardTaskTypes);
1056
+
1057
+ if (statsData) {
1058
+ if (Array.isArray(statsData.failure_patterns)) {
1059
+ statsData.failure_patterns.forEach((fp) => {
1060
+ if (fp.task_type) discovered.add(fp.task_type);
1061
+ });
1062
+ }
1063
+ if (Array.isArray(statsData.recent_trajectories)) {
1064
+ statsData.recent_trajectories.forEach((t) => {
1065
+ if (t.task_type) discovered.add(t.task_type);
1066
+ });
1067
+ }
1068
+ }
1069
+
1070
+ select.replaceChildren();
1071
+ const allOpt = el('option', { value: '' }, 'All / Any Task Type');
1072
+ select.appendChild(allOpt);
1073
+
1074
+ const sorted = Array.from(discovered).sort();
1075
+ sorted.forEach((tt) => {
1076
+ const opt = el('option', { value: tt }, tt);
1077
+ if (tt === currentVal) {
1078
+ opt.selected = true;
1079
+ }
1080
+ select.appendChild(opt);
1081
+ });
1082
+ }
1083
+
1084
+ // Tab 2: Hybrid Search & Push Injection Workbench
1085
+ function initSearchWorkbench() {
1086
+ const searchForm = document.getElementById('searchForm');
1087
+ if (searchForm) {
1088
+ searchForm.addEventListener('submit', (e) => {
1089
+ e.preventDefault();
1090
+ executeSearch();
1091
+ });
1092
+ }
1093
+
1094
+ const btnSearch = document.getElementById('btnExecuteSearch');
1095
+ if (btnSearch) {
1096
+ btnSearch.addEventListener('click', executeSearch);
1097
+ }
1098
+
1099
+ const searchInput = document.getElementById('searchInputQ');
1100
+ if (searchInput) {
1101
+ searchInput.addEventListener('keydown', (e) => {
1102
+ if (e.key === 'Enter') {
1103
+ e.preventDefault();
1104
+ executeSearch();
1105
+ }
1106
+ });
1107
+ }
1108
+
1109
+ const searchProjectWrapper = document.getElementById('searchProjectDropdownWrapper');
1110
+ const searchProjectInput = document.getElementById('searchInputProject');
1111
+ if (searchProjectWrapper && searchProjectInput) {
1112
+ attachSearchableProjectDropdown(searchProjectWrapper, searchProjectInput, {
1113
+ includeAllOption: true,
1114
+ allOptionLabel: 'All Projects (Global)',
1115
+ onSelect: () => executeSearch(),
1116
+ onEnter: () => executeSearch()
1117
+ });
1118
+ }
1119
+
1120
+ const injectProjectWrapper = document.getElementById('injectProjectDropdownWrapper');
1121
+ const injectProjectInput = document.getElementById('injectInputProject');
1122
+ if (injectProjectWrapper && injectProjectInput) {
1123
+ attachSearchableProjectDropdown(injectProjectWrapper, injectProjectInput, {
1124
+ includeAllOption: false
1125
+ });
1126
+ }
1127
+
1128
+ const injectForm = document.getElementById('injectForm');
1129
+ if (injectForm) {
1130
+ injectForm.addEventListener('submit', (e) => {
1131
+ e.preventDefault();
1132
+ executeInjection();
1133
+ });
1134
+ }
1135
+
1136
+ const btnInject = document.getElementById('btnExecuteInject');
1137
+ if (btnInject) {
1138
+ btnInject.addEventListener('click', executeInjection);
1139
+ }
1140
+ }
1141
+
1142
+ async function executeSearch() {
1143
+ const queryInput = document.getElementById('searchInputQ');
1144
+ const q = queryInput ? queryInput.value.trim() : '';
1145
+ if (!q) {
1146
+ showToast('Please enter a search query', 'amber');
1147
+ return;
1148
+ }
1149
+
1150
+ const scopeSelect = document.getElementById('searchSelectScope');
1151
+ const projectInput = document.getElementById('searchInputProject');
1152
+ const checkGlobal = document.getElementById('searchCheckGlobal');
1153
+ const fileInput = document.getElementById('searchInputFilePath');
1154
+ const noteTypeSelect = document.getElementById('searchNoteType');
1155
+
1156
+ const grains = [];
1157
+ if (document.getElementById('grainCheckNote')?.checked) grains.push('note');
1158
+ if (document.getElementById('grainCheckTrajectory')?.checked) grains.push('trajectory');
1159
+ if (document.getElementById('grainCheckObservation')?.checked) grains.push('observation');
1160
+ if (document.getElementById('grainCheckSummary')?.checked) grains.push('summary');
1161
+
1162
+ let proj = projectInput ? projectInput.value.trim() : '';
1163
+ if (proj.toLowerCase() === 'all projects (global)' || proj.toLowerCase() === 'all projects') {
1164
+ proj = '';
1165
+ }
1166
+
1167
+ const selectedNoteType = noteTypeSelect && noteTypeSelect.value ? noteTypeSelect.value.trim() : '';
1168
+ const filters = {};
1169
+ if (fileInput && fileInput.value.trim()) {
1170
+ filters.file_path = fileInput.value.trim();
1171
+ }
1172
+ if (selectedNoteType) {
1173
+ filters.type = [selectedNoteType];
1174
+ }
1175
+
1176
+ const payload = {
1177
+ q,
1178
+ grains: grains.length > 0 ? grains : undefined,
1179
+ scope: scopeSelect && scopeSelect.value ? scopeSelect.value : undefined,
1180
+ project_id: proj || undefined,
1181
+ include_global: checkGlobal ? checkGlobal.checked : true,
1182
+ filters: Object.keys(filters).length > 0 ? filters : undefined,
1183
+ limit: 20
1184
+ };
1185
+
1186
+ const resultsContainer = document.getElementById('searchResultsContainer');
1187
+ const metaBar = document.getElementById('searchMetaBar');
1188
+ if (resultsContainer) {
1189
+ resultsContainer.replaceChildren(
1190
+ el('div', { className: 'text-muted', style: { padding: '20px', textAlign: 'center' } }, 'Searching brain with RRF fusion...')
1191
+ );
1192
+ }
1193
+
1194
+ try {
1195
+ const startTime = performance.now();
1196
+ const resp = await apiFetch('/search', {
1197
+ method: 'POST',
1198
+ headers: { 'Content-Type': 'application/json' },
1199
+ body: JSON.stringify(payload)
1200
+ });
1201
+ const durationMs = Math.round(performance.now() - startTime);
1202
+
1203
+ if (!resp.ok) {
1204
+ const errJson = await resp.json().catch(() => ({}));
1205
+ throw new Error(errJson.error?.message || 'Search failed with status ' + resp.status);
1206
+ }
1207
+
1208
+ const data = await resp.json();
1209
+ renderSearchResults(data, durationMs);
1210
+ } catch (err) {
1211
+ if (resultsContainer) {
1212
+ resultsContainer.replaceChildren(
1213
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
1214
+ el('span', {}, 'Search Error: ' + err.message)
1215
+ )
1216
+ );
1217
+ }
1218
+ }
1219
+ }
1220
+
1221
+ function renderSearchResults(data, durationMs) {
1222
+ const resultsContainer = document.getElementById('searchResultsContainer');
1223
+ const metaBar = document.getElementById('searchMetaBar');
1224
+ if (!resultsContainer || !metaBar) return;
1225
+
1226
+ metaBar.style.display = 'flex';
1227
+ metaBar.replaceChildren();
1228
+
1229
+ const mode = data.mode || (data.degraded ? 'bm25-degraded' : 'hybrid');
1230
+ const modeBadge = createBadge('MODE: ' + mode.toUpperCase(), mode.includes('bm25') ? 'amber' : 'emerald', true);
1231
+ const countBadge = createBadge((data.results ? data.results.length : 0) + ' results (' + durationMs + 'ms)', 'cyan', true);
1232
+
1233
+ metaBar.appendChild(modeBadge);
1234
+ metaBar.appendChild(countBadge);
1235
+
1236
+ if (data.degraded) {
1237
+ const degradedBanner = el('div', {
1238
+ className: 'badge badge-rose badge-mono',
1239
+ style: { marginLeft: 'auto' }
1240
+ }, '⚠️ ' + data.degraded);
1241
+ metaBar.appendChild(degradedBanner);
1242
+ }
1243
+
1244
+ resultsContainer.replaceChildren();
1245
+
1246
+ if (!data.results || data.results.length === 0) {
1247
+ resultsContainer.appendChild(
1248
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } },
1249
+ 'No matching records found. Try broader keywords or toggle scope to global/unknown.'
1250
+ )
1251
+ );
1252
+ return;
1253
+ }
1254
+
1255
+ data.results.forEach((item, index) => {
1256
+ const card = el('div', { className: 'result-card' });
1257
+
1258
+ // Header row
1259
+ const grainVariant = item.grain === 'note' ? 'cyan' : item.grain === 'summary' ? 'purple' : item.grain === 'trajectory' ? 'emerald' : 'amber';
1260
+ const grainBadge = createBadge(item.grain.toUpperCase(), grainVariant, true);
1261
+
1262
+ const rrfScore = typeof item.score === 'number' ? item.score.toFixed(4) : String(item.score || '');
1263
+ const scoreSpan = el('span', { className: 'result-score' }, 'RRF Score: ' + rrfScore);
1264
+
1265
+ const header = el('div', { className: 'result-header' },
1266
+ el('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
1267
+ el('span', { className: 'code-pill' }, '#' + (index + 1)),
1268
+ grainBadge,
1269
+ item.scope ? createBadge(item.scope + (item.project_id ? ': ' + item.project_id : ''), 'subtle', true) : null
1270
+ ),
1271
+ scoreSpan
1272
+ );
1273
+
1274
+ // Title & Content
1275
+ let titleText = item.title || item.task_type || item.tool_name || item.id;
1276
+ let bodyText = item.content || item.description || item.input || item.output || '';
1277
+
1278
+ const titleEl = el('div', { className: 'result-title', textContent: titleText });
1279
+ const bodyEl = el('div', { className: 'result-body', textContent: bodyText });
1280
+
1281
+ // Tag list (concepts, files)
1282
+ const tagList = el('div', { className: 'tag-list' });
1283
+ if (Array.isArray(item.concepts)) {
1284
+ item.concepts.forEach((c) => tagList.appendChild(createBadge('#' + c, 'subtle', true)));
1285
+ }
1286
+ if (Array.isArray(item.files)) {
1287
+ item.files.forEach((f) => tagList.appendChild(createBadge('📁 ' + f, 'subtle', true)));
1288
+ }
1289
+ if (item.file_path) {
1290
+ tagList.appendChild(createBadge('📁 ' + item.file_path, 'subtle', true));
1291
+ }
1292
+
1293
+ card.appendChild(header);
1294
+ card.appendChild(titleEl);
1295
+ card.appendChild(bodyEl);
1296
+ if (tagList.children.length > 0) {
1297
+ card.appendChild(tagList);
1298
+ }
1299
+
1300
+ resultsContainer.appendChild(card);
1301
+ });
1302
+ }
1303
+
1304
+ async function executeInjection() {
1305
+ const projectInput = document.getElementById('injectInputProject');
1306
+ const taskTypeInput = document.getElementById('injectInputTaskType');
1307
+ const container = document.getElementById('injectOutputContainer');
1308
+ if (!container) return;
1309
+
1310
+ const proj = projectInput ? projectInput.value.trim() : '';
1311
+ const task = taskTypeInput ? taskTypeInput.value.trim() : '';
1312
+
1313
+ if (!proj) {
1314
+ showToast('Please specify a project_id for injection simulation', 'amber');
1315
+ return;
1316
+ }
1317
+
1318
+ container.replaceChildren(
1319
+ el('div', { className: 'text-muted', style: { padding: '20px', textAlign: 'center' } }, 'Simulating task-start injection...')
1320
+ );
1321
+
1322
+ try {
1323
+ const url = '/inject?project_id=' + encodeURIComponent(proj) + (task ? '&task_type=' + encodeURIComponent(task) : '') + '&limit=5';
1324
+ const resp = await apiFetch(url);
1325
+ if (!resp.ok) {
1326
+ throw new Error('Injection request failed: ' + resp.status);
1327
+ }
1328
+
1329
+ const data = await resp.json();
1330
+ renderInjectionOutput(data, proj, task);
1331
+ } catch (err) {
1332
+ container.replaceChildren(
1333
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
1334
+ el('span', {}, 'Injection Error: ' + err.message)
1335
+ )
1336
+ );
1337
+ }
1338
+ }
1339
+
1340
+ function renderInjectionOutput(data, proj, task) {
1341
+ const container = document.getElementById('injectOutputContainer');
1342
+ if (!container) return;
1343
+ container.replaceChildren();
1344
+
1345
+ // 1. Critical Warnings Block (NeuralSwarm reference text)
1346
+ const warningBlock = el('div', { style: { marginBottom: '16px' } });
1347
+ const warningTitle = el('div', {
1348
+ style: {
1349
+ fontSize: '13px',
1350
+ fontWeight: '700',
1351
+ color: '#fbbf24',
1352
+ marginBottom: '8px',
1353
+ display: 'flex',
1354
+ alignItems: 'center',
1355
+ gap: '6px'
1356
+ }
1357
+ }, '⚠️ CRITICAL WARNINGS (Learn from past failures in project: ' + proj + ')');
1358
+
1359
+ const formattedPre = el('pre', {
1360
+ className: 'code-block',
1361
+ textContent: data.formatted_warnings || 'No critical failure warnings recorded for this project/task_type.'
1362
+ });
1363
+
1364
+ warningBlock.appendChild(warningTitle);
1365
+ warningBlock.appendChild(formattedPre);
1366
+ container.appendChild(warningBlock);
1367
+
1368
+ // 2. Scoped Failure Patterns Section
1369
+ const fpCount = Array.isArray(data.failure_patterns) ? data.failure_patterns.length : 0;
1370
+ const fpSection = el('div', { style: { marginBottom: '16px' } },
1371
+ el('div', { style: { fontSize: '13px', fontWeight: '700', marginBottom: '8px' } },
1372
+ 'Scoped Failure Patterns (' + fpCount + ' patterns with SQL counts)'
1373
+ )
1374
+ );
1375
+
1376
+ if (fpCount === 0) {
1377
+ fpSection.appendChild(el('div', { className: 'text-muted', style: { fontSize: '12px' } }, 'None recorded.'));
1378
+ } else {
1379
+ data.failure_patterns.forEach((fp) => {
1380
+ const item = el('div', { className: 'result-card', style: { padding: '12px' } },
1381
+ el('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: '6px' } },
1382
+ el('span', { className: 'badge badge-rose badge-mono' }, 'COUNT: ' + fp.count + ' occurrences'),
1383
+ el('span', { className: 'code-pill' }, 'task_type: ' + fp.task_type)
1384
+ ),
1385
+ el('div', { className: 'code-block', style: { padding: '8px', fontSize: '11px' }, textContent: fp.error_text })
1386
+ );
1387
+ fpSection.appendChild(item);
1388
+ });
1389
+ }
1390
+ container.appendChild(fpSection);
1391
+
1392
+ // 3. Relevant Curated Notes
1393
+ const notesCount = Array.isArray(data.notes) ? data.notes.length : 0;
1394
+ const notesSection = el('div', {},
1395
+ el('div', { style: { fontSize: '13px', fontWeight: '700', marginBottom: '8px' } },
1396
+ 'Relevant Project Knowledge (' + notesCount + ' bug/pattern/preference notes)'
1397
+ )
1398
+ );
1399
+
1400
+ if (notesCount === 0) {
1401
+ notesSection.appendChild(el('div', { className: 'text-muted', style: { fontSize: '12px' } }, 'No relevant notes found for this scope.'));
1402
+ } else {
1403
+ data.notes.forEach((note) => {
1404
+ const noteCard = el('div', { className: 'result-card', style: { padding: '12px' } },
1405
+ el('div', { style: { display: 'flex', gap: '8px', marginBottom: '4px' } },
1406
+ createBadge(note.type.toUpperCase(), 'amber', true),
1407
+ el('strong', { textContent: note.title })
1408
+ ),
1409
+ el('div', { style: { fontSize: '12px', color: 'var(--text-secondary)' }, textContent: note.content })
1410
+ );
1411
+ notesSection.appendChild(noteCard);
1412
+ });
1413
+ }
1414
+ container.appendChild(notesSection);
1415
+ }
1416
+
1417
+ function updateNotesCategoryPills() {
1418
+ const pillButtons = document.querySelectorAll('#notesCategoryPills button[data-note-category]');
1419
+ pillButtons.forEach((btn) => {
1420
+ const cat = btn.getAttribute('data-note-category');
1421
+ btn.className = cat === activeNotesCategory ? 'btn btn-primary' : 'btn';
1422
+ });
1423
+ }
1424
+
1425
+ // Tab 3: Notes Explorer & Scope Repair Queue
1426
+ function initNotesTab() {
1427
+ const pillButtons = document.querySelectorAll('#notesCategoryPills button[data-note-category]');
1428
+ pillButtons.forEach((btn) => {
1429
+ btn.addEventListener('click', () => {
1430
+ const cat = btn.getAttribute('data-note-category') || 'all';
1431
+ activeNotesCategory = cat;
1432
+ updateNotesCategoryPills();
1433
+
1434
+ const scopeSelect = document.getElementById('notesFilterScope');
1435
+ const typeSelect = document.getElementById('notesFilterType');
1436
+ if (typeSelect) typeSelect.value = '';
1437
+ if (scopeSelect) {
1438
+ if (cat === 'unknown') {
1439
+ scopeSelect.value = 'unknown';
1440
+ } else if (scopeSelect.value === 'unknown') {
1441
+ scopeSelect.value = '';
1442
+ }
1443
+ }
1444
+ applyNotesFilter();
1445
+ });
1446
+ });
1447
+
1448
+ const btnApply = document.getElementById('btnApplyNotesFilter');
1449
+ if (btnApply) {
1450
+ btnApply.addEventListener('click', applyNotesFilter);
1451
+ }
1452
+
1453
+ const btnCreateModal = document.getElementById('btnOpenCreateNoteModal');
1454
+ if (btnCreateModal) {
1455
+ btnCreateModal.addEventListener('click', openCreateNoteModal);
1456
+ }
1457
+
1458
+ const notesProjectWrapper = document.getElementById('notesProjectDropdownWrapper');
1459
+ const notesProjectInput = document.getElementById('notesFilterProject');
1460
+ if (notesProjectWrapper && notesProjectInput) {
1461
+ attachSearchableProjectDropdown(notesProjectWrapper, notesProjectInput, {
1462
+ includeAllOption: true,
1463
+ allOptionLabel: 'All Projects',
1464
+ onSelect: () => applyNotesFilter(),
1465
+ onEnter: () => applyNotesFilter()
1466
+ });
1467
+ }
1468
+ }
1469
+
1470
+ async function applyNotesFilter() {
1471
+ const scopeSelect = document.getElementById('notesFilterScope');
1472
+ const projectInput = document.getElementById('notesFilterProject');
1473
+ const typeSelect = document.getElementById('notesFilterType');
1474
+ const fileInput = document.getElementById('notesFilterFile');
1475
+
1476
+ let projectVal = projectInput ? projectInput.value.trim() : '';
1477
+ if (projectVal.toLowerCase() === 'all projects') projectVal = '';
1478
+
1479
+ const params = new URLSearchParams();
1480
+ if (scopeSelect && scopeSelect.value) {
1481
+ params.set('scope', scopeSelect.value);
1482
+ } else if (activeNotesCategory === 'unknown') {
1483
+ params.set('scope', 'unknown');
1484
+ }
1485
+ if (projectVal) params.set('project_id', projectVal);
1486
+
1487
+ if (typeSelect && typeSelect.value) {
1488
+ params.set('type', typeSelect.value);
1489
+ } else if (activeNotesCategory === 'memories') {
1490
+ ['fact', 'architecture', 'pattern', 'workflow', 'preference'].forEach((t) => params.append('type', t));
1491
+ } else if (activeNotesCategory === 'lessons') {
1492
+ ['lesson', 'bug'].forEach((t) => params.append('type', t));
1493
+ }
1494
+
1495
+ if (fileInput && fileInput.value.trim()) params.set('file_path', fileInput.value.trim());
1496
+ params.set('limit', '50');
1497
+
1498
+ const listContainer = document.getElementById('notesListContainer');
1499
+ if (listContainer) {
1500
+ listContainer.replaceChildren(
1501
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading notes...')
1502
+ );
1503
+ }
1504
+
1505
+ try {
1506
+ const resp = await apiFetch('/notes?' + params.toString());
1507
+ if (!resp.ok) throw new Error('Notes query failed: ' + resp.status);
1508
+ const notes = await resp.json();
1509
+ renderNotesList(notes, scopeSelect ? scopeSelect.value : '');
1510
+ } catch (err) {
1511
+ if (listContainer) {
1512
+ listContainer.replaceChildren(
1513
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
1514
+ el('span', {}, 'Error: ' + err.message)
1515
+ )
1516
+ );
1517
+ }
1518
+ }
1519
+ }
1520
+
1521
+ function renderNotesTab() {
1522
+ applyNotesFilter();
1523
+ }
1524
+
1525
+ function renderNotesList(notes, activeScopeFilter) {
1526
+ const listContainer = document.getElementById('notesListContainer');
1527
+ const repairBanner = document.getElementById('repairBannerContainer');
1528
+ if (!listContainer || !repairBanner) return;
1529
+
1530
+ if (Array.isArray(notes)) {
1531
+ let anyAdded = false;
1532
+ notes.forEach((note) => {
1533
+ if (note.project_id && !knownProjects.has(note.project_id)) {
1534
+ knownProjects.set(note.project_id, { notes_count: 1, total: 1 });
1535
+ anyAdded = true;
1536
+ }
1537
+ });
1538
+ if (anyAdded) {
1539
+ notifyDropdowns();
1540
+ }
1541
+ }
1542
+
1543
+ repairBanner.replaceChildren();
1544
+
1545
+ if (activeScopeFilter === 'unknown') {
1546
+ const banner = el('div', {
1547
+ className: 'warning-banner',
1548
+ style: { borderRadius: '8px', marginBottom: '16px', backgroundColor: 'rgba(245, 158, 11, 0.15)', borderColor: 'var(--accent-amber-border)' }
1549
+ },
1550
+ el('div', { className: 'warning-banner-text' },
1551
+ el('span', { style: { fontSize: '18px' } }, '🛠️'),
1552
+ el('div', {},
1553
+ el('strong', { style: { color: '#fcd34d' } }, 'REPAIR QUEUE (Legacy Unscoped Notes): '),
1554
+ 'These records were imported without a project tag. Under Rule 4, use the inline controls below to assign each note to its proper project or mark as global.'
1555
+ )
1556
+ )
1557
+ );
1558
+ repairBanner.appendChild(banner);
1559
+ }
1560
+
1561
+ listContainer.replaceChildren();
1562
+
1563
+ if (!notes || notes.length === 0) {
1564
+ listContainer.appendChild(
1565
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } },
1566
+ 'No notes match the current filters.'
1567
+ )
1568
+ );
1569
+ return;
1570
+ }
1571
+
1572
+ notes.forEach((note) => {
1573
+ const card = el('div', { className: 'result-card', id: 'noteCard_' + note.id });
1574
+
1575
+ // Note Header
1576
+ const typeBadge = createBadge(note.type.toUpperCase(), 'amber', true);
1577
+ const isUnknown = note.scope === 'unknown';
1578
+ const scopeBadge = createBadge(
1579
+ isUnknown ? '⚠️ UNKNOWN (NEEDS SCOPE)' : (note.scope + (note.project_id ? ': ' + note.project_id : '')),
1580
+ isUnknown ? 'rose' : (note.scope === 'global' ? 'cyan' : 'emerald'),
1581
+ true
1582
+ );
1583
+
1584
+ // Inline Scope Repair Widget (Hidden by default; consistent control heights: 38px)
1585
+ const repairWidget = el('div', {
1586
+ className: 'scope-repair-widget hidden'
1587
+ });
1588
+
1589
+ // Pencil edit button to toggle scope editing
1590
+ const btnEditScope = el('button', {
1591
+ className: 'btn-icon-edit',
1592
+ title: 'Edit Scope',
1593
+ 'aria-label': 'Edit Scope',
1594
+ onClick: (e) => {
1595
+ e.stopPropagation();
1596
+ const isHidden = repairWidget.classList.contains('hidden');
1597
+ if (isHidden) {
1598
+ repairWidget.classList.remove('hidden');
1599
+ btnEditScope.classList.add('active');
1600
+ if (scopeSelect.value === 'project') {
1601
+ projInput.focus();
1602
+ }
1603
+ } else {
1604
+ repairWidget.classList.add('hidden');
1605
+ btnEditScope.classList.remove('active');
1606
+ projCtrl.close();
1607
+ }
1608
+ }
1609
+ }, '✎');
1610
+
1611
+ const header = el('div', { className: 'result-header' },
1612
+ el('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' } },
1613
+ typeBadge,
1614
+ scopeBadge,
1615
+ btnEditScope,
1616
+ el('span', { className: 'code-pill' }, 'v' + note.version),
1617
+ el('span', { className: 'text-muted', style: { fontSize: '11px' } }, formatTimestamp(note.created_at))
1618
+ ),
1619
+ el('span', { className: 'code-pill text-mono' }, note.id)
1620
+ );
1621
+
1622
+ // Title & Content
1623
+ const titleEl = el('div', { className: 'result-title', textContent: note.title });
1624
+ const contentEl = el('div', { className: 'result-body', textContent: note.content });
1625
+
1626
+ // Relations
1627
+ const tagList = el('div', { className: 'tag-list', style: { marginBottom: '12px' } });
1628
+ if (Array.isArray(note.concepts)) {
1629
+ note.concepts.forEach((c) => tagList.appendChild(createBadge('#' + c, 'subtle', true)));
1630
+ }
1631
+ if (Array.isArray(note.files)) {
1632
+ note.files.forEach((f) => tagList.appendChild(createBadge('📁 ' + f, 'subtle', true)));
1633
+ }
1634
+
1635
+ const scopeSelect = el('select', { className: 'form-select' },
1636
+ el('option', { value: 'project', selected: note.scope === 'project' }, 'Assign to Project'),
1637
+ el('option', { value: 'global', selected: note.scope === 'global' }, 'Mark Global'),
1638
+ el('option', { value: 'unknown', selected: note.scope === 'unknown' }, 'Keep Unknown')
1639
+ );
1640
+
1641
+ const projWrapper = el('div', { className: 'searchable-dropdown' });
1642
+ const projInput = el('input', {
1643
+ type: 'text',
1644
+ className: 'form-input input-w-180-pr',
1645
+ placeholder: 'Select or type project...',
1646
+ value: note.project_id || ''
1647
+ });
1648
+ projWrapper.appendChild(projInput);
1649
+
1650
+ const projCtrl = attachSearchableProjectDropdown(projWrapper, projInput, {
1651
+ includeAllOption: false,
1652
+ onSelect: (selectedPid) => {
1653
+ projInput.value = selectedPid;
1654
+ }
1655
+ });
1656
+
1657
+ scopeSelect.addEventListener('change', () => {
1658
+ const isProj = scopeSelect.value === 'project';
1659
+ projWrapper.style.display = isProj ? 'inline-flex' : 'none';
1660
+ if (isProj) {
1661
+ projInput.focus();
1662
+ } else {
1663
+ projCtrl.close();
1664
+ }
1665
+ });
1666
+ projWrapper.style.display = note.scope === 'project' ? 'inline-flex' : 'none';
1667
+
1668
+ const btnSaveScope = el('button', {
1669
+ className: 'btn btn-primary',
1670
+ onClick: async () => {
1671
+ const newScope = scopeSelect.value;
1672
+ const newProj = newScope === 'project' ? projInput.value.trim() : null;
1673
+
1674
+ if (newScope === 'project' && !newProj) {
1675
+ showToast('Project slug is required when scope is project', 'amber');
1676
+ return;
1677
+ }
1678
+
1679
+ try {
1680
+ btnSaveScope.disabled = true;
1681
+ btnSaveScope.textContent = 'Saving...';
1682
+ const resp = await apiFetch('/notes/' + encodeURIComponent(note.id) + '/scope', {
1683
+ method: 'PATCH',
1684
+ headers: { 'Content-Type': 'application/json' },
1685
+ body: JSON.stringify({ scope: newScope, projectId: newProj })
1686
+ });
1687
+
1688
+ if (!resp.ok) {
1689
+ const err = await resp.json().catch(() => ({}));
1690
+ throw new Error(err.error?.message || 'Failed to update scope');
1691
+ }
1692
+
1693
+ if (newProj && !knownProjects.has(newProj)) {
1694
+ knownProjects.set(newProj, { notes_count: 1, total: 1 });
1695
+ notifyDropdowns();
1696
+ }
1697
+
1698
+ showToast('Scope updated for note ' + note.id, 'emerald');
1699
+ fetchStats();
1700
+ applyNotesFilter();
1701
+ } catch (err) {
1702
+ showToast('Error: ' + err.message, 'rose');
1703
+ btnSaveScope.disabled = false;
1704
+ btnSaveScope.textContent = 'Assign Scope';
1705
+ }
1706
+ }
1707
+ }, 'Assign Scope');
1708
+
1709
+ repairWidget.appendChild(el('span', { className: 'text-muted form-label-inline' }, 'RULE 4 SCOPE:'));
1710
+ repairWidget.appendChild(scopeSelect);
1711
+ repairWidget.appendChild(projWrapper);
1712
+ repairWidget.appendChild(btnSaveScope);
1713
+
1714
+ card.appendChild(header);
1715
+ card.appendChild(titleEl);
1716
+ card.appendChild(contentEl);
1717
+ if (tagList.children.length > 0) card.appendChild(tagList);
1718
+ card.appendChild(repairWidget);
1719
+
1720
+ listContainer.appendChild(card);
1721
+ });
1722
+ }
1723
+
1724
+ // Create Note Modal Form (Enforces Rule 4 explicitly)
1725
+ function openCreateNoteModal() {
1726
+ const scopeSelect = el('select', { className: 'form-select', style: { width: '100%' } },
1727
+ el('option', { value: 'project', selected: true }, 'project (requires projectId)'),
1728
+ el('option', { value: 'global' }, 'global (applies everywhere)'),
1729
+ el('option', { value: 'unknown' }, 'unknown (unspecified scope)')
1730
+ );
1731
+
1732
+ const projWrapper = el('div', { className: 'searchable-dropdown flex-1', style: { width: '100%' } });
1733
+ const projectInput = el('input', {
1734
+ type: 'text',
1735
+ className: 'form-input input-w-full-pr',
1736
+ placeholder: 'Project ID (e.g. example-app, demo-project)...'
1737
+ });
1738
+ projWrapper.appendChild(projectInput);
1739
+ attachSearchableProjectDropdown(projWrapper, projectInput, {
1740
+ includeAllOption: false
1741
+ });
1742
+
1743
+ scopeSelect.addEventListener('change', () => {
1744
+ const isProj = scopeSelect.value === 'project';
1745
+ projectInput.disabled = !isProj;
1746
+ if (!isProj) {
1747
+ projectInput.value = '';
1748
+ projWrapper.style.opacity = '0.5';
1749
+ } else {
1750
+ projWrapper.style.opacity = '1';
1751
+ }
1752
+ });
1753
+
1754
+ const typeSelect = el('select', { className: 'form-select', style: { width: '100%' } },
1755
+ el('option', { value: 'fact' }, 'fact'),
1756
+ el('option', { value: 'architecture' }, 'architecture'),
1757
+ el('option', { value: 'pattern' }, 'pattern'),
1758
+ el('option', { value: 'workflow' }, 'workflow'),
1759
+ el('option', { value: 'bug' }, 'bug'),
1760
+ el('option', { value: 'lesson' }, 'lesson'),
1761
+ el('option', { value: 'preference' }, 'preference')
1762
+ );
1763
+
1764
+ const titleInput = el('input', {
1765
+ type: 'text',
1766
+ className: 'form-input',
1767
+ style: { width: '100%' },
1768
+ placeholder: 'Note Title...'
1769
+ });
1770
+
1771
+ const contentTextarea = el('textarea', {
1772
+ className: 'form-textarea',
1773
+ placeholder: 'Curated knowledge content (will never be auto-deleted)...'
1774
+ });
1775
+
1776
+ const conceptsInput = el('input', {
1777
+ type: 'text',
1778
+ className: 'form-input',
1779
+ style: { width: '100%' },
1780
+ placeholder: 'Concepts (comma-separated, e.g. sqlite, schema, migrations)'
1781
+ });
1782
+
1783
+ const filesInput = el('input', {
1784
+ type: 'text',
1785
+ className: 'form-input',
1786
+ style: { width: '100%' },
1787
+ placeholder: 'Files touched (comma-separated paths, e.g. src/lib/db.ts)'
1788
+ });
1789
+
1790
+ const bodyNodes = [
1791
+ el('div', {},
1792
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'RULE 4 SCOPE *'),
1793
+ scopeSelect
1794
+ ),
1795
+ el('div', {},
1796
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'PROJECT ID'),
1797
+ projWrapper
1798
+ ),
1799
+ el('div', {},
1800
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'NOTE TYPE *'),
1801
+ typeSelect
1802
+ ),
1803
+ el('div', {},
1804
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'TITLE *'),
1805
+ titleInput
1806
+ ),
1807
+ el('div', {},
1808
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'CONTENT *'),
1809
+ contentTextarea
1810
+ ),
1811
+ el('div', {},
1812
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'CONCEPTS (OPTIONAL)'),
1813
+ conceptsInput
1814
+ ),
1815
+ el('div', {},
1816
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'FILES TOUCHED (OPTIONAL)'),
1817
+ filesInput
1818
+ )
1819
+ ];
1820
+
1821
+ showModal('Create Long-Term Memory (Rule 4 Explicit Scope)', bodyNodes, [
1822
+ {
1823
+ label: 'Commit Note',
1824
+ variant: 'primary',
1825
+ onClick: async (_e, close) => {
1826
+ const scope = scopeSelect.value;
1827
+ const projectId = scope === 'project' ? projectInput.value.trim() : null;
1828
+ const type = typeSelect.value;
1829
+ const title = titleInput.value.trim();
1830
+ const content = contentTextarea.value.trim();
1831
+
1832
+ if (scope === 'project' && !projectId) {
1833
+ showToast('projectId is required when scope is project', 'amber');
1834
+ return;
1835
+ }
1836
+ if (!title || !content) {
1837
+ showToast('Title and content are required', 'amber');
1838
+ return;
1839
+ }
1840
+
1841
+ const concepts = conceptsInput.value.split(',').map((s) => s.trim()).filter(Boolean);
1842
+ const files = filesInput.value.split(',').map((s) => s.trim()).filter(Boolean);
1843
+
1844
+ try {
1845
+ const resp = await apiFetch('/notes', {
1846
+ method: 'POST',
1847
+ headers: { 'Content-Type': 'application/json' },
1848
+ body: JSON.stringify({
1849
+ scope,
1850
+ project_id: projectId,
1851
+ type,
1852
+ title,
1853
+ content,
1854
+ concepts,
1855
+ files
1856
+ })
1857
+ });
1858
+
1859
+ if (!resp.ok) {
1860
+ const err = await resp.json().catch(() => ({}));
1861
+ throw new Error(err.error?.message || 'Create note failed: ' + resp.status);
1862
+ }
1863
+
1864
+ showToast('Note created successfully!', 'emerald');
1865
+ close();
1866
+ fetchStats();
1867
+ applyNotesFilter();
1868
+ } catch (err) {
1869
+ showToast('Error creating note: ' + err.message, 'rose');
1870
+ }
1871
+ }
1872
+ }
1873
+ ]);
1874
+ }
1875
+
1876
+ // Tab 4: Trajectories & Observations
1877
+ function showTrajectoryModal(t) {
1878
+ const isSuccess = t.success === 1;
1879
+ const isUnknown = t.success === null || t.success === undefined;
1880
+ const outcomeBadge = isUnknown
1881
+ ? createBadge('UNKNOWN', 'amber', true)
1882
+ : createBadge(isSuccess ? 'SUCCESS' : 'FAILED', isSuccess ? 'emerald' : 'rose', true);
1883
+
1884
+ const bodyNodes = [
1885
+ el('div', { className: 'inspector-grid' },
1886
+ el('div', { className: 'inspector-field' },
1887
+ el('div', { className: 'inspector-label' }, 'TRAJECTORY ID'),
1888
+ el('div', { className: 'inspector-value text-mono', style: { color: 'var(--accent-cyan)' } }, t.id)
1889
+ ),
1890
+ el('div', { className: 'inspector-field' },
1891
+ el('div', { className: 'inspector-label' }, 'OUTCOME'),
1892
+ el('div', { className: 'inspector-value' }, outcomeBadge)
1893
+ ),
1894
+ el('div', { className: 'inspector-field' },
1895
+ el('div', { className: 'inspector-label' }, 'SCOPE & PROJECT'),
1896
+ el('div', { className: 'inspector-value' },
1897
+ createBadge(t.scope + (t.project_id ? ': ' + t.project_id : ''), 'subtle', true)
1898
+ )
1899
+ ),
1900
+ el('div', { className: 'inspector-field' },
1901
+ el('div', { className: 'inspector-label' }, 'TASK TYPE'),
1902
+ el('div', { className: 'inspector-value' },
1903
+ el('span', { className: 'code-pill' }, t.task_type || 'unknown')
1904
+ )
1905
+ ),
1906
+ el('div', { className: 'inspector-field' },
1907
+ el('div', { className: 'inspector-label' }, 'DURATION'),
1908
+ el('div', { className: 'inspector-value text-mono' }, (t.duration_ms || 0) + ' ms')
1909
+ ),
1910
+ el('div', { className: 'inspector-field' },
1911
+ el('div', { className: 'inspector-label' }, 'RECORDED AT'),
1912
+ el('div', { className: 'inspector-value' }, formatTimestamp(t.created_at))
1913
+ )
1914
+ ),
1915
+ el('div', { style: { marginBottom: '16px' } },
1916
+ el('div', { className: 'inspector-label' }, 'DESCRIPTION / PROMPT'),
1917
+ el('div', { className: 'inspector-code-block' }, t.description || '(no description)')
1918
+ ),
1919
+ el('div', {},
1920
+ el('div', { className: 'inspector-label' }, 'RESULT / OUTCOME SUMMARY'),
1921
+ el('div', { className: 'inspector-code-block' }, t.result || '(no result recorded)')
1922
+ )
1923
+ ];
1924
+
1925
+ showModal('Trajectory Inspector · ' + t.id, bodyNodes);
1926
+ }
1927
+
1928
+ function showObservationModal(obs) {
1929
+ const isFailed = obs.failed === 1;
1930
+ const bodyNodes = [
1931
+ el('div', { className: 'inspector-grid' },
1932
+ el('div', { className: 'inspector-field' },
1933
+ el('div', { className: 'inspector-label' }, 'OBSERVATION ID'),
1934
+ el('div', { className: 'inspector-value text-mono', style: { color: 'var(--accent-cyan)' } }, obs.id)
1935
+ ),
1936
+ el('div', { className: 'inspector-field' },
1937
+ el('div', { className: 'inspector-label' }, 'STATUS / OUTCOME'),
1938
+ el('div', { className: 'inspector-value' },
1939
+ createBadge(isFailed ? 'FAILED' : 'SUCCESS / OK', isFailed ? 'rose' : 'emerald', true)
1940
+ )
1941
+ ),
1942
+ el('div', { className: 'inspector-field' },
1943
+ el('div', { className: 'inspector-label' }, 'SCOPE & PROJECT'),
1944
+ el('div', { className: 'inspector-value' },
1945
+ createBadge(obs.scope + (obs.project_id ? ': ' + obs.project_id : ''), 'subtle', true)
1946
+ )
1947
+ ),
1948
+ el('div', { className: 'inspector-field' },
1949
+ el('div', { className: 'inspector-label' }, 'KIND / TOOL'),
1950
+ el('div', { className: 'inspector-value' },
1951
+ el('span', { className: 'code-pill', style: { color: 'var(--accent-cyan)' } }, obs.tool_name || obs.kind || 'unknown')
1952
+ )
1953
+ ),
1954
+ el('div', { className: 'inspector-field' },
1955
+ el('div', { className: 'inspector-label' }, 'FILE PATH'),
1956
+ el('div', { className: 'inspector-value' },
1957
+ obs.file_path ? el('span', { className: 'code-pill' }, obs.file_path) : el('span', { className: 'text-muted' }, 'None')
1958
+ )
1959
+ ),
1960
+ el('div', { className: 'inspector-field' },
1961
+ el('div', { className: 'inspector-label' }, 'SESSION ID'),
1962
+ el('div', { className: 'inspector-value text-mono' }, obs.session_id || el('span', { className: 'text-muted' }, 'N/A'))
1963
+ ),
1964
+ el('div', { className: 'inspector-field' },
1965
+ el('div', { className: 'inspector-label' }, 'DURATION'),
1966
+ el('div', { className: 'inspector-value text-mono' }, (obs.duration_ms || 0) + ' ms')
1967
+ ),
1968
+ el('div', { className: 'inspector-field' },
1969
+ el('div', { className: 'inspector-label' }, 'RECORDED AT'),
1970
+ el('div', { className: 'inspector-value' }, formatTimestamp(obs.created_at))
1971
+ )
1972
+ ),
1973
+ el('div', { style: { marginBottom: '16px' } },
1974
+ el('div', { className: 'inspector-label' }, 'INPUT / PROMPT'),
1975
+ el('div', { className: 'inspector-code-block' }, obs.input || '(empty input)')
1976
+ ),
1977
+ el('div', {},
1978
+ el('div', { className: 'inspector-label', style: { color: isFailed ? '#f87171' : 'var(--text-muted)' } }, 'OUTPUT / EXECUTION RESULT'),
1979
+ el('div', {
1980
+ className: 'inspector-code-block',
1981
+ style: isFailed ? { color: '#fca5a5', borderColor: 'var(--accent-rose-border)' } : {}
1982
+ }, obs.output || '(empty output)')
1983
+ )
1984
+ ];
1985
+
1986
+ showModal('Observation Inspector · ' + obs.id, bodyNodes);
1987
+ }
1988
+
1989
+ function showObservationNotFoundModal(recordId, grain = 'observation') {
1990
+ const bodyNodes = [
1991
+ el('div', {
1992
+ className: 'warning-banner',
1993
+ style: {
1994
+ borderRadius: '8px',
1995
+ marginBottom: '16px',
1996
+ backgroundColor: 'var(--accent-rose-bg)',
1997
+ borderColor: 'var(--accent-rose-border)'
1998
+ }
1999
+ },
2000
+ el('div', { className: 'warning-banner-text' },
2001
+ el('span', { style: { fontSize: '20px' } }, '⚠️'),
2002
+ el('div', {},
2003
+ el('strong', { style: { color: '#fda4af', display: 'block', marginBottom: '4px' } },
2004
+ 'Observation ' + recordId + ' not found in active store (may have been archived or cleaned up)'
2005
+ ),
2006
+ el('span', { className: 'text-muted', style: { fontSize: '12px' } },
2007
+ 'The cited record ID does not exist in the active observations table.'
2008
+ )
2009
+ )
2010
+ )
2011
+ ),
2012
+ el('div', { className: 'inspector-grid' },
2013
+ el('div', { className: 'inspector-field' },
2014
+ el('div', { className: 'inspector-label' }, 'CITED RECORD ID'),
2015
+ el('div', { className: 'inspector-value text-mono', style: { color: 'var(--accent-rose)' } }, recordId)
2016
+ ),
2017
+ el('div', { className: 'inspector-field' },
2018
+ el('div', { className: 'inspector-label' }, 'GRAIN'),
2019
+ el('div', { className: 'inspector-value' },
2020
+ createBadge((grain || 'observation').toUpperCase(), 'purple', true)
2021
+ )
2022
+ ),
2023
+ el('div', { className: 'inspector-field' },
2024
+ el('div', { className: 'inspector-label' }, 'HTTP STATUS'),
2025
+ el('div', { className: 'inspector-value' },
2026
+ createBadge('404 NOT FOUND', 'rose', true)
2027
+ )
2028
+ )
2029
+ ),
2030
+ el('div', {
2031
+ style: {
2032
+ backgroundColor: 'var(--bg-subtle)',
2033
+ padding: '14px 16px',
2034
+ borderRadius: '6px',
2035
+ border: '1px solid var(--border-color)',
2036
+ fontSize: '13px',
2037
+ lineHeight: '1.6',
2038
+ color: 'var(--text-secondary)'
2039
+ }
2040
+ },
2041
+ el('strong', { style: { color: 'var(--text-primary)', display: 'block', marginBottom: '6px' } },
2042
+ 'Why is this observation not found?'
2043
+ ),
2044
+ el('ul', { style: { paddingLeft: '20px', margin: 0 } },
2045
+ el('li', { style: { marginBottom: '4px' } },
2046
+ 'Rule 6 derived summaries cite machine observations as evidence. If this summary originated from an AI conformance fixture (fx1-failure, fx2-success, fx3-sparse), synthetic source IDs are validated during test verification and never committed to the live observation store.'
2047
+ ),
2048
+ el('li', {},
2049
+ 'If this was a production tool call, it may have been moved to observations_archive by the background retention sweeper (active observations are archived after 30 days).'
2050
+ )
2051
+ )
2052
+ )
2053
+ ];
2054
+
2055
+ showModal('Citation Inspector · ' + recordId, bodyNodes);
2056
+ }
2057
+
2058
+ async function inspectCitation(recordId, grain = 'observation') {
2059
+ showToast('Fetching cited ' + (grain || 'observation') + ': ' + recordId + '...', 'cyan', 2500);
2060
+
2061
+ // 1. Switch to Trajectories tab & Observations subtab
2062
+ switchTab('trajectories');
2063
+
2064
+ if (grain === 'trajectory') {
2065
+ switchSubTab('trajectories', recordId);
2066
+ try {
2067
+ const resp = await apiFetch('/trajectories/' + encodeURIComponent(recordId));
2068
+ if (resp.status === 404) {
2069
+ showObservationNotFoundModal(recordId, grain);
2070
+ return;
2071
+ }
2072
+ if (!resp.ok) {
2073
+ throw new Error('Server returned HTTP ' + resp.status + ' (' + resp.statusText + ')');
2074
+ }
2075
+ const traj = await resp.json();
2076
+ showTrajectoryModal(traj);
2077
+ } catch (err) {
2078
+ showToast('Citation fetch failed: ' + err.message, 'rose', 6000);
2079
+ }
2080
+ return;
2081
+ }
2082
+
2083
+ switchSubTab('observations', recordId);
2084
+
2085
+ // 2. Fetch the observation
2086
+ try {
2087
+ const resp = await apiFetch('/observations/' + encodeURIComponent(recordId));
2088
+ if (resp.status === 404) {
2089
+ showObservationNotFoundModal(recordId, grain);
2090
+ return;
2091
+ }
2092
+ if (!resp.ok) {
2093
+ throw new Error('Server returned HTTP ' + resp.status + ' (' + resp.statusText + ')');
2094
+ }
2095
+ const obs = await resp.json();
2096
+ showObservationModal(obs);
2097
+ } catch (err) {
2098
+ showToast('Citation fetch failed: ' + err.message, 'rose', 6000);
2099
+ }
2100
+ }
2101
+
2102
+ function renderTrajectoriesSubView(highlightId = null) {
2103
+ const container = document.getElementById('trajectoriesSubViewContainer');
2104
+ if (!container) return;
2105
+
2106
+ container.replaceChildren();
2107
+
2108
+ if (activeSubTab === 'trajectories') {
2109
+ renderTrajectoriesTable(container, highlightId);
2110
+ } else if (activeSubTab === 'observations') {
2111
+ renderObservationsTable(container, highlightId);
2112
+ } else if (activeSubTab === 'summaries') {
2113
+ renderSummariesList(container);
2114
+ }
2115
+ }
2116
+
2117
+ async function renderTrajectoriesTable(container, highlightId = null) {
2118
+ container.replaceChildren(
2119
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading trajectories...')
2120
+ );
2121
+
2122
+ try {
2123
+ const resp = await apiFetch('/trajectories?limit=50');
2124
+ if (!resp.ok) throw new Error('Failed to load trajectories: HTTP ' + resp.status);
2125
+ const list = await resp.json();
2126
+
2127
+ container.replaceChildren();
2128
+ if (!list || list.length === 0) {
2129
+ const trajCounts = statsData?.counts?.trajectories || {};
2130
+ const archivedCount = trajCounts.archived || 0;
2131
+ const emptyCard = el('div', {
2132
+ className: 'result-card',
2133
+ style: { padding: '32px 24px', textAlign: 'center', backgroundColor: 'var(--bg-subtle)' }
2134
+ },
2135
+ el('div', { style: { fontSize: '28px', marginBottom: '12px' } }, '📋'),
2136
+ el('h3', { style: { fontSize: '16px', fontWeight: '700', marginBottom: '8px' } }, 'No Active Trajectories Recorded'),
2137
+ el('p', { className: 'text-muted', style: { fontSize: '13px', maxWidth: '520px', margin: '0 auto 16px', lineHeight: '1.5' } },
2138
+ 'Trajectories represent task-level attempts with arithmetic outcome metrics (success rate, duration, and tool count). ' +
2139
+ (archivedCount > 0 ? (archivedCount + ' trajectories exist in trajectory_archive (older than 30 days). ') : '') +
2140
+ 'Use the button below or POST /capture/trajectories to capture task executions.'
2141
+ ),
2142
+ el('button', {
2143
+ className: 'btn btn-emerald',
2144
+ onClick: () => openCaptureModal('trajectory')
2145
+ }, '+ Capture Test Trajectory')
2146
+ );
2147
+ container.appendChild(emptyCard);
2148
+ return;
2149
+ }
2150
+
2151
+ let highlightedRowEl = null;
2152
+
2153
+ const table = el('table', { className: 'data-table' },
2154
+ el('thead', {},
2155
+ el('tr', {},
2156
+ el('th', {}, 'ID'),
2157
+ el('th', {}, 'Scope / Project'),
2158
+ el('th', {}, 'Task Type'),
2159
+ el('th', {}, 'Outcome'),
2160
+ el('th', {}, 'Duration'),
2161
+ el('th', {}, 'Description & Result'),
2162
+ el('th', {}, 'Action')
2163
+ )
2164
+ ),
2165
+ el('tbody', {},
2166
+ ...list.map((t) => {
2167
+ const isTarget = highlightId && (t.id === highlightId);
2168
+ const outcomeBadge =
2169
+ t.success === null || t.success === undefined
2170
+ ? createBadge('UNKNOWN', 'amber', true)
2171
+ : createBadge(t.success === 1 ? 'SUCCESS' : 'FAILED', t.success === 1 ? 'emerald' : 'rose', true);
2172
+
2173
+ const row = el('tr', {
2174
+ id: 'traj-row-' + t.id,
2175
+ className: isTarget ? 'row-highlight' : '',
2176
+ style: { cursor: 'pointer' },
2177
+ onClick: () => showTrajectoryModal(t)
2178
+ },
2179
+ el('td', {}, el('span', { className: 'code-pill text-mono' + (isTarget ? ' text-bold' : '') }, t.id)),
2180
+ el('td', {}, createBadge(t.scope + (t.project_id ? ': ' + t.project_id : ''), 'subtle', true)),
2181
+ el('td', {}, el('span', { className: 'code-pill' }, t.task_type || 'unknown')),
2182
+ el('td', {}, outcomeBadge),
2183
+ el('td', {}, el('span', { className: 'text-mono' }, (t.duration_ms || 0) + 'ms')),
2184
+ el('td', {},
2185
+ el('div', { style: { fontWeight: '600', marginBottom: '4px' } }, t.description),
2186
+ t.result ? el('div', { className: 'text-muted', style: { fontSize: '12px' } }, t.result) : null
2187
+ ),
2188
+ el('td', {},
2189
+ el('button', {
2190
+ className: 'btn',
2191
+ style: { height: '28px', padding: '0 8px', fontSize: '11px' },
2192
+ onClick: (e) => {
2193
+ e.stopPropagation();
2194
+ showTrajectoryModal(t);
2195
+ }
2196
+ }, 'Inspect')
2197
+ )
2198
+ );
2199
+
2200
+ if (isTarget) {
2201
+ highlightedRowEl = row;
2202
+ }
2203
+
2204
+ return row;
2205
+ })
2206
+ )
2207
+ );
2208
+
2209
+ container.appendChild(table);
2210
+
2211
+ if (highlightedRowEl) {
2212
+ setTimeout(() => {
2213
+ highlightedRowEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
2214
+ }, 120);
2215
+ }
2216
+ } catch (err) {
2217
+ container.replaceChildren(
2218
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
2219
+ el('span', {}, 'Error: ' + err.message)
2220
+ )
2221
+ );
2222
+ }
2223
+ }
2224
+
2225
+ async function renderObservationsTable(container, highlightId = null) {
2226
+ container.replaceChildren(
2227
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading observations...')
2228
+ );
2229
+
2230
+ try {
2231
+ const resp = await apiFetch('/observations?limit=50');
2232
+ if (!resp.ok) throw new Error('Failed to load observations: HTTP ' + resp.status);
2233
+ const list = await resp.json();
2234
+
2235
+ container.replaceChildren();
2236
+ if (!list || list.length === 0) {
2237
+ const obsCounts = statsData?.counts?.observations || {};
2238
+ const archivedCount = obsCounts.archived || 0;
2239
+ const emptyCard = el('div', {
2240
+ className: 'result-card',
2241
+ style: { padding: '32px 24px', textAlign: 'center', backgroundColor: 'var(--bg-subtle)' }
2242
+ },
2243
+ el('div', { style: { fontSize: '28px', marginBottom: '12px' } }, '🔍'),
2244
+ el('h3', { style: { fontSize: '16px', fontWeight: '700', marginBottom: '8px' } }, 'No Active Observations Recorded'),
2245
+ el('p', { className: 'text-muted', style: { fontSize: '13px', maxWidth: '520px', margin: '0 auto 16px', lineHeight: '1.5' } },
2246
+ 'Observations capture high-volume machine-written tool calls, file edits, and prompts in real time. ' +
2247
+ (archivedCount > 0 ? (archivedCount + ' observations exist in observations_archive (older than 30 days). ') : '') +
2248
+ 'Use the button below or POST /capture/observations to record tool activity.'
2249
+ ),
2250
+ el('button', {
2251
+ className: 'btn btn-emerald',
2252
+ onClick: () => openCaptureModal('observation')
2253
+ }, '+ Capture Test Observation')
2254
+ );
2255
+ container.appendChild(emptyCard);
2256
+ return;
2257
+ }
2258
+
2259
+ let highlightedRowEl = null;
2260
+
2261
+ const table = el('table', { className: 'data-table' },
2262
+ el('thead', {},
2263
+ el('tr', {},
2264
+ el('th', {}, 'ID'),
2265
+ el('th', {}, 'Scope / Project'),
2266
+ el('th', {}, 'Tool / Kind'),
2267
+ el('th', {}, 'File Path'),
2268
+ el('th', {}, 'Status'),
2269
+ el('th', {}, 'Duration'),
2270
+ el('th', {}, 'Preview'),
2271
+ el('th', {}, 'Action')
2272
+ )
2273
+ ),
2274
+ el('tbody', {},
2275
+ ...list.map((obs) => {
2276
+ const isFailed = obs.failed === 1;
2277
+ const statusBadge = createBadge(isFailed ? 'FAILED' : 'OK', isFailed ? 'rose' : 'emerald', true);
2278
+ const toolStr = obs.tool_name || obs.kind;
2279
+ const isTarget = highlightId && (obs.id === highlightId);
2280
+
2281
+ const row = el('tr', {
2282
+ id: 'obs-row-' + obs.id,
2283
+ className: isTarget ? 'row-highlight' : '',
2284
+ style: { cursor: 'pointer' },
2285
+ onClick: () => showObservationModal(obs)
2286
+ },
2287
+ el('td', {}, el('span', { className: 'code-pill text-mono' + (isTarget ? ' text-bold' : '') }, obs.id)),
2288
+ el('td', {}, createBadge(obs.scope + (obs.project_id ? ': ' + obs.project_id : ''), 'subtle', true)),
2289
+ el('td', {}, el('span', { className: 'code-pill', style: { color: 'var(--accent-cyan)' } }, toolStr)),
2290
+ el('td', {}, obs.file_path ? el('span', { className: 'code-pill' }, obs.file_path) : el('span', { className: 'text-muted' }, '-')),
2291
+ el('td', {}, statusBadge),
2292
+ el('td', {}, el('span', { className: 'text-mono' }, (obs.duration_ms || 0) + 'ms')),
2293
+ el('td', {},
2294
+ el('div', { style: { fontSize: '11px', maxHeight: '40px', overflow: 'hidden' } },
2295
+ obs.input ? el('span', { className: 'text-muted' }, 'in: ' + obs.input.slice(0, 70)) : null,
2296
+ obs.output ? el('div', { style: { color: isFailed ? '#f87171' : 'var(--text-secondary)' } }, 'out: ' + obs.output.slice(0, 70)) : null
2297
+ )
2298
+ ),
2299
+ el('td', {},
2300
+ el('button', {
2301
+ className: 'btn',
2302
+ style: { height: '28px', padding: '0 8px', fontSize: '11px' },
2303
+ onClick: (e) => {
2304
+ e.stopPropagation();
2305
+ showObservationModal(obs);
2306
+ }
2307
+ }, 'Inspect')
2308
+ )
2309
+ );
2310
+
2311
+ if (isTarget) {
2312
+ highlightedRowEl = row;
2313
+ }
2314
+
2315
+ return row;
2316
+ })
2317
+ )
2318
+ );
2319
+
2320
+ container.appendChild(table);
2321
+
2322
+ if (highlightedRowEl) {
2323
+ setTimeout(() => {
2324
+ highlightedRowEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
2325
+ }, 120);
2326
+ }
2327
+ } catch (err) {
2328
+ container.replaceChildren(
2329
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
2330
+ el('span', {}, 'Error: ' + err.message)
2331
+ )
2332
+ );
2333
+ }
2334
+ }
2335
+
2336
+ async function renderSummariesList(container) {
2337
+ container.replaceChildren(
2338
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading extractive summaries...')
2339
+ );
2340
+
2341
+ try {
2342
+ const resp = await apiFetch('/summaries?limit=50');
2343
+ if (!resp.ok) throw new Error('Failed to load summaries: HTTP ' + resp.status);
2344
+ const list = await resp.json();
2345
+
2346
+ container.replaceChildren();
2347
+ if (!list || list.length === 0) {
2348
+ container.appendChild(
2349
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } },
2350
+ 'No extractive summaries stored yet. Derived rows are produced under Rule 6 attribution.'
2351
+ )
2352
+ );
2353
+ return;
2354
+ }
2355
+
2356
+ list.forEach((sum) => {
2357
+ const card = el('div', { className: 'result-card' });
2358
+
2359
+ const outcomeVariant = sum.outcome === 'success' ? 'emerald' : sum.outcome === 'failure' ? 'rose' : 'amber';
2360
+ const outcomeBadge = createBadge('OUTCOME: ' + (sum.outcome || 'unknown').toUpperCase(), outcomeVariant, true);
2361
+
2362
+ const producerStr = (sum.producer_tier || 'agent') + (sum.producer_model ? '/' + sum.producer_model : '') + ' (' + sum.prompt_version + ')';
2363
+ const producerBadge = createBadge('PRODUCER: ' + producerStr, 'purple', true);
2364
+
2365
+ const header = el('div', { className: 'result-header' },
2366
+ el('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' } },
2367
+ createBadge(sum.kind.toUpperCase(), 'cyan', true),
2368
+ outcomeBadge,
2369
+ producerBadge,
2370
+ sum.verified === 1 ? createBadge('VERIFIED', 'emerald', true) : createBadge('UNVERIFIED', 'amber', true)
2371
+ ),
2372
+ el('span', { className: 'code-pill text-mono' }, sum.id)
2373
+ );
2374
+
2375
+ // Claims list
2376
+ const claimsList = el('div', { style: { marginTop: '10px' } });
2377
+ if (Array.isArray(sum.claims) && sum.claims.length > 0) {
2378
+ sum.claims.forEach((claim, idx) => {
2379
+ const claimSources = (sum.sources || []).filter((s) => s.claim_id === claim.id);
2380
+ const sourcePills = claimSources.map((s) =>
2381
+ el('span', {
2382
+ className: 'code-pill citation-badge',
2383
+ title: 'Citation source: ' + s.grain + ' -> ' + s.record_id + ' (Click to inspect observation)',
2384
+ onClick: (e) => {
2385
+ e.stopPropagation();
2386
+ inspectCitation(s.record_id, s.grain);
2387
+ }
2388
+ }, '🔍 ' + s.record_id)
2389
+ );
2390
+
2391
+ const claimItem = el('div', {
2392
+ style: {
2393
+ backgroundColor: 'var(--bg-subtle)',
2394
+ padding: '10px 14px',
2395
+ borderRadius: '6px',
2396
+ marginBottom: '6px'
2397
+ }
2398
+ },
2399
+ el('div', { style: { fontWeight: '600', marginBottom: '4px' } }, (idx + 1) + '. ' + claim.text),
2400
+ el('div', { style: { display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' } },
2401
+ el('span', { className: 'text-muted', style: { fontSize: '11px' } }, 'Citations:'),
2402
+ ...sourcePills
2403
+ )
2404
+ );
2405
+ claimsList.appendChild(claimItem);
2406
+ });
2407
+ }
2408
+
2409
+ // Additional/General citations if any sources are not mapped to specific claims
2410
+ const claimedSourceIds = new Set((sum.claims || []).flatMap((c) => (sum.sources || []).filter(s => s.claim_id === c.id).map(s => s.record_id)));
2411
+ const generalSources = (sum.sources || []).filter(s => !claimedSourceIds.has(s.record_id));
2412
+ if (generalSources.length > 0) {
2413
+ const generalPills = generalSources.map((s) =>
2414
+ el('span', {
2415
+ className: 'code-pill citation-badge',
2416
+ title: 'Source: ' + s.grain + ' -> ' + s.record_id + ' (Click to inspect observation)',
2417
+ onClick: (e) => {
2418
+ e.stopPropagation();
2419
+ inspectCitation(s.record_id, s.grain);
2420
+ }
2421
+ }, '🔍 ' + s.record_id)
2422
+ );
2423
+ claimsList.appendChild(
2424
+ el('div', {
2425
+ style: {
2426
+ backgroundColor: 'var(--bg-subtle)',
2427
+ padding: '8px 14px',
2428
+ borderRadius: '6px',
2429
+ marginTop: '6px',
2430
+ display: 'flex',
2431
+ gap: '8px',
2432
+ alignItems: 'center',
2433
+ flexWrap: 'wrap'
2434
+ }
2435
+ },
2436
+ el('span', { className: 'text-muted', style: { fontSize: '11px', fontWeight: '600' } }, 'General Citations:'),
2437
+ ...generalPills
2438
+ )
2439
+ );
2440
+ }
2441
+
2442
+ card.appendChild(header);
2443
+ card.appendChild(claimsList);
2444
+ container.appendChild(card);
2445
+ });
2446
+ } catch (err) {
2447
+ container.replaceChildren(
2448
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
2449
+ el('span', {}, 'Error: ' + err.message)
2450
+ )
2451
+ );
2452
+ }
2453
+ }
2454
+
2455
+ // Interactive Test Capture Modal
2456
+ function openCaptureModal(defaultGrain = 'observation') {
2457
+ const isTraj = defaultGrain === 'trajectory';
2458
+ const grainSelect = el('select', { className: 'form-select', style: { width: '100%' } },
2459
+ el('option', { value: 'observation', selected: !isTraj }, 'Observation (Tool Call / Hot Path)'),
2460
+ el('option', { value: 'trajectory', selected: isTraj }, 'Trajectory (Task Attempt Rollup)')
2461
+ );
2462
+
2463
+ const scopeSelect = el('select', { className: 'form-select', style: { width: '100%' } },
2464
+ el('option', { value: 'project', selected: true }, 'project'),
2465
+ el('option', { value: 'global' }, 'global'),
2466
+ el('option', { value: 'unknown' }, 'unknown')
2467
+ );
2468
+
2469
+ const projectInput = el('input', {
2470
+ type: 'text',
2471
+ className: 'form-input',
2472
+ style: { width: '100%' },
2473
+ value: 'example-app',
2474
+ placeholder: 'Project ID...'
2475
+ });
2476
+
2477
+ const toolOrTaskInput = el('input', {
2478
+ type: 'text',
2479
+ className: 'form-input',
2480
+ style: { width: '100%' },
2481
+ value: isTraj ? 'migration' : 'ExecuteCommand',
2482
+ placeholder: 'Tool Name (e.g. Edit, ExecuteCommand) or Task Type...'
2483
+ });
2484
+
2485
+ const fileInput = el('input', {
2486
+ type: 'text',
2487
+ className: 'form-input',
2488
+ style: { width: '100%' },
2489
+ value: isTraj ? '' : 'src/lib/db.ts',
2490
+ placeholder: 'Target File Path...'
2491
+ });
2492
+
2493
+ const failedSelect = el('select', { className: 'form-select', style: { width: '100%' } },
2494
+ el('option', { value: '0', selected: true }, 'Success / OK (failed = 0)'),
2495
+ el('option', { value: '1' }, 'Failed (failed = 1) — Triggers Failure Pattern UPSERT')
2496
+ );
2497
+
2498
+ const inputArea = el('textarea', {
2499
+ className: 'form-textarea',
2500
+ placeholder: 'Input / Description...',
2501
+ textContent: isTraj ? 'Execute migration for SQLite composite index' : 'npm test -- memories'
2502
+ });
2503
+
2504
+ const outputArea = el('textarea', {
2505
+ className: 'form-textarea',
2506
+ placeholder: 'Output / Error Result...',
2507
+ textContent: isTraj ? 'Migration applied cleanly in 210ms' : 'Tests passed: 70/70'
2508
+ });
2509
+
2510
+ grainSelect.addEventListener('change', () => {
2511
+ const isNowTraj = grainSelect.value === 'trajectory';
2512
+ if (isNowTraj) {
2513
+ toolOrTaskInput.value = 'migration';
2514
+ fileInput.value = '';
2515
+ inputArea.value = 'Migrate schema to support compound index';
2516
+ outputArea.value = 'Migration completed in 240ms';
2517
+ } else {
2518
+ toolOrTaskInput.value = 'ExecuteCommand';
2519
+ fileInput.value = 'src/lib/db.ts';
2520
+ inputArea.value = 'npm test -- memories';
2521
+ outputArea.value = 'Tests passed: 70/70';
2522
+ }
2523
+ });
2524
+
2525
+ failedSelect.addEventListener('change', () => {
2526
+ if (failedSelect.value === '1') {
2527
+ outputArea.textContent = 'SqliteError: FOREIGN KEY constraint failed';
2528
+ }
2529
+ });
2530
+
2531
+ const bodyNodes = [
2532
+ el('div', {},
2533
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'GRAIN'),
2534
+ grainSelect
2535
+ ),
2536
+ el('div', {},
2537
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'SCOPE & PROJECT'),
2538
+ el('div', { style: { display: 'flex', gap: '8px' } }, scopeSelect, projectInput)
2539
+ ),
2540
+ el('div', {},
2541
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'TOOL / TASK TYPE'),
2542
+ toolOrTaskInput
2543
+ ),
2544
+ el('div', {},
2545
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'FILE PATH'),
2546
+ fileInput
2547
+ ),
2548
+ el('div', {},
2549
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'STATUS / OUTCOME'),
2550
+ failedSelect
2551
+ ),
2552
+ el('div', {},
2553
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'INPUT / PROMPT'),
2554
+ inputArea
2555
+ ),
2556
+ el('div', {},
2557
+ el('label', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600', display: 'block', marginBottom: '4px' } }, 'OUTPUT / RESULT'),
2558
+ outputArea
2559
+ )
2560
+ ];
2561
+
2562
+ showModal('Capture Telemetry Event (Direct Hot-Path)', bodyNodes, [
2563
+ {
2564
+ label: 'Commit Capture',
2565
+ variant: 'emerald',
2566
+ onClick: async (_e, close) => {
2567
+ const grain = grainSelect.value;
2568
+ const scope = scopeSelect.value;
2569
+ const projectId = scope === 'project' ? projectInput.value.trim() : null;
2570
+ const failed = parseInt(failedSelect.value, 10);
2571
+
2572
+ try {
2573
+ if (grain === 'observation') {
2574
+ const resp = await apiFetch('/capture/observations', {
2575
+ method: 'POST',
2576
+ headers: { 'Content-Type': 'application/json' },
2577
+ body: JSON.stringify({
2578
+ observations: [{
2579
+ scope,
2580
+ project_id: projectId,
2581
+ kind: 'tool_call',
2582
+ tool_name: toolOrTaskInput.value.trim(),
2583
+ file_path: fileInput.value.trim() || null,
2584
+ input: inputArea.value.trim(),
2585
+ output: outputArea.value.trim(),
2586
+ failed,
2587
+ duration_ms: 120
2588
+ }]
2589
+ })
2590
+ });
2591
+ if (!resp.ok) throw new Error('Observation capture failed: ' + resp.status);
2592
+ const result = await resp.json();
2593
+ showToast('Captured observation ' + (result.ids ? result.ids[0] : 'ok'), 'emerald');
2594
+ } else {
2595
+ const resp = await apiFetch('/capture/trajectories', {
2596
+ method: 'POST',
2597
+ headers: { 'Content-Type': 'application/json' },
2598
+ body: JSON.stringify({
2599
+ trajectories: [{
2600
+ scope,
2601
+ project_id: projectId,
2602
+ task_type: toolOrTaskInput.value.trim(),
2603
+ description: inputArea.value.trim(),
2604
+ result: outputArea.value.trim(),
2605
+ success: failed === 0,
2606
+ duration_ms: 350
2607
+ }]
2608
+ })
2609
+ });
2610
+ if (!resp.ok) throw new Error('Trajectory capture failed: ' + resp.status);
2611
+ const result = await resp.json();
2612
+ showToast('Captured trajectory ' + (result.ids ? result.ids[0] : 'ok'), 'emerald');
2613
+ }
2614
+
2615
+ close();
2616
+ fetchStats();
2617
+ renderTrajectoriesSubView();
2618
+ } catch (err) {
2619
+ showToast('Capture error: ' + err.message, 'rose');
2620
+ }
2621
+ }
2622
+ }
2623
+ ]);
2624
+ }
2625
+
2626
+ // Tab 5: Failure Patterns, Dead Letters & AI Conformance Doctor
2627
+ function initConformanceTab() {
2628
+ const btnRun = document.getElementById('btnRunConformance');
2629
+ if (btnRun) {
2630
+ btnRun.addEventListener('click', runConformanceDiagnostics);
2631
+ }
2632
+ }
2633
+
2634
+ async function runConformanceDiagnostics() {
2635
+ const verdictContainer = document.getElementById('conformanceVerdictContainer');
2636
+ const resultsContainer = document.getElementById('conformanceResultsContainer');
2637
+ const btnRun = document.getElementById('btnRunConformance');
2638
+
2639
+ if (btnRun) {
2640
+ btnRun.disabled = true;
2641
+ btnRun.textContent = 'Running Fixtures...';
2642
+ }
2643
+
2644
+ if (verdictContainer) {
2645
+ verdictContainer.replaceChildren(
2646
+ el('div', { className: 'text-muted', style: { padding: '16px', textAlign: 'center' } },
2647
+ 'Running conformance fixtures (fx1-failure, fx2-success, fx3-sparse) through verification gate...'
2648
+ )
2649
+ );
2650
+ }
2651
+
2652
+ try {
2653
+ const resp = await apiFetch('/diagnostics/ai');
2654
+ if (!resp.ok) throw new Error('Diagnostics request failed: ' + resp.status);
2655
+ const data = await resp.json();
2656
+ renderConformanceReport(data);
2657
+ showToast('Conformance fixtures complete: ' + data.passed_count + '/' + data.total_count + ' passed', data.all_passing ? 'emerald' : 'amber');
2658
+ } catch (err) {
2659
+ if (verdictContainer) {
2660
+ verdictContainer.replaceChildren(
2661
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
2662
+ el('span', {}, 'Diagnostics Error: ' + err.message)
2663
+ )
2664
+ );
2665
+ }
2666
+ } finally {
2667
+ if (btnRun) {
2668
+ btnRun.disabled = false;
2669
+ btnRun.textContent = 'Run Conformance Fixtures';
2670
+ }
2671
+ }
2672
+ }
2673
+
2674
+ function renderConformanceReport(data) {
2675
+ const verdictContainer = document.getElementById('conformanceVerdictContainer');
2676
+ const resultsContainer = document.getElementById('conformanceResultsContainer');
2677
+ if (!verdictContainer || !resultsContainer) return;
2678
+
2679
+ // 1. Overall Non-Contradictory Verdict Banner
2680
+ const isPassing = data.all_passing === true;
2681
+ const banner = el('div', {
2682
+ className: 'warning-banner',
2683
+ style: {
2684
+ borderRadius: '8px',
2685
+ marginBottom: '16px',
2686
+ backgroundColor: isPassing ? 'rgba(16, 185, 129, 0.15)' : 'rgba(244, 63, 94, 0.15)',
2687
+ borderColor: isPassing ? 'var(--accent-emerald-border)' : 'var(--accent-rose-border)'
2688
+ }
2689
+ },
2690
+ el('div', { className: 'warning-banner-text' },
2691
+ el('span', { style: { fontSize: '20px' } }, isPassing ? '✅' : '❌'),
2692
+ el('div', {},
2693
+ el('strong', { style: { color: isPassing ? '#6ee7b7' : '#fda4af', fontSize: '15px' } },
2694
+ isPassing
2695
+ ? 'CONFORMANCE VERDICT: ALL ' + data.total_count + ' ASSERTIONS PASSED (100% COMPLIANCE)'
2696
+ : 'CONFORMANCE VERDICT: FAILED (' + data.passed_count + '/' + data.total_count + ' CHECKS PASSING)'
2697
+ ),
2698
+ el('div', { style: { fontSize: '12px', marginTop: '2px', color: 'var(--text-secondary)' } },
2699
+ 'Single authoritative non-contradictory verdict. Verified against verification gate and dead letter queues.'
2700
+ )
2701
+ )
2702
+ )
2703
+ );
2704
+ verdictContainer.replaceChildren(banner);
2705
+
2706
+ // 2. Assertions Table
2707
+ const table = el('table', { className: 'data-table' },
2708
+ el('thead', {},
2709
+ el('tr', {},
2710
+ el('th', {}, 'Assertion Name'),
2711
+ el('th', {}, 'Status'),
2712
+ el('th', {}, 'Expected'),
2713
+ el('th', {}, 'Actual')
2714
+ )
2715
+ ),
2716
+ el('tbody', {},
2717
+ ...(data.results || []).map((r) => {
2718
+ const passBadge = createBadge(r.pass ? 'PASS' : 'FAIL', r.pass ? 'emerald' : 'rose', true);
2719
+ return el('tr', {},
2720
+ el('td', {}, el('strong', { textContent: r.name })),
2721
+ el('td', {}, passBadge),
2722
+ el('td', {}, el('span', { className: 'code-pill text-mono' }, r.expected)),
2723
+ el('td', {}, el('span', { className: 'code-pill text-mono', style: { color: r.pass ? 'var(--accent-emerald)' : 'var(--accent-rose)' } }, r.actual))
2724
+ );
2725
+ })
2726
+ )
2727
+ );
2728
+ resultsContainer.replaceChildren(table);
2729
+ }
2730
+
2731
+ function renderFailurePatternsTable() {
2732
+ const container = document.getElementById('failurePatternsContainer');
2733
+ if (!container || !statsData) return;
2734
+
2735
+ const list = statsData.failure_patterns || [];
2736
+ container.replaceChildren();
2737
+
2738
+ if (list.length === 0) {
2739
+ container.appendChild(
2740
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } },
2741
+ 'No failure patterns currently registered. Failure patterns are created automatically via SQL UPSERT when observations or trajectories fail.'
2742
+ )
2743
+ );
2744
+ return;
2745
+ }
2746
+
2747
+ const table = el('table', { className: 'data-table' },
2748
+ el('thead', {},
2749
+ el('tr', {},
2750
+ el('th', {}, 'Project'),
2751
+ el('th', {}, 'Task Type'),
2752
+ el('th', {}, 'Occurrences (SQL UPSERT)'),
2753
+ el('th', {}, 'Last Seen'),
2754
+ el('th', {}, 'Error Verbatim Pattern')
2755
+ )
2756
+ ),
2757
+ el('tbody', {},
2758
+ ...list.map((fp) => {
2759
+ return el('tr', {},
2760
+ el('td', {}, createBadge(fp.project_id || 'global', 'subtle', true)),
2761
+ el('td', {}, el('span', { className: 'code-pill' }, fp.task_type)),
2762
+ el('td', {}, el('span', { className: 'badge badge-rose badge-mono' }, String(fp.count))),
2763
+ el('td', {}, el('span', { className: 'text-mono', style: { fontSize: '12px' } }, formatTimestamp(fp.last_seen_at))),
2764
+ el('td', {}, el('pre', { className: 'code-block', style: { padding: '6px 10px', fontSize: '11px', margin: 0 }, textContent: fp.error_text }))
2765
+ );
2766
+ })
2767
+ )
2768
+ );
2769
+
2770
+ container.appendChild(table);
2771
+ }
2772
+
2773
+ function renderDeadLettersSection() {
2774
+ const breakdownContainer = document.getElementById('deadLettersBreakdownContainer');
2775
+ const tableContainer = document.getElementById('deadLettersContainer');
2776
+ if (!breakdownContainer || !tableContainer || !statsData) return;
2777
+
2778
+ breakdownContainer.replaceChildren();
2779
+ tableContainer.replaceChildren();
2780
+
2781
+ const deadLettersData = statsData.dead_letters || {};
2782
+ const items = deadLettersData.items || [];
2783
+ const byReason = deadLettersData.by_reason || [];
2784
+ const byProducer = deadLettersData.by_producer || [];
2785
+
2786
+ // Breakdown Pills
2787
+ const breakdownPills = el('div', { style: { display: 'flex', gap: '8px', flexWrap: 'wrap' } });
2788
+ breakdownPills.appendChild(el('span', { className: 'text-muted', style: { fontSize: '12px', fontWeight: '600' } }, 'REASON BREAKDOWN:'));
2789
+
2790
+ if (byReason.length === 0) {
2791
+ breakdownPills.appendChild(el('span', { className: 'text-muted' }, '0 dead letters recorded.'));
2792
+ } else {
2793
+ byReason.forEach((r) => {
2794
+ breakdownPills.appendChild(createBadge(r.reason + ': ' + r.count, 'rose', true));
2795
+ });
2796
+ }
2797
+ breakdownContainer.appendChild(breakdownPills);
2798
+
2799
+ if (items.length === 0) {
2800
+ tableContainer.appendChild(
2801
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } },
2802
+ 'No dead letters recorded. Under Rule 3, records are only dead-lettered for malformed payloads.'
2803
+ )
2804
+ );
2805
+ return;
2806
+ }
2807
+
2808
+ const table = el('table', { className: 'data-table' },
2809
+ el('thead', {},
2810
+ el('tr', {},
2811
+ el('th', {}, 'ID'),
2812
+ el('th', {}, 'Source'),
2813
+ el('th', {}, 'Rejection Reason'),
2814
+ el('th', {}, 'Producer'),
2815
+ el('th', {}, 'Created At'),
2816
+ el('th', {}, 'Payload Inspector')
2817
+ )
2818
+ ),
2819
+ el('tbody', {},
2820
+ ...items.map((dl) => {
2821
+ return el('tr', {},
2822
+ el('td', {}, el('span', { className: 'code-pill text-mono' }, dl.id)),
2823
+ el('td', {}, createBadge(dl.source, 'subtle', true)),
2824
+ el('td', {}, createBadge(dl.reason, 'rose', true)),
2825
+ el('td', {}, el('span', { className: 'code-pill' }, dl.producer || 'unknown')),
2826
+ el('td', {}, el('span', { className: 'text-mono', style: { fontSize: '12px' } }, formatTimestamp(dl.created_at))),
2827
+ el('td', {},
2828
+ el('button', {
2829
+ className: 'btn',
2830
+ style: { height: '30px', padding: '0 10px', fontSize: '12px' },
2831
+ onClick: () => {
2832
+ showModal('Dead Letter Payload Inspector (' + dl.id + ')', [
2833
+ el('div', { style: { marginBottom: '8px' } },
2834
+ createBadge('REASON: ' + dl.reason, 'rose', true),
2835
+ createBadge('PRODUCER: ' + (dl.producer || 'unknown'), 'purple', true)
2836
+ ),
2837
+ el('pre', { className: 'code-block', style: { maxHeight: '400px' }, textContent: dl.payload })
2838
+ ]);
2839
+ }
2840
+ }, 'Inspect Payload')
2841
+ )
2842
+ );
2843
+ })
2844
+ )
2845
+ );
2846
+
2847
+ tableContainer.appendChild(table);
2848
+ }
2849
+
2850
+ // API Key Management & Generator Modal (Safe DOM only)
2851
+ async function openApiKeyManagerModal(newKeyData) {
2852
+ const modalBodyNodes = [];
2853
+
2854
+ // 1. Newly generated key banner (if just generated)
2855
+ if (newKeyData && newKeyData.key) {
2856
+ const banner = el('div', {
2857
+ style: {
2858
+ backgroundColor: 'rgba(16, 185, 129, 0.08)',
2859
+ border: '1px solid var(--accent-emerald-border)',
2860
+ borderRadius: '8px',
2861
+ padding: '14px',
2862
+ marginBottom: '16px'
2863
+ }
2864
+ },
2865
+ el('div', {
2866
+ style: {
2867
+ display: 'flex',
2868
+ alignItems: 'center',
2869
+ justifyContent: 'space-between',
2870
+ marginBottom: '8px'
2871
+ }
2872
+ },
2873
+ el('strong', {
2874
+ style: { color: '#6ee7b7', fontSize: '13px' },
2875
+ textContent: '✓ API Key Successfully Created'
2876
+ }),
2877
+ createBadge('SAVE SECURELY - SHOWN ONCE', 'emerald', true)
2878
+ ),
2879
+ el('div', {
2880
+ style: {
2881
+ fontSize: '12px',
2882
+ color: 'var(--text-secondary)',
2883
+ marginBottom: '10px',
2884
+ lineHeight: '1.4'
2885
+ },
2886
+ textContent: 'This raw key will never be shown again. Copy it now and store it in your agent environment or .env file.'
2887
+ }),
2888
+ el('div', {
2889
+ style: {
2890
+ display: 'flex',
2891
+ gap: '8px',
2892
+ alignItems: 'center'
2893
+ }
2894
+ },
2895
+ el('input', {
2896
+ type: 'text',
2897
+ readOnly: true,
2898
+ value: newKeyData.key,
2899
+ className: 'form-input',
2900
+ style: {
2901
+ flex: '1',
2902
+ fontFamily: 'var(--font-mono)',
2903
+ fontSize: '12px',
2904
+ backgroundColor: 'var(--bg-base)',
2905
+ color: '#6ee7b7'
2906
+ }
2907
+ }),
2908
+ el('button', {
2909
+ className: 'btn btn-primary',
2910
+ style: { cursor: 'pointer', height: '38px' },
2911
+ onClick: async () => {
2912
+ try {
2913
+ await navigator.clipboard.writeText(newKeyData.key);
2914
+ showToast('API key copied to clipboard!', 'emerald', 3000);
2915
+ } catch {
2916
+ showToast('Failed to copy to clipboard', 'rose');
2917
+ }
2918
+ }
2919
+ }, 'Copy Key')
2920
+ )
2921
+ );
2922
+ modalBodyNodes.push(banner);
2923
+ }
2924
+
2925
+ // 2. Ready-to-paste MCP Configuration
2926
+ const mcpRawKey = (newKeyData && newKeyData.key) ? newKeyData.key : 'YOUR_API_KEY';
2927
+ const mcpConfigObj = {
2928
+ mcpServers: {
2929
+ 'neuralbrain': {
2930
+ command: 'neuralbrain',
2931
+ args: ['mcp'],
2932
+ env: {
2933
+ BRAIN_API_URL: (window && window.location && window.location.origin) ? window.location.origin : 'http://127.0.0.1:3737',
2934
+ BRAIN_API_KEY: mcpRawKey
2935
+ }
2936
+ }
2937
+ }
2938
+ };
2939
+ const mcpSnippetText = JSON.stringify(mcpConfigObj, null, 2);
2940
+
2941
+ const mcpSection = el('div', {
2942
+ style: {
2943
+ marginBottom: '20px',
2944
+ backgroundColor: 'var(--bg-card)',
2945
+ border: '1px solid var(--border-color)',
2946
+ borderRadius: '8px',
2947
+ padding: '14px'
2948
+ }
2949
+ },
2950
+ el('div', {
2951
+ style: {
2952
+ display: 'flex',
2953
+ justifyContent: 'space-between',
2954
+ alignItems: 'center',
2955
+ marginBottom: '8px'
2956
+ }
2957
+ },
2958
+ el('div', {
2959
+ style: { fontWeight: '600', fontSize: '13px', color: 'var(--text-primary)' },
2960
+ textContent: 'Agent MCP Configuration (Antigravity / Claude Code)'
2961
+ }),
2962
+ el('button', {
2963
+ className: 'btn',
2964
+ style: { height: '30px', padding: '0 12px', fontSize: '12px', cursor: 'pointer' },
2965
+ onClick: async () => {
2966
+ try {
2967
+ await navigator.clipboard.writeText(mcpSnippetText);
2968
+ showToast('MCP configuration JSON copied to clipboard!', 'emerald', 3000);
2969
+ } catch {
2970
+ showToast('Failed to copy to clipboard', 'rose');
2971
+ }
2972
+ }
2973
+ }, 'Copy MCP JSON')
2974
+ ),
2975
+ el('pre', {
2976
+ className: 'code-block',
2977
+ style: {
2978
+ maxHeight: '160px',
2979
+ overflowY: 'auto',
2980
+ fontSize: '11px',
2981
+ margin: '0',
2982
+ backgroundColor: 'var(--bg-base)'
2983
+ },
2984
+ textContent: mcpSnippetText
2985
+ })
2986
+ );
2987
+ modalBodyNodes.push(mcpSection);
2988
+
2989
+ // 3. Active Keys List Section
2990
+ const activeKeysContainer = el('div', {
2991
+ style: {
2992
+ border: '1px solid var(--border-color)',
2993
+ borderRadius: '8px',
2994
+ padding: '14px',
2995
+ backgroundColor: 'var(--bg-card)'
2996
+ }
2997
+ });
2998
+
2999
+ const activeKeysHeader = el('div', {
3000
+ style: {
3001
+ display: 'flex',
3002
+ justifyContent: 'space-between',
3003
+ alignItems: 'center',
3004
+ marginBottom: '10px'
3005
+ }
3006
+ },
3007
+ el('div', {
3008
+ style: { fontWeight: '600', fontSize: '13px', color: 'var(--text-primary)' },
3009
+ textContent: 'Active API Keys'
3010
+ }),
3011
+ el('button', {
3012
+ className: 'btn',
3013
+ style: { height: '28px', padding: '0 10px', fontSize: '11px', cursor: 'pointer' },
3014
+ onClick: () => refreshKeysList()
3015
+ }, 'Refresh')
3016
+ );
3017
+ activeKeysContainer.appendChild(activeKeysHeader);
3018
+
3019
+ const keysTableWrapper = el('div', { style: { overflowX: 'auto' } });
3020
+ activeKeysContainer.appendChild(keysTableWrapper);
3021
+ modalBodyNodes.push(activeKeysContainer);
3022
+
3023
+ async function refreshKeysList() {
3024
+ keysTableWrapper.replaceChildren();
3025
+ const loading = el('div', {
3026
+ style: { padding: '16px', textAlign: 'center', color: 'var(--text-muted)', fontSize: '12px' },
3027
+ textContent: 'Loading active keys...'
3028
+ });
3029
+ keysTableWrapper.appendChild(loading);
3030
+
3031
+ try {
3032
+ const resp = await apiFetch('/maintenance/api-keys');
3033
+ const keys = await resp.json();
3034
+ keysTableWrapper.replaceChildren();
3035
+
3036
+ if (!resp.ok) {
3037
+ keysTableWrapper.appendChild(el('div', {
3038
+ style: { padding: '12px', color: '#fda4af', fontSize: '12px' },
3039
+ textContent: keys.error?.message || 'Failed to load keys'
3040
+ }));
3041
+ return;
3042
+ }
3043
+
3044
+ if (!Array.isArray(keys) || keys.length === 0) {
3045
+ keysTableWrapper.appendChild(el('div', {
3046
+ style: { padding: '16px', textAlign: 'center', color: 'var(--text-muted)', fontSize: '12px' },
3047
+ textContent: 'No active API keys found.'
3048
+ }));
3049
+ return;
3050
+ }
3051
+
3052
+ const table = el('table', { className: 'data-table', style: { width: '100%', fontSize: '12px' } },
3053
+ el('thead', null,
3054
+ el('tr', null,
3055
+ el('th', { style: { textAlign: 'left', padding: '8px' } }, 'Name'),
3056
+ el('th', { style: { textAlign: 'left', padding: '8px' } }, 'Key ID'),
3057
+ el('th', { style: { textAlign: 'left', padding: '8px' } }, 'Created'),
3058
+ el('th', { style: { textAlign: 'left', padding: '8px' } }, 'Last Used'),
3059
+ el('th', { style: { textAlign: 'center', padding: '8px', width: '80px' } }, 'Action')
3060
+ )
3061
+ ),
3062
+ el('tbody', null,
3063
+ ...keys.map((k) => {
3064
+ const tr = el('tr', null,
3065
+ el('td', { style: { padding: '8px', fontWeight: '500' }, textContent: k.name || 'unnamed' }),
3066
+ el('td', { style: { padding: '8px', fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--text-secondary)' }, textContent: k.id }),
3067
+ el('td', { style: { padding: '8px', color: 'var(--text-secondary)' }, textContent: k.created_at ? new Date(k.created_at).toLocaleDateString() : 'unknown' }),
3068
+ el('td', { style: { padding: '8px', color: 'var(--text-secondary)' }, textContent: k.last_used_at ? new Date(k.last_used_at).toLocaleTimeString() : 'never' }),
3069
+ el('td', { style: { padding: '8px', textAlign: 'center' } },
3070
+ el('button', {
3071
+ className: 'btn btn-rose',
3072
+ style: { height: '26px', padding: '0 8px', fontSize: '11px', cursor: 'pointer' },
3073
+ onClick: async () => {
3074
+ try {
3075
+ const delResp = await apiFetch('/maintenance/api-keys/' + encodeURIComponent(k.id), {
3076
+ method: 'DELETE'
3077
+ });
3078
+ if (delResp.ok) {
3079
+ showToast('API key "' + k.name + '" revoked', 'emerald', 2500);
3080
+ await refreshKeysList();
3081
+ } else {
3082
+ const errData = await delResp.json();
3083
+ showToast('Failed to revoke: ' + (errData.error?.message || 'Unknown error'), 'rose');
3084
+ }
3085
+ } catch (err) {
3086
+ showToast('Revoke error: ' + err.message, 'rose');
3087
+ }
3088
+ }
3089
+ }, 'Revoke')
3090
+ )
3091
+ );
3092
+ return tr;
3093
+ })
3094
+ )
3095
+ );
3096
+ keysTableWrapper.appendChild(table);
3097
+ } catch (err) {
3098
+ keysTableWrapper.replaceChildren();
3099
+ keysTableWrapper.appendChild(el('div', {
3100
+ style: { padding: '12px', color: '#fda4af', fontSize: '12px' },
3101
+ textContent: 'Error loading API keys: ' + err.message
3102
+ }));
3103
+ }
3104
+ }
3105
+
3106
+ await refreshKeysList();
3107
+
3108
+ // Show modal dialog
3109
+ showModal('API Key & MCP Configuration Manager', modalBodyNodes, [
3110
+ {
3111
+ label: '+ Generate Another Key',
3112
+ variant: 'emerald',
3113
+ onClick: async (_e, _close) => {
3114
+ try {
3115
+ const resp = await apiFetch('/maintenance/api-keys', {
3116
+ method: 'POST',
3117
+ headers: { 'Content-Type': 'application/json' },
3118
+ body: JSON.stringify({ name: 'dashboard-generated' })
3119
+ });
3120
+ const data = await resp.json();
3121
+ if (!resp.ok) throw new Error(data.error?.message || 'Failed to create key');
3122
+ showToast('New API key generated!', 'emerald', 2500);
3123
+ await openApiKeyManagerModal(data);
3124
+ } catch (err) {
3125
+ showToast('Generate key error: ' + err.message, 'rose');
3126
+ }
3127
+ }
3128
+ }
3129
+ ]);
3130
+ }
3131
+
3132
+ // Quick Action Buttons
3133
+ function initActionButtons() {
3134
+ // 0. Generate API Key Button
3135
+ const btnGenApiKey = document.getElementById('btnGenerateApiKey');
3136
+ if (btnGenApiKey) {
3137
+ btnGenApiKey.addEventListener('click', async () => {
3138
+ // If keys already exist and current window is not authenticated, warn user immediately!
3139
+ if (!isBootstrapRequired && !isSessionAuthenticated && !inMemoryApiKey) {
3140
+ showToast('Authentication required: Paste your existing API key in the top bar before generating or managing keys.', 'rose', 6000);
3141
+ const apiKeyInput = document.getElementById('inputDashboardApiKey');
3142
+ if (apiKeyInput) apiKeyInput.focus();
3143
+ return;
3144
+ }
3145
+
3146
+ try {
3147
+ btnGenApiKey.disabled = true;
3148
+ btnGenApiKey.textContent = isBootstrapRequired ? 'Claiming...' : 'Generating...';
3149
+ const resp = await apiFetch('/maintenance/api-keys', {
3150
+ method: 'POST',
3151
+ headers: { 'Content-Type': 'application/json' },
3152
+ body: JSON.stringify({ name: isBootstrapRequired ? 'initial-operator-key' : 'dashboard-generated' })
3153
+ });
3154
+ const data = await resp.json();
3155
+ if (!resp.ok) {
3156
+ if (resp.status === 401) {
3157
+ throw new Error('Authentication required: Paste your existing API key in the top bar before generating or managing keys.');
3158
+ }
3159
+ throw new Error(data.error?.message || 'Failed to generate API key');
3160
+ }
3161
+
3162
+ // Automatically activate the key in this window!
3163
+ inMemoryApiKey = data.key;
3164
+ isSessionAuthenticated = true;
3165
+ sessionKeyName = data.name || 'Active';
3166
+ isBootstrapRequired = false;
3167
+ updateAuthStatusUI();
3168
+
3169
+ showToast(isBootstrapRequired ? 'First-time key claimed successfully!' : 'API key created successfully!', 'emerald', 3000);
3170
+ await openApiKeyManagerModal(data);
3171
+ await fetchStats();
3172
+ refreshActiveTab();
3173
+ } catch (err) {
3174
+ showToast(err.message, 'rose', 6000);
3175
+ } finally {
3176
+ btnGenApiKey.disabled = false;
3177
+ updateAuthStatusUI();
3178
+ }
3179
+ });
3180
+ }
3181
+
3182
+ // 0b. Logout API Key Button
3183
+ const btnLogoutApiKey = document.getElementById('btnLogoutApiKey');
3184
+ if (btnLogoutApiKey) {
3185
+ btnLogoutApiKey.addEventListener('click', async () => {
3186
+ try {
3187
+ await apiFetch('/dashboard/api/session', { method: 'DELETE' });
3188
+ } catch {
3189
+ // ignore
3190
+ }
3191
+ inMemoryApiKey = '';
3192
+ isSessionAuthenticated = false;
3193
+ sessionKeyName = '';
3194
+ updateAuthStatusUI();
3195
+ showToast('Logged out of dashboard session.', 'amber', 3000);
3196
+ const apiKeyInput = document.getElementById('inputDashboardApiKey');
3197
+ if (apiKeyInput) apiKeyInput.focus();
3198
+ });
3199
+ }
3200
+
3201
+ // 1. Drain Embed Queue
3202
+ const btnDrain = document.getElementById('btnDrainEmbed');
3203
+ if (btnDrain) {
3204
+ btnDrain.addEventListener('click', async () => {
3205
+ try {
3206
+ btnDrain.disabled = true;
3207
+ btnDrain.textContent = 'Draining...';
3208
+ const resp = await apiFetch('/dashboard/api/drain-embed', { method: 'POST' });
3209
+ const result = await resp.json();
3210
+ if (!resp.ok) throw new Error(result.error || 'Drain failed');
3211
+
3212
+ showToast('Drain complete! Processed ' + result.processed + ' embeddings (' + result.remaining + ' remaining)', 'emerald');
3213
+ await fetchStats();
3214
+ } catch (err) {
3215
+ showToast('Drain error: ' + err.message, 'rose');
3216
+ } finally {
3217
+ btnDrain.disabled = false;
3218
+ btnDrain.textContent = 'Drain Embed Queue';
3219
+ }
3220
+ });
3221
+ }
3222
+
3223
+ // 3. Retention Cleanup Pass
3224
+ const btnCleanup = document.getElementById('btnCleanup');
3225
+ if (btnCleanup) {
3226
+ btnCleanup.addEventListener('click', async () => {
3227
+ try {
3228
+ btnCleanup.disabled = true;
3229
+ btnCleanup.textContent = 'Running Cleanup...';
3230
+ const resp = await apiFetch('/maintenance/cleanup', { method: 'POST' });
3231
+ const result = await resp.json();
3232
+ if (!resp.ok) throw new Error('Cleanup failed');
3233
+
3234
+ showToast('Retention cleanup done: ' + (result.observationsArchived || 0) + ' obs archived, ' + (result.trajectoriesArchived || 0) + ' trajectories archived', 'emerald');
3235
+ await fetchStats();
3236
+ } catch (err) {
3237
+ showToast('Cleanup error: ' + err.message, 'rose');
3238
+ } finally {
3239
+ btnCleanup.disabled = false;
3240
+ btnCleanup.textContent = 'Run Retention Cleanup';
3241
+ }
3242
+ });
3243
+ }
3244
+
3245
+ // 4. Refresh Data
3246
+ const btnRefresh = document.getElementById('btnRefresh');
3247
+ if (btnRefresh) {
3248
+ btnRefresh.addEventListener('click', async () => {
3249
+ btnRefresh.textContent = 'Refreshing...';
3250
+ await fetchStats();
3251
+ btnRefresh.textContent = 'Refresh Data';
3252
+ showToast('Telemetry and memory layer stats refreshed', 'cyan', 2000);
3253
+ });
3254
+ }
3255
+
3256
+ // 5. Re-embed Button on Mismatch Warning Banner
3257
+ const btnReembed = document.getElementById('btnBannerReembed');
3258
+ if (btnReembed) {
3259
+ btnReembed.addEventListener('click', async () => {
3260
+ try {
3261
+ btnReembed.disabled = true;
3262
+ btnReembed.textContent = 'Starting Atomic Re-embed...';
3263
+ const resp = await apiFetch('/maintenance/reembed', { method: 'POST' });
3264
+ const result = await resp.json();
3265
+ if (!resp.ok) throw new Error(result.error?.message || 'Re-embed failed to start');
3266
+
3267
+ showToast('Atomic re-embed initiated: collection ' + (result.collection || 'new'), 'emerald', 6000);
3268
+ pollReembedProgress();
3269
+ } catch (err) {
3270
+ showToast('Re-embed error: ' + err.message, 'rose');
3271
+ btnReembed.disabled = false;
3272
+ btnReembed.textContent = 'Run Atomic Re-embed';
3273
+ }
3274
+ });
3275
+ }
3276
+
3277
+ // 6. Test Capture Button
3278
+ const btnOpenCapture = document.getElementById('btnOpenCaptureModal');
3279
+ if (btnOpenCapture) {
3280
+ btnOpenCapture.addEventListener('click', () => {
3281
+ openCaptureModal(activeSubTab === 'trajectories' ? 'trajectory' : 'observation');
3282
+ });
3283
+ }
3284
+ }
3285
+
3286
+ function updateReembedUI(status) {
3287
+ const reembedBadge = document.getElementById('reembedBadge');
3288
+ const reembedText = document.getElementById('reembedText');
3289
+ const btnReembed = document.getElementById('btnBannerReembed');
3290
+
3291
+ if (!status || status.status === 'idle') {
3292
+ if (reembedBadge) reembedBadge.classList.add('hidden');
3293
+ if (btnReembed) {
3294
+ btnReembed.disabled = false;
3295
+ btnReembed.textContent = 'Run Atomic Re-embed';
3296
+ }
3297
+ return;
3298
+ }
3299
+
3300
+ const total = Number(status.total) || 0;
3301
+ const processed = Number(status.processed) || 0;
3302
+ const failed = Number(status.failed) || 0;
3303
+ const pct = total > 0 ? Math.min(100, Math.round((processed / total) * 100)) : 0;
3304
+
3305
+ if (reembedBadge && reembedText) {
3306
+ reembedBadge.classList.remove('hidden');
3307
+ if (status.status === 'running') {
3308
+ reembedBadge.className = 'badge badge-amber badge-mono';
3309
+ reembedText.textContent = 'REEMBED: ' + processed + '/' + total + ' (' + pct + '%)';
3310
+ } else if (status.status === 'completed') {
3311
+ reembedBadge.className = 'badge badge-emerald badge-mono';
3312
+ reembedText.textContent = 'REEMBED: done ' + processed + '/' + total;
3313
+ } else if (status.status === 'failed') {
3314
+ reembedBadge.className = 'badge badge-rose badge-mono';
3315
+ reembedText.textContent = 'REEMBED: failed';
3316
+ }
3317
+ reembedBadge.title = 'Collection: ' + (status.collection || 'n/a') +
3318
+ ' | Processed: ' + processed + '/' + total +
3319
+ ' | Failed: ' + failed +
3320
+ (status.error ? ' | Error: ' + status.error : '');
3321
+ }
3322
+
3323
+ if (btnReembed) {
3324
+ if (status.status === 'running') {
3325
+ btnReembed.disabled = true;
3326
+ btnReembed.textContent = 'Re-embedding ' + processed + '/' + total + ' (' + pct + '%)...';
3327
+ } else {
3328
+ btnReembed.disabled = false;
3329
+ btnReembed.textContent = 'Run Atomic Re-embed';
3330
+ }
3331
+ }
3332
+ }
3333
+
3334
+ // Poll Re-embed Progress
3335
+ async function pollReembedProgress() {
3336
+ if (isReembedding) return;
3337
+ isReembedding = true;
3338
+
3339
+ let consecutiveErrors = 0;
3340
+
3341
+ const scheduleNextPoll = () => {
3342
+ setTimeout(async () => {
3343
+ let shouldContinue = true;
3344
+ try {
3345
+ const resp = await apiFetch('/maintenance/reembed');
3346
+ if (!resp.ok) {
3347
+ consecutiveErrors++;
3348
+ if (consecutiveErrors >= 5) {
3349
+ shouldContinue = false;
3350
+ isReembedding = false;
3351
+ showToast('Re-embed polling stopped after 5 consecutive errors', 'rose', 6000);
3352
+ const btnReembed = document.getElementById('btnBannerReembed');
3353
+ if (btnReembed) {
3354
+ btnReembed.disabled = false;
3355
+ btnReembed.textContent = 'Run Atomic Re-embed';
3356
+ }
3357
+ }
3358
+ return;
3359
+ }
3360
+ consecutiveErrors = 0;
3361
+ const status = await resp.json();
3362
+ updateReembedUI(status);
3363
+
3364
+ if (status.status === 'completed') {
3365
+ shouldContinue = false;
3366
+ isReembedding = false;
3367
+ showToast('Atomic re-embed successfully completed! Processed ' + status.processed + ' vectors', 'emerald', 7000);
3368
+ await fetchStats();
3369
+ const btnReembed = document.getElementById('btnBannerReembed');
3370
+ if (btnReembed) {
3371
+ btnReembed.disabled = false;
3372
+ btnReembed.textContent = 'Run Atomic Re-embed';
3373
+ }
3374
+ } else if (status.status === 'failed') {
3375
+ shouldContinue = false;
3376
+ isReembedding = false;
3377
+ showToast('Re-embed failed: ' + status.error, 'rose', 7000);
3378
+ const btnReembed = document.getElementById('btnBannerReembed');
3379
+ if (btnReembed) {
3380
+ btnReembed.disabled = false;
3381
+ btnReembed.textContent = 'Run Atomic Re-embed';
3382
+ }
3383
+ }
3384
+ } catch {
3385
+ consecutiveErrors++;
3386
+ if (consecutiveErrors >= 5) {
3387
+ shouldContinue = false;
3388
+ isReembedding = false;
3389
+ showToast('Re-embed polling stopped after network errors', 'rose', 6000);
3390
+ const btnReembed = document.getElementById('btnBannerReembed');
3391
+ if (btnReembed) {
3392
+ btnReembed.disabled = false;
3393
+ btnReembed.textContent = 'Run Atomic Re-embed';
3394
+ }
3395
+ }
3396
+ } finally {
3397
+ if (shouldContinue && isReembedding) {
3398
+ scheduleNextPoll();
3399
+ }
3400
+ }
3401
+ }, 2000);
3402
+ };
3403
+
3404
+ scheduleNextPoll();
3405
+ }
3406
+
3407
+ // =========================================================================
3408
+ // Short-Term Tab (Sessions, Next Actions & Session Replay)
3409
+ // =========================================================================
3410
+ function initShortTermTab() {
3411
+ const sessWrapper = document.getElementById('shortSessionsProjectDropdownWrapper');
3412
+ const sessInput = document.getElementById('shortSessionsProject');
3413
+ if (sessWrapper && sessInput) {
3414
+ attachSearchableProjectDropdown(sessWrapper, sessInput, {
3415
+ includeAllOption: true,
3416
+ allOptionLabel: 'All Projects',
3417
+ onSelect: () => loadShortSessions(),
3418
+ onEnter: () => loadShortSessions()
3419
+ });
3420
+ }
3421
+
3422
+ const actWrapper = document.getElementById('shortActionsProjectDropdownWrapper');
3423
+ const actInput = document.getElementById('shortActionsProject');
3424
+ if (actWrapper && actInput) {
3425
+ attachSearchableProjectDropdown(actWrapper, actInput, {
3426
+ includeAllOption: true,
3427
+ allOptionLabel: 'All Projects',
3428
+ onSelect: () => loadShortActions(),
3429
+ onEnter: () => loadShortActions()
3430
+ });
3431
+ }
3432
+
3433
+ const btnSess = document.getElementById('btnFilterShortSessions');
3434
+ if (btnSess) btnSess.addEventListener('click', loadShortSessions);
3435
+ const selSessStatus = document.getElementById('shortSessionsStatus');
3436
+ if (selSessStatus) selSessStatus.addEventListener('change', loadShortSessions);
3437
+
3438
+ const btnAct = document.getElementById('btnFilterShortActions');
3439
+ if (btnAct) btnAct.addEventListener('click', loadShortActions);
3440
+ const selActStatus = document.getElementById('shortActionsStatus');
3441
+ if (selActStatus) selActStatus.addEventListener('change', loadShortActions);
3442
+ }
3443
+
3444
+ function switchShortSubTab(subTabKey) {
3445
+ activeShortSubTab = subTabKey;
3446
+ const buttons = document.querySelectorAll('#paneShortTerm button[data-short-subtab]');
3447
+ buttons.forEach((btn) => {
3448
+ btn.className = btn.getAttribute('data-short-subtab') === subTabKey ? 'btn btn-primary' : 'btn';
3449
+ });
3450
+ const sessBar = document.getElementById('shortSessionsFilterBar');
3451
+ const actBar = document.getElementById('shortActionsFilterBar');
3452
+ if (sessBar) sessBar.classList.toggle('hidden', subTabKey !== 'sessions');
3453
+ if (actBar) actBar.classList.toggle('hidden', subTabKey !== 'actions');
3454
+ renderShortTermSubView();
3455
+ }
3456
+
3457
+ function renderShortTermSubView() {
3458
+ if (activeShortSubTab === 'actions') {
3459
+ loadShortActions();
3460
+ } else if (activeShortSubTab === 'summaries') {
3461
+ const container = document.getElementById('shortTermListContainer');
3462
+ if (container) renderSummariesList(container);
3463
+ } else {
3464
+ loadShortSessions();
3465
+ }
3466
+ }
3467
+
3468
+ function getSessionStatusVariant(status) {
3469
+ if (status === 'active') return 'emerald';
3470
+ if (status === 'paused') return 'amber';
3471
+ if (status === 'completed') return 'cyan';
3472
+ if (status === 'abandoned') return 'rose';
3473
+ return 'subtle';
3474
+ }
3475
+
3476
+ function getActionPriorityVariant(priority) {
3477
+ if (priority === 'urgent') return 'rose';
3478
+ if (priority === 'high') return 'amber';
3479
+ if (priority === 'normal') return 'cyan';
3480
+ return 'subtle';
3481
+ }
3482
+
3483
+ function getActionStatusVariant(status) {
3484
+ if (status === 'ready') return 'emerald';
3485
+ if (status === 'blocked') return 'rose';
3486
+ if (status === 'in_progress') return 'cyan';
3487
+ return 'subtle';
3488
+ }
3489
+
3490
+ async function loadShortSessions() {
3491
+ const container = document.getElementById('shortTermListContainer');
3492
+ if (!container) return;
3493
+ container.replaceChildren(
3494
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading sessions...')
3495
+ );
3496
+
3497
+ const projInput = document.getElementById('shortSessionsProject');
3498
+ const statusSelect = document.getElementById('shortSessionsStatus');
3499
+ let projVal = projInput ? projInput.value.trim() : '';
3500
+ if (projVal.toLowerCase() === 'all projects') projVal = '';
3501
+
3502
+ const params = new URLSearchParams();
3503
+ if (projVal) params.set('project_id', projVal);
3504
+ if (statusSelect && statusSelect.value) params.set('status', statusSelect.value);
3505
+ params.set('limit', '50');
3506
+
3507
+ try {
3508
+ const resp = await apiFetch('/sessions?' + params.toString());
3509
+ if (!resp.ok) throw new Error('Failed to load sessions: ' + resp.status);
3510
+ const data = await resp.json();
3511
+ const sessions = Array.isArray(data.sessions) ? data.sessions : [];
3512
+
3513
+ container.replaceChildren();
3514
+ if (sessions.length === 0) {
3515
+ container.appendChild(
3516
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'No sessions match the current filters.')
3517
+ );
3518
+ return;
3519
+ }
3520
+
3521
+ sessions.forEach((sess) => {
3522
+ const card = el('div', { className: 'result-card' });
3523
+ const agentName = sess.agent_name || 'unknown-agent';
3524
+ const scopeVariant = sess.scope === 'project' ? 'emerald' : (sess.scope === 'global' ? 'cyan' : 'rose');
3525
+
3526
+ const headerLeft = el('div', { className: 'control-row', style: { flexWrap: 'wrap' } },
3527
+ createBadge(agentName, 'purple', true),
3528
+ createBadge((sess.status || 'active').toUpperCase(), getSessionStatusVariant(sess.status), true),
3529
+ createBadge(sess.scope || 'unknown', scopeVariant, true),
3530
+ sess.project_id ? createBadge(sess.project_id, 'subtle', true) : null
3531
+ );
3532
+
3533
+ const replayBtn = el('button', {
3534
+ type: 'button',
3535
+ className: 'btn btn-primary',
3536
+ onClick: () => showSessionReplayModal(sess.id)
3537
+ }, 'Replay');
3538
+
3539
+ card.appendChild(el('div', { className: 'card-header', style: { marginBottom: '8px' } },
3540
+ headerLeft,
3541
+ replayBtn
3542
+ ));
3543
+
3544
+ card.appendChild(el('div', { style: { fontSize: '13px', marginBottom: '6px' } },
3545
+ sess.summary ? sess.summary : el('span', { className: 'text-muted' }, 'No session summary recorded.')
3546
+ ));
3547
+
3548
+ card.appendChild(el('div', { className: 'text-muted text-mono', style: { fontSize: '11px' } },
3549
+ 'ID: ' + sess.id + ' · Started: ' + formatTimestamp(sess.started_at) +
3550
+ (sess.ended_at ? ' · Ended: ' + formatTimestamp(sess.ended_at) : '')
3551
+ ));
3552
+
3553
+ container.appendChild(card);
3554
+ });
3555
+ } catch (err) {
3556
+ container.replaceChildren(
3557
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
3558
+ el('span', {}, 'Error loading sessions: ' + err.message)
3559
+ )
3560
+ );
3561
+ }
3562
+ }
3563
+
3564
+ async function showSessionReplayModal(sessionId) {
3565
+ showModal(
3566
+ 'Session Replay: ' + sessionId,
3567
+ [el('div', { className: 'text-muted', style: { padding: '16px', textAlign: 'center' } }, 'Loading session replay timeline...')],
3568
+ []
3569
+ );
3570
+
3571
+ try {
3572
+ let resp = await apiFetch('/sessions/' + encodeURIComponent(sessionId) + '/replay');
3573
+ let replayData = null;
3574
+
3575
+ if (resp.status === 404) {
3576
+ resp = await apiFetch('/sessions/' + encodeURIComponent(sessionId));
3577
+ if (!resp.ok) throw new Error('Session not found (' + resp.status + ')');
3578
+ const details = await resp.json();
3579
+ const timeline = [];
3580
+ (details.observations || []).forEach((o) => {
3581
+ timeline.push({
3582
+ kind: 'observation',
3583
+ timestamp: o.created_at,
3584
+ id: o.id,
3585
+ title: o.tool_name || o.kind || 'observation',
3586
+ detail: o.output || o.input || null
3587
+ });
3588
+ });
3589
+ (details.notes || []).forEach((n) => {
3590
+ timeline.push({
3591
+ kind: 'note',
3592
+ timestamp: n.created_at,
3593
+ id: n.id,
3594
+ title: n.title || n.type || 'note',
3595
+ detail: n.content || null
3596
+ });
3597
+ });
3598
+ (details.actions || []).forEach((a) => {
3599
+ timeline.push({
3600
+ kind: 'action',
3601
+ timestamp: a.created_at,
3602
+ id: a.id,
3603
+ title: a.title || 'action',
3604
+ detail: a.description || null
3605
+ });
3606
+ });
3607
+ timeline.sort((a, b) => String(a.timestamp || '').localeCompare(String(b.timestamp || '')));
3608
+ replayData = { session: details.session, timeline };
3609
+ } else if (!resp.ok) {
3610
+ throw new Error('Replay request failed: ' + resp.status);
3611
+ } else {
3612
+ replayData = await resp.json();
3613
+ }
3614
+
3615
+ const sess = replayData.session || {};
3616
+ const timeline = Array.isArray(replayData.timeline) ? replayData.timeline : [];
3617
+
3618
+ const bodyNodes = [
3619
+ el('div', { className: 'control-row mb-4', style: { flexWrap: 'wrap' } },
3620
+ createBadge(sess.agent_name || 'unknown-agent', 'purple', true),
3621
+ createBadge((sess.status || 'unknown').toUpperCase(), getSessionStatusVariant(sess.status), true),
3622
+ sess.project_id ? createBadge(sess.project_id, 'emerald', true) : createBadge(sess.scope || 'unknown', 'subtle', true),
3623
+ el('span', { className: 'text-muted text-mono', style: { fontSize: '12px' } },
3624
+ 'Started: ' + formatTimestamp(sess.started_at)
3625
+ )
3626
+ ),
3627
+ sess.summary ? el('div', { className: 'result-card', style: { marginBottom: '12px' } },
3628
+ el('strong', {}, 'Summary: '),
3629
+ sess.summary
3630
+ ) : null
3631
+ ];
3632
+
3633
+ if (timeline.length === 0) {
3634
+ bodyNodes.push(el('div', { className: 'text-muted', style: { padding: '16px', textAlign: 'center' } }, 'No timeline events recorded for this session.'));
3635
+ } else {
3636
+ const listEl = el('div', { className: 'replay-timeline' });
3637
+ timeline.forEach((item) => {
3638
+ const kind = item.kind || 'observation';
3639
+ const kindVariant = kind === 'note' ? 'emerald' : (kind === 'action' ? 'amber' : 'cyan');
3640
+ listEl.appendChild(
3641
+ el('div', { className: 'replay-item kind-' + kind },
3642
+ el('div', { className: 'control-row', style: { justifyContent: 'space-between', marginBottom: '4px' } },
3643
+ el('div', { className: 'control-row' },
3644
+ createBadge(kind.toUpperCase(), kindVariant, true),
3645
+ el('strong', { style: { fontSize: '13px' } }, item.title || item.id)
3646
+ ),
3647
+ el('span', { className: 'text-muted text-mono', style: { fontSize: '11px' } }, formatTimestamp(item.timestamp))
3648
+ ),
3649
+ item.detail ? el('div', { style: { fontSize: '12px', color: 'var(--text-secondary)', whiteSpace: 'pre-wrap' } }, item.detail) : null
3650
+ )
3651
+ );
3652
+ });
3653
+ bodyNodes.push(listEl);
3654
+ }
3655
+
3656
+ showModal(
3657
+ 'Session Replay: ' + sessionId,
3658
+ bodyNodes,
3659
+ []
3660
+ );
3661
+ } catch (err) {
3662
+ showModal(
3663
+ 'Session Replay Error',
3664
+ [el('div', { className: 'toast toast-rose', style: { position: 'static' } }, 'Error: ' + err.message)],
3665
+ []
3666
+ );
3667
+ }
3668
+ }
3669
+
3670
+ async function loadShortActions() {
3671
+ const container = document.getElementById('shortTermListContainer');
3672
+ if (!container) return;
3673
+ container.replaceChildren(
3674
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'Loading next actions...')
3675
+ );
3676
+
3677
+ const projInput = document.getElementById('shortActionsProject');
3678
+ const statusSelect = document.getElementById('shortActionsStatus');
3679
+ let projVal = projInput ? projInput.value.trim() : '';
3680
+ if (projVal.toLowerCase() === 'all projects') projVal = '';
3681
+
3682
+ const params = new URLSearchParams();
3683
+ if (projVal) params.set('project_id', projVal);
3684
+ if (statusSelect && statusSelect.value) params.set('status', statusSelect.value);
3685
+ params.set('limit', '50');
3686
+
3687
+ try {
3688
+ const resp = await apiFetch('/actions?' + params.toString());
3689
+ if (!resp.ok) throw new Error('Failed to load actions: ' + resp.status);
3690
+ const data = await resp.json();
3691
+ const actions = Array.isArray(data.actions) ? data.actions : [];
3692
+
3693
+ container.replaceChildren();
3694
+ if (actions.length === 0) {
3695
+ container.appendChild(
3696
+ el('div', { className: 'text-muted', style: { padding: '24px', textAlign: 'center' } }, 'No next actions match the current filters.')
3697
+ );
3698
+ return;
3699
+ }
3700
+
3701
+ actions.forEach((act) => {
3702
+ const card = el('div', { className: 'result-card' });
3703
+ const scopeVariant = act.scope === 'project' ? 'emerald' : (act.scope === 'global' ? 'cyan' : 'rose');
3704
+ const isTerminal = act.status === 'done' || act.status === 'dismissed';
3705
+
3706
+ const headerLeft = el('div', { className: 'control-row', style: { flexWrap: 'wrap' } },
3707
+ createBadge((act.priority || 'normal').toUpperCase(), getActionPriorityVariant(act.priority), true),
3708
+ createBadge((act.status || 'ready').toUpperCase(), getActionStatusVariant(act.status), true),
3709
+ createBadge(act.scope || 'unknown', scopeVariant, true),
3710
+ act.project_id ? createBadge(act.project_id, 'subtle', true) : null
3711
+ );
3712
+
3713
+ const doneBtn = el('button', {
3714
+ type: 'button',
3715
+ className: 'btn btn-emerald',
3716
+ disabled: isTerminal,
3717
+ onClick: () => updateActionStatus(act.id, 'done')
3718
+ }, 'Done');
3719
+
3720
+ const dismissBtn = el('button', {
3721
+ type: 'button',
3722
+ className: 'btn',
3723
+ disabled: isTerminal,
3724
+ onClick: () => updateActionStatus(act.id, 'dismissed')
3725
+ }, 'Dismiss');
3726
+
3727
+ card.appendChild(el('div', { className: 'card-header', style: { marginBottom: '8px' } },
3728
+ headerLeft,
3729
+ el('div', { className: 'control-row' }, doneBtn, dismissBtn)
3730
+ ));
3731
+
3732
+ card.appendChild(el('div', { className: 'font-semibold', style: { fontSize: '14px', marginBottom: '4px' } }, act.title));
3733
+ if (act.description) {
3734
+ card.appendChild(el('div', { style: { fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '6px' } }, act.description));
3735
+ }
3736
+ if (act.blocked_reason) {
3737
+ card.appendChild(el('div', { style: { fontSize: '12px', color: '#fda4af', marginBottom: '6px' } }, 'Blocked: ' + act.blocked_reason));
3738
+ }
3739
+ card.appendChild(el('div', { className: 'text-muted text-mono', style: { fontSize: '11px' } },
3740
+ 'ID: ' + act.id + ' · Updated: ' + formatTimestamp(act.updated_at || act.created_at)
3741
+ ));
3742
+
3743
+ container.appendChild(card);
3744
+ });
3745
+ } catch (err) {
3746
+ container.replaceChildren(
3747
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
3748
+ el('span', {}, 'Error loading actions: ' + err.message)
3749
+ )
3750
+ );
3751
+ }
3752
+ }
3753
+
3754
+ async function updateActionStatus(actionId, status) {
3755
+ try {
3756
+ const resp = await apiFetch('/actions/' + encodeURIComponent(actionId), {
3757
+ method: 'PATCH',
3758
+ headers: { 'Content-Type': 'application/json' },
3759
+ body: JSON.stringify({ status })
3760
+ });
3761
+ if (!resp.ok) throw new Error('Update failed: ' + resp.status);
3762
+ showToast('Action marked as ' + status, 'emerald', 3000);
3763
+ loadShortActions();
3764
+ fetchStats();
3765
+ } catch (err) {
3766
+ showToast('Failed to update action: ' + err.message, 'rose');
3767
+ }
3768
+ }
3769
+
3770
+ // =========================================================================
3771
+ // Knowledge Graph Tab (SVG Renderer + Side Inspector)
3772
+ // =========================================================================
3773
+ const GRAPH_TYPE_COLORS = {
3774
+ note: '#38bdf8',
3775
+ lesson: '#f59e0b',
3776
+ concept: '#a855f7',
3777
+ file: '#10b981',
3778
+ session: '#60a5fa',
3779
+ action: '#f43f5e',
3780
+ summary: '#2dd4bf'
3781
+ };
3782
+
3783
+ function initGraphTab() {
3784
+ const graphWrapper = document.getElementById('graphProjectDropdownWrapper');
3785
+ const graphInput = document.getElementById('graphFilterProject');
3786
+ if (graphWrapper && graphInput) {
3787
+ attachSearchableProjectDropdown(graphWrapper, graphInput, {
3788
+ includeAllOption: true,
3789
+ allOptionLabel: 'All Projects',
3790
+ onSelect: () => loadGraph(),
3791
+ onEnter: () => loadGraph()
3792
+ });
3793
+ }
3794
+
3795
+ const btnLoad = document.getElementById('btnLoadGraph');
3796
+ if (btnLoad) btnLoad.addEventListener('click', loadGraph);
3797
+ const scopeSel = document.getElementById('graphFilterScope');
3798
+ if (scopeSel) scopeSel.addEventListener('change', loadGraph);
3799
+ const limitSel = document.getElementById('graphFilterLimit');
3800
+ if (limitSel) limitSel.addEventListener('change', loadGraph);
3801
+ }
3802
+
3803
+ async function loadGraph() {
3804
+ const canvasWrap = document.getElementById('graphCanvasContainer');
3805
+ const statsBadge = document.getElementById('graphStatsBadge');
3806
+ if (!canvasWrap) return;
3807
+
3808
+ canvasWrap.replaceChildren(
3809
+ el('div', { className: 'text-muted', style: { padding: '24px' } }, 'Loading knowledge graph...')
3810
+ );
3811
+
3812
+ const projInput = document.getElementById('graphFilterProject');
3813
+ const scopeSel = document.getElementById('graphFilterScope');
3814
+ const limitSel = document.getElementById('graphFilterLimit');
3815
+
3816
+ let projVal = projInput ? projInput.value.trim() : '';
3817
+ if (projVal.toLowerCase() === 'all projects') projVal = '';
3818
+
3819
+ const params = new URLSearchParams();
3820
+ if (projVal) params.set('project_id', projVal);
3821
+ if (scopeSel && scopeSel.value) params.set('scope', scopeSel.value);
3822
+ if (limitSel && limitSel.value) params.set('limit', limitSel.value);
3823
+
3824
+ try {
3825
+ const resp = await apiFetch('/dashboard/api/graph?' + params.toString());
3826
+ if (!resp.ok) throw new Error('Graph request failed: ' + resp.status);
3827
+ graphData = await resp.json();
3828
+ selectedGraphNodeId = null;
3829
+
3830
+ const nodes = Array.isArray(graphData.nodes) ? graphData.nodes : [];
3831
+ const edges = Array.isArray(graphData.edges) ? graphData.edges : [];
3832
+ if (statsBadge) {
3833
+ statsBadge.textContent = nodes.length + ' nodes · ' + edges.length + ' edges';
3834
+ }
3835
+
3836
+ renderGraphLegend();
3837
+ renderGraphSvg(nodes, edges);
3838
+
3839
+ const inspector = document.getElementById('graphInspectorContainer');
3840
+ if (inspector) {
3841
+ inspector.replaceChildren(
3842
+ el('div', { className: 'text-muted' }, 'Click any node in the graph to inspect its metadata and connections.')
3843
+ );
3844
+ }
3845
+ } catch (err) {
3846
+ canvasWrap.replaceChildren(
3847
+ el('div', { className: 'toast toast-rose', style: { position: 'static' } },
3848
+ el('span', {}, 'Error loading graph: ' + err.message)
3849
+ )
3850
+ );
3851
+ }
3852
+ }
3853
+
3854
+ function renderGraphLegend() {
3855
+ const legend = document.getElementById('graphLegend');
3856
+ if (!legend) return;
3857
+ legend.replaceChildren();
3858
+ Object.entries(GRAPH_TYPE_COLORS).forEach(([type, color]) => {
3859
+ legend.appendChild(
3860
+ el('div', { className: 'graph-legend-item' },
3861
+ el('span', { className: 'graph-legend-swatch', style: { backgroundColor: color } }),
3862
+ el('span', {}, type)
3863
+ )
3864
+ );
3865
+ });
3866
+ }
3867
+
3868
+ function computeGraphPositions(nodes, edges, width, height) {
3869
+ const cx = width / 2;
3870
+ const cy = height / 2;
3871
+ const typeOrder = ['session', 'summary', 'note', 'lesson', 'action', 'concept', 'file'];
3872
+ const buckets = new Map();
3873
+ typeOrder.forEach((t) => buckets.set(t, []));
3874
+ nodes.forEach((n) => {
3875
+ const t = buckets.has(n.type) ? n.type : 'note';
3876
+ buckets.get(t).push(n);
3877
+ });
3878
+
3879
+ const pos = new Map();
3880
+ const ringRadii = {
3881
+ session: 70,
3882
+ summary: 120,
3883
+ note: 175,
3884
+ lesson: 175,
3885
+ action: 215,
3886
+ concept: 240,
3887
+ file: 255
3888
+ };
3889
+
3890
+ typeOrder.forEach((type, typeIdx) => {
3891
+ const group = buckets.get(type) || [];
3892
+ const radius = ringRadii[type] || 180;
3893
+ group.forEach((node, idx) => {
3894
+ const angle = ((idx / Math.max(1, group.length)) * Math.PI * 2) + (typeIdx * 0.45);
3895
+ pos.set(node.id, {
3896
+ x: cx + Math.cos(angle) * radius * (width / height * 0.72),
3897
+ y: cy + Math.sin(angle) * radius * 0.85
3898
+ });
3899
+ });
3900
+ });
3901
+
3902
+ // Light deterministic repulsion + edge attraction so nodes stay well-separated
3903
+ for (let iter = 0; iter < 30; iter++) {
3904
+ for (let i = 0; i < nodes.length; i++) {
3905
+ for (let j = i + 1; j < nodes.length; j++) {
3906
+ const p1 = pos.get(nodes[i].id);
3907
+ const p2 = pos.get(nodes[j].id);
3908
+ const dx = p2.x - p1.x;
3909
+ const dy = p2.y - p1.y;
3910
+ const distSq = dx * dx + dy * dy + 0.01;
3911
+ if (distSq < 2600) {
3912
+ const dist = Math.sqrt(distSq);
3913
+ const push = (52 - dist) * 0.25;
3914
+ const ux = dx / dist;
3915
+ const uy = dy / dist;
3916
+ p1.x -= ux * push;
3917
+ p1.y -= uy * push;
3918
+ p2.x += ux * push;
3919
+ p2.y += uy * push;
3920
+ }
3921
+ }
3922
+ }
3923
+ edges.forEach((e) => {
3924
+ const p1 = pos.get(e.source);
3925
+ const p2 = pos.get(e.target);
3926
+ if (!p1 || !p2) return;
3927
+ const dx = p2.x - p1.x;
3928
+ const dy = p2.y - p1.y;
3929
+ p1.x += dx * 0.03;
3930
+ p1.y += dy * 0.03;
3931
+ p2.x -= dx * 0.03;
3932
+ p2.y -= dy * 0.03;
3933
+ });
3934
+ nodes.forEach((n) => {
3935
+ const p = pos.get(n.id);
3936
+ p.x = Math.max(48, Math.min(width - 48, p.x));
3937
+ p.y = Math.max(36, Math.min(height - 36, p.y));
3938
+ });
3939
+ }
3940
+
3941
+ return pos;
3942
+ }
3943
+
3944
+ function renderGraphSvg(nodes, edges) {
3945
+ const canvasWrap = document.getElementById('graphCanvasContainer');
3946
+ if (!canvasWrap) return;
3947
+ canvasWrap.replaceChildren();
3948
+
3949
+ if (nodes.length === 0) {
3950
+ canvasWrap.appendChild(
3951
+ el('div', { className: 'text-muted', style: { padding: '24px' } }, 'No graph nodes found for the selected filters.')
3952
+ );
3953
+ return;
3954
+ }
3955
+
3956
+ const SVG_NS = 'http://www.w3.org/2000/svg';
3957
+ const width = 960;
3958
+ const height = 560;
3959
+ const positions = computeGraphPositions(nodes, edges, width, height);
3960
+
3961
+ const svg = document.createElementNS(SVG_NS, 'svg');
3962
+ svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
3963
+ svg.setAttribute('class', 'graph-svg');
3964
+
3965
+ // Edges layer
3966
+ const edgesGroup = document.createElementNS(SVG_NS, 'g');
3967
+ edges.forEach((edge) => {
3968
+ const p1 = positions.get(edge.source);
3969
+ const p2 = positions.get(edge.target);
3970
+ if (!p1 || !p2) return;
3971
+ const line = document.createElementNS(SVG_NS, 'line');
3972
+ line.setAttribute('x1', String(Math.round(p1.x)));
3973
+ line.setAttribute('y1', String(Math.round(p1.y)));
3974
+ line.setAttribute('x2', String(Math.round(p2.x)));
3975
+ line.setAttribute('y2', String(Math.round(p2.y)));
3976
+ line.setAttribute('stroke', '#334155');
3977
+ line.setAttribute('stroke-width', '1.4');
3978
+ line.setAttribute('stroke-opacity', '0.75');
3979
+ const title = document.createElementNS(SVG_NS, 'title');
3980
+ title.textContent = edge.type + ': ' + edge.source + ' -> ' + edge.target;
3981
+ line.appendChild(title);
3982
+ edgesGroup.appendChild(line);
3983
+ });
3984
+ svg.appendChild(edgesGroup);
3985
+
3986
+ // Nodes layer
3987
+ const nodesGroup = document.createElementNS(SVG_NS, 'g');
3988
+ nodes.forEach((node) => {
3989
+ const p = positions.get(node.id);
3990
+ if (!p) return;
3991
+ const g = document.createElementNS(SVG_NS, 'g');
3992
+ g.setAttribute('class', 'graph-node' + (selectedGraphNodeId === node.id ? ' selected' : ''));
3993
+ g.setAttribute('data-node-id', node.id);
3994
+
3995
+ const circle = document.createElementNS(SVG_NS, 'circle');
3996
+ circle.setAttribute('cx', String(Math.round(p.x)));
3997
+ circle.setAttribute('cy', String(Math.round(p.y)));
3998
+ circle.setAttribute('r', node.type === 'session' || node.type === 'summary' ? '12' : '9');
3999
+ circle.setAttribute('fill', GRAPH_TYPE_COLORS[node.type] || '#94a3b8');
4000
+ circle.setAttribute('stroke', '#0f172a');
4001
+ circle.setAttribute('stroke-width', '1.5');
4002
+
4003
+ const labelText = (node.label || node.id || '').slice(0, 18);
4004
+ const text = document.createElementNS(SVG_NS, 'text');
4005
+ text.setAttribute('x', String(Math.round(p.x)));
4006
+ text.setAttribute('y', String(Math.round(p.y + 20)));
4007
+ text.setAttribute('text-anchor', 'middle');
4008
+ text.setAttribute('class', 'graph-node-label');
4009
+ text.textContent = labelText;
4010
+
4011
+ const title = document.createElementNS(SVG_NS, 'title');
4012
+ title.textContent = '[' + node.type + '] ' + (node.label || node.id);
4013
+
4014
+ g.appendChild(circle);
4015
+ g.appendChild(text);
4016
+ g.appendChild(title);
4017
+ g.addEventListener('click', () => selectGraphNode(node.id));
4018
+ nodesGroup.appendChild(g);
4019
+ });
4020
+ svg.appendChild(nodesGroup);
4021
+
4022
+ canvasWrap.appendChild(svg);
4023
+ }
4024
+
4025
+ function selectGraphNode(nodeId) {
4026
+ selectedGraphNodeId = nodeId;
4027
+ document.querySelectorAll('#graphCanvasContainer .graph-node').forEach((g) => {
4028
+ if (g.getAttribute('data-node-id') === nodeId) {
4029
+ g.classList.add('selected');
4030
+ } else {
4031
+ g.classList.remove('selected');
4032
+ }
4033
+ });
4034
+
4035
+ if (!graphData || !Array.isArray(graphData.nodes)) return;
4036
+ const node = graphData.nodes.find((n) => n.id === nodeId);
4037
+ if (node) {
4038
+ renderGraphInspector(node);
4039
+ }
4040
+ }
4041
+
4042
+ function renderGraphInspector(node) {
4043
+ const inspector = document.getElementById('graphInspectorContainer');
4044
+ if (!inspector) return;
4045
+ inspector.replaceChildren();
4046
+
4047
+ const nodesById = new Map();
4048
+ (graphData && graphData.nodes ? graphData.nodes : []).forEach((n) => nodesById.set(n.id, n));
4049
+ const edges = (graphData && graphData.edges ? graphData.edges : []);
4050
+
4051
+ inspector.appendChild(
4052
+ el('div', { className: 'control-row mb-4', style: { flexWrap: 'wrap' } },
4053
+ createBadge((node.type || 'node').toUpperCase(), 'cyan', true),
4054
+ node.scope ? createBadge(node.scope, node.scope === 'project' ? 'emerald' : 'subtle', true) : null,
4055
+ node.project_id ? createBadge(node.project_id, 'subtle', true) : null
4056
+ )
4057
+ );
4058
+
4059
+ inspector.appendChild(el('h3', { style: { fontSize: '15px', marginBottom: '6px', wordBreak: 'break-word' } }, node.label || node.id));
4060
+ inspector.appendChild(el('div', { className: 'text-muted text-mono mb-4', style: { fontSize: '11px', wordBreak: 'break-all' } }, 'ID: ' + node.id));
4061
+
4062
+ if (node.meta && typeof node.meta === 'object' && Object.keys(node.meta).length > 0) {
4063
+ const metaBox = el('div', { className: 'result-card', style: { marginBottom: '12px', padding: '10px' } });
4064
+ Object.entries(node.meta).forEach(([k, v]) => {
4065
+ if (v === null || v === undefined) return;
4066
+ metaBox.appendChild(
4067
+ el('div', { style: { fontSize: '12px', marginBottom: '4px' } },
4068
+ el('span', { className: 'text-muted text-mono' }, k + ': '),
4069
+ el('span', {}, typeof v === 'object' ? JSON.stringify(v) : String(v))
4070
+ )
4071
+ );
4072
+ });
4073
+ inspector.appendChild(metaBox);
4074
+ }
4075
+
4076
+ const connected = edges.filter((e) => e.source === node.id || e.target === node.id);
4077
+ inspector.appendChild(
4078
+ el('div', { className: 'form-label-inline', style: { marginBottom: '8px' } }, 'CONNECTIONS (' + connected.length + ')')
4079
+ );
4080
+
4081
+ if (connected.length === 0) {
4082
+ inspector.appendChild(el('div', { className: 'text-muted', style: { fontSize: '12px' } }, 'No connected edges in current view.'));
4083
+ return;
4084
+ }
4085
+
4086
+ connected.forEach((edge) => {
4087
+ const isOutgoing = edge.source === node.id;
4088
+ const otherId = isOutgoing ? edge.target : edge.source;
4089
+ const otherNode = nodesById.get(otherId);
4090
+ const otherLabel = otherNode ? ('[' + otherNode.type + '] ' + (otherNode.label || otherId)) : otherId;
4091
+
4092
+ inspector.appendChild(
4093
+ el('button', {
4094
+ type: 'button',
4095
+ className: 'graph-edge-link',
4096
+ onClick: () => selectGraphNode(otherId)
4097
+ },
4098
+ el('span', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
4099
+ (isOutgoing ? '→ ' : '← ') + otherLabel
4100
+ ),
4101
+ el('span', { className: 'text-muted text-mono', style: { fontSize: '10px', flexShrink: '0' } }, edge.type)
4102
+ )
4103
+ );
4104
+ });
4105
+ }
4106
+
4107
+ // App Initialization
4108
+ document.addEventListener('DOMContentLoaded', () => {
4109
+ initTabs();
4110
+ initSearchWorkbench();
4111
+ initNotesTab();
4112
+ initShortTermTab();
4113
+ initGraphTab();
4114
+ initConformanceTab();
4115
+ initActionButtons();
4116
+
4117
+ const modalContainerEl = document.getElementById('modalContainer');
4118
+ if (modalContainerEl) {
4119
+ modalContainerEl.addEventListener('click', (e) => {
4120
+ if (e.target === modalContainerEl) {
4121
+ closeModal();
4122
+ }
4123
+ });
4124
+ }
4125
+
4126
+ const apiKeyInput = document.getElementById('inputDashboardApiKey');
4127
+ if (apiKeyInput) {
4128
+ const handleKeyUpdate = async () => {
4129
+ const val = apiKeyInput.value.trim();
4130
+ if (val) {
4131
+ try {
4132
+ const resp = await apiFetch('/dashboard/api/session', {
4133
+ method: 'POST',
4134
+ headers: { 'Content-Type': 'application/json' },
4135
+ body: JSON.stringify({ key: val })
4136
+ });
4137
+ if (resp.ok) {
4138
+ const data = await resp.json();
4139
+ inMemoryApiKey = val;
4140
+ isSessionAuthenticated = true;
4141
+ sessionKeyName = data.name || 'Active';
4142
+ isBootstrapRequired = false;
4143
+ apiKeyInput.value = '';
4144
+ updateAuthStatusUI();
4145
+ showToast('Authenticated as ' + sessionKeyName + '. Session active!', 'emerald', 3000);
4146
+ fetchStats();
4147
+ refreshActiveTab();
4148
+ } else {
4149
+ showToast('Invalid or expired API key', 'rose', 3500);
4150
+ }
4151
+ } catch (err) {
4152
+ showToast('Authentication error: ' + err.message, 'rose', 3500);
4153
+ }
4154
+ }
4155
+ };
4156
+
4157
+ const apiKeyForm = document.getElementById('formDashboardApiKey');
4158
+ if (apiKeyForm) {
4159
+ apiKeyForm.addEventListener('submit', (e) => {
4160
+ e.preventDefault();
4161
+ handleKeyUpdate();
4162
+ });
4163
+ }
4164
+
4165
+ apiKeyInput.addEventListener('input', (e) => {
4166
+ const val = (e.target && e.target.value) ? e.target.value.trim() : '';
4167
+ if (val && val !== inMemoryApiKey) {
4168
+ inMemoryApiKey = val;
4169
+ }
4170
+ });
4171
+ apiKeyInput.addEventListener('change', handleKeyUpdate);
4172
+ apiKeyInput.addEventListener('keydown', (e) => {
4173
+ if (e.key === 'Enter') {
4174
+ handleKeyUpdate();
4175
+ }
4176
+ });
4177
+ }
4178
+
4179
+ checkAuthStatus();
4180
+ fetchStats();
4181
+
4182
+ // Auto-refresh stats every 30 seconds (chained setTimeout prevents overlapping requests)
4183
+ const scheduleStatsRefresh = () => {
4184
+ setTimeout(async () => {
4185
+ try {
4186
+ await fetchStats();
4187
+ } finally {
4188
+ scheduleStatsRefresh();
4189
+ }
4190
+ }, 30000);
4191
+ };
4192
+ scheduleStatsRefresh();
4193
+
4194
+ // Global click listener to close open dropdowns when clicking outside
4195
+ document.addEventListener('click', (e) => {
4196
+ document.querySelectorAll('.searchable-dropdown.open').forEach((w) => {
4197
+ if (!w.contains(e.target)) {
4198
+ w.classList.remove('open');
4199
+ const m = w.querySelector('.dropdown-menu');
4200
+ if (m) m.classList.remove('open');
4201
+ const inp = w.querySelector('input');
4202
+ if (inp) inp.setAttribute('aria-expanded', 'false');
4203
+ }
4204
+ });
4205
+ });
4206
+ });
4207
+ })();
4208
+ `;