@nerviq/cli 1.29.0 → 1.30.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 (93) hide show
  1. package/CHANGELOG.md +1764 -1493
  2. package/README.md +568 -538
  3. package/SECURITY.md +78 -82
  4. package/bin/cli.js +2838 -2558
  5. package/docs/api-reference.md +356 -356
  6. package/docs/audit-fix.md +109 -0
  7. package/docs/autofix.md +3 -62
  8. package/docs/getting-started.md +1 -1
  9. package/docs/index.html +592 -592
  10. package/docs/integration-contracts.md +287 -287
  11. package/docs/maintenance.md +128 -128
  12. package/docs/new-platform-guide.md +202 -202
  13. package/docs/release-process.md +63 -0
  14. package/docs/shallow-risk.md +244 -244
  15. package/docs/why-nerviq.md +82 -82
  16. package/package.json +75 -67
  17. package/sdk/README.md +12 -3
  18. package/sdk/examples/langchain-integration.md +128 -0
  19. package/sdk/examples/self-governing-agent.js +135 -0
  20. package/sdk/index.d.ts +115 -0
  21. package/sdk/index.js +94 -0
  22. package/sdk/package.json +11 -0
  23. package/src/activity.js +13 -0
  24. package/src/aider/activity.js +226 -226
  25. package/src/aider/context.js +162 -162
  26. package/src/aider/freshness.js +123 -123
  27. package/src/aider/techniques.js +3465 -3465
  28. package/src/audit/layers.js +180 -180
  29. package/src/audit.js +1133 -1032
  30. package/src/auto-suggest.js +9 -2
  31. package/src/behavioral-drift.js +37 -2
  32. package/src/benchmark.js +299 -299
  33. package/src/codex/activity.js +324 -324
  34. package/src/codex/freshness.js +149 -142
  35. package/src/codex/techniques.js +4895 -4895
  36. package/src/context.js +326 -326
  37. package/src/continuous-ops.js +11 -1
  38. package/src/convert.js +340 -340
  39. package/src/copilot/config-parser.js +280 -280
  40. package/src/copilot/context.js +218 -218
  41. package/src/copilot/freshness.js +184 -177
  42. package/src/copilot/patch.js +238 -238
  43. package/src/copilot/techniques.js +3578 -3578
  44. package/src/cursor/freshness.js +194 -194
  45. package/src/cursor/patch.js +243 -243
  46. package/src/cursor/techniques.js +3735 -3735
  47. package/src/doctor.js +201 -201
  48. package/src/fix-engine.js +511 -8
  49. package/src/formatters/csv.js +86 -86
  50. package/src/formatters/junit.js +123 -123
  51. package/src/formatters/markdown.js +164 -164
  52. package/src/formatters/otel.js +151 -151
  53. package/src/freshness.js +163 -156
  54. package/src/gemini/activity.js +402 -402
  55. package/src/gemini/context.js +290 -290
  56. package/src/gemini/freshness.js +188 -188
  57. package/src/gemini/patch.js +229 -229
  58. package/src/gemini/techniques.js +3811 -3811
  59. package/src/governance.js +533 -533
  60. package/src/harmony/audit.js +306 -306
  61. package/src/i18n.js +63 -63
  62. package/src/insights.js +119 -119
  63. package/src/integrations.js +134 -134
  64. package/src/locales/en.json +33 -33
  65. package/src/locales/es.json +33 -33
  66. package/src/migrate.js +354 -354
  67. package/src/opencode/activity.js +286 -286
  68. package/src/opencode/freshness.js +137 -137
  69. package/src/opencode/techniques.js +3450 -3450
  70. package/src/safe-glyph.js +97 -0
  71. package/src/setup/analysis.js +12 -12
  72. package/src/setup.js +13 -6
  73. package/src/shallow-risk/index.js +113 -56
  74. package/src/shallow-risk/patterns/agent-config-cross-platform-drift.js +51 -50
  75. package/src/shallow-risk/patterns/agent-config-dangerous-autoapprove.js +47 -46
  76. package/src/shallow-risk/patterns/agent-config-deprecated-keys.js +47 -46
  77. package/src/shallow-risk/patterns/agent-config-framework-version-mismatch.js +138 -0
  78. package/src/shallow-risk/patterns/agent-config-missing-file.js +318 -317
  79. package/src/shallow-risk/patterns/agent-config-script-not-in-package-json.js +108 -0
  80. package/src/shallow-risk/patterns/agent-config-secret-literal.js +52 -49
  81. package/src/shallow-risk/patterns/agent-config-stack-contradiction.js +35 -34
  82. package/src/shallow-risk/patterns/hook-script-missing.js +71 -70
  83. package/src/shallow-risk/patterns/mcp-server-no-allowlist.js +53 -52
  84. package/src/shallow-risk/shared.js +653 -648
  85. package/src/source-urls.js +295 -295
  86. package/src/state-paths.js +85 -85
  87. package/src/supplemental-checks.js +805 -805
  88. package/src/telemetry.js +160 -160
  89. package/src/watch.js +46 -0
  90. package/src/windsurf/context.js +359 -359
  91. package/src/windsurf/freshness.js +194 -194
  92. package/src/windsurf/patch.js +231 -231
  93. package/src/windsurf/techniques.js +3779 -3779
