@nerviq/cli 1.20.1 → 1.22.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 (186) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +20 -2
  3. package/bin/cli.js +3 -3
  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 +4 -1
  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 +312 -67
  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/audit.js +20 -0
  25. package/src/auto-suggest.js +154 -154
  26. package/src/badge.js +13 -13
  27. package/src/behavioral-drift.js +801 -801
  28. package/src/benchmark.js +67 -67
  29. package/src/catalog.js +103 -103
  30. package/src/certification.js +128 -128
  31. package/src/codex/config-parser.js +183 -183
  32. package/src/codex/context.js +223 -223
  33. package/src/codex/deep-review.js +493 -493
  34. package/src/codex/domain-packs.js +394 -394
  35. package/src/codex/freshness.js +84 -84
  36. package/src/codex/governance.js +192 -192
  37. package/src/codex/interactive.js +618 -618
  38. package/src/codex/mcp-packs.js +914 -914
  39. package/src/codex/patch.js +209 -209
  40. package/src/codex/plans.js +251 -251
  41. package/src/codex/premium.js +614 -614
  42. package/src/codex/setup.js +591 -591
  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/csv.js +69 -0
  78. package/src/formatters/junit.js +99 -0
  79. package/src/formatters/markdown.js +118 -0
  80. package/src/formatters/sarif.js +115 -115
  81. package/src/freshness.js +74 -74
  82. package/src/gemini/config-parser.js +275 -275
  83. package/src/gemini/deep-review.js +559 -559
  84. package/src/gemini/domain-packs.js +393 -393
  85. package/src/gemini/freshness.js +66 -66
  86. package/src/gemini/governance.js +201 -201
  87. package/src/gemini/interactive.js +860 -860
  88. package/src/gemini/mcp-packs.js +915 -915
  89. package/src/gemini/plans.js +269 -269
  90. package/src/gemini/premium.js +760 -760
  91. package/src/gemini/setup.js +692 -692
  92. package/src/governance.js +72 -72
  93. package/src/harmony/add.js +68 -68
  94. package/src/harmony/advisor.js +333 -333
  95. package/src/harmony/canon.js +565 -565
  96. package/src/harmony/cli.js +591 -591
  97. package/src/harmony/drift.js +401 -401
  98. package/src/harmony/governance.js +313 -313
  99. package/src/harmony/memory.js +239 -239
  100. package/src/harmony/sync.js +475 -475
  101. package/src/harmony/watch.js +370 -370
  102. package/src/hook-validation.js +342 -342
  103. package/src/index.js +271 -271
  104. package/src/init.js +184 -184
  105. package/src/instruction-surfaces.js +185 -185
  106. package/src/integrations.js +144 -144
  107. package/src/interactive.js +118 -118
  108. package/src/locales/en.json +1 -1
  109. package/src/locales/es.json +1 -1
  110. package/src/mcp-packs.js +830 -830
  111. package/src/mcp-server.js +726 -726
  112. package/src/mcp-validation.js +337 -337
  113. package/src/nerviq-sync.json +7 -7
  114. package/src/opencode/config-parser.js +109 -109
  115. package/src/opencode/context.js +247 -247
  116. package/src/opencode/deep-review.js +313 -313
  117. package/src/opencode/domain-packs.js +262 -262
  118. package/src/opencode/freshness.js +66 -66
  119. package/src/opencode/governance.js +159 -159
  120. package/src/opencode/interactive.js +392 -392
  121. package/src/opencode/mcp-packs.js +705 -705
  122. package/src/opencode/patch.js +184 -184
  123. package/src/opencode/plans.js +231 -231
  124. package/src/opencode/premium.js +413 -413
  125. package/src/opencode/setup.js +449 -449
  126. package/src/opencode/techniques.js +27 -27
  127. package/src/operating-profile.js +574 -574
  128. package/src/org.js +152 -152
  129. package/src/permission-rules.js +218 -218
  130. package/src/plans.js +839 -839
  131. package/src/platform-change-manifest.js +86 -86
  132. package/src/plugins.js +110 -110
  133. package/src/policy-layers.js +210 -210
  134. package/src/profiles.js +124 -124
  135. package/src/prompt-injection.js +74 -74
  136. package/src/public-api.js +173 -173
  137. package/src/recommendation-rules.js +84 -84
  138. package/src/repo-archetype.js +386 -386
  139. package/src/secret-patterns.js +39 -39
  140. package/src/server.js +527 -527
  141. package/src/setup/analysis.js +607 -607
  142. package/src/setup/runtime.js +172 -172
  143. package/src/setup.js +677 -677
  144. package/src/shared/capabilities.js +194 -194
  145. package/src/source-urls.js +132 -132
  146. package/src/stack-checks.js +565 -565
  147. package/src/supplemental-checks.js +13 -13
  148. package/src/synergy/adaptive.js +261 -261
  149. package/src/synergy/compensation.js +137 -137
  150. package/src/synergy/evidence.js +193 -193
  151. package/src/synergy/learning.js +199 -199
  152. package/src/synergy/patterns.js +227 -227
  153. package/src/synergy/ranking.js +83 -83
  154. package/src/synergy/report.js +165 -165
  155. package/src/synergy/routing.js +146 -146
  156. package/src/techniques/api.js +407 -407
  157. package/src/techniques/automation.js +316 -316
  158. package/src/techniques/compliance.js +257 -257
  159. package/src/techniques/hygiene.js +294 -294
  160. package/src/techniques/instructions.js +243 -243
  161. package/src/techniques/observability.js +226 -226
  162. package/src/techniques/optimization.js +142 -142
  163. package/src/techniques/quality.js +318 -318
  164. package/src/techniques/security.js +237 -237
  165. package/src/techniques/shared.js +443 -443
  166. package/src/techniques/stacks.js +2294 -2294
  167. package/src/techniques/tools.js +106 -106
  168. package/src/techniques/workflow.js +413 -413
  169. package/src/techniques.js +81 -81
  170. package/src/terminology.js +73 -73
  171. package/src/token-estimate.js +35 -35
  172. package/src/usage-patterns.js +99 -99
  173. package/src/verification-metadata.js +145 -145
  174. package/src/watch.js +247 -247
  175. package/src/windsurf/activity.js +302 -302
  176. package/src/windsurf/config-parser.js +267 -267
  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/workspace.js +375 -375
