@nerviq/cli 1.18.0 → 1.19.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 (187) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/bin/cli.js +130 -130
  4. package/package.json +1 -1
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +158 -158
  9. package/src/aider/deep-review.js +316 -316
  10. package/src/aider/domain-packs.js +303 -303
  11. package/src/aider/freshness.js +93 -93
  12. package/src/aider/governance.js +253 -253
  13. package/src/aider/interactive.js +334 -334
  14. package/src/aider/mcp-packs.js +329 -329
  15. package/src/aider/patch.js +214 -214
  16. package/src/aider/plans.js +186 -186
  17. package/src/aider/premium.js +360 -360
  18. package/src/aider/setup.js +404 -404
  19. package/src/aider/techniques.js +16 -16
  20. package/src/analyze.js +951 -951
  21. package/src/anti-patterns.js +485 -485
  22. package/src/audit/instruction-files.js +180 -180
  23. package/src/audit/recommendations.js +577 -577
  24. package/src/auto-suggest.js +154 -154
  25. package/src/badge.js +13 -13
  26. package/src/behavioral-drift.js +801 -801
  27. package/src/benchmark.js +67 -67
  28. package/src/catalog.js +103 -103
  29. package/src/certification.js +128 -128
  30. package/src/codex/config-parser.js +183 -183
  31. package/src/codex/context.js +223 -223
  32. package/src/codex/deep-review.js +493 -493
  33. package/src/codex/domain-packs.js +394 -394
  34. package/src/codex/freshness.js +84 -84
  35. package/src/codex/governance.js +192 -192
  36. package/src/codex/interactive.js +618 -618
  37. package/src/codex/mcp-packs.js +914 -914
  38. package/src/codex/patch.js +209 -209
  39. package/src/codex/plans.js +251 -251
  40. package/src/codex/premium.js +614 -614
  41. package/src/codex/setup.js +591 -591
  42. package/src/context.js +320 -320
  43. package/src/continuous-ops.js +681 -681
  44. package/src/copilot/activity.js +309 -309
  45. package/src/copilot/deep-review.js +346 -346
  46. package/src/copilot/domain-packs.js +372 -372
  47. package/src/copilot/freshness.js +57 -57
  48. package/src/copilot/governance.js +222 -222
  49. package/src/copilot/interactive.js +406 -406
  50. package/src/copilot/mcp-packs.js +826 -826
  51. package/src/copilot/plans.js +253 -253
  52. package/src/copilot/premium.js +451 -451
  53. package/src/copilot/setup.js +488 -488
  54. package/src/cost-tracking.js +61 -61
  55. package/src/cursor/activity.js +301 -301
  56. package/src/cursor/config-parser.js +265 -265
  57. package/src/cursor/context.js +256 -256
  58. package/src/cursor/deep-review.js +334 -334
  59. package/src/cursor/domain-packs.js +368 -368
  60. package/src/cursor/freshness.js +65 -65
  61. package/src/cursor/governance.js +229 -229
  62. package/src/cursor/interactive.js +391 -391
  63. package/src/cursor/mcp-packs.js +828 -828
  64. package/src/cursor/plans.js +254 -254
  65. package/src/cursor/premium.js +469 -469
  66. package/src/cursor/setup.js +488 -488
  67. package/src/dashboard.js +493 -493
  68. package/src/deep-review.js +428 -428
  69. package/src/deprecation.js +98 -98
  70. package/src/diff-only.js +280 -280
  71. package/src/doctor.js +119 -119
  72. package/src/domain-pack-expansion.js +1033 -1033
  73. package/src/domain-packs.js +387 -387
  74. package/src/feedback.js +178 -178
  75. package/src/fix-engine.js +783 -783
  76. package/src/fix-prompts.js +122 -122
  77. package/src/formatters/sarif.js +115 -115
  78. package/src/freshness.js +74 -74
  79. package/src/gemini/config-parser.js +275 -275
  80. package/src/gemini/context.js +221 -221
  81. package/src/gemini/deep-review.js +559 -559
  82. package/src/gemini/domain-packs.js +393 -393
  83. package/src/gemini/freshness.js +66 -66
  84. package/src/gemini/governance.js +201 -201
  85. package/src/gemini/interactive.js +860 -860
  86. package/src/gemini/mcp-packs.js +915 -915
  87. package/src/gemini/plans.js +269 -269
  88. package/src/gemini/premium.js +760 -760
  89. package/src/gemini/setup.js +692 -692
  90. package/src/gemini/techniques.js +14 -14
  91. package/src/governance.js +72 -72
  92. package/src/harmony/add.js +68 -68
  93. package/src/harmony/advisor.js +333 -333
  94. package/src/harmony/canon.js +565 -565
  95. package/src/harmony/cli.js +591 -591
  96. package/src/harmony/drift.js +401 -401
  97. package/src/harmony/governance.js +313 -313
  98. package/src/harmony/memory.js +239 -239
  99. package/src/harmony/sync.js +475 -475
  100. package/src/harmony/watch.js +370 -370
  101. package/src/hook-validation.js +342 -342
  102. package/src/index.js +271 -271
  103. package/src/init.js +184 -184
  104. package/src/instruction-surfaces.js +185 -185
  105. package/src/integrations.js +144 -144
  106. package/src/interactive.js +118 -118
  107. package/src/locales/en.json +1 -1
  108. package/src/locales/es.json +1 -1
  109. package/src/mcp-packs.js +830 -830
  110. package/src/mcp-server.js +726 -726
  111. package/src/mcp-validation.js +337 -337
  112. package/src/nerviq-sync.json +7 -7
  113. package/src/opencode/config-parser.js +109 -109
  114. package/src/opencode/context.js +247 -247
  115. package/src/opencode/deep-review.js +313 -313
  116. package/src/opencode/domain-packs.js +262 -262
  117. package/src/opencode/freshness.js +66 -66
  118. package/src/opencode/governance.js +159 -159
  119. package/src/opencode/interactive.js +392 -392
  120. package/src/opencode/mcp-packs.js +705 -705
  121. package/src/opencode/patch.js +184 -184
  122. package/src/opencode/plans.js +231 -231
  123. package/src/opencode/premium.js +413 -413
  124. package/src/opencode/setup.js +449 -449
  125. package/src/opencode/techniques.js +27 -27
  126. package/src/operating-profile.js +574 -574
  127. package/src/org.js +152 -152
  128. package/src/permission-rules.js +218 -218
  129. package/src/plans.js +839 -839
  130. package/src/platform-change-manifest.js +86 -86
  131. package/src/plugins.js +110 -110
  132. package/src/policy-layers.js +210 -210
  133. package/src/profiles.js +124 -124
  134. package/src/prompt-injection.js +74 -74
  135. package/src/public-api.js +173 -173
  136. package/src/recommendation-rules.js +84 -84
  137. package/src/repo-archetype.js +386 -386
  138. package/src/secret-patterns.js +39 -39
  139. package/src/server.js +527 -527
  140. package/src/setup/analysis.js +607 -607
  141. package/src/setup/runtime.js +172 -172
  142. package/src/setup.js +677 -677
  143. package/src/shared/capabilities.js +194 -194
  144. package/src/source-urls.js +132 -132
  145. package/src/stack-checks.js +565 -565
  146. package/src/supplemental-checks.js +13 -13
  147. package/src/synergy/adaptive.js +261 -261
  148. package/src/synergy/compensation.js +137 -137
  149. package/src/synergy/evidence.js +193 -193
  150. package/src/synergy/learning.js +199 -199
  151. package/src/synergy/patterns.js +227 -227
  152. package/src/synergy/ranking.js +83 -83
  153. package/src/synergy/report.js +165 -165
  154. package/src/synergy/routing.js +146 -146
  155. package/src/techniques/api.js +407 -407
  156. package/src/techniques/automation.js +316 -316
  157. package/src/techniques/compliance.js +257 -257
  158. package/src/techniques/hygiene.js +294 -294
  159. package/src/techniques/instructions.js +243 -243
  160. package/src/techniques/observability.js +226 -226
  161. package/src/techniques/optimization.js +142 -142
  162. package/src/techniques/quality.js +318 -318
  163. package/src/techniques/security.js +237 -237
  164. package/src/techniques/shared.js +443 -443
  165. package/src/techniques/stacks.js +2294 -2294
  166. package/src/techniques/tools.js +106 -106
  167. package/src/techniques/workflow.js +413 -413
  168. package/src/techniques.js +81 -81
  169. package/src/terminology.js +73 -73
  170. package/src/token-estimate.js +35 -35
  171. package/src/usage-patterns.js +99 -99
  172. package/src/verification-metadata.js +145 -145
  173. package/src/watch.js +247 -247
  174. package/src/windsurf/activity.js +302 -302
  175. package/src/windsurf/config-parser.js +267 -267
  176. package/src/windsurf/context.js +249 -249
  177. package/src/windsurf/deep-review.js +337 -337
  178. package/src/windsurf/domain-packs.js +370 -370
  179. package/src/windsurf/freshness.js +36 -36
  180. package/src/windsurf/governance.js +231 -231
  181. package/src/windsurf/interactive.js +388 -388
  182. package/src/windsurf/mcp-packs.js +792 -792
  183. package/src/windsurf/plans.js +247 -247
  184. package/src/windsurf/premium.js +468 -468
  185. package/src/windsurf/setup.js +471 -471
  186. package/src/windsurf/techniques.js +17 -17
  187. package/src/workspace.js +375 -375