@@ -1,402 +1,402 @@
1
- /**
2
- * Gemini Repeat-Usage Surfaces
3
- *
4
- * Adapts the shared activity/snapshot backend for Gemini CLI platform.
5
- * Provides: history, compare, trend, feedback, insights.
6
- *
7
- * Gemini snapshots are stored alongside Claude snapshots in
8
- * .nerviq/snapshots/ (legacy: .claude/nerviq-cli/snapshots/) but filtered by platform='gemini'.
9
- */
10
-
11
- const path = require('path');
12
- const {
13
- readSnapshotIndex,
14
- recordRecommendationOutcome,
15
- readOutcomeIndex,
16
- summarizeOutcomeEntries,
17
- } = require('../activity');
18
- const { version } = require('../../package.json');
19
-
20
- // --- History ---
21
-
22
- /**
23
- * Get Gemini audit history from snapshots.
24
- * Filters to platform='gemini' snapshots only.
25
- */
26
- function getGeminiHistory(dir, limit = 20) {
27
- const entries = readSnapshotIndex(dir);
28
- return entries
29
- .filter(e => e.snapshotKind === 'audit' && (e.platform === 'gemini' || e.summary?.platform === 'gemini'))
30
- .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
31
- .slice(0, limit);
32
- }
33
-
34
- function formatGeminiHistory(dir) {
35
- const history = getGeminiHistory(dir, 10);
36
- if (history.length === 0) {
37
- return 'No Gemini snapshots found. Run `npx nerviq --platform gemini --snapshot` to save one.';
38
- }
39
-
40
- const lines = ['Gemini Score History (most recent first):', ''];
41
- for (const entry of history) {
42
- const date = entry.createdAt?.split('T')[0] || 'unknown';
43
- const score = entry.summary?.score ?? '?';
44
- const passed = entry.summary?.passed ?? '?';
45
- const total = entry.summary?.checkCount ?? '?';
46
- lines.push(` ${date} ${score}/100 (${passed}/${total} passing)`);
47
- }
48
-
49
- const comparison = compareGeminiLatest(dir);
50
- if (comparison) {
51
- lines.push('');
52
- const sign = comparison.delta.score >= 0 ? '+' : '';
53
- lines.push(` Trend: ${comparison.trend} (${sign}${comparison.delta.score} since previous)`);
54
- if (comparison.improvements.length > 0) {
55
- lines.push(` Fixed: ${comparison.improvements.join(', ')}`);
56
- }
57
- if (comparison.regressions.length > 0) {
58
- lines.push(` New gaps: ${comparison.regressions.join(', ')}`);
59
- }
60
- }
61
-
62
- return lines.join('\n');
63
- }
64
-
65
- // --- Compare ---
66
-
67
- /**
68
- * Compare the two most recent Gemini audit snapshots.
69
- */
70
- function compareGeminiLatest(dir) {
71
- const audits = getGeminiHistory(dir, 2);
72
- if (audits.length < 2) return null;
73
-
74
- const current = audits[0];
75
- const previous = audits[1];
76
-
77
- const delta = {
78
- score: (current.summary?.score || 0) - (previous.summary?.score || 0),
79
- organic: (current.summary?.organicScore || 0) - (previous.summary?.organicScore || 0),
80
- passed: (current.summary?.passed || 0) - (previous.summary?.passed || 0),
81
- };
82
-
83
- const regressions = [];
84
- const improvements = [];
85
-
86
- const prevKeys = new Set(previous.summary?.topActionKeys || []);
87
- const currKeys = new Set(current.summary?.topActionKeys || []);
88
-
89
- for (const key of currKeys) {
90
- if (!prevKeys.has(key)) regressions.push(key);
91
- }
92
- for (const key of prevKeys) {
93
- if (!currKeys.has(key)) improvements.push(key);
94
- }
95
-
96
- return {
97
- platform: 'gemini',
98
- current: { date: current.createdAt, score: current.summary?.score, passed: current.summary?.passed },
99
- previous: { date: previous.createdAt, score: previous.summary?.score, passed: previous.summary?.passed },
100
- delta,
101
- regressions,
102
- improvements,
103
- trend: delta.score > 0 ? 'improving' : delta.score < 0 ? 'regressing' : 'stable',
104
- };
105
- }
106
-
107
- // --- Trend ---
108
-
109
- /**
110
- * Export Gemini trend report as markdown.
111
- */
112
- function exportGeminiTrendReport(dir) {
113
- const history = getGeminiHistory(dir, 50);
114
- if (history.length === 0) return null;
115
-
116
- const comparison = compareGeminiLatest(dir);
117
- const lines = [
118
- '# Gemini CLI Setup Trend Report',
119
- '',
120
- `**Project:** ${path.basename(dir)}`,
121
- `**Platform:** Gemini CLI`,
122
- `**Generated:** ${new Date().toISOString().split('T')[0]}`,
123
- `**Snapshots:** ${history.length}`,
124
- '',
125
- '## Score History',
126
- '',
127
- '| Date | Score | Passed | Checks |',
128
- '|------|-------|--------|--------|',
129
- ];
130
-
131
- for (const entry of history) {
132
- const date = entry.createdAt?.split('T')[0] || '?';
133
- lines.push(`| ${date} | ${entry.summary?.score ?? '?'}/100 | ${entry.summary?.passed ?? '?'} | ${entry.summary?.checkCount ?? '?'} |`);
134
- }
135
-
136
- if (comparison) {
137
- lines.push('');
138
- lines.push('## Latest Comparison');
139
- lines.push('');
140
- lines.push(`- **Previous:** ${comparison.previous.score}/100 (${comparison.previous.date?.split('T')[0]})`);
141
- lines.push(`- **Current:** ${comparison.current.score}/100 (${comparison.current.date?.split('T')[0]})`);
142
- lines.push(`- **Delta:** ${comparison.delta.score >= 0 ? '+' : ''}${comparison.delta.score} points`);
143
- lines.push(`- **Trend:** ${comparison.trend}`);
144
- if (comparison.improvements.length > 0) lines.push(`- **Fixed:** ${comparison.improvements.join(', ')}`);
145
- if (comparison.regressions.length > 0) lines.push(`- **New gaps:** ${comparison.regressions.join(', ')}`);
146
- }
147
-
148
- // ASCII trend chart
149
- if (history.length >= 3) {
150
- lines.push('');
151
- lines.push('## Trend Chart');
152
- lines.push('');
153
- lines.push('```');
154
- const scores = history.slice().reverse().map(e => e.summary?.score ?? 0);
155
- const max = Math.max(...scores, 100);
156
- const chartHeight = 10;
157
- for (let row = chartHeight; row >= 0; row--) {
158
- const threshold = (row / chartHeight) * max;
159
- const rowLabel = String(Math.round(threshold)).padStart(3);
160
- const bar = scores.map(s => s >= threshold ? '#' : ' ').join('');
161
- lines.push(`${rowLabel} |${bar}`);
162
- }
163
- lines.push(` +${'─'.repeat(scores.length)}`);
164
- lines.push('```');
165
- }
166
-
167
- lines.push('');
168
- lines.push(`---`);
169
- lines.push(`*Generated by nerviq v${version} for Gemini CLI*`);
170
- return lines.join('\n');
171
- }
172
-
173
- // --- Feedback ---
174
-
175
- /**
176
- * Record feedback on a Gemini recommendation.
177
- */
178
- function recordGeminiFeedback(dir, payload) {
179
- return recordRecommendationOutcome(dir, {
180
- ...payload,
181
- source: payload.source || 'gemini-cli',
182
- platform: 'gemini',
183
- });
184
- }
185
-
186
- /**
187
- * Get Gemini feedback summary.
188
- */
189
- function getGeminiFeedbackSummary(dir) {
190
- const entries = readOutcomeIndex(dir)
191
- .filter(e => e.source === 'gemini-cli' || e.platform === 'gemini');
192
- return summarizeOutcomeEntries(entries);
193
- }
194
-
195
- function formatGeminiFeedback(dir) {
196
- const summary = getGeminiFeedbackSummary(dir);
197
- if (!summary || Object.keys(summary).length === 0) {
198
- return 'No Gemini feedback recorded yet. Use `npx nerviq --platform gemini feedback` to rate recommendations.';
199
- }
200
-
201
- const lines = ['Gemini Recommendation Feedback:', ''];
202
- const entries = Array.isArray(summary) ? summary : Object.values(summary);
203
- for (const entry of entries) {
204
- const key = entry.key || 'unknown';
205
- const accepted = entry.accepted || 0;
206
- const rejected = entry.rejected || 0;
207
- const total = entry.total || 0;
208
- lines.push(` ${key}: ${accepted} accepted, ${rejected} rejected (${total} total)`);
209
- }
210
- return lines.join('\n');
211
- }
212
-
213
- // --- Insights ---
214
-
215
- /**
216
- * Generate Gemini-specific insights from audit history and feedback.
217
- * Includes Gemini-unique patterns: sandbox-drift, policy-complexity,
218
- * caveat-persistence, trust-class-stagnation.
219
- */
220
- function generateGeminiInsights(dir) {
221
- const history = getGeminiHistory(dir, 50);
222
- const feedback = getGeminiFeedbackSummary(dir);
223
- const insights = [];
224
-
225
- // Pattern 1: Persistent failures
226
- if (history.length >= 3) {
227
- const recentFailKeys = new Map();
228
- for (const entry of history.slice(0, 5)) {
229
- for (const key of (entry.summary?.topActionKeys || [])) {
230
- recentFailKeys.set(key, (recentFailKeys.get(key) || 0) + 1);
231
- }
232
- }
233
- for (const [key, count] of recentFailKeys) {
234
- if (count >= 3) {
235
- insights.push({
236
- type: 'persistent-failure',
237
- severity: 'high',
238
- key,
239
- message: `Check ${key} has failed in ${count} of the last ${Math.min(history.length, 5)} audits. Consider addressing it or marking it as intentionally skipped.`,
240
- });
241
- }
242
- }
243
- }
244
-
245
- // Pattern 2: Score regression
246
- if (history.length >= 2) {
247
- const scores = history.map(e => e.summary?.score ?? 0);
248
- if (scores[0] < scores[1]) {
249
- insights.push({
250
- type: 'regression-pattern',
251
- severity: 'medium',
252
- message: `Score dropped from ${scores[1]} to ${scores[0]} in the most recent audit. Review recent changes.`,
253
- delta: scores[0] - scores[1],
254
- });
255
- }
256
- }
257
-
258
- // Pattern 3: Improvement velocity stall
259
- if (history.length >= 5) {
260
- const recentScores = history.slice(0, 5).map(e => e.summary?.score ?? 0);
261
- const range = Math.max(...recentScores) - Math.min(...recentScores);
262
- if (range <= 2) {
263
- insights.push({
264
- type: 'velocity-stall',
265
- severity: 'low',
266
- message: `Score has been flat (range: ${range} points) over the last 5 audits. Consider addressing lower-priority checks.`,
267
- });
268
- }
269
- }
270
-
271
- // Pattern 4: Feedback signals
272
- const feedbackEntries = Array.isArray(feedback) ? feedback : Object.values(feedback || {});
273
- for (const entry of feedbackEntries) {
274
- if (entry.rejected > entry.accepted && entry.total >= 2) {
275
- insights.push({
276
- type: 'feedback-signal',
277
- severity: 'medium',
278
- key: entry.key,
279
- message: `Recommendation ${entry.key} has been rejected more than accepted (${entry.rejected}/${entry.total}). Consider adjusting or removing this recommendation.`,
280
- });
281
- }
282
- }
283
-
284
- // Gemini-specific Pattern 5: Sandbox drift
285
- if (history.length >= 3) {
286
- const sandboxKeys = [];
287
- for (const entry of history.slice(0, 5)) {
288
- for (const key of (entry.summary?.topActionKeys || [])) {
289
- if (key.includes('sandbox') || key.includes('isolation')) {
290
- sandboxKeys.push(key);
291
- }
292
- }
293
- }
294
- if (sandboxKeys.length >= 2) {
295
- insights.push({
296
- type: 'sandbox-drift',
297
- severity: 'high',
298
- message: `Sandbox-related checks have appeared in ${sandboxKeys.length} recent audits. Gemini sandbox configuration may be drifting from recommended posture.`,
299
- keys: [...new Set(sandboxKeys)],
300
- });
301
- }
302
- }
303
-
304
- // Gemini-specific Pattern 6: Policy complexity
305
- if (history.length >= 2) {
306
- const latest = history[0];
307
- const policyKeys = (latest.summary?.topActionKeys || []).filter(
308
- k => k.includes('policy') || k.includes('governance') || k.includes('rule')
309
- );
310
- if (policyKeys.length >= 3) {
311
- insights.push({
312
- type: 'policy-complexity',
313
- severity: 'medium',
314
- message: `${policyKeys.length} policy/governance checks are failing simultaneously. Gemini policy configuration may be overly complex or misconfigured.`,
315
- keys: policyKeys,
316
- });
317
- }
318
- }
319
-
320
- // Gemini-specific Pattern 7: Caveat persistence
321
- if (history.length >= 3) {
322
- const caveatKeys = new Map();
323
- for (const entry of history.slice(0, 5)) {
324
- for (const key of (entry.summary?.topActionKeys || [])) {
325
- if (key.includes('caveat') || key.includes('warning') || key.includes('limitation')) {
326
- caveatKeys.set(key, (caveatKeys.get(key) || 0) + 1);
327
- }
328
- }
329
- }
330
- for (const [key, count] of caveatKeys) {
331
- if (count >= 3) {
332
- insights.push({
333
- type: 'caveat-persistence',
334
- severity: 'medium',
335
- key,
336
- message: `Caveat/limitation ${key} has persisted across ${count} audits. This may indicate a Gemini CLI limitation that should be documented or worked around.`,
337
- });
338
- }
339
- }
340
- }
341
-
342
- // Gemini-specific Pattern 8: Trust class stagnation
343
- if (history.length >= 5) {
344
- const trustKeys = new Map();
345
- for (const entry of history.slice(0, 5)) {
346
- for (const key of (entry.summary?.topActionKeys || [])) {
347
- if (key.includes('trust') || key.includes('approval') || key.includes('permission')) {
348
- trustKeys.set(key, (trustKeys.get(key) || 0) + 1);
349
- }
350
- }
351
- }
352
- for (const [key, count] of trustKeys) {
353
- if (count >= 4) {
354
- insights.push({
355
- type: 'trust-class-stagnation',
356
- severity: 'medium',
357
- key,
358
- message: `Trust/permission check ${key} has been failing in ${count} of the last 5 audits. Gemini trust classification may need elevation or explicit override.`,
359
- });
360
- }
361
- }
362
- }
363
-
364
- return {
365
- platform: 'gemini',
366
- generatedAt: new Date().toISOString(),
367
- snapshotCount: history.length,
368
- feedbackCount: feedbackEntries.length,
369
- insights,
370
- summary: insights.length === 0
371
- ? 'No actionable insights detected. Keep running audits to build pattern data.'
372
- : `${insights.length} insight(s) detected across ${history.length} snapshots.`,
373
- };
374
- }
375
-
376
- function formatGeminiInsights(dir) {
377
- const result = generateGeminiInsights(dir);
378
- if (result.insights.length === 0) {
379
- return result.summary;
380
- }
381
-
382
- const lines = ['Gemini Insights:', ''];
383
- for (const insight of result.insights) {
384
- const severity = insight.severity.toUpperCase();
385
- lines.push(` [${severity}] ${insight.message}`);
386
- }
387
- lines.push('');
388
- lines.push(result.summary);
389
- return lines.join('\n');
390
- }
391
-
392
- module.exports = {
393
- getGeminiHistory,
394
- formatGeminiHistory,
395
- compareGeminiLatest,
396
- exportGeminiTrendReport,
397
- recordGeminiFeedback,
398
- getGeminiFeedbackSummary,
399
- formatGeminiFeedback,
400
- generateGeminiInsights,
401
- formatGeminiInsights,
402
- };
1
+ /**
2
+ * Gemini Repeat-Usage Surfaces
3
+ *
4
+ * Adapts the shared activity/snapshot backend for Gemini CLI platform.
5
+ * Provides: history, compare, trend, feedback, insights.
6
+ *
7
+ * Gemini snapshots are stored alongside Claude snapshots in
8
+ * .nerviq/snapshots/ (legacy: .claude/nerviq-cli/snapshots/) but filtered by platform='gemini'.
9
+ */
10
+
11
+ const path = require('path');
12
+ const {
13
+ readSnapshotIndex,
14
+ recordRecommendationOutcome,
15
+ readOutcomeIndex,
16
+ summarizeOutcomeEntries,
17
+ } = require('../activity');
18
+ const { version } = require('../../package.json');
19
+
20
+ // --- History ---
21
+
22
+ /**
23
+ * Get Gemini audit history from snapshots.
24
+ * Filters to platform='gemini' snapshots only.
25
+ */
26
+ function getGeminiHistory(dir, limit = 20) {
27
+ const entries = readSnapshotIndex(dir);
28
+ return entries
29
+ .filter(e => e.snapshotKind === 'audit' && (e.platform === 'gemini' || e.summary?.platform === 'gemini'))
30
+ .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
31
+ .slice(0, limit);
32
+ }
33
+
34
+ function formatGeminiHistory(dir) {
35
+ const history = getGeminiHistory(dir, 10);
36
+ if (history.length === 0) {
37
+ return 'No Gemini snapshots found. Run `npx nerviq --platform gemini --snapshot` to save one.';
38
+ }
39
+
40
+ const lines = ['Gemini Score History (most recent first):', ''];
41
+ for (const entry of history) {
42
+ const date = entry.createdAt?.split('T')[0] || 'unknown';
43
+ const score = entry.summary?.score ?? '?';
44
+ const passed = entry.summary?.passed ?? '?';
45
+ const total = entry.summary?.checkCount ?? '?';
46
+ lines.push(` ${date} ${score}/100 (${passed}/${total} passing)`);
47
+ }
48
+
49
+ const comparison = compareGeminiLatest(dir);
50
+ if (comparison) {
51
+ lines.push('');
52
+ const sign = comparison.delta.score >= 0 ? '+' : '';
53
+ lines.push(` Trend: ${comparison.trend} (${sign}${comparison.delta.score} since previous)`);
54
+ if (comparison.improvements.length > 0) {
55
+ lines.push(` Fixed: ${comparison.improvements.join(', ')}`);
56
+ }
57
+ if (comparison.regressions.length > 0) {
58
+ lines.push(` New gaps: ${comparison.regressions.join(', ')}`);
59
+ }
60
+ }
61
+
62
+ return lines.join('\n');
63
+ }
64
+
65
+ // --- Compare ---
66
+
67
+ /**
68
+ * Compare the two most recent Gemini audit snapshots.
69
+ */
70
+ function compareGeminiLatest(dir) {
71
+ const audits = getGeminiHistory(dir, 2);
72
+ if (audits.length < 2) return null;
73
+
74
+ const current = audits[0];
75
+ const previous = audits[1];
76
+
77
+ const delta = {
78
+ score: (current.summary?.score || 0) - (previous.summary?.score || 0),
79
+ organic: (current.summary?.organicScore || 0) - (previous.summary?.organicScore || 0),
80
+ passed: (current.summary?.passed || 0) - (previous.summary?.passed || 0),
81
+ };
82
+
83
+ const regressions = [];
84
+ const improvements = [];
85
+
86
+ const prevKeys = new Set(previous.summary?.topActionKeys || []);
87
+ const currKeys = new Set(current.summary?.topActionKeys || []);
88
+
89
+ for (const key of currKeys) {
90
+ if (!prevKeys.has(key)) regressions.push(key);
91
+ }
92
+ for (const key of prevKeys) {
93
+ if (!currKeys.has(key)) improvements.push(key);
94
+ }
95
+
96
+ return {
97
+ platform: 'gemini',
98
+ current: { date: current.createdAt, score: current.summary?.score, passed: current.summary?.passed },
99
+ previous: { date: previous.createdAt, score: previous.summary?.score, passed: previous.summary?.passed },
100
+ delta,
101
+ regressions,
102
+ improvements,
103
+ trend: delta.score > 0 ? 'improving' : delta.score < 0 ? 'regressing' : 'stable',
104
+ };
105
+ }
106
+
107
+ // --- Trend ---
108
+
109
+ /**
110
+ * Export Gemini trend report as markdown.
111
+ */
112
+ function exportGeminiTrendReport(dir) {
113
+ const history = getGeminiHistory(dir, 50);
114
+ if (history.length === 0) return null;
115
+
116
+ const comparison = compareGeminiLatest(dir);
117
+ const lines = [
118
+ '# Gemini CLI Setup Trend Report',
119
+ '',
120
+ `**Project:** ${path.basename(dir)}`,
121
+ `**Platform:** Gemini CLI`,
122
+ `**Generated:** ${new Date().toISOString().split('T')[0]}`,
123
+ `**Snapshots:** ${history.length}`,
124
+ '',
125
+ '## Score History',
126
+ '',
127
+ '| Date | Score | Passed | Checks |',
128
+ '|------|-------|--------|--------|',
129
+ ];
130
+
131
+ for (const entry of history) {
132
+ const date = entry.createdAt?.split('T')[0] || '?';
133
+ lines.push(`| ${date} | ${entry.summary?.score ?? '?'}/100 | ${entry.summary?.passed ?? '?'} | ${entry.summary?.checkCount ?? '?'} |`);
134
+ }
135
+
136
+ if (comparison) {
137
+ lines.push('');
138
+ lines.push('## Latest Comparison');
139
+ lines.push('');
140
+ lines.push(`- **Previous:** ${comparison.previous.score}/100 (${comparison.previous.date?.split('T')[0]})`);
141
+ lines.push(`- **Current:** ${comparison.current.score}/100 (${comparison.current.date?.split('T')[0]})`);
142
+ lines.push(`- **Delta:** ${comparison.delta.score >= 0 ? '+' : ''}${comparison.delta.score} points`);
143
+ lines.push(`- **Trend:** ${comparison.trend}`);
144
+ if (comparison.improvements.length > 0) lines.push(`- **Fixed:** ${comparison.improvements.join(', ')}`);
145
+ if (comparison.regressions.length > 0) lines.push(`- **New gaps:** ${comparison.regressions.join(', ')}`);
146
+ }
147
+
148
+ // ASCII trend chart
149
+ if (history.length >= 3) {
150
+ lines.push('');
151
+ lines.push('## Trend Chart');
152
+ lines.push('');
153
+ lines.push('```');
154
+ const scores = history.slice().reverse().map(e => e.summary?.score ?? 0);
155
+ const max = Math.max(...scores, 100);
156
+ const chartHeight = 10;
157
+ for (let row = chartHeight; row >= 0; row--) {
158
+ const threshold = (row / chartHeight) * max;
159
+ const rowLabel = String(Math.round(threshold)).padStart(3);
160
+ const bar = scores.map(s => s >= threshold ? '#' : ' ').join('');
161
+ lines.push(`${rowLabel} |${bar}`);
162
+ }
163
+ lines.push(` +${'─'.repeat(scores.length)}`);
164
+ lines.push('```');
165
+ }
166
+
167
+ lines.push('');
168
+ lines.push(`---`);
169
+ lines.push(`*Generated by nerviq v${version} for Gemini CLI*`);
170
+ return lines.join('\n');
171
+ }
172
+
173
+ // --- Feedback ---
174
+
175
+ /**
176
+ * Record feedback on a Gemini recommendation.
177
+ */
178
+ function recordGeminiFeedback(dir, payload) {
179
+ return recordRecommendationOutcome(dir, {
180
+ ...payload,
181
+ source: payload.source || 'gemini-cli',
182
+ platform: 'gemini',
183
+ });
184
+ }
185
+
186
+ /**
187
+ * Get Gemini feedback summary.
188
+ */
189
+ function getGeminiFeedbackSummary(dir) {
190
+ const entries = readOutcomeIndex(dir)
191
+ .filter(e => e.source === 'gemini-cli' || e.platform === 'gemini');
192
+ return summarizeOutcomeEntries(entries);
193
+ }
194
+
195
+ function formatGeminiFeedback(dir) {
196
+ const summary = getGeminiFeedbackSummary(dir);
197
+ if (!summary || Object.keys(summary).length === 0) {
198
+ return 'No Gemini feedback recorded yet. Use `npx nerviq --platform gemini feedback` to rate recommendations.';
199
+ }
200
+
201
+ const lines = ['Gemini Recommendation Feedback:', ''];
202
+ const entries = Array.isArray(summary) ? summary : Object.values(summary);
203
+ for (const entry of entries) {
204
+ const key = entry.key || 'unknown';
205
+ const accepted = entry.accepted || 0;
206
+ const rejected = entry.rejected || 0;
207
+ const total = entry.total || 0;
208
+ lines.push(` ${key}: ${accepted} accepted, ${rejected} rejected (${total} total)`);
209
+ }
210
+ return lines.join('\n');
211
+ }
212
+
213
+ // --- Insights ---
214
+
215
+ /**
216
+ * Generate Gemini-specific insights from audit history and feedback.
217
+ * Includes Gemini-unique patterns: sandbox-drift, policy-complexity,
218
+ * caveat-persistence, trust-class-stagnation.
219
+ */
220
+ function generateGeminiInsights(dir) {
221
+ const history = getGeminiHistory(dir, 50);
222
+ const feedback = getGeminiFeedbackSummary(dir);
223
+ const insights = [];
224
+
225
+ // Pattern 1: Persistent failures
226
+ if (history.length >= 3) {
227
+ const recentFailKeys = new Map();
228
+ for (const entry of history.slice(0, 5)) {
229
+ for (const key of (entry.summary?.topActionKeys || [])) {
230
+ recentFailKeys.set(key, (recentFailKeys.get(key) || 0) + 1);
231
+ }
232
+ }
233
+ for (const [key, count] of recentFailKeys) {
234
+ if (count >= 3) {
235
+ insights.push({
236
+ type: 'persistent-failure',
237
+ severity: 'high',
238
+ key,
239
+ message: `Check ${key} has failed in ${count} of the last ${Math.min(history.length, 5)} audits. Consider addressing it or marking it as intentionally skipped.`,
240
+ });
241
+ }
242
+ }
243
+ }
244
+
245
+ // Pattern 2: Score regression
246
+ if (history.length >= 2) {
247
+ const scores = history.map(e => e.summary?.score ?? 0);
248
+ if (scores[0] < scores[1]) {
249
+ insights.push({
250
+ type: 'regression-pattern',
251
+ severity: 'medium',
252
+ message: `Score dropped from ${scores[1]} to ${scores[0]} in the most recent audit. Review recent changes.`,
253
+ delta: scores[0] - scores[1],
254
+ });
255
+ }
256
+ }
257
+
258
+ // Pattern 3: Improvement velocity stall
259
+ if (history.length >= 5) {
260
+ const recentScores = history.slice(0, 5).map(e => e.summary?.score ?? 0);
261
+ const range = Math.max(...recentScores) - Math.min(...recentScores);
262
+ if (range <= 2) {
263
+ insights.push({
264
+ type: 'velocity-stall',
265
+ severity: 'low',
266
+ message: `Score has been flat (range: ${range} points) over the last 5 audits. Consider addressing lower-priority checks.`,
267
+ });
268
+ }
269
+ }
270
+
271
+ // Pattern 4: Feedback signals
272
+ const feedbackEntries = Array.isArray(feedback) ? feedback : Object.values(feedback || {});
273
+ for (const entry of feedbackEntries) {
274
+ if (entry.rejected > entry.accepted && entry.total >= 2) {
275
+ insights.push({
276
+ type: 'feedback-signal',
277
+ severity: 'medium',
278
+ key: entry.key,
279
+ message: `Recommendation ${entry.key} has been rejected more than accepted (${entry.rejected}/${entry.total}). Consider adjusting or removing this recommendation.`,
280
+ });
281
+ }
282
+ }
283
+
284
+ // Gemini-specific Pattern 5: Sandbox drift
285
+ if (history.length >= 3) {
286
+ const sandboxKeys = [];
287
+ for (const entry of history.slice(0, 5)) {
288
+ for (const key of (entry.summary?.topActionKeys || [])) {
289
+ if (key.includes('sandbox') || key.includes('isolation')) {
290
+ sandboxKeys.push(key);
291
+ }
292
+ }
293
+ }
294
+ if (sandboxKeys.length >= 2) {
295
+ insights.push({
296
+ type: 'sandbox-drift',
297
+ severity: 'high',
298
+ message: `Sandbox-related checks have appeared in ${sandboxKeys.length} recent audits. Gemini sandbox configuration may be drifting from recommended posture.`,
299
+ keys: [...new Set(sandboxKeys)],
300
+ });
301
+ }
302
+ }
303
+
304
+ // Gemini-specific Pattern 6: Policy complexity
305
+ if (history.length >= 2) {
306
+ const latest = history[0];
307
+ const policyKeys = (latest.summary?.topActionKeys || []).filter(
308
+ k => k.includes('policy') || k.includes('governance') || k.includes('rule')
309
+ );
310
+ if (policyKeys.length >= 3) {
311
+ insights.push({
312
+ type: 'policy-complexity',
313
+ severity: 'medium',
314
+ message: `${policyKeys.length} policy/governance checks are failing simultaneously. Gemini policy configuration may be overly complex or misconfigured.`,
315
+ keys: policyKeys,
316
+ });
317
+ }
318
+ }
319
+
320
+ // Gemini-specific Pattern 7: Caveat persistence
321
+ if (history.length >= 3) {
322
+ const caveatKeys = new Map();
323
+ for (const entry of history.slice(0, 5)) {
324
+ for (const key of (entry.summary?.topActionKeys || [])) {
325
+ if (key.includes('caveat') || key.includes('warning') || key.includes('limitation')) {
326
+ caveatKeys.set(key, (caveatKeys.get(key) || 0) + 1);
327
+ }
328
+ }
329
+ }
330
+ for (const [key, count] of caveatKeys) {
331
+ if (count >= 3) {
332
+ insights.push({
333
+ type: 'caveat-persistence',
334
+ severity: 'medium',
335
+ key,
336
+ message: `Caveat/limitation ${key} has persisted across ${count} audits. This may indicate a Gemini CLI limitation that should be documented or worked around.`,
337
+ });
338
+ }
339
+ }
340
+ }
341
+
342
+ // Gemini-specific Pattern 8: Trust class stagnation
343
+ if (history.length >= 5) {
344
+ const trustKeys = new Map();
345
+ for (const entry of history.slice(0, 5)) {
346
+ for (const key of (entry.summary?.topActionKeys || [])) {
347
+ if (key.includes('trust') || key.includes('approval') || key.includes('permission')) {
348
+ trustKeys.set(key, (trustKeys.get(key) || 0) + 1);
349
+ }
350
+ }
351
+ }
352
+ for (const [key, count] of trustKeys) {
353
+ if (count >= 4) {
354
+ insights.push({
355
+ type: 'trust-class-stagnation',
356
+ severity: 'medium',
357
+ key,
358
+ message: `Trust/permission check ${key} has been failing in ${count} of the last 5 audits. Gemini trust classification may need elevation or explicit override.`,
359
+ });
360
+ }
361
+ }
362
+ }
363
+
364
+ return {
365
+ platform: 'gemini',
366
+ generatedAt: new Date().toISOString(),
367
+ snapshotCount: history.length,
368
+ feedbackCount: feedbackEntries.length,
369
+ insights,
370
+ summary: insights.length === 0
371
+ ? 'No actionable insights detected. Keep running audits to build pattern data.'
372
+ : `${insights.length} insight(s) detected across ${history.length} snapshots.`,
373
+ };
374
+ }
375
+
376
+ function formatGeminiInsights(dir) {
377
+ const result = generateGeminiInsights(dir);
378
+ if (result.insights.length === 0) {
379
+ return result.summary;
380
+ }
381
+
382
+ const lines = ['Gemini Insights:', ''];
383
+ for (const insight of result.insights) {
384
+ const severity = insight.severity.toUpperCase();
385
+ lines.push(` [${severity}] ${insight.message}`);
386
+ }
387
+ lines.push('');
388
+ lines.push(result.summary);
389
+ return lines.join('\n');
390
+ }
391
+
392
+ module.exports = {
393
+ getGeminiHistory,
394
+ formatGeminiHistory,
395
+ compareGeminiLatest,
396
+ exportGeminiTrendReport,
397
+ recordGeminiFeedback,
398
+ getGeminiFeedbackSummary,
399
+ formatGeminiFeedback,
400
+ generateGeminiInsights,
401
+ formatGeminiInsights,
402
+ };