agent-knowledge 1.1.5 → 1.1.7

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 (81) hide show
  1. package/CHANGELOG.md +123 -5
  2. package/README.md +86 -24
  3. package/dist/dashboard.d.ts +1 -0
  4. package/dist/dashboard.d.ts.map +1 -1
  5. package/dist/dashboard.js +145 -19
  6. package/dist/dashboard.js.map +1 -1
  7. package/dist/embeddings/anthropic.d.ts.map +1 -1
  8. package/dist/embeddings/anthropic.js +2 -1
  9. package/dist/embeddings/anthropic.js.map +1 -1
  10. package/dist/embeddings/gemini.d.ts.map +1 -1
  11. package/dist/embeddings/gemini.js +2 -1
  12. package/dist/embeddings/gemini.js.map +1 -1
  13. package/dist/embeddings/local.d.ts.map +1 -1
  14. package/dist/embeddings/local.js +3 -0
  15. package/dist/embeddings/local.js.map +1 -1
  16. package/dist/knowledge/consolidate.d.ts +46 -0
  17. package/dist/knowledge/consolidate.d.ts.map +1 -0
  18. package/dist/knowledge/consolidate.js +164 -0
  19. package/dist/knowledge/consolidate.js.map +1 -0
  20. package/dist/knowledge/distill.d.ts.map +1 -1
  21. package/dist/knowledge/distill.js +4 -2
  22. package/dist/knowledge/distill.js.map +1 -1
  23. package/dist/knowledge/graph.d.ts +64 -0
  24. package/dist/knowledge/graph.d.ts.map +1 -0
  25. package/dist/knowledge/graph.js +214 -0
  26. package/dist/knowledge/graph.js.map +1 -0
  27. package/dist/knowledge/reflect.d.ts +33 -0
  28. package/dist/knowledge/reflect.d.ts.map +1 -0
  29. package/dist/knowledge/reflect.js +115 -0
  30. package/dist/knowledge/reflect.js.map +1 -0
  31. package/dist/knowledge/scoring.d.ts +57 -0
  32. package/dist/knowledge/scoring.d.ts.map +1 -0
  33. package/dist/knowledge/scoring.js +194 -0
  34. package/dist/knowledge/scoring.js.map +1 -0
  35. package/dist/knowledge/search.d.ts.map +1 -1
  36. package/dist/knowledge/search.js +15 -2
  37. package/dist/knowledge/search.js.map +1 -1
  38. package/dist/knowledge/store.d.ts.map +1 -1
  39. package/dist/knowledge/store.js +4 -3
  40. package/dist/knowledge/store.js.map +1 -1
  41. package/dist/search/excerpt.d.ts.map +1 -1
  42. package/dist/search/excerpt.js +2 -1
  43. package/dist/search/excerpt.js.map +1 -1
  44. package/dist/search/tfidf.d.ts +1 -0
  45. package/dist/search/tfidf.d.ts.map +1 -1
  46. package/dist/search/tfidf.js +38 -3
  47. package/dist/search/tfidf.js.map +1 -1
  48. package/dist/server.d.ts.map +1 -1
  49. package/dist/server.js +125 -382
  50. package/dist/server.js.map +1 -1
  51. package/dist/sessions/parser.d.ts.map +1 -1
  52. package/dist/sessions/parser.js +44 -69
  53. package/dist/sessions/parser.js.map +1 -1
  54. package/dist/sessions/search.js +17 -3
  55. package/dist/sessions/search.js.map +1 -1
  56. package/dist/sessions/summary.d.ts.map +1 -1
  57. package/dist/sessions/summary.js +26 -16
  58. package/dist/sessions/summary.js.map +1 -1
  59. package/dist/tool-handlers.d.ts +41 -0
  60. package/dist/tool-handlers.d.ts.map +1 -0
  61. package/dist/tool-handlers.js +440 -0
  62. package/dist/tool-handlers.js.map +1 -0
  63. package/dist/types.d.ts.map +1 -1
  64. package/dist/types.js +6 -4
  65. package/dist/types.js.map +1 -1
  66. package/dist/ui/app.js +201 -691
  67. package/dist/ui/index.html +29 -0
  68. package/dist/ui/render-knowledge.js +233 -0
  69. package/dist/ui/render-panel.js +350 -0
  70. package/dist/ui/render-search.js +109 -0
  71. package/dist/ui/render-sessions.js +234 -0
  72. package/dist/ui/styles.css +261 -0
  73. package/dist/ui/ui-utils.js +196 -0
  74. package/dist/vectorstore/store.d.ts +25 -44
  75. package/dist/vectorstore/store.d.ts.map +1 -1
  76. package/dist/vectorstore/store.js +167 -167
  77. package/dist/vectorstore/store.js.map +1 -1
  78. package/docs/ARCHITECTURE.md +94 -1
  79. package/docs/DASHBOARD.md +26 -13
  80. package/docs/SETUP.md +74 -23
  81. package/package.json +2 -2
