@codepulse-oss/web 0.0.0-stage → 2.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 (67) hide show
  1. package/dist/__tests__/github-app.test.d.ts +2 -0
  2. package/dist/__tests__/github-app.test.d.ts.map +1 -0
  3. package/dist/__tests__/github-app.test.js +91 -0
  4. package/dist/__tests__/github-app.test.js.map +1 -0
  5. package/dist/__tests__/i18n.test.d.ts +2 -0
  6. package/dist/__tests__/i18n.test.d.ts.map +1 -0
  7. package/dist/__tests__/i18n.test.js +76 -0
  8. package/dist/__tests__/i18n.test.js.map +1 -0
  9. package/dist/__tests__/onboarding-apis.test.d.ts +2 -0
  10. package/dist/__tests__/onboarding-apis.test.d.ts.map +1 -0
  11. package/dist/__tests__/onboarding-apis.test.js +152 -0
  12. package/dist/__tests__/onboarding-apis.test.js.map +1 -0
  13. package/dist/__tests__/phase5-web.test.d.ts +2 -0
  14. package/dist/__tests__/phase5-web.test.d.ts.map +1 -0
  15. package/dist/__tests__/phase5-web.test.js +72 -0
  16. package/dist/__tests__/phase5-web.test.js.map +1 -0
  17. package/dist/__tests__/poller-vault.test.d.ts +2 -0
  18. package/dist/__tests__/poller-vault.test.d.ts.map +1 -0
  19. package/dist/__tests__/poller-vault.test.js +150 -0
  20. package/dist/__tests__/poller-vault.test.js.map +1 -0
  21. package/dist/__tests__/v1-routes.test.d.ts +2 -0
  22. package/dist/__tests__/v1-routes.test.d.ts.map +1 -0
  23. package/dist/__tests__/v1-routes.test.js +133 -0
  24. package/dist/__tests__/v1-routes.test.js.map +1 -0
  25. package/dist/__tests__/v1.1-settings-telemetry.test.d.ts +2 -0
  26. package/dist/__tests__/v1.1-settings-telemetry.test.d.ts.map +1 -0
  27. package/dist/__tests__/v1.1-settings-telemetry.test.js +95 -0
  28. package/dist/__tests__/v1.1-settings-telemetry.test.js.map +1 -0
  29. package/dist/__tests__/v2-routes.test.d.ts +2 -0
  30. package/dist/__tests__/v2-routes.test.d.ts.map +1 -0
  31. package/dist/__tests__/v2-routes.test.js +61 -0
  32. package/dist/__tests__/v2-routes.test.js.map +1 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +2 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/server.d.ts +84 -0
  38. package/dist/server.d.ts.map +1 -0
  39. package/dist/server.js +1804 -0
  40. package/dist/server.js.map +1 -0
  41. package/package.json +44 -4
  42. package/public/app.js +2087 -0
  43. package/public/fonts/cairo-arabic-400-normal.woff2 +0 -0
  44. package/public/fonts/cairo-arabic-500-normal.woff2 +0 -0
  45. package/public/fonts/cairo-arabic-600-normal.woff2 +0 -0
  46. package/public/fonts/cairo-arabic-700-normal.woff2 +0 -0
  47. package/public/fonts/cairo-latin-400-normal.woff2 +0 -0
  48. package/public/fonts/cairo-latin-500-normal.woff2 +0 -0
  49. package/public/fonts/cairo-latin-600-normal.woff2 +0 -0
  50. package/public/fonts/cairo-latin-700-normal.woff2 +0 -0
  51. package/public/fonts/jetbrains-mono-latin-400-normal.woff2 +0 -0
  52. package/public/fonts/jetbrains-mono-latin-500-normal.woff2 +0 -0
  53. package/public/fonts/jetbrains-mono-latin-600-normal.woff2 +0 -0
  54. package/public/fonts/jetbrains-mono-latin-700-normal.woff2 +0 -0
  55. package/public/fonts/plus-jakarta-sans-latin-400-normal.woff2 +0 -0
  56. package/public/fonts/plus-jakarta-sans-latin-500-normal.woff2 +0 -0
  57. package/public/fonts/plus-jakarta-sans-latin-600-normal.woff2 +0 -0
  58. package/public/fonts/plus-jakarta-sans-latin-700-normal.woff2 +0 -0
  59. package/public/fonts/plus-jakarta-sans-latin-ext-400-normal.woff2 +0 -0
  60. package/public/fonts/plus-jakarta-sans-latin-ext-500-normal.woff2 +0 -0
  61. package/public/fonts/plus-jakarta-sans-latin-ext-600-normal.woff2 +0 -0
  62. package/public/fonts/plus-jakarta-sans-latin-ext-700-normal.woff2 +0 -0
  63. package/public/i18n.js +882 -0
  64. package/public/index.html +775 -0
  65. package/public/styles.css +848 -0
  66. package/public/vendor/mermaid.min.js +4329 -0
  67. package/README.md +0 -3
package/public/app.js ADDED
@@ -0,0 +1,2087 @@
1
+ const { DEFAULT_LOCALE, LOCALE_META, I18N } = globalThis.CODEPULSE_I18N;
2
+
3
+ const state = {
4
+ lang: localStorage.getItem('codepulse_lang') || DEFAULT_LOCALE || 'en',
5
+ theme: localStorage.getItem('codepulse_theme') || 'obsidian',
6
+ authToken: localStorage.getItem('codepulse_auth_token') || '',
7
+ repos: [],
8
+ selectedRepoId: null,
9
+ jobs: [],
10
+ fullJobCache: {},
11
+ selectedJobId: null,
12
+ findingsViewCleared: false,
13
+ modelCatalog: {},
14
+ githubRepos: [],
15
+ onboardingChecked: false,
16
+ devicePollTimer: null,
17
+ devicePollActive: false,
18
+ deviceSession: null,
19
+ lastUpdateState: null,
20
+ graphData: { nodes: [], edges: [], slices: [] },
21
+ graphZoom: 1,
22
+ graphPanX: 0,
23
+ graphPanY: 0,
24
+ docsCache: null,
25
+ legalCache: null,
26
+ activeDocSection: 'architectureMd',
27
+ wsRefreshTimer: null
28
+ };
29
+
30
+ function t(key, vars = {}) {
31
+ const dict = I18N[state.lang] || I18N.en;
32
+ let str = dict[key] ?? I18N.en[key] ?? key;
33
+ for (const [k, v] of Object.entries(vars)) {
34
+ str = str.replace(new RegExp(`\\{${k}\\}`, 'g'), String(v));
35
+ }
36
+ return str;
37
+ }
38
+
39
+ // --- Global Toast Stack & Button Spinners ---
40
+ let toastSeq = 0;
41
+ function showToast(type, message, timeoutMs = 4200) {
42
+ const stack = document.getElementById('toastStack');
43
+ if (!stack) return null;
44
+ const id = `toast-${++toastSeq}`;
45
+ const el = document.createElement('div');
46
+ el.id = id;
47
+ el.className = `toast toast-${type}`;
48
+ const spinner = type === 'loading' ? '<span class="spin"></span>' : '';
49
+ el.innerHTML = `<div class="row-gap">${spinner}<span>${escapeHtml(message)}</span></div><button type="button" class="btn btn-xs btn-ghost" onclick="this.parentElement.remove()">×</button>`;
50
+ stack.appendChild(el);
51
+ if (timeoutMs > 0 && type !== 'loading') {
52
+ setTimeout(() => el.remove(), timeoutMs);
53
+ }
54
+ return id;
55
+ }
56
+
57
+ function updateToast(id, type, message, timeoutMs = 4000) {
58
+ if (!id) return showToast(type, message, timeoutMs);
59
+ const el = document.getElementById(id);
60
+ if (!el) return showToast(type, message, timeoutMs);
61
+ el.className = `toast toast-${type}`;
62
+ el.innerHTML = `<span>${escapeHtml(message)}</span><button type="button" class="btn btn-xs btn-ghost" onclick="this.parentElement.remove()">×</button>`;
63
+ if (timeoutMs > 0) setTimeout(() => el.remove(), timeoutMs);
64
+ }
65
+
66
+ async function withButtonLoading(btnEl, fn) {
67
+ if (!btnEl || typeof btnEl.disabled !== 'boolean') return fn();
68
+ const prevHtml = btnEl.innerHTML;
69
+ btnEl.disabled = true;
70
+ btnEl.innerHTML = `<span class="spin"></span><span>${escapeHtml(btnEl.textContent || '...')}</span>`;
71
+ try {
72
+ return await fn();
73
+ } finally {
74
+ btnEl.disabled = false;
75
+ btnEl.innerHTML = prevHtml;
76
+ }
77
+ }
78
+
79
+ async function api(url, opts = {}) {
80
+ const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
81
+ if (state.authToken) {
82
+ headers.Authorization = `Bearer ${state.authToken}`;
83
+ }
84
+ const res = await fetch(url, { ...opts, headers });
85
+ if (res.status === 401 && url !== '/api/webhooks/github') {
86
+ const dlg = document.getElementById('authModal');
87
+ if (dlg && !dlg.open) dlg.showModal();
88
+ }
89
+ return res.json();
90
+ }
91
+
92
+ const THEMES_CATALOG = [
93
+ { id: 'obsidian', label: 'Obsidian', colors: ['#0b0d11', '#11141a', '#5e6ad2'] },
94
+ { id: 'slate', label: 'Slate', colors: ['#10151e', '#161d29', '#3b82f6'] },
95
+ { id: 'nord', label: 'Nord Arctic', colors: ['#2e3440', '#3b4252', '#88c0d0'] },
96
+ { id: 'tokyo', label: 'Tokyo Night', colors: ['#1a1b26', '#1f2335', '#7aa2f7'] },
97
+ { id: 'emerald', label: 'Emerald', colors: ['#07130f', '#0b1c16', '#10b981'] },
98
+ { id: 'rose', label: 'Rosé Pine', colors: ['#191724', '#1f1d2e', '#ebbcba'] },
99
+ { id: 'dracula', label: 'Dracula', colors: ['#1e1f29', '#282a36', '#bd93f9'] },
100
+ { id: 'amber', label: 'Solar Amber', colors: ['#16110b', '#1f1810', '#f59e0b'] },
101
+ { id: 'light', label: 'Clean Light', colors: ['#f8f9fb', '#ffffff', '#4f46e5'] },
102
+ { id: 'paper', label: 'Warm Paper', colors: ['#f7f4ec', '#fffdf8', '#b45309'] }
103
+ ];
104
+
105
+ function renderThemeSwatchGrid() {
106
+ const wrap = document.getElementById('themeSwatchGrid');
107
+ if (!wrap) return;
108
+ wrap.replaceChildren();
109
+ for (const th of THEMES_CATALOG) {
110
+ const btn = document.createElement('button');
111
+ btn.type = 'button';
112
+ btn.className = `theme-swatch-card ${state.theme === th.id ? 'active' : ''}`;
113
+ btn.addEventListener('click', () => window.setTheme(th.id));
114
+ const dots = document.createElement('div');
115
+ dots.className = 'theme-swatch-dots';
116
+ for (const hex of th.colors) {
117
+ const dot = document.createElement('span');
118
+ dot.className = 'theme-dot';
119
+ dot.style.background = hex;
120
+ dots.appendChild(dot);
121
+ }
122
+ const lbl = document.createElement('span');
123
+ lbl.textContent = th.label;
124
+ btn.appendChild(dots);
125
+ btn.appendChild(lbl);
126
+ wrap.appendChild(btn);
127
+ }
128
+ }
129
+
130
+ function applyTheme(theme) {
131
+ const validIds = THEMES_CATALOG.map((t) => t.id);
132
+ const valid = validIds.includes(theme) ? theme : 'obsidian';
133
+ state.theme = valid;
134
+ document.documentElement.setAttribute('data-theme', valid);
135
+ localStorage.setItem('codepulse_theme', valid);
136
+ const sel = document.getElementById('settingsThemeSelect');
137
+ if (sel) sel.value = valid;
138
+ renderThemeSwatchGrid();
139
+ }
140
+
141
+ window.setTheme = async (nextTheme, persist = true) => {
142
+ applyTheme(nextTheme);
143
+ if (persist) {
144
+ await api('/api/settings', {
145
+ method: 'PUT',
146
+ body: JSON.stringify({ theme: state.theme })
147
+ }).catch(() => undefined);
148
+ showToast('ok', `Theme switched to ${state.theme}.`, 2500);
149
+ }
150
+ };
151
+
152
+ function applyLang() {
153
+ if (!I18N[state.lang]) state.lang = 'en';
154
+ const meta = LOCALE_META[state.lang] || LOCALE_META.en;
155
+ document.documentElement.lang = state.lang;
156
+ document.documentElement.dir = meta.dir;
157
+
158
+ const headerSel = document.getElementById('headerLangSelect');
159
+ const settingsSel = document.getElementById('settingsLangSelect');
160
+ if (headerSel) headerSel.value = state.lang;
161
+ if (settingsSel) settingsSel.value = state.lang;
162
+
163
+ document.querySelectorAll('[data-i18n]').forEach((el) => {
164
+ const key = el.getAttribute('data-i18n');
165
+ const val = t(key);
166
+ if (val) el.textContent = val;
167
+ });
168
+
169
+ document.querySelectorAll('[data-i18n-placeholder]').forEach((el) => {
170
+ const key = el.getAttribute('data-i18n-placeholder');
171
+ const val = t(key);
172
+ if (val) el.setAttribute('placeholder', val);
173
+ });
174
+
175
+ if (state.lastUpdateState) {
176
+ renderUpdateState(state.lastUpdateState);
177
+ }
178
+ }
179
+
180
+ window.setLanguage = async (nextLang, persist = true) => {
181
+ state.lang = I18N[nextLang] ? nextLang : 'en';
182
+ localStorage.setItem('codepulse_lang', state.lang);
183
+ applyLang();
184
+ if (persist) {
185
+ await api('/api/settings', {
186
+ method: 'PUT',
187
+ body: JSON.stringify({ language: state.lang })
188
+ }).catch(() => undefined);
189
+ }
190
+ };
191
+
192
+ window.switchTab = (tabName) => {
193
+ document.querySelectorAll('#mainTabs .tab').forEach((tEl) => {
194
+ tEl.classList.toggle('active', tEl.dataset.tab === tabName);
195
+ });
196
+ document.querySelectorAll('.tab-content').forEach((c) => {
197
+ c.classList.toggle('active', c.id === `tab-${tabName}`);
198
+ });
199
+ if (tabName === 'graph') loadGraph();
200
+ if (tabName === 'mainAudit') { loadPulseAndSlices(); loadRepoGroups(); }
201
+ if (tabName === 'rules') loadMemoryRules();
202
+ if (tabName === 'bridge') renderMcpConfigBox();
203
+ };
204
+
205
+ document.querySelectorAll('#mainTabs .tab').forEach((btn) => {
206
+ btn.onclick = () => switchTab(btn.dataset.tab);
207
+ });
208
+
209
+ document.getElementById('addRepoBtn')?.addEventListener('click', () => document.getElementById('repoModal').showModal());
210
+ document.getElementById('onboardingBtn')?.addEventListener('click', () => openOnboardingWizard(0));
211
+
212
+ window.openExternalDoc = (ev, url) => {
213
+ if (window.codepulseDesktop?.openExternal) {
214
+ ev.preventDefault();
215
+ window.codepulseDesktop.openExternal(url);
216
+ }
217
+ };
218
+
219
+ document.getElementById('authModalForm').onsubmit = async (e) => {
220
+ e.preventDefault();
221
+ const tok = document.getElementById('authTokenInput').value.trim();
222
+ if (!tok) return;
223
+ state.authToken = tok;
224
+ localStorage.setItem('codepulse_auth_token', tok);
225
+ document.getElementById('authModal').close();
226
+ connectWs();
227
+ await refreshAll();
228
+ showToast('ok', 'Authenticated with access token.');
229
+ };
230
+
231
+ // --- Settings Center Modal ---
232
+ window.openSettingsModal = async (paneName = 'general') => {
233
+ showSettingsPane(paneName);
234
+ document.getElementById('settingsModal').showModal();
235
+ await loadSettings();
236
+ if (paneName === 'privacy') await loadTelemetryPreview();
237
+ if (paneName === 'legal') await loadLegalDoc('termsMd');
238
+ };
239
+
240
+ window.showSettingsPane = (paneName) => {
241
+ document.querySelectorAll('#settingsNav .settings-nav-btn').forEach((b) => {
242
+ b.classList.toggle('active', b.dataset.spane === paneName);
243
+ });
244
+ document.querySelectorAll('.settings-pane').forEach((p) => {
245
+ p.classList.toggle('hidden', p.id !== `spane-${paneName}`);
246
+ });
247
+ if (paneName === 'privacy') loadTelemetryPreview();
248
+ if (paneName === 'legal') loadLegalDoc('termsMd');
249
+ };
250
+
251
+ window.saveGeneralPreferences = async (btnEl) => {
252
+ await withButtonLoading(btnEl, async () => {
253
+ const concurrency = Number(document.getElementById('settingsConcurrency')?.value || 4);
254
+ const pollSeconds = Number(document.getElementById('settingsPollSeconds')?.value ?? 60);
255
+ const body = {
256
+ theme: document.getElementById('settingsThemeSelect')?.value || state.theme,
257
+ language: document.getElementById('settingsLangSelect')?.value || state.lang,
258
+ concurrency,
259
+ pollSeconds,
260
+ closeAction: document.getElementById('settingsCloseAction')?.value || 'tray',
261
+ openAtLogin: Boolean(document.getElementById('settingsOpenAtLogin')?.checked),
262
+ checkUpdatesOnStartup: Boolean(document.getElementById('settingsCheckUpdatesStartup')?.checked),
263
+ autoDownloadUpdates: Boolean(document.getElementById('settingsAutoDownload')?.checked),
264
+ includeSeoGeo: Boolean(document.getElementById('settingsIncludeSeoGeo')?.checked),
265
+ enableOsv: Boolean(document.getElementById('settingsEnableOsv')?.checked),
266
+ enableRadar: Boolean(document.getElementById('settingsEnableRadar')?.checked),
267
+ autoScanOpenPrsOnPoll: Boolean(document.getElementById('settingsAutoScanPrs')?.checked),
268
+ autofixDefault: Boolean(document.getElementById('settingsAutofixDefault')?.checked),
269
+ telemetryOptIn: Boolean(document.getElementById('settingsTelemetryOptIn')?.checked),
270
+ compliancePacks: Array.from(document.querySelectorAll('.compliance-pack-chk:checked')).map((el) => el.value)
271
+ };
272
+ const res = await api('/api/settings', { method: 'PUT', body: JSON.stringify(body) });
273
+ if (res.error) return showToast('err', res.error);
274
+ await Promise.all([refreshHealth(), loadSettings(), loadTelemetryPreview()]);
275
+ showToast('ok', 'Preferences saved cleanly.');
276
+ });
277
+ };
278
+
279
+ window.checkForUpdatesFromSettings = async (btnEl) => {
280
+ await withButtonLoading(btnEl, async () => {
281
+ const st = await api('/api/app/update-check', { method: 'POST', body: '{}' });
282
+ renderUpdateState(st);
283
+ const box = document.getElementById('settingsUpdateStatus');
284
+ if (box) {
285
+ box.textContent = st.status === 'available'
286
+ ? `Update v${st.latestVersion} available! ${st.releaseNotes || ''}`
287
+ : `Status: ${st.status} (Current v${st.currentVersion || '2.0.1'})`;
288
+ }
289
+ showToast('info', `Update status: ${st.status}`);
290
+ });
291
+ };
292
+
293
+ window.loadTelemetryPreview = async (btnEl) => {
294
+ const run = async () => {
295
+ const res = await api('/api/telemetry/preview').catch(() => ({}));
296
+ const statsEl = document.getElementById('telemetryLocalStats');
297
+ const preEl = document.getElementById('telemetryPayloadPreview');
298
+ if (statsEl && res.stats) {
299
+ statsEl.textContent = `Opt-In: ${res.stats.optIn ? 'ENABLED' : 'DISABLED (Default)'} · Scans: ${res.stats.totalScans} · Findings: ${res.stats.totalFindings}`;
300
+ }
301
+ if (preEl && res.samplePayload) {
302
+ preEl.textContent = JSON.stringify(res.samplePayload, null, 2);
303
+ }
304
+ };
305
+ if (btnEl) await withButtonLoading(btnEl, run);
306
+ else await run();
307
+ };
308
+
309
+ window.loadLegalDoc = async (docKey) => {
310
+ const viewer = document.getElementById('legalDocViewer');
311
+ if (!state.legalCache) {
312
+ state.legalCache = await api('/api/legal/docs').catch(() => ({}));
313
+ }
314
+ if (viewer) viewer.textContent = state.legalCache[docKey] || 'Document unavailable.';
315
+ };
316
+
317
+ // --- Command Palette (Ctrl+K / Cmd+K & Ctrl+,) ---
318
+ window.openCommandPalette = () => {
319
+ document.getElementById('cmdPaletteModal').showModal();
320
+ const inp = document.getElementById('cmdPaletteInput');
321
+ inp.value = '';
322
+ inp.focus();
323
+ renderCommandPaletteResults();
324
+ };
325
+
326
+ window.renderCommandPaletteResults = () => {
327
+ const q = (document.getElementById('cmdPaletteInput').value || '').toLowerCase();
328
+ const commands = [
329
+ { label: 'Run Full Spectrum Audit (All Engines)', hint: 'AST + SAST + Extended + OSV + Radar + SEO/GEO + Debate', run: () => runAction('directory', 'comprehensive') },
330
+ { label: 'Run Local Debate Review', hint: 'Scan local_uncommitted', run: () => runAction('local_uncommitted', 'debate') },
331
+ { label: 'Run SEO & GEO AI Search Audit', hint: 'Mode: seo-geo', run: () => runAction('directory', 'seo-geo') },
332
+ { label: 'Run Adversarial Security Scan', hint: 'Scan security & races', run: () => runAction('branch_diff', 'adversarial') },
333
+ { label: 'Scan Main Branch (Full Audit)', hint: 'main_full + Pulse', run: () => runAction('main_full', 'comprehensive') },
334
+ { label: 'Generate Living Architecture Docs', hint: 'ARCHITECTURE.md + Mermaid', run: () => generateDocsAction() },
335
+ { label: 'Open Preferences / Settings', hint: 'Ctrl+, · Language, Themes, AI, Desktop, Telemetry', run: () => openSettingsModal('general') },
336
+ { label: 'Re-run Guided Onboarding', hint: 'Step-by-step AI, GitHub & Repo wizard', run: () => openOnboardingWizard(0) },
337
+ { label: 'Language: English', hint: 'Switch UI to English (LTR)', run: () => setLanguage('en') },
338
+ { label: 'Language: العربية (Arabic · Cairo)', hint: 'Switch UI to Arabic (RTL)', run: () => setLanguage('ar') },
339
+ { label: 'Language: Español', hint: 'Switch UI to Spanish (LTR)', run: () => setLanguage('es') },
340
+ { label: 'Language: Français', hint: 'Switch UI to French (LTR)', run: () => setLanguage('fr') },
341
+ ...THEMES_CATALOG.map((th) => ({
342
+ label: `Theme: ${th.label}`,
343
+ hint: `Switch visual palette (${th.id})`,
344
+ run: () => setTheme(th.id)
345
+ })),
346
+ { label: 'Open Blast Radius Graph', hint: 'Tab: Graph', run: () => switchTab('graph') },
347
+ { label: 'Open Main Audit & Pulse Score', hint: 'Tab: Main Audit', run: () => switchTab('mainAudit') },
348
+ { label: 'Open Agent Bridge (/mcp)', hint: 'Tab: Bridge', run: () => switchTab('bridge') },
349
+ { label: 'Export Smart Context Pack (.md)', hint: 'AST-condensed prompt', run: () => exportContextPack('markdown') },
350
+ ...state.repos.map((r) => ({ label: `Select Repo: ${r.name}`, hint: r.localPath || `${r.githubOwner}/${r.githubRepo}`, run: () => selectRepo(r.id) })),
351
+ ...state.jobs.slice(0, 6).map((j) => ({ label: `Inspect Job: ${j.repoName || j.target}${j.prNumber ? ` · PR #${j.prNumber}` : ''} · ${j.mode}`, hint: `${j.status} · ${j.verdict || ''}`, run: () => { switchTab('findings'); selectJob(j.id); } }))
352
+ ].filter((c) => !q || c.label.toLowerCase().includes(q) || (c.hint || '').toLowerCase().includes(q));
353
+
354
+ window.__paletteActions = commands;
355
+ document.getElementById('cmdPaletteResults').innerHTML = commands.slice(0, 12).map((c, idx) => `
356
+ <div class="list-item" onclick="execPaletteAction(${idx})">
357
+ <div class="finding-top">
358
+ <strong>${escapeHtml(c.label)}</strong>
359
+ <span class="muted mono">${escapeHtml(c.hint || '')}</span>
360
+ </div>
361
+ </div>`).join('');
362
+ };
363
+
364
+ window.execPaletteAction = (idx) => {
365
+ const act = (window.__paletteActions || [])[idx];
366
+ document.getElementById('cmdPaletteModal').close();
367
+ if (act?.run) act.run();
368
+ };
369
+
370
+ document.addEventListener('keydown', (e) => {
371
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
372
+ e.preventDefault();
373
+ openCommandPalette();
374
+ }
375
+ if ((e.ctrlKey || e.metaKey) && e.key === ',') {
376
+ e.preventDefault();
377
+ openSettingsModal('general');
378
+ }
379
+ });
380
+
381
+ // --- Auto-Updater Version Pill & Banner ---
382
+ function renderUpdateState(u) {
383
+ if (!u) return;
384
+ state.lastUpdateState = u;
385
+ const pill = document.getElementById('versionPill');
386
+ const banner = document.getElementById('updateBanner');
387
+ const bannerText = document.getElementById('updateBannerText');
388
+ const bannerActions = document.getElementById('updateBannerActions');
389
+
390
+ const ver = u.currentVersion || '2.0.1';
391
+ if (u.status === 'checking') {
392
+ pill.textContent = `v${ver} ⟳`;
393
+ pill.className = 'pill pill-accent clickable';
394
+ } else if (u.status === 'available') {
395
+ pill.textContent = `Update v${u.latestVersion} Available`;
396
+ pill.className = 'pill pill-warn clickable';
397
+ banner.classList.remove('hidden');
398
+ bannerText.textContent = t('updAvailableText', { version: u.latestVersion || '' });
399
+ const dlBtn = u.manualDownloadOnly
400
+ ? `<a class="btn btn-sm btn-primary" href="${escapeHtml(u.releaseUrl || 'https://github.com/ymorningstar/CodePulse/releases/latest')}" target="_blank" rel="noreferrer">${escapeHtml(t('updBtnDownloadDmg'))}</a>`
401
+ : `<button class="btn btn-sm btn-primary" onclick="downloadAppUpdate()">${escapeHtml(t('updBtnDownload'))}</button>`;
402
+ bannerActions.innerHTML = `
403
+ ${dlBtn}
404
+ <button class="btn btn-sm btn-ghost" onclick="document.getElementById('updateBanner').classList.add('hidden')">${escapeHtml(t('updBtnSkip'))}</button>`;
405
+ } else if (u.status === 'downloading') {
406
+ const pct = u.downloadPercent ?? 0;
407
+ pill.textContent = `Downloading ${pct}%`;
408
+ pill.className = 'pill pill-accent clickable';
409
+ banner.classList.remove('hidden');
410
+ bannerText.textContent = t('updDownloadingText', { version: u.latestVersion || '', percent: pct });
411
+ bannerActions.innerHTML = '';
412
+ } else if (u.status === 'downloaded') {
413
+ pill.textContent = `Restart for v${u.latestVersion}`;
414
+ pill.className = 'pill pill-warn clickable';
415
+ banner.classList.remove('hidden');
416
+ bannerText.textContent = t('updDownloadedText', { version: u.latestVersion || '' });
417
+ bannerActions.innerHTML = `
418
+ <button class="btn btn-sm btn-primary" onclick="installAppUpdate()">${escapeHtml(t('updBtnInstall'))}</button>
419
+ <button class="btn btn-sm btn-ghost" onclick="document.getElementById('updateBanner').classList.add('hidden')">${escapeHtml(t('updBtnOnQuit'))}</button>`;
420
+ } else {
421
+ pill.textContent = `v${ver} ✓`;
422
+ pill.className = 'pill pill-ok clickable';
423
+ banner.classList.add('hidden');
424
+ }
425
+ }
426
+
427
+ document.getElementById('versionPill').onclick = async () => {
428
+ const st = await api('/api/app/update-check', { method: 'POST', body: '{}' });
429
+ renderUpdateState(st);
430
+ showToast('info', st.status === 'available' ? `Update v${st.latestVersion} available!` : `CodePulse v${st.currentVersion || '2.0.1'} is up to date.`);
431
+ };
432
+
433
+ window.downloadAppUpdate = async () => {
434
+ const st = await api('/api/app/update-download', { method: 'POST', body: '{}' });
435
+ renderUpdateState(st);
436
+ };
437
+
438
+ window.installAppUpdate = async () => {
439
+ await api('/api/app/update-install', { method: 'POST', body: '{}' });
440
+ };
441
+
442
+ if (window.codepulseDesktop?.onUpdateStatus) {
443
+ window.codepulseDesktop.onUpdateStatus((st) => renderUpdateState(st));
444
+ }
445
+
446
+ // --- Curated AI Models & Key Vault ---
447
+ async function loadModelCatalog() {
448
+ const res = await api('/api/settings/models');
449
+ state.modelCatalog = res.models || {};
450
+ populateModelDropdown('dialProvider', 'dialModel', 'dialCustomModel');
451
+ populateModelDropdown('wizProvider', 'wizModel', 'wizCustomModel');
452
+ }
453
+
454
+ window.populateModelDropdown = (providerId, selectId, customId, currentVal) => {
455
+ const providerEl = document.getElementById(providerId);
456
+ const sel = document.getElementById(selectId);
457
+ if (!providerEl || !sel) return;
458
+ const models = state.modelCatalog[providerEl.value] || ['gemini-2.5-pro'];
459
+ sel.innerHTML = models.map((m) => `<option value="${escapeHtml(m)}">${escapeHtml(m)}</option>`).join('') + '<option value="__custom__">Custom model...</option>';
460
+ const customEl = document.getElementById(customId);
461
+ if (currentVal && models.includes(currentVal)) {
462
+ sel.value = currentVal;
463
+ if (customEl) customEl.classList.add('hidden');
464
+ } else if (currentVal) {
465
+ sel.value = '__custom__';
466
+ if (customEl) {
467
+ customEl.value = currentVal;
468
+ customEl.classList.remove('hidden');
469
+ }
470
+ }
471
+ };
472
+
473
+ window.toggleCustomModel = (selectId, customId) => {
474
+ const sel = document.getElementById(selectId);
475
+ const c = document.getElementById(customId);
476
+ if (c) c.classList.toggle('hidden', sel.value !== '__custom__');
477
+ };
478
+
479
+ function getSelectedModelValue(selectId, customId) {
480
+ const sel = document.getElementById(selectId).value;
481
+ return sel === '__custom__' ? document.getElementById(customId).value.trim() : sel;
482
+ }
483
+
484
+ window.saveAndTestAi = async (btnEl) => {
485
+ await withButtonLoading(btnEl, async () => {
486
+ const provider = document.getElementById('dialProvider').value;
487
+ const model = getSelectedModelValue('dialModel', 'dialCustomModel');
488
+ const baseUrl = document.getElementById('dialBaseUrl')?.value.trim() || '';
489
+ const apiKey = document.getElementById('dialApiKey').value.trim() || undefined;
490
+ const budget = Number(document.getElementById('dialBudgetWarn')?.value || 2);
491
+
492
+ const badge = document.getElementById('aiTestBadge');
493
+ if (badge) {
494
+ badge.textContent = 'Testing...';
495
+ badge.className = 'pill pill-accent';
496
+ }
497
+
498
+ await api('/api/settings/secrets', {
499
+ method: 'POST',
500
+ body: JSON.stringify({ provider, model, baseUrl, apiKey })
501
+ });
502
+ await api('/api/settings', {
503
+ method: 'PUT',
504
+ body: JSON.stringify({ tokenBudgetWarnUsd: budget })
505
+ });
506
+ document.getElementById('dialApiKey').value = '';
507
+
508
+ const testRes = await api('/api/settings/test-ai', {
509
+ method: 'POST',
510
+ body: JSON.stringify({ provider, model, baseUrl })
511
+ });
512
+ if (testRes.ok) {
513
+ if (badge) {
514
+ badge.textContent = `Connected ✓ (${testRes.latencyMs}ms)`;
515
+ badge.className = 'pill pill-ok';
516
+ }
517
+ showToast('ok', `Connected to ${provider}/${model} (${testRes.latencyMs}ms).`);
518
+ } else {
519
+ if (badge) {
520
+ badge.textContent = 'Error';
521
+ badge.className = 'pill pill-danger';
522
+ }
523
+ showToast('err', testRes.error || 'AI connection test failed');
524
+ }
525
+ await Promise.all([refreshHealth(), loadSettings()]);
526
+ });
527
+ };
528
+
529
+ // --- GitHub Device Flow (Sequential setTimeout Polling — Never Stuck!) ---
530
+ window.openGithubConnectModal = () => {
531
+ document.getElementById('githubConnectModal').showModal();
532
+ };
533
+
534
+ window.showGhTab = (tabName, btn) => {
535
+ btn.parentElement.querySelectorAll('.tab').forEach((tEl) => tEl.classList.remove('active'));
536
+ btn.classList.add('active');
537
+ ['device', 'pat', 'cli', 'app'].forEach((name) => {
538
+ document.getElementById(`ghTab-${name}`).classList.toggle('hidden', name !== tabName);
539
+ });
540
+ };
541
+
542
+ function stopDevicePolling() {
543
+ state.devicePollActive = false;
544
+ if (state.devicePollTimer) {
545
+ clearTimeout(state.devicePollTimer);
546
+ state.devicePollTimer = null;
547
+ }
548
+ }
549
+
550
+ async function pollDeviceOnce(containerId) {
551
+ if (!state.deviceSession?.sessionId) return true;
552
+ const statusEl = document.getElementById(`${containerId}-status`);
553
+ if (statusEl) statusEl.textContent = 'Checking authorization with GitHub...';
554
+
555
+ const p = await api('/api/github/device/poll', {
556
+ method: 'POST',
557
+ body: JSON.stringify({ sessionId: state.deviceSession.sessionId })
558
+ }).catch((err) => ({ status: 'error', error: err.message }));
559
+
560
+ if (p.status === 'authorized') {
561
+ stopDevicePolling();
562
+ if (statusEl) {
563
+ statusEl.innerHTML = `<span style="color:var(--green)">Authorized ✓ (${escapeHtml(p.maskedGithubToken || '')})</span>`;
564
+ }
565
+ showToast('ok', 'GitHub authorized! Loading your repositories...');
566
+ await Promise.all([refreshHealth(), loadSettings(), loadGithubRepos()]);
567
+ return true;
568
+ }
569
+
570
+ if (p.status === 'expired' || p.status === 'denied' || p.status === 'error') {
571
+ stopDevicePolling();
572
+ if (statusEl) statusEl.innerHTML = `<span style="color:var(--red)">${escapeHtml(p.error || p.status)}</span>`;
573
+ showToast('err', p.error || `GitHub authorization ${p.status}`);
574
+ return true;
575
+ }
576
+
577
+ if (p.status === 'slow_down' && p.interval) {
578
+ state.deviceSession.interval = p.interval;
579
+ }
580
+ if (statusEl) {
581
+ statusEl.textContent = `Waiting for GitHub approval (checking every ${Math.max((state.deviceSession.interval || 5) + 1, 6)}s)...`;
582
+ }
583
+ return false;
584
+ }
585
+
586
+ window.checkDeviceAuthorizationNow = async (containerId, btnEl) => {
587
+ await withButtonLoading(btnEl, async () => {
588
+ await pollDeviceOnce(containerId);
589
+ });
590
+ };
591
+
592
+ window.startDeviceFlow = async (containerId, btnEl) => {
593
+ stopDevicePolling();
594
+ const run = async () => {
595
+ const box = document.getElementById(containerId);
596
+ box.classList.remove('hidden');
597
+ box.innerHTML = '<div class="muted">Requesting GitHub Device Code...</div>';
598
+
599
+ const res = await api('/api/github/device/start', { method: 'POST', body: '{}' });
600
+ if (res.error) {
601
+ box.innerHTML = `<div style="color:var(--red)">${escapeHtml(res.error)}</div>`;
602
+ return showToast('err', res.error);
603
+ }
604
+
605
+ state.deviceSession = { sessionId: res.sessionId, interval: res.interval || 5 };
606
+ box.innerHTML = `
607
+ <div>Enter this code on GitHub:</div>
608
+ <div class="device-code-big">${escapeHtml(res.userCode)}</div>
609
+ <div class="row-gap">
610
+ <button type="button" class="btn btn-sm btn-secondary" onclick="copyText('${escapeHtml(res.userCode)}', 'Device code copied')">Copy Code</button>
611
+ <a class="btn btn-sm btn-primary" href="${escapeHtml(res.verificationUri)}" target="_blank" rel="noreferrer">Open GitHub Device Page</a>
612
+ <button type="button" class="btn btn-sm btn-secondary" onclick="checkDeviceAuthorizationNow('${containerId}', this)">I Authorized — Check Now</button>
613
+ </div>
614
+ <div id="${containerId}-status" class="muted" style="margin-top:8px">Waiting for authorization...</div>`;
615
+
616
+ if (window.codepulseDesktop?.openExternal) {
617
+ window.codepulseDesktop.openExternal(res.verificationUri);
618
+ } else {
619
+ window.open(res.verificationUri, '_blank', 'noopener');
620
+ }
621
+
622
+ state.devicePollActive = true;
623
+ const loop = async () => {
624
+ if (!state.devicePollActive) return;
625
+ const delayMs = Math.max((state.deviceSession?.interval || 5) + 1, 6) * 1000;
626
+ state.devicePollTimer = setTimeout(async () => {
627
+ if (!state.devicePollActive) return;
628
+ const done = await pollDeviceOnce(containerId);
629
+ if (!done && state.devicePollActive) loop();
630
+ }, delayMs);
631
+ };
632
+ loop();
633
+ };
634
+ if (btnEl) await withButtonLoading(btnEl, run);
635
+ else await run();
636
+ };
637
+
638
+ window.savePatFromInput = async (inputId, btnEl) => {
639
+ await withButtonLoading(btnEl, async () => {
640
+ const token = document.getElementById(inputId).value.trim();
641
+ if (!token) return showToast('err', 'Paste a GitHub PAT first.');
642
+ await api('/api/settings/secrets', { method: 'POST', body: JSON.stringify({ githubToken: token }) });
643
+ document.getElementById(inputId).value = '';
644
+ showToast('ok', 'GitHub token saved securely locally.');
645
+ await Promise.all([refreshHealth(), loadSettings(), loadGithubRepos()]);
646
+ });
647
+ };
648
+
649
+ window.openOnboardingWizard = (stepIdx = 0) => {
650
+ showWizardStep(stepIdx);
651
+ document.getElementById('onboardingModal').showModal();
652
+ if (stepIdx === 2) loadGithubRepos();
653
+ };
654
+
655
+ window.showWizardStep = (idx) => {
656
+ [0, 1, 2, 3].forEach((i) => {
657
+ document.getElementById(`wizTab${i}`)?.classList.toggle('active', i === idx);
658
+ document.getElementById(`wizStep${i}`)?.classList.toggle('hidden', i !== idx);
659
+ });
660
+ };
661
+
662
+ window.wizardSaveAndTestAi = async (btnEl) => {
663
+ await withButtonLoading(btnEl, async () => {
664
+ const provider = document.getElementById('wizProvider').value;
665
+ const model = getSelectedModelValue('wizModel', 'wizCustomModel');
666
+ const apiKey = document.getElementById('wizApiKey').value.trim() || undefined;
667
+ const statusEl = document.getElementById('wizAiStatus');
668
+ statusEl.textContent = 'Saving & testing connection...';
669
+
670
+ await api('/api/settings/secrets', {
671
+ method: 'POST',
672
+ body: JSON.stringify({ provider, model, apiKey })
673
+ });
674
+ const testRes = await api('/api/settings/test-ai', {
675
+ method: 'POST',
676
+ body: JSON.stringify({ provider, model })
677
+ });
678
+ if (testRes.ok) {
679
+ statusEl.innerHTML = `<span style="color:var(--green)">Connected ✓ (${testRes.latencyMs}ms)</span>`;
680
+ showToast('ok', `AI Connected (${testRes.latencyMs}ms).`);
681
+ await Promise.all([refreshHealth(), loadSettings()]);
682
+ showWizardStep(1);
683
+ } else {
684
+ statusEl.innerHTML = `<span style="color:var(--red)">${escapeHtml(testRes.error || 'Failed')}</span>`;
685
+ showToast('err', testRes.error || 'AI connection failed');
686
+ }
687
+ });
688
+ };
689
+
690
+ window.finishOnboardingConsent = async (btnEl) => {
691
+ if (!document.getElementById('wizAcceptTerms')?.checked) {
692
+ return showToast('err', 'Please accept Terms of Service & Privacy Policy to continue.');
693
+ }
694
+ await withButtonLoading(btnEl, async () => {
695
+ const optIn = Boolean(document.getElementById('wizTelemetryOptIn')?.checked);
696
+ await api('/api/settings', {
697
+ method: 'PUT',
698
+ body: JSON.stringify({ telemetryOptIn: optIn, consentCompleted: true })
699
+ });
700
+ document.getElementById('onboardingModal').close();
701
+ showToast('ok', 'CodePulse setup complete!');
702
+ await loadSettings();
703
+ });
704
+ };
705
+
706
+ window.loadGithubRepos = async (btnEl) => {
707
+ const run = async () => {
708
+ const box = document.getElementById('wizRepoResults');
709
+ box.innerHTML = '<div class="muted">Loading accessible public & private repos...</div>';
710
+ const res = await api('/api/github/repos');
711
+ if (res.error) {
712
+ box.innerHTML = `<div class="muted">${escapeHtml(res.error)}</div>`;
713
+ return;
714
+ }
715
+ state.githubRepos = res.repos || [];
716
+ if (state.githubRepos.length === 0) {
717
+ box.innerHTML = `
718
+ <div class="card">
719
+ <div class="muted" style="margin-bottom:8px">No repositories accessible to CodePulsebot yet. Grant repo access or open a local folder:</div>
720
+ <div class="row-gap">
721
+ <a class="btn btn-sm btn-primary" href="https://github.com/apps/codepulsebot/installations/new" target="_blank" rel="noreferrer">Install CodePulsebot on Your Repos</a>
722
+ <button type="button" class="btn btn-sm btn-secondary" onclick="loadGithubRepos(this)">Refresh Repos</button>
723
+ </div>
724
+ </div>`;
725
+ return;
726
+ }
727
+ filterGithubRepos();
728
+ };
729
+ if (btnEl) await withButtonLoading(btnEl, run);
730
+ else await run();
731
+ };
732
+
733
+ window.filterGithubRepos = () => {
734
+ const q = (document.getElementById('wizRepoSearch').value || '').toLowerCase();
735
+ const box = document.getElementById('wizRepoResults');
736
+ const filtered = state.githubRepos.filter((r) => r.fullName.toLowerCase().includes(q));
737
+ box.innerHTML = filtered.length === 0
738
+ ? '<div class="muted">No matching repositories found.</div>'
739
+ : filtered.slice(0, 40).map((r) => `
740
+ <div class="list-item" onclick="connectGithubRepo('${escapeHtml(r.owner)}','${escapeHtml(r.name)}','${escapeHtml(r.defaultBranch)}')">
741
+ <div class="finding-top">
742
+ <strong>${escapeHtml(r.fullName)}</strong>
743
+ <span class="pill pill-muted">${r.private ? 'Private' : 'Public'}</span>
744
+ </div>
745
+ <div class="muted">${escapeHtml(r.description || r.defaultBranch)}</div>
746
+ </div>`).join('');
747
+ };
748
+
749
+ window.connectGithubRepo = async (owner, name, defaultBranch) => {
750
+ const res = await api('/api/repos', {
751
+ method: 'POST',
752
+ body: JSON.stringify({ name: `${owner}/${name}`, githubOwner: owner, githubRepo: name, defaultBranch })
753
+ });
754
+ if (res.repo) {
755
+ state.selectedRepoId = res.repo.id;
756
+ showToast('ok', `Connected ${owner}/${name}`);
757
+ showWizardStep(3);
758
+ await refreshAll();
759
+ }
760
+ };
761
+
762
+ window.pickNativeFolderAndConnect = async (btnEl) => {
763
+ await withButtonLoading(btnEl, async () => {
764
+ const folder = window.codepulseDesktop?.pickLocalFolder
765
+ ? await window.codepulseDesktop.pickLocalFolder()
766
+ : (await api('/api/desktop/pick-folder', { method: 'POST', body: '{}' })).folder;
767
+ if (!folder) return;
768
+ const res = await api('/api/repos', { method: 'POST', body: JSON.stringify({ localPath: folder }) });
769
+ if (res.repo) {
770
+ state.selectedRepoId = res.repo.id;
771
+ showToast('ok', `Connected ${res.repo.name}`);
772
+ showWizardStep(3);
773
+ await refreshAll();
774
+ }
775
+ });
776
+ };
777
+
778
+ window.browseLocalPathIntoModal = async () => {
779
+ const folder = window.codepulseDesktop?.pickLocalFolder
780
+ ? await window.codepulseDesktop.pickLocalFolder()
781
+ : (await api('/api/desktop/pick-folder', { method: 'POST', body: '{}' })).folder;
782
+ if (folder) document.getElementById('modalLocalPath').value = folder;
783
+ };
784
+
785
+ // --- Launcher & Pre-Flight Cost Estimator ---
786
+ window.onLaunchTargetChange = () => {
787
+ const tgt = document.getElementById('launchTarget').value;
788
+ document.getElementById('launchPrWrap').classList.toggle('hidden', tgt !== 'pr');
789
+ document.getElementById('launchDirWrap').classList.toggle('hidden', tgt !== 'directory');
790
+ refreshPreFlightEstimate();
791
+ };
792
+
793
+ window.refreshPreFlightEstimate = async (btnEl) => {
794
+ const run = async () => {
795
+ const el = document.getElementById('estimateSummary');
796
+ if (!state.selectedRepoId) {
797
+ el.textContent = t('estimatePending');
798
+ return;
799
+ }
800
+ const target = document.getElementById('launchTarget').value;
801
+ if (target === 'docs') {
802
+ el.textContent = 'Docs generator uses local AST graph + optional BYOK AI synthesis.';
803
+ return;
804
+ }
805
+ const mode = document.getElementById('launchMode').value;
806
+ if (mode === 'fast') {
807
+ el.textContent = 'Fast Mode (Deterministic SAST + OSV CVE): 0 AI tokens · $0.0000';
808
+ return;
809
+ }
810
+ if (mode === 'comprehensive') {
811
+ el.textContent = 'Full Spectrum Audit: AST + Extended Detectors + OSV CVEs + Radar + SEO/GEO + Adversarial Debate.';
812
+ return;
813
+ }
814
+ if (mode === 'seo-geo') {
815
+ el.textContent = 'SEO & GEO Audit: Technical SEO + llms.txt + JSON-LD + AI crawler checks (~0–1K tokens).';
816
+ return;
817
+ }
818
+ const res = await api('/api/jobs/estimate', {
819
+ method: 'POST',
820
+ body: JSON.stringify({ repoId: state.selectedRepoId, target })
821
+ }).catch(() => ({}));
822
+ if (res.estimate) {
823
+ const e = res.estimate;
824
+ el.textContent = `Est (${e.model}): ${e.fileCount} files · ~${e.astSlicedTokens.toLocaleString()} AST tokens (${e.tokenSavingsPercent}% saved vs ${e.rawTokens.toLocaleString()} raw) · ~$${e.estimatedCostUsd.toFixed(4)}`;
825
+ }
826
+ };
827
+ if (btnEl) await withButtonLoading(btnEl, run);
828
+ else await run();
829
+ };
830
+
831
+ window.refreshOpenPrs = async (btnEl) => {
832
+ const run = async () => {
833
+ const sel = document.getElementById('launchPrSelect');
834
+ const repo = state.repos.find((r) => r.id === state.selectedRepoId);
835
+ if (!repo?.githubOwner || !repo?.githubRepo) {
836
+ sel.innerHTML = '<option value="">Local-only repo (no GitHub remote)</option>';
837
+ return;
838
+ }
839
+ sel.innerHTML = '<option value="">Loading open PRs...</option>';
840
+ const res = await api(`/api/github/repos/${encodeURIComponent(repo.githubOwner)}/${encodeURIComponent(repo.githubRepo)}/pulls`);
841
+ if (res.error || !res.pulls?.length) {
842
+ sel.innerHTML = `<option value="">${escapeHtml(res.error || 'No open Pull Requests')}</option>`;
843
+ return;
844
+ }
845
+ sel.innerHTML = res.pulls.map((p) =>
846
+ `<option value="${p.number}" data-base="${escapeHtml(p.baseRef)}" data-head="${escapeHtml(p.headRef)}">#${p.number} ${escapeHtml(p.title)} (${escapeHtml(p.author)})</option>`
847
+ ).join('');
848
+ };
849
+ if (btnEl) await withButtonLoading(btnEl, run);
850
+ else await run();
851
+ };
852
+
853
+ window.launchConfiguredScan = async (btnEl) => {
854
+ if (!state.selectedRepoId) return openOnboardingWizard(2);
855
+ const target = document.getElementById('launchTarget').value;
856
+ if (target === 'docs') return generateDocsAction(btnEl);
857
+
858
+ await withButtonLoading(btnEl, async () => {
859
+ const mode = document.getElementById('launchMode').value;
860
+ const prSel = document.getElementById('launchPrSelect');
861
+ const selectedOpt = prSel.options[prSel.selectedIndex];
862
+ const prNumber = target === 'pr' && prSel.value ? Number(prSel.value) : undefined;
863
+ if (target === 'pr' && !prNumber) {
864
+ showToast('err', 'Select an open Pull Request first (or switch target to Main / Local).');
865
+ return;
866
+ }
867
+
868
+ state.findingsViewCleared = false;
869
+ const res = await api('/api/jobs', {
870
+ method: 'POST',
871
+ body: JSON.stringify({
872
+ repoId: state.selectedRepoId,
873
+ target,
874
+ mode,
875
+ prNumber,
876
+ baseRef: selectedOpt?.dataset?.base,
877
+ headRef: selectedOpt?.dataset?.head,
878
+ directoryPath: target === 'directory' ? document.getElementById('launchDirInput').value.trim() : undefined,
879
+ postToGithub: document.getElementById('launchPostGh').checked,
880
+ saveMarkdownOnce: document.getElementById('launchSaveMd').checked
881
+ })
882
+ });
883
+ if (res.error) return showToast('err', res.error);
884
+ if (res.job) {
885
+ state.selectedJobId = res.job.id;
886
+ showToast('ok', `Queued ${mode} scan (${target}).`);
887
+ await refreshJobs();
888
+ }
889
+ });
890
+ };
891
+
892
+ document.getElementById('repoModalForm').onsubmit = async (e) => {
893
+ e.preventDefault();
894
+ const res = await api('/api/repos', {
895
+ method: 'POST',
896
+ body: JSON.stringify({
897
+ localPath: document.getElementById('modalLocalPath').value.trim() || undefined,
898
+ githubOwner: document.getElementById('modalGhOwner').value.trim() || undefined,
899
+ githubRepo: document.getElementById('modalGhRepo').value.trim() || undefined,
900
+ autofixEnabled: document.getElementById('modalAutofix').checked
901
+ })
902
+ });
903
+ if (res.error) return showToast('err', res.error);
904
+ if (res.repo) {
905
+ state.selectedRepoId = res.repo.id;
906
+ document.getElementById('repoModal').close();
907
+ showToast('ok', `Connected repository ${res.repo.name}`);
908
+ await refreshAll();
909
+ }
910
+ };
911
+
912
+ async function refreshHealth() {
913
+ const h = await api('/api/health');
914
+ const aiEl = document.getElementById('aiStatusPill');
915
+ if (aiEl) {
916
+ aiEl.innerHTML = `<span class="status-dot ${h.aiConfigured ? 'ok' : 'warn'}"></span><span>AI: ${escapeHtml(h.aiProvider)}/${escapeHtml(h.aiModel)} ${h.aiConfigured ? 'Ready' : '(Setup)'}</span>`;
917
+ aiEl.onclick = () => openSettingsModal('ai');
918
+ }
919
+
920
+ const ghEl = document.getElementById('ghStatusPill');
921
+ if (ghEl) {
922
+ ghEl.innerHTML = `<span class="status-dot ${h.githubConnected ? 'ok' : ''}"></span><span>${h.githubConnected ? 'GitHub Connected' : 'GitHub: Connect'}</span>`;
923
+ }
924
+
925
+ const qPill = document.getElementById('queuePill');
926
+ if (qPill) qPill.textContent = `Queue: ${h.activeJobs}/${h.concurrency}`;
927
+ const qCounter = document.getElementById('queueCounter');
928
+ if (qCounter) qCounter.textContent = `${h.activeJobs}/${h.concurrency}`;
929
+
930
+ if (!state.onboardingChecked) {
931
+ state.onboardingChecked = true;
932
+ const s = await api('/api/settings').catch(() => ({}));
933
+ if (!h.aiConfigured || h.reposCount === 0 || !s.consentCompleted) {
934
+ openOnboardingWizard(!h.aiConfigured ? 0 : !h.githubConnected ? 1 : h.reposCount === 0 ? 2 : 3);
935
+ }
936
+ }
937
+ }
938
+
939
+ async function refreshRepos() {
940
+ const { repos } = await api('/api/repos');
941
+ state.repos = repos || [];
942
+ if ((!state.selectedRepoId || !state.repos.some((r) => r.id === state.selectedRepoId)) && state.repos.length > 0) {
943
+ state.selectedRepoId = state.repos[0].id;
944
+ }
945
+ const el = document.getElementById('repoList');
946
+ el.innerHTML = state.repos.length === 0
947
+ ? `<div class="muted">${escapeHtml(t('noRepos'))}</div>`
948
+ : state.repos.map((r) => `
949
+ <div class="list-item ${r.id === state.selectedRepoId ? 'active' : ''}" onclick="selectRepo('${r.id}')">
950
+ <div class="finding-top">
951
+ <strong>${escapeHtml(r.name)}</strong>
952
+ <button type="button" class="btn btn-xs btn-ghost" title="Remove repo" onclick="event.stopPropagation(); removeRepo('${r.id}')">×</button>
953
+ </div>
954
+ <div class="muted mono">${escapeHtml(r.localPath || `${r.githubOwner}/${r.githubRepo}`)}</div>
955
+ </div>`).join('');
956
+ await Promise.all([refreshOpenPrs(), refreshPreFlightEstimate(), loadPulseAndSlices()]);
957
+ }
958
+
959
+ window.removeRepo = async (repoId) => {
960
+ await api(`/api/repos/${repoId}`, { method: 'DELETE' });
961
+ if (state.selectedRepoId === repoId) state.selectedRepoId = null;
962
+ showToast('info', 'Repository removed.');
963
+ await refreshRepos();
964
+ };
965
+
966
+ window.selectRepo = async (id) => {
967
+ state.selectedRepoId = id;
968
+ await Promise.all([refreshRepos(), loadOutputRule(), loadMemoryRules()]);
969
+ };
970
+
971
+ async function refreshJobs() {
972
+ const data = await api('/api/jobs');
973
+ state.jobs = data.jobs || [];
974
+ if (!state.selectedJobId && state.jobs.length > 0 && !state.findingsViewCleared) {
975
+ state.selectedJobId = state.jobs[0].id;
976
+ }
977
+ const el = document.getElementById('jobList');
978
+ el.innerHTML = state.jobs.slice(0, 14).map((j) => {
979
+ const canCancel = j.status === 'queued' || j.status === 'running';
980
+ const canRetry = j.status === 'completed' || j.status === 'failed' || j.status === 'cancelled';
981
+ const repoObj = state.repos.find((r) => r.id === j.repoId);
982
+ const repoLabel = j.repoName || repoObj?.name || 'workspace';
983
+ const prLabel = j.prNumber ? ` · PR #${j.prNumber}` : '';
984
+ const statusCls = j.status === 'completed' ? (j.mergeGatePassed ? 'pill-ok' : 'pill-danger') : j.status === 'cancelled' || j.status === 'failed' ? 'pill-muted' : 'pill-accent';
985
+ return `
986
+ <div class="list-item ${j.id === state.selectedJobId ? 'active' : ''}" onclick="selectJob('${j.id}')">
987
+ <div class="finding-top">
988
+ <strong>${escapeHtml(repoLabel)}${escapeHtml(prLabel)} · ${escapeHtml(j.mode)}</strong>
989
+ <span class="pill ${statusCls}">${j.status}</span>
990
+ </div>
991
+ <div class="muted">${escapeHtml(j.target)} · ${escapeHtml(j.currentStep || '')} (${j.progress}%)</div>
992
+ <div class="progress-bar"><div class="progress-fill" style="width:${j.progress}%"></div></div>
993
+ <div class="finding-actions" onclick="event.stopPropagation()">
994
+ ${canCancel ? `<button class="btn btn-xs btn-danger" onclick="cancelJob('${j.id}', this)">Cancel</button>` : ''}
995
+ ${canRetry ? `<button class="btn btn-xs btn-ghost" onclick="retryJob('${j.id}', this)">Retry</button>` : ''}
996
+ </div>
997
+ </div>`;
998
+ }).join('');
999
+ await renderSelectedJob();
1000
+ }
1001
+
1002
+ window.clearCompletedJobs = async (btnEl) => {
1003
+ await withButtonLoading(btnEl, async () => {
1004
+ const res = await api('/api/jobs/history', { method: 'DELETE' });
1005
+ state.fullJobCache = {};
1006
+ showToast('info', `Cleared ${res.cleared || 0} completed job(s).`);
1007
+ await refreshJobs();
1008
+ });
1009
+ };
1010
+
1011
+ window.clearSelectedFindingsView = () => {
1012
+ state.findingsViewCleared = true;
1013
+ state.selectedJobId = null;
1014
+ renderSelectedJob();
1015
+ showToast('info', 'Findings view cleared. Select any job or start a new scan.');
1016
+ };
1017
+
1018
+ window.selectJob = async (id) => {
1019
+ state.findingsViewCleared = false;
1020
+ state.selectedJobId = id;
1021
+ await refreshJobs();
1022
+ };
1023
+
1024
+ window.cancelJob = async (jobId, btnEl) => {
1025
+ await withButtonLoading(btnEl, async () => {
1026
+ await api(`/api/jobs/${jobId}/cancel`, { method: 'POST', body: '{}' });
1027
+ showToast('info', `Cancelled job ${jobId.slice(0, 8)}.`);
1028
+ await refreshJobs();
1029
+ });
1030
+ };
1031
+
1032
+ window.retryJob = async (jobId, btnEl) => {
1033
+ await withButtonLoading(btnEl, async () => {
1034
+ state.findingsViewCleared = false;
1035
+ const res = await api(`/api/jobs/${jobId}/retry`, { method: 'POST', body: '{}' });
1036
+ if (res.job) state.selectedJobId = res.job.id;
1037
+ showToast('ok', 'Re-queued scan job.');
1038
+ await refreshJobs();
1039
+ });
1040
+ };
1041
+
1042
+ function renderPatchLines(patchText, mode) {
1043
+ const lines = String(patchText || '').split(/\r?\n/);
1044
+ if (mode === 'split') {
1045
+ const left = [];
1046
+ const right = [];
1047
+ lines.forEach((l, i) => {
1048
+ if (l.startsWith('-')) left.push(`<div class="diff-row diff-line-del"><span class="diff-ln">${i + 1}</span><span>${escapeHtml(l)}</span></div>`);
1049
+ else if (l.startsWith('+')) right.push(`<div class="diff-row diff-line-add"><span class="diff-ln">${i + 1}</span><span>${escapeHtml(l)}</span></div>`);
1050
+ else {
1051
+ const row = `<div class="diff-row"><span class="diff-ln">${i + 1}</span><span>${escapeHtml(l)}</span></div>`;
1052
+ left.push(row);
1053
+ right.push(row);
1054
+ }
1055
+ });
1056
+ return `<div class="diff-panel diff-split-grid"><div class="diff-col">${left.join('')}</div><div class="diff-col">${right.join('')}</div></div>`;
1057
+ }
1058
+ return `<div class="diff-panel">${lines.map((l, i) => {
1059
+ const cls = l.startsWith('+') ? 'diff-line-add' : l.startsWith('-') ? 'diff-line-del' : '';
1060
+ return `<div class="diff-row ${cls}"><span class="diff-ln">${i + 1}</span><span>${escapeHtml(l)}</span></div>`;
1061
+ }).join('')}</div>`;
1062
+ }
1063
+
1064
+ function getFindingDomainKey(f) {
1065
+ const rid = String(f.rule_id || '');
1066
+ if (rid.startsWith('OSV-') || rid.includes('CVE-')) return 'cves';
1067
+ if (f.category === 'security' || f.category === 'auth') return 'security-auth';
1068
+ if (f.category === 'migration-drift' || f.category === 'architecture') return 'drift';
1069
+ if (f.category === 'performance' || f.category === 'concurrency') return 'perf';
1070
+ if (f.category === 'reliability' || f.category === 'logic' || f.category === 'finance' || f.category === 'null-safety') return 'reliability';
1071
+ if (f.category === 'accessibility') return 'a11y';
1072
+ if (f.category === 'env-config' || f.category === 'iac-docker') return 'env-ci';
1073
+ if (f.category === 'seo' || f.category === 'geo') return 'seo-geo';
1074
+ return 'quality';
1075
+ }
1076
+
1077
+ function getCategoryMeta(groupKey) {
1078
+ const map = {
1079
+ 'security-auth': { tag: 'SEC', label: 'Security & Auth' },
1080
+ cves: { tag: 'CVE', label: 'Dependency CVEs' },
1081
+ drift: { tag: 'API', label: 'Cross-Layer Drift' },
1082
+ perf: { tag: 'PERF', label: 'Performance & N+1' },
1083
+ reliability: { tag: 'REL', label: 'Reliability & Logic' },
1084
+ a11y: { tag: 'A11Y', label: 'Accessibility' },
1085
+ 'env-ci': { tag: 'ENV', label: 'Environment & CI' },
1086
+ 'seo-geo': { tag: 'GEO', label: 'SEO & GEO' },
1087
+ quality: { tag: 'QUAL', label: 'Dead Code & Quality' }
1088
+ };
1089
+ return map[groupKey] || { tag: 'ITEM', label: String(groupKey).toUpperCase() };
1090
+ }
1091
+
1092
+ window.setAllFindingsExpanded = (expand) => {
1093
+ document.querySelectorAll('#findingsList details').forEach((d) => {
1094
+ d.open = expand;
1095
+ });
1096
+ };
1097
+
1098
+ async function renderSelectedJob() {
1099
+ const summaryJob = state.jobs.find((j) => j.id === state.selectedJobId);
1100
+ const banner = document.getElementById('jobHeaderBanner');
1101
+ const list = document.getElementById('findingsList');
1102
+ const countLabel = document.getElementById('findingsCountLabel');
1103
+
1104
+ if (!summaryJob || state.findingsViewCleared) {
1105
+ banner.textContent = t('emptyFindingsBanner');
1106
+ list.innerHTML = '';
1107
+ if (countLabel) countLabel.textContent = '';
1108
+ return;
1109
+ }
1110
+
1111
+ let job = summaryJob;
1112
+ if (summaryJob.status === 'completed' && !summaryJob.resultJson) {
1113
+ if (!state.fullJobCache[summaryJob.id]) {
1114
+ const fullRes = await api(`/api/jobs/${summaryJob.id}`).catch(() => ({}));
1115
+ if (fullRes.job) state.fullJobCache[summaryJob.id] = fullRes.job;
1116
+ }
1117
+ job = state.fullJobCache[summaryJob.id] || summaryJob;
1118
+ }
1119
+
1120
+ if (!job.resultJson) {
1121
+ banner.textContent = `Job ${job.id}: ${job.status} (${job.currentStep || ''})`;
1122
+ list.innerHTML = '';
1123
+ if (countLabel) countLabel.textContent = '';
1124
+ return;
1125
+ }
1126
+
1127
+ const out = job.resultJson;
1128
+ const groupBy = document.getElementById('findingsGroupBy')?.value || 'category';
1129
+ const sevFilter = document.getElementById('findingsSeverityFilter')?.value || 'all';
1130
+ const diffMode = document.getElementById('diffViewMode')?.value || 'unified';
1131
+ const visible = out.findings.filter((f) =>
1132
+ sevFilter === 'blockers' ? (f.severity === 'critical' || f.severity === 'high') : true
1133
+ );
1134
+ if (countLabel) countLabel.textContent = `${visible.length} / ${out.findings.length} shown`;
1135
+
1136
+ const seoGeoHtml = (out.seoScore !== undefined || out.geoScore !== undefined)
1137
+ ? `<span class="pill pill-accent">SEO: ${out.seoScore ?? 100}/100</span> <span class="pill pill-ok">GEO AI: ${out.geoScore ?? 100}/100</span>`
1138
+ : '';
1139
+ const covHtml = out.patchCoveragePercent !== undefined
1140
+ ? `<span class="pill ${out.patchCoveragePercent >= 60 ? 'pill-ok' : 'pill-warn'}">Patch Cov: ${out.patchCoveragePercent}%</span>`
1141
+ : '';
1142
+
1143
+ banner.innerHTML = `
1144
+ <div class="finding-top">
1145
+ <div class="row-gap">
1146
+ <strong>Verdict:</strong> ${escapeHtml(out.verdict.toUpperCase())} |
1147
+ <strong>Merge Gate:</strong> <span class="pill ${out.merge_gate.passed ? 'pill-ok' : 'pill-danger'}">${out.merge_gate.passed ? 'PASS' : 'BLOCKED'}</span>
1148
+ <span class="muted mono">(${out.merge_gate.blockers_count} Critical, ${out.merge_gate.high_count} High)</span>
1149
+ ${seoGeoHtml} ${covHtml}
1150
+ </div>
1151
+ <div class="finding-actions" style="margin-top:0">
1152
+ <button class="btn btn-sm btn-secondary" onclick="copyReportMd('${job.id}', this)">Copy MD</button>
1153
+ <button class="btn btn-sm btn-secondary" onclick="exportJobMd('${job.id}', this)">Save .md</button>
1154
+ <button class="btn btn-sm btn-secondary" onclick="exportJobPdf('${job.id}', this)">Export PDF</button>
1155
+ <button class="btn btn-sm btn-primary" onclick="copyAgentPrompt('${job.id}', this)">Copy Prompt for AI Agent</button>
1156
+ </div>
1157
+ </div>
1158
+ <div class="muted" style="margin-top:6px">${escapeHtml(out.summary)}</div>`;
1159
+
1160
+ if (visible.length === 0) {
1161
+ list.innerHTML = '<div class="card muted">No open findings match this filter. Merge gate clear!</div>';
1162
+ return;
1163
+ }
1164
+
1165
+ // Group into 2-level Collapsible Hierarchy
1166
+ const groups = new Map();
1167
+ for (const f of visible) {
1168
+ const key = groupBy === 'severity' ? f.severity : getFindingDomainKey(f);
1169
+ if (!groups.has(key)) groups.set(key, []);
1170
+ groups.get(key).push(f);
1171
+ }
1172
+
1173
+ list.innerHTML = Array.from(groups.entries()).map(([groupKey, items]) => {
1174
+ const crit = items.filter((i) => i.severity === 'critical').length;
1175
+ const high = items.filter((i) => i.severity === 'high').length;
1176
+ const med = items.filter((i) => i.severity === 'medium').length;
1177
+ const meta = groupBy === 'severity'
1178
+ ? { tag: groupKey.slice(0, 4).toUpperCase(), label: groupKey.toUpperCase() }
1179
+ : getCategoryMeta(groupKey);
1180
+
1181
+ const chips = [
1182
+ crit ? `<span class="pill pill-danger">${crit} Critical</span>` : '',
1183
+ high ? `<span class="pill pill-warn">${high} High</span>` : '',
1184
+ med ? `<span class="pill pill-accent">${med} Medium</span>` : ''
1185
+ ].filter(Boolean).join(' ');
1186
+
1187
+ const rowsHtml = items.map((f) => {
1188
+ const sevCls = f.severity === 'critical' ? 'pill-danger' : f.severity === 'high' ? 'pill-warn' : f.severity === 'medium' ? 'pill-accent' : 'pill-muted';
1189
+ const debateHtml = f.debate ? `
1190
+ <details class="debate-proof">
1191
+ <summary>Debate Proof (${escapeHtml(f.debate.status || 'agreed')})</summary>
1192
+ <div class="debate-grid">
1193
+ <div class="debate-cell"><strong>Finder / Red Team</strong><p class="muted">${escapeHtml(f.debate.reviewer_argument || '')}</p></div>
1194
+ <div class="debate-cell"><strong>Skeptic / Defense</strong><p class="muted">${escapeHtml(f.debate.skeptic_argument || '')}</p></div>
1195
+ <div class="debate-cell"><strong>Judge Resolution</strong><p class="muted">${escapeHtml(f.debate.resolution_note || '')}</p></div>
1196
+ </div>
1197
+ </details>` : '';
1198
+
1199
+ const reachCls = f.reachability === 'external_reachable' ? 'reach-external' : f.reachability === 'isolated_unreachable' ? 'reach-isolated' : 'reach-internal';
1200
+ const reachPill = f.reachability ? `<span class="reach-pill ${reachCls}">${escapeHtml(f.reachability)}</span>` : '';
1201
+ const compPills = (f.compliance_tags || []).slice(0, 3).map((tag) => `<span class="pill pill-accent">${escapeHtml(tag)}</span>`).join(' ');
1202
+
1203
+ return `
1204
+ <details class="finding-acc sev-${f.severity}">
1205
+ <summary class="finding-row">
1206
+ <span class="pill ${sevCls}">${f.severity.toUpperCase()}</span>
1207
+ <span class="finding-row-loc">${escapeHtml(f.file)}:${f.line_start}</span>
1208
+ <span class="finding-row-title">${escapeHtml(f.title)}</span>
1209
+ <span class="row-gap">${reachPill}<span class="pill pill-muted">${Math.round(f.confidence * 100)}% · Blast ${f.blast_radius.risk_score} · ${escapeHtml(f.status)}</span></span>
1210
+ </summary>
1211
+ <div class="finding-detail">
1212
+ <div class="finding-meta">
1213
+ <code>${escapeHtml(f.file)}:${f.line_start}${f.line_end !== f.line_start ? '-' + f.line_end : ''}</code>
1214
+ · Rule: <b>${escapeHtml(f.rule_id || f.source)}</b> · Blast Risk: <b>${f.blast_radius.risk_score}/100</b>
1215
+ ${f.call_path?.length ? `· Call Path: <code>${escapeHtml(f.call_path.join(' → '))}</code>` : ''}
1216
+ ${compPills ? ` <span class="row-gap">${compPills}</span>` : ''}
1217
+ </div>
1218
+ <div>${escapeHtml(f.body)}</div>
1219
+ <div style="font-size:12px;margin-top:6px;color:var(--accent)"><b>Fix Recommendation:</b> ${escapeHtml(f.recommendation)}</div>
1220
+ ${f.patch_suggestion ? renderPatchLines(f.patch_suggestion, diffMode) : ''}
1221
+ ${debateHtml}
1222
+ <div id="ctx-${f.id}"></div>
1223
+ <div id="testgen-${f.id}"></div>
1224
+ <div class="finding-actions">
1225
+ <button class="btn btn-sm btn-ghost" onclick="toggleFindingContext('${f.id}', this)">Inspect Source Lines</button>
1226
+ <button class="btn btn-sm btn-secondary" onclick="generateTestsForFinding('${escapeHtml(f.file)}', '${f.id}', this)">Generate Tests</button>
1227
+ <button class="btn btn-sm btn-secondary" onclick="autofixFinding('${f.id}', this)">Auto-Fix (Worktree)</button>
1228
+ <button class="btn btn-sm btn-ghost" onclick="revalidateAction(['${f.id}'], this)">Revalidate</button>
1229
+ <button class="btn btn-sm btn-ghost" onclick="dismissFindingToMemory('${f.id}', this)">${escapeHtml(t('btnDismissFalsePositive'))}</button>
1230
+ </div>
1231
+ </div>
1232
+ </details>`;
1233
+ }).join('');
1234
+
1235
+ return `
1236
+ <details class="cat-group" open>
1237
+ <summary class="cat-summary">
1238
+ <span class="row-gap"><span class="kbd-hint">${escapeHtml(meta.tag)}</span><strong>${escapeHtml(meta.label)}</strong><span class="pill pill-muted">${items.length}</span></span>
1239
+ <span class="row-gap">${chips}</span>
1240
+ </summary>
1241
+ <div class="cat-items">${rowsHtml}</div>
1242
+ </details>`;
1243
+ }).join('');
1244
+ }
1245
+
1246
+ window.toggleFindingContext = async (findingId, btnEl) => {
1247
+ const slot = document.getElementById(`ctx-${findingId}`);
1248
+ if (!slot) return;
1249
+ if (slot.innerHTML.trim()) {
1250
+ slot.innerHTML = '';
1251
+ return;
1252
+ }
1253
+ await withButtonLoading(btnEl, async () => {
1254
+ const res = await api(`/api/findings/${findingId}/context`);
1255
+ if (!res.lines?.length) {
1256
+ slot.innerHTML = '<div class="muted" style="margin-top:6px">Source file unavailable locally.</div>';
1257
+ return;
1258
+ }
1259
+ slot.innerHTML = `<div class="diff-panel">${res.lines.map((l) => {
1260
+ const hl = l.line >= res.highlightStart && l.line <= res.highlightEnd ? 'diff-line-hl' : '';
1261
+ return `<div class="diff-row ${hl}"><span class="diff-ln">${l.line}</span><span>${escapeHtml(l.text)}</span></div>`;
1262
+ }).join('')}</div>`;
1263
+ });
1264
+ };
1265
+
1266
+ window.dismissFindingToMemory = async (findingId, btnEl) => {
1267
+ const reason = prompt('Reason to teach CodePulse Team Memory (optional):', 'Intentional / mitigated upstream');
1268
+ if (reason === null) return;
1269
+ await withButtonLoading(btnEl, async () => {
1270
+ await api(`/api/findings/${findingId}/ignore`, {
1271
+ method: 'POST',
1272
+ body: JSON.stringify({ reason })
1273
+ });
1274
+ delete state.fullJobCache[state.selectedJobId];
1275
+ showToast('ok', 'Pattern saved to .codepulse/memory.json.');
1276
+ await Promise.all([refreshJobs(), loadMemoryRules()]);
1277
+ });
1278
+ };
1279
+
1280
+ window.runAction = async (target, defaultMode, btnEl) => {
1281
+ if (!state.selectedRepoId) return openOnboardingWizard(2);
1282
+ await withButtonLoading(btnEl, async () => {
1283
+ let mode = defaultMode;
1284
+ if (defaultMode !== 'seo-geo' && defaultMode !== 'comprehensive') {
1285
+ if (document.getElementById('toggleAdversarial').checked) mode = 'adversarial';
1286
+ else if (document.getElementById('toggleDebate').checked && defaultMode === 'debate') mode = 'debate';
1287
+ }
1288
+ state.findingsViewCleared = false;
1289
+ const res = await api('/api/jobs', {
1290
+ method: 'POST',
1291
+ body: JSON.stringify({
1292
+ repoId: state.selectedRepoId,
1293
+ target,
1294
+ mode,
1295
+ saveMarkdownOnce: document.getElementById('toggleSaveOnce').checked
1296
+ })
1297
+ });
1298
+ if (res.error) return showToast('err', res.error);
1299
+ if (res.job) {
1300
+ state.selectedJobId = res.job.id;
1301
+ showToast('ok', `Started ${mode} scan.`);
1302
+ await refreshJobs();
1303
+ }
1304
+ });
1305
+ };
1306
+
1307
+ window.copyText = async (txt, toastMsg = 'Copied to clipboard.') => {
1308
+ await navigator.clipboard.writeText(txt);
1309
+ showToast('ok', toastMsg, 2600);
1310
+ };
1311
+
1312
+ window.copyReportMd = async (jobId, btnEl) => {
1313
+ await withButtonLoading(btnEl, async () => {
1314
+ const { markdown } = await api(`/api/jobs/${jobId}/markdown`);
1315
+ await navigator.clipboard.writeText(markdown);
1316
+ showToast('ok', 'Markdown report copied to clipboard.');
1317
+ });
1318
+ };
1319
+
1320
+ window.copyAgentPrompt = async (jobId, btnEl) => {
1321
+ await withButtonLoading(btnEl, async () => {
1322
+ const { markdown } = await api(`/api/jobs/${jobId}/markdown`);
1323
+ await navigator.clipboard.writeText(`Fix all Critical/High CodePulse blockers below and call revalidate_findings:\n\n${markdown}`);
1324
+ showToast('ok', 'AI Agent prompt copied to clipboard.');
1325
+ });
1326
+ };
1327
+
1328
+ window.exportJobMd = async (jobId, btnEl) => {
1329
+ await withButtonLoading(btnEl, async () => {
1330
+ const exportDir = document.getElementById('ruleExportDir').value || './reports';
1331
+ const res = await api(`/api/jobs/${jobId}/export-md`, { method: 'POST', body: JSON.stringify({ exportDir }) });
1332
+ showToast(res.writtenPath ? 'ok' : 'err', res.writtenPath ? `Saved to ${res.writtenPath}` : (res.error || 'Export failed'));
1333
+ });
1334
+ };
1335
+
1336
+ window.exportJobPdf = async (jobId, btnEl) => {
1337
+ await withButtonLoading(btnEl, async () => {
1338
+ const res = await api(`/api/jobs/${jobId}/export-pdf`, { method: 'POST', body: '{}' });
1339
+ if (res.saved && res.path) {
1340
+ showToast('ok', `Executive PDF saved to ${res.path}`);
1341
+ return;
1342
+ }
1343
+ if (res.printUrl) {
1344
+ window.open(res.printUrl, '_blank');
1345
+ showToast('info', 'Opened print-ready Executive Audit report (Print -> Save as PDF).');
1346
+ } else if (res.error) {
1347
+ showToast('err', res.error);
1348
+ }
1349
+ });
1350
+ };
1351
+
1352
+ window.generateTestsForFinding = async (targetFile, findingId, btnEl) => {
1353
+ if (!state.selectedRepoId) return;
1354
+ const slot = document.getElementById(`testgen-${findingId}`);
1355
+ if (slot && slot.childElementCount > 0) {
1356
+ slot.replaceChildren();
1357
+ return;
1358
+ }
1359
+ await withButtonLoading(btnEl, async () => {
1360
+ const res = await api('/api/testing/generate', {
1361
+ method: 'POST',
1362
+ body: JSON.stringify({ repoId: state.selectedRepoId, targetFile, findingId, writeToDisk: false })
1363
+ });
1364
+ if (res.error) return showToast('err', res.error);
1365
+ if (slot) {
1366
+ slot.replaceChildren();
1367
+ const box = document.createElement('div');
1368
+ box.className = 'card form-stack';
1369
+ box.style.marginTop = '8px';
1370
+ const hdr = document.createElement('div');
1371
+ hdr.className = 'card-header';
1372
+ const title = document.createElement('strong');
1373
+ title.textContent = `${res.framework} -> ${res.suggestedTestPath}`;
1374
+ const writeBtn = document.createElement('button');
1375
+ writeBtn.type = 'button';
1376
+ writeBtn.className = 'btn btn-sm btn-primary';
1377
+ writeBtn.textContent = 'Write Test File';
1378
+ writeBtn.addEventListener('click', async () => {
1379
+ const wRes = await api('/api/testing/generate', {
1380
+ method: 'POST',
1381
+ body: JSON.stringify({ repoId: state.selectedRepoId, targetFile, findingId, writeToDisk: true })
1382
+ });
1383
+ showToast(wRes.writtenPath ? 'ok' : 'err', wRes.writtenPath ? `Saved test: ${wRes.writtenPath}` : 'Write failed');
1384
+ });
1385
+ hdr.appendChild(title);
1386
+ hdr.appendChild(writeBtn);
1387
+ const pre = document.createElement('pre');
1388
+ pre.className = 'code-block';
1389
+ pre.textContent = res.testCode || '';
1390
+ box.appendChild(hdr);
1391
+ box.appendChild(pre);
1392
+ slot.appendChild(box);
1393
+ }
1394
+ });
1395
+ };
1396
+
1397
+ window.exportContextPack = async (format = 'markdown', btnEl) => {
1398
+ if (!state.selectedRepoId) return openOnboardingWizard(2);
1399
+ await withButtonLoading(btnEl, async () => {
1400
+ const res = await api(`/api/context-pack/${state.selectedRepoId}?format=${encodeURIComponent(format)}`);
1401
+ if (res.error) return showToast('err', res.error);
1402
+ await navigator.clipboard.writeText(res.pack.content);
1403
+ showToast('ok', `Copied ${format.toUpperCase()} Smart Context Pack (${res.pack.fileCount} files, ~${res.pack.estimatedTokens} tokens).`);
1404
+ });
1405
+ };
1406
+
1407
+ window.autofixFinding = async (findingId, btnEl) => {
1408
+ await withButtonLoading(btnEl, async () => {
1409
+ const optIn = document.getElementById('toggleAutofix').checked;
1410
+ const res = await api(`/api/findings/${findingId}/autofix`, { method: 'POST', body: JSON.stringify({ optIn }) });
1411
+ showToast(res.attempt ? 'ok' : 'err', res.attempt ? `Worktree patch ready on ${res.attempt.branchName} (${res.attempt.status}). Run Revalidate to verify.` : (res.error || 'Auto-Fix failed'));
1412
+ });
1413
+ };
1414
+
1415
+ window.revalidateAction = async (findingIds, btnEl) => {
1416
+ if (!state.selectedRepoId) return;
1417
+ await withButtonLoading(btnEl, async () => {
1418
+ const res = await api('/api/revalidate', {
1419
+ method: 'POST',
1420
+ body: JSON.stringify({ repoId: state.selectedRepoId, baseScanId: state.selectedJobId, findingIds })
1421
+ });
1422
+ delete state.fullJobCache[state.selectedJobId];
1423
+ showToast('ok', `Revalidated: ${res.verifiedFixedIds?.length || 0} fixed, ${res.stillOpenIds?.length || 0} still open.`);
1424
+ await refreshJobs();
1425
+ });
1426
+ };
1427
+
1428
+ // --- Docs & Local Bundled Mermaid Diagrams ---
1429
+ async function renderMarkdownWithMermaid(markdown) {
1430
+ const outEl = document.getElementById('docsOutput');
1431
+ const parts = String(markdown || '').split(/```mermaid\s*\r?\n([\s\S]*?)```/g);
1432
+ outEl.innerHTML = '';
1433
+ for (let i = 0; i < parts.length; i++) {
1434
+ const chunk = parts[i];
1435
+ if (!chunk.trim()) continue;
1436
+ if (i % 2 === 0) {
1437
+ const pre = document.createElement('pre');
1438
+ pre.className = 'code-block';
1439
+ pre.textContent = chunk.trim();
1440
+ outEl.appendChild(pre);
1441
+ } else {
1442
+ const box = document.createElement('div');
1443
+ box.className = 'mermaid-box';
1444
+ if (globalThis.mermaid?.render) {
1445
+ try {
1446
+ globalThis.mermaid.initialize({ startOnLoad: false, theme: state.theme === 'light' ? 'default' : 'dark' });
1447
+ const { svg } = await globalThis.mermaid.render(`mmd-${Date.now()}-${i}`, chunk.trim());
1448
+ box.innerHTML = svg;
1449
+ } catch {
1450
+ box.innerHTML = `<pre class="code-block">${escapeHtml(chunk)}</pre>`;
1451
+ }
1452
+ } else {
1453
+ box.innerHTML = `<pre class="code-block">${escapeHtml(chunk)}</pre>`;
1454
+ }
1455
+ outEl.appendChild(box);
1456
+ }
1457
+ }
1458
+ }
1459
+
1460
+ window.selectDocSection = (sec) => {
1461
+ state.activeDocSection = sec;
1462
+ if (state.docsCache?.[sec]) {
1463
+ renderMarkdownWithMermaid(state.docsCache[sec]);
1464
+ }
1465
+ };
1466
+
1467
+ window.generateDocsAction = async (btnEl) => {
1468
+ if (!state.selectedRepoId) return openOnboardingWizard(2);
1469
+ switchTab('docs');
1470
+ await withButtonLoading(btnEl, async () => {
1471
+ const docs = await api('/api/docs/generate', { method: 'POST', body: JSON.stringify({ repoId: state.selectedRepoId }) });
1472
+ state.docsCache = docs;
1473
+ await renderMarkdownWithMermaid(docs[state.activeDocSection] || docs.architectureMd || '');
1474
+ showToast('ok', `Generated ${docs.writtenFiles?.length || 4} project doc files.`);
1475
+ });
1476
+ };
1477
+
1478
+ // --- Interactive SVG Blast-Radius Graph ---
1479
+ window.zoomGraph = (factor) => {
1480
+ state.graphZoom = Math.max(0.4, Math.min(2.6, state.graphZoom * factor));
1481
+ renderGraphSvg();
1482
+ };
1483
+ window.resetGraphZoom = () => {
1484
+ state.graphZoom = 1;
1485
+ state.graphPanX = 0;
1486
+ state.graphPanY = 0;
1487
+ renderGraphSvg();
1488
+ };
1489
+
1490
+ window.loadGraph = async (btnEl) => {
1491
+ if (!state.selectedRepoId) return;
1492
+ const run = async () => {
1493
+ const g = await api(`/api/graph/${state.selectedRepoId}`);
1494
+ state.graphData = { nodes: g.nodes || [], edges: g.edges || [], slices: g.slices || [] };
1495
+ document.getElementById('graphStats').textContent = `${state.graphData.nodes.length} nodes · ${state.graphData.edges.length} edges · ${state.graphData.slices.length} slices`;
1496
+ renderGraphSvg();
1497
+ };
1498
+ if (btnEl) await withButtonLoading(btnEl, run);
1499
+ else await run();
1500
+ };
1501
+
1502
+ window.renderGraphSvg = () => {
1503
+ const wrap = document.getElementById('graphContainer');
1504
+ const filter = (document.getElementById('graphSearchInput')?.value || '').toLowerCase();
1505
+ const filesMap = new Map();
1506
+ for (const n of state.graphData.nodes) {
1507
+ if (filter && !n.file.toLowerCase().includes(filter) && !n.name.toLowerCase().includes(filter)) continue;
1508
+ if (!filesMap.has(n.file)) filesMap.set(n.file, []);
1509
+ filesMap.get(n.file).push(n);
1510
+ }
1511
+ const fileNodes = Array.from(filesMap.entries()).slice(0, 28).map(([file, syms], idx) => ({
1512
+ id: file,
1513
+ label: file.split('/').pop() || file,
1514
+ fullFile: file,
1515
+ syms,
1516
+ x: 40 + (idx % 4) * 210,
1517
+ y: 36 + Math.floor(idx / 4) * 86
1518
+ }));
1519
+
1520
+ if (fileNodes.length === 0) {
1521
+ wrap.innerHTML = '<div class="muted" style="padding:20px">Run a scan to populate the interactive AST graph.</div>';
1522
+ return;
1523
+ }
1524
+
1525
+ const posMap = new Map(fileNodes.map((n) => [n.id, n]));
1526
+ const edgeSvg = [];
1527
+ for (const e of state.graphData.edges.slice(0, 120)) {
1528
+ const src = posMap.get(e.file);
1529
+ const dst = fileNodes.find((fn) => fn.syms.some((s) => s.name === e.targetName));
1530
+ if (src && dst && src.id !== dst.id) {
1531
+ edgeSvg.push(`<line x1="${src.x + 85}" y1="${src.y + 22}" x2="${dst.x + 85}" y2="${dst.y + 22}" stroke="var(--border-strong)" stroke-width="1.4" />`);
1532
+ }
1533
+ }
1534
+
1535
+ const cachedJob = state.fullJobCache[state.selectedJobId] || state.jobs.find((j) => j.id === state.selectedJobId);
1536
+ const jobFindings = cachedJob?.resultJson?.findings || [];
1537
+ const nodeSvg = fileNodes.map((n, i) => {
1538
+ const fCount = jobFindings.filter((f) => f.file === n.fullFile).length;
1539
+ const stroke = fCount > 0 ? 'var(--red)' : 'var(--accent)';
1540
+ const fill = fCount > 0 ? 'rgba(248, 81, 73, 0.12)' : 'var(--surface)';
1541
+ return `
1542
+ <g class="graph-node" transform="translate(${n.x}, ${n.y})" onclick="inspectGraphNode(${i})">
1543
+ <rect width="175" height="44" fill="${fill}" stroke="${stroke}" />
1544
+ <text x="10" y="18">${escapeHtml(n.label.slice(0, 22))}</text>
1545
+ <text x="10" y="34" fill="var(--muted)" font-size="10">${n.syms.length} syms${fCount ? ` · ${fCount} findings` : ''}</text>
1546
+ </g>`;
1547
+ }).join('');
1548
+
1549
+ window.__renderedGraphNodes = fileNodes;
1550
+ wrap.innerHTML = `
1551
+ <svg id="blastSvg" viewBox="${-state.graphPanX} ${-state.graphPanY} ${Math.round(900 / state.graphZoom)} ${Math.round(640 / state.graphZoom)}">
1552
+ ${edgeSvg.join('')}
1553
+ ${nodeSvg}
1554
+ </svg>`;
1555
+ };
1556
+
1557
+ window.inspectGraphNode = (idx) => {
1558
+ const n = (window.__renderedGraphNodes || [])[idx];
1559
+ if (!n) return;
1560
+ const callers = state.graphData.edges.filter((e) => n.syms.some((s) => s.name === e.targetName)).slice(0, 10);
1561
+ document.getElementById('graphInspectorBody').innerHTML = `
1562
+ <div class="mono" style="margin-bottom:8px;color:var(--accent)">${escapeHtml(n.fullFile)}</div>
1563
+ <div class="muted"><strong>Symbols (${n.syms.length}):</strong></div>
1564
+ <ul style="padding-left:16px;font-size:11px;margin:4px 0 8px">
1565
+ ${n.syms.slice(0, 12).map((s) => `<li><code>${escapeHtml(s.kind)} ${escapeHtml(s.name)}:${s.lineStart}</code></li>`).join('')}
1566
+ </ul>
1567
+ <div class="muted"><strong>Incoming Edges (${callers.length}):</strong></div>
1568
+ <ul style="padding-left:16px;font-size:11px;margin:4px 0">
1569
+ ${callers.map((c) => `<li><code>${escapeHtml(c.file)}:${c.line}</code></li>`).join('') || '<li>None indexed</li>'}
1570
+ </ul>`;
1571
+ };
1572
+
1573
+ // --- Project Pulse Health Timeline & Semantic Slices ---
1574
+ window.loadPulseAndSlices = async (btnEl) => {
1575
+ if (!state.selectedRepoId) return;
1576
+ const run = async () => {
1577
+ const [pulse, graph] = await Promise.all([
1578
+ api(`/api/pulse/${state.selectedRepoId}`).catch(() => ({ currentScore: 100, history: [] })),
1579
+ api(`/api/graph/${state.selectedRepoId}`).catch(() => ({ slices: [] }))
1580
+ ]);
1581
+
1582
+ const score = pulse.currentScore ?? 100;
1583
+ const topPill = document.getElementById('pulseScorePill');
1584
+ if (topPill) {
1585
+ topPill.innerHTML = `<span class="status-dot ${score >= 85 ? 'ok' : 'warn'}"></span><span>Pulse: ${score}/100</span>`;
1586
+ }
1587
+
1588
+ document.getElementById('pulseBigNumber').textContent = `${score}`;
1589
+ document.getElementById('pulseBigNumber').style.color = score >= 85 ? 'var(--green)' : score >= 60 ? 'var(--amber)' : 'var(--red)';
1590
+
1591
+ const hist = pulse.history || [];
1592
+ const latest = hist[hist.length - 1];
1593
+ document.getElementById('pulseBreakdown').textContent = latest
1594
+ ? `${latest.criticalCount} Critical · ${latest.highCount} High · ${latest.mediumCount} Medium`
1595
+ : 'No historical scans yet';
1596
+
1597
+ const pts = hist.length > 0 ? hist : [{ pulseScore: score }];
1598
+ const w = 420;
1599
+ const h = 72;
1600
+ const coords = pts.map((p, i) => {
1601
+ const x = pts.length === 1 ? w / 2 : Math.round((i / (pts.length - 1)) * (w - 20)) + 10;
1602
+ const y = Math.round(h - 10 - ((p.pulseScore || 0) / 100) * (h - 20));
1603
+ return `${x},${y}`;
1604
+ });
1605
+ document.getElementById('pulseSparklineWrap').innerHTML = `
1606
+ <svg width="100%" height="${h}" viewBox="0 0 ${w} ${h}" style="background:var(--surface-3);border:1px solid var(--border);border-radius:6px">
1607
+ <polyline fill="none" stroke="var(--accent)" stroke-width="2" points="${coords.join(' ')}" />
1608
+ ${coords.map((c) => {
1609
+ const [cx, cy] = c.split(',');
1610
+ return `<circle cx="${cx}" cy="${cy}" r="3.5" fill="var(--green)" />`;
1611
+ }).join('')}
1612
+ </svg>`;
1613
+
1614
+ const slices = graph.slices || [];
1615
+ document.getElementById('slicesContainer').innerHTML = slices.length === 0
1616
+ ? '<div class="muted">Run Scan Main Branch to partition semantic feature slices.</div>'
1617
+ : slices.map((s) => `
1618
+ <div class="card clickable" onclick="switchTab('findings')">
1619
+ <div class="finding-top">
1620
+ <strong>${escapeHtml(s.name)}</strong>
1621
+ <span class="pill ${s.riskScore >= 60 ? 'pill-danger' : 'pill-muted'}">${s.riskScore}/100</span>
1622
+ </div>
1623
+ <div class="muted mono" style="margin-top:4px">${escapeHtml(s.domain)} · ${s.files?.length || 0} files · ${escapeHtml(s.status)}</div>
1624
+ </div>`).join('');
1625
+ };
1626
+ if (btnEl) await withButtonLoading(btnEl, run);
1627
+ else await run();
1628
+ };
1629
+
1630
+ // --- Rules, Output Routing & Team Feedback Memory ---
1631
+ window.loadMemoryRules = async (btnEl) => {
1632
+ const el = document.getElementById('memoryRulesList');
1633
+ if (!state.selectedRepoId) {
1634
+ el.innerHTML = '<div class="muted">Select a repository with a local path to inspect memory rules.</div>';
1635
+ return;
1636
+ }
1637
+ const run = async () => {
1638
+ const res = await api(`/api/memory/${state.selectedRepoId}`).catch(() => ({}));
1639
+ const rules = res.memory?.rules || [];
1640
+ el.innerHTML = rules.length === 0
1641
+ ? '<div class="muted">No ignored false-positive patterns stored yet in .codepulse/memory.json.</div>'
1642
+ : rules.map((r) => `
1643
+ <div class="list-item">
1644
+ <div class="finding-top">
1645
+ <code class="mono">${escapeHtml(r.ruleId || r.titlePattern || r.fingerprint)}</code>
1646
+ <button type="button" class="btn btn-sm btn-danger" onclick="deleteMemoryRule('${r.id}', this)">Remove</button>
1647
+ </div>
1648
+ <div class="muted">${escapeHtml(r.filePattern || '*')} — ${escapeHtml(r.reason || 'Suppressed')}</div>
1649
+ </div>`).join('');
1650
+ };
1651
+ if (btnEl) await withButtonLoading(btnEl, run);
1652
+ else await run();
1653
+ };
1654
+
1655
+ window.deleteMemoryRule = async (ruleId, btnEl) => {
1656
+ if (!state.selectedRepoId) return;
1657
+ await withButtonLoading(btnEl, async () => {
1658
+ await api(`/api/memory/${state.selectedRepoId}/${ruleId}`, { method: 'DELETE' });
1659
+ showToast('info', 'Removed memory suppression rule.');
1660
+ await loadMemoryRules();
1661
+ });
1662
+ };
1663
+
1664
+ window.loadOutputRule = async () => {
1665
+ const id = state.selectedRepoId || 'default';
1666
+ const { rule } = await api(`/api/output-rules/${id}`);
1667
+ if (rule) {
1668
+ document.getElementById('ruleExportDir').value = rule.exportDir;
1669
+ document.getElementById('ruleTemplate').value = rule.filenameTemplate;
1670
+ document.getElementById('ruleAutoSave').checked = rule.autoSave;
1671
+ document.getElementById('rulePostGh').checked = rule.postGithubComments;
1672
+ document.getElementById('ruleCommentPolicy').value = rule.commentPolicy;
1673
+ }
1674
+ };
1675
+
1676
+ document.getElementById('outputRuleForm').onsubmit = async (e) => {
1677
+ e.preventDefault();
1678
+ const id = state.selectedRepoId || 'default';
1679
+ await api(`/api/output-rules/${id}`, {
1680
+ method: 'PUT',
1681
+ body: JSON.stringify({
1682
+ exportDir: document.getElementById('ruleExportDir').value,
1683
+ filenameTemplate: document.getElementById('ruleTemplate').value,
1684
+ autoSave: document.getElementById('ruleAutoSave').checked,
1685
+ postGithubComments: document.getElementById('rulePostGh').checked,
1686
+ commentPolicy: document.getElementById('ruleCommentPolicy').value
1687
+ })
1688
+ });
1689
+ showToast('ok', 'Output routing rule saved.');
1690
+ };
1691
+
1692
+ window.loadSettings = async () => {
1693
+ const s = await api('/api/settings');
1694
+ if (s.language && !localStorage.getItem('codepulse_lang')) {
1695
+ await setLanguage(s.language, false);
1696
+ }
1697
+ if (s.theme && !localStorage.getItem('codepulse_theme')) {
1698
+ applyTheme(s.theme);
1699
+ }
1700
+ const setVal = (id, v) => { const el = document.getElementById(id); if (el) el.value = v; };
1701
+ const setChk = (id, v) => { const el = document.getElementById(id); if (el) el.checked = Boolean(v); };
1702
+
1703
+ setVal('dialProvider', s.provider || 'gemini');
1704
+ populateModelDropdown('dialProvider', 'dialModel', 'dialCustomModel', s.model);
1705
+ setVal('dialBaseUrl', s.baseUrl || '');
1706
+ setVal('dialBudgetWarn', s.tokenBudgetWarnUsd ?? 2);
1707
+
1708
+ setVal('wizProvider', s.provider || 'gemini');
1709
+ populateModelDropdown('wizProvider', 'wizModel', 'wizCustomModel', s.model);
1710
+
1711
+ setVal('settingsThemeSelect', s.theme || state.theme);
1712
+ setVal('settingsLangSelect', s.language || state.lang);
1713
+ setVal('settingsCloseAction', s.closeAction || 'tray');
1714
+ setChk('settingsOpenAtLogin', s.openAtLogin);
1715
+ setVal('settingsConcurrency', s.concurrency ?? 4);
1716
+ setChk('settingsCheckUpdatesStartup', s.checkUpdatesOnStartup !== false);
1717
+ setChk('settingsAutoDownload', s.autoDownloadUpdates);
1718
+ setVal('settingsPollSeconds', s.pollSeconds ?? 60);
1719
+ setChk('settingsAutoScanPrs', Boolean(s.autoScanOpenPrsOnPoll));
1720
+ setChk('settingsIncludeSeoGeo', s.includeSeoGeo !== false);
1721
+ setChk('settingsEnableOsv', s.enableOsv !== false);
1722
+ setChk('settingsEnableRadar', s.enableRadar !== false);
1723
+ setChk('settingsAutofixDefault', s.autofixDefault);
1724
+ setChk('settingsTelemetryOptIn', s.telemetryOptIn);
1725
+ setChk('toggleAutofix', s.autofixDefault);
1726
+ setVal('settingsGitlabUrl', s.gitlabBaseUrl || 'https://gitlab.com');
1727
+
1728
+ const activePacks = new Set(s.compliancePacks || []);
1729
+ document.querySelectorAll('.compliance-pack-chk').forEach((chk) => {
1730
+ chk.checked = activePacks.has(chk.value);
1731
+ });
1732
+ state.starPromptDismissed = Boolean(s.starPromptDismissed || localStorage.getItem('codepulse_star_dismissed'));
1733
+ state.consentCompleted = Boolean(s.consentCompleted);
1734
+
1735
+ document.getElementById('vaultStatus').textContent =
1736
+ `AI Key: ${s.hasApiKey ? s.maskedKey : 'Not set'} · GitHub: ${s.hasGithubToken ? s.maskedGithubToken : 'Not set'} · Poller: ${s.pollerActive ? 'Active' : 'Idle'}`;
1737
+ };
1738
+
1739
+ window.saveMultiHostTokens = async (btnEl) => {
1740
+ await withButtonLoading(btnEl, async () => {
1741
+ const gitlabBaseUrl = document.getElementById('settingsGitlabUrl')?.value.trim() || 'https://gitlab.com';
1742
+ const gitlabToken = document.getElementById('settingsGitlabToken')?.value.trim() || undefined;
1743
+ const bitbucketUsername = document.getElementById('settingsBitbucketUser')?.value.trim() || undefined;
1744
+ const bitbucketToken = document.getElementById('settingsBitbucketToken')?.value.trim() || undefined;
1745
+ const res = await api('/api/settings/secrets', {
1746
+ method: 'POST',
1747
+ body: JSON.stringify({ gitlabBaseUrl, gitlabToken, bitbucketUsername, bitbucketToken })
1748
+ });
1749
+ if (res.error) return showToast('err', res.error);
1750
+ if (document.getElementById('settingsGitlabToken')) document.getElementById('settingsGitlabToken').value = '';
1751
+ if (document.getElementById('settingsBitbucketToken')) document.getElementById('settingsBitbucketToken').value = '';
1752
+ showToast('ok', 'GitLab / Bitbucket credentials stored locally in .env Vault.');
1753
+ });
1754
+ };
1755
+
1756
+ window.loadRepoGroups = async () => {
1757
+ const listEl = document.getElementById('repoGroupsList');
1758
+ if (!listEl) return;
1759
+ const res = await api('/api/repos/groups').catch(() => ({ groups: [] }));
1760
+ const groups = res.groups || [];
1761
+ if (groups.length === 0) {
1762
+ listEl.textContent = 'No linked multi-repo groups yet.';
1763
+ return;
1764
+ }
1765
+ listEl.replaceChildren();
1766
+ for (const g of groups) {
1767
+ const row = document.createElement('div');
1768
+ row.className = 'card row-gap';
1769
+ row.style.justifyContent = 'space-between';
1770
+ row.style.marginBottom = '6px';
1771
+ const info = document.createElement('div');
1772
+ const title = document.createElement('strong');
1773
+ title.textContent = g.name;
1774
+ const meta = document.createElement('span');
1775
+ meta.className = 'muted mono';
1776
+ meta.textContent = ` (${g.repoIds.length} repos)`;
1777
+ info.appendChild(title);
1778
+ info.appendChild(meta);
1779
+ const radarBtn = document.createElement('button');
1780
+ radarBtn.type = 'button';
1781
+ radarBtn.className = 'btn btn-sm btn-secondary';
1782
+ radarBtn.textContent = 'Run Group Drift Radar';
1783
+ radarBtn.addEventListener('click', async () => {
1784
+ const rRes = await api(`/api/repos/groups/${g.id}/radar`, { method: 'POST', body: '{}' });
1785
+ showToast('info', `Group "${g.name}": ${rRes.findings?.length || 0} cross-repo drift finding(s).`);
1786
+ });
1787
+ row.appendChild(info);
1788
+ row.appendChild(radarBtn);
1789
+ listEl.appendChild(row);
1790
+ }
1791
+ };
1792
+
1793
+ window.createRepoGroupPrompt = async (btnEl) => {
1794
+ if ((state.repos || []).length < 2) {
1795
+ return showToast('info', 'Connect at least 2 repositories first to link them in a workspace group.');
1796
+ }
1797
+ const name = prompt('Enter Multi-Repo Group Name (e.g. fullstack-app):', 'fullstack-stack');
1798
+ if (!name?.trim()) return;
1799
+ await withButtonLoading(btnEl, async () => {
1800
+ const repoIds = state.repos.map((r) => r.id);
1801
+ await api('/api/repos/groups', {
1802
+ method: 'POST',
1803
+ body: JSON.stringify({ name: name.trim(), repoIds })
1804
+ });
1805
+ await loadRepoGroups();
1806
+ showToast('ok', `Linked ${repoIds.length} repositories under "${name.trim()}".`);
1807
+ });
1808
+ };
1809
+
1810
+ window.dismissStarPrompt = async (showNotice = false) => {
1811
+ state.starPromptDismissed = true;
1812
+ localStorage.setItem('codepulse_star_dismissed', '1');
1813
+ document.getElementById('starToastBanner')?.remove();
1814
+ await api('/api/settings', { method: 'PUT', body: JSON.stringify({ starPromptDismissed: true }) }).catch(() => undefined);
1815
+ if (showNotice) showToast('info', 'Thanks for using CodePulse!', 2000);
1816
+ };
1817
+
1818
+ function maybeShowFirstScanStarPrompt() {
1819
+ if (state.starPromptDismissed || !state.consentCompleted) return;
1820
+ if (document.getElementById('starToastBanner')) return;
1821
+ const stack = document.getElementById('toastStack');
1822
+ if (!stack) return;
1823
+ const el = document.createElement('div');
1824
+ el.id = 'starToastBanner';
1825
+ el.className = 'toast toast-info';
1826
+ const body = document.createElement('div');
1827
+ body.className = 'form-stack';
1828
+ const strong = document.createElement('strong');
1829
+ strong.textContent = 'First scan complete!';
1830
+ const desc = document.createElement('span');
1831
+ desc.textContent = 'Find CodePulse useful? A quick GitHub star supports open-source development.';
1832
+ const row = document.createElement('div');
1833
+ row.className = 'row-gap';
1834
+ const starLink = document.createElement('a');
1835
+ starLink.className = 'btn btn-sm btn-primary';
1836
+ starLink.href = 'https://github.com/ymorningstar/CodePulse';
1837
+ starLink.target = '_blank';
1838
+ starLink.rel = 'noreferrer';
1839
+ starLink.textContent = 'Star on GitHub ⭐';
1840
+ starLink.addEventListener('click', (ev) => {
1841
+ window.openExternalDoc(ev, starLink.href);
1842
+ void window.dismissStarPrompt(false);
1843
+ });
1844
+ const laterBtn = document.createElement('button');
1845
+ laterBtn.type = 'button';
1846
+ laterBtn.className = 'btn btn-sm btn-ghost';
1847
+ laterBtn.textContent = 'Maybe Later';
1848
+ laterBtn.addEventListener('click', () => window.dismissStarPrompt(false));
1849
+ row.appendChild(starLink);
1850
+ row.appendChild(laterBtn);
1851
+ body.appendChild(strong);
1852
+ body.appendChild(desc);
1853
+ body.appendChild(row);
1854
+ el.appendChild(body);
1855
+ stack.appendChild(el);
1856
+ }
1857
+
1858
+ function renderPendingPrBanner(pendingPrs) {
1859
+ const banner = document.getElementById('pendingPrBanner');
1860
+ const txt = document.getElementById('pendingPrText');
1861
+ const actions = document.getElementById('pendingPrActions');
1862
+ if (!banner || !txt || !actions) return;
1863
+
1864
+ const list = Array.isArray(pendingPrs) ? pendingPrs : [];
1865
+ if (list.length === 0) {
1866
+ banner.classList.add('hidden');
1867
+ return;
1868
+ }
1869
+
1870
+ banner.classList.remove('hidden');
1871
+ const first = list[0];
1872
+ const repoSlug = `${String(first.owner || '')}/${String(first.repo || '')}`;
1873
+
1874
+ txt.replaceChildren();
1875
+ const strongEl = document.createElement('strong');
1876
+ strongEl.textContent = `${list.length} open PR update(s) detected`;
1877
+ txt.appendChild(strongEl);
1878
+ txt.appendChild(document.createTextNode(' on '));
1879
+ const codeEl = document.createElement('code');
1880
+ codeEl.textContent = repoSlug;
1881
+ txt.appendChild(codeEl);
1882
+ if (first.prNumber) {
1883
+ const prNum = Number.parseInt(String(first.prNumber), 10);
1884
+ const titlePreview = first.title ? `: ${String(first.title).slice(0, 60)}` : '';
1885
+ txt.appendChild(document.createTextNode(` (e.g. PR #${Number.isFinite(prNum) ? prNum : ''}${titlePreview})`));
1886
+ }
1887
+
1888
+ actions.replaceChildren();
1889
+ const reviewBtn = document.createElement('button');
1890
+ reviewBtn.type = 'button';
1891
+ reviewBtn.className = 'btn btn-sm btn-primary';
1892
+ reviewBtn.textContent = 'Review Now';
1893
+ reviewBtn.addEventListener('click', () => window.reviewPendingPr(reviewBtn));
1894
+
1895
+ const dismissBtn = document.createElement('button');
1896
+ dismissBtn.type = 'button';
1897
+ dismissBtn.className = 'btn btn-sm btn-ghost';
1898
+ dismissBtn.textContent = 'Dismiss';
1899
+ dismissBtn.addEventListener('click', () => window.dismissPendingPrs(dismissBtn));
1900
+
1901
+ actions.appendChild(reviewBtn);
1902
+ actions.appendChild(dismissBtn);
1903
+ }
1904
+
1905
+ async function refreshPendingPrs() {
1906
+ const res = await api('/api/github/pending-prs').catch(() => ({ pendingPrs: [] }));
1907
+ renderPendingPrBanner(res.pendingPrs || []);
1908
+ }
1909
+
1910
+ window.reviewPendingPr = async (btnEl) => {
1911
+ await withButtonLoading(btnEl, async () => {
1912
+ const res = await api('/api/github/pending-prs/review', {
1913
+ method: 'POST',
1914
+ body: JSON.stringify({ all: true })
1915
+ });
1916
+ renderPendingPrBanner(res.pendingPrs || []);
1917
+ showToast('ok', `Queued ${res.enqueued || 0} PR review(s).`);
1918
+ await refreshJobs();
1919
+ });
1920
+ };
1921
+
1922
+ window.dismissPendingPrs = async (btnEl) => {
1923
+ await withButtonLoading(btnEl, async () => {
1924
+ await api('/api/github/pending-prs/dismiss', { method: 'POST', body: JSON.stringify({ all: true }) });
1925
+ renderPendingPrBanner([]);
1926
+ });
1927
+ };
1928
+
1929
+ window.pollGithubNow = async (btnEl) => {
1930
+ await withButtonLoading(btnEl, async () => {
1931
+ const res = await api('/api/github/poll-now', { method: 'POST', body: '{}' });
1932
+ if (res.error) return showToast('err', res.error);
1933
+ renderPendingPrBanner(res.pendingPrs || []);
1934
+ const pendingCount = (res.pendingPrs || []).length;
1935
+ if (pendingCount > 0 && (res.triggersCount || 0) >= pendingCount) {
1936
+ showToast('info', `${pendingCount} open PR update(s) detected across ${res.polledRepos} repo(s) — click Review Now to start.`);
1937
+ } else {
1938
+ showToast('ok', `Synced ${res.polledRepos} GitHub repo(s): ${res.triggersCount || 0} trigger(s).`);
1939
+ }
1940
+ await refreshJobs();
1941
+ });
1942
+ };
1943
+
1944
+ // --- Universal Agent Bridge & Streamable HTTP /mcp ---
1945
+ function getMcpConfigs() {
1946
+ const origin = window.location.origin;
1947
+ return {
1948
+ stdio: JSON.stringify({
1949
+ mcpServers: {
1950
+ codepulse: {
1951
+ command: 'npx',
1952
+ args: ['-y', 'codepulse', 'mcp', '--stdio']
1953
+ }
1954
+ }
1955
+ }, null, 2),
1956
+ http: JSON.stringify({
1957
+ mcpServers: {
1958
+ codepulse: {
1959
+ url: `${origin}/mcp`,
1960
+ headers: state.authToken ? { Authorization: `Bearer ${state.authToken}` } : undefined
1961
+ }
1962
+ }
1963
+ }, null, 2)
1964
+ };
1965
+ }
1966
+
1967
+ function renderMcpConfigBox() {
1968
+ const el = document.getElementById('mcpConfigSnippet');
1969
+ if (!el) return;
1970
+ el.textContent = getMcpConfigs().http;
1971
+ }
1972
+
1973
+ window.copyMcpConfig = async (kind) => {
1974
+ const cfg = getMcpConfigs()[kind];
1975
+ await navigator.clipboard.writeText(cfg);
1976
+ renderMcpConfigBox();
1977
+ showToast('ok', `Copied ${kind.toUpperCase()} MCP config to clipboard.`);
1978
+ };
1979
+
1980
+ window.testMcpHealth = async (btnEl) => {
1981
+ await withButtonLoading(btnEl, async () => {
1982
+ const res = await api('/api/mcp/health', { method: 'POST', body: '{}' });
1983
+ const el = document.getElementById('mcpHealthStatus');
1984
+ const txt = res.ok ? `Healthy · ${res.transport} (${res.endpoint}) · ${res.toolsCount} tools` : 'MCP Unavailable';
1985
+ if (el) el.textContent = txt;
1986
+ showToast(res.ok ? 'ok' : 'err', txt);
1987
+ });
1988
+ };
1989
+
1990
+ window.loadBridgePlatforms = async (btnEl) => {
1991
+ const run = async () => {
1992
+ renderMcpConfigBox();
1993
+ const { platforms } = await api('/api/bridge/detect');
1994
+ document.getElementById('bridgeList').innerHTML = (platforms || []).map((p) => `
1995
+ <div class="card">
1996
+ <div class="finding-top">
1997
+ <strong>${escapeHtml(p.displayName)}</strong>
1998
+ <span class="pill ${p.configured ? 'pill-ok' : p.detected ? 'pill-accent' : 'pill-muted'}">${p.configured ? 'Connected' : p.detected ? 'Detected' : 'Not Found'}</span>
1999
+ </div>
2000
+ <div class="muted mono" style="margin-top:6px;word-break:break-all">${escapeHtml(p.configPath)}</div>
2001
+ </div>`).join('');
2002
+ };
2003
+ if (btnEl) await withButtonLoading(btnEl, run);
2004
+ else await run();
2005
+ };
2006
+
2007
+ window.installAllDetectedAgents = async (btnEl) => {
2008
+ await withButtonLoading(btnEl, async () => {
2009
+ const res = await api('/api/bridge/install', { method: 'POST', body: JSON.stringify({}) });
2010
+ const cnt = res.results.filter((r) => r.action === 'installed').length;
2011
+ showToast('ok', `Configured ${cnt} coding agent(s).`);
2012
+ await loadBridgePlatforms();
2013
+ });
2014
+ };
2015
+
2016
+ document.getElementById('chatForm').onsubmit = async (e) => {
2017
+ e.preventDefault();
2018
+ const input = document.getElementById('chatInput');
2019
+ const msg = input.value.trim();
2020
+ if (!msg) return;
2021
+ input.value = '';
2022
+ const hist = document.getElementById('chatHistory');
2023
+ const userEl = document.createElement('div');
2024
+ userEl.className = 'chat-msg user';
2025
+ userEl.textContent = msg;
2026
+ hist.appendChild(userEl);
2027
+ const res = await api('/api/chat', { method: 'POST', body: JSON.stringify({ message: msg, repoId: state.selectedRepoId }) });
2028
+ const botEl = document.createElement('div');
2029
+ botEl.className = 'chat-msg bot';
2030
+ botEl.textContent = String(res.reply || '');
2031
+ hist.appendChild(botEl);
2032
+ hist.scrollTop = hist.scrollHeight;
2033
+ await refreshJobs();
2034
+ };
2035
+
2036
+ function connectWs() {
2037
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
2038
+ const tokenParam = state.authToken ? `?token=${encodeURIComponent(state.authToken)}` : '';
2039
+ const ws = new WebSocket(`${proto}//${location.host}/ws${tokenParam}`);
2040
+ ws.onmessage = (ev) => {
2041
+ try {
2042
+ const parsed = JSON.parse(ev.data);
2043
+ if (parsed.type === 'pr_updates_detected') {
2044
+ renderPendingPrBanner(parsed.pendingPrs || []);
2045
+ return;
2046
+ }
2047
+ if (parsed.type === 'job_completed' || parsed.type === 'job_failed') {
2048
+ delete state.fullJobCache[parsed.jobId];
2049
+ if (parsed.type === 'job_completed') {
2050
+ setTimeout(() => maybeShowFirstScanStarPrompt(), 900);
2051
+ }
2052
+ }
2053
+ } catch {
2054
+ // ignore non-json
2055
+ }
2056
+ if (state.wsRefreshTimer) clearTimeout(state.wsRefreshTimer);
2057
+ state.wsRefreshTimer = setTimeout(() => {
2058
+ refreshJobs();
2059
+ refreshHealth();
2060
+ }, 300);
2061
+ };
2062
+ ws.onclose = () => setTimeout(connectWs, 3000);
2063
+ }
2064
+
2065
+ function escapeHtml(s) {
2066
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
2067
+ }
2068
+
2069
+ async function refreshAll() {
2070
+ await loadModelCatalog();
2071
+ const [, , , , , , upd] = await Promise.all([
2072
+ refreshHealth(),
2073
+ refreshRepos(),
2074
+ refreshJobs(),
2075
+ loadBridgePlatforms(),
2076
+ loadOutputRule(),
2077
+ loadSettings(),
2078
+ api('/api/app/update-status'),
2079
+ refreshPendingPrs()
2080
+ ]);
2081
+ renderUpdateState(upd);
2082
+ }
2083
+
2084
+ applyTheme(state.theme);
2085
+ applyLang();
2086
+ refreshAll();
2087
+ connectWs();