@@ -1,692 +1,692 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const os = require('os');
4
- const { version } = require('../../package.json');
5
- const { STACKS } = require('../techniques');
6
- const { writeActivityArtifact, writeRollbackArtifact } = require('../activity');
7
- const { GeminiProjectContext } = require('./context');
8
- const { recommendGeminiMcpPacks, packToJson } = require('./mcp-packs');
9
-
10
- function detectScripts(ctx) {
11
- const pkg = ctx.jsonFile('package.json');
12
- if (!pkg || !pkg.scripts) return {};
13
- return pkg.scripts;
14
- }
15
-
16
- function detectProjectName(ctx) {
17
- const pkg = ctx.jsonFile('package.json');
18
- if (pkg && pkg.name) return pkg.name;
19
- return path.basename(ctx.dir);
20
- }
21
-
22
- function hasStack(stacks, key) {
23
- return stacks.some((item) => item.key === key);
24
- }
25
-
26
- function buildMermaid(stacks) {
27
- if (hasStack(stacks, 'nextjs')) {
28
- return [
29
- '```mermaid',
30
- 'graph TD',
31
- ' UI[App Router / Pages] --> Logic[Server Actions or API Routes]',
32
- ' Logic --> Data[Data Layer]',
33
- ' Data --> External[External Services / DB]',
34
- '```',
35
- ].join('\n');
36
- }
37
-
38
- if (hasStack(stacks, 'fastapi') || hasStack(stacks, 'django') || hasStack(stacks, 'python')) {
39
- return [
40
- '```mermaid',
41
- 'graph TD',
42
- ' API[API / CLI Entry] --> Services[Service Layer]',
43
- ' Services --> Models[Models / Schemas]',
44
- ' Models --> Data[Database or External APIs]',
45
- '```',
46
- ].join('\n');
47
- }
48
-
49
- if (hasStack(stacks, 'go')) {
50
- return [
51
- '```mermaid',
52
- 'graph TD',
53
- ' Cmd[cmd/ or main package] --> Internal[internal/ packages]',
54
- ' Internal --> Data[Storage / APIs]',
55
- '```',
56
- ].join('\n');
57
- }
58
-
59
- if (hasStack(stacks, 'rust')) {
60
- return [
61
- '```mermaid',
62
- 'graph TD',
63
- ' Bin[src/main.rs] --> Core[src/lib.rs]',
64
- ' Core --> Modules[domain / adapters / services]',
65
- '```',
66
- ].join('\n');
67
- }
68
-
69
- return [
70
- '```mermaid',
71
- 'graph TD',
72
- ' Entry[Entry Point] --> Core[Core Logic]',
73
- ' Core --> Data[Data / External Services]',
74
- '```',
75
- ].join('\n');
76
- }
77
-
78
- function buildVerificationCommands(ctx) {
79
- const scripts = detectScripts(ctx);
80
- const commands = [];
81
-
82
- if (scripts.test) commands.push(`- Test: \`npm test\``);
83
- if (scripts.lint) commands.push(`- Lint: \`npm run lint\``);
84
- if (scripts.build) commands.push(`- Build: \`npm run build\``);
85
-
86
- if (commands.length === 0 && ctx.fileContent('pyproject.toml')) {
87
- commands.push('- Test: `python -m pytest`');
88
- }
89
- if (commands.length === 0 && ctx.fileContent('requirements.txt')) {
90
- commands.push('- Test: `python -m pytest`');
91
- }
92
- if (commands.length === 0 && ctx.fileContent('go.mod')) {
93
- commands.push('- Test: `go test ./...`');
94
- commands.push('- Build: `go build ./...`');
95
- }
96
- if (commands.length === 0 && ctx.fileContent('Cargo.toml')) {
97
- commands.push('- Test: `cargo test`');
98
- commands.push('- Build: `cargo build`');
99
- }
100
-
101
- if (commands.length === 0) {
102
- commands.push('- Test: add the repo test command');
103
- commands.push('- Lint: add the repo lint command');
104
- commands.push('- Build: add the repo build command');
105
- }
106
-
107
- return commands;
108
- }
109
-
110
- function buildCodingConventions(stacks) {
111
- const lines = [];
112
-
113
- if (hasStack(stacks, 'typescript')) {
114
- lines.push('- Keep TypeScript strict and prefer typed boundaries over implicit `any`.');
115
- }
116
- if (hasStack(stacks, 'react') || hasStack(stacks, 'nextjs')) {
117
- lines.push('- Prefer small, reviewable component changes and document risky UI state assumptions before refactors.');
118
- }
119
- if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
120
- lines.push('- Prefer explicit validation, typed schemas, and focused service functions over large route handlers.');
121
- }
122
- if (hasStack(stacks, 'go')) {
123
- lines.push('- Keep packages small, avoid cross-package cycles, and prefer table-driven tests.');
124
- }
125
- if (hasStack(stacks, 'rust')) {
126
- lines.push('- Prefer explicit ownership-safe refactors and small module-scoped changes over broad rewrites.');
127
- }
128
- if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
129
- lines.push('- Treat infrastructure changes as high-risk: prefer diffs that are easy to plan, review, and roll back.');
130
- }
131
-
132
- if (lines.length === 0) {
133
- lines.push('- Prefer small, reviewable diffs and explicit reasoning over broad rewrites.');
134
- }
135
-
136
- return lines;
137
- }
138
-
139
- function buildSecurityNotes(stacks) {
140
- const lines = [
141
- '- Never commit secrets, tokens, or `.env` values into tracked files.',
142
- '- Prefer the repo verification commands before handoff, and explain any command you could not run.',
143
- ];
144
-
145
- if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
146
- lines.push('- Validate auth, permissions, and data-handling changes carefully before touching production-sensitive paths.');
147
- }
148
- if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
149
- lines.push('- Review blast radius before changing infra, deployment, or cluster configuration.');
150
- }
151
-
152
- return lines;
153
- }
154
-
155
- function buildGeminiMd(ctx, stacks) {
156
- const stackLabels = stacks.map((item) => item.label).join(', ') || 'General repo';
157
- const verificationCommands = buildVerificationCommands(ctx);
158
- const codingConventions = buildCodingConventions(stacks);
159
- const securityNotes = buildSecurityNotes(stacks);
160
-
161
- return [
162
- `# ${detectProjectName(ctx)}`,
163
- '',
164
- '## Scope',
165
- '- Primary platform: Gemini CLI',
166
- `- Detected stack: ${stackLabels}`,
167
- '- Keep this file focused on Gemini CLI-specific guidance when the repo also uses Claude or other agents.',
168
- '',
169
- '## Architecture',
170
- buildMermaid(stacks),
171
- '- Replace the default diagram and bullets with the real entry points, boundaries, and high-risk subsystems for this repo.',
172
- '',
173
- '## Verification',
174
- ...verificationCommands,
175
- '',
176
- '## Coding Conventions',
177
- ...codingConventions,
178
- '',
179
- '## Review Workflow',
180
- '- Use `gemini review` before handoff on risky diffs or broad refactors.',
181
- '- Explain which verification commands ran successfully and which were skipped.',
182
- '- Keep working-tree expectations explicit: do not silently mix unrelated edits into the same handoff.',
183
- '',
184
- '## Security',
185
- ...securityNotes,
186
- '',
187
- '## Cost & Automation',
188
- '- Reserve heavy reasoning or long automation chains for tasks that actually need them.',
189
- '- Test Gemini CLI automation manually or in workflow_dispatch before turning it into a scheduled workflow.',
190
- '- Be aware of `--yolo` mode risks: it bypasses all confirmation prompts and should only be used in externally sandboxed environments.',
191
- '',
192
- '## Notes',
193
- '- If this repo also uses Claude, keep Claude-specific instructions in `CLAUDE.md` and use GEMINI.md for Gemini CLI-native behavior.',
194
- '- If you add repo-local commands, place them under `.gemini/commands/` as TOML files with kebab-case names.',
195
- '- If you add custom agents, keep them under `.gemini/agents/` as markdown files.',
196
- '- Policy files go under `.gemini/policy/` as TOML files for Gemini-specific governance rules.',
197
- '',
198
- `_Generated by nerviq v${version} for Gemini CLI. Customize this file before relying on it in production flows._`,
199
- '',
200
- ].join('\n');
201
- }
202
-
203
- function buildSettingsJson() {
204
- return JSON.stringify({
205
- "$schema": "https://gemini.google.com/settings-schema.json",
206
- "theme": "system",
207
- "model": "gemini-2.5-pro",
208
- "sandbox": true,
209
- "codeExecution": false,
210
- "checkpointFrequency": "auto",
211
- "yolo": false,
212
- "context": {
213
- "fileName": "GEMINI.md",
214
- "maxDepth": 3,
215
- },
216
- "hooks": {},
217
- "mcpServers": {},
218
- }, null, 2) + '\n';
219
- }
220
-
221
- function buildGeminiSetupFiles(options = {}) {
222
- const ctx = new GeminiProjectContext(options.dir);
223
- const stacks = ctx.detectStacks(STACKS);
224
- const files = [];
225
-
226
- // 1. GEMINI.md
227
- const geminiMdPath = path.join(options.dir, 'GEMINI.md');
228
- if (!fs.existsSync(geminiMdPath)) {
229
- files.push({
230
- path: 'GEMINI.md',
231
- action: 'create',
232
- content: buildGeminiMd(ctx, stacks),
233
- currentState: 'GEMINI.md is missing',
234
- proposedState: 'create a Gemini CLI-native GEMINI.md baseline with verification, architecture, review, and trust guidance',
235
- });
236
- }
237
-
238
- // 2. .gemini/settings.json
239
- const settingsPath = path.join(options.dir, '.gemini', 'settings.json');
240
- if (!fs.existsSync(settingsPath)) {
241
- files.push({
242
- path: '.gemini/settings.json',
243
- action: 'create',
244
- content: buildSettingsJson(),
245
- currentState: '.gemini/settings.json is missing',
246
- proposedState: 'create a safe Gemini CLI baseline settings.json with explicit sandbox, model, context, and hooks settings',
247
- });
248
- }
249
-
250
- // --- Optional setup families ---
251
- const modules = options.modules || 'all';
252
- const wantModule = (name) => modules === 'all' || (Array.isArray(modules) && modules.includes(name));
253
-
254
- // 3. Hooks config in settings.json (scaffold)
255
- if (wantModule('hooks')) {
256
- const hooksInSettings = ctx.hooksConfig();
257
- if (!hooksInSettings || Object.keys(hooksInSettings).length === 0) {
258
- files.push({
259
- path: '.gemini/settings.json (hooks append)',
260
- action: 'patch',
261
- family: 'gemini-hooks',
262
- content: buildHooksStarter(),
263
- currentState: 'No hooks configured in .gemini/settings.json',
264
- proposedState: 'add BeforeTool/AfterTool hook starters to settings.json',
265
- });
266
- }
267
- }
268
-
269
- // 4. Commands starter
270
- if (wantModule('commands')) {
271
- const commandsDir = path.join(options.dir, '.gemini', 'commands');
272
- const commandsReadme = path.join(commandsDir, 'README.md');
273
- if (!fs.existsSync(commandsReadme) && !fs.existsSync(commandsDir)) {
274
- files.push({
275
- path: '.gemini/commands/README.md',
276
- action: 'create',
277
- family: 'gemini-commands',
278
- content: buildCommandsStarter(),
279
- currentState: '.gemini/commands/ directory is missing',
280
- proposedState: 'create a Gemini CLI commands starter with TOML conventions and usage guidance',
281
- });
282
- }
283
- }
284
-
285
- // 5. Agents starter
286
- if (wantModule('agents')) {
287
- const agentsDir = path.join(options.dir, '.gemini', 'agents');
288
- if (!fs.existsSync(agentsDir)) {
289
- files.push({
290
- path: '.gemini/agents/README.md',
291
- action: 'create',
292
- family: 'gemini-agents',
293
- content: buildAgentsStarter(),
294
- currentState: '.gemini/agents/ directory is missing',
295
- proposedState: 'create a Gemini CLI agents starter with markdown conventions',
296
- });
297
- }
298
- }
299
-
300
- // 6. Skills starter
301
- if (wantModule('skills')) {
302
- const skillsDir = path.join(options.dir, '.gemini', 'skills');
303
- const skillsReadme = path.join(skillsDir, 'README.md');
304
- if (!fs.existsSync(skillsReadme) && !fs.existsSync(skillsDir)) {
305
- files.push({
306
- path: '.gemini/skills/README.md',
307
- action: 'create',
308
- family: 'gemini-skills',
309
- content: buildSkillsStarter(),
310
- currentState: '.gemini/skills/ directory is missing',
311
- proposedState: 'create a Gemini CLI skills starter with naming conventions and structure guidance',
312
- });
313
- }
314
- }
315
-
316
- // 7. Policy starter (Gemini-unique!)
317
- if (wantModule('policy')) {
318
- const policyDir = path.join(options.dir, '.gemini', 'policy');
319
- if (!fs.existsSync(policyDir)) {
320
- files.push({
321
- path: '.gemini/policy/README.md',
322
- action: 'create',
323
- family: 'gemini-policy',
324
- content: buildPolicyStarter(),
325
- currentState: '.gemini/policy/ directory is missing',
326
- proposedState: 'create a Gemini CLI policy TOML starter with governance and enforcement guidance',
327
- });
328
- }
329
- }
330
-
331
- // 8. MCP packs
332
- if (wantModule('mcp')) {
333
- const mcpServers = ctx.mcpServers();
334
- const hasMcpSection = mcpServers && Object.keys(mcpServers).length > 0;
335
- if (!hasMcpSection) {
336
- const domainPacks = options.domainPacks || [];
337
- const mcpRecs = recommendGeminiMcpPacks(stacks, domainPacks, { ctx });
338
- if (mcpRecs.length > 0) {
339
- const mcpJson = JSON.stringify(
340
- Object.assign({}, ...mcpRecs.map(p => packToJson(p))),
341
- null, 2
342
- );
343
- files.push({
344
- path: '.gemini/settings.json (MCP append)',
345
- action: 'append',
346
- family: 'gemini-mcp',
347
- content: mcpJson,
348
- currentState: 'No MCP servers configured in .gemini/settings.json',
349
- proposedState: `add ${mcpRecs.length} recommended MCP packs: ${mcpRecs.map(p => p.label).join(', ')}`,
350
- });
351
- }
352
- }
353
- }
354
-
355
- // 9. CI / Review workflow starter
356
- if (wantModule('ci')) {
357
- const workflowDir = path.join(options.dir, '.github', 'workflows');
358
- const geminiWorkflow = path.join(workflowDir, 'gemini-review.yml');
359
- if (!fs.existsSync(geminiWorkflow)) {
360
- files.push({
361
- path: '.github/workflows/gemini-review.yml',
362
- action: 'create',
363
- family: 'gemini-ci-review',
364
- content: buildCiReviewStarter(),
365
- currentState: 'No Gemini CLI CI review workflow exists',
366
- proposedState: 'create a GitHub Actions workflow for Gemini CLI-based PR review',
367
- });
368
- }
369
- }
370
-
371
- return { ctx, stacks, files };
372
- }
373
-
374
- // --- Starter builders ---
375
-
376
- function buildHooksStarter() {
377
- return JSON.stringify({
378
- "hooks": {
379
- "BeforeTool": [
380
- {
381
- "command": "echo 'Gemini tool about to execute'",
382
- "description": "Example BeforeTool hook — customize or remove",
383
- "timeout_ms": 5000,
384
- }
385
- ],
386
- "AfterTool": [
387
- {
388
- "command": "echo 'Gemini tool completed'",
389
- "description": "Example AfterTool hook — customize or remove",
390
- "timeout_ms": 5000,
391
- }
392
- ],
393
- }
394
- }, null, 2) + '\n';
395
- }
396
-
397
- function buildCommandsStarter() {
398
- return [
399
- '# Gemini CLI Commands',
400
- '',
401
- 'Place TOML command files in this directory to extend Gemini CLI.',
402
- '',
403
- '## Command format',
404
- '',
405
- '```toml',
406
- 'name = "my-command"',
407
- 'description = "What this command does"',
408
- 'prompt = "The prompt template for this command"',
409
- '```',
410
- '',
411
- '## Example command',
412
- '',
413
- '```toml',
414
- 'name = "review"',
415
- 'description = "Review the current diff for issues"',
416
- 'prompt = """',
417
- 'Review the current git diff for bugs, security issues, and style problems.',
418
- 'Focus on correctness first, then readability.',
419
- '"""',
420
- '```',
421
- '',
422
- '## Best practices',
423
- '',
424
- '- Use kebab-case for command file names (e.g., `code-review.toml`)',
425
- '- Keep prompts focused and actionable',
426
- '- Document expected inputs and outputs in the description',
427
- '',
428
- `_Generated by nerviq v${version}_`,
429
- '',
430
- ].join('\n');
431
- }
432
-
433
- function buildAgentsStarter() {
434
- return [
435
- '# Gemini CLI Agents',
436
- '',
437
- 'Place agent markdown files here to define specialized Gemini CLI agents.',
438
- '',
439
- '## Format',
440
- '',
441
- 'Each agent file should be a `.md` file with:',
442
- '- A clear title and purpose',
443
- '- Specific instructions for the agent role',
444
- '- Constraints and boundaries',
445
- '',
446
- '## Example agent',
447
- '',
448
- '```markdown',
449
- '# Security Reviewer',
450
- '',
451
- 'You are a security-focused code reviewer. Check for:',
452
- '- SQL injection vulnerabilities',
453
- '- XSS attack vectors',
454
- '- Hardcoded secrets or credentials',
455
- '- Insecure dependencies',
456
- '',
457
- 'Report findings with severity levels: critical, high, medium, low.',
458
- '```',
459
- '',
460
- '## Best practices',
461
- '',
462
- '- Keep agent instructions focused on a single responsibility',
463
- '- Use markdown files with clear headings',
464
- '- Document the agent scope and limitations',
465
- '',
466
- `_Generated by nerviq v${version}_`,
467
- '',
468
- ].join('\n');
469
- }
470
-
471
- function buildSkillsStarter() {
472
- return [
473
- '# Gemini CLI Skills',
474
- '',
475
- 'Place skill directories here. Each skill needs a definition file.',
476
- '',
477
- '## Directory structure',
478
- '',
479
- '```',
480
- '.gemini/skills/',
481
- ' my-skill/',
482
- ' SKILL.md # Required: name, description, instructions',
483
- ' helpers.js # Optional: supporting files',
484
- '```',
485
- '',
486
- '## SKILL.md format',
487
- '',
488
- '```markdown',
489
- '---',
490
- 'name: my-skill',
491
- 'description: Short description for invocation',
492
- '---',
493
- '',
494
- '# My Skill',
495
- '',
496
- 'Instructions for Gemini CLI when this skill is invoked.',
497
- '```',
498
- '',
499
- '## Critical naming rules',
500
- '',
501
- '- Use **kebab-case** for skill directory names (e.g., `code-review`, not `CodeReview`)',
502
- '- Keep descriptions short for bounded context cost',
503
- '',
504
- `_Generated by nerviq v${version}_`,
505
- '',
506
- ].join('\n');
507
- }
508
-
509
- function buildPolicyStarter() {
510
- return [
511
- '# Gemini CLI Policy',
512
- '',
513
- 'Place TOML policy files here to govern Gemini CLI behavior in this repo.',
514
- '',
515
- 'Gemini CLI policy files are a **Gemini-unique feature** for declarative governance.',
516
- '',
517
- '## Policy format',
518
- '',
519
- '```toml',
520
- '[policy]',
521
- 'name = "baseline-safe"',
522
- 'description = "Safe baseline policy for this repo"',
523
- '',
524
- '[rules]',
525
- 'allow_file_write = true',
526
- 'allow_file_delete = false',
527
- 'allow_network = false',
528
- 'allow_shell_exec = "prompt"',
529
- 'max_file_size_kb = 1024',
530
- '',
531
- '[sandbox]',
532
- 'mode = "restricted"',
533
- 'allowed_paths = ["src/", "tests/", "docs/"]',
534
- 'blocked_paths = [".env", "secrets/", "credentials/"]',
535
- '```',
536
- '',
537
- '## Example policies',
538
- '',
539
- '### Locked-down (read-only review)',
540
- '',
541
- '```toml',
542
- '[policy]',
543
- 'name = "review-only"',
544
- '',
545
- '[rules]',
546
- 'allow_file_write = false',
547
- 'allow_file_delete = false',
548
- 'allow_shell_exec = false',
549
- '```',
550
- '',
551
- '### Automation (CI context)',
552
- '',
553
- '```toml',
554
- '[policy]',
555
- 'name = "ci-automation"',
556
- '',
557
- '[rules]',
558
- 'allow_file_write = true',
559
- 'allow_shell_exec = true',
560
- 'require_confirmation = false',
561
- '```',
562
- '',
563
- '## Best practices',
564
- '',
565
- '- Start with restrictive policies and relax as needed',
566
- '- Use `blocked_paths` to protect sensitive files',
567
- '- Review policy changes in PRs like code changes',
568
- '- Separate CI policies from local development policies',
569
- '',
570
- `_Generated by nerviq v${version}_`,
571
- '',
572
- ].join('\n');
573
- }
574
-
575
- function buildCiReviewStarter() {
576
- return [
577
- 'name: Gemini Review',
578
- '',
579
- 'on:',
580
- ' pull_request:',
581
- ' types: [opened, synchronize]',
582
- '',
583
- 'permissions:',
584
- ' contents: read',
585
- ' pull-requests: write',
586
- '',
587
- 'jobs:',
588
- ' gemini-review:',
589
- ' runs-on: ubuntu-latest',
590
- ' steps:',
591
- ' - uses: actions/checkout@v4',
592
- ' - name: Gemini Review',
593
- ' uses: google/gemini-code-review-action@v1',
594
- ' with:',
595
- ' safety-strategy: review-only',
596
- ' env:',
597
- ' GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}',
598
- ].join('\n') + '\n';
599
- }
600
-
601
- async function setupGemini(options) {
602
- const silent = options.silent === true;
603
- const { ctx, stacks, files } = buildGeminiSetupFiles(options);
604
- const writtenFiles = [];
605
- const preservedFiles = [];
606
-
607
- function log(message = '') {
608
- if (!silent) {
609
- console.log(message);
610
- }
611
- }
612
-
613
- log('');
614
- log('\x1b[1m nerviq gemini setup\x1b[0m');
615
- log('\x1b[2m ═══════════════════════════════════════\x1b[0m');
616
- if (stacks.length > 0) {
617
- log(`\x1b[36m Detected: ${stacks.map((s) => s.label).join(', ')}\x1b[0m`);
618
- }
619
- log('');
620
-
621
- for (const file of files) {
622
- const fullPath = path.join(options.dir, file.path);
623
- if (fs.existsSync(fullPath)) {
624
- preservedFiles.push(file.path);
625
- log(` \x1b[2m⏭️ Skipped ${file.path} (already exists — your version is kept)\x1b[0m`);
626
- continue;
627
- }
628
-
629
- fs.mkdirSync(path.dirname(fullPath), { recursive: true });
630
- fs.writeFileSync(fullPath, file.content, 'utf8');
631
- writtenFiles.push(file.path);
632
- log(` \x1b[32m✅\x1b[0m Created ${file.path}`);
633
- }
634
-
635
- const skippedSet = new Set(preservedFiles);
636
- if (!skippedSet.has('GEMINI.md') && fs.existsSync(path.join(options.dir, 'GEMINI.md')) && !writtenFiles.includes('GEMINI.md')) {
637
- preservedFiles.push('GEMINI.md');
638
- }
639
- if (!skippedSet.has('.gemini/settings.json') && fs.existsSync(path.join(options.dir, '.gemini', 'settings.json')) && !writtenFiles.includes('.gemini/settings.json')) {
640
- preservedFiles.push('.gemini/settings.json');
641
- }
642
-
643
- let rollbackArtifact = null;
644
- let activityArtifact = null;
645
- if (writtenFiles.length > 0) {
646
- rollbackArtifact = writeRollbackArtifact(options.dir, {
647
- sourcePlan: 'gemini-setup',
648
- createdFiles: writtenFiles,
649
- patchedFiles: [],
650
- rollbackInstructions: writtenFiles.map((file) => `Delete ${file}`),
651
- });
652
- activityArtifact = writeActivityArtifact(options.dir, 'gemini-setup', {
653
- platform: 'gemini',
654
- createdFiles: writtenFiles,
655
- preservedFiles,
656
- stackLabels: stacks.map((item) => item.label),
657
- rollbackArtifact: rollbackArtifact.relativePath,
658
- });
659
- }
660
-
661
- log('');
662
- log(` \x1b[1m${writtenFiles.length} files created.\x1b[0m`);
663
- if (preservedFiles.length > 0) {
664
- log(` \x1b[2m${preservedFiles.length} existing files preserved (not overwritten).\x1b[0m`);
665
- }
666
- if (rollbackArtifact) {
667
- log(` Rollback: \x1b[1m${rollbackArtifact.relativePath}\x1b[0m`);
668
- }
669
- if (activityArtifact) {
670
- log(` Activity log: \x1b[1m${activityArtifact.relativePath}\x1b[0m`);
671
- }
672
- log('');
673
- log(' Run \x1b[1mnpx nerviq --platform gemini\x1b[0m to audit your Gemini CLI setup.');
674
- log('');
675
-
676
- return {
677
- created: writtenFiles.length,
678
- skipped: preservedFiles.length,
679
- writtenFiles,
680
- preservedFiles,
681
- stacks,
682
- rollbackArtifact: rollbackArtifact ? rollbackArtifact.relativePath : null,
683
- activityArtifact: activityArtifact ? activityArtifact.relativePath : null,
684
- };
685
- }
686
-
687
- module.exports = {
688
- buildGeminiMd,
689
- buildSettingsJson,
690
- buildGeminiSetupFiles,
691
- setupGemini,
692
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { version } = require('../../package.json');
5
+ const { STACKS } = require('../techniques');
6
+ const { writeActivityArtifact, writeRollbackArtifact } = require('../activity');
7
+ const { GeminiProjectContext } = require('./context');
8
+ const { recommendGeminiMcpPacks, packToJson } = require('./mcp-packs');
9
+
10
+ function detectScripts(ctx) {
11
+ const pkg = ctx.jsonFile('package.json');
12
+ if (!pkg || !pkg.scripts) return {};
13
+ return pkg.scripts;
14
+ }
15
+
16
+ function detectProjectName(ctx) {
17
+ const pkg = ctx.jsonFile('package.json');
18
+ if (pkg && pkg.name) return pkg.name;
19
+ return path.basename(ctx.dir);
20
+ }
21
+
22
+ function hasStack(stacks, key) {
23
+ return stacks.some((item) => item.key === key);
24
+ }
25
+
26
+ function buildMermaid(stacks) {
27
+ if (hasStack(stacks, 'nextjs')) {
28
+ return [
29
+ '```mermaid',
30
+ 'graph TD',
31
+ ' UI[App Router / Pages] --> Logic[Server Actions or API Routes]',
32
+ ' Logic --> Data[Data Layer]',
33
+ ' Data --> External[External Services / DB]',
34
+ '```',
35
+ ].join('\n');
36
+ }
37
+
38
+ if (hasStack(stacks, 'fastapi') || hasStack(stacks, 'django') || hasStack(stacks, 'python')) {
39
+ return [
40
+ '```mermaid',
41
+ 'graph TD',
42
+ ' API[API / CLI Entry] --> Services[Service Layer]',
43
+ ' Services --> Models[Models / Schemas]',
44
+ ' Models --> Data[Database or External APIs]',
45
+ '```',
46
+ ].join('\n');
47
+ }
48
+
49
+ if (hasStack(stacks, 'go')) {
50
+ return [
51
+ '```mermaid',
52
+ 'graph TD',
53
+ ' Cmd[cmd/ or main package] --> Internal[internal/ packages]',
54
+ ' Internal --> Data[Storage / APIs]',
55
+ '```',
56
+ ].join('\n');
57
+ }
58
+
59
+ if (hasStack(stacks, 'rust')) {
60
+ return [
61
+ '```mermaid',
62
+ 'graph TD',
63
+ ' Bin[src/main.rs] --> Core[src/lib.rs]',
64
+ ' Core --> Modules[domain / adapters / services]',
65
+ '```',
66
+ ].join('\n');
67
+ }
68
+
69
+ return [
70
+ '```mermaid',
71
+ 'graph TD',
72
+ ' Entry[Entry Point] --> Core[Core Logic]',
73
+ ' Core --> Data[Data / External Services]',
74
+ '```',
75
+ ].join('\n');
76
+ }
77
+
78
+ function buildVerificationCommands(ctx) {
79
+ const scripts = detectScripts(ctx);
80
+ const commands = [];
81
+
82
+ if (scripts.test) commands.push(`- Test: \`npm test\``);
83
+ if (scripts.lint) commands.push(`- Lint: \`npm run lint\``);
84
+ if (scripts.build) commands.push(`- Build: \`npm run build\``);
85
+
86
+ if (commands.length === 0 && ctx.fileContent('pyproject.toml')) {
87
+ commands.push('- Test: `python -m pytest`');
88
+ }
89
+ if (commands.length === 0 && ctx.fileContent('requirements.txt')) {
90
+ commands.push('- Test: `python -m pytest`');
91
+ }
92
+ if (commands.length === 0 && ctx.fileContent('go.mod')) {
93
+ commands.push('- Test: `go test ./...`');
94
+ commands.push('- Build: `go build ./...`');
95
+ }
96
+ if (commands.length === 0 && ctx.fileContent('Cargo.toml')) {
97
+ commands.push('- Test: `cargo test`');
98
+ commands.push('- Build: `cargo build`');
99
+ }
100
+
101
+ if (commands.length === 0) {
102
+ commands.push('- Test: add the repo test command');
103
+ commands.push('- Lint: add the repo lint command');
104
+ commands.push('- Build: add the repo build command');
105
+ }
106
+
107
+ return commands;
108
+ }
109
+
110
+ function buildCodingConventions(stacks) {
111
+ const lines = [];
112
+
113
+ if (hasStack(stacks, 'typescript')) {
114
+ lines.push('- Keep TypeScript strict and prefer typed boundaries over implicit `any`.');
115
+ }
116
+ if (hasStack(stacks, 'react') || hasStack(stacks, 'nextjs')) {
117
+ lines.push('- Prefer small, reviewable component changes and document risky UI state assumptions before refactors.');
118
+ }
119
+ if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
120
+ lines.push('- Prefer explicit validation, typed schemas, and focused service functions over large route handlers.');
121
+ }
122
+ if (hasStack(stacks, 'go')) {
123
+ lines.push('- Keep packages small, avoid cross-package cycles, and prefer table-driven tests.');
124
+ }
125
+ if (hasStack(stacks, 'rust')) {
126
+ lines.push('- Prefer explicit ownership-safe refactors and small module-scoped changes over broad rewrites.');
127
+ }
128
+ if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
129
+ lines.push('- Treat infrastructure changes as high-risk: prefer diffs that are easy to plan, review, and roll back.');
130
+ }
131
+
132
+ if (lines.length === 0) {
133
+ lines.push('- Prefer small, reviewable diffs and explicit reasoning over broad rewrites.');
134
+ }
135
+
136
+ return lines;
137
+ }
138
+
139
+ function buildSecurityNotes(stacks) {
140
+ const lines = [
141
+ '- Never commit secrets, tokens, or `.env` values into tracked files.',
142
+ '- Prefer the repo verification commands before handoff, and explain any command you could not run.',
143
+ ];
144
+
145
+ if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
146
+ lines.push('- Validate auth, permissions, and data-handling changes carefully before touching production-sensitive paths.');
147
+ }
148
+ if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
149
+ lines.push('- Review blast radius before changing infra, deployment, or cluster configuration.');
150
+ }
151
+
152
+ return lines;
153
+ }
154
+
155
+ function buildGeminiMd(ctx, stacks) {
156
+ const stackLabels = stacks.map((item) => item.label).join(', ') || 'General repo';
157
+ const verificationCommands = buildVerificationCommands(ctx);
158
+ const codingConventions = buildCodingConventions(stacks);
159
+ const securityNotes = buildSecurityNotes(stacks);
160
+
161
+ return [
162
+ `# ${detectProjectName(ctx)}`,
163
+ '',
164
+ '## Scope',
165
+ '- Primary platform: Gemini CLI',
166
+ `- Detected stack: ${stackLabels}`,
167
+ '- Keep this file focused on Gemini CLI-specific guidance when the repo also uses Claude or other agents.',
168
+ '',
169
+ '## Architecture',
170
+ buildMermaid(stacks),
171
+ '- Replace the default diagram and bullets with the real entry points, boundaries, and high-risk subsystems for this repo.',
172
+ '',
173
+ '## Verification',
174
+ ...verificationCommands,
175
+ '',
176
+ '## Coding Conventions',
177
+ ...codingConventions,
178
+ '',
179
+ '## Review Workflow',
180
+ '- Use `gemini review` before handoff on risky diffs or broad refactors.',
181
+ '- Explain which verification commands ran successfully and which were skipped.',
182
+ '- Keep working-tree expectations explicit: do not silently mix unrelated edits into the same handoff.',
183
+ '',
184
+ '## Security',
185
+ ...securityNotes,
186
+ '',
187
+ '## Cost & Automation',
188
+ '- Reserve heavy reasoning or long automation chains for tasks that actually need them.',
189
+ '- Test Gemini CLI automation manually or in workflow_dispatch before turning it into a scheduled workflow.',
190
+ '- Be aware of `--yolo` mode risks: it bypasses all confirmation prompts and should only be used in externally sandboxed environments.',
191
+ '',
192
+ '## Notes',
193
+ '- If this repo also uses Claude, keep Claude-specific instructions in `CLAUDE.md` and use GEMINI.md for Gemini CLI-native behavior.',
194
+ '- If you add repo-local commands, place them under `.gemini/commands/` as TOML files with kebab-case names.',
195
+ '- If you add custom agents, keep them under `.gemini/agents/` as markdown files.',
196
+ '- Policy files go under `.gemini/policy/` as TOML files for Gemini-specific governance rules.',
197
+ '',
198
+ `_Generated by nerviq v${version} for Gemini CLI. Customize this file before relying on it in production flows._`,
199
+ '',
200
+ ].join('\n');
201
+ }
202
+
203
+ function buildSettingsJson() {
204
+ return JSON.stringify({
205
+ "$schema": "https://gemini.google.com/settings-schema.json",
206
+ "theme": "system",
207
+ "model": "gemini-2.5-pro",
208
+ "sandbox": true,
209
+ "codeExecution": false,
210
+ "checkpointFrequency": "auto",
211
+ "yolo": false,
212
+ "context": {
213
+ "fileName": "GEMINI.md",
214
+ "maxDepth": 3,
215
+ },
216
+ "hooks": {},
217
+ "mcpServers": {},
218
+ }, null, 2) + '\n';
219
+ }
220
+
221
+ function buildGeminiSetupFiles(options = {}) {
222
+ const ctx = new GeminiProjectContext(options.dir);
223
+ const stacks = ctx.detectStacks(STACKS);
224
+ const files = [];
225
+
226
+ // 1. GEMINI.md
227
+ const geminiMdPath = path.join(options.dir, 'GEMINI.md');
228
+ if (!fs.existsSync(geminiMdPath)) {
229
+ files.push({
230
+ path: 'GEMINI.md',
231
+ action: 'create',
232
+ content: buildGeminiMd(ctx, stacks),
233
+ currentState: 'GEMINI.md is missing',
234
+ proposedState: 'create a Gemini CLI-native GEMINI.md baseline with verification, architecture, review, and trust guidance',
235
+ });
236
+ }
237
+
238
+ // 2. .gemini/settings.json
239
+ const settingsPath = path.join(options.dir, '.gemini', 'settings.json');
240
+ if (!fs.existsSync(settingsPath)) {
241
+ files.push({
242
+ path: '.gemini/settings.json',
243
+ action: 'create',
244
+ content: buildSettingsJson(),
245
+ currentState: '.gemini/settings.json is missing',
246
+ proposedState: 'create a safe Gemini CLI baseline settings.json with explicit sandbox, model, context, and hooks settings',
247
+ });
248
+ }
249
+
250
+ // --- Optional setup families ---
251
+ const modules = options.modules || 'all';
252
+ const wantModule = (name) => modules === 'all' || (Array.isArray(modules) && modules.includes(name));
253
+
254
+ // 3. Hooks config in settings.json (scaffold)
255
+ if (wantModule('hooks')) {
256
+ const hooksInSettings = ctx.hooksConfig();
257
+ if (!hooksInSettings || Object.keys(hooksInSettings).length === 0) {
258
+ files.push({
259
+ path: '.gemini/settings.json (hooks append)',
260
+ action: 'patch',
261
+ family: 'gemini-hooks',
262
+ content: buildHooksStarter(),
263
+ currentState: 'No hooks configured in .gemini/settings.json',
264
+ proposedState: 'add BeforeTool/AfterTool hook starters to settings.json',
265
+ });
266
+ }
267
+ }
268
+
269
+ // 4. Commands starter
270
+ if (wantModule('commands')) {
271
+ const commandsDir = path.join(options.dir, '.gemini', 'commands');
272
+ const commandsReadme = path.join(commandsDir, 'README.md');
273
+ if (!fs.existsSync(commandsReadme) && !fs.existsSync(commandsDir)) {
274
+ files.push({
275
+ path: '.gemini/commands/README.md',
276
+ action: 'create',
277
+ family: 'gemini-commands',
278
+ content: buildCommandsStarter(),
279
+ currentState: '.gemini/commands/ directory is missing',
280
+ proposedState: 'create a Gemini CLI commands starter with TOML conventions and usage guidance',
281
+ });
282
+ }
283
+ }
284
+
285
+ // 5. Agents starter
286
+ if (wantModule('agents')) {
287
+ const agentsDir = path.join(options.dir, '.gemini', 'agents');
288
+ if (!fs.existsSync(agentsDir)) {
289
+ files.push({
290
+ path: '.gemini/agents/README.md',
291
+ action: 'create',
292
+ family: 'gemini-agents',
293
+ content: buildAgentsStarter(),
294
+ currentState: '.gemini/agents/ directory is missing',
295
+ proposedState: 'create a Gemini CLI agents starter with markdown conventions',
296
+ });
297
+ }
298
+ }
299
+
300
+ // 6. Skills starter
301
+ if (wantModule('skills')) {
302
+ const skillsDir = path.join(options.dir, '.gemini', 'skills');
303
+ const skillsReadme = path.join(skillsDir, 'README.md');
304
+ if (!fs.existsSync(skillsReadme) && !fs.existsSync(skillsDir)) {
305
+ files.push({
306
+ path: '.gemini/skills/README.md',
307
+ action: 'create',
308
+ family: 'gemini-skills',
309
+ content: buildSkillsStarter(),
310
+ currentState: '.gemini/skills/ directory is missing',
311
+ proposedState: 'create a Gemini CLI skills starter with naming conventions and structure guidance',
312
+ });
313
+ }
314
+ }
315
+
316
+ // 7. Policy starter (Gemini-unique!)
317
+ if (wantModule('policy')) {
318
+ const policyDir = path.join(options.dir, '.gemini', 'policy');
319
+ if (!fs.existsSync(policyDir)) {
320
+ files.push({
321
+ path: '.gemini/policy/README.md',
322
+ action: 'create',
323
+ family: 'gemini-policy',
324
+ content: buildPolicyStarter(),
325
+ currentState: '.gemini/policy/ directory is missing',
326
+ proposedState: 'create a Gemini CLI policy TOML starter with governance and enforcement guidance',
327
+ });
328
+ }
329
+ }
330
+
331
+ // 8. MCP packs
332
+ if (wantModule('mcp')) {
333
+ const mcpServers = ctx.mcpServers();
334
+ const hasMcpSection = mcpServers && Object.keys(mcpServers).length > 0;
335
+ if (!hasMcpSection) {
336
+ const domainPacks = options.domainPacks || [];
337
+ const mcpRecs = recommendGeminiMcpPacks(stacks, domainPacks, { ctx });
338
+ if (mcpRecs.length > 0) {
339
+ const mcpJson = JSON.stringify(
340
+ Object.assign({}, ...mcpRecs.map(p => packToJson(p))),
341
+ null, 2
342
+ );
343
+ files.push({
344
+ path: '.gemini/settings.json (MCP append)',
345
+ action: 'append',
346
+ family: 'gemini-mcp',
347
+ content: mcpJson,
348
+ currentState: 'No MCP servers configured in .gemini/settings.json',
349
+ proposedState: `add ${mcpRecs.length} recommended MCP packs: ${mcpRecs.map(p => p.label).join(', ')}`,
350
+ });
351
+ }
352
+ }
353
+ }
354
+
355
+ // 9. CI / Review workflow starter
356
+ if (wantModule('ci')) {
357
+ const workflowDir = path.join(options.dir, '.github', 'workflows');
358
+ const geminiWorkflow = path.join(workflowDir, 'gemini-review.yml');
359
+ if (!fs.existsSync(geminiWorkflow)) {
360
+ files.push({
361
+ path: '.github/workflows/gemini-review.yml',
362
+ action: 'create',
363
+ family: 'gemini-ci-review',
364
+ content: buildCiReviewStarter(),
365
+ currentState: 'No Gemini CLI CI review workflow exists',
366
+ proposedState: 'create a GitHub Actions workflow for Gemini CLI-based PR review',
367
+ });
368
+ }
369
+ }
370
+
371
+ return { ctx, stacks, files };
372
+ }
373
+
374
+ // --- Starter builders ---
375
+
376
+ function buildHooksStarter() {
377
+ return JSON.stringify({
378
+ "hooks": {
379
+ "BeforeTool": [
380
+ {
381
+ "command": "echo 'Gemini tool about to execute'",
382
+ "description": "Example BeforeTool hook — customize or remove",
383
+ "timeout_ms": 5000,
384
+ }
385
+ ],
386
+ "AfterTool": [
387
+ {
388
+ "command": "echo 'Gemini tool completed'",
389
+ "description": "Example AfterTool hook — customize or remove",
390
+ "timeout_ms": 5000,
391
+ }
392
+ ],
393
+ }
394
+ }, null, 2) + '\n';
395
+ }
396
+
397
+ function buildCommandsStarter() {
398
+ return [
399
+ '# Gemini CLI Commands',
400
+ '',
401
+ 'Place TOML command files in this directory to extend Gemini CLI.',
402
+ '',
403
+ '## Command format',
404
+ '',
405
+ '```toml',
406
+ 'name = "my-command"',
407
+ 'description = "What this command does"',
408
+ 'prompt = "The prompt template for this command"',
409
+ '```',
410
+ '',
411
+ '## Example command',
412
+ '',
413
+ '```toml',
414
+ 'name = "review"',
415
+ 'description = "Review the current diff for issues"',
416
+ 'prompt = """',
417
+ 'Review the current git diff for bugs, security issues, and style problems.',
418
+ 'Focus on correctness first, then readability.',
419
+ '"""',
420
+ '```',
421
+ '',
422
+ '## Best practices',
423
+ '',
424
+ '- Use kebab-case for command file names (e.g., `code-review.toml`)',
425
+ '- Keep prompts focused and actionable',
426
+ '- Document expected inputs and outputs in the description',
427
+ '',
428
+ `_Generated by nerviq v${version}_`,
429
+ '',
430
+ ].join('\n');
431
+ }
432
+
433
+ function buildAgentsStarter() {
434
+ return [
435
+ '# Gemini CLI Agents',
436
+ '',
437
+ 'Place agent markdown files here to define specialized Gemini CLI agents.',
438
+ '',
439
+ '## Format',
440
+ '',
441
+ 'Each agent file should be a `.md` file with:',
442
+ '- A clear title and purpose',
443
+ '- Specific instructions for the agent role',
444
+ '- Constraints and boundaries',
445
+ '',
446
+ '## Example agent',
447
+ '',
448
+ '```markdown',
449
+ '# Security Reviewer',
450
+ '',
451
+ 'You are a security-focused code reviewer. Check for:',
452
+ '- SQL injection vulnerabilities',
453
+ '- XSS attack vectors',
454
+ '- Hardcoded secrets or credentials',
455
+ '- Insecure dependencies',
456
+ '',
457
+ 'Report findings with severity levels: critical, high, medium, low.',
458
+ '```',
459
+ '',
460
+ '## Best practices',
461
+ '',
462
+ '- Keep agent instructions focused on a single responsibility',
463
+ '- Use markdown files with clear headings',
464
+ '- Document the agent scope and limitations',
465
+ '',
466
+ `_Generated by nerviq v${version}_`,
467
+ '',
468
+ ].join('\n');
469
+ }
470
+
471
+ function buildSkillsStarter() {
472
+ return [
473
+ '# Gemini CLI Skills',
474
+ '',
475
+ 'Place skill directories here. Each skill needs a definition file.',
476
+ '',
477
+ '## Directory structure',
478
+ '',
479
+ '```',
480
+ '.gemini/skills/',
481
+ ' my-skill/',
482
+ ' SKILL.md # Required: name, description, instructions',
483
+ ' helpers.js # Optional: supporting files',
484
+ '```',
485
+ '',
486
+ '## SKILL.md format',
487
+ '',
488
+ '```markdown',
489
+ '---',
490
+ 'name: my-skill',
491
+ 'description: Short description for invocation',
492
+ '---',
493
+ '',
494
+ '# My Skill',
495
+ '',
496
+ 'Instructions for Gemini CLI when this skill is invoked.',
497
+ '```',
498
+ '',
499
+ '## Critical naming rules',
500
+ '',
501
+ '- Use **kebab-case** for skill directory names (e.g., `code-review`, not `CodeReview`)',
502
+ '- Keep descriptions short for bounded context cost',
503
+ '',
504
+ `_Generated by nerviq v${version}_`,
505
+ '',
506
+ ].join('\n');
507
+ }
508
+
509
+ function buildPolicyStarter() {
510
+ return [
511
+ '# Gemini CLI Policy',
512
+ '',
513
+ 'Place TOML policy files here to govern Gemini CLI behavior in this repo.',
514
+ '',
515
+ 'Gemini CLI policy files are a **Gemini-unique feature** for declarative governance.',
516
+ '',
517
+ '## Policy format',
518
+ '',
519
+ '```toml',
520
+ '[policy]',
521
+ 'name = "baseline-safe"',
522
+ 'description = "Safe baseline policy for this repo"',
523
+ '',
524
+ '[rules]',
525
+ 'allow_file_write = true',
526
+ 'allow_file_delete = false',
527
+ 'allow_network = false',
528
+ 'allow_shell_exec = "prompt"',
529
+ 'max_file_size_kb = 1024',
530
+ '',
531
+ '[sandbox]',
532
+ 'mode = "restricted"',
533
+ 'allowed_paths = ["src/", "tests/", "docs/"]',
534
+ 'blocked_paths = [".env", "secrets/", "credentials/"]',
535
+ '```',
536
+ '',
537
+ '## Example policies',
538
+ '',
539
+ '### Locked-down (read-only review)',
540
+ '',
541
+ '```toml',
542
+ '[policy]',
543
+ 'name = "review-only"',
544
+ '',
545
+ '[rules]',
546
+ 'allow_file_write = false',
547
+ 'allow_file_delete = false',
548
+ 'allow_shell_exec = false',
549
+ '```',
550
+ '',
551
+ '### Automation (CI context)',
552
+ '',
553
+ '```toml',
554
+ '[policy]',
555
+ 'name = "ci-automation"',
556
+ '',
557
+ '[rules]',
558
+ 'allow_file_write = true',
559
+ 'allow_shell_exec = true',
560
+ 'require_confirmation = false',
561
+ '```',
562
+ '',
563
+ '## Best practices',
564
+ '',
565
+ '- Start with restrictive policies and relax as needed',
566
+ '- Use `blocked_paths` to protect sensitive files',
567
+ '- Review policy changes in PRs like code changes',
568
+ '- Separate CI policies from local development policies',
569
+ '',
570
+ `_Generated by nerviq v${version}_`,
571
+ '',
572
+ ].join('\n');
573
+ }
574
+
575
+ function buildCiReviewStarter() {
576
+ return [
577
+ 'name: Gemini Review',
578
+ '',
579
+ 'on:',
580
+ ' pull_request:',
581
+ ' types: [opened, synchronize]',
582
+ '',
583
+ 'permissions:',
584
+ ' contents: read',
585
+ ' pull-requests: write',
586
+ '',
587
+ 'jobs:',
588
+ ' gemini-review:',
589
+ ' runs-on: ubuntu-latest',
590
+ ' steps:',
591
+ ' - uses: actions/checkout@v4',
592
+ ' - name: Gemini Review',
593
+ ' uses: google/gemini-code-review-action@v1',
594
+ ' with:',
595
+ ' safety-strategy: review-only',
596
+ ' env:',
597
+ ' GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}',
598
+ ].join('\n') + '\n';
599
+ }
600
+
601
+ async function setupGemini(options) {
602
+ const silent = options.silent === true;
603
+ const { ctx, stacks, files } = buildGeminiSetupFiles(options);
604
+ const writtenFiles = [];
605
+ const preservedFiles = [];
606
+
607
+ function log(message = '') {
608
+ if (!silent) {
609
+ console.log(message);
610
+ }
611
+ }
612
+
613
+ log('');
614
+ log('\x1b[1m nerviq gemini setup\x1b[0m');
615
+ log('\x1b[2m ═══════════════════════════════════════\x1b[0m');
616
+ if (stacks.length > 0) {
617
+ log(`\x1b[36m Detected: ${stacks.map((s) => s.label).join(', ')}\x1b[0m`);
618
+ }
619
+ log('');
620
+
621
+ for (const file of files) {
622
+ const fullPath = path.join(options.dir, file.path);
623
+ if (fs.existsSync(fullPath)) {
624
+ preservedFiles.push(file.path);
625
+ log(` \x1b[2m⏭️ Skipped ${file.path} (already exists — your version is kept)\x1b[0m`);
626
+ continue;
627
+ }
628
+
629
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
630
+ fs.writeFileSync(fullPath, file.content, 'utf8');
631
+ writtenFiles.push(file.path);
632
+ log(` \x1b[32m✅\x1b[0m Created ${file.path}`);
633
+ }
634
+
635
+ const skippedSet = new Set(preservedFiles);
636
+ if (!skippedSet.has('GEMINI.md') && fs.existsSync(path.join(options.dir, 'GEMINI.md')) && !writtenFiles.includes('GEMINI.md')) {
637
+ preservedFiles.push('GEMINI.md');
638
+ }
639
+ if (!skippedSet.has('.gemini/settings.json') && fs.existsSync(path.join(options.dir, '.gemini', 'settings.json')) && !writtenFiles.includes('.gemini/settings.json')) {
640
+ preservedFiles.push('.gemini/settings.json');
641
+ }
642
+
643
+ let rollbackArtifact = null;
644
+ let activityArtifact = null;
645
+ if (writtenFiles.length > 0) {
646
+ rollbackArtifact = writeRollbackArtifact(options.dir, {
647
+ sourcePlan: 'gemini-setup',
648
+ createdFiles: writtenFiles,
649
+ patchedFiles: [],
650
+ rollbackInstructions: writtenFiles.map((file) => `Delete ${file}`),
651
+ });
652
+ activityArtifact = writeActivityArtifact(options.dir, 'gemini-setup', {
653
+ platform: 'gemini',
654
+ createdFiles: writtenFiles,
655
+ preservedFiles,
656
+ stackLabels: stacks.map((item) => item.label),
657
+ rollbackArtifact: rollbackArtifact.relativePath,
658
+ });
659
+ }
660
+
661
+ log('');
662
+ log(` \x1b[1m${writtenFiles.length} files created.\x1b[0m`);
663
+ if (preservedFiles.length > 0) {
664
+ log(` \x1b[2m${preservedFiles.length} existing files preserved (not overwritten).\x1b[0m`);
665
+ }
666
+ if (rollbackArtifact) {
667
+ log(` Rollback: \x1b[1m${rollbackArtifact.relativePath}\x1b[0m`);
668
+ }
669
+ if (activityArtifact) {
670
+ log(` Activity log: \x1b[1m${activityArtifact.relativePath}\x1b[0m`);
671
+ }
672
+ log('');
673
+ log(' Run \x1b[1mnpx nerviq --platform gemini\x1b[0m to audit your Gemini CLI setup.');
674
+ log('');
675
+
676
+ return {
677
+ created: writtenFiles.length,
678
+ skipped: preservedFiles.length,
679
+ writtenFiles,
680
+ preservedFiles,
681
+ stacks,
682
+ rollbackArtifact: rollbackArtifact ? rollbackArtifact.relativePath : null,
683
+ activityArtifact: activityArtifact ? activityArtifact.relativePath : null,
684
+ };
685
+ }
686
+
687
+ module.exports = {
688
+ buildGeminiMd,
689
+ buildSettingsJson,
690
+ buildGeminiSetupFiles,
691
+ setupGemini,
692
+ };