@@ -1,760 +1,760 @@
1
- /**
2
- * Gemini CLI Premium Operator UX
3
- *
4
- * Three subsystems:
5
- * 1. Multi-Pack Composition Engine — merge domain + MCP + policy + extension packs with dedup, conflict resolution, dependency ordering
6
- * 2. CI Template Library — 5 GitHub Actions workflow templates for Gemini CLI automation (using run-gemini-cli action)
7
- * 3. Adoption Signal Gate — activate features based on local usage telemetry (5 gates)
8
- */
9
-
10
- const path = require('path');
11
- const { GEMINI_DOMAIN_PACKS } = require('./domain-packs');
12
- const { GEMINI_MCP_PACKS } = require('./mcp-packs');
13
- const { resolveGeminiStateReadPath } = require('../state-paths');
14
-
15
- // ---------------------------------------------------------------------------
16
- // 1. Multi-Pack Composition Engine
17
- // ---------------------------------------------------------------------------
18
-
19
- /** Pack dependency order — earlier = more foundational */
20
- const PACK_DEPENDENCY_ORDER = [
21
- 'baseline-general',
22
- 'backend-api',
23
- 'frontend-ui',
24
- 'infra-platform',
25
- 'monorepo',
26
- 'enterprise-governed',
27
- ];
28
-
29
- /** Specificity rank: higher = more specific, wins conflicts */
30
- const PACK_SPECIFICITY = {
31
- 'baseline-general': 0,
32
- 'backend-api': 2,
33
- 'frontend-ui': 2,
34
- 'infra-platform': 3,
35
- 'monorepo': 3,
36
- 'enterprise-governed': 4,
37
- };
38
-
39
- /** Policy pack definitions — Gemini-unique */
40
- const POLICY_PACKS = [
41
- {
42
- key: 'policy-file-restrictions',
43
- label: 'File Restrictions',
44
- description: 'Protect sensitive files from unreviewed edits.',
45
- policyContent: {
46
- 'file-restrictions': {
47
- deny_edit: ['.env', '.env.*', '*.pem', '*.key', 'credentials.*'],
48
- deny_delete: ['.env', '.env.*', '*.pem', '*.key', '*.lock'],
49
- read_only_dirs: ['.git', 'node_modules', '.gemini/policy'],
50
- },
51
- },
52
- },
53
- {
54
- key: 'policy-tool-restrictions',
55
- label: 'Tool Restrictions',
56
- description: 'Limit which tools the agent can invoke without approval.',
57
- policyContent: {
58
- 'tool-restrictions': {
59
- deny_tools: ['shell_exec_unsafe', 'network_raw'],
60
- require_approval: ['file_delete', 'git_push', 'deploy'],
61
- },
62
- },
63
- },
64
- {
65
- key: 'policy-governance',
66
- label: 'Governance',
67
- description: 'Strict audit and escalation policies for enterprise use.',
68
- policyContent: {
69
- governance: {
70
- audit_trail: true,
71
- escalation_on_deny: true,
72
- max_auto_edits_per_session: 50,
73
- require_justification_for: ['security-override', 'policy-bypass'],
74
- },
75
- },
76
- },
77
- ];
78
-
79
- /** Extension pack definitions — Gemini-unique */
80
- const EXTENSION_PACKS = [
81
- {
82
- key: 'ext-code-review',
83
- label: 'Code Review Extension',
84
- description: 'Structured code review with severity ratings and inline suggestions.',
85
- },
86
- {
87
- key: 'ext-test-gen',
88
- label: 'Test Generation Extension',
89
- description: 'Auto-generate test stubs for new or modified files.',
90
- },
91
- {
92
- key: 'ext-docs-sync',
93
- label: 'Docs Sync Extension',
94
- description: 'Detect stale documentation and suggest updates.',
95
- },
96
- ];
97
-
98
- const DEFAULT_SIZE_BUDGET = 16000; // characters for combined instruction content
99
-
100
- function lookupDomainPack(key) {
101
- return GEMINI_DOMAIN_PACKS.find(p => p.key === key) || null;
102
- }
103
-
104
- function lookupMcpPack(key) {
105
- return GEMINI_MCP_PACKS.find(p => p.key === key) || null;
106
- }
107
-
108
- function lookupPolicyPack(key) {
109
- return POLICY_PACKS.find(p => p.key === key) || null;
110
- }
111
-
112
- function lookupExtensionPack(key) {
113
- return EXTENSION_PACKS.find(p => p.key === key) || null;
114
- }
115
-
116
- /**
117
- * Compose domain packs, MCP packs, policy packs, and extension packs into a unified,
118
- * deduplicated, ordered result.
119
- *
120
- * @param {string[]} domainPackKeys - Array of domain pack keys to compose
121
- * @param {string[]} mcpPackKeys - Array of MCP pack keys to compose
122
- * @param {object} [options]
123
- * @param {number} [options.sizeBudget] - Max characters for combined instructions (default 16000)
124
- * @param {string[]} [options.policyPackKeys] - Array of policy pack keys (Gemini-unique)
125
- * @param {string[]} [options.extensionPackKeys] - Array of extension pack keys (Gemini-unique)
126
- * @returns {object} Composition report
127
- */
128
- function composePacks(domainPackKeys = [], mcpPackKeys = [], options = {}) {
129
- const sizeBudget = options.sizeBudget || DEFAULT_SIZE_BUDGET;
130
- const policyPackKeys = options.policyPackKeys || [];
131
- const extensionPackKeys = options.extensionPackKeys || [];
132
- const warnings = [];
133
-
134
- // --- Resolve domain packs ---
135
- const seenDomainKeys = new Set();
136
- const rawDomainPacks = [];
137
- for (const key of domainPackKeys) {
138
- if (seenDomainKeys.has(key)) continue;
139
- seenDomainKeys.add(key);
140
- const pack = lookupDomainPack(key);
141
- if (!pack) {
142
- warnings.push(`Domain pack "${key}" not found, skipped.`);
143
- continue;
144
- }
145
- rawDomainPacks.push(pack);
146
- }
147
-
148
- // Order by dependency (base -> framework -> tool-specific)
149
- rawDomainPacks.sort((a, b) => {
150
- const orderA = PACK_DEPENDENCY_ORDER.indexOf(a.key);
151
- const orderB = PACK_DEPENDENCY_ORDER.indexOf(b.key);
152
- return (orderA === -1 ? 99 : orderA) - (orderB === -1 ? 99 : orderB);
153
- });
154
-
155
- // Deduplicate overlapping recommendedModules; more specific pack wins
156
- const moduleOwner = new Map(); // module -> { key, specificity }
157
- for (const pack of rawDomainPacks) {
158
- const specificity = PACK_SPECIFICITY[pack.key] ?? 1;
159
- for (const mod of pack.recommendedModules || []) {
160
- const existing = moduleOwner.get(mod);
161
- if (!existing || specificity > existing.specificity) {
162
- moduleOwner.set(mod, { key: pack.key, specificity });
163
- }
164
- }
165
- }
166
-
167
- // Deduplicate surfaces
168
- const allSurfaces = new Set();
169
- for (const pack of rawDomainPacks) {
170
- for (const surface of pack.recommendedSurfaces || []) {
171
- allSurfaces.add(surface);
172
- }
173
- }
174
-
175
- // Deduplicate proposal families
176
- const allProposalFamilies = new Set();
177
- for (const pack of rawDomainPacks) {
178
- for (const family of pack.recommendedProposalFamilies || []) {
179
- allProposalFamilies.add(family);
180
- }
181
- }
182
-
183
- // --- Resolve MCP packs ---
184
- const seenMcpKeys = new Set();
185
- const resolvedMcpPacks = [];
186
- for (const key of mcpPackKeys) {
187
- if (seenMcpKeys.has(key)) continue;
188
- seenMcpKeys.add(key);
189
- const pack = lookupMcpPack(key);
190
- if (!pack) {
191
- warnings.push(`MCP pack "${key}" not found, skipped.`);
192
- continue;
193
- }
194
- resolvedMcpPacks.push(pack);
195
- }
196
-
197
- // Merge excludeTools across all MCP packs (union — Gemini uses deny-list, not allow-list)
198
- const mergedExcludeTools = new Set();
199
- for (const pack of resolvedMcpPacks) {
200
- for (const tool of pack.excludeTools || []) {
201
- mergedExcludeTools.add(tool);
202
- }
203
- }
204
-
205
- // Collect required auth (union)
206
- const mergedRequiredAuth = new Set();
207
- for (const pack of resolvedMcpPacks) {
208
- for (const auth of pack.requiredAuth || []) {
209
- mergedRequiredAuth.add(auth);
210
- }
211
- }
212
-
213
- // --- Resolve policy packs (Gemini-unique) ---
214
- const seenPolicyKeys = new Set();
215
- const resolvedPolicyPacks = [];
216
- const mergedPolicyContent = {};
217
- for (const key of policyPackKeys) {
218
- if (seenPolicyKeys.has(key)) continue;
219
- seenPolicyKeys.add(key);
220
- const pack = lookupPolicyPack(key);
221
- if (!pack) {
222
- warnings.push(`Policy pack "${key}" not found, skipped.`);
223
- continue;
224
- }
225
- resolvedPolicyPacks.push(pack);
226
- // Merge policy content sections
227
- if (pack.policyContent) {
228
- for (const [section, rules] of Object.entries(pack.policyContent)) {
229
- if (!mergedPolicyContent[section]) {
230
- mergedPolicyContent[section] = { ...rules };
231
- } else {
232
- // Merge arrays, overwrite scalars
233
- for (const [ruleKey, ruleValue] of Object.entries(rules)) {
234
- if (Array.isArray(ruleValue) && Array.isArray(mergedPolicyContent[section][ruleKey])) {
235
- const merged = new Set([...mergedPolicyContent[section][ruleKey], ...ruleValue]);
236
- mergedPolicyContent[section][ruleKey] = [...merged];
237
- } else {
238
- mergedPolicyContent[section][ruleKey] = ruleValue;
239
- }
240
- }
241
- }
242
- }
243
- }
244
- }
245
-
246
- // --- Resolve extension packs (Gemini-unique) ---
247
- const seenExtKeys = new Set();
248
- const resolvedExtensionPacks = [];
249
- for (const key of extensionPackKeys) {
250
- if (seenExtKeys.has(key)) continue;
251
- seenExtKeys.add(key);
252
- const pack = lookupExtensionPack(key);
253
- if (!pack) {
254
- warnings.push(`Extension pack "${key}" not found, skipped.`);
255
- continue;
256
- }
257
- resolvedExtensionPacks.push(pack);
258
- }
259
-
260
- // --- Size budget tracking ---
261
- const estimatedSize = estimateCompositionSize(rawDomainPacks, resolvedMcpPacks, resolvedPolicyPacks, resolvedExtensionPacks);
262
- const overBudget = estimatedSize > sizeBudget;
263
- if (overBudget) {
264
- warnings.push(
265
- `Combined instruction size (~${estimatedSize} chars) exceeds budget (${sizeBudget}). ` +
266
- `Consider removing lower-priority packs.`
267
- );
268
- }
269
-
270
- return {
271
- domainPacks: rawDomainPacks.map(p => ({
272
- key: p.key,
273
- label: p.label,
274
- modulesOwned: [...moduleOwner.entries()]
275
- .filter(([, owner]) => owner.key === p.key)
276
- .map(([mod]) => mod),
277
- })),
278
- mcpPacks: resolvedMcpPacks.map(p => ({
279
- key: p.key,
280
- label: p.label,
281
- serverName: p.serverName,
282
- trustLevel: p.trustLevel,
283
- })),
284
- policyPacks: resolvedPolicyPacks.map(p => ({
285
- key: p.key,
286
- label: p.label,
287
- description: p.description,
288
- })),
289
- extensionPacks: resolvedExtensionPacks.map(p => ({
290
- key: p.key,
291
- label: p.label,
292
- description: p.description,
293
- })),
294
- merged: {
295
- surfaces: [...allSurfaces],
296
- proposalFamilies: [...allProposalFamilies],
297
- modules: [...moduleOwner.entries()].map(([mod, owner]) => ({ module: mod, owner: owner.key })),
298
- excludeTools: [...mergedExcludeTools].sort(),
299
- requiredAuth: [...mergedRequiredAuth].sort(),
300
- policyContent: mergedPolicyContent,
301
- },
302
- budget: {
303
- estimatedSize,
304
- limit: sizeBudget,
305
- overBudget,
306
- utilization: Math.round((estimatedSize / sizeBudget) * 100),
307
- },
308
- warnings,
309
- };
310
- }
311
-
312
- function estimateCompositionSize(domainPacks, mcpPacks, policyPacks = [], extensionPacks = []) {
313
- let size = 0;
314
- for (const pack of domainPacks) {
315
- size += (pack.label || '').length + (pack.useWhen || '').length + (pack.adoption || '').length;
316
- size += JSON.stringify(pack.recommendedModules || []).length;
317
- size += JSON.stringify(pack.benchmarkFocus || []).length;
318
- }
319
- for (const pack of mcpPacks) {
320
- size += (pack.label || '').length + (pack.description || '').length;
321
- size += JSON.stringify(pack.jsonProjection || {}).length;
322
- size += JSON.stringify(pack.excludeTools || []).length;
323
- }
324
- for (const pack of policyPacks) {
325
- size += (pack.label || '').length + (pack.description || '').length;
326
- size += JSON.stringify(pack.policyContent || {}).length;
327
- }
328
- for (const pack of extensionPacks) {
329
- size += (pack.label || '').length + (pack.description || '').length;
330
- }
331
- return size;
332
- }
333
-
334
- // ---------------------------------------------------------------------------
335
- // 2. CI Template Library (5 templates using run-gemini-cli action)
336
- // ---------------------------------------------------------------------------
337
-
338
- const CI_TEMPLATES = [
339
- {
340
- key: 'gemini-pr-review',
341
- label: 'Gemini PR Review',
342
- filename: 'gemini-pr-review.yml',
343
- description: 'Runs Gemini CLI review on pull request diffs.',
344
- trigger: 'pull_request',
345
- },
346
- {
347
- key: 'gemini-issue-triage',
348
- label: 'Gemini Issue Triage',
349
- filename: 'gemini-issue-triage.yml',
350
- description: 'Classifies and labels new issues using Gemini CLI.',
351
- trigger: 'issues.opened',
352
- },
353
- {
354
- key: 'gemini-scheduled-audit',
355
- label: 'Gemini Scheduled Audit',
356
- filename: 'gemini-scheduled-audit.yml',
357
- description: 'Weekly deep review of the codebase with Gemini CLI.',
358
- trigger: 'schedule (cron)',
359
- },
360
- {
361
- key: 'gemini-test-gen',
362
- label: 'Gemini Test Generation',
363
- filename: 'gemini-test-gen.yml',
364
- description: 'Generates test stubs for newly added files using Gemini CLI.',
365
- trigger: 'pull_request',
366
- },
367
- {
368
- key: 'gemini-docs-sync',
369
- label: 'Gemini Docs Sync',
370
- filename: 'gemini-docs-sync.yml',
371
- description: 'Checks for documentation staleness using Gemini CLI.',
372
- trigger: 'schedule (cron)',
373
- },
374
- ];
375
-
376
- const TEMPLATE_CONTENT = {
377
- 'gemini-pr-review': `# Gemini PR Review — generated by nerviq
378
- # Runs Gemini CLI to review pull request diffs and post suggestions.
379
- #
380
- # CUSTOMIZE: Adjust the model, sandbox, and timeout to match your team.
381
-
382
- name: Gemini PR Review
383
-
384
- on:
385
- pull_request:
386
- types: [opened, synchronize]
387
-
388
- # CUSTOMIZE: Add path filters if you only want reviews on certain directories
389
- # paths: ['src/**', 'lib/**']
390
-
391
- permissions:
392
- contents: read
393
- pull-requests: write
394
-
395
- jobs:
396
- gemini-review:
397
- runs-on: ubuntu-latest
398
- timeout-minutes: 15 # CUSTOMIZE: Adjust timeout for your repo size
399
- env:
400
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
401
- # CUSTOMIZE: Set DRY_RUN=true to preview without posting comments
402
- DRY_RUN: \${{ inputs.dry_run || 'false' }}
403
- steps:
404
- - uses: actions/checkout@v4
405
- with:
406
- fetch-depth: 0
407
-
408
- - name: Run Gemini CLI Review
409
- uses: google/run-gemini-cli@v1
410
- with:
411
- prompt: |
412
- Review the following pull request diff for issues, improvements, and best practices.
413
- Focus on security, performance, and correctness.
414
- sandbox: docker
415
- env:
416
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
417
- `,
418
-
419
- 'gemini-issue-triage': `# Gemini Issue Triage — generated by nerviq
420
- # Classifies newly opened issues and applies labels using Gemini CLI.
421
- #
422
- # CUSTOMIZE: Edit the label mapping and classification prompt below.
423
-
424
- name: Gemini Issue Triage
425
-
426
- on:
427
- issues:
428
- types: [opened]
429
-
430
- permissions:
431
- issues: write
432
-
433
- jobs:
434
- triage:
435
- runs-on: ubuntu-latest
436
- timeout-minutes: 5 # CUSTOMIZE: Issues are small; 5 min is usually enough
437
- env:
438
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
439
- DRY_RUN: \${{ inputs.dry_run || 'false' }}
440
- steps:
441
- - uses: actions/checkout@v4
442
-
443
- - name: Classify Issue with Gemini
444
- uses: google/run-gemini-cli@v1
445
- with:
446
- prompt: |
447
- Classify this issue and suggest labels from: bug, feature, question, docs, security.
448
- Title: \${{ github.event.issue.title }}
449
- Body: \${{ github.event.issue.body }}
450
- sandbox: docker
451
- env:
452
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
453
- `,
454
-
455
- 'gemini-scheduled-audit': `# Gemini Scheduled Audit — generated by nerviq
456
- # Weekly deep review of the codebase using Gemini CLI.
457
- #
458
- # CUSTOMIZE: Adjust the cron schedule and audit scope.
459
-
460
- name: Gemini Scheduled Audit
461
-
462
- on:
463
- schedule:
464
- - cron: '0 9 * * 1' # CUSTOMIZE: Every Monday at 09:00 UTC
465
- workflow_dispatch:
466
- inputs:
467
- dry_run:
468
- description: 'Run in dry-run mode (no changes)'
469
- required: false
470
- default: 'false'
471
-
472
- permissions:
473
- contents: read
474
- issues: write
475
-
476
- jobs:
477
- audit:
478
- runs-on: ubuntu-latest
479
- timeout-minutes: 30 # CUSTOMIZE: Deep audits may need more time
480
- env:
481
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
482
- DRY_RUN: \${{ inputs.dry_run || 'false' }}
483
- steps:
484
- - uses: actions/checkout@v4
485
- with:
486
- fetch-depth: 0
487
-
488
- - name: Run Deep Audit with Gemini
489
- uses: google/run-gemini-cli@v1
490
- with:
491
- prompt: |
492
- Perform a deep audit of this codebase. Check for:
493
- - Security vulnerabilities
494
- - Performance issues
495
- - Code quality concerns
496
- - Dependency health
497
- Output a structured markdown report.
498
- sandbox: docker
499
- env:
500
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
501
-
502
- - name: Upload Report
503
- if: env.DRY_RUN != 'true'
504
- uses: actions/upload-artifact@v4
505
- with:
506
- name: gemini-audit-report
507
- path: audit-report.md
508
- retention-days: 30
509
- `,
510
-
511
- 'gemini-test-gen': `# Gemini Test Generation — generated by nerviq
512
- # Generates test stubs for new files in a pull request using Gemini CLI.
513
- #
514
- # CUSTOMIZE: Adjust file patterns, test framework, and output directory.
515
-
516
- name: Gemini Test Generation
517
-
518
- on:
519
- pull_request:
520
- types: [opened, synchronize]
521
-
522
- permissions:
523
- contents: read
524
- pull-requests: write
525
-
526
- jobs:
527
- test-gen:
528
- runs-on: ubuntu-latest
529
- timeout-minutes: 10 # CUSTOMIZE: Adjust for repo size
530
- env:
531
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
532
- DRY_RUN: \${{ inputs.dry_run || 'false' }}
533
- steps:
534
- - uses: actions/checkout@v4
535
- with:
536
- fetch-depth: 0
537
-
538
- - name: Detect New Files
539
- id: new-files
540
- run: |
541
- FILES=$(git diff --name-only --diff-filter=A \${{ github.event.pull_request.base.sha }}..\${{ github.sha }})
542
- # CUSTOMIZE: Filter to source files only
543
- SRC_FILES=$(echo "$FILES" | grep -E '\\.(js|ts|py|go|rs|java)$' || true)
544
- echo "files=$SRC_FILES" >> $GITHUB_OUTPUT
545
-
546
- - name: Generate Test Stubs with Gemini
547
- if: steps.new-files.outputs.files != ''
548
- uses: google/run-gemini-cli@v1
549
- with:
550
- prompt: |
551
- Generate test stubs for the following new files:
552
- \${{ steps.new-files.outputs.files }}
553
- Use the project's existing test framework and conventions.
554
- sandbox: docker
555
- env:
556
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
557
- `,
558
-
559
- 'gemini-docs-sync': `# Gemini Docs Sync — generated by nerviq
560
- # Checks for documentation staleness and suggests updates using Gemini CLI.
561
- #
562
- # CUSTOMIZE: Adjust the staleness threshold and doc paths.
563
-
564
- name: Gemini Docs Sync
565
-
566
- on:
567
- schedule:
568
- - cron: '0 10 * * 3' # CUSTOMIZE: Every Wednesday at 10:00 UTC
569
- workflow_dispatch:
570
- inputs:
571
- dry_run:
572
- description: 'Run in dry-run mode (no changes)'
573
- required: false
574
- default: 'false'
575
-
576
- permissions:
577
- contents: read
578
- issues: write
579
-
580
- jobs:
581
- docs-check:
582
- runs-on: ubuntu-latest
583
- timeout-minutes: 10 # CUSTOMIZE: Usually fast
584
- env:
585
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
586
- DRY_RUN: \${{ inputs.dry_run || 'false' }}
587
- steps:
588
- - uses: actions/checkout@v4
589
- with:
590
- fetch-depth: 0
591
-
592
- - name: Check Doc Staleness
593
- run: |
594
- # CUSTOMIZE: Adjust paths and staleness threshold (days)
595
- STALE_THRESHOLD=30
596
- DOC_PATHS="README.md docs/ CONTRIBUTING.md"
597
-
598
- for doc_path in $DOC_PATHS; do
599
- [ ! -e "$doc_path" ] && continue
600
- LAST_MODIFIED=$(git log -1 --format="%ct" -- "$doc_path" 2>/dev/null || echo 0)
601
- NOW=$(date +%s)
602
- DAYS_OLD=$(( (NOW - LAST_MODIFIED) / 86400 ))
603
- if [ "$DAYS_OLD" -gt "$STALE_THRESHOLD" ]; then
604
- echo "STALE: $doc_path ($DAYS_OLD days old)"
605
- fi
606
- done
607
-
608
- - name: Suggest Doc Updates with Gemini
609
- uses: google/run-gemini-cli@v1
610
- with:
611
- prompt: |
612
- Review the project documentation for staleness and accuracy.
613
- Compare docs against the current codebase and suggest updates.
614
- Focus on README.md, CONTRIBUTING.md, and files in docs/.
615
- sandbox: docker
616
- env:
617
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
618
- `,
619
- };
620
-
621
- /**
622
- * Get a CI template by key.
623
- *
624
- * @param {string} templateKey - One of the CI_TEMPLATES keys
625
- * @returns {string|null} Template content string or null if not found
626
- */
627
- function getCiTemplate(templateKey) {
628
- const meta = CI_TEMPLATES.find(t => t.key === templateKey);
629
- if (!meta) return null;
630
- return TEMPLATE_CONTENT[templateKey] || null;
631
- }
632
-
633
- // ---------------------------------------------------------------------------
634
- // 3. Adoption Signal Gate (5 gates)
635
- // ---------------------------------------------------------------------------
636
-
637
- /**
638
- * Gate thresholds: each gate defines a minimum usage signal before activation.
639
- * Uses local snapshot history for privacy-preserving telemetry.
640
- */
641
- const GATE_THRESHOLDS = {
642
- 'ci-templates': {
643
- metric: 'auditCount',
644
- threshold: 3,
645
- description: 'Activate CI templates after 3+ successful audits.',
646
- },
647
- 'policy-engine': {
648
- metric: 'auditCount',
649
- threshold: 2,
650
- description: 'Activate policy engine packs after 2+ audits.',
651
- },
652
- 'multi-pack': {
653
- metric: 'auditCount',
654
- threshold: 2,
655
- description: 'Activate multi-pack composition after 2+ audits.',
656
- },
657
- 'extension-marketplace': {
658
- metric: 'auditCount',
659
- threshold: 5,
660
- description: 'Activate extension marketplace recommendations after 5+ audits.',
661
- },
662
- 'governance-upgrade': {
663
- metric: 'averageScore',
664
- threshold: 70,
665
- description: 'Suggest governance upgrade when average score exceeds 70.',
666
- },
667
- };
668
-
669
- /**
670
- * Read Gemini audit snapshot history from the local .gemini/.nerviq/ directory.
671
- * @param {string} dir - Project directory
672
- * @param {number} limit - Max snapshots to read
673
- * @returns {object[]} Array of snapshot objects
674
- */
675
- function getGeminiHistory(dir, limit = 20) {
676
- const fs = require('fs');
677
- const snapshotDir = resolveGeminiStateReadPath(dir, 'snapshots');
678
- try {
679
- const files = fs.readdirSync(snapshotDir)
680
- .filter(f => f.endsWith('.json'))
681
- .sort()
682
- .slice(-limit);
683
-
684
- return files.map(f => {
685
- try {
686
- return JSON.parse(fs.readFileSync(path.join(snapshotDir, f), 'utf8'));
687
- } catch {
688
- return null;
689
- }
690
- }).filter(Boolean);
691
- } catch {
692
- return [];
693
- }
694
- }
695
-
696
- /**
697
- * Check if an adoption gate should be activated based on local telemetry.
698
- *
699
- * @param {string} gateKey - Key from GATE_THRESHOLDS
700
- * @param {string} dir - Project directory to read snapshots from
701
- * @returns {{ activated: boolean, current: number, threshold: number, gate: string, description: string }}
702
- */
703
- function checkAdoptionGate(gateKey, dir) {
704
- const gate = GATE_THRESHOLDS[gateKey];
705
- if (!gate) {
706
- return {
707
- activated: false,
708
- current: 0,
709
- threshold: 0,
710
- gate: gateKey,
711
- description: `Unknown gate "${gateKey}".`,
712
- };
713
- }
714
-
715
- const history = getGeminiHistory(dir, 100);
716
- let current = 0;
717
-
718
- switch (gate.metric) {
719
- case 'auditCount':
720
- current = history.length;
721
- break;
722
- case 'averageScore': {
723
- const scores = history
724
- .map(e => e.summary?.score)
725
- .filter(s => typeof s === 'number');
726
- current = scores.length > 0
727
- ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
728
- : 0;
729
- break;
730
- }
731
- default:
732
- current = 0;
733
- }
734
-
735
- return {
736
- activated: current >= gate.threshold,
737
- current,
738
- threshold: gate.threshold,
739
- gate: gateKey,
740
- description: gate.description,
741
- };
742
- }
743
-
744
- // ---------------------------------------------------------------------------
745
- // Exports
746
- // ---------------------------------------------------------------------------
747
-
748
- module.exports = {
749
- composePacks,
750
- getCiTemplate,
751
- CI_TEMPLATES,
752
- checkAdoptionGate,
753
- // Internals exposed for testing
754
- GATE_THRESHOLDS,
755
- PACK_DEPENDENCY_ORDER,
756
- PACK_SPECIFICITY,
757
- DEFAULT_SIZE_BUDGET,
758
- POLICY_PACKS,
759
- EXTENSION_PACKS,
760
- };
1
+ /**
2
+ * Gemini CLI Premium Operator UX
3
+ *
4
+ * Three subsystems:
5
+ * 1. Multi-Pack Composition Engine — merge domain + MCP + policy + extension packs with dedup, conflict resolution, dependency ordering
6
+ * 2. CI Template Library — 5 GitHub Actions workflow templates for Gemini CLI automation (using run-gemini-cli action)
7
+ * 3. Adoption Signal Gate — activate features based on local usage telemetry (5 gates)
8
+ */
9
+
10
+ const path = require('path');
11
+ const { GEMINI_DOMAIN_PACKS } = require('./domain-packs');
12
+ const { GEMINI_MCP_PACKS } = require('./mcp-packs');
13
+ const { resolveGeminiStateReadPath } = require('../state-paths');
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // 1. Multi-Pack Composition Engine
17
+ // ---------------------------------------------------------------------------
18
+
19
+ /** Pack dependency order — earlier = more foundational */
20
+ const PACK_DEPENDENCY_ORDER = [
21
+ 'baseline-general',
22
+ 'backend-api',
23
+ 'frontend-ui',
24
+ 'infra-platform',
25
+ 'monorepo',
26
+ 'enterprise-governed',
27
+ ];
28
+
29
+ /** Specificity rank: higher = more specific, wins conflicts */
30
+ const PACK_SPECIFICITY = {
31
+ 'baseline-general': 0,
32
+ 'backend-api': 2,
33
+ 'frontend-ui': 2,
34
+ 'infra-platform': 3,
35
+ 'monorepo': 3,
36
+ 'enterprise-governed': 4,
37
+ };
38
+
39
+ /** Policy pack definitions — Gemini-unique */
40
+ const POLICY_PACKS = [
41
+ {
42
+ key: 'policy-file-restrictions',
43
+ label: 'File Restrictions',
44
+ description: 'Protect sensitive files from unreviewed edits.',
45
+ policyContent: {
46
+ 'file-restrictions': {
47
+ deny_edit: ['.env', '.env.*', '*.pem', '*.key', 'credentials.*'],
48
+ deny_delete: ['.env', '.env.*', '*.pem', '*.key', '*.lock'],
49
+ read_only_dirs: ['.git', 'node_modules', '.gemini/policy'],
50
+ },
51
+ },
52
+ },
53
+ {
54
+ key: 'policy-tool-restrictions',
55
+ label: 'Tool Restrictions',
56
+ description: 'Limit which tools the agent can invoke without approval.',
57
+ policyContent: {
58
+ 'tool-restrictions': {
59
+ deny_tools: ['shell_exec_unsafe', 'network_raw'],
60
+ require_approval: ['file_delete', 'git_push', 'deploy'],
61
+ },
62
+ },
63
+ },
64
+ {
65
+ key: 'policy-governance',
66
+ label: 'Governance',
67
+ description: 'Strict audit and escalation policies for enterprise use.',
68
+ policyContent: {
69
+ governance: {
70
+ audit_trail: true,
71
+ escalation_on_deny: true,
72
+ max_auto_edits_per_session: 50,
73
+ require_justification_for: ['security-override', 'policy-bypass'],
74
+ },
75
+ },
76
+ },
77
+ ];
78
+
79
+ /** Extension pack definitions — Gemini-unique */
80
+ const EXTENSION_PACKS = [
81
+ {
82
+ key: 'ext-code-review',
83
+ label: 'Code Review Extension',
84
+ description: 'Structured code review with severity ratings and inline suggestions.',
85
+ },
86
+ {
87
+ key: 'ext-test-gen',
88
+ label: 'Test Generation Extension',
89
+ description: 'Auto-generate test stubs for new or modified files.',
90
+ },
91
+ {
92
+ key: 'ext-docs-sync',
93
+ label: 'Docs Sync Extension',
94
+ description: 'Detect stale documentation and suggest updates.',
95
+ },
96
+ ];
97
+
98
+ const DEFAULT_SIZE_BUDGET = 16000; // characters for combined instruction content
99
+
100
+ function lookupDomainPack(key) {
101
+ return GEMINI_DOMAIN_PACKS.find(p => p.key === key) || null;
102
+ }
103
+
104
+ function lookupMcpPack(key) {
105
+ return GEMINI_MCP_PACKS.find(p => p.key === key) || null;
106
+ }
107
+
108
+ function lookupPolicyPack(key) {
109
+ return POLICY_PACKS.find(p => p.key === key) || null;
110
+ }
111
+
112
+ function lookupExtensionPack(key) {
113
+ return EXTENSION_PACKS.find(p => p.key === key) || null;
114
+ }
115
+
116
+ /**
117
+ * Compose domain packs, MCP packs, policy packs, and extension packs into a unified,
118
+ * deduplicated, ordered result.
119
+ *
120
+ * @param {string[]} domainPackKeys - Array of domain pack keys to compose
121
+ * @param {string[]} mcpPackKeys - Array of MCP pack keys to compose
122
+ * @param {object} [options]
123
+ * @param {number} [options.sizeBudget] - Max characters for combined instructions (default 16000)
124
+ * @param {string[]} [options.policyPackKeys] - Array of policy pack keys (Gemini-unique)
125
+ * @param {string[]} [options.extensionPackKeys] - Array of extension pack keys (Gemini-unique)
126
+ * @returns {object} Composition report
127
+ */
128
+ function composePacks(domainPackKeys = [], mcpPackKeys = [], options = {}) {
129
+ const sizeBudget = options.sizeBudget || DEFAULT_SIZE_BUDGET;
130
+ const policyPackKeys = options.policyPackKeys || [];
131
+ const extensionPackKeys = options.extensionPackKeys || [];
132
+ const warnings = [];
133
+
134
+ // --- Resolve domain packs ---
135
+ const seenDomainKeys = new Set();
136
+ const rawDomainPacks = [];
137
+ for (const key of domainPackKeys) {
138
+ if (seenDomainKeys.has(key)) continue;
139
+ seenDomainKeys.add(key);
140
+ const pack = lookupDomainPack(key);
141
+ if (!pack) {
142
+ warnings.push(`Domain pack "${key}" not found, skipped.`);
143
+ continue;
144
+ }
145
+ rawDomainPacks.push(pack);
146
+ }
147
+
148
+ // Order by dependency (base -> framework -> tool-specific)
149
+ rawDomainPacks.sort((a, b) => {
150
+ const orderA = PACK_DEPENDENCY_ORDER.indexOf(a.key);
151
+ const orderB = PACK_DEPENDENCY_ORDER.indexOf(b.key);
152
+ return (orderA === -1 ? 99 : orderA) - (orderB === -1 ? 99 : orderB);
153
+ });
154
+
155
+ // Deduplicate overlapping recommendedModules; more specific pack wins
156
+ const moduleOwner = new Map(); // module -> { key, specificity }
157
+ for (const pack of rawDomainPacks) {
158
+ const specificity = PACK_SPECIFICITY[pack.key] ?? 1;
159
+ for (const mod of pack.recommendedModules || []) {
160
+ const existing = moduleOwner.get(mod);
161
+ if (!existing || specificity > existing.specificity) {
162
+ moduleOwner.set(mod, { key: pack.key, specificity });
163
+ }
164
+ }
165
+ }
166
+
167
+ // Deduplicate surfaces
168
+ const allSurfaces = new Set();
169
+ for (const pack of rawDomainPacks) {
170
+ for (const surface of pack.recommendedSurfaces || []) {
171
+ allSurfaces.add(surface);
172
+ }
173
+ }
174
+
175
+ // Deduplicate proposal families
176
+ const allProposalFamilies = new Set();
177
+ for (const pack of rawDomainPacks) {
178
+ for (const family of pack.recommendedProposalFamilies || []) {
179
+ allProposalFamilies.add(family);
180
+ }
181
+ }
182
+
183
+ // --- Resolve MCP packs ---
184
+ const seenMcpKeys = new Set();
185
+ const resolvedMcpPacks = [];
186
+ for (const key of mcpPackKeys) {
187
+ if (seenMcpKeys.has(key)) continue;
188
+ seenMcpKeys.add(key);
189
+ const pack = lookupMcpPack(key);
190
+ if (!pack) {
191
+ warnings.push(`MCP pack "${key}" not found, skipped.`);
192
+ continue;
193
+ }
194
+ resolvedMcpPacks.push(pack);
195
+ }
196
+
197
+ // Merge excludeTools across all MCP packs (union — Gemini uses deny-list, not allow-list)
198
+ const mergedExcludeTools = new Set();
199
+ for (const pack of resolvedMcpPacks) {
200
+ for (const tool of pack.excludeTools || []) {
201
+ mergedExcludeTools.add(tool);
202
+ }
203
+ }
204
+
205
+ // Collect required auth (union)
206
+ const mergedRequiredAuth = new Set();
207
+ for (const pack of resolvedMcpPacks) {
208
+ for (const auth of pack.requiredAuth || []) {
209
+ mergedRequiredAuth.add(auth);
210
+ }
211
+ }
212
+
213
+ // --- Resolve policy packs (Gemini-unique) ---
214
+ const seenPolicyKeys = new Set();
215
+ const resolvedPolicyPacks = [];
216
+ const mergedPolicyContent = {};
217
+ for (const key of policyPackKeys) {
218
+ if (seenPolicyKeys.has(key)) continue;
219
+ seenPolicyKeys.add(key);
220
+ const pack = lookupPolicyPack(key);
221
+ if (!pack) {
222
+ warnings.push(`Policy pack "${key}" not found, skipped.`);
223
+ continue;
224
+ }
225
+ resolvedPolicyPacks.push(pack);
226
+ // Merge policy content sections
227
+ if (pack.policyContent) {
228
+ for (const [section, rules] of Object.entries(pack.policyContent)) {
229
+ if (!mergedPolicyContent[section]) {
230
+ mergedPolicyContent[section] = { ...rules };
231
+ } else {
232
+ // Merge arrays, overwrite scalars
233
+ for (const [ruleKey, ruleValue] of Object.entries(rules)) {
234
+ if (Array.isArray(ruleValue) && Array.isArray(mergedPolicyContent[section][ruleKey])) {
235
+ const merged = new Set([...mergedPolicyContent[section][ruleKey], ...ruleValue]);
236
+ mergedPolicyContent[section][ruleKey] = [...merged];
237
+ } else {
238
+ mergedPolicyContent[section][ruleKey] = ruleValue;
239
+ }
240
+ }
241
+ }
242
+ }
243
+ }
244
+ }
245
+
246
+ // --- Resolve extension packs (Gemini-unique) ---
247
+ const seenExtKeys = new Set();
248
+ const resolvedExtensionPacks = [];
249
+ for (const key of extensionPackKeys) {
250
+ if (seenExtKeys.has(key)) continue;
251
+ seenExtKeys.add(key);
252
+ const pack = lookupExtensionPack(key);
253
+ if (!pack) {
254
+ warnings.push(`Extension pack "${key}" not found, skipped.`);
255
+ continue;
256
+ }
257
+ resolvedExtensionPacks.push(pack);
258
+ }
259
+
260
+ // --- Size budget tracking ---
261
+ const estimatedSize = estimateCompositionSize(rawDomainPacks, resolvedMcpPacks, resolvedPolicyPacks, resolvedExtensionPacks);
262
+ const overBudget = estimatedSize > sizeBudget;
263
+ if (overBudget) {
264
+ warnings.push(
265
+ `Combined instruction size (~${estimatedSize} chars) exceeds budget (${sizeBudget}). ` +
266
+ `Consider removing lower-priority packs.`
267
+ );
268
+ }
269
+
270
+ return {
271
+ domainPacks: rawDomainPacks.map(p => ({
272
+ key: p.key,
273
+ label: p.label,
274
+ modulesOwned: [...moduleOwner.entries()]
275
+ .filter(([, owner]) => owner.key === p.key)
276
+ .map(([mod]) => mod),
277
+ })),
278
+ mcpPacks: resolvedMcpPacks.map(p => ({
279
+ key: p.key,
280
+ label: p.label,
281
+ serverName: p.serverName,
282
+ trustLevel: p.trustLevel,
283
+ })),
284
+ policyPacks: resolvedPolicyPacks.map(p => ({
285
+ key: p.key,
286
+ label: p.label,
287
+ description: p.description,
288
+ })),
289
+ extensionPacks: resolvedExtensionPacks.map(p => ({
290
+ key: p.key,
291
+ label: p.label,
292
+ description: p.description,
293
+ })),
294
+ merged: {
295
+ surfaces: [...allSurfaces],
296
+ proposalFamilies: [...allProposalFamilies],
297
+ modules: [...moduleOwner.entries()].map(([mod, owner]) => ({ module: mod, owner: owner.key })),
298
+ excludeTools: [...mergedExcludeTools].sort(),
299
+ requiredAuth: [...mergedRequiredAuth].sort(),
300
+ policyContent: mergedPolicyContent,
301
+ },
302
+ budget: {
303
+ estimatedSize,
304
+ limit: sizeBudget,
305
+ overBudget,
306
+ utilization: Math.round((estimatedSize / sizeBudget) * 100),
307
+ },
308
+ warnings,
309
+ };
310
+ }
311
+
312
+ function estimateCompositionSize(domainPacks, mcpPacks, policyPacks = [], extensionPacks = []) {
313
+ let size = 0;
314
+ for (const pack of domainPacks) {
315
+ size += (pack.label || '').length + (pack.useWhen || '').length + (pack.adoption || '').length;
316
+ size += JSON.stringify(pack.recommendedModules || []).length;
317
+ size += JSON.stringify(pack.benchmarkFocus || []).length;
318
+ }
319
+ for (const pack of mcpPacks) {
320
+ size += (pack.label || '').length + (pack.description || '').length;
321
+ size += JSON.stringify(pack.jsonProjection || {}).length;
322
+ size += JSON.stringify(pack.excludeTools || []).length;
323
+ }
324
+ for (const pack of policyPacks) {
325
+ size += (pack.label || '').length + (pack.description || '').length;
326
+ size += JSON.stringify(pack.policyContent || {}).length;
327
+ }
328
+ for (const pack of extensionPacks) {
329
+ size += (pack.label || '').length + (pack.description || '').length;
330
+ }
331
+ return size;
332
+ }
333
+
334
+ // ---------------------------------------------------------------------------
335
+ // 2. CI Template Library (5 templates using run-gemini-cli action)
336
+ // ---------------------------------------------------------------------------
337
+
338
+ const CI_TEMPLATES = [
339
+ {
340
+ key: 'gemini-pr-review',
341
+ label: 'Gemini PR Review',
342
+ filename: 'gemini-pr-review.yml',
343
+ description: 'Runs Gemini CLI review on pull request diffs.',
344
+ trigger: 'pull_request',
345
+ },
346
+ {
347
+ key: 'gemini-issue-triage',
348
+ label: 'Gemini Issue Triage',
349
+ filename: 'gemini-issue-triage.yml',
350
+ description: 'Classifies and labels new issues using Gemini CLI.',
351
+ trigger: 'issues.opened',
352
+ },
353
+ {
354
+ key: 'gemini-scheduled-audit',
355
+ label: 'Gemini Scheduled Audit',
356
+ filename: 'gemini-scheduled-audit.yml',
357
+ description: 'Weekly deep review of the codebase with Gemini CLI.',
358
+ trigger: 'schedule (cron)',
359
+ },
360
+ {
361
+ key: 'gemini-test-gen',
362
+ label: 'Gemini Test Generation',
363
+ filename: 'gemini-test-gen.yml',
364
+ description: 'Generates test stubs for newly added files using Gemini CLI.',
365
+ trigger: 'pull_request',
366
+ },
367
+ {
368
+ key: 'gemini-docs-sync',
369
+ label: 'Gemini Docs Sync',
370
+ filename: 'gemini-docs-sync.yml',
371
+ description: 'Checks for documentation staleness using Gemini CLI.',
372
+ trigger: 'schedule (cron)',
373
+ },
374
+ ];
375
+
376
+ const TEMPLATE_CONTENT = {
377
+ 'gemini-pr-review': `# Gemini PR Review — generated by nerviq
378
+ # Runs Gemini CLI to review pull request diffs and post suggestions.
379
+ #
380
+ # CUSTOMIZE: Adjust the model, sandbox, and timeout to match your team.
381
+
382
+ name: Gemini PR Review
383
+
384
+ on:
385
+ pull_request:
386
+ types: [opened, synchronize]
387
+
388
+ # CUSTOMIZE: Add path filters if you only want reviews on certain directories
389
+ # paths: ['src/**', 'lib/**']
390
+
391
+ permissions:
392
+ contents: read
393
+ pull-requests: write
394
+
395
+ jobs:
396
+ gemini-review:
397
+ runs-on: ubuntu-latest
398
+ timeout-minutes: 15 # CUSTOMIZE: Adjust timeout for your repo size
399
+ env:
400
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
401
+ # CUSTOMIZE: Set DRY_RUN=true to preview without posting comments
402
+ DRY_RUN: \${{ inputs.dry_run || 'false' }}
403
+ steps:
404
+ - uses: actions/checkout@v4
405
+ with:
406
+ fetch-depth: 0
407
+
408
+ - name: Run Gemini CLI Review
409
+ uses: google/run-gemini-cli@v1
410
+ with:
411
+ prompt: |
412
+ Review the following pull request diff for issues, improvements, and best practices.
413
+ Focus on security, performance, and correctness.
414
+ sandbox: docker
415
+ env:
416
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
417
+ `,
418
+
419
+ 'gemini-issue-triage': `# Gemini Issue Triage — generated by nerviq
420
+ # Classifies newly opened issues and applies labels using Gemini CLI.
421
+ #
422
+ # CUSTOMIZE: Edit the label mapping and classification prompt below.
423
+
424
+ name: Gemini Issue Triage
425
+
426
+ on:
427
+ issues:
428
+ types: [opened]
429
+
430
+ permissions:
431
+ issues: write
432
+
433
+ jobs:
434
+ triage:
435
+ runs-on: ubuntu-latest
436
+ timeout-minutes: 5 # CUSTOMIZE: Issues are small; 5 min is usually enough
437
+ env:
438
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
439
+ DRY_RUN: \${{ inputs.dry_run || 'false' }}
440
+ steps:
441
+ - uses: actions/checkout@v4
442
+
443
+ - name: Classify Issue with Gemini
444
+ uses: google/run-gemini-cli@v1
445
+ with:
446
+ prompt: |
447
+ Classify this issue and suggest labels from: bug, feature, question, docs, security.
448
+ Title: \${{ github.event.issue.title }}
449
+ Body: \${{ github.event.issue.body }}
450
+ sandbox: docker
451
+ env:
452
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
453
+ `,
454
+
455
+ 'gemini-scheduled-audit': `# Gemini Scheduled Audit — generated by nerviq
456
+ # Weekly deep review of the codebase using Gemini CLI.
457
+ #
458
+ # CUSTOMIZE: Adjust the cron schedule and audit scope.
459
+
460
+ name: Gemini Scheduled Audit
461
+
462
+ on:
463
+ schedule:
464
+ - cron: '0 9 * * 1' # CUSTOMIZE: Every Monday at 09:00 UTC
465
+ workflow_dispatch:
466
+ inputs:
467
+ dry_run:
468
+ description: 'Run in dry-run mode (no changes)'
469
+ required: false
470
+ default: 'false'
471
+
472
+ permissions:
473
+ contents: read
474
+ issues: write
475
+
476
+ jobs:
477
+ audit:
478
+ runs-on: ubuntu-latest
479
+ timeout-minutes: 30 # CUSTOMIZE: Deep audits may need more time
480
+ env:
481
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
482
+ DRY_RUN: \${{ inputs.dry_run || 'false' }}
483
+ steps:
484
+ - uses: actions/checkout@v4
485
+ with:
486
+ fetch-depth: 0
487
+
488
+ - name: Run Deep Audit with Gemini
489
+ uses: google/run-gemini-cli@v1
490
+ with:
491
+ prompt: |
492
+ Perform a deep audit of this codebase. Check for:
493
+ - Security vulnerabilities
494
+ - Performance issues
495
+ - Code quality concerns
496
+ - Dependency health
497
+ Output a structured markdown report.
498
+ sandbox: docker
499
+ env:
500
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
501
+
502
+ - name: Upload Report
503
+ if: env.DRY_RUN != 'true'
504
+ uses: actions/upload-artifact@v4
505
+ with:
506
+ name: gemini-audit-report
507
+ path: audit-report.md
508
+ retention-days: 30
509
+ `,
510
+
511
+ 'gemini-test-gen': `# Gemini Test Generation — generated by nerviq
512
+ # Generates test stubs for new files in a pull request using Gemini CLI.
513
+ #
514
+ # CUSTOMIZE: Adjust file patterns, test framework, and output directory.
515
+
516
+ name: Gemini Test Generation
517
+
518
+ on:
519
+ pull_request:
520
+ types: [opened, synchronize]
521
+
522
+ permissions:
523
+ contents: read
524
+ pull-requests: write
525
+
526
+ jobs:
527
+ test-gen:
528
+ runs-on: ubuntu-latest
529
+ timeout-minutes: 10 # CUSTOMIZE: Adjust for repo size
530
+ env:
531
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
532
+ DRY_RUN: \${{ inputs.dry_run || 'false' }}
533
+ steps:
534
+ - uses: actions/checkout@v4
535
+ with:
536
+ fetch-depth: 0
537
+
538
+ - name: Detect New Files
539
+ id: new-files
540
+ run: |
541
+ FILES=$(git diff --name-only --diff-filter=A \${{ github.event.pull_request.base.sha }}..\${{ github.sha }})
542
+ # CUSTOMIZE: Filter to source files only
543
+ SRC_FILES=$(echo "$FILES" | grep -E '\\.(js|ts|py|go|rs|java)$' || true)
544
+ echo "files=$SRC_FILES" >> $GITHUB_OUTPUT
545
+
546
+ - name: Generate Test Stubs with Gemini
547
+ if: steps.new-files.outputs.files != ''
548
+ uses: google/run-gemini-cli@v1
549
+ with:
550
+ prompt: |
551
+ Generate test stubs for the following new files:
552
+ \${{ steps.new-files.outputs.files }}
553
+ Use the project's existing test framework and conventions.
554
+ sandbox: docker
555
+ env:
556
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
557
+ `,
558
+
559
+ 'gemini-docs-sync': `# Gemini Docs Sync — generated by nerviq
560
+ # Checks for documentation staleness and suggests updates using Gemini CLI.
561
+ #
562
+ # CUSTOMIZE: Adjust the staleness threshold and doc paths.
563
+
564
+ name: Gemini Docs Sync
565
+
566
+ on:
567
+ schedule:
568
+ - cron: '0 10 * * 3' # CUSTOMIZE: Every Wednesday at 10:00 UTC
569
+ workflow_dispatch:
570
+ inputs:
571
+ dry_run:
572
+ description: 'Run in dry-run mode (no changes)'
573
+ required: false
574
+ default: 'false'
575
+
576
+ permissions:
577
+ contents: read
578
+ issues: write
579
+
580
+ jobs:
581
+ docs-check:
582
+ runs-on: ubuntu-latest
583
+ timeout-minutes: 10 # CUSTOMIZE: Usually fast
584
+ env:
585
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
586
+ DRY_RUN: \${{ inputs.dry_run || 'false' }}
587
+ steps:
588
+ - uses: actions/checkout@v4
589
+ with:
590
+ fetch-depth: 0
591
+
592
+ - name: Check Doc Staleness
593
+ run: |
594
+ # CUSTOMIZE: Adjust paths and staleness threshold (days)
595
+ STALE_THRESHOLD=30
596
+ DOC_PATHS="README.md docs/ CONTRIBUTING.md"
597
+
598
+ for doc_path in $DOC_PATHS; do
599
+ [ ! -e "$doc_path" ] && continue
600
+ LAST_MODIFIED=$(git log -1 --format="%ct" -- "$doc_path" 2>/dev/null || echo 0)
601
+ NOW=$(date +%s)
602
+ DAYS_OLD=$(( (NOW - LAST_MODIFIED) / 86400 ))
603
+ if [ "$DAYS_OLD" -gt "$STALE_THRESHOLD" ]; then
604
+ echo "STALE: $doc_path ($DAYS_OLD days old)"
605
+ fi
606
+ done
607
+
608
+ - name: Suggest Doc Updates with Gemini
609
+ uses: google/run-gemini-cli@v1
610
+ with:
611
+ prompt: |
612
+ Review the project documentation for staleness and accuracy.
613
+ Compare docs against the current codebase and suggest updates.
614
+ Focus on README.md, CONTRIBUTING.md, and files in docs/.
615
+ sandbox: docker
616
+ env:
617
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
618
+ `,
619
+ };
620
+
621
+ /**
622
+ * Get a CI template by key.
623
+ *
624
+ * @param {string} templateKey - One of the CI_TEMPLATES keys
625
+ * @returns {string|null} Template content string or null if not found
626
+ */
627
+ function getCiTemplate(templateKey) {
628
+ const meta = CI_TEMPLATES.find(t => t.key === templateKey);
629
+ if (!meta) return null;
630
+ return TEMPLATE_CONTENT[templateKey] || null;
631
+ }
632
+
633
+ // ---------------------------------------------------------------------------
634
+ // 3. Adoption Signal Gate (5 gates)
635
+ // ---------------------------------------------------------------------------
636
+
637
+ /**
638
+ * Gate thresholds: each gate defines a minimum usage signal before activation.
639
+ * Uses local snapshot history for privacy-preserving telemetry.
640
+ */
641
+ const GATE_THRESHOLDS = {
642
+ 'ci-templates': {
643
+ metric: 'auditCount',
644
+ threshold: 3,
645
+ description: 'Activate CI templates after 3+ successful audits.',
646
+ },
647
+ 'policy-engine': {
648
+ metric: 'auditCount',
649
+ threshold: 2,
650
+ description: 'Activate policy engine packs after 2+ audits.',
651
+ },
652
+ 'multi-pack': {
653
+ metric: 'auditCount',
654
+ threshold: 2,
655
+ description: 'Activate multi-pack composition after 2+ audits.',
656
+ },
657
+ 'extension-marketplace': {
658
+ metric: 'auditCount',
659
+ threshold: 5,
660
+ description: 'Activate extension marketplace recommendations after 5+ audits.',
661
+ },
662
+ 'governance-upgrade': {
663
+ metric: 'averageScore',
664
+ threshold: 70,
665
+ description: 'Suggest governance upgrade when average score exceeds 70.',
666
+ },
667
+ };
668
+
669
+ /**
670
+ * Read Gemini audit snapshot history from the local .gemini/.nerviq/ directory.
671
+ * @param {string} dir - Project directory
672
+ * @param {number} limit - Max snapshots to read
673
+ * @returns {object[]} Array of snapshot objects
674
+ */
675
+ function getGeminiHistory(dir, limit = 20) {
676
+ const fs = require('fs');
677
+ const snapshotDir = resolveGeminiStateReadPath(dir, 'snapshots');
678
+ try {
679
+ const files = fs.readdirSync(snapshotDir)
680
+ .filter(f => f.endsWith('.json'))
681
+ .sort()
682
+ .slice(-limit);
683
+
684
+ return files.map(f => {
685
+ try {
686
+ return JSON.parse(fs.readFileSync(path.join(snapshotDir, f), 'utf8'));
687
+ } catch {
688
+ return null;
689
+ }
690
+ }).filter(Boolean);
691
+ } catch {
692
+ return [];
693
+ }
694
+ }
695
+
696
+ /**
697
+ * Check if an adoption gate should be activated based on local telemetry.
698
+ *
699
+ * @param {string} gateKey - Key from GATE_THRESHOLDS
700
+ * @param {string} dir - Project directory to read snapshots from
701
+ * @returns {{ activated: boolean, current: number, threshold: number, gate: string, description: string }}
702
+ */
703
+ function checkAdoptionGate(gateKey, dir) {
704
+ const gate = GATE_THRESHOLDS[gateKey];
705
+ if (!gate) {
706
+ return {
707
+ activated: false,
708
+ current: 0,
709
+ threshold: 0,
710
+ gate: gateKey,
711
+ description: `Unknown gate "${gateKey}".`,
712
+ };
713
+ }
714
+
715
+ const history = getGeminiHistory(dir, 100);
716
+ let current = 0;
717
+
718
+ switch (gate.metric) {
719
+ case 'auditCount':
720
+ current = history.length;
721
+ break;
722
+ case 'averageScore': {
723
+ const scores = history
724
+ .map(e => e.summary?.score)
725
+ .filter(s => typeof s === 'number');
726
+ current = scores.length > 0
727
+ ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
728
+ : 0;
729
+ break;
730
+ }
731
+ default:
732
+ current = 0;
733
+ }
734
+
735
+ return {
736
+ activated: current >= gate.threshold,
737
+ current,
738
+ threshold: gate.threshold,
739
+ gate: gateKey,
740
+ description: gate.description,
741
+ };
742
+ }
743
+
744
+ // ---------------------------------------------------------------------------
745
+ // Exports
746
+ // ---------------------------------------------------------------------------
747
+
748
+ module.exports = {
749
+ composePacks,
750
+ getCiTemplate,
751
+ CI_TEMPLATES,
752
+ checkAdoptionGate,
753
+ // Internals exposed for testing
754
+ GATE_THRESHOLDS,
755
+ PACK_DEPENDENCY_ORDER,
756
+ PACK_SPECIFICITY,
757
+ DEFAULT_SIZE_BUDGET,
758
+ POLICY_PACKS,
759
+ EXTENSION_PACKS,
760
+ };