@nerviq/cli 1.17.3 → 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 (190) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +4 -4
  3. package/bin/cli.js +61 -274
  4. package/package.json +60 -60
  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/config-parser.js +280 -226
  46. package/src/copilot/context.js +218 -197
  47. package/src/copilot/deep-review.js +346 -346
  48. package/src/copilot/domain-packs.js +372 -372
  49. package/src/copilot/freshness.js +57 -57
  50. package/src/copilot/governance.js +222 -222
  51. package/src/copilot/interactive.js +406 -406
  52. package/src/copilot/mcp-packs.js +826 -826
  53. package/src/copilot/plans.js +253 -253
  54. package/src/copilot/premium.js +451 -451
  55. package/src/copilot/setup.js +488 -488
  56. package/src/copilot/techniques.js +219 -78
  57. package/src/cost-tracking.js +61 -61
  58. package/src/cursor/activity.js +301 -301
  59. package/src/cursor/config-parser.js +265 -265
  60. package/src/cursor/context.js +256 -256
  61. package/src/cursor/deep-review.js +334 -334
  62. package/src/cursor/domain-packs.js +368 -368
  63. package/src/cursor/freshness.js +65 -65
  64. package/src/cursor/governance.js +229 -229
  65. package/src/cursor/interactive.js +391 -391
  66. package/src/cursor/mcp-packs.js +828 -828
  67. package/src/cursor/plans.js +254 -254
  68. package/src/cursor/premium.js +469 -469
  69. package/src/cursor/setup.js +488 -488
  70. package/src/dashboard.js +493 -493
  71. package/src/deep-review.js +428 -428
  72. package/src/deprecation.js +98 -98
  73. package/src/diff-only.js +280 -280
  74. package/src/doctor.js +119 -119
  75. package/src/domain-pack-expansion.js +1033 -1033
  76. package/src/domain-packs.js +387 -387
  77. package/src/feedback.js +178 -178
  78. package/src/fix-engine.js +783 -0
  79. package/src/fix-prompts.js +122 -122
  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/context.js +221 -221
  84. package/src/gemini/deep-review.js +559 -559
  85. package/src/gemini/domain-packs.js +393 -393
  86. package/src/gemini/freshness.js +66 -66
  87. package/src/gemini/governance.js +201 -201
  88. package/src/gemini/interactive.js +860 -860
  89. package/src/gemini/mcp-packs.js +915 -915
  90. package/src/gemini/plans.js +269 -269
  91. package/src/gemini/premium.js +760 -760
  92. package/src/gemini/setup.js +692 -692
  93. package/src/gemini/techniques.js +14 -14
  94. package/src/governance.js +72 -72
  95. package/src/harmony/add.js +68 -68
  96. package/src/harmony/advisor.js +333 -333
  97. package/src/harmony/canon.js +565 -565
  98. package/src/harmony/cli.js +591 -591
  99. package/src/harmony/drift.js +401 -401
  100. package/src/harmony/governance.js +313 -313
  101. package/src/harmony/memory.js +239 -239
  102. package/src/harmony/sync.js +475 -475
  103. package/src/harmony/watch.js +370 -370
  104. package/src/hook-validation.js +342 -342
  105. package/src/index.js +271 -271
  106. package/src/init.js +184 -184
  107. package/src/instruction-surfaces.js +185 -185
  108. package/src/integrations.js +144 -144
  109. package/src/interactive.js +118 -118
  110. package/src/locales/en.json +1 -1
  111. package/src/locales/es.json +1 -1
  112. package/src/mcp-packs.js +830 -830
  113. package/src/mcp-server.js +726 -726
  114. package/src/mcp-validation.js +337 -337
  115. package/src/nerviq-sync.json +7 -7
  116. package/src/opencode/config-parser.js +109 -109
  117. package/src/opencode/context.js +247 -247
  118. package/src/opencode/deep-review.js +313 -313
  119. package/src/opencode/domain-packs.js +262 -262
  120. package/src/opencode/freshness.js +66 -66
  121. package/src/opencode/governance.js +159 -159
  122. package/src/opencode/interactive.js +392 -392
  123. package/src/opencode/mcp-packs.js +705 -705
  124. package/src/opencode/patch.js +184 -184
  125. package/src/opencode/plans.js +231 -231
  126. package/src/opencode/premium.js +413 -413
  127. package/src/opencode/setup.js +449 -449
  128. package/src/opencode/techniques.js +27 -27
  129. package/src/operating-profile.js +574 -574
  130. package/src/org.js +152 -152
  131. package/src/permission-rules.js +218 -218
  132. package/src/plans.js +839 -839
  133. package/src/platform-change-manifest.js +86 -86
  134. package/src/plugins.js +110 -110
  135. package/src/policy-layers.js +210 -210
  136. package/src/profiles.js +124 -124
  137. package/src/prompt-injection.js +74 -74
  138. package/src/public-api.js +173 -173
  139. package/src/recommendation-rules.js +84 -84
  140. package/src/repo-archetype.js +386 -386
  141. package/src/secret-patterns.js +39 -39
  142. package/src/server.js +527 -527
  143. package/src/setup/analysis.js +607 -607
  144. package/src/setup/runtime.js +172 -172
  145. package/src/setup.js +677 -677
  146. package/src/shared/capabilities.js +194 -194
  147. package/src/source-urls.js +132 -132
  148. package/src/stack-checks.js +565 -565
  149. package/src/supplemental-checks.js +13 -13
  150. package/src/synergy/adaptive.js +261 -261
  151. package/src/synergy/compensation.js +137 -137
  152. package/src/synergy/evidence.js +193 -193
  153. package/src/synergy/learning.js +199 -199
  154. package/src/synergy/patterns.js +227 -227
  155. package/src/synergy/ranking.js +83 -83
  156. package/src/synergy/report.js +165 -165
  157. package/src/synergy/routing.js +146 -146
  158. package/src/techniques/api.js +407 -407
  159. package/src/techniques/automation.js +316 -316
  160. package/src/techniques/compliance.js +257 -257
  161. package/src/techniques/hygiene.js +294 -294
  162. package/src/techniques/instructions.js +243 -243
  163. package/src/techniques/observability.js +226 -226
  164. package/src/techniques/optimization.js +142 -142
  165. package/src/techniques/quality.js +318 -318
  166. package/src/techniques/security.js +237 -237
  167. package/src/techniques/shared.js +443 -443
  168. package/src/techniques/stacks.js +2294 -2294
  169. package/src/techniques/tools.js +106 -106
  170. package/src/techniques/workflow.js +413 -413
  171. package/src/techniques.js +81 -81
  172. package/src/terminology.js +73 -73
  173. package/src/token-estimate.js +35 -35
  174. package/src/usage-patterns.js +99 -99
  175. package/src/verification-metadata.js +145 -145
  176. package/src/watch.js +247 -247
  177. package/src/windsurf/activity.js +302 -302
  178. package/src/windsurf/config-parser.js +267 -267
  179. package/src/windsurf/context.js +249 -249
  180. package/src/windsurf/deep-review.js +337 -337
  181. package/src/windsurf/domain-packs.js +370 -370
  182. package/src/windsurf/freshness.js +36 -36
  183. package/src/windsurf/governance.js +231 -231
  184. package/src/windsurf/interactive.js +388 -388
  185. package/src/windsurf/mcp-packs.js +792 -792
  186. package/src/windsurf/plans.js +247 -247
  187. package/src/windsurf/premium.js +468 -468
  188. package/src/windsurf/setup.js +471 -471
  189. package/src/windsurf/techniques.js +17 -17
  190. 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
+ };