@@ -114,6 +114,18 @@
114
114
  >
115
115
  <div class="view-header">
116
116
  <h2><span class="material-symbols-outlined view-icon">folder</span>Knowledge Base</h2>
117
+ <div class="view-actions">
118
+ <button
119
+ id="btn-consolidate"
120
+ class="header-action-btn"
121
+ title="Scan for duplicate entries"
122
+ >
123
+ <span class="material-symbols-outlined">content_copy</span>Duplicates
124
+ </button>
125
+ <button id="btn-reflect" class="header-action-btn" title="Find unconnected entries">
126
+ <span class="material-symbols-outlined">psychology</span>Reflect
127
+ </button>
128
+ </div>
117
129
  </div>
118
130
  <div
119
131
  class="filter-chips"
@@ -140,6 +152,18 @@
140
152
  <span class="material-symbols-outlined chip-icon">sticky_note_2</span>Notes
141
153
  </button>
142
154
  </div>
155
+ <div class="search-bar knowledge-search-bar">
156
+ <span class="material-symbols-outlined search-input-icon">search</span>
157
+ <input
158
+ type="search"
159
+ id="knowledge-search-input"
160
+ class="search-input"
161
+ placeholder="Search knowledge entries..."
162
+ autocomplete="off"
163
+ aria-label="Search knowledge entries"
164
+ />
165
+ </div>
166
+ <div id="knowledge-search-results" class="results-list" style="display: none"></div>
143
167
  <div id="knowledge-grid" class="card-grid"></div>
144
168
  <div id="knowledge-empty" class="empty-state hidden">
145
169
  <span class="material-symbols-outlined empty-icon">folder_off</span>
@@ -324,6 +348,11 @@
324
348
  media="(prefers-color-scheme: dark)"
325
349
  />
326
350
  <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11/build/highlight.min.js"></script>
351
+ <script src="ui-utils.js"></script>
352
+ <script src="render-knowledge.js"></script>
353
+ <script src="render-search.js"></script>
354
+ <script src="render-sessions.js"></script>
355
+ <script src="render-panel.js"></script>
327
356
  <script src="app.js"></script>
328
357
  </body>
329
358
  </html>
