@nerviq/cli 1.8.6 → 1.8.8

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.
@@ -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/claudex-setup/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
+ };