@nerviq/cli 1.20.1 → 1.21.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 (181) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/package.json +1 -1
  4. package/src/activity.js +1039 -1039
  5. package/src/adoption-advisor.js +299 -299
  6. package/src/aider/config-parser.js +166 -166
  7. package/src/aider/context.js +4 -1
  8. package/src/aider/deep-review.js +316 -316
  9. package/src/aider/domain-packs.js +303 -303
  10. package/src/aider/freshness.js +93 -93
  11. package/src/aider/governance.js +253 -253
  12. package/src/aider/interactive.js +334 -334
  13. package/src/aider/mcp-packs.js +329 -329
  14. package/src/aider/patch.js +214 -214
  15. package/src/aider/plans.js +186 -186
  16. package/src/aider/premium.js +360 -360
  17. package/src/aider/setup.js +404 -404
  18. package/src/aider/techniques.js +312 -67
  19. package/src/analyze.js +951 -951
  20. package/src/anti-patterns.js +485 -485
  21. package/src/audit/instruction-files.js +180 -180
  22. package/src/audit/recommendations.js +577 -577
  23. package/src/auto-suggest.js +154 -154
  24. package/src/badge.js +13 -13
  25. package/src/behavioral-drift.js +801 -801
  26. package/src/benchmark.js +67 -67
  27. package/src/catalog.js +103 -103
  28. package/src/certification.js +128 -128
  29. package/src/codex/config-parser.js +183 -183
  30. package/src/codex/context.js +223 -223
  31. package/src/codex/deep-review.js +493 -493
  32. package/src/codex/domain-packs.js +394 -394
  33. package/src/codex/freshness.js +84 -84
  34. package/src/codex/governance.js +192 -192
  35. package/src/codex/interactive.js +618 -618
  36. package/src/codex/mcp-packs.js +914 -914
  37. package/src/codex/patch.js +209 -209
  38. package/src/codex/plans.js +251 -251
  39. package/src/codex/premium.js +614 -614
  40. package/src/codex/setup.js +591 -591
  41. package/src/continuous-ops.js +681 -681
  42. package/src/copilot/activity.js +309 -309
  43. package/src/copilot/deep-review.js +346 -346
  44. package/src/copilot/domain-packs.js +372 -372
  45. package/src/copilot/freshness.js +57 -57
  46. package/src/copilot/governance.js +222 -222
  47. package/src/copilot/interactive.js +406 -406
  48. package/src/copilot/mcp-packs.js +826 -826
  49. package/src/copilot/plans.js +253 -253
  50. package/src/copilot/premium.js +451 -451
  51. package/src/copilot/setup.js +488 -488
  52. package/src/cost-tracking.js +61 -61
  53. package/src/cursor/activity.js +301 -301
  54. package/src/cursor/config-parser.js +265 -265
  55. package/src/cursor/context.js +256 -256
  56. package/src/cursor/deep-review.js +334 -334
  57. package/src/cursor/domain-packs.js +368 -368
  58. package/src/cursor/freshness.js +65 -65
  59. package/src/cursor/governance.js +229 -229
  60. package/src/cursor/interactive.js +391 -391
  61. package/src/cursor/mcp-packs.js +828 -828
  62. package/src/cursor/plans.js +254 -254
  63. package/src/cursor/premium.js +469 -469
  64. package/src/cursor/setup.js +488 -488
  65. package/src/dashboard.js +493 -493
  66. package/src/deep-review.js +428 -428
  67. package/src/deprecation.js +98 -98
  68. package/src/diff-only.js +280 -280
  69. package/src/doctor.js +119 -119
  70. package/src/domain-pack-expansion.js +1033 -1033
  71. package/src/domain-packs.js +387 -387
  72. package/src/feedback.js +178 -178
  73. package/src/fix-engine.js +783 -783
  74. package/src/fix-prompts.js +122 -122
  75. package/src/formatters/sarif.js +115 -115
  76. package/src/freshness.js +74 -74
  77. package/src/gemini/config-parser.js +275 -275
  78. package/src/gemini/deep-review.js +559 -559
  79. package/src/gemini/domain-packs.js +393 -393
  80. package/src/gemini/freshness.js +66 -66
  81. package/src/gemini/governance.js +201 -201
  82. package/src/gemini/interactive.js +860 -860
  83. package/src/gemini/mcp-packs.js +915 -915
  84. package/src/gemini/plans.js +269 -269
  85. package/src/gemini/premium.js +760 -760
  86. package/src/gemini/setup.js +692 -692
  87. package/src/governance.js +72 -72
  88. package/src/harmony/add.js +68 -68
  89. package/src/harmony/advisor.js +333 -333
  90. package/src/harmony/canon.js +565 -565
  91. package/src/harmony/cli.js +591 -591
  92. package/src/harmony/drift.js +401 -401
  93. package/src/harmony/governance.js +313 -313
  94. package/src/harmony/memory.js +239 -239
  95. package/src/harmony/sync.js +475 -475
  96. package/src/harmony/watch.js +370 -370
  97. package/src/hook-validation.js +342 -342
  98. package/src/index.js +271 -271
  99. package/src/init.js +184 -184
  100. package/src/instruction-surfaces.js +185 -185
  101. package/src/integrations.js +144 -144
  102. package/src/interactive.js +118 -118
  103. package/src/locales/en.json +1 -1
  104. package/src/locales/es.json +1 -1
  105. package/src/mcp-packs.js +830 -830
  106. package/src/mcp-server.js +726 -726
  107. package/src/mcp-validation.js +337 -337
  108. package/src/nerviq-sync.json +7 -7
  109. package/src/opencode/config-parser.js +109 -109
  110. package/src/opencode/context.js +247 -247
  111. package/src/opencode/deep-review.js +313 -313
  112. package/src/opencode/domain-packs.js +262 -262
  113. package/src/opencode/freshness.js +66 -66
  114. package/src/opencode/governance.js +159 -159
  115. package/src/opencode/interactive.js +392 -392
  116. package/src/opencode/mcp-packs.js +705 -705
  117. package/src/opencode/patch.js +184 -184
  118. package/src/opencode/plans.js +231 -231
  119. package/src/opencode/premium.js +413 -413
  120. package/src/opencode/setup.js +449 -449
  121. package/src/opencode/techniques.js +27 -27
  122. package/src/operating-profile.js +574 -574
  123. package/src/org.js +152 -152
  124. package/src/permission-rules.js +218 -218
  125. package/src/plans.js +839 -839
  126. package/src/platform-change-manifest.js +86 -86
  127. package/src/plugins.js +110 -110
  128. package/src/policy-layers.js +210 -210
  129. package/src/profiles.js +124 -124
  130. package/src/prompt-injection.js +74 -74
  131. package/src/public-api.js +173 -173
  132. package/src/recommendation-rules.js +84 -84
  133. package/src/repo-archetype.js +386 -386
  134. package/src/secret-patterns.js +39 -39
  135. package/src/server.js +527 -527
  136. package/src/setup/analysis.js +607 -607
  137. package/src/setup/runtime.js +172 -172
  138. package/src/setup.js +677 -677
  139. package/src/shared/capabilities.js +194 -194
  140. package/src/source-urls.js +132 -132
  141. package/src/stack-checks.js +565 -565
  142. package/src/supplemental-checks.js +13 -13
  143. package/src/synergy/adaptive.js +261 -261
  144. package/src/synergy/compensation.js +137 -137
  145. package/src/synergy/evidence.js +193 -193
  146. package/src/synergy/learning.js +199 -199
  147. package/src/synergy/patterns.js +227 -227
  148. package/src/synergy/ranking.js +83 -83
  149. package/src/synergy/report.js +165 -165
  150. package/src/synergy/routing.js +146 -146
  151. package/src/techniques/api.js +407 -407
  152. package/src/techniques/automation.js +316 -316
  153. package/src/techniques/compliance.js +257 -257
  154. package/src/techniques/hygiene.js +294 -294
  155. package/src/techniques/instructions.js +243 -243
  156. package/src/techniques/observability.js +226 -226
  157. package/src/techniques/optimization.js +142 -142
  158. package/src/techniques/quality.js +318 -318
  159. package/src/techniques/security.js +237 -237
  160. package/src/techniques/shared.js +443 -443
  161. package/src/techniques/stacks.js +2294 -2294
  162. package/src/techniques/tools.js +106 -106
  163. package/src/techniques/workflow.js +413 -413
  164. package/src/techniques.js +81 -81
  165. package/src/terminology.js +73 -73
  166. package/src/token-estimate.js +35 -35
  167. package/src/usage-patterns.js +99 -99
  168. package/src/verification-metadata.js +145 -145
  169. package/src/watch.js +247 -247
  170. package/src/windsurf/activity.js +302 -302
  171. package/src/windsurf/config-parser.js +267 -267
  172. package/src/windsurf/deep-review.js +337 -337
  173. package/src/windsurf/domain-packs.js +370 -370
  174. package/src/windsurf/freshness.js +36 -36
  175. package/src/windsurf/governance.js +231 -231
  176. package/src/windsurf/interactive.js +388 -388
  177. package/src/windsurf/mcp-packs.js +792 -792
  178. package/src/windsurf/plans.js +247 -247
  179. package/src/windsurf/premium.js +468 -468
  180. package/src/windsurf/setup.js +471 -471
  181. package/src/workspace.js +375 -375
