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