@nerviq/cli 1.20.1 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/package.json +1 -1
  4. package/src/activity.js +1039 -1039
  5. package/src/adoption-advisor.js +299 -299
  6. package/src/aider/config-parser.js +166 -166
  7. package/src/aider/context.js +4 -1
  8. package/src/aider/deep-review.js +316 -316
  9. package/src/aider/domain-packs.js +303 -303
  10. package/src/aider/freshness.js +93 -93
  11. package/src/aider/governance.js +253 -253
  12. package/src/aider/interactive.js +334 -334
  13. package/src/aider/mcp-packs.js +329 -329
  14. package/src/aider/patch.js +214 -214
  15. package/src/aider/plans.js +186 -186
  16. package/src/aider/premium.js +360 -360
  17. package/src/aider/setup.js +404 -404
  18. package/src/aider/techniques.js +312 -67
  19. package/src/analyze.js +951 -951
  20. package/src/anti-patterns.js +485 -485
  21. package/src/audit/instruction-files.js +180 -180
  22. package/src/audit/recommendations.js +577 -577
  23. package/src/auto-suggest.js +154 -154
  24. package/src/badge.js +13 -13
  25. package/src/behavioral-drift.js +801 -801
  26. package/src/benchmark.js +67 -67
  27. package/src/catalog.js +103 -103
  28. package/src/certification.js +128 -128
  29. package/src/codex/config-parser.js +183 -183
  30. package/src/codex/context.js +223 -223
  31. package/src/codex/deep-review.js +493 -493
  32. package/src/codex/domain-packs.js +394 -394
  33. package/src/codex/freshness.js +84 -84
  34. package/src/codex/governance.js +192 -192
  35. package/src/codex/interactive.js +618 -618
  36. package/src/codex/mcp-packs.js +914 -914
  37. package/src/codex/patch.js +209 -209
  38. package/src/codex/plans.js +251 -251
  39. package/src/codex/premium.js +614 -614
  40. package/src/codex/setup.js +591 -591
  41. package/src/continuous-ops.js +681 -681
  42. package/src/copilot/activity.js +309 -309
  43. package/src/copilot/deep-review.js +346 -346
  44. package/src/copilot/domain-packs.js +372 -372
  45. package/src/copilot/freshness.js +57 -57
  46. package/src/copilot/governance.js +222 -222
  47. package/src/copilot/interactive.js +406 -406
  48. package/src/copilot/mcp-packs.js +826 -826
  49. package/src/copilot/plans.js +253 -253
  50. package/src/copilot/premium.js +451 -451
  51. package/src/copilot/setup.js +488 -488
  52. package/src/cost-tracking.js +61 -61
  53. package/src/cursor/activity.js +301 -301
  54. package/src/cursor/config-parser.js +265 -265
  55. package/src/cursor/context.js +256 -256
  56. package/src/cursor/deep-review.js +334 -334
  57. package/src/cursor/domain-packs.js +368 -368
  58. package/src/cursor/freshness.js +65 -65
  59. package/src/cursor/governance.js +229 -229
  60. package/src/cursor/interactive.js +391 -391
  61. package/src/cursor/mcp-packs.js +828 -828
  62. package/src/cursor/plans.js +254 -254
  63. package/src/cursor/premium.js +469 -469
  64. package/src/cursor/setup.js +488 -488
  65. package/src/dashboard.js +493 -493
  66. package/src/deep-review.js +428 -428
  67. package/src/deprecation.js +98 -98
  68. package/src/diff-only.js +280 -280
  69. package/src/doctor.js +119 -119
  70. package/src/domain-pack-expansion.js +1033 -1033
  71. package/src/domain-packs.js +387 -387
  72. package/src/feedback.js +178 -178
  73. package/src/fix-engine.js +783 -783
  74. package/src/fix-prompts.js +122 -122
  75. package/src/formatters/sarif.js +115 -115
  76. package/src/freshness.js +74 -74
  77. package/src/gemini/config-parser.js +275 -275
  78. package/src/gemini/deep-review.js +559 -559
  79. package/src/gemini/domain-packs.js +393 -393
  80. package/src/gemini/freshness.js +66 -66
  81. package/src/gemini/governance.js +201 -201
  82. package/src/gemini/interactive.js +860 -860
  83. package/src/gemini/mcp-packs.js +915 -915
  84. package/src/gemini/plans.js +269 -269
  85. package/src/gemini/premium.js +760 -760
  86. package/src/gemini/setup.js +692 -692
  87. package/src/governance.js +72 -72
  88. package/src/harmony/add.js +68 -68
  89. package/src/harmony/advisor.js +333 -333
  90. package/src/harmony/canon.js +565 -565
  91. package/src/harmony/cli.js +591 -591
  92. package/src/harmony/drift.js +401 -401
  93. package/src/harmony/governance.js +313 -313
  94. package/src/harmony/memory.js +239 -239
  95. package/src/harmony/sync.js +475 -475
  96. package/src/harmony/watch.js +370 -370
  97. package/src/hook-validation.js +342 -342
  98. package/src/index.js +271 -271
  99. package/src/init.js +184 -184
  100. package/src/instruction-surfaces.js +185 -185
  101. package/src/integrations.js +144 -144
  102. package/src/interactive.js +118 -118
  103. package/src/locales/en.json +1 -1
  104. package/src/locales/es.json +1 -1
  105. package/src/mcp-packs.js +830 -830
  106. package/src/mcp-server.js +726 -726
  107. package/src/mcp-validation.js +337 -337
  108. package/src/nerviq-sync.json +7 -7
  109. package/src/opencode/config-parser.js +109 -109
  110. package/src/opencode/context.js +247 -247
  111. package/src/opencode/deep-review.js +313 -313
  112. package/src/opencode/domain-packs.js +262 -262
  113. package/src/opencode/freshness.js +66 -66
  114. package/src/opencode/governance.js +159 -159
  115. package/src/opencode/interactive.js +392 -392
  116. package/src/opencode/mcp-packs.js +705 -705
  117. package/src/opencode/patch.js +184 -184
  118. package/src/opencode/plans.js +231 -231
  119. package/src/opencode/premium.js +413 -413
  120. package/src/opencode/setup.js +449 -449
  121. package/src/opencode/techniques.js +27 -27
  122. package/src/operating-profile.js +574 -574
  123. package/src/org.js +152 -152
  124. package/src/permission-rules.js +218 -218
  125. package/src/plans.js +839 -839
  126. package/src/platform-change-manifest.js +86 -86
  127. package/src/plugins.js +110 -110
  128. package/src/policy-layers.js +210 -210
  129. package/src/profiles.js +124 -124
  130. package/src/prompt-injection.js +74 -74
  131. package/src/public-api.js +173 -173
  132. package/src/recommendation-rules.js +84 -84
  133. package/src/repo-archetype.js +386 -386
  134. package/src/secret-patterns.js +39 -39
  135. package/src/server.js +527 -527
  136. package/src/setup/analysis.js +607 -607
  137. package/src/setup/runtime.js +172 -172
  138. package/src/setup.js +677 -677
  139. package/src/shared/capabilities.js +194 -194
  140. package/src/source-urls.js +132 -132
  141. package/src/stack-checks.js +565 -565
  142. package/src/supplemental-checks.js +13 -13
  143. package/src/synergy/adaptive.js +261 -261
  144. package/src/synergy/compensation.js +137 -137
  145. package/src/synergy/evidence.js +193 -193
  146. package/src/synergy/learning.js +199 -199
  147. package/src/synergy/patterns.js +227 -227
  148. package/src/synergy/ranking.js +83 -83
  149. package/src/synergy/report.js +165 -165
  150. package/src/synergy/routing.js +146 -146
  151. package/src/techniques/api.js +407 -407
  152. package/src/techniques/automation.js +316 -316
  153. package/src/techniques/compliance.js +257 -257
  154. package/src/techniques/hygiene.js +294 -294
  155. package/src/techniques/instructions.js +243 -243
  156. package/src/techniques/observability.js +226 -226
  157. package/src/techniques/optimization.js +142 -142
  158. package/src/techniques/quality.js +318 -318
  159. package/src/techniques/security.js +237 -237
  160. package/src/techniques/shared.js +443 -443
  161. package/src/techniques/stacks.js +2294 -2294
  162. package/src/techniques/tools.js +106 -106
  163. package/src/techniques/workflow.js +413 -413
  164. package/src/techniques.js +81 -81
  165. package/src/terminology.js +73 -73
  166. package/src/token-estimate.js +35 -35
  167. package/src/usage-patterns.js +99 -99
  168. package/src/verification-metadata.js +145 -145
  169. package/src/watch.js +247 -247
  170. package/src/windsurf/activity.js +302 -302
  171. package/src/windsurf/config-parser.js +267 -267
  172. package/src/windsurf/deep-review.js +337 -337
  173. package/src/windsurf/domain-packs.js +370 -370
  174. package/src/windsurf/freshness.js +36 -36
  175. package/src/windsurf/governance.js +231 -231
  176. package/src/windsurf/interactive.js +388 -388
  177. package/src/windsurf/mcp-packs.js +792 -792
  178. package/src/windsurf/plans.js +247 -247
  179. package/src/windsurf/premium.js +468 -468
  180. package/src/windsurf/setup.js +471 -471
  181. package/src/workspace.js +375 -375