@@ -1,860 +1,860 @@
1
- /**
2
- * Gemini CLI Interactive Wizard
3
- *
4
- * 10-stage guided setup for Gemini CLI projects.
5
- * Uses Node.js readline (zero dependencies), same pattern as the Claude/Codex wizard.
6
- *
7
- * Stages:
8
- * 1. Project detection (stacks, existing .gemini/)
9
- * 2. Trust & approval (normal/auto_edit/yolo)
10
- * 3. Sandbox selection (OS-aware: Seatbelt for macOS, Docker for Linux, etc.)
11
- * 4. Agent structure
12
- * 5. Domain pack selection
13
- * 6. MCP pack selection
14
- * 7. Policy tier config (Gemini-unique!)
15
- * 8. Hook configuration (BeforeTool/AfterTool)
16
- * 9. CI integration
17
- * 10. Review & generate
18
- */
19
-
20
- const fs = require('fs');
21
- const os = require('os');
22
- const path = require('path');
23
- const readline = require('readline');
24
- const { STACKS } = require('../techniques');
25
- const { GeminiProjectContext } = require('./context');
26
- const { GEMINI_TECHNIQUES } = require('./techniques');
27
- const { GEMINI_DOMAIN_PACKS, detectGeminiDomainPacks } = require('./domain-packs');
28
- const { recommendGeminiMcpPacks, GEMINI_MCP_PACKS } = require('./mcp-packs');
29
-
30
- // ---------------------------------------------------------------------------
31
- // Colors & helpers (matches Claude/Codex interactive.js)
32
- // ---------------------------------------------------------------------------
33
-
34
- const COLORS = {
35
- reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
36
- red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m',
37
- blue: '\x1b[36m', magenta: '\x1b[35m',
38
- };
39
- const c = (text, color) => `${COLORS[color] || ''}${text}${COLORS.reset}`;
40
-
41
- function ask(rl, question) {
42
- return new Promise(resolve => rl.question(question, resolve));
43
- }
44
-
45
- function isTTY() {
46
- return Boolean(process.stdin.isTTY && process.stdout.isTTY);
47
- }
48
-
49
- // ---------------------------------------------------------------------------
50
- // Stage definitions
51
- // ---------------------------------------------------------------------------
52
-
53
- const STAGE_NAMES = [
54
- 'Project Detection',
55
- 'Trust & Approval',
56
- 'Sandbox Selection',
57
- 'Agent Structure',
58
- 'Domain Pack Selection',
59
- 'MCP Pack Selection',
60
- 'Policy Tier Config',
61
- 'Hook Configuration',
62
- 'CI Integration',
63
- 'Review & Generate',
64
- ];
65
-
66
- function printStageHeader(index) {
67
- const num = index + 1;
68
- const total = STAGE_NAMES.length;
69
- console.log('');
70
- console.log(c(` ── Stage ${num}/${total}: ${STAGE_NAMES[index]} ──`, 'magenta'));
71
- console.log('');
72
- }
73
-
74
- // ---------------------------------------------------------------------------
75
- // Stage 1 — Project Detection
76
- // ---------------------------------------------------------------------------
77
-
78
- function runProjectDetection(ctx) {
79
- const stacks = ctx.detectStacks(STACKS);
80
- const hasGeminiDir = fs.existsSync(path.join(ctx.dir, '.gemini'));
81
- const hasGeminiMd = Boolean(ctx.geminiMdContent());
82
- const settingsResult = ctx.settingsJson();
83
- const hasSettings = settingsResult.ok;
84
-
85
- // Quick audit
86
- const auditResults = [];
87
- for (const [key, technique] of Object.entries(GEMINI_TECHNIQUES)) {
88
- auditResults.push({ key, ...technique, passed: technique.check(ctx) });
89
- }
90
- const passed = auditResults.filter(r => r.passed === true);
91
- const failed = auditResults.filter(r => r.passed === false);
92
-
93
- return { stacks, hasGeminiDir, hasGeminiMd, hasSettings, auditResults, passed, failed };
94
- }
95
-
96
- async function stageProjectDetection(rl, ctx, state) {
97
- printStageHeader(0);
98
- const det = runProjectDetection(ctx);
99
- Object.assign(state, det);
100
-
101
- if (det.stacks.length > 0) {
102
- console.log(c(` Detected stacks: ${det.stacks.map(s => s.label).join(', ')}`, 'blue'));
103
- } else {
104
- console.log(c(' No specific stack detected — will use baseline defaults.', 'dim'));
105
- }
106
-
107
- console.log(c(` Working directory: ${ctx.dir}`, 'dim'));
108
- console.log('');
109
- console.log(` ${c(`${det.passed.length}/${det.auditResults.length}`, 'bold')} Gemini checks passing.`);
110
- console.log(` ${c(String(det.failed.length), 'yellow')} improvements available.`);
111
-
112
- if (det.hasGeminiDir || det.hasGeminiMd) {
113
- console.log('');
114
- console.log(c(' Existing Gemini configuration detected:', 'yellow'));
115
- if (det.hasGeminiDir) console.log(c(' .gemini/ directory found', 'dim'));
116
- if (det.hasGeminiMd) console.log(c(' GEMINI.md found', 'dim'));
117
- if (det.hasSettings) console.log(c(' .gemini/settings.json found', 'dim'));
118
- console.log('');
119
-
120
- const migrationAnswer = await ask(rl, c(' Merge with existing config or replace? (merge/replace/quit) ', 'magenta'));
121
- const choice = migrationAnswer.trim().toLowerCase();
122
- if (choice === 'quit' || choice === 'q') return 'quit';
123
- state.migrationMode = choice === 'replace' ? 'replace' : 'merge';
124
- console.log(c(` → ${state.migrationMode === 'replace' ? 'Will replace existing files' : 'Will merge with existing config'}`, 'green'));
125
- } else {
126
- state.migrationMode = 'create';
127
- console.log('');
128
- console.log(c(' No existing Gemini config — will create fresh setup.', 'dim'));
129
- }
130
-
131
- return 'next';
132
- }
133
-
134
- // ---------------------------------------------------------------------------
135
- // Stage 2 — Trust & Approval
136
- // ---------------------------------------------------------------------------
137
-
138
- const TRUST_POLICIES = [
139
- { key: 'normal', label: 'Normal (safest)', desc: 'Gemini asks approval for all tool calls and edits.' },
140
- { key: 'auto_edit', label: 'Auto-Edit (balanced)', desc: 'Gemini can edit files but asks before running commands.' },
141
- { key: 'yolo', label: 'YOLO (maximum autonomy)', desc: 'Gemini runs everything automatically. Use only in trusted sandboxes.' },
142
- ];
143
-
144
- async function stageTrustApproval(rl, _ctx, state) {
145
- printStageHeader(1);
146
-
147
- console.log(' Select a trust level for Gemini CLI:');
148
- console.log('');
149
- TRUST_POLICIES.forEach((p, i) => {
150
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(p.label, 'blue')} — ${p.desc}`);
151
- });
152
- console.log('');
153
-
154
- const answer = await ask(rl, c(' Choice (1-3, or b=back, q=quit) [1]: ', 'magenta'));
155
- const trimmed = answer.trim().toLowerCase();
156
- if (trimmed === 'b') return 'back';
157
- if (trimmed === 'q') return 'quit';
158
-
159
- const index = parseInt(trimmed, 10);
160
- const selected = TRUST_POLICIES[(index >= 1 && index <= 3) ? index - 1 : 0];
161
- state.trustLevel = selected.key;
162
- console.log(c(` → Trust level: ${selected.label}`, 'green'));
163
-
164
- if (selected.key === 'yolo') {
165
- console.log('');
166
- console.log(c(' ⚠ YOLO mode grants full autonomy. Ensure a sandbox is configured in the next stage.', 'yellow'));
167
- }
168
-
169
- return 'next';
170
- }
171
-
172
- // ---------------------------------------------------------------------------
173
- // Stage 3 — Sandbox Selection (OS-aware)
174
- // ---------------------------------------------------------------------------
175
-
176
- function detectOS() {
177
- const platform = os.platform();
178
- if (platform === 'darwin') return 'macOS';
179
- if (platform === 'linux') return 'Linux';
180
- if (platform === 'win32') return 'Windows';
181
- return platform;
182
- }
183
-
184
- const SANDBOX_OPTIONS = {
185
- macOS: [
186
- { key: 'seatbelt', label: 'Seatbelt (recommended)', desc: 'macOS sandboxing via sandbox-exec. Blocks network/disk outside project.' },
187
- { key: 'docker', label: 'Docker', desc: 'Full container isolation. Requires Docker Desktop.' },
188
- { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
189
- ],
190
- Linux: [
191
- { key: 'docker', label: 'Docker (recommended)', desc: 'Full container isolation with volume mounts.' },
192
- { key: 'firejail', label: 'Firejail', desc: 'Lightweight Linux sandbox. Good for quick isolation.' },
193
- { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
194
- ],
195
- Windows: [
196
- { key: 'docker', label: 'Docker (recommended)', desc: 'Full container isolation via Docker Desktop / WSL2.' },
197
- { key: 'wsl', label: 'WSL2 Isolation', desc: 'Run Gemini inside a WSL2 distro for basic isolation.' },
198
- { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
199
- ],
200
- };
201
-
202
- async function stageSandboxSelection(rl, _ctx, state) {
203
- printStageHeader(2);
204
-
205
- const detectedOS = detectOS();
206
- const options = SANDBOX_OPTIONS[detectedOS] || SANDBOX_OPTIONS.Linux;
207
-
208
- console.log(c(` Detected OS: ${detectedOS}`, 'blue'));
209
- console.log('');
210
- console.log(' Select a sandbox mode:');
211
- console.log('');
212
- options.forEach((opt, i) => {
213
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(opt.label, 'blue')} — ${opt.desc}`);
214
- });
215
- console.log('');
216
-
217
- const answer = await ask(rl, c(` Choice (1-${options.length}, or b=back, q=quit) [1]: `, 'magenta'));
218
- const trimmed = answer.trim().toLowerCase();
219
- if (trimmed === 'b') return 'back';
220
- if (trimmed === 'q') return 'quit';
221
-
222
- const index = parseInt(trimmed, 10);
223
- const selected = options[(index >= 1 && index <= options.length) ? index - 1 : 0];
224
- state.sandboxMode = selected.key;
225
- state.detectedOS = detectedOS;
226
- console.log(c(` → Sandbox: ${selected.label}`, 'green'));
227
-
228
- if (selected.key === 'none' && state.trustLevel === 'yolo') {
229
- console.log('');
230
- console.log(c(' ⚠ WARNING: YOLO mode without sandbox is extremely risky!', 'red'));
231
- console.log(c(' Consider adding at least Docker or OS-level sandboxing.', 'yellow'));
232
- }
233
-
234
- return 'next';
235
- }
236
-
237
- // ---------------------------------------------------------------------------
238
- // Stage 4 — Agent Structure
239
- // ---------------------------------------------------------------------------
240
-
241
- async function stageAgentStructure(rl, _ctx, state) {
242
- printStageHeader(3);
243
-
244
- console.log(' How should Gemini operate in this project?');
245
- console.log('');
246
- console.log(` ${c('1', 'bold')}. ${c('Single agent', 'blue')} — One Gemini agent handles everything (simpler, good for small repos).`);
247
- console.log(` ${c('2', 'bold')}. ${c('Multi-agent', 'blue')} — Orchestrator + specialized sub-agents (better for large repos).`);
248
- console.log('');
249
-
250
- const answer = await ask(rl, c(' Choice (1-2, or b=back, q=quit) [1]: ', 'magenta'));
251
- const trimmed = answer.trim().toLowerCase();
252
- if (trimmed === 'b') return 'back';
253
- if (trimmed === 'q') return 'quit';
254
-
255
- state.agentMode = trimmed === '2' ? 'multi' : 'single';
256
- console.log(c(` → Agent mode: ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`, 'green'));
257
-
258
- if (state.agentMode === 'multi') {
259
- console.log('');
260
- console.log(c(' Will generate .gemini/agents/ with sub-agent markdown starters.', 'dim'));
261
- }
262
-
263
- return 'next';
264
- }
265
-
266
- // ---------------------------------------------------------------------------
267
- // Stage 5 — Domain Pack Selection
268
- // ---------------------------------------------------------------------------
269
-
270
- async function stageDomainPacks(rl, ctx, state) {
271
- printStageHeader(4);
272
-
273
- const detected = detectGeminiDomainPacks(ctx, state.stacks || []);
274
- const detectedKeys = new Set(detected.map(p => p.key));
275
-
276
- console.log(' Available domain packs:');
277
- console.log('');
278
-
279
- const allPacks = GEMINI_DOMAIN_PACKS.map(pack => {
280
- const isDetected = detectedKeys.has(pack.key);
281
- return { ...pack, isDetected };
282
- });
283
-
284
- allPacks.forEach((pack, i) => {
285
- const marker = pack.isDetected ? c(' (detected)', 'green') : '';
286
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}`);
287
- console.log(c(` ${pack.useWhen}`, 'dim'));
288
- });
289
- console.log('');
290
-
291
- const defaultSelection = allPacks
292
- .map((p, i) => p.isDetected ? String(i + 1) : null)
293
- .filter(Boolean)
294
- .join(',');
295
-
296
- const answer = await ask(rl, c(` Select packs (comma-separated numbers, or b=back, q=quit) [${defaultSelection || 'all detected'}]: `, 'magenta'));
297
- const trimmed = answer.trim().toLowerCase();
298
- if (trimmed === 'b') return 'back';
299
- if (trimmed === 'q') return 'quit';
300
-
301
- let selectedPacks;
302
- if (trimmed === '' || trimmed === 'all') {
303
- selectedPacks = detected;
304
- } else {
305
- const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < allPacks.length);
306
- selectedPacks = indices.map(i => allPacks[i]);
307
- }
308
-
309
- state.domainPacks = selectedPacks;
310
- console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
311
-
312
- return 'next';
313
- }
314
-
315
- // ---------------------------------------------------------------------------
316
- // Stage 6 — MCP Pack Selection
317
- // ---------------------------------------------------------------------------
318
-
319
- async function stageMcpPacks(rl, ctx, state) {
320
- printStageHeader(5);
321
-
322
- const recommended = recommendGeminiMcpPacks(state.stacks || [], state.domainPacks || [], { ctx });
323
- const recommendedKeys = new Set(recommended.map(p => p.key));
324
-
325
- console.log(' Available MCP packs:');
326
- console.log('');
327
-
328
- GEMINI_MCP_PACKS.forEach((pack, i) => {
329
- const isRec = recommendedKeys.has(pack.key);
330
- const marker = isRec ? c(' (recommended)', 'green') : '';
331
- const authNote = pack.requiredAuth.length > 0
332
- ? c(` [requires: ${pack.requiredAuth.join(', ')}]`, 'yellow')
333
- : '';
334
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}${authNote}`);
335
- console.log(c(` ${pack.description}`, 'dim'));
336
- });
337
- console.log('');
338
-
339
- const defaultSelection = GEMINI_MCP_PACKS
340
- .map((p, i) => recommendedKeys.has(p.key) ? String(i + 1) : null)
341
- .filter(Boolean)
342
- .join(',');
343
-
344
- const answer = await ask(rl, c(` Select packs (comma-separated numbers, n=none, b=back, q=quit) [${defaultSelection || 'none'}]: `, 'magenta'));
345
- const trimmed = answer.trim().toLowerCase();
346
- if (trimmed === 'b') return 'back';
347
- if (trimmed === 'q') return 'quit';
348
-
349
- let selectedPacks;
350
- if (trimmed === 'n' || trimmed === 'none') {
351
- selectedPacks = [];
352
- } else if (trimmed === '') {
353
- selectedPacks = recommended;
354
- } else {
355
- const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < GEMINI_MCP_PACKS.length);
356
- selectedPacks = indices.map(i => GEMINI_MCP_PACKS[i]);
357
- }
358
-
359
- state.mcpPacks = selectedPacks;
360
- console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
361
-
362
- return 'next';
363
- }
364
-
365
- // ---------------------------------------------------------------------------
366
- // Stage 7 — Policy Tier Config (Gemini-unique!)
367
- // ---------------------------------------------------------------------------
368
-
369
- const POLICY_TIERS = [
370
- { key: 'none', label: 'No Policy Engine', desc: 'Trust is managed entirely via settings.json and sandbox.' },
371
- { key: 'basic', label: 'Basic Policies', desc: 'File-type restrictions and read-only directories.' },
372
- { key: 'standard', label: 'Standard Policies', desc: 'File-type + tool restrictions + sensitive path protection.' },
373
- { key: 'strict', label: 'Strict Governance', desc: 'Full policy engine with audit trail, approval escalation, and deny-lists.' },
374
- ];
375
-
376
- async function stagePolicyTier(rl, _ctx, state) {
377
- printStageHeader(6);
378
-
379
- console.log(' Gemini CLI supports a policy engine for fine-grained control.');
380
- console.log(c(' Policies live in .gemini/policy/*.toml and complement settings.json.', 'dim'));
381
- console.log('');
382
-
383
- POLICY_TIERS.forEach((tier, i) => {
384
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(tier.label, 'blue')} — ${tier.desc}`);
385
- });
386
- console.log('');
387
-
388
- // Recommend tier based on trust level
389
- let recommended = 1;
390
- if (state.trustLevel === 'yolo') recommended = 3;
391
- else if (state.trustLevel === 'auto_edit') recommended = 2;
392
-
393
- const answer = await ask(rl, c(` Choice (1-4, or b=back, q=quit) [${recommended}]: `, 'magenta'));
394
- const trimmed = answer.trim().toLowerCase();
395
- if (trimmed === 'b') return 'back';
396
- if (trimmed === 'q') return 'quit';
397
-
398
- const index = parseInt(trimmed, 10);
399
- const selected = POLICY_TIERS[(index >= 1 && index <= 4) ? index - 1 : recommended - 1];
400
- state.policyTier = selected.key;
401
- console.log(c(` → Policy tier: ${selected.label}`, 'green'));
402
-
403
- if (selected.key === 'strict') {
404
- console.log('');
405
- console.log(c(' Will generate .gemini/policy/ with governance TOML files.', 'dim'));
406
- console.log(c(' Includes: file-restrictions, tool-deny-list, audit-escalation.', 'dim'));
407
- } else if (selected.key === 'standard') {
408
- console.log('');
409
- console.log(c(' Will generate .gemini/policy/ with standard restriction rules.', 'dim'));
410
- } else if (selected.key === 'basic') {
411
- console.log('');
412
- console.log(c(' Will generate .gemini/policy/ with basic file-type restrictions.', 'dim'));
413
- }
414
-
415
- return 'next';
416
- }
417
-
418
- // ---------------------------------------------------------------------------
419
- // Stage 8 — Hook Configuration (BeforeTool/AfterTool)
420
- // ---------------------------------------------------------------------------
421
-
422
- const COMMON_HOOKS = [
423
- { key: 'before-scrub-secrets', event: 'BeforeTool', label: 'Scrub secrets from tool inputs', command: "grep -rn 'sk-\\|AKIA\\|ghp_\\|xox[baprs]-' . && echo 'BLOCKED: secret detected' && exit 1 || true" },
424
- { key: 'before-lint', event: 'BeforeTool', label: 'Lint check before edits', command: 'npm run lint --silent 2>/dev/null || true' },
425
- { key: 'after-redact', event: 'AfterTool', label: 'Redact sensitive output', command: "sed 's/sk-[A-Za-z0-9_-]\\{20,\\}/[REDACTED]/g'" },
426
- { key: 'after-test', event: 'AfterTool', label: 'Run tests after changes', command: 'npm test --silent 2>/dev/null || true' },
427
- { key: 'before-block-dangerous', event: 'BeforeTool', label: 'Block dangerous commands (rm -rf, chmod 777)', command: "echo \"$TOOL_INPUT\" | grep -qE 'rm -rf /|chmod 777|curl.*\\| bash' && echo 'BLOCKED: dangerous command' && exit 1 || true" },
428
- { key: 'after-size-check', event: 'AfterTool', label: 'Check output size limits', command: "wc -c < /dev/stdin | awk '{if ($1 > 100000) {print \"WARNING: large output\"; exit 1}}' || true" },
429
- ];
430
-
431
- async function stageHooks(rl, _ctx, state) {
432
- printStageHeader(7);
433
-
434
- console.log(' Configure Gemini hooks (BeforeTool and AfterTool lifecycle events):');
435
- console.log(c(' BeforeTool: runs before each tool call (validate, scrub, block)', 'dim'));
436
- console.log(c(' AfterTool: runs after each tool call (redact, test, audit)', 'dim'));
437
- console.log('');
438
-
439
- const answer = await ask(rl, c(' Enable hooks? (y/n, b=back, q=quit) [y]: ', 'magenta'));
440
- const trimmed = answer.trim().toLowerCase();
441
- if (trimmed === 'b') return 'back';
442
- if (trimmed === 'q') return 'quit';
443
-
444
- if (trimmed === 'n') {
445
- state.hooks = [];
446
- state.hooksEnabled = false;
447
- console.log(c(' → Hooks disabled.', 'dim'));
448
- return 'next';
449
- }
450
-
451
- state.hooksEnabled = true;
452
- console.log('');
453
- console.log(' Available hook patterns:');
454
- console.log('');
455
-
456
- COMMON_HOOKS.forEach((hook, i) => {
457
- const eventColor = hook.event === 'BeforeTool' ? 'yellow' : 'blue';
458
- console.log(` ${c(`${i + 1}`, 'bold')}. ${c(hook.label, 'blue')} (${c(hook.event, eventColor)})`);
459
- console.log(c(` ${hook.command.slice(0, 80)}${hook.command.length > 80 ? '...' : ''}`, 'dim'));
460
- });
461
- console.log('');
462
-
463
- const hookAnswer = await ask(rl, c(' Select hooks (comma-separated numbers, a=all, n=none) [1,3]: ', 'magenta'));
464
- const hookTrimmed = hookAnswer.trim().toLowerCase();
465
-
466
- let selectedHooks;
467
- if (hookTrimmed === 'n' || hookTrimmed === 'none') {
468
- selectedHooks = [];
469
- } else if (hookTrimmed === 'a' || hookTrimmed === 'all') {
470
- selectedHooks = [...COMMON_HOOKS];
471
- } else if (hookTrimmed === '') {
472
- selectedHooks = [COMMON_HOOKS[0], COMMON_HOOKS[2]]; // default: scrub + redact
473
- } else {
474
- const indices = hookTrimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < COMMON_HOOKS.length);
475
- selectedHooks = indices.map(i => COMMON_HOOKS[i]);
476
- }
477
-
478
- state.hooks = selectedHooks;
479
- console.log(c(` → Selected ${selectedHooks.length} hook(s): ${selectedHooks.map(h => h.label).join(', ') || 'none'}`, 'green'));
480
-
481
- return 'next';
482
- }
483
-
484
- // ---------------------------------------------------------------------------
485
- // Stage 9 — CI Integration
486
- // ---------------------------------------------------------------------------
487
-
488
- async function stageCi(rl, _ctx, state) {
489
- printStageHeader(8);
490
-
491
- console.log(' Optionally generate GitHub Actions workflows for Gemini CLI automation.');
492
- console.log(c(' Uses the run-gemini-cli action for CI integration.', 'dim'));
493
- console.log('');
494
-
495
- const answer = await ask(rl, c(' Generate CI workflows? (y/n, b=back, q=quit) [n]: ', 'magenta'));
496
- const trimmed = answer.trim().toLowerCase();
497
- if (trimmed === 'b') return 'back';
498
- if (trimmed === 'q') return 'quit';
499
-
500
- state.enableCi = trimmed === 'y' || trimmed === 'yes';
501
- console.log(c(` → CI workflows: ${state.enableCi ? 'will be generated' : 'skipped'}`, state.enableCi ? 'green' : 'dim'));
502
-
503
- return 'next';
504
- }
505
-
506
- // ---------------------------------------------------------------------------
507
- // Stage 10 — Review & Generate
508
- // ---------------------------------------------------------------------------
509
-
510
- async function stageReviewAndGenerate(rl, ctx, state, options) {
511
- printStageHeader(9);
512
-
513
- console.log(c(' Setup Summary:', 'bold'));
514
- console.log('');
515
- console.log(` ${c('Directory:', 'dim')} ${ctx.dir}`);
516
- console.log(` ${c('Stacks:', 'dim')} ${(state.stacks || []).map(s => s.label).join(', ') || 'none detected'}`);
517
- console.log(` ${c('Migration:', 'dim')} ${state.migrationMode || 'create'}`);
518
- console.log(` ${c('Trust level:', 'dim')} ${state.trustLevel || 'normal'}`);
519
- console.log(` ${c('Sandbox:', 'dim')} ${state.sandboxMode || 'none'} (${state.detectedOS || detectOS()})`);
520
- console.log(` ${c('Agent mode:', 'dim')} ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`);
521
- console.log(` ${c('Domain packs:', 'dim')} ${(state.domainPacks || []).map(p => p.label).join(', ') || 'none'}`);
522
- console.log(` ${c('MCP packs:', 'dim')} ${(state.mcpPacks || []).map(p => p.label).join(', ') || 'none'}`);
523
- console.log(` ${c('Policy tier:', 'dim')} ${state.policyTier || 'none'}`);
524
- console.log(` ${c('Hooks:', 'dim')} ${state.hooksEnabled ? `${(state.hooks || []).length} hook(s)` : 'disabled'}`);
525
- console.log(` ${c('CI workflows:', 'dim')} ${state.enableCi ? 'yes' : 'no'}`);
526
- console.log('');
527
-
528
- // List artifacts that will be generated
529
- const artifacts = ['GEMINI.md', '.gemini/settings.json'];
530
- if (state.agentMode === 'multi') artifacts.push('.gemini/agents/ (sub-agent starters)');
531
- if ((state.domainPacks || []).length > 0) artifacts.push('.gemini/settings.json (domain config)');
532
- if ((state.mcpPacks || []).length > 0) artifacts.push('.gemini/settings.json (MCP sections)');
533
- if (state.policyTier && state.policyTier !== 'none') artifacts.push('.gemini/policy/ (policy TOML files)');
534
- if (state.hooksEnabled && (state.hooks || []).length > 0) artifacts.push('.gemini/settings.json (hooks section)');
535
- if (state.enableCi) artifacts.push('.github/workflows/ (Gemini CI workflows)');
536
-
537
- console.log(c(' Artifacts to generate:', 'bold'));
538
- for (const a of artifacts) {
539
- console.log(c(` + ${a}`, 'green'));
540
- }
541
- console.log('');
542
-
543
- const answer = await ask(rl, c(' Proceed with generation? (y/n, b=back) [y]: ', 'magenta'));
544
- const trimmed = answer.trim().toLowerCase();
545
- if (trimmed === 'b') return 'back';
546
- if (trimmed === 'n' || trimmed === 'q') return 'quit';
547
-
548
- console.log('');
549
- console.log(c(' Generating artifacts...', 'bold'));
550
- console.log('');
551
-
552
- const writtenFiles = [];
553
- const preservedFiles = [];
554
- const geminiDir = path.join(ctx.dir, '.gemini');
555
-
556
- // Ensure .gemini/ directory exists
557
- fs.mkdirSync(geminiDir, { recursive: true });
558
-
559
- // Generate GEMINI.md
560
- const geminiMdPath = path.join(ctx.dir, 'GEMINI.md');
561
- if (state.migrationMode !== 'merge' || !fs.existsSync(geminiMdPath)) {
562
- const stackNames = (state.stacks || []).map(s => s.label).join(', ') || 'general';
563
- const geminiMdContent = `# Project Instructions for Gemini CLI
564
-
565
- ## Role
566
- You are an AI assistant working on this ${stackNames} project.
567
-
568
- ## Constraints
569
- - Follow existing code conventions and patterns
570
- - Run tests before suggesting changes are complete
571
- - Never commit secrets, API keys, or credentials
572
- - Ask for clarification when requirements are ambiguous
573
-
574
- ## Verification
575
- - Always verify changes compile/build successfully
576
- - Run the test suite after modifications
577
- - Check for lint errors before marking work as done
578
- `;
579
- fs.writeFileSync(geminiMdPath, geminiMdContent, 'utf8');
580
- writtenFiles.push('GEMINI.md');
581
- console.log(c(' + Created GEMINI.md', 'green'));
582
- } else {
583
- preservedFiles.push('GEMINI.md');
584
- console.log(c(' ~ GEMINI.md (preserved, merge mode)', 'dim'));
585
- }
586
-
587
- // Generate settings.json
588
- const settingsPath = path.join(geminiDir, 'settings.json');
589
- const settings = {};
590
-
591
- // Trust level
592
- if (state.trustLevel === 'yolo') {
593
- settings.toolPolicy = 'yolo';
594
- settings.autoApprove = true;
595
- } else if (state.trustLevel === 'auto_edit') {
596
- settings.toolPolicy = 'auto-edit';
597
- settings.autoApprove = false;
598
- } else {
599
- settings.toolPolicy = 'normal';
600
- settings.autoApprove = false;
601
- }
602
-
603
- // Sandbox
604
- if (state.sandboxMode && state.sandboxMode !== 'none') {
605
- settings.sandbox = state.sandboxMode;
606
- }
607
-
608
- // Hooks
609
- if (state.hooksEnabled && (state.hooks || []).length > 0) {
610
- settings.hooks = {};
611
- const beforeHooks = (state.hooks || []).filter(h => h.event === 'BeforeTool');
612
- const afterHooks = (state.hooks || []).filter(h => h.event === 'AfterTool');
613
- if (beforeHooks.length > 0) {
614
- settings.hooks.BeforeTool = beforeHooks.map(h => ({
615
- description: h.label,
616
- command: h.command,
617
- timeout_ms: 10000,
618
- }));
619
- }
620
- if (afterHooks.length > 0) {
621
- settings.hooks.AfterTool = afterHooks.map(h => ({
622
- description: h.label,
623
- command: h.command,
624
- timeout_ms: 10000,
625
- }));
626
- }
627
- }
628
-
629
- // MCP servers
630
- if ((state.mcpPacks || []).length > 0) {
631
- settings.mcpServers = {};
632
- for (const pack of state.mcpPacks) {
633
- if (pack.serverName && pack.jsonProjection) {
634
- settings.mcpServers[pack.serverName] = pack.jsonProjection;
635
- }
636
- }
637
- }
638
-
639
- if (state.migrationMode !== 'merge' || !fs.existsSync(settingsPath)) {
640
- fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
641
- writtenFiles.push('.gemini/settings.json');
642
- console.log(c(' + Created .gemini/settings.json', 'green'));
643
- } else {
644
- preservedFiles.push('.gemini/settings.json');
645
- console.log(c(' ~ .gemini/settings.json (preserved, merge mode)', 'dim'));
646
- }
647
-
648
- // Generate policy files
649
- if (state.policyTier && state.policyTier !== 'none') {
650
- const policyDir = path.join(geminiDir, 'policy');
651
- fs.mkdirSync(policyDir, { recursive: true });
652
-
653
- if (state.policyTier === 'basic' || state.policyTier === 'standard' || state.policyTier === 'strict') {
654
- const fileRestrictions = `# File type restrictions — generated by nerviq
655
- # Protect sensitive files from unreviewed edits.
656
-
657
- [file-restrictions]
658
- deny_edit = [".env", ".env.*", "*.pem", "*.key", "credentials.*"]
659
- deny_delete = [".env", ".env.*", "*.pem", "*.key", "*.lock"]
660
- read_only_dirs = [".git", "node_modules", ".gemini/policy"]
661
- `;
662
- const frPath = path.join(policyDir, 'file-restrictions.toml');
663
- fs.writeFileSync(frPath, fileRestrictions, 'utf8');
664
- writtenFiles.push('.gemini/policy/file-restrictions.toml');
665
- console.log(c(' + Created .gemini/policy/file-restrictions.toml', 'green'));
666
- }
667
-
668
- if (state.policyTier === 'standard' || state.policyTier === 'strict') {
669
- const toolRestrictions = `# Tool restrictions — generated by nerviq
670
- # Limit which tools the agent can invoke without approval.
671
-
672
- [tool-restrictions]
673
- deny_tools = ["shell_exec_unsafe", "network_raw"]
674
- require_approval = ["file_delete", "git_push", "deploy"]
675
- `;
676
- const trPath = path.join(policyDir, 'tool-restrictions.toml');
677
- fs.writeFileSync(trPath, toolRestrictions, 'utf8');
678
- writtenFiles.push('.gemini/policy/tool-restrictions.toml');
679
- console.log(c(' + Created .gemini/policy/tool-restrictions.toml', 'green'));
680
- }
681
-
682
- if (state.policyTier === 'strict') {
683
- const governance = `# Governance rules — generated by nerviq
684
- # Strict audit and escalation policies.
685
-
686
- [governance]
687
- audit_trail = true
688
- escalation_on_deny = true
689
- max_auto_edits_per_session = 50
690
- require_justification_for = ["security-override", "policy-bypass"]
691
-
692
- [governance.approval-escalation]
693
- # Edits to these paths require explicit human approval
694
- paths = [".gemini/", ".github/workflows/", "deploy/", "infra/"]
695
- `;
696
- const govPath = path.join(policyDir, 'governance.toml');
697
- fs.writeFileSync(govPath, governance, 'utf8');
698
- writtenFiles.push('.gemini/policy/governance.toml');
699
- console.log(c(' + Created .gemini/policy/governance.toml', 'green'));
700
- }
701
- }
702
-
703
- // Generate sub-agent starters
704
- if (state.agentMode === 'multi') {
705
- const agentsDir = path.join(geminiDir, 'agents');
706
- fs.mkdirSync(agentsDir, { recursive: true });
707
-
708
- const orchestrator = `# Orchestrator Agent
709
- You coordinate work across specialized sub-agents.
710
- Delegate tasks to the appropriate sub-agent and synthesize results.
711
- `;
712
- fs.writeFileSync(path.join(agentsDir, 'orchestrator.md'), orchestrator, 'utf8');
713
- writtenFiles.push('.gemini/agents/orchestrator.md');
714
-
715
- const reviewer = `# Code Reviewer Agent
716
- You specialize in reviewing code changes for quality, security, and correctness.
717
- Focus on actionable feedback with specific line references.
718
- `;
719
- fs.writeFileSync(path.join(agentsDir, 'reviewer.md'), reviewer, 'utf8');
720
- writtenFiles.push('.gemini/agents/reviewer.md');
721
-
722
- console.log(c(' + Created .gemini/agents/ (2 sub-agent starters)', 'green'));
723
- }
724
-
725
- // Generate CI workflows
726
- if (state.enableCi) {
727
- const workflowDir = path.join(ctx.dir, '.github', 'workflows');
728
- fs.mkdirSync(workflowDir, { recursive: true });
729
-
730
- const ciContent = `# Gemini PR Review — generated by nerviq
731
- name: Gemini PR Review
732
-
733
- on:
734
- pull_request:
735
- types: [opened, synchronize]
736
-
737
- permissions:
738
- contents: read
739
- pull-requests: write
740
-
741
- jobs:
742
- gemini-review:
743
- runs-on: ubuntu-latest
744
- timeout-minutes: 15
745
- steps:
746
- - uses: actions/checkout@v4
747
- with:
748
- fetch-depth: 0
749
-
750
- - name: Run Gemini CLI Review
751
- uses: google/run-gemini-cli@v1
752
- with:
753
- approval-policy: suggest
754
- format: github-pr-comment
755
- env:
756
- GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
757
- `;
758
- const ciPath = path.join(workflowDir, 'gemini-review.yml');
759
- fs.writeFileSync(ciPath, ciContent, 'utf8');
760
- writtenFiles.push('.github/workflows/gemini-review.yml');
761
- console.log(c(' + Created .github/workflows/gemini-review.yml', 'green'));
762
- }
763
-
764
- // Report results
765
- console.log('');
766
- console.log(` ${c(String(writtenFiles.length), 'bold')} files created.`);
767
- if (preservedFiles.length > 0) {
768
- console.log(` ${c(String(preservedFiles.length), 'dim')} existing files preserved.`);
769
- }
770
-
771
- return 'done';
772
- }
773
-
774
- // ---------------------------------------------------------------------------
775
- // Main wizard loop with back-navigation
776
- // ---------------------------------------------------------------------------
777
-
778
- const STAGES = [
779
- stageProjectDetection,
780
- stageTrustApproval,
781
- stageSandboxSelection,
782
- stageAgentStructure,
783
- stageDomainPacks,
784
- stageMcpPacks,
785
- stagePolicyTier,
786
- stageHooks,
787
- stageCi,
788
- stageReviewAndGenerate,
789
- ];
790
-
791
- async function geminiInteractive(options = {}) {
792
- const dir = options.dir || process.cwd();
793
-
794
- // Non-interactive fallback: if no TTY, skip wizard
795
- if (!isTTY()) {
796
- console.log(c(' No interactive terminal detected — cannot run wizard.', 'dim'));
797
- console.log(c(' Use `npx nerviq --platform gemini` for non-interactive setup.', 'dim'));
798
- return { cancelled: true };
799
- }
800
-
801
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
802
- const ctx = new GeminiProjectContext(dir);
803
- const state = {};
804
-
805
- console.log('');
806
- console.log(c(' +----------------------------------------------+', 'magenta'));
807
- console.log(c(' | nerviq: Gemini Interactive Wizard |', 'magenta'));
808
- console.log(c(' +----------------------------------------------+', 'magenta'));
809
- console.log('');
810
- console.log(c(` Working directory: ${dir}`, 'dim'));
811
-
812
- let stageIndex = 0;
813
-
814
- while (stageIndex < STAGES.length) {
815
- const stageFn = STAGES[stageIndex];
816
- let result;
817
-
818
- try {
819
- result = await stageFn(rl, ctx, state, options);
820
- } catch (err) {
821
- console.log('');
822
- console.log(c(` Error in stage: ${err.message}`, 'red'));
823
- rl.close();
824
- throw err;
825
- }
826
-
827
- if (result === 'quit') {
828
- console.log('');
829
- console.log(c(' Wizard cancelled. No changes were made.', 'dim'));
830
- rl.close();
831
- return { cancelled: true };
832
- }
833
-
834
- if (result === 'back') {
835
- if (stageIndex > 0) {
836
- stageIndex--;
837
- } else {
838
- console.log(c(' Already at the first stage.', 'dim'));
839
- }
840
- continue;
841
- }
842
-
843
- if (result === 'done') {
844
- break;
845
- }
846
-
847
- // 'next' — advance
848
- stageIndex++;
849
- }
850
-
851
- rl.close();
852
-
853
- console.log('');
854
- console.log(c(' Done! Run `npx nerviq --platform gemini` to audit your setup.', 'green'));
855
- console.log('');
856
-
857
- return { cancelled: false, state };
858
- }
859
-
860
- module.exports = { geminiInteractive };
1
+ /**
2
+ * Gemini CLI Interactive Wizard
3
+ *
4
+ * 10-stage guided setup for Gemini CLI projects.
5
+ * Uses Node.js readline (zero dependencies), same pattern as the Claude/Codex wizard.
6
+ *
7
+ * Stages:
8
+ * 1. Project detection (stacks, existing .gemini/)
9
+ * 2. Trust & approval (normal/auto_edit/yolo)
10
+ * 3. Sandbox selection (OS-aware: Seatbelt for macOS, Docker for Linux, etc.)
11
+ * 4. Agent structure
12
+ * 5. Domain pack selection
13
+ * 6. MCP pack selection
14
+ * 7. Policy tier config (Gemini-unique!)
15
+ * 8. Hook configuration (BeforeTool/AfterTool)
16
+ * 9. CI integration
17
+ * 10. Review & generate
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const os = require('os');
22
+ const path = require('path');
23
+ const readline = require('readline');
24
+ const { STACKS } = require('../techniques');
25
+ const { GeminiProjectContext } = require('./context');
26
+ const { GEMINI_TECHNIQUES } = require('./techniques');
27
+ const { GEMINI_DOMAIN_PACKS, detectGeminiDomainPacks } = require('./domain-packs');
28
+ const { recommendGeminiMcpPacks, GEMINI_MCP_PACKS } = require('./mcp-packs');
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Colors & helpers (matches Claude/Codex interactive.js)
32
+ // ---------------------------------------------------------------------------
33
+
34
+ const COLORS = {
35
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
36
+ red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m',
37
+ blue: '\x1b[36m', magenta: '\x1b[35m',
38
+ };
39
+ const c = (text, color) => `${COLORS[color] || ''}${text}${COLORS.reset}`;
40
+
41
+ function ask(rl, question) {
42
+ return new Promise(resolve => rl.question(question, resolve));
43
+ }
44
+
45
+ function isTTY() {
46
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
47
+ }
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Stage definitions
51
+ // ---------------------------------------------------------------------------
52
+
53
+ const STAGE_NAMES = [
54
+ 'Project Detection',
55
+ 'Trust & Approval',
56
+ 'Sandbox Selection',
57
+ 'Agent Structure',
58
+ 'Domain Pack Selection',
59
+ 'MCP Pack Selection',
60
+ 'Policy Tier Config',
61
+ 'Hook Configuration',
62
+ 'CI Integration',
63
+ 'Review & Generate',
64
+ ];
65
+
66
+ function printStageHeader(index) {
67
+ const num = index + 1;
68
+ const total = STAGE_NAMES.length;
69
+ console.log('');
70
+ console.log(c(` ── Stage ${num}/${total}: ${STAGE_NAMES[index]} ──`, 'magenta'));
71
+ console.log('');
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Stage 1 — Project Detection
76
+ // ---------------------------------------------------------------------------
77
+
78
+ function runProjectDetection(ctx) {
79
+ const stacks = ctx.detectStacks(STACKS);
80
+ const hasGeminiDir = fs.existsSync(path.join(ctx.dir, '.gemini'));
81
+ const hasGeminiMd = Boolean(ctx.geminiMdContent());
82
+ const settingsResult = ctx.settingsJson();
83
+ const hasSettings = settingsResult.ok;
84
+
85
+ // Quick audit
86
+ const auditResults = [];
87
+ for (const [key, technique] of Object.entries(GEMINI_TECHNIQUES)) {
88
+ auditResults.push({ key, ...technique, passed: technique.check(ctx) });
89
+ }
90
+ const passed = auditResults.filter(r => r.passed === true);
91
+ const failed = auditResults.filter(r => r.passed === false);
92
+
93
+ return { stacks, hasGeminiDir, hasGeminiMd, hasSettings, auditResults, passed, failed };
94
+ }
95
+
96
+ async function stageProjectDetection(rl, ctx, state) {
97
+ printStageHeader(0);
98
+ const det = runProjectDetection(ctx);
99
+ Object.assign(state, det);
100
+
101
+ if (det.stacks.length > 0) {
102
+ console.log(c(` Detected stacks: ${det.stacks.map(s => s.label).join(', ')}`, 'blue'));
103
+ } else {
104
+ console.log(c(' No specific stack detected — will use baseline defaults.', 'dim'));
105
+ }
106
+
107
+ console.log(c(` Working directory: ${ctx.dir}`, 'dim'));
108
+ console.log('');
109
+ console.log(` ${c(`${det.passed.length}/${det.auditResults.length}`, 'bold')} Gemini checks passing.`);
110
+ console.log(` ${c(String(det.failed.length), 'yellow')} improvements available.`);
111
+
112
+ if (det.hasGeminiDir || det.hasGeminiMd) {
113
+ console.log('');
114
+ console.log(c(' Existing Gemini configuration detected:', 'yellow'));
115
+ if (det.hasGeminiDir) console.log(c(' .gemini/ directory found', 'dim'));
116
+ if (det.hasGeminiMd) console.log(c(' GEMINI.md found', 'dim'));
117
+ if (det.hasSettings) console.log(c(' .gemini/settings.json found', 'dim'));
118
+ console.log('');
119
+
120
+ const migrationAnswer = await ask(rl, c(' Merge with existing config or replace? (merge/replace/quit) ', 'magenta'));
121
+ const choice = migrationAnswer.trim().toLowerCase();
122
+ if (choice === 'quit' || choice === 'q') return 'quit';
123
+ state.migrationMode = choice === 'replace' ? 'replace' : 'merge';
124
+ console.log(c(` → ${state.migrationMode === 'replace' ? 'Will replace existing files' : 'Will merge with existing config'}`, 'green'));
125
+ } else {
126
+ state.migrationMode = 'create';
127
+ console.log('');
128
+ console.log(c(' No existing Gemini config — will create fresh setup.', 'dim'));
129
+ }
130
+
131
+ return 'next';
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Stage 2 — Trust & Approval
136
+ // ---------------------------------------------------------------------------
137
+
138
+ const TRUST_POLICIES = [
139
+ { key: 'normal', label: 'Normal (safest)', desc: 'Gemini asks approval for all tool calls and edits.' },
140
+ { key: 'auto_edit', label: 'Auto-Edit (balanced)', desc: 'Gemini can edit files but asks before running commands.' },
141
+ { key: 'yolo', label: 'YOLO (maximum autonomy)', desc: 'Gemini runs everything automatically. Use only in trusted sandboxes.' },
142
+ ];
143
+
144
+ async function stageTrustApproval(rl, _ctx, state) {
145
+ printStageHeader(1);
146
+
147
+ console.log(' Select a trust level for Gemini CLI:');
148
+ console.log('');
149
+ TRUST_POLICIES.forEach((p, i) => {
150
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(p.label, 'blue')} — ${p.desc}`);
151
+ });
152
+ console.log('');
153
+
154
+ const answer = await ask(rl, c(' Choice (1-3, or b=back, q=quit) [1]: ', 'magenta'));
155
+ const trimmed = answer.trim().toLowerCase();
156
+ if (trimmed === 'b') return 'back';
157
+ if (trimmed === 'q') return 'quit';
158
+
159
+ const index = parseInt(trimmed, 10);
160
+ const selected = TRUST_POLICIES[(index >= 1 && index <= 3) ? index - 1 : 0];
161
+ state.trustLevel = selected.key;
162
+ console.log(c(` → Trust level: ${selected.label}`, 'green'));
163
+
164
+ if (selected.key === 'yolo') {
165
+ console.log('');
166
+ console.log(c(' ⚠ YOLO mode grants full autonomy. Ensure a sandbox is configured in the next stage.', 'yellow'));
167
+ }
168
+
169
+ return 'next';
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Stage 3 — Sandbox Selection (OS-aware)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ function detectOS() {
177
+ const platform = os.platform();
178
+ if (platform === 'darwin') return 'macOS';
179
+ if (platform === 'linux') return 'Linux';
180
+ if (platform === 'win32') return 'Windows';
181
+ return platform;
182
+ }
183
+
184
+ const SANDBOX_OPTIONS = {
185
+ macOS: [
186
+ { key: 'seatbelt', label: 'Seatbelt (recommended)', desc: 'macOS sandboxing via sandbox-exec. Blocks network/disk outside project.' },
187
+ { key: 'docker', label: 'Docker', desc: 'Full container isolation. Requires Docker Desktop.' },
188
+ { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
189
+ ],
190
+ Linux: [
191
+ { key: 'docker', label: 'Docker (recommended)', desc: 'Full container isolation with volume mounts.' },
192
+ { key: 'firejail', label: 'Firejail', desc: 'Lightweight Linux sandbox. Good for quick isolation.' },
193
+ { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
194
+ ],
195
+ Windows: [
196
+ { key: 'docker', label: 'Docker (recommended)', desc: 'Full container isolation via Docker Desktop / WSL2.' },
197
+ { key: 'wsl', label: 'WSL2 Isolation', desc: 'Run Gemini inside a WSL2 distro for basic isolation.' },
198
+ { key: 'none', label: 'None', desc: 'No sandbox. Only use for fully trusted repos.' },
199
+ ],
200
+ };
201
+
202
+ async function stageSandboxSelection(rl, _ctx, state) {
203
+ printStageHeader(2);
204
+
205
+ const detectedOS = detectOS();
206
+ const options = SANDBOX_OPTIONS[detectedOS] || SANDBOX_OPTIONS.Linux;
207
+
208
+ console.log(c(` Detected OS: ${detectedOS}`, 'blue'));
209
+ console.log('');
210
+ console.log(' Select a sandbox mode:');
211
+ console.log('');
212
+ options.forEach((opt, i) => {
213
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(opt.label, 'blue')} — ${opt.desc}`);
214
+ });
215
+ console.log('');
216
+
217
+ const answer = await ask(rl, c(` Choice (1-${options.length}, or b=back, q=quit) [1]: `, 'magenta'));
218
+ const trimmed = answer.trim().toLowerCase();
219
+ if (trimmed === 'b') return 'back';
220
+ if (trimmed === 'q') return 'quit';
221
+
222
+ const index = parseInt(trimmed, 10);
223
+ const selected = options[(index >= 1 && index <= options.length) ? index - 1 : 0];
224
+ state.sandboxMode = selected.key;
225
+ state.detectedOS = detectedOS;
226
+ console.log(c(` → Sandbox: ${selected.label}`, 'green'));
227
+
228
+ if (selected.key === 'none' && state.trustLevel === 'yolo') {
229
+ console.log('');
230
+ console.log(c(' ⚠ WARNING: YOLO mode without sandbox is extremely risky!', 'red'));
231
+ console.log(c(' Consider adding at least Docker or OS-level sandboxing.', 'yellow'));
232
+ }
233
+
234
+ return 'next';
235
+ }
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // Stage 4 — Agent Structure
239
+ // ---------------------------------------------------------------------------
240
+
241
+ async function stageAgentStructure(rl, _ctx, state) {
242
+ printStageHeader(3);
243
+
244
+ console.log(' How should Gemini operate in this project?');
245
+ console.log('');
246
+ console.log(` ${c('1', 'bold')}. ${c('Single agent', 'blue')} — One Gemini agent handles everything (simpler, good for small repos).`);
247
+ console.log(` ${c('2', 'bold')}. ${c('Multi-agent', 'blue')} — Orchestrator + specialized sub-agents (better for large repos).`);
248
+ console.log('');
249
+
250
+ const answer = await ask(rl, c(' Choice (1-2, or b=back, q=quit) [1]: ', 'magenta'));
251
+ const trimmed = answer.trim().toLowerCase();
252
+ if (trimmed === 'b') return 'back';
253
+ if (trimmed === 'q') return 'quit';
254
+
255
+ state.agentMode = trimmed === '2' ? 'multi' : 'single';
256
+ console.log(c(` → Agent mode: ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`, 'green'));
257
+
258
+ if (state.agentMode === 'multi') {
259
+ console.log('');
260
+ console.log(c(' Will generate .gemini/agents/ with sub-agent markdown starters.', 'dim'));
261
+ }
262
+
263
+ return 'next';
264
+ }
265
+
266
+ // ---------------------------------------------------------------------------
267
+ // Stage 5 — Domain Pack Selection
268
+ // ---------------------------------------------------------------------------
269
+
270
+ async function stageDomainPacks(rl, ctx, state) {
271
+ printStageHeader(4);
272
+
273
+ const detected = detectGeminiDomainPacks(ctx, state.stacks || []);
274
+ const detectedKeys = new Set(detected.map(p => p.key));
275
+
276
+ console.log(' Available domain packs:');
277
+ console.log('');
278
+
279
+ const allPacks = GEMINI_DOMAIN_PACKS.map(pack => {
280
+ const isDetected = detectedKeys.has(pack.key);
281
+ return { ...pack, isDetected };
282
+ });
283
+
284
+ allPacks.forEach((pack, i) => {
285
+ const marker = pack.isDetected ? c(' (detected)', 'green') : '';
286
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}`);
287
+ console.log(c(` ${pack.useWhen}`, 'dim'));
288
+ });
289
+ console.log('');
290
+
291
+ const defaultSelection = allPacks
292
+ .map((p, i) => p.isDetected ? String(i + 1) : null)
293
+ .filter(Boolean)
294
+ .join(',');
295
+
296
+ const answer = await ask(rl, c(` Select packs (comma-separated numbers, or b=back, q=quit) [${defaultSelection || 'all detected'}]: `, 'magenta'));
297
+ const trimmed = answer.trim().toLowerCase();
298
+ if (trimmed === 'b') return 'back';
299
+ if (trimmed === 'q') return 'quit';
300
+
301
+ let selectedPacks;
302
+ if (trimmed === '' || trimmed === 'all') {
303
+ selectedPacks = detected;
304
+ } else {
305
+ const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < allPacks.length);
306
+ selectedPacks = indices.map(i => allPacks[i]);
307
+ }
308
+
309
+ state.domainPacks = selectedPacks;
310
+ console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
311
+
312
+ return 'next';
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Stage 6 — MCP Pack Selection
317
+ // ---------------------------------------------------------------------------
318
+
319
+ async function stageMcpPacks(rl, ctx, state) {
320
+ printStageHeader(5);
321
+
322
+ const recommended = recommendGeminiMcpPacks(state.stacks || [], state.domainPacks || [], { ctx });
323
+ const recommendedKeys = new Set(recommended.map(p => p.key));
324
+
325
+ console.log(' Available MCP packs:');
326
+ console.log('');
327
+
328
+ GEMINI_MCP_PACKS.forEach((pack, i) => {
329
+ const isRec = recommendedKeys.has(pack.key);
330
+ const marker = isRec ? c(' (recommended)', 'green') : '';
331
+ const authNote = pack.requiredAuth.length > 0
332
+ ? c(` [requires: ${pack.requiredAuth.join(', ')}]`, 'yellow')
333
+ : '';
334
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}${authNote}`);
335
+ console.log(c(` ${pack.description}`, 'dim'));
336
+ });
337
+ console.log('');
338
+
339
+ const defaultSelection = GEMINI_MCP_PACKS
340
+ .map((p, i) => recommendedKeys.has(p.key) ? String(i + 1) : null)
341
+ .filter(Boolean)
342
+ .join(',');
343
+
344
+ const answer = await ask(rl, c(` Select packs (comma-separated numbers, n=none, b=back, q=quit) [${defaultSelection || 'none'}]: `, 'magenta'));
345
+ const trimmed = answer.trim().toLowerCase();
346
+ if (trimmed === 'b') return 'back';
347
+ if (trimmed === 'q') return 'quit';
348
+
349
+ let selectedPacks;
350
+ if (trimmed === 'n' || trimmed === 'none') {
351
+ selectedPacks = [];
352
+ } else if (trimmed === '') {
353
+ selectedPacks = recommended;
354
+ } else {
355
+ const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < GEMINI_MCP_PACKS.length);
356
+ selectedPacks = indices.map(i => GEMINI_MCP_PACKS[i]);
357
+ }
358
+
359
+ state.mcpPacks = selectedPacks;
360
+ console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
361
+
362
+ return 'next';
363
+ }
364
+
365
+ // ---------------------------------------------------------------------------
366
+ // Stage 7 — Policy Tier Config (Gemini-unique!)
367
+ // ---------------------------------------------------------------------------
368
+
369
+ const POLICY_TIERS = [
370
+ { key: 'none', label: 'No Policy Engine', desc: 'Trust is managed entirely via settings.json and sandbox.' },
371
+ { key: 'basic', label: 'Basic Policies', desc: 'File-type restrictions and read-only directories.' },
372
+ { key: 'standard', label: 'Standard Policies', desc: 'File-type + tool restrictions + sensitive path protection.' },
373
+ { key: 'strict', label: 'Strict Governance', desc: 'Full policy engine with audit trail, approval escalation, and deny-lists.' },
374
+ ];
375
+
376
+ async function stagePolicyTier(rl, _ctx, state) {
377
+ printStageHeader(6);
378
+
379
+ console.log(' Gemini CLI supports a policy engine for fine-grained control.');
380
+ console.log(c(' Policies live in .gemini/policy/*.toml and complement settings.json.', 'dim'));
381
+ console.log('');
382
+
383
+ POLICY_TIERS.forEach((tier, i) => {
384
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(tier.label, 'blue')} — ${tier.desc}`);
385
+ });
386
+ console.log('');
387
+
388
+ // Recommend tier based on trust level
389
+ let recommended = 1;
390
+ if (state.trustLevel === 'yolo') recommended = 3;
391
+ else if (state.trustLevel === 'auto_edit') recommended = 2;
392
+
393
+ const answer = await ask(rl, c(` Choice (1-4, or b=back, q=quit) [${recommended}]: `, 'magenta'));
394
+ const trimmed = answer.trim().toLowerCase();
395
+ if (trimmed === 'b') return 'back';
396
+ if (trimmed === 'q') return 'quit';
397
+
398
+ const index = parseInt(trimmed, 10);
399
+ const selected = POLICY_TIERS[(index >= 1 && index <= 4) ? index - 1 : recommended - 1];
400
+ state.policyTier = selected.key;
401
+ console.log(c(` → Policy tier: ${selected.label}`, 'green'));
402
+
403
+ if (selected.key === 'strict') {
404
+ console.log('');
405
+ console.log(c(' Will generate .gemini/policy/ with governance TOML files.', 'dim'));
406
+ console.log(c(' Includes: file-restrictions, tool-deny-list, audit-escalation.', 'dim'));
407
+ } else if (selected.key === 'standard') {
408
+ console.log('');
409
+ console.log(c(' Will generate .gemini/policy/ with standard restriction rules.', 'dim'));
410
+ } else if (selected.key === 'basic') {
411
+ console.log('');
412
+ console.log(c(' Will generate .gemini/policy/ with basic file-type restrictions.', 'dim'));
413
+ }
414
+
415
+ return 'next';
416
+ }
417
+
418
+ // ---------------------------------------------------------------------------
419
+ // Stage 8 — Hook Configuration (BeforeTool/AfterTool)
420
+ // ---------------------------------------------------------------------------
421
+
422
+ const COMMON_HOOKS = [
423
+ { key: 'before-scrub-secrets', event: 'BeforeTool', label: 'Scrub secrets from tool inputs', command: "grep -rn 'sk-\\|AKIA\\|ghp_\\|xox[baprs]-' . && echo 'BLOCKED: secret detected' && exit 1 || true" },
424
+ { key: 'before-lint', event: 'BeforeTool', label: 'Lint check before edits', command: 'npm run lint --silent 2>/dev/null || true' },
425
+ { key: 'after-redact', event: 'AfterTool', label: 'Redact sensitive output', command: "sed 's/sk-[A-Za-z0-9_-]\\{20,\\}/[REDACTED]/g'" },
426
+ { key: 'after-test', event: 'AfterTool', label: 'Run tests after changes', command: 'npm test --silent 2>/dev/null || true' },
427
+ { key: 'before-block-dangerous', event: 'BeforeTool', label: 'Block dangerous commands (rm -rf, chmod 777)', command: "echo \"$TOOL_INPUT\" | grep -qE 'rm -rf /|chmod 777|curl.*\\| bash' && echo 'BLOCKED: dangerous command' && exit 1 || true" },
428
+ { key: 'after-size-check', event: 'AfterTool', label: 'Check output size limits', command: "wc -c < /dev/stdin | awk '{if ($1 > 100000) {print \"WARNING: large output\"; exit 1}}' || true" },
429
+ ];
430
+
431
+ async function stageHooks(rl, _ctx, state) {
432
+ printStageHeader(7);
433
+
434
+ console.log(' Configure Gemini hooks (BeforeTool and AfterTool lifecycle events):');
435
+ console.log(c(' BeforeTool: runs before each tool call (validate, scrub, block)', 'dim'));
436
+ console.log(c(' AfterTool: runs after each tool call (redact, test, audit)', 'dim'));
437
+ console.log('');
438
+
439
+ const answer = await ask(rl, c(' Enable hooks? (y/n, b=back, q=quit) [y]: ', 'magenta'));
440
+ const trimmed = answer.trim().toLowerCase();
441
+ if (trimmed === 'b') return 'back';
442
+ if (trimmed === 'q') return 'quit';
443
+
444
+ if (trimmed === 'n') {
445
+ state.hooks = [];
446
+ state.hooksEnabled = false;
447
+ console.log(c(' → Hooks disabled.', 'dim'));
448
+ return 'next';
449
+ }
450
+
451
+ state.hooksEnabled = true;
452
+ console.log('');
453
+ console.log(' Available hook patterns:');
454
+ console.log('');
455
+
456
+ COMMON_HOOKS.forEach((hook, i) => {
457
+ const eventColor = hook.event === 'BeforeTool' ? 'yellow' : 'blue';
458
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(hook.label, 'blue')} (${c(hook.event, eventColor)})`);
459
+ console.log(c(` ${hook.command.slice(0, 80)}${hook.command.length > 80 ? '...' : ''}`, 'dim'));
460
+ });
461
+ console.log('');
462
+
463
+ const hookAnswer = await ask(rl, c(' Select hooks (comma-separated numbers, a=all, n=none) [1,3]: ', 'magenta'));
464
+ const hookTrimmed = hookAnswer.trim().toLowerCase();
465
+
466
+ let selectedHooks;
467
+ if (hookTrimmed === 'n' || hookTrimmed === 'none') {
468
+ selectedHooks = [];
469
+ } else if (hookTrimmed === 'a' || hookTrimmed === 'all') {
470
+ selectedHooks = [...COMMON_HOOKS];
471
+ } else if (hookTrimmed === '') {
472
+ selectedHooks = [COMMON_HOOKS[0], COMMON_HOOKS[2]]; // default: scrub + redact
473
+ } else {
474
+ const indices = hookTrimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < COMMON_HOOKS.length);
475
+ selectedHooks = indices.map(i => COMMON_HOOKS[i]);
476
+ }
477
+
478
+ state.hooks = selectedHooks;
479
+ console.log(c(` → Selected ${selectedHooks.length} hook(s): ${selectedHooks.map(h => h.label).join(', ') || 'none'}`, 'green'));
480
+
481
+ return 'next';
482
+ }
483
+
484
+ // ---------------------------------------------------------------------------
485
+ // Stage 9 — CI Integration
486
+ // ---------------------------------------------------------------------------
487
+
488
+ async function stageCi(rl, _ctx, state) {
489
+ printStageHeader(8);
490
+
491
+ console.log(' Optionally generate GitHub Actions workflows for Gemini CLI automation.');
492
+ console.log(c(' Uses the run-gemini-cli action for CI integration.', 'dim'));
493
+ console.log('');
494
+
495
+ const answer = await ask(rl, c(' Generate CI workflows? (y/n, b=back, q=quit) [n]: ', 'magenta'));
496
+ const trimmed = answer.trim().toLowerCase();
497
+ if (trimmed === 'b') return 'back';
498
+ if (trimmed === 'q') return 'quit';
499
+
500
+ state.enableCi = trimmed === 'y' || trimmed === 'yes';
501
+ console.log(c(` → CI workflows: ${state.enableCi ? 'will be generated' : 'skipped'}`, state.enableCi ? 'green' : 'dim'));
502
+
503
+ return 'next';
504
+ }
505
+
506
+ // ---------------------------------------------------------------------------
507
+ // Stage 10 — Review & Generate
508
+ // ---------------------------------------------------------------------------
509
+
510
+ async function stageReviewAndGenerate(rl, ctx, state, options) {
511
+ printStageHeader(9);
512
+
513
+ console.log(c(' Setup Summary:', 'bold'));
514
+ console.log('');
515
+ console.log(` ${c('Directory:', 'dim')} ${ctx.dir}`);
516
+ console.log(` ${c('Stacks:', 'dim')} ${(state.stacks || []).map(s => s.label).join(', ') || 'none detected'}`);
517
+ console.log(` ${c('Migration:', 'dim')} ${state.migrationMode || 'create'}`);
518
+ console.log(` ${c('Trust level:', 'dim')} ${state.trustLevel || 'normal'}`);
519
+ console.log(` ${c('Sandbox:', 'dim')} ${state.sandboxMode || 'none'} (${state.detectedOS || detectOS()})`);
520
+ console.log(` ${c('Agent mode:', 'dim')} ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`);
521
+ console.log(` ${c('Domain packs:', 'dim')} ${(state.domainPacks || []).map(p => p.label).join(', ') || 'none'}`);
522
+ console.log(` ${c('MCP packs:', 'dim')} ${(state.mcpPacks || []).map(p => p.label).join(', ') || 'none'}`);
523
+ console.log(` ${c('Policy tier:', 'dim')} ${state.policyTier || 'none'}`);
524
+ console.log(` ${c('Hooks:', 'dim')} ${state.hooksEnabled ? `${(state.hooks || []).length} hook(s)` : 'disabled'}`);
525
+ console.log(` ${c('CI workflows:', 'dim')} ${state.enableCi ? 'yes' : 'no'}`);
526
+ console.log('');
527
+
528
+ // List artifacts that will be generated
529
+ const artifacts = ['GEMINI.md', '.gemini/settings.json'];
530
+ if (state.agentMode === 'multi') artifacts.push('.gemini/agents/ (sub-agent starters)');
531
+ if ((state.domainPacks || []).length > 0) artifacts.push('.gemini/settings.json (domain config)');
532
+ if ((state.mcpPacks || []).length > 0) artifacts.push('.gemini/settings.json (MCP sections)');
533
+ if (state.policyTier && state.policyTier !== 'none') artifacts.push('.gemini/policy/ (policy TOML files)');
534
+ if (state.hooksEnabled && (state.hooks || []).length > 0) artifacts.push('.gemini/settings.json (hooks section)');
535
+ if (state.enableCi) artifacts.push('.github/workflows/ (Gemini CI workflows)');
536
+
537
+ console.log(c(' Artifacts to generate:', 'bold'));
538
+ for (const a of artifacts) {
539
+ console.log(c(` + ${a}`, 'green'));
540
+ }
541
+ console.log('');
542
+
543
+ const answer = await ask(rl, c(' Proceed with generation? (y/n, b=back) [y]: ', 'magenta'));
544
+ const trimmed = answer.trim().toLowerCase();
545
+ if (trimmed === 'b') return 'back';
546
+ if (trimmed === 'n' || trimmed === 'q') return 'quit';
547
+
548
+ console.log('');
549
+ console.log(c(' Generating artifacts...', 'bold'));
550
+ console.log('');
551
+
552
+ const writtenFiles = [];
553
+ const preservedFiles = [];
554
+ const geminiDir = path.join(ctx.dir, '.gemini');
555
+
556
+ // Ensure .gemini/ directory exists
557
+ fs.mkdirSync(geminiDir, { recursive: true });
558
+
559
+ // Generate GEMINI.md
560
+ const geminiMdPath = path.join(ctx.dir, 'GEMINI.md');
561
+ if (state.migrationMode !== 'merge' || !fs.existsSync(geminiMdPath)) {
562
+ const stackNames = (state.stacks || []).map(s => s.label).join(', ') || 'general';
563
+ const geminiMdContent = `# Project Instructions for Gemini CLI
564
+
565
+ ## Role
566
+ You are an AI assistant working on this ${stackNames} project.
567
+
568
+ ## Constraints
569
+ - Follow existing code conventions and patterns
570
+ - Run tests before suggesting changes are complete
571
+ - Never commit secrets, API keys, or credentials
572
+ - Ask for clarification when requirements are ambiguous
573
+
574
+ ## Verification
575
+ - Always verify changes compile/build successfully
576
+ - Run the test suite after modifications
577
+ - Check for lint errors before marking work as done
578
+ `;
579
+ fs.writeFileSync(geminiMdPath, geminiMdContent, 'utf8');
580
+ writtenFiles.push('GEMINI.md');
581
+ console.log(c(' + Created GEMINI.md', 'green'));
582
+ } else {
583
+ preservedFiles.push('GEMINI.md');
584
+ console.log(c(' ~ GEMINI.md (preserved, merge mode)', 'dim'));
585
+ }
586
+
587
+ // Generate settings.json
588
+ const settingsPath = path.join(geminiDir, 'settings.json');
589
+ const settings = {};
590
+
591
+ // Trust level
592
+ if (state.trustLevel === 'yolo') {
593
+ settings.toolPolicy = 'yolo';
594
+ settings.autoApprove = true;
595
+ } else if (state.trustLevel === 'auto_edit') {
596
+ settings.toolPolicy = 'auto-edit';
597
+ settings.autoApprove = false;
598
+ } else {
599
+ settings.toolPolicy = 'normal';
600
+ settings.autoApprove = false;
601
+ }
602
+
603
+ // Sandbox
604
+ if (state.sandboxMode && state.sandboxMode !== 'none') {
605
+ settings.sandbox = state.sandboxMode;
606
+ }
607
+
608
+ // Hooks
609
+ if (state.hooksEnabled && (state.hooks || []).length > 0) {
610
+ settings.hooks = {};
611
+ const beforeHooks = (state.hooks || []).filter(h => h.event === 'BeforeTool');
612
+ const afterHooks = (state.hooks || []).filter(h => h.event === 'AfterTool');
613
+ if (beforeHooks.length > 0) {
614
+ settings.hooks.BeforeTool = beforeHooks.map(h => ({
615
+ description: h.label,
616
+ command: h.command,
617
+ timeout_ms: 10000,
618
+ }));
619
+ }
620
+ if (afterHooks.length > 0) {
621
+ settings.hooks.AfterTool = afterHooks.map(h => ({
622
+ description: h.label,
623
+ command: h.command,
624
+ timeout_ms: 10000,
625
+ }));
626
+ }
627
+ }
628
+
629
+ // MCP servers
630
+ if ((state.mcpPacks || []).length > 0) {
631
+ settings.mcpServers = {};
632
+ for (const pack of state.mcpPacks) {
633
+ if (pack.serverName && pack.jsonProjection) {
634
+ settings.mcpServers[pack.serverName] = pack.jsonProjection;
635
+ }
636
+ }
637
+ }
638
+
639
+ if (state.migrationMode !== 'merge' || !fs.existsSync(settingsPath)) {
640
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
641
+ writtenFiles.push('.gemini/settings.json');
642
+ console.log(c(' + Created .gemini/settings.json', 'green'));
643
+ } else {
644
+ preservedFiles.push('.gemini/settings.json');
645
+ console.log(c(' ~ .gemini/settings.json (preserved, merge mode)', 'dim'));
646
+ }
647
+
648
+ // Generate policy files
649
+ if (state.policyTier && state.policyTier !== 'none') {
650
+ const policyDir = path.join(geminiDir, 'policy');
651
+ fs.mkdirSync(policyDir, { recursive: true });
652
+
653
+ if (state.policyTier === 'basic' || state.policyTier === 'standard' || state.policyTier === 'strict') {
654
+ const fileRestrictions = `# File type restrictions — generated by nerviq
655
+ # Protect sensitive files from unreviewed edits.
656
+
657
+ [file-restrictions]
658
+ deny_edit = [".env", ".env.*", "*.pem", "*.key", "credentials.*"]
659
+ deny_delete = [".env", ".env.*", "*.pem", "*.key", "*.lock"]
660
+ read_only_dirs = [".git", "node_modules", ".gemini/policy"]
661
+ `;
662
+ const frPath = path.join(policyDir, 'file-restrictions.toml');
663
+ fs.writeFileSync(frPath, fileRestrictions, 'utf8');
664
+ writtenFiles.push('.gemini/policy/file-restrictions.toml');
665
+ console.log(c(' + Created .gemini/policy/file-restrictions.toml', 'green'));
666
+ }
667
+
668
+ if (state.policyTier === 'standard' || state.policyTier === 'strict') {
669
+ const toolRestrictions = `# Tool restrictions — generated by nerviq
670
+ # Limit which tools the agent can invoke without approval.
671
+
672
+ [tool-restrictions]
673
+ deny_tools = ["shell_exec_unsafe", "network_raw"]
674
+ require_approval = ["file_delete", "git_push", "deploy"]
675
+ `;
676
+ const trPath = path.join(policyDir, 'tool-restrictions.toml');
677
+ fs.writeFileSync(trPath, toolRestrictions, 'utf8');
678
+ writtenFiles.push('.gemini/policy/tool-restrictions.toml');
679
+ console.log(c(' + Created .gemini/policy/tool-restrictions.toml', 'green'));
680
+ }
681
+
682
+ if (state.policyTier === 'strict') {
683
+ const governance = `# Governance rules — generated by nerviq
684
+ # Strict audit and escalation policies.
685
+
686
+ [governance]
687
+ audit_trail = true
688
+ escalation_on_deny = true
689
+ max_auto_edits_per_session = 50
690
+ require_justification_for = ["security-override", "policy-bypass"]
691
+
692
+ [governance.approval-escalation]
693
+ # Edits to these paths require explicit human approval
694
+ paths = [".gemini/", ".github/workflows/", "deploy/", "infra/"]
695
+ `;
696
+ const govPath = path.join(policyDir, 'governance.toml');
697
+ fs.writeFileSync(govPath, governance, 'utf8');
698
+ writtenFiles.push('.gemini/policy/governance.toml');
699
+ console.log(c(' + Created .gemini/policy/governance.toml', 'green'));
700
+ }
701
+ }
702
+
703
+ // Generate sub-agent starters
704
+ if (state.agentMode === 'multi') {
705
+ const agentsDir = path.join(geminiDir, 'agents');
706
+ fs.mkdirSync(agentsDir, { recursive: true });
707
+
708
+ const orchestrator = `# Orchestrator Agent
709
+ You coordinate work across specialized sub-agents.
710
+ Delegate tasks to the appropriate sub-agent and synthesize results.
711
+ `;
712
+ fs.writeFileSync(path.join(agentsDir, 'orchestrator.md'), orchestrator, 'utf8');
713
+ writtenFiles.push('.gemini/agents/orchestrator.md');
714
+
715
+ const reviewer = `# Code Reviewer Agent
716
+ You specialize in reviewing code changes for quality, security, and correctness.
717
+ Focus on actionable feedback with specific line references.
718
+ `;
719
+ fs.writeFileSync(path.join(agentsDir, 'reviewer.md'), reviewer, 'utf8');
720
+ writtenFiles.push('.gemini/agents/reviewer.md');
721
+
722
+ console.log(c(' + Created .gemini/agents/ (2 sub-agent starters)', 'green'));
723
+ }
724
+
725
+ // Generate CI workflows
726
+ if (state.enableCi) {
727
+ const workflowDir = path.join(ctx.dir, '.github', 'workflows');
728
+ fs.mkdirSync(workflowDir, { recursive: true });
729
+
730
+ const ciContent = `# Gemini PR Review — generated by nerviq
731
+ name: Gemini PR Review
732
+
733
+ on:
734
+ pull_request:
735
+ types: [opened, synchronize]
736
+
737
+ permissions:
738
+ contents: read
739
+ pull-requests: write
740
+
741
+ jobs:
742
+ gemini-review:
743
+ runs-on: ubuntu-latest
744
+ timeout-minutes: 15
745
+ steps:
746
+ - uses: actions/checkout@v4
747
+ with:
748
+ fetch-depth: 0
749
+
750
+ - name: Run Gemini CLI Review
751
+ uses: google/run-gemini-cli@v1
752
+ with:
753
+ approval-policy: suggest
754
+ format: github-pr-comment
755
+ env:
756
+ GEMINI_API_KEY: \${{ secrets.GEMINI_API_KEY }}
757
+ `;
758
+ const ciPath = path.join(workflowDir, 'gemini-review.yml');
759
+ fs.writeFileSync(ciPath, ciContent, 'utf8');
760
+ writtenFiles.push('.github/workflows/gemini-review.yml');
761
+ console.log(c(' + Created .github/workflows/gemini-review.yml', 'green'));
762
+ }
763
+
764
+ // Report results
765
+ console.log('');
766
+ console.log(` ${c(String(writtenFiles.length), 'bold')} files created.`);
767
+ if (preservedFiles.length > 0) {
768
+ console.log(` ${c(String(preservedFiles.length), 'dim')} existing files preserved.`);
769
+ }
770
+
771
+ return 'done';
772
+ }
773
+
774
+ // ---------------------------------------------------------------------------
775
+ // Main wizard loop with back-navigation
776
+ // ---------------------------------------------------------------------------
777
+
778
+ const STAGES = [
779
+ stageProjectDetection,
780
+ stageTrustApproval,
781
+ stageSandboxSelection,
782
+ stageAgentStructure,
783
+ stageDomainPacks,
784
+ stageMcpPacks,
785
+ stagePolicyTier,
786
+ stageHooks,
787
+ stageCi,
788
+ stageReviewAndGenerate,
789
+ ];
790
+
791
+ async function geminiInteractive(options = {}) {
792
+ const dir = options.dir || process.cwd();
793
+
794
+ // Non-interactive fallback: if no TTY, skip wizard
795
+ if (!isTTY()) {
796
+ console.log(c(' No interactive terminal detected — cannot run wizard.', 'dim'));
797
+ console.log(c(' Use `npx nerviq --platform gemini` for non-interactive setup.', 'dim'));
798
+ return { cancelled: true };
799
+ }
800
+
801
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
802
+ const ctx = new GeminiProjectContext(dir);
803
+ const state = {};
804
+
805
+ console.log('');
806
+ console.log(c(' +----------------------------------------------+', 'magenta'));
807
+ console.log(c(' | nerviq: Gemini Interactive Wizard |', 'magenta'));
808
+ console.log(c(' +----------------------------------------------+', 'magenta'));
809
+ console.log('');
810
+ console.log(c(` Working directory: ${dir}`, 'dim'));
811
+
812
+ let stageIndex = 0;
813
+
814
+ while (stageIndex < STAGES.length) {
815
+ const stageFn = STAGES[stageIndex];
816
+ let result;
817
+
818
+ try {
819
+ result = await stageFn(rl, ctx, state, options);
820
+ } catch (err) {
821
+ console.log('');
822
+ console.log(c(` Error in stage: ${err.message}`, 'red'));
823
+ rl.close();
824
+ throw err;
825
+ }
826
+
827
+ if (result === 'quit') {
828
+ console.log('');
829
+ console.log(c(' Wizard cancelled. No changes were made.', 'dim'));
830
+ rl.close();
831
+ return { cancelled: true };
832
+ }
833
+
834
+ if (result === 'back') {
835
+ if (stageIndex > 0) {
836
+ stageIndex--;
837
+ } else {
838
+ console.log(c(' Already at the first stage.', 'dim'));
839
+ }
840
+ continue;
841
+ }
842
+
843
+ if (result === 'done') {
844
+ break;
845
+ }
846
+
847
+ // 'next' — advance
848
+ stageIndex++;
849
+ }
850
+
851
+ rl.close();
852
+
853
+ console.log('');
854
+ console.log(c(' Done! Run `npx nerviq --platform gemini` to audit your setup.', 'green'));
855
+ console.log('');
856
+
857
+ return { cancelled: false, state };
858
+ }
859
+
860
+ module.exports = { geminiInteractive };