@@ -0,0 +1,233 @@
1
+ /* agent-knowledge — knowledge tab rendering */
2
+ (function () {
3
+ 'use strict';
4
+
5
+ const K = window.Knowledge;
6
+
7
+ // ── Render knowledge grid ─────────────────────────────────────────────────
8
+
9
+ function renderKnowledge(state, el) {
10
+ const cat = state.knowledge.activeCategory;
11
+ const filtered =
12
+ cat === 'all'
13
+ ? state.knowledge.entries
14
+ : state.knowledge.entries.filter((e) => e.category === cat);
15
+
16
+ if (filtered.length === 0) {
17
+ el.knowledgeGrid.innerHTML = '';
18
+ el.knowledgeEmpty.classList.remove('hidden');
19
+ return;
20
+ }
21
+
22
+ el.knowledgeEmpty.classList.add('hidden');
23
+ el.knowledgeGrid.innerHTML = filtered
24
+ .map((entry) => {
25
+ const cat = entry.category || 'notes';
26
+ const catIcons = {
27
+ projects: 'code',
28
+ people: 'group',
29
+ decisions: 'gavel',
30
+ workflows: 'account_tree',
31
+ notes: 'sticky_note_2',
32
+ };
33
+ const icon = catIcons[cat] || 'article';
34
+ const title = entry.title || entry.path || entry.id || 'Untitled';
35
+ const tags = (entry.tags || [])
36
+ .slice(0, 3)
37
+ .map((t) => `<span class="card-tag">${K.esc(t)}</span>`)
38
+ .join('');
39
+ const time = K.relativeTime(entry.updated || entry.created);
40
+
41
+ const maturity = entry.maturity || 'candidate';
42
+ const accessCount = entry.access_count || 0;
43
+ const hasDuplicates = !!state.knowledge.duplicateClusters[entry.path || ''];
44
+
45
+ return `<div class="knowledge-card${hasDuplicates ? ' has-duplicates' : ''}" data-path="${K.esc(entry.path || entry.id || '')}" tabindex="0" role="button">
46
+ <div class="card-header-row">
47
+ <span class="card-category" data-cat="${K.esc(cat)}">
48
+ <span class="material-symbols-outlined" style="font-size:14px">${icon}</span>
49
+ ${K.esc(cat)}
50
+ </span>
51
+ <div style="display:flex;align-items:center;gap:4px">
52
+ ${hasDuplicates ? '<span class="material-symbols-outlined duplicate-warn" title="Potential duplicate detected" style="font-size:16px;color:var(--warning)">content_copy</span>' : ''}
53
+ <span class="maturity-badge" data-maturity="${K.esc(maturity)}">${K.esc(maturity)}${accessCount > 0 ? ` <span class="maturity-reads">&middot; ${accessCount} reads</span>` : ''}</span>
54
+ </div>
55
+ </div>
56
+ ${time ? `<span class="card-date">${time}</span>` : ''}
57
+ <div class="card-title">${K.esc(title)}</div>
58
+ ${tags ? `<div class="card-tags">${tags}</div>` : ''}
59
+ </div>`;
60
+ })
61
+ .join('');
62
+
63
+ el.knowledgeGrid.querySelectorAll('.knowledge-card').forEach((card) => {
64
+ card.addEventListener('click', () => K.openKnowledgePanel(card.dataset.path));
65
+ card.addEventListener('keydown', (e) => {
66
+ if (e.key === 'Enter') K.openKnowledgePanel(card.dataset.path);
67
+ });
68
+ });
69
+ }
70
+
71
+ // ── Knowledge search ──────────────────────────────────────────────────────
72
+
73
+ function createKnowledgeSearch(state, el) {
74
+ return K.debounce(async () => {
75
+ const q = (el.knowledgeSearchInput ? el.knowledgeSearchInput.value : '').trim();
76
+ if (!q) {
77
+ el.knowledgeSearchResults.style.display = 'none';
78
+ el.knowledgeGrid.style.display = '';
79
+ el.knowledgeEmpty.classList.add('hidden');
80
+ renderKnowledge(state, el);
81
+ return;
82
+ }
83
+ try {
84
+ const params = new URLSearchParams({ q, max_results: '20' });
85
+ const cat = state.knowledge.activeCategory;
86
+ if (cat !== 'all') params.set('category', cat);
87
+ const results = await K.api(`/knowledge/search?${params}`);
88
+ renderKnowledgeSearchResults(Array.isArray(results) ? results : [], q, el);
89
+ } catch (err) {
90
+ K.toast(`Knowledge search failed: ${err.message}`, 'error');
91
+ }
92
+ }, 300);
93
+ }
94
+
95
+ function renderKnowledgeSearchResults(results, query, el) {
96
+ if (results.length === 0) {
97
+ el.knowledgeSearchResults.style.display = 'none';
98
+ el.knowledgeGrid.style.display = 'none';
99
+ el.knowledgeEmpty.classList.remove('hidden');
100
+ el.knowledgeEmpty.querySelector('.empty-text').textContent = 'No results found';
101
+ el.knowledgeEmpty.querySelector('.empty-hint').textContent =
102
+ `No knowledge entries match "${query}"`;
103
+ return;
104
+ }
105
+
106
+ el.knowledgeEmpty.classList.add('hidden');
107
+ el.knowledgeGrid.style.display = 'none';
108
+ el.knowledgeSearchResults.style.display = '';
109
+ el.knowledgeSearchResults.innerHTML = results
110
+ .map((r) => {
111
+ const title = r.title || r.path || '';
112
+ const excerpt = r.excerpt || '';
113
+ const score = r.score;
114
+ const maturity = r.maturity || 'candidate';
115
+ const accessCount = r.access_count || 0;
116
+ const decayF = r.decay_factor;
117
+ const matMult = r.maturity_multiplier;
118
+ const path = r.path || '';
119
+
120
+ let scoreBreakdown = '';
121
+ if (score != null) {
122
+ const parts = [];
123
+ parts.push(`relevance: ${score.toFixed(2)}`);
124
+ if (decayF != null) parts.push(`decay: ${decayF.toFixed(2)}`);
125
+ if (matMult != null) parts.push(`maturity: x${matMult.toFixed(1)}`);
126
+ const finalScore = score * (decayF || 1) * (matMult || 1);
127
+ scoreBreakdown = `<div class="score-breakdown">Score: ${finalScore.toFixed(2)} (${parts.join(' \u00d7 ')})</div>`;
128
+ }
129
+
130
+ return `<div class="result-item knowledge-result-item" data-path="${K.esc(path)}" tabindex="0" role="button">
131
+ <div class="result-meta">
132
+ <span class="maturity-badge" data-maturity="${K.esc(maturity)}">${K.esc(maturity)}${accessCount > 0 ? ` <span class="maturity-reads">&middot; ${accessCount} reads</span>` : ''}</span>
133
+ <span class="result-entry-title">${K.esc(title)}</span>
134
+ ${score != null ? `<span class="score-container">${K.formatScore(score, {})}</span>` : ''}
135
+ </div>
136
+ <div class="result-excerpt">${K.highlightExcerpt(excerpt, query)}</div>
137
+ ${scoreBreakdown}
138
+ </div>`;
139
+ })
140
+ .join('');
141
+
142
+ el.knowledgeSearchResults.querySelectorAll('.knowledge-result-item').forEach((card) => {
143
+ card.addEventListener('click', () => K.openKnowledgePanel(card.dataset.path));
144
+ card.addEventListener('keydown', (e) => {
145
+ if (e.key === 'Enter') K.openKnowledgePanel(card.dataset.path);
146
+ });
147
+ });
148
+ }
149
+
150
+ // ── Load knowledge from API ───────────────────────────────────────────────
151
+
152
+ async function loadKnowledge(state, el) {
153
+ try {
154
+ const data = await K.api('/knowledge');
155
+ const entries = Array.isArray(data) ? data : data.entries || [];
156
+ state.knowledge.entries = entries;
157
+ state.stats.knowledgeCount = entries.length;
158
+ K.updateStats(state, el);
159
+ renderKnowledge(state, el);
160
+ } catch (err) {
161
+ K.toast(`Failed to load knowledge: ${err.message}`, 'error');
162
+ }
163
+ }
164
+
165
+ // ── Open knowledge entry in panel ─────────────────────────────────────────
166
+
167
+ async function openKnowledgePanel(path) {
168
+ if (!path) return;
169
+ try {
170
+ const [entryRes, linksRes] = await Promise.allSettled([
171
+ K.api(`/knowledge/${encodeURIComponent(path)}`),
172
+ K.api(`/knowledge/${encodeURIComponent(path)}/links`),
173
+ ]);
174
+ const data = entryRes.status === 'fulfilled' ? entryRes.value : {};
175
+ const links = linksRes.status === 'fulfilled' ? linksRes.value : [];
176
+ const title = data.title || data.path || path;
177
+ const content = data.content || data.body || '';
178
+ K.openPanel('knowledge', { title, content, meta: data, links, entryPath: path });
179
+ } catch (err) {
180
+ K.toast(`Failed to load entry: ${err.message}`, 'error');
181
+ }
182
+ }
183
+
184
+ // ── Consolidate (duplicates) ──────────────────────────────────────────────
185
+
186
+ async function loadConsolidate(state, el) {
187
+ try {
188
+ K.toast('Scanning for duplicates...', 'info', 2000);
189
+ const report = await K.api('/knowledge/consolidate');
190
+ state.knowledge.duplicateClusters = {};
191
+ if (report.clusters && report.clusters.length > 0) {
192
+ for (const cluster of report.clusters) {
193
+ for (const entry of cluster.entries) {
194
+ state.knowledge.duplicateClusters[entry.path] = cluster;
195
+ }
196
+ }
197
+ renderKnowledge(state, el);
198
+ K.openPanel('consolidate', report);
199
+ } else {
200
+ K.toast('No duplicate clusters found', 'success');
201
+ }
202
+ } catch (err) {
203
+ K.toast(`Consolidation failed: ${err.message}`, 'error');
204
+ }
205
+ }
206
+
207
+ // ── Reflect (unconnected entries) ─────────────────────────────────────────
208
+
209
+ async function loadReflect() {
210
+ try {
211
+ K.toast('Finding unconnected entries...', 'info', 2000);
212
+ const result = await K.api('/knowledge/reflect');
213
+ if (result.unconnectedEntries && result.unconnectedEntries.length > 0) {
214
+ K.openPanel('reflect', result);
215
+ } else {
216
+ K.toast('All entries are connected in the graph', 'success');
217
+ }
218
+ } catch (err) {
219
+ K.toast(`Reflect failed: ${err.message}`, 'error');
220
+ }
221
+ }
222
+
223
+ // ── Export ──────────────────────────────────────────────────────────────────
224
+
225
+ Object.assign(K, {
226
+ renderKnowledge,
227
+ createKnowledgeSearch,
228
+ loadKnowledge,
229
+ openKnowledgePanel,
230
+ loadConsolidate,
231
+ loadReflect,
232
+ });
233
+ })();
@@ -0,0 +1,350 @@
1
+ /* agent-knowledge — side panel rendering */
2
+ (function () {
3
+ 'use strict';
4
+
5
+ const K = window.Knowledge;
6
+
7
+ // ── Open / close panel ────────────────────────────────────────────────────
8
+
9
+ function openPanel(type, data) {
10
+ const state = K._state;
11
+ const el = K._el;
12
+ state.panel = { open: true, type, data };
13
+ el.sidePanel.hidden = false;
14
+ requestAnimationFrame(() => el.sidePanel.classList.add('open'));
15
+ el.contentWrapper.classList.add('panel-visible');
16
+
17
+ if (type === 'knowledge') {
18
+ renderKnowledgePanel(data, el);
19
+ } else if (type === 'session') {
20
+ renderSessionPanel(data, el);
21
+ } else if (type === 'consolidate') {
22
+ renderConsolidatePanel(data, el);
23
+ } else if (type === 'reflect') {
24
+ renderReflectPanel(data, el);
25
+ }
26
+ }
27
+
28
+ function closePanel() {
29
+ const state = K._state;
30
+ const el = K._el;
31
+ state.panel = { open: false, type: null, data: null };
32
+ el.sidePanel.classList.remove('open');
33
+ el.contentWrapper.classList.remove('panel-visible');
34
+ el.sidePanel.addEventListener(
35
+ 'transitionend',
36
+ function handler() {
37
+ if (!state.panel.open) el.sidePanel.hidden = true;
38
+ el.sidePanel.removeEventListener('transitionend', handler);
39
+ },
40
+ { once: true },
41
+ );
42
+ // Fallback: hide after 400ms if transitionend doesn't fire
43
+ setTimeout(() => {
44
+ if (!state.panel.open) el.sidePanel.hidden = true;
45
+ }, 400);
46
+ }
47
+
48
+ // ── Knowledge panel ───────────────────────────────────────────────────────
49
+
50
+ function renderKnowledgePanel(data, el) {
51
+ el.panelTitle.innerHTML = `<span class="material-symbols-outlined panel-icon">article</span>${K.esc(data.title)}`;
52
+ const meta = data.meta || {};
53
+ const entry = meta.entry || meta;
54
+ const category = entry.category || meta.category || '';
55
+ const tags = entry.tags || meta.tags || [];
56
+ const updated = entry.updated || meta.updated || '';
57
+ const maturity = meta.maturity || 'candidate';
58
+ const accessCount = meta.access_count || 0;
59
+
60
+ let metaHtml = '<div class="panel-meta">';
61
+ if (category)
62
+ metaHtml += `<span class="card-category" data-cat="${K.esc(category)}">${K.esc(category)}</span>`;
63
+ metaHtml += `<span class="maturity-badge" data-maturity="${K.esc(maturity)}">${K.esc(maturity)}${accessCount > 0 ? ` <span class="maturity-reads">&middot; ${accessCount} reads</span>` : ''}</span>`;
64
+ if (tags.length)
65
+ metaHtml += tags.map((t) => `<span class="card-tag">${K.esc(t)}</span>`).join('');
66
+ if (updated) metaHtml += `<span class="panel-meta-date">${K.esc(updated)}</span>`;
67
+ metaHtml += '</div>';
68
+
69
+ const body = K.stripFrontmatter(data.content);
70
+ let html = metaHtml + `<div class="prose">${K.renderMd(body)}</div>`;
71
+
72
+ // Related entries section
73
+ const links = data.links || [];
74
+ if (links.length > 0) {
75
+ const entryPath = data.entryPath || '';
76
+ html += '<div class="panel-section related-section">';
77
+ html +=
78
+ '<h4 class="panel-section-title"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:middle;margin-right:4px">hub</span>Related</h4>';
79
+ html += '<div class="related-entries">';
80
+ links.forEach((link) => {
81
+ const linkedPath = link.source === entryPath ? link.target : link.source;
82
+ const relType = link.rel_type || 'related_to';
83
+ const strength = link.strength != null ? link.strength : 0.5;
84
+ const linkedTitle = linkedPath.split('/').pop().replace(/\.md$/, '').replace(/[-_]/g, ' ');
85
+ html += `<div class="related-entry" data-path="${K.esc(linkedPath)}" tabindex="0" role="button">
86
+ <span class="rel-type-pill" data-rel="${K.esc(relType)}">${K.esc(relType.replace(/_/g, ' '))}</span>
87
+ <span class="related-entry-title">${K.esc(linkedTitle)}</span>
88
+ <span class="related-entry-strength" title="Strength: ${strength.toFixed(2)}">${(strength * 100).toFixed(0)}%</span>
89
+ </div>`;
90
+ });
91
+ html += '</div></div>';
92
+ }
93
+
94
+ el.panelBody.innerHTML = html;
95
+
96
+ // Bind click handlers on related entries
97
+ el.panelBody.querySelectorAll('.related-entry').forEach((entryEl) => {
98
+ entryEl.addEventListener('click', () => K.openKnowledgePanel(entryEl.dataset.path));
99
+ entryEl.addEventListener('keydown', (e) => {
100
+ if (e.key === 'Enter') K.openKnowledgePanel(entryEl.dataset.path);
101
+ });
102
+ });
103
+ }
104
+
105
+ // ── Session panel ─────────────────────────────────────────────────────────
106
+
107
+ function renderSessionPanel(data, el) {
108
+ const s = data.session || {};
109
+ const summary = data.summary;
110
+ const id = data.sessionId || s.id || '';
111
+ const meta = s.meta || s;
112
+
113
+ el.panelTitle.innerHTML = `<span class="material-symbols-outlined panel-icon">terminal</span>Session ${K.esc(id.slice(0, 8))}`;
114
+
115
+ let html = '<div class="panel-meta">';
116
+ if (meta.cwd)
117
+ html += `<span class="panel-meta-item"><span class="material-symbols-outlined" style="font-size:14px">folder</span>${K.esc(meta.cwd)}</span>`;
118
+ if (meta.branch)
119
+ html += `<span class="panel-meta-item"><span class="material-symbols-outlined" style="font-size:14px">alt_route</span>${K.esc(meta.branch)}</span>`;
120
+ if (meta.startTime && meta.startTime !== 'unknown')
121
+ html += `<span class="panel-meta-item"><span class="material-symbols-outlined" style="font-size:14px">schedule</span>${new Date(meta.startTime).toLocaleString()}</span>`;
122
+ if (meta.messageCount)
123
+ html += `<span class="panel-meta-item"><span class="material-symbols-outlined" style="font-size:14px">chat</span>${meta.messageCount} messages</span>`;
124
+ html += '</div>';
125
+
126
+ if (summary && summary.topics && summary.topics.length) {
127
+ html +=
128
+ '<div class="panel-section"><h4 class="panel-section-title">Topics</h4><ul class="panel-topics">';
129
+ summary.topics.slice(0, 8).forEach((t) => {
130
+ html += `<li>${K.esc(t.content)}</li>`;
131
+ });
132
+ html += '</ul></div>';
133
+ }
134
+
135
+ const messages = s.messages || s.conversation || [];
136
+ // Filter out noisy messages (tool JSON, base64, system reminders)
137
+ const cleanMessages = messages.filter((m) => {
138
+ const t = (m.content || '').trimStart();
139
+ if (t.startsWith('[{') || t.startsWith('{"')) return false;
140
+ if (t.includes('tool_use_id') || t.includes('tool_result')) return false;
141
+ if (t.includes('base64') || t.includes('media_type')) return false;
142
+ if (t.includes('<system-reminder>')) return false;
143
+ if (t.length < 3) return false;
144
+ return true;
145
+ });
146
+
147
+ if (cleanMessages.length) {
148
+ html += '<div class="chat-messages">';
149
+ cleanMessages.forEach((m) => {
150
+ const role = m.role || 'unknown';
151
+ const text = m.content || m.text || '';
152
+ const isUser = role === 'user';
153
+ const cls = isUser ? 'chat-msg user' : 'chat-msg assistant';
154
+ const roleIcon = isUser ? 'person' : 'smart_toy';
155
+ const truncated = text.length > 1500 ? text.slice(0, 1500) + '...' : text;
156
+ const time = m.timestamp ? K.relativeTime(m.timestamp) : '';
157
+
158
+ html += `<div class="${cls}">
159
+ <div class="chat-msg-role"><span class="material-symbols-outlined" style="font-size:14px">${roleIcon}</span> ${K.esc(role)} ${time ? `<span class="chat-msg-time">${time}</span>` : ''}</div>
160
+ <div>${isUser ? K.esc(truncated) : K.renderMd(truncated)}</div>
161
+ </div>`;
162
+ });
163
+ html += '</div>';
164
+ } else {
165
+ html +=
166
+ '<div class="empty-state"><span class="material-symbols-outlined empty-icon">chat_bubble</span><div class="empty-text">No messages available</div></div>';
167
+ }
168
+
169
+ el.panelBody.innerHTML = html;
170
+
171
+ // Scroll to and highlight matching message from search
172
+ if (data.searchExcerpt) {
173
+ setTimeout(() => {
174
+ // Extract meaningful words from excerpt (strip JSON, XML, tool output noise)
175
+ const raw = data.searchExcerpt.replace(/\s+/g, ' ').trim().toLowerCase();
176
+ const cleaned = raw
177
+ .replace(/\{[^}]*\}/g, ' ') // strip JSON objects
178
+ .replace(/<[^>]*>/g, ' ') // strip XML/HTML tags
179
+ .replace(/[\\/"{}[\]]/g, ' ') // strip special chars
180
+ .replace(/tool_use_id|tool_result|content|type|text/g, ' ') // strip common JSON keys
181
+ .replace(/toolu_[a-z0-9]+/g, ' ') // strip tool IDs
182
+ .replace(/\b[a-f0-9]{8,}\b/g, ' '); // strip hex strings
183
+ const words = cleaned.split(/\s+/).filter((w) => w.length > 3 && !/^[0-9]+$/.test(w));
184
+
185
+ if (words.length === 0) return;
186
+
187
+ const msgEls = el.panelBody.querySelectorAll('.chat-msg');
188
+ let bestMatch = null;
189
+ let bestScore = -1;
190
+
191
+ msgEls.forEach((msgEl) => {
192
+ const text = msgEl.textContent.replace(/\s+/g, ' ').trim().toLowerCase();
193
+ // Count how many meaningful words appear in this message
194
+ const matched = words.filter((w) => text.includes(w)).length;
195
+ const ratio = matched / words.length;
196
+ if (ratio > bestScore && matched >= 2) {
197
+ bestScore = ratio;
198
+ bestMatch = msgEl;
199
+ }
200
+ });
201
+
202
+ if (bestMatch) {
203
+ bestMatch.classList.add('chat-msg-highlight');
204
+ bestMatch.scrollIntoView({ behavior: 'smooth', block: 'center' });
205
+ setTimeout(() => bestMatch.classList.remove('chat-msg-highlight'), 4000);
206
+ }
207
+ }, 300);
208
+ }
209
+ }
210
+
211
+ // ── Consolidate panel ─────────────────────────────────────────────────────
212
+
213
+ function renderConsolidatePanel(data, el) {
214
+ el.panelTitle.innerHTML =
215
+ '<span class="material-symbols-outlined panel-icon">content_copy</span>Duplicate Analysis';
216
+
217
+ let html = '<div class="panel-meta">';
218
+ html += `<span class="panel-meta-item">${data.totalEntries} entries scanned</span>`;
219
+ html += `<span class="panel-meta-item">${data.clustersFound} cluster(s) found</span>`;
220
+ html += `<span class="panel-meta-item">threshold: ${data.threshold}</span>`;
221
+ html += '</div>';
222
+
223
+ if (data.clusters.length === 0) {
224
+ html +=
225
+ '<div class="empty-state"><span class="material-symbols-outlined empty-icon">check_circle</span><div class="empty-text">No duplicates found</div></div>';
226
+ } else {
227
+ for (let i = 0; i < data.clusters.length; i++) {
228
+ const cluster = data.clusters[i];
229
+ html += `<div class="panel-section">`;
230
+ html += `<h4 class="panel-section-title">Cluster ${i + 1} (${cluster.entries.length} entries)</h4>`;
231
+ html += '<div class="related-entries">';
232
+ for (const entry of cluster.entries) {
233
+ const isRep = entry.path === cluster.representative;
234
+ html += `<div class="related-entry" data-path="${K.esc(entry.path)}" tabindex="0" role="button">
235
+ <span class="related-entry-title">${K.esc(entry.title)}${isRep ? ' <span class="maturity-badge" data-maturity="proven" style="font-size:10px">representative</span>' : ''}</span>
236
+ </div>`;
237
+ }
238
+ html += '</div>';
239
+
240
+ if (cluster.similarities.length > 0) {
241
+ html += '<div class="score-breakdown" style="margin-top:8px">';
242
+ for (const sim of cluster.similarities) {
243
+ const aShort = sim.a.split('/').pop().replace(/\.md$/, '');
244
+ const bShort = sim.b.split('/').pop().replace(/\.md$/, '');
245
+ html += `<div style="font-size:12px;margin:2px 0">${K.esc(aShort)} &harr; ${K.esc(bShort)}: <strong>${(sim.score * 100).toFixed(0)}%</strong></div>`;
246
+ }
247
+ html += '</div>';
248
+ }
249
+ html += '</div>';
250
+ }
251
+ }
252
+
253
+ el.panelBody.innerHTML = html;
254
+
255
+ el.panelBody.querySelectorAll('.related-entry').forEach((entryEl) => {
256
+ entryEl.addEventListener('click', () => K.openKnowledgePanel(entryEl.dataset.path));
257
+ });
258
+ }
259
+
260
+ // ── Reflect panel ─────────────────────────────────────────────────────────
261
+
262
+ function renderReflectPanel(data, el) {
263
+ el.panelTitle.innerHTML =
264
+ '<span class="material-symbols-outlined panel-icon">psychology</span>Reflection Analysis';
265
+
266
+ let html = '<div class="panel-meta">';
267
+ html += `<span class="panel-meta-item">${data.totalEntries} total entries</span>`;
268
+ html += `<span class="panel-meta-item">${data.unconnectedEntries.length} unconnected</span>`;
269
+ html += `<span class="panel-meta-item">${data.connectedCount} connected</span>`;
270
+ html += '</div>';
271
+
272
+ if (data.unconnectedEntries.length === 0) {
273
+ html +=
274
+ '<div class="empty-state"><span class="material-symbols-outlined empty-icon">hub</span><div class="empty-text">All entries connected</div></div>';
275
+ } else {
276
+ html += '<div class="panel-section">';
277
+ html +=
278
+ '<h4 class="panel-section-title"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:middle;margin-right:4px">link_off</span>Unconnected Entries</h4>';
279
+ html += '<div class="related-entries">';
280
+ for (const entry of data.unconnectedEntries) {
281
+ html += `<div class="related-entry" data-path="${K.esc(entry.path)}" tabindex="0" role="button">
282
+ <span class="card-category" data-cat="${K.esc(entry.category)}" style="font-size:10px">${K.esc(entry.category)}</span>
283
+ <span class="related-entry-title">${K.esc(entry.title)}</span>
284
+ </div>`;
285
+ if (entry.summary) {
286
+ html += `<div style="font-size:12px;color:var(--text-secondary);padding:2px 8px 8px;line-height:1.4">${K.esc(entry.summary.slice(0, 150))}${entry.summary.length > 150 ? '...' : ''}</div>`;
287
+ }
288
+ }
289
+ html += '</div></div>';
290
+
291
+ html += '<div class="panel-section">';
292
+ html +=
293
+ '<h4 class="panel-section-title"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:middle;margin-right:4px">smart_toy</span>Suggested Prompt</h4>';
294
+ html += `<div class="prose" style="font-size:12px;max-height:300px;overflow-y:auto"><pre style="white-space:pre-wrap;font-size:11px">${K.esc(data.instructions)}</pre></div>`;
295
+ html += '</div>';
296
+ }
297
+
298
+ el.panelBody.innerHTML = html;
299
+
300
+ el.panelBody.querySelectorAll('.related-entry').forEach((entryEl) => {
301
+ entryEl.addEventListener('click', () => K.openKnowledgePanel(entryEl.dataset.path));
302
+ });
303
+ }
304
+
305
+ // ── Panel resize ──────────────────────────────────────────────────────────
306
+
307
+ function initPanelResize() {
308
+ const panel = document.getElementById('side-panel');
309
+ if (!panel) return;
310
+ const handle = document.createElement('div');
311
+ handle.className = 'panel-resize-handle';
312
+ panel.appendChild(handle);
313
+
314
+ let isResizing = false;
315
+ let startX = 0;
316
+ let startWidth = 0;
317
+
318
+ handle.addEventListener('mousedown', (e) => {
319
+ isResizing = true;
320
+ startX = e.clientX;
321
+ startWidth = panel.offsetWidth;
322
+ document.body.style.cursor = 'col-resize';
323
+ document.body.style.userSelect = 'none';
324
+ e.preventDefault();
325
+ });
326
+
327
+ document.addEventListener('mousemove', (e) => {
328
+ if (!isResizing) return;
329
+ const dx = startX - e.clientX;
330
+ const newWidth = Math.max(320, Math.min(startWidth + dx, window.innerWidth * 0.8));
331
+ panel.style.width = newWidth + 'px';
332
+ panel.style.minWidth = newWidth + 'px';
333
+ });
334
+
335
+ document.addEventListener('mouseup', () => {
336
+ if (!isResizing) return;
337
+ isResizing = false;
338
+ document.body.style.cursor = '';
339
+ document.body.style.userSelect = '';
340
+ });
341
+ }
342
+
343
+ // ── Export ──────────────────────────────────────────────────────────────────
344
+
345
+ Object.assign(K, {
346
+ openPanel,
347
+ closePanel,
348
+ initPanelResize,
349
+ });
350
+ })();