package/src/dashboard.js CHANGED
@@ -1,493 +1,493 @@
1
- /**
2
- * Dashboard generator — produces a self-contained HTML report from audit snapshots.
3
- */
4
-
5
- const fs = require('fs');
6
- const path = require('path');
7
- const { version } = require('../package.json');
8
- const { readSnapshotIndex, getHistory, loadSnapshotPayload } = require('./activity');
9
-
10
- const COLORS = {
11
- bg: '#0a0a0a',
12
- surface: '#18181b',
13
- border: '#27272a',
14
- text: '#e4e4e7',
15
- textDim: '#a1a1aa',
16
- green: '#22c55e',
17
- red: '#ef4444',
18
- yellow: '#eab308',
19
- blue: '#3b82f6',
20
- };
21
-
22
- function scoreColor(score) {
23
- if (score >= 70) return COLORS.green;
24
- if (score >= 40) return COLORS.yellow;
25
- return COLORS.red;
26
- }
27
-
28
- function escapeHtml(str) {
29
- return String(str)
30
- .replace(/&/g, '&')
31
- .replace(/</g, '&lt;')
32
- .replace(/>/g, '&gt;')
33
- .replace(/"/g, '&quot;');
34
- }
35
-
36
- function buildScoreOverTimeSvg(history) {
37
- if (!history || history.length < 2) return '';
38
- const entries = history.slice().reverse(); // oldest first
39
- const w = 600, h = 200, pad = 40;
40
- const plotW = w - pad * 2, plotH = h - pad * 2;
41
- const n = entries.length;
42
- const step = n > 1 ? plotW / (n - 1) : 0;
43
-
44
- const points = entries.map((e, i) => {
45
- const x = pad + i * step;
46
- const score = e.summary?.score ?? 0;
47
- const y = pad + plotH - (score / 100) * plotH;
48
- return { x, y, score, date: (e.createdAt || '').split('T')[0] };
49
- });
50
-
51
- const polyline = points.map(p => `${p.x},${p.y}`).join(' ');
52
- const dots = points.map(p =>
53
- `<circle cx="${p.x}" cy="${p.y}" r="4" fill="${scoreColor(p.score)}"/>`
54
- + `<title>${p.date}: ${p.score}/100</title>`
55
- ).join('\n ');
56
-
57
- // Y-axis labels
58
- const yLabels = [0, 25, 50, 75, 100].map(v => {
59
- const y = pad + plotH - (v / 100) * plotH;
60
- return `<text x="${pad - 8}" y="${y + 4}" text-anchor="end" fill="${COLORS.textDim}" font-size="11">${v}</text>`
61
- + `<line x1="${pad}" y1="${y}" x2="${w - pad}" y2="${y}" stroke="${COLORS.border}" stroke-dasharray="4"/>`;
62
- }).join('\n ');
63
-
64
- // X-axis: first and last date
65
- const first = points[0], last = points[points.length - 1];
66
- const xLabels = `<text x="${first.x}" y="${h - 8}" text-anchor="start" fill="${COLORS.textDim}" font-size="11">${first.date}</text>`
67
- + `<text x="${last.x}" y="${h - 8}" text-anchor="end" fill="${COLORS.textDim}" font-size="11">${last.date}</text>`;
68
-
69
- return `
70
- <div class="card">
71
- <h2>Audit Snapshot Score Over Time</h2>
72
- <svg viewBox="0 0 ${w} ${h}" width="100%" style="max-width:${w}px">
73
- ${yLabels}
74
- <polyline points="${polyline}" fill="none" stroke="${COLORS.blue}" stroke-width="2"/>
75
- ${dots}
76
- ${xLabels}
77
- </svg>
78
- </div>`;
79
- }
80
-
81
- function buildCategoryBreakdownSvg(results) {
82
- if (!results || results.length === 0) return '';
83
- const cats = {};
84
- for (const r of results) {
85
- if (r.passed === null) continue;
86
- const cat = r.category || 'other';
87
- if (!cats[cat]) cats[cat] = { pass: 0, total: 0 };
88
- cats[cat].total++;
89
- if (r.passed) cats[cat].pass++;
90
- }
91
- const sorted = Object.entries(cats).sort((a, b) => {
92
- const rateA = a[1].total > 0 ? a[1].pass / a[1].total : 0;
93
- const rateB = b[1].total > 0 ? b[1].pass / b[1].total : 0;
94
- return rateA - rateB;
95
- });
96
- if (sorted.length === 0) return '';
97
-
98
- const barH = 28, gap = 6, labelW = 160, barMaxW = 360, padR = 60;
99
- const svgH = sorted.length * (barH + gap) + 10;
100
- const svgW = labelW + barMaxW + padR;
101
-
102
- const bars = sorted.map(([cat, data], i) => {
103
- const rate = data.total > 0 ? data.pass / data.total : 0;
104
- const pct = Math.round(rate * 100);
105
- const barW = Math.max(2, rate * barMaxW);
106
- const y = i * (barH + gap) + 4;
107
- const color = pct >= 70 ? COLORS.green : pct >= 40 ? COLORS.yellow : COLORS.red;
108
- return `<text x="${labelW - 8}" y="${y + barH / 2 + 4}" text-anchor="end" fill="${COLORS.text}" font-size="13">${escapeHtml(cat)}</text>`
109
- + `<rect x="${labelW}" y="${y}" width="${barW}" height="${barH}" rx="4" fill="${color}" opacity="0.85"/>`
110
- + `<text x="${labelW + barW + 8}" y="${y + barH / 2 + 4}" fill="${COLORS.textDim}" font-size="12">${pct}% (${data.pass}/${data.total})</text>`;
111
- }).join('\n ');
112
-
113
- return `
114
- <div class="card">
115
- <h2>Category Breakdown</h2>
116
- <svg viewBox="0 0 ${svgW} ${svgH}" width="100%" style="max-width:${svgW}px">
117
- ${bars}
118
- </svg>
119
- </div>`;
120
- }
121
-
122
- function getDashboardScoreMeta(history) {
123
- if (history && history.length > 0) {
124
- return {
125
- label: 'Latest audit snapshot score',
126
- note: 'Dashboard is anchored to the most recent saved audit snapshot. Trend and drift sections use audit snapshots only.',
127
- consoleSource: 'latest audit snapshot',
128
- };
129
- }
130
-
131
- return {
132
- label: 'Live audit score',
133
- note: 'No saved audit snapshots found, so this dashboard ran a live audit of the current repo. Run `nerviq audit --snapshot` to build history.',
134
- consoleSource: 'live audit (no snapshots yet)',
135
- };
136
- }
137
-
138
- function buildHtml(projectName, auditPayload, history) {
139
- const score = auditPayload.score ?? 0;
140
- const platform = auditPayload.platform || 'unknown';
141
- const results = auditPayload.results || [];
142
- const timestamp = new Date().toISOString();
143
- const scoreMeta = getDashboardScoreMeta(history);
144
-
145
- // Top 5 failed checks sorted by impact severity
146
- const impactOrder = { critical: 0, high: 1, medium: 2, low: 3 };
147
- const failed = results
148
- .filter(r => r.passed === false)
149
- .sort((a, b) => (impactOrder[a.impact] ?? 9) - (impactOrder[b.impact] ?? 9))
150
- .slice(0, 5);
151
-
152
- const failedRows = failed.length > 0
153
- ? failed.map(r =>
154
- `<tr><td>${escapeHtml(r.name || r.key)}</td><td class="impact-${r.impact || 'medium'}">${escapeHtml(r.impact || '-')}</td><td>${escapeHtml(r.category || '-')}</td></tr>`
155
- ).join('\n ')
156
- : '<tr><td colspan="3" style="text-align:center;color:' + COLORS.green + '">All checks passing!</td></tr>';
157
-
158
- const scoreOverTime = buildScoreOverTimeSvg(history);
159
- const categoryBreakdown = buildCategoryBreakdownSvg(results);
160
- const drifts = detectDrifts(history);
161
- const driftAlerts = buildDriftAlertsHtml(drifts);
162
-
163
- const detectedPlatforms = auditPayload.detectedPlatforms
164
- || (auditPayload.platform ? [auditPayload.platform] : ['unknown']);
165
- const platformList = (Array.isArray(detectedPlatforms) ? detectedPlatforms : [detectedPlatforms])
166
- .map(p => `<span class="badge">${escapeHtml(p)}</span>`).join(' ');
167
-
168
- return `<!DOCTYPE html>
169
- <html lang="en">
170
- <head>
171
- <meta charset="utf-8"/>
172
- <meta name="viewport" content="width=device-width,initial-scale=1"/>
173
- <title>Nerviq Dashboard — ${escapeHtml(projectName)}</title>
174
- <style>
175
- *{margin:0;padding:0;box-sizing:border-box}
176
- body{background:${COLORS.bg};color:${COLORS.text};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:2rem;max-width:900px;margin:0 auto}
177
- h1{font-size:1.6rem;margin-bottom:.3rem}
178
- h2{font-size:1.1rem;margin-bottom:1rem;color:${COLORS.textDim}}
179
- .timestamp{color:${COLORS.textDim};font-size:.85rem;margin-bottom:2rem}
180
- .card{background:${COLORS.surface};border:1px solid ${COLORS.border};border-radius:12px;padding:1.5rem;margin-bottom:1.5rem}
181
- .score-card{text-align:center;padding:2rem}
182
- .score-number{font-size:4rem;font-weight:800;line-height:1}
183
- .score-label{color:${COLORS.textDim};font-size:1rem;margin-top:.5rem}
184
- .badge{display:inline-block;background:${COLORS.border};padding:3px 10px;border-radius:6px;font-size:.85rem;margin:2px}
185
- table{width:100%;border-collapse:collapse}
186
- th,td{text-align:left;padding:8px 12px;border-bottom:1px solid ${COLORS.border}}
187
- th{color:${COLORS.textDim};font-weight:600;font-size:.85rem;text-transform:uppercase;letter-spacing:.03em}
188
- .impact-critical{color:${COLORS.red};font-weight:700}
189
- .impact-high{color:${COLORS.red}}
190
- .impact-medium{color:${COLORS.yellow}}
191
- .impact-low{color:${COLORS.textDim}}
192
- .footer{text-align:center;color:${COLORS.textDim};font-size:.8rem;margin-top:2rem;padding-top:1rem;border-top:1px solid ${COLORS.border}}
193
- .footer a{color:${COLORS.blue};text-decoration:none}
194
- .footer a:hover{text-decoration:underline}
195
- svg text{font-family:inherit}
196
- </style>
197
- </head>
198
- <body>
199
- <h1>Nerviq Dashboard &mdash; ${escapeHtml(projectName)}</h1>
200
- <div class="timestamp">Generated ${timestamp}</div>
201
-
202
- <div class="card score-card">
203
- <div class="score-number" style="color:${scoreColor(score)}">${score}</div>
204
- <div class="score-label">${escapeHtml(scoreMeta.label)}</div>
205
- <div style="color:${COLORS.textDim};font-size:.85rem;margin-top:.75rem;max-width:520px;margin-left:auto;margin-right:auto">${escapeHtml(scoreMeta.note)}</div>
206
- </div>
207
-
208
- <div class="card">
209
- <h2>Platforms Detected</h2>
210
- ${platformList}
211
- </div>
212
-
213
- <div class="card">
214
- <h2>Top Failed Checks</h2>
215
- <table>
216
- <thead><tr><th>Check</th><th>Impact</th><th>Category</th></tr></thead>
217
- <tbody>
218
- ${failedRows}
219
- </tbody>
220
- </table>
221
- </div>
222
-
223
- ${scoreOverTime}
224
- ${driftAlerts}
225
- ${categoryBreakdown}
226
-
227
- <div class="footer">
228
- Generated by <a href="https://github.com/nerviq/cli">Nerviq v${version}</a>
229
- </div>
230
- </body>
231
- </html>`;
232
- }
233
-
234
- /**
235
- * Generate a static HTML dashboard report.
236
- * @param {string} dir - Project root directory.
237
- * @param {Object} flags - CLI flags (--out, --open, --json, etc).
238
- */
239
- async function generateDashboard(dir, flags = {}) {
240
- const outputFile = flags.out || 'nerviq-dashboard.html';
241
- const outputPath = path.isAbsolute(outputFile) ? outputFile : path.join(dir, outputFile);
242
- const projectName = path.basename(dir);
243
-
244
- // Collect audit history from snapshots
245
- const history = getHistory(dir, 50);
246
- let auditPayload = null;
247
-
248
- if (history.length > 0) {
249
- // Load the most recent audit snapshot
250
- auditPayload = loadSnapshotPayload(dir, history[0]);
251
- }
252
-
253
- if (!auditPayload) {
254
- // No snapshots — run a fresh audit
255
- const { audit } = require('./audit');
256
- auditPayload = await audit({ dir, silent: true, platform: flags.platform || 'claude' });
257
- }
258
-
259
- const scoreMeta = getDashboardScoreMeta(history);
260
- const html = buildHtml(projectName, auditPayload, history);
261
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
262
- fs.writeFileSync(outputPath, html, 'utf8');
263
-
264
- const relPath = path.relative(dir, outputPath);
265
- if (!flags.json) {
266
- console.log('');
267
- console.log(' nerviq dashboard');
268
- console.log(' \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550');
269
- console.log(` Dashboard score: ${auditPayload.score ?? '?'}/100`);
270
- console.log(` Score source: ${scoreMeta.consoleSource}`);
271
- console.log(` Audit snapshots: ${history.length}`);
272
- console.log(` Output: ${relPath}`);
273
- console.log('');
274
- }
275
-
276
- if (flags.open) {
277
- const { exec } = require('child_process');
278
- const cmd = process.platform === 'win32' ? `start "" "${outputPath}"`
279
- : process.platform === 'darwin' ? `open "${outputPath}"`
280
- : `xdg-open "${outputPath}"`;
281
- exec(cmd);
282
- }
283
-
284
- return { outputPath, relativePath: relPath, score: auditPayload.score, scoreSource: scoreMeta.consoleSource };
285
- }
286
-
287
- /**
288
- * Detect score drift between recent snapshots.
289
- * Returns array of { from, to, delta, date } for drifts > threshold.
290
- */
291
- function detectDrifts(history, threshold = 5) {
292
- if (!history || history.length < 2) return [];
293
- const drifts = [];
294
- for (let i = 0; i < history.length - 1; i++) {
295
- const current = history[i];
296
- const previous = history[i + 1];
297
- const currentScore = current.summary?.score;
298
- const previousScore = previous.summary?.score;
299
- if (currentScore != null && previousScore != null) {
300
- const delta = currentScore - previousScore;
301
- if (Math.abs(delta) >= threshold) {
302
- drifts.push({
303
- date: current.createdAt || current.date || current.timestamp,
304
- from: previousScore,
305
- to: currentScore,
306
- delta,
307
- });
308
- }
309
- }
310
- }
311
- return drifts;
312
- }
313
-
314
- /**
315
- * Build drift alerts HTML section for the dashboard.
316
- */
317
- function buildDriftAlertsHtml(drifts) {
318
- if (!drifts.length) return '';
319
- const rows = drifts.map(d => {
320
- const color = d.delta < 0 ? COLORS.red : COLORS.green;
321
- const arrow = d.delta < 0 ? '▼' : '▲';
322
- const sign = d.delta > 0 ? '+' : '';
323
- return `<tr>
324
- <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border}">${escapeHtml(d.date)}</td>
325
- <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border}">${d.from} → ${d.to}</td>
326
- <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border};color:${color};font-weight:bold">${arrow} ${sign}${d.delta}</td>
327
- </tr>`;
328
- }).join('');
329
-
330
- return `
331
- <div style="margin-top:32px">
332
- <h2 style="color:${COLORS.text};font-size:18px;margin-bottom:12px">⚠ Audit Snapshot Drift Alerts</h2>
333
- <p style="color:${COLORS.textDim};font-size:13px;margin-bottom:12px">Changes of 5+ points between consecutive audit snapshots</p>
334
- <table style="width:100%;border-collapse:collapse;background:${COLORS.surface};border-radius:8px;overflow:hidden">
335
- <thead><tr style="background:${COLORS.border}">
336
- <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Date</th>
337
- <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Score Change</th>
338
- <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Delta</th>
339
- </tr></thead>
340
- <tbody>${rows}</tbody>
341
- </table>
342
- </div>`;
343
- }
344
-
345
- /**
346
- * Build a portfolio HTML page summarizing multiple repos.
347
- */
348
- function buildPortfolioHtml(repoResults) {
349
- const timestamp = new Date().toISOString();
350
- const scores = repoResults.map(r => r.score);
351
- const avgScore = repoResults.length > 0 ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
352
- const weakest = repoResults.reduce((a, b) => a.score <= b.score ? a : b, repoResults[0]);
353
- const strongest = repoResults.reduce((a, b) => a.score >= b.score ? a : b, repoResults[0]);
354
-
355
- const rows = repoResults.map(r => {
356
- const indicator = r.score >= 70 ? '\u{1F7E2}' : r.score >= 40 ? '\u{1F7E1}' : '\u{1F534}';
357
- const platforms = (r.platforms || ['unknown']).map(p => `<span class="badge">${escapeHtml(p)}</span>`).join(' ');
358
- const isWeak = r.name === weakest.name && repoResults.length > 1;
359
- const isStrong = r.name === strongest.name && repoResults.length > 1;
360
- const highlight = isWeak ? ' style="border-left:3px solid ' + COLORS.red + '"'
361
- : isStrong ? ' style="border-left:3px solid ' + COLORS.green + '"' : '';
362
- return `<tr${highlight}><td>${escapeHtml(r.name)}</td><td>${platforms}</td><td style="color:${scoreColor(r.score)};font-weight:700">${r.score}</td><td>${r.critical}</td><td>${r.high}</td><td>${indicator}</td></tr>`;
363
- }).join('\n ');
364
-
365
- return `<!DOCTYPE html>
366
- <html lang="en">
367
- <head>
368
- <meta charset="utf-8"/>
369
- <meta name="viewport" content="width=device-width,initial-scale=1"/>
370
- <title>Nerviq Portfolio Dashboard</title>
371
- <style>
372
- *{margin:0;padding:0;box-sizing:border-box}
373
- body{background:${COLORS.bg};color:${COLORS.text};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:2rem;max-width:1000px;margin:0 auto}
374
- h1{font-size:1.6rem;margin-bottom:.3rem}
375
- h2{font-size:1.1rem;margin-bottom:1rem;color:${COLORS.textDim}}
376
- .timestamp{color:${COLORS.textDim};font-size:.85rem;margin-bottom:2rem}
377
- .card{background:${COLORS.surface};border:1px solid ${COLORS.border};border-radius:12px;padding:1.5rem;margin-bottom:1.5rem}
378
- .score-card{text-align:center;padding:2rem}
379
- .score-number{font-size:4rem;font-weight:800;line-height:1}
380
- .score-label{color:${COLORS.textDim};font-size:1rem;margin-top:.5rem}
381
- .badge{display:inline-block;background:${COLORS.border};padding:3px 10px;border-radius:6px;font-size:.85rem;margin:2px}
382
- .highlights{display:flex;gap:1.5rem;margin-bottom:1.5rem}
383
- .highlights .card{flex:1;text-align:center}
384
- .highlights .label{color:${COLORS.textDim};font-size:.85rem;margin-bottom:.5rem}
385
- .highlights .value{font-size:1.3rem;font-weight:700}
386
- table{width:100%;border-collapse:collapse}
387
- th,td{text-align:left;padding:8px 12px;border-bottom:1px solid ${COLORS.border}}
388
- th{color:${COLORS.textDim};font-weight:600;font-size:.85rem;text-transform:uppercase;letter-spacing:.03em}
389
- .footer{text-align:center;color:${COLORS.textDim};font-size:.8rem;margin-top:2rem;padding-top:1rem;border-top:1px solid ${COLORS.border}}
390
- .footer a{color:${COLORS.blue};text-decoration:none}
391
- .footer a:hover{text-decoration:underline}
392
- </style>
393
- </head>
394
- <body>
395
- <h1>Nerviq Portfolio Dashboard</h1>
396
- <div class="timestamp">${repoResults.length} repos &mdash; Generated ${timestamp}</div>
397
-
398
- <div class="card score-card">
399
- <div class="score-number" style="color:${scoreColor(avgScore)}">${avgScore}</div>
400
- <div class="score-label">average live audit score across ${repoResults.length} repos</div>
401
- </div>
402
-
403
- <div class="highlights">
404
- <div class="card">
405
- <div class="label">Strongest Repo</div>
406
- <div class="value" style="color:${COLORS.green}">${escapeHtml(strongest.name)} (${strongest.score})</div>
407
- </div>
408
- <div class="card">
409
- <div class="label">Weakest Repo</div>
410
- <div class="value" style="color:${COLORS.red}">${escapeHtml(weakest.name)} (${weakest.score})</div>
411
- </div>
412
- </div>
413
-
414
- <div class="card">
415
- <h2>Repository Summary</h2>
416
- <table>
417
- <thead><tr><th>Repo</th><th>Platform(s)</th><th>Score</th><th>Critical</th><th>High</th><th>Status</th></tr></thead>
418
- <tbody>
419
- ${rows}
420
- </tbody>
421
- </table>
422
- </div>
423
-
424
- <div class="footer">
425
- Generated by <a href="https://github.com/nerviq/cli">Nerviq v${version}</a>
426
- </div>
427
- </body>
428
- </html>`;
429
- }
430
-
431
- /**
432
- * Generate a portfolio dashboard across multiple repos.
433
- * @param {string[]} repoPaths - Array of repo directory paths.
434
- * @param {Object} flags - CLI flags (--out, --open, --json, --platform).
435
- */
436
- async function generatePortfolioDashboard(repoPaths, flags = {}) {
437
- const { audit } = require('./audit');
438
- const repoResults = [];
439
-
440
- for (const repoPath of repoPaths) {
441
- const absPath = path.isAbsolute(repoPath) ? repoPath : path.resolve(repoPath);
442
- if (!fs.existsSync(absPath)) {
443
- console.error(` Warning: skipping ${repoPath} (not found)`);
444
- continue;
445
- }
446
- const name = path.basename(absPath);
447
- try {
448
- const result = await audit({ dir: absPath, silent: true, platform: flags.platform || 'claude' });
449
- const results = result.results || [];
450
- const critical = results.filter(r => !r.passed && r.impact === 'critical').length;
451
- const high = results.filter(r => !r.passed && r.impact === 'high').length;
452
- const platforms = result.detectedPlatforms || (result.platform ? [result.platform] : ['unknown']);
453
- repoResults.push({ name, score: result.score ?? 0, platforms, critical, high });
454
- } catch (err) {
455
- console.error(` Warning: audit failed for ${name}: ${err.message}`);
456
- repoResults.push({ name, score: 0, platforms: ['error'], critical: 0, high: 0 });
457
- }
458
- }
459
-
460
- if (repoResults.length === 0) {
461
- console.error('\n Error: no valid repos found.\n');
462
- process.exit(1);
463
- }
464
-
465
- const outputFile = flags.out || 'nerviq-portfolio.html';
466
- const outputPath = path.isAbsolute(outputFile) ? outputFile : path.resolve(outputFile);
467
- const html = buildPortfolioHtml(repoResults);
468
- fs.mkdirSync(path.dirname(outputPath), { recursive: true });
469
- fs.writeFileSync(outputPath, html, 'utf8');
470
-
471
- const avgScore = Math.round(repoResults.reduce((s, r) => s + r.score, 0) / repoResults.length);
472
- if (!flags.json) {
473
- console.log('');
474
- console.log(' nerviq portfolio dashboard');
475
- console.log(' \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550');
476
- console.log(` Repos: ${repoResults.length}`);
477
- console.log(` Average live audit score: ${avgScore}/100`);
478
- console.log(` Output: ${outputPath}`);
479
- console.log('');
480
- }
481
-
482
- if (flags.open) {
483
- const { exec } = require('child_process');
484
- const cmd = process.platform === 'win32' ? `start "" "${outputPath}"`
485
- : process.platform === 'darwin' ? `open "${outputPath}"`
486
- : `xdg-open "${outputPath}"`;
487
- exec(cmd);
488
- }
489
-
490
- return { outputPath, repoCount: repoResults.length, avgScore, repos: repoResults };
491
- }
492
-
493
- module.exports = { generateDashboard, generatePortfolioDashboard, detectDrifts, buildDriftAlertsHtml };
1
+ /**
2
+ * Dashboard generator — produces a self-contained HTML report from audit snapshots.
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { version } = require('../package.json');
8
+ const { readSnapshotIndex, getHistory, loadSnapshotPayload } = require('./activity');
9
+
10
+ const COLORS = {
11
+ bg: '#0a0a0a',
12
+ surface: '#18181b',
13
+ border: '#27272a',
14
+ text: '#e4e4e7',
15
+ textDim: '#a1a1aa',
16
+ green: '#22c55e',
17
+ red: '#ef4444',
18
+ yellow: '#eab308',
19
+ blue: '#3b82f6',
20
+ };
21
+
22
+ function scoreColor(score) {
23
+ if (score >= 70) return COLORS.green;
24
+ if (score >= 40) return COLORS.yellow;
25
+ return COLORS.red;
26
+ }
27
+
28
+ function escapeHtml(str) {
29
+ return String(str)
30
+ .replace(/&/g, '&amp;')
31
+ .replace(/</g, '&lt;')
32
+ .replace(/>/g, '&gt;')
33
+ .replace(/"/g, '&quot;');
34
+ }
35
+
36
+ function buildScoreOverTimeSvg(history) {
37
+ if (!history || history.length < 2) return '';
38
+ const entries = history.slice().reverse(); // oldest first
39
+ const w = 600, h = 200, pad = 40;
40
+ const plotW = w - pad * 2, plotH = h - pad * 2;
41
+ const n = entries.length;
42
+ const step = n > 1 ? plotW / (n - 1) : 0;
43
+
44
+ const points = entries.map((e, i) => {
45
+ const x = pad + i * step;
46
+ const score = e.summary?.score ?? 0;
47
+ const y = pad + plotH - (score / 100) * plotH;
48
+ return { x, y, score, date: (e.createdAt || '').split('T')[0] };
49
+ });
50
+
51
+ const polyline = points.map(p => `${p.x},${p.y}`).join(' ');
52
+ const dots = points.map(p =>
53
+ `<circle cx="${p.x}" cy="${p.y}" r="4" fill="${scoreColor(p.score)}"/>`
54
+ + `<title>${p.date}: ${p.score}/100</title>`
55
+ ).join('\n ');
56
+
57
+ // Y-axis labels
58
+ const yLabels = [0, 25, 50, 75, 100].map(v => {
59
+ const y = pad + plotH - (v / 100) * plotH;
60
+ return `<text x="${pad - 8}" y="${y + 4}" text-anchor="end" fill="${COLORS.textDim}" font-size="11">${v}</text>`
61
+ + `<line x1="${pad}" y1="${y}" x2="${w - pad}" y2="${y}" stroke="${COLORS.border}" stroke-dasharray="4"/>`;
62
+ }).join('\n ');
63
+
64
+ // X-axis: first and last date
65
+ const first = points[0], last = points[points.length - 1];
66
+ const xLabels = `<text x="${first.x}" y="${h - 8}" text-anchor="start" fill="${COLORS.textDim}" font-size="11">${first.date}</text>`
67
+ + `<text x="${last.x}" y="${h - 8}" text-anchor="end" fill="${COLORS.textDim}" font-size="11">${last.date}</text>`;
68
+
69
+ return `
70
+ <div class="card">
71
+ <h2>Audit Snapshot Score Over Time</h2>
72
+ <svg viewBox="0 0 ${w} ${h}" width="100%" style="max-width:${w}px">
73
+ ${yLabels}
74
+ <polyline points="${polyline}" fill="none" stroke="${COLORS.blue}" stroke-width="2"/>
75
+ ${dots}
76
+ ${xLabels}
77
+ </svg>
78
+ </div>`;
79
+ }
80
+
81
+ function buildCategoryBreakdownSvg(results) {
82
+ if (!results || results.length === 0) return '';
83
+ const cats = {};
84
+ for (const r of results) {
85
+ if (r.passed === null) continue;
86
+ const cat = r.category || 'other';
87
+ if (!cats[cat]) cats[cat] = { pass: 0, total: 0 };
88
+ cats[cat].total++;
89
+ if (r.passed) cats[cat].pass++;
90
+ }
91
+ const sorted = Object.entries(cats).sort((a, b) => {
92
+ const rateA = a[1].total > 0 ? a[1].pass / a[1].total : 0;
93
+ const rateB = b[1].total > 0 ? b[1].pass / b[1].total : 0;
94
+ return rateA - rateB;
95
+ });
96
+ if (sorted.length === 0) return '';
97
+
98
+ const barH = 28, gap = 6, labelW = 160, barMaxW = 360, padR = 60;
99
+ const svgH = sorted.length * (barH + gap) + 10;
100
+ const svgW = labelW + barMaxW + padR;
101
+
102
+ const bars = sorted.map(([cat, data], i) => {
103
+ const rate = data.total > 0 ? data.pass / data.total : 0;
104
+ const pct = Math.round(rate * 100);
105
+ const barW = Math.max(2, rate * barMaxW);
106
+ const y = i * (barH + gap) + 4;
107
+ const color = pct >= 70 ? COLORS.green : pct >= 40 ? COLORS.yellow : COLORS.red;
108
+ return `<text x="${labelW - 8}" y="${y + barH / 2 + 4}" text-anchor="end" fill="${COLORS.text}" font-size="13">${escapeHtml(cat)}</text>`
109
+ + `<rect x="${labelW}" y="${y}" width="${barW}" height="${barH}" rx="4" fill="${color}" opacity="0.85"/>`
110
+ + `<text x="${labelW + barW + 8}" y="${y + barH / 2 + 4}" fill="${COLORS.textDim}" font-size="12">${pct}% (${data.pass}/${data.total})</text>`;
111
+ }).join('\n ');
112
+
113
+ return `
114
+ <div class="card">
115
+ <h2>Category Breakdown</h2>
116
+ <svg viewBox="0 0 ${svgW} ${svgH}" width="100%" style="max-width:${svgW}px">
117
+ ${bars}
118
+ </svg>
119
+ </div>`;
120
+ }
121
+
122
+ function getDashboardScoreMeta(history) {
123
+ if (history && history.length > 0) {
124
+ return {
125
+ label: 'Latest audit snapshot score',
126
+ note: 'Dashboard is anchored to the most recent saved audit snapshot. Trend and drift sections use audit snapshots only.',
127
+ consoleSource: 'latest audit snapshot',
128
+ };
129
+ }
130
+
131
+ return {
132
+ label: 'Live audit score',
133
+ note: 'No saved audit snapshots found, so this dashboard ran a live audit of the current repo. Run `nerviq audit --snapshot` to build history.',
134
+ consoleSource: 'live audit (no snapshots yet)',
135
+ };
136
+ }
137
+
138
+ function buildHtml(projectName, auditPayload, history) {
139
+ const score = auditPayload.score ?? 0;
140
+ const platform = auditPayload.platform || 'unknown';
141
+ const results = auditPayload.results || [];
142
+ const timestamp = new Date().toISOString();
143
+ const scoreMeta = getDashboardScoreMeta(history);
144
+
145
+ // Top 5 failed checks sorted by impact severity
146
+ const impactOrder = { critical: 0, high: 1, medium: 2, low: 3 };
147
+ const failed = results
148
+ .filter(r => r.passed === false)
149
+ .sort((a, b) => (impactOrder[a.impact] ?? 9) - (impactOrder[b.impact] ?? 9))
150
+ .slice(0, 5);
151
+
152
+ const failedRows = failed.length > 0
153
+ ? failed.map(r =>
154
+ `<tr><td>${escapeHtml(r.name || r.key)}</td><td class="impact-${r.impact || 'medium'}">${escapeHtml(r.impact || '-')}</td><td>${escapeHtml(r.category || '-')}</td></tr>`
155
+ ).join('\n ')
156
+ : '<tr><td colspan="3" style="text-align:center;color:' + COLORS.green + '">All checks passing!</td></tr>';
157
+
158
+ const scoreOverTime = buildScoreOverTimeSvg(history);
159
+ const categoryBreakdown = buildCategoryBreakdownSvg(results);
160
+ const drifts = detectDrifts(history);
161
+ const driftAlerts = buildDriftAlertsHtml(drifts);
162
+
163
+ const detectedPlatforms = auditPayload.detectedPlatforms
164
+ || (auditPayload.platform ? [auditPayload.platform] : ['unknown']);
165
+ const platformList = (Array.isArray(detectedPlatforms) ? detectedPlatforms : [detectedPlatforms])
166
+ .map(p => `<span class="badge">${escapeHtml(p)}</span>`).join(' ');
167
+
168
+ return `<!DOCTYPE html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8"/>
172
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
173
+ <title>Nerviq Dashboard — ${escapeHtml(projectName)}</title>
174
+ <style>
175
+ *{margin:0;padding:0;box-sizing:border-box}
176
+ body{background:${COLORS.bg};color:${COLORS.text};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:2rem;max-width:900px;margin:0 auto}
177
+ h1{font-size:1.6rem;margin-bottom:.3rem}
178
+ h2{font-size:1.1rem;margin-bottom:1rem;color:${COLORS.textDim}}
179
+ .timestamp{color:${COLORS.textDim};font-size:.85rem;margin-bottom:2rem}
180
+ .card{background:${COLORS.surface};border:1px solid ${COLORS.border};border-radius:12px;padding:1.5rem;margin-bottom:1.5rem}
181
+ .score-card{text-align:center;padding:2rem}
182
+ .score-number{font-size:4rem;font-weight:800;line-height:1}
183
+ .score-label{color:${COLORS.textDim};font-size:1rem;margin-top:.5rem}
184
+ .badge{display:inline-block;background:${COLORS.border};padding:3px 10px;border-radius:6px;font-size:.85rem;margin:2px}
185
+ table{width:100%;border-collapse:collapse}
186
+ th,td{text-align:left;padding:8px 12px;border-bottom:1px solid ${COLORS.border}}
187
+ th{color:${COLORS.textDim};font-weight:600;font-size:.85rem;text-transform:uppercase;letter-spacing:.03em}
188
+ .impact-critical{color:${COLORS.red};font-weight:700}
189
+ .impact-high{color:${COLORS.red}}
190
+ .impact-medium{color:${COLORS.yellow}}
191
+ .impact-low{color:${COLORS.textDim}}
192
+ .footer{text-align:center;color:${COLORS.textDim};font-size:.8rem;margin-top:2rem;padding-top:1rem;border-top:1px solid ${COLORS.border}}
193
+ .footer a{color:${COLORS.blue};text-decoration:none}
194
+ .footer a:hover{text-decoration:underline}
195
+ svg text{font-family:inherit}
196
+ </style>
197
+ </head>
198
+ <body>
199
+ <h1>Nerviq Dashboard &mdash; ${escapeHtml(projectName)}</h1>
200
+ <div class="timestamp">Generated ${timestamp}</div>
201
+
202
+ <div class="card score-card">
203
+ <div class="score-number" style="color:${scoreColor(score)}">${score}</div>
204
+ <div class="score-label">${escapeHtml(scoreMeta.label)}</div>
205
+ <div style="color:${COLORS.textDim};font-size:.85rem;margin-top:.75rem;max-width:520px;margin-left:auto;margin-right:auto">${escapeHtml(scoreMeta.note)}</div>
206
+ </div>
207
+
208
+ <div class="card">
209
+ <h2>Platforms Detected</h2>
210
+ ${platformList}
211
+ </div>
212
+
213
+ <div class="card">
214
+ <h2>Top Failed Checks</h2>
215
+ <table>
216
+ <thead><tr><th>Check</th><th>Impact</th><th>Category</th></tr></thead>
217
+ <tbody>
218
+ ${failedRows}
219
+ </tbody>
220
+ </table>
221
+ </div>
222
+
223
+ ${scoreOverTime}
224
+ ${driftAlerts}
225
+ ${categoryBreakdown}
226
+
227
+ <div class="footer">
228
+ Generated by <a href="https://github.com/nerviq/cli">Nerviq v${version}</a>
229
+ </div>
230
+ </body>
231
+ </html>`;
232
+ }
233
+
234
+ /**
235
+ * Generate a static HTML dashboard report.
236
+ * @param {string} dir - Project root directory.
237
+ * @param {Object} flags - CLI flags (--out, --open, --json, etc).
238
+ */
239
+ async function generateDashboard(dir, flags = {}) {
240
+ const outputFile = flags.out || 'nerviq-dashboard.html';
241
+ const outputPath = path.isAbsolute(outputFile) ? outputFile : path.join(dir, outputFile);
242
+ const projectName = path.basename(dir);
243
+
244
+ // Collect audit history from snapshots
245
+ const history = getHistory(dir, 50);
246
+ let auditPayload = null;
247
+
248
+ if (history.length > 0) {
249
+ // Load the most recent audit snapshot
250
+ auditPayload = loadSnapshotPayload(dir, history[0]);
251
+ }
252
+
253
+ if (!auditPayload) {
254
+ // No snapshots — run a fresh audit
255
+ const { audit } = require('./audit');
256
+ auditPayload = await audit({ dir, silent: true, platform: flags.platform || 'claude' });
257
+ }
258
+
259
+ const scoreMeta = getDashboardScoreMeta(history);
260
+ const html = buildHtml(projectName, auditPayload, history);
261
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
262
+ fs.writeFileSync(outputPath, html, 'utf8');
263
+
264
+ const relPath = path.relative(dir, outputPath);
265
+ if (!flags.json) {
266
+ console.log('');
267
+ console.log(' nerviq dashboard');
268
+ console.log(' \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550');
269
+ console.log(` Dashboard score: ${auditPayload.score ?? '?'}/100`);
270
+ console.log(` Score source: ${scoreMeta.consoleSource}`);
271
+ console.log(` Audit snapshots: ${history.length}`);
272
+ console.log(` Output: ${relPath}`);
273
+ console.log('');
274
+ }
275
+
276
+ if (flags.open) {
277
+ const { exec } = require('child_process');
278
+ const cmd = process.platform === 'win32' ? `start "" "${outputPath}"`
279
+ : process.platform === 'darwin' ? `open "${outputPath}"`
280
+ : `xdg-open "${outputPath}"`;
281
+ exec(cmd);
282
+ }
283
+
284
+ return { outputPath, relativePath: relPath, score: auditPayload.score, scoreSource: scoreMeta.consoleSource };
285
+ }
286
+
287
+ /**
288
+ * Detect score drift between recent snapshots.
289
+ * Returns array of { from, to, delta, date } for drifts > threshold.
290
+ */
291
+ function detectDrifts(history, threshold = 5) {
292
+ if (!history || history.length < 2) return [];
293
+ const drifts = [];
294
+ for (let i = 0; i < history.length - 1; i++) {
295
+ const current = history[i];
296
+ const previous = history[i + 1];
297
+ const currentScore = current.summary?.score;
298
+ const previousScore = previous.summary?.score;
299
+ if (currentScore != null && previousScore != null) {
300
+ const delta = currentScore - previousScore;
301
+ if (Math.abs(delta) >= threshold) {
302
+ drifts.push({
303
+ date: current.createdAt || current.date || current.timestamp,
304
+ from: previousScore,
305
+ to: currentScore,
306
+ delta,
307
+ });
308
+ }
309
+ }
310
+ }
311
+ return drifts;
312
+ }
313
+
314
+ /**
315
+ * Build drift alerts HTML section for the dashboard.
316
+ */
317
+ function buildDriftAlertsHtml(drifts) {
318
+ if (!drifts.length) return '';
319
+ const rows = drifts.map(d => {
320
+ const color = d.delta < 0 ? COLORS.red : COLORS.green;
321
+ const arrow = d.delta < 0 ? '▼' : '▲';
322
+ const sign = d.delta > 0 ? '+' : '';
323
+ return `<tr>
324
+ <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border}">${escapeHtml(d.date)}</td>
325
+ <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border}">${d.from} → ${d.to}</td>
326
+ <td style="padding:8px 12px;border-bottom:1px solid ${COLORS.border};color:${color};font-weight:bold">${arrow} ${sign}${d.delta}</td>
327
+ </tr>`;
328
+ }).join('');
329
+
330
+ return `
331
+ <div style="margin-top:32px">
332
+ <h2 style="color:${COLORS.text};font-size:18px;margin-bottom:12px">⚠ Audit Snapshot Drift Alerts</h2>
333
+ <p style="color:${COLORS.textDim};font-size:13px;margin-bottom:12px">Changes of 5+ points between consecutive audit snapshots</p>
334
+ <table style="width:100%;border-collapse:collapse;background:${COLORS.surface};border-radius:8px;overflow:hidden">
335
+ <thead><tr style="background:${COLORS.border}">
336
+ <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Date</th>
337
+ <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Score Change</th>
338
+ <th style="padding:8px 12px;text-align:left;color:${COLORS.textDim};font-size:12px">Delta</th>
339
+ </tr></thead>
340
+ <tbody>${rows}</tbody>
341
+ </table>
342
+ </div>`;
343
+ }
344
+
345
+ /**
346
+ * Build a portfolio HTML page summarizing multiple repos.
347
+ */
348
+ function buildPortfolioHtml(repoResults) {
349
+ const timestamp = new Date().toISOString();
350
+ const scores = repoResults.map(r => r.score);
351
+ const avgScore = repoResults.length > 0 ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length) : 0;
352
+ const weakest = repoResults.reduce((a, b) => a.score <= b.score ? a : b, repoResults[0]);
353
+ const strongest = repoResults.reduce((a, b) => a.score >= b.score ? a : b, repoResults[0]);
354
+
355
+ const rows = repoResults.map(r => {
356
+ const indicator = r.score >= 70 ? '\u{1F7E2}' : r.score >= 40 ? '\u{1F7E1}' : '\u{1F534}';
357
+ const platforms = (r.platforms || ['unknown']).map(p => `<span class="badge">${escapeHtml(p)}</span>`).join(' ');
358
+ const isWeak = r.name === weakest.name && repoResults.length > 1;
359
+ const isStrong = r.name === strongest.name && repoResults.length > 1;
360
+ const highlight = isWeak ? ' style="border-left:3px solid ' + COLORS.red + '"'
361
+ : isStrong ? ' style="border-left:3px solid ' + COLORS.green + '"' : '';
362
+ return `<tr${highlight}><td>${escapeHtml(r.name)}</td><td>${platforms}</td><td style="color:${scoreColor(r.score)};font-weight:700">${r.score}</td><td>${r.critical}</td><td>${r.high}</td><td>${indicator}</td></tr>`;
363
+ }).join('\n ');
364
+
365
+ return `<!DOCTYPE html>
366
+ <html lang="en">
367
+ <head>
368
+ <meta charset="utf-8"/>
369
+ <meta name="viewport" content="width=device-width,initial-scale=1"/>
370
+ <title>Nerviq Portfolio Dashboard</title>
371
+ <style>
372
+ *{margin:0;padding:0;box-sizing:border-box}
373
+ body{background:${COLORS.bg};color:${COLORS.text};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;padding:2rem;max-width:1000px;margin:0 auto}
374
+ h1{font-size:1.6rem;margin-bottom:.3rem}
375
+ h2{font-size:1.1rem;margin-bottom:1rem;color:${COLORS.textDim}}
376
+ .timestamp{color:${COLORS.textDim};font-size:.85rem;margin-bottom:2rem}
377
+ .card{background:${COLORS.surface};border:1px solid ${COLORS.border};border-radius:12px;padding:1.5rem;margin-bottom:1.5rem}
378
+ .score-card{text-align:center;padding:2rem}
379
+ .score-number{font-size:4rem;font-weight:800;line-height:1}
380
+ .score-label{color:${COLORS.textDim};font-size:1rem;margin-top:.5rem}
381
+ .badge{display:inline-block;background:${COLORS.border};padding:3px 10px;border-radius:6px;font-size:.85rem;margin:2px}
382
+ .highlights{display:flex;gap:1.5rem;margin-bottom:1.5rem}
383
+ .highlights .card{flex:1;text-align:center}
384
+ .highlights .label{color:${COLORS.textDim};font-size:.85rem;margin-bottom:.5rem}
385
+ .highlights .value{font-size:1.3rem;font-weight:700}
386
+ table{width:100%;border-collapse:collapse}
387
+ th,td{text-align:left;padding:8px 12px;border-bottom:1px solid ${COLORS.border}}
388
+ th{color:${COLORS.textDim};font-weight:600;font-size:.85rem;text-transform:uppercase;letter-spacing:.03em}
389
+ .footer{text-align:center;color:${COLORS.textDim};font-size:.8rem;margin-top:2rem;padding-top:1rem;border-top:1px solid ${COLORS.border}}
390
+ .footer a{color:${COLORS.blue};text-decoration:none}
391
+ .footer a:hover{text-decoration:underline}
392
+ </style>
393
+ </head>
394
+ <body>
395
+ <h1>Nerviq Portfolio Dashboard</h1>
396
+ <div class="timestamp">${repoResults.length} repos &mdash; Generated ${timestamp}</div>
397
+
398
+ <div class="card score-card">
399
+ <div class="score-number" style="color:${scoreColor(avgScore)}">${avgScore}</div>
400
+ <div class="score-label">average live audit score across ${repoResults.length} repos</div>
401
+ </div>
402
+
403
+ <div class="highlights">
404
+ <div class="card">
405
+ <div class="label">Strongest Repo</div>
406
+ <div class="value" style="color:${COLORS.green}">${escapeHtml(strongest.name)} (${strongest.score})</div>
407
+ </div>
408
+ <div class="card">
409
+ <div class="label">Weakest Repo</div>
410
+ <div class="value" style="color:${COLORS.red}">${escapeHtml(weakest.name)} (${weakest.score})</div>
411
+ </div>
412
+ </div>
413
+
414
+ <div class="card">
415
+ <h2>Repository Summary</h2>
416
+ <table>
417
+ <thead><tr><th>Repo</th><th>Platform(s)</th><th>Score</th><th>Critical</th><th>High</th><th>Status</th></tr></thead>
418
+ <tbody>
419
+ ${rows}
420
+ </tbody>
421
+ </table>
422
+ </div>
423
+
424
+ <div class="footer">
425
+ Generated by <a href="https://github.com/nerviq/cli">Nerviq v${version}</a>
426
+ </div>
427
+ </body>
428
+ </html>`;
429
+ }
430
+
431
+ /**
432
+ * Generate a portfolio dashboard across multiple repos.
433
+ * @param {string[]} repoPaths - Array of repo directory paths.
434
+ * @param {Object} flags - CLI flags (--out, --open, --json, --platform).
435
+ */
436
+ async function generatePortfolioDashboard(repoPaths, flags = {}) {
437
+ const { audit } = require('./audit');
438
+ const repoResults = [];
439
+
440
+ for (const repoPath of repoPaths) {
441
+ const absPath = path.isAbsolute(repoPath) ? repoPath : path.resolve(repoPath);
442
+ if (!fs.existsSync(absPath)) {
443
+ console.error(` Warning: skipping ${repoPath} (not found)`);
444
+ continue;
445
+ }
446
+ const name = path.basename(absPath);
447
+ try {
448
+ const result = await audit({ dir: absPath, silent: true, platform: flags.platform || 'claude' });
449
+ const results = result.results || [];
450
+ const critical = results.filter(r => !r.passed && r.impact === 'critical').length;
451
+ const high = results.filter(r => !r.passed && r.impact === 'high').length;
452
+ const platforms = result.detectedPlatforms || (result.platform ? [result.platform] : ['unknown']);
453
+ repoResults.push({ name, score: result.score ?? 0, platforms, critical, high });
454
+ } catch (err) {
455
+ console.error(` Warning: audit failed for ${name}: ${err.message}`);
456
+ repoResults.push({ name, score: 0, platforms: ['error'], critical: 0, high: 0 });
457
+ }
458
+ }
459
+
460
+ if (repoResults.length === 0) {
461
+ console.error('\n Error: no valid repos found.\n');
462
+ process.exit(1);
463
+ }
464
+
465
+ const outputFile = flags.out || 'nerviq-portfolio.html';
466
+ const outputPath = path.isAbsolute(outputFile) ? outputFile : path.resolve(outputFile);
467
+ const html = buildPortfolioHtml(repoResults);
468
+ fs.mkdirSync(path.dirname(outputPath), { recursive: true });
469
+ fs.writeFileSync(outputPath, html, 'utf8');
470
+
471
+ const avgScore = Math.round(repoResults.reduce((s, r) => s + r.score, 0) / repoResults.length);
472
+ if (!flags.json) {
473
+ console.log('');
474
+ console.log(' nerviq portfolio dashboard');
475
+ console.log(' \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550');
476
+ console.log(` Repos: ${repoResults.length}`);
477
+ console.log(` Average live audit score: ${avgScore}/100`);
478
+ console.log(` Output: ${outputPath}`);
479
+ console.log('');
480
+ }
481
+
482
+ if (flags.open) {
483
+ const { exec } = require('child_process');
484
+ const cmd = process.platform === 'win32' ? `start "" "${outputPath}"`
485
+ : process.platform === 'darwin' ? `open "${outputPath}"`
486
+ : `xdg-open "${outputPath}"`;
487
+ exec(cmd);
488
+ }
489
+
490
+ return { outputPath, repoCount: repoResults.length, avgScore, repos: repoResults };
491
+ }
492
+
493
+ module.exports = { generateDashboard, generatePortfolioDashboard, detectDrifts, buildDriftAlertsHtml };