@nerviq/cli 0.0.1 → 0.9.0-beta.2

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 (148) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -0
  4. package/bin/cli.js +749 -0
  5. package/content/case-study-template.md +91 -0
  6. package/content/claims-governance.md +37 -0
  7. package/content/claude-code/audit-repo/SKILL.md +20 -0
  8. package/content/claude-native-integration.md +60 -0
  9. package/content/devto-article.json +9 -0
  10. package/content/launch-posts.md +226 -0
  11. package/content/pilot-rollout-kit.md +30 -0
  12. package/content/release-checklist.md +31 -0
  13. package/package.json +53 -4
  14. package/src/activity.js +529 -0
  15. package/src/aider/activity.js +226 -0
  16. package/src/aider/config-parser.js +166 -0
  17. package/src/aider/context.js +158 -0
  18. package/src/aider/deep-review.js +316 -0
  19. package/src/aider/domain-packs.js +278 -0
  20. package/src/aider/freshness.js +168 -0
  21. package/src/aider/governance.js +253 -0
  22. package/src/aider/interactive.js +334 -0
  23. package/src/aider/mcp-packs.js +98 -0
  24. package/src/aider/patch.js +214 -0
  25. package/src/aider/plans.js +186 -0
  26. package/src/aider/premium.js +360 -0
  27. package/src/aider/setup.js +404 -0
  28. package/src/aider/techniques.js +1323 -0
  29. package/src/analyze.js +821 -0
  30. package/src/audit.js +1003 -0
  31. package/src/badge.js +13 -0
  32. package/src/benchmark.js +339 -0
  33. package/src/claudex-sync.json +7 -0
  34. package/src/codex/activity.js +324 -0
  35. package/src/codex/config-parser.js +183 -0
  36. package/src/codex/context.js +221 -0
  37. package/src/codex/deep-review.js +493 -0
  38. package/src/codex/domain-packs.js +372 -0
  39. package/src/codex/freshness.js +167 -0
  40. package/src/codex/governance.js +192 -0
  41. package/src/codex/interactive.js +618 -0
  42. package/src/codex/mcp-packs.js +660 -0
  43. package/src/codex/patch.js +209 -0
  44. package/src/codex/plans.js +251 -0
  45. package/src/codex/premium.js +614 -0
  46. package/src/codex/setup.js +603 -0
  47. package/src/codex/techniques.js +2649 -0
  48. package/src/context.js +272 -0
  49. package/src/copilot/activity.js +309 -0
  50. package/src/copilot/config-parser.js +226 -0
  51. package/src/copilot/context.js +197 -0
  52. package/src/copilot/deep-review.js +346 -0
  53. package/src/copilot/domain-packs.js +350 -0
  54. package/src/copilot/freshness.js +197 -0
  55. package/src/copilot/governance.js +222 -0
  56. package/src/copilot/interactive.js +406 -0
  57. package/src/copilot/mcp-packs.js +572 -0
  58. package/src/copilot/patch.js +238 -0
  59. package/src/copilot/plans.js +253 -0
  60. package/src/copilot/premium.js +450 -0
  61. package/src/copilot/setup.js +488 -0
  62. package/src/copilot/techniques.js +1822 -0
  63. package/src/cursor/activity.js +301 -0
  64. package/src/cursor/config-parser.js +265 -0
  65. package/src/cursor/context.js +236 -0
  66. package/src/cursor/deep-review.js +334 -0
  67. package/src/cursor/domain-packs.js +346 -0
  68. package/src/cursor/freshness.js +214 -0
  69. package/src/cursor/governance.js +229 -0
  70. package/src/cursor/interactive.js +391 -0
  71. package/src/cursor/mcp-packs.js +571 -0
  72. package/src/cursor/patch.js +243 -0
  73. package/src/cursor/plans.js +254 -0
  74. package/src/cursor/premium.js +468 -0
  75. package/src/cursor/setup.js +488 -0
  76. package/src/cursor/techniques.js +1786 -0
  77. package/src/deep-review.js +345 -0
  78. package/src/domain-packs.js +364 -0
  79. package/src/formatters/sarif.js +115 -0
  80. package/src/gemini/activity.js +402 -0
  81. package/src/gemini/config-parser.js +275 -0
  82. package/src/gemini/context.js +221 -0
  83. package/src/gemini/deep-review.js +559 -0
  84. package/src/gemini/domain-packs.js +371 -0
  85. package/src/gemini/freshness.js +204 -0
  86. package/src/gemini/governance.js +201 -0
  87. package/src/gemini/interactive.js +860 -0
  88. package/src/gemini/mcp-packs.js +658 -0
  89. package/src/gemini/patch.js +229 -0
  90. package/src/gemini/plans.js +269 -0
  91. package/src/gemini/premium.js +759 -0
  92. package/src/gemini/setup.js +692 -0
  93. package/src/gemini/techniques.js +2084 -0
  94. package/src/governance.js +523 -0
  95. package/src/harmony/advisor.js +383 -0
  96. package/src/harmony/audit.js +303 -0
  97. package/src/harmony/canon.js +444 -0
  98. package/src/harmony/cli.js +331 -0
  99. package/src/harmony/drift.js +401 -0
  100. package/src/harmony/governance.js +313 -0
  101. package/src/harmony/memory.js +238 -0
  102. package/src/harmony/sync.js +458 -0
  103. package/src/harmony/watch.js +336 -0
  104. package/src/index.js +256 -0
  105. package/src/insights.js +119 -0
  106. package/src/interactive.js +118 -0
  107. package/src/mcp-packs.js +597 -0
  108. package/src/opencode/activity.js +286 -0
  109. package/src/opencode/config-parser.js +109 -0
  110. package/src/opencode/context.js +247 -0
  111. package/src/opencode/deep-review.js +313 -0
  112. package/src/opencode/domain-packs.js +240 -0
  113. package/src/opencode/freshness.js +158 -0
  114. package/src/opencode/governance.js +159 -0
  115. package/src/opencode/interactive.js +392 -0
  116. package/src/opencode/mcp-packs.js +474 -0
  117. package/src/opencode/patch.js +184 -0
  118. package/src/opencode/plans.js +231 -0
  119. package/src/opencode/premium.js +413 -0
  120. package/src/opencode/setup.js +449 -0
  121. package/src/opencode/techniques.js +1713 -0
  122. package/src/plans.js +655 -0
  123. package/src/secret-patterns.js +30 -0
  124. package/src/setup.js +1274 -0
  125. package/src/synergy/adaptive.js +261 -0
  126. package/src/synergy/compensation.js +156 -0
  127. package/src/synergy/evidence.js +193 -0
  128. package/src/synergy/learning.js +184 -0
  129. package/src/synergy/patterns.js +227 -0
  130. package/src/synergy/ranking.js +83 -0
  131. package/src/synergy/report.js +163 -0
  132. package/src/synergy/routing.js +152 -0
  133. package/src/techniques.js +1354 -0
  134. package/src/watch.js +229 -0
  135. package/src/windsurf/activity.js +302 -0
  136. package/src/windsurf/config-parser.js +267 -0
  137. package/src/windsurf/context.js +249 -0
  138. package/src/windsurf/deep-review.js +337 -0
  139. package/src/windsurf/domain-packs.js +348 -0
  140. package/src/windsurf/freshness.js +215 -0
  141. package/src/windsurf/governance.js +231 -0
  142. package/src/windsurf/interactive.js +388 -0
  143. package/src/windsurf/mcp-packs.js +535 -0
  144. package/src/windsurf/patch.js +231 -0
  145. package/src/windsurf/plans.js +247 -0
  146. package/src/windsurf/premium.js +467 -0
  147. package/src/windsurf/setup.js +471 -0
  148. package/src/windsurf/techniques.js +1758 -0
@@ -0,0 +1,618 @@
1
+ /**
2
+ * Codex Interactive Wizard — CP-14
3
+ *
4
+ * 8-stage guided setup for Codex CLI projects.
5
+ * Uses Node.js readline (zero dependencies), same pattern as the Claude wizard.
6
+ *
7
+ * Stages:
8
+ * 1. Project detection
9
+ * 2. Trust & approval posture
10
+ * 3. Agent structure
11
+ * 4. Domain pack selection
12
+ * 5. MCP pack selection
13
+ * 6. Hook configuration
14
+ * 7. CI integration
15
+ * 8. Review & generate
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const readline = require('readline');
21
+ const { STACKS } = require('../techniques');
22
+ const { CodexProjectContext } = require('./context');
23
+ const { CODEX_TECHNIQUES } = require('./techniques');
24
+ const { CODEX_DOMAIN_PACKS, detectCodexDomainPacks } = require('./domain-packs');
25
+ const { recommendCodexMcpPacks, CODEX_MCP_PACKS } = require('./mcp-packs');
26
+ const { setupCodex } = require('./setup');
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Colors & helpers (matches Claude interactive.js)
30
+ // ---------------------------------------------------------------------------
31
+
32
+ const COLORS = {
33
+ reset: '\x1b[0m', bold: '\x1b[1m', dim: '\x1b[2m',
34
+ red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m',
35
+ blue: '\x1b[36m', magenta: '\x1b[35m',
36
+ };
37
+ const c = (text, color) => `${COLORS[color] || ''}${text}${COLORS.reset}`;
38
+
39
+ function ask(rl, question) {
40
+ return new Promise(resolve => rl.question(question, resolve));
41
+ }
42
+
43
+ function isTTY() {
44
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Stage definitions
49
+ // ---------------------------------------------------------------------------
50
+
51
+ const STAGE_NAMES = [
52
+ 'Project Detection',
53
+ 'Trust & Approval Posture',
54
+ 'Agent Structure',
55
+ 'Domain Pack Selection',
56
+ 'MCP Pack Selection',
57
+ 'Hook Configuration',
58
+ 'CI Integration',
59
+ 'Review & Generate',
60
+ ];
61
+
62
+ function printStageHeader(index) {
63
+ const num = index + 1;
64
+ const total = STAGE_NAMES.length;
65
+ console.log('');
66
+ console.log(c(` ── Stage ${num}/${total}: ${STAGE_NAMES[index]} ──`, 'magenta'));
67
+ console.log('');
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Stage 1 — Project Detection
72
+ // ---------------------------------------------------------------------------
73
+
74
+ function runProjectDetection(ctx) {
75
+ const stacks = ctx.detectStacks(STACKS);
76
+ const hasCodexDir = fs.existsSync(path.join(ctx.dir, '.codex'));
77
+ const hasAgentsMd = Boolean(ctx.fileContent('AGENTS.md'));
78
+ const configContent = ctx.configContent ? ctx.configContent() : null;
79
+
80
+ // Quick audit
81
+ const auditResults = [];
82
+ for (const [key, technique] of Object.entries(CODEX_TECHNIQUES)) {
83
+ auditResults.push({ key, ...technique, passed: technique.check(ctx) });
84
+ }
85
+ const passed = auditResults.filter(r => r.passed === true);
86
+ const failed = auditResults.filter(r => r.passed === false);
87
+
88
+ return { stacks, hasCodexDir, hasAgentsMd, configContent, auditResults, passed, failed };
89
+ }
90
+
91
+ async function stageProjectDetection(rl, ctx, state) {
92
+ printStageHeader(0);
93
+ const det = runProjectDetection(ctx);
94
+ Object.assign(state, det);
95
+
96
+ if (det.stacks.length > 0) {
97
+ console.log(c(` Detected stacks: ${det.stacks.map(s => s.label).join(', ')}`, 'blue'));
98
+ } else {
99
+ console.log(c(' No specific stack detected — will use baseline defaults.', 'dim'));
100
+ }
101
+
102
+ console.log(c(` Working directory: ${ctx.dir}`, 'dim'));
103
+ console.log('');
104
+ console.log(` ${c(`${det.passed.length}/${det.auditResults.length}`, 'bold')} Codex checks passing.`);
105
+ console.log(` ${c(String(det.failed.length), 'yellow')} improvements available.`);
106
+
107
+ if (det.hasCodexDir || det.hasAgentsMd) {
108
+ console.log('');
109
+ console.log(c(' Existing Codex configuration detected:', 'yellow'));
110
+ if (det.hasCodexDir) console.log(c(' .codex/ directory found', 'dim'));
111
+ if (det.hasAgentsMd) console.log(c(' AGENTS.md found', 'dim'));
112
+ console.log('');
113
+
114
+ const migrationAnswer = await ask(rl, c(' Merge with existing config or replace? (merge/replace/quit) ', 'magenta'));
115
+ const choice = migrationAnswer.trim().toLowerCase();
116
+ if (choice === 'quit' || choice === 'q') return 'quit';
117
+ state.migrationMode = choice === 'replace' ? 'replace' : 'merge';
118
+ console.log(c(` → ${state.migrationMode === 'replace' ? 'Will replace existing files' : 'Will merge with existing config'}`, 'green'));
119
+ } else {
120
+ state.migrationMode = 'create';
121
+ console.log('');
122
+ console.log(c(' No existing Codex config — will create fresh setup.', 'dim'));
123
+ }
124
+
125
+ return 'next';
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Stage 2 — Trust & Approval Posture
130
+ // ---------------------------------------------------------------------------
131
+
132
+ const APPROVAL_POLICIES = [
133
+ { key: 'suggest', label: 'Suggest (safest)', desc: 'Codex suggests changes but never writes without approval.' },
134
+ { key: 'auto-edit', label: 'Auto-Edit (balanced)', desc: 'Codex can edit files but asks before running commands.' },
135
+ { key: 'full-auto', label: 'Full-Auto (maximum autonomy)', desc: 'Codex runs everything automatically. Use only in trusted sandboxes.' },
136
+ ];
137
+
138
+ const SANDBOX_MODES = [
139
+ { key: 'workspace-write', label: 'Workspace Write (default)', desc: 'Write only within the project directory.' },
140
+ { key: 'workspace-read', label: 'Workspace Read', desc: 'Read-only access to the project directory.' },
141
+ { key: 'full-write', label: 'Full Write', desc: 'Write anywhere on disk. Use with extreme caution.' },
142
+ ];
143
+
144
+ async function stageTrustPosture(rl, _ctx, state) {
145
+ printStageHeader(1);
146
+
147
+ console.log(' Select an approval policy for Codex:');
148
+ console.log('');
149
+ APPROVAL_POLICIES.forEach((p, i) => {
150
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(p.label, 'blue')} — ${p.desc}`);
151
+ });
152
+ console.log('');
153
+
154
+ const policyAnswer = await ask(rl, c(' Choice (1-3, or b=back, q=quit) [1]: ', 'magenta'));
155
+ const trimmed = policyAnswer.trim().toLowerCase();
156
+ if (trimmed === 'b') return 'back';
157
+ if (trimmed === 'q') return 'quit';
158
+
159
+ const policyIndex = parseInt(trimmed, 10);
160
+ const selectedPolicy = APPROVAL_POLICIES[(policyIndex >= 1 && policyIndex <= 3) ? policyIndex - 1 : 0];
161
+ state.approvalPolicy = selectedPolicy.key;
162
+ console.log(c(` → Approval policy: ${selectedPolicy.label}`, 'green'));
163
+
164
+ console.log('');
165
+ console.log(' Select a sandbox mode:');
166
+ console.log('');
167
+ SANDBOX_MODES.forEach((m, i) => {
168
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(m.label, 'blue')} — ${m.desc}`);
169
+ });
170
+ console.log('');
171
+
172
+ const sandboxAnswer = await ask(rl, c(' Choice (1-3) [1]: ', 'magenta'));
173
+ const sandboxIndex = parseInt(sandboxAnswer.trim(), 10);
174
+ const selectedSandbox = SANDBOX_MODES[(sandboxIndex >= 1 && sandboxIndex <= 3) ? sandboxIndex - 1 : 0];
175
+ state.sandboxMode = selectedSandbox.key;
176
+ console.log(c(` → Sandbox mode: ${selectedSandbox.label}`, 'green'));
177
+
178
+ return 'next';
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Stage 3 — Agent Structure
183
+ // ---------------------------------------------------------------------------
184
+
185
+ async function stageAgentStructure(rl, _ctx, state) {
186
+ printStageHeader(2);
187
+
188
+ console.log(' How should Codex operate in this project?');
189
+ console.log('');
190
+ console.log(` ${c('1', 'bold')}. ${c('Single agent', 'blue')} — One Codex agent handles everything (simpler, good for small repos).`);
191
+ console.log(` ${c('2', 'bold')}. ${c('Multi-agent', 'blue')} — Orchestrator + specialized sub-agents (better for large repos).`);
192
+ console.log('');
193
+
194
+ const answer = await ask(rl, c(' Choice (1-2, or b=back, q=quit) [1]: ', 'magenta'));
195
+ const trimmed = answer.trim().toLowerCase();
196
+ if (trimmed === 'b') return 'back';
197
+ if (trimmed === 'q') return 'quit';
198
+
199
+ state.agentMode = trimmed === '2' ? 'multi' : 'single';
200
+ console.log(c(` → Agent mode: ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`, 'green'));
201
+
202
+ if (state.agentMode === 'multi') {
203
+ console.log('');
204
+ console.log(c(' Will generate .codex/agents/ with sub-agent TOML starters.', 'dim'));
205
+ }
206
+
207
+ return 'next';
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // Stage 4 — Domain Pack Selection
212
+ // ---------------------------------------------------------------------------
213
+
214
+ async function stageDomainPacks(rl, ctx, state) {
215
+ printStageHeader(3);
216
+
217
+ const detected = detectCodexDomainPacks(ctx, state.stacks || []);
218
+ const detectedKeys = new Set(detected.map(p => p.key));
219
+
220
+ console.log(' Available domain packs:');
221
+ console.log('');
222
+
223
+ const allPacks = CODEX_DOMAIN_PACKS.map(pack => {
224
+ const isDetected = detectedKeys.has(pack.key);
225
+ return { ...pack, isDetected };
226
+ });
227
+
228
+ allPacks.forEach((pack, i) => {
229
+ const marker = pack.isDetected ? c(' (detected)', 'green') : '';
230
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}`);
231
+ console.log(c(` ${pack.useWhen}`, 'dim'));
232
+ });
233
+ console.log('');
234
+
235
+ const defaultSelection = allPacks
236
+ .map((p, i) => p.isDetected ? String(i + 1) : null)
237
+ .filter(Boolean)
238
+ .join(',');
239
+
240
+ const answer = await ask(rl, c(` Select packs (comma-separated numbers, or b=back, q=quit) [${defaultSelection || 'all detected'}]: `, 'magenta'));
241
+ const trimmed = answer.trim().toLowerCase();
242
+ if (trimmed === 'b') return 'back';
243
+ if (trimmed === 'q') return 'quit';
244
+
245
+ let selectedPacks;
246
+ if (trimmed === '' || trimmed === 'all') {
247
+ selectedPacks = detected;
248
+ } else {
249
+ const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < allPacks.length);
250
+ selectedPacks = indices.map(i => allPacks[i]);
251
+ }
252
+
253
+ state.domainPacks = selectedPacks;
254
+ console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
255
+
256
+ return 'next';
257
+ }
258
+
259
+ // ---------------------------------------------------------------------------
260
+ // Stage 5 — MCP Pack Selection
261
+ // ---------------------------------------------------------------------------
262
+
263
+ async function stageMcpPacks(rl, ctx, state) {
264
+ printStageHeader(4);
265
+
266
+ const recommended = recommendCodexMcpPacks(state.stacks || [], state.domainPacks || [], { ctx });
267
+ const recommendedKeys = new Set(recommended.map(p => p.key));
268
+
269
+ console.log(' Available MCP packs:');
270
+ console.log('');
271
+
272
+ CODEX_MCP_PACKS.forEach((pack, i) => {
273
+ const isRec = recommendedKeys.has(pack.key);
274
+ const marker = isRec ? c(' (recommended)', 'green') : '';
275
+ const authNote = pack.requiredAuth.length > 0
276
+ ? c(` [requires: ${pack.requiredAuth.join(', ')}]`, 'yellow')
277
+ : '';
278
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(pack.label, 'blue')}${marker}${authNote}`);
279
+ console.log(c(` ${pack.description}`, 'dim'));
280
+ });
281
+ console.log('');
282
+
283
+ const defaultSelection = CODEX_MCP_PACKS
284
+ .map((p, i) => recommendedKeys.has(p.key) ? String(i + 1) : null)
285
+ .filter(Boolean)
286
+ .join(',');
287
+
288
+ const answer = await ask(rl, c(` Select packs (comma-separated numbers, n=none, b=back, q=quit) [${defaultSelection || 'none'}]: `, 'magenta'));
289
+ const trimmed = answer.trim().toLowerCase();
290
+ if (trimmed === 'b') return 'back';
291
+ if (trimmed === 'q') return 'quit';
292
+
293
+ let selectedPacks;
294
+ if (trimmed === 'n' || trimmed === 'none') {
295
+ selectedPacks = [];
296
+ } else if (trimmed === '') {
297
+ selectedPacks = recommended;
298
+ } else {
299
+ const indices = trimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < CODEX_MCP_PACKS.length);
300
+ selectedPacks = indices.map(i => CODEX_MCP_PACKS[i]);
301
+ }
302
+
303
+ state.mcpPacks = selectedPacks;
304
+ console.log(c(` → Selected: ${selectedPacks.map(p => p.label).join(', ') || 'none'}`, 'green'));
305
+
306
+ return 'next';
307
+ }
308
+
309
+ // ---------------------------------------------------------------------------
310
+ // Stage 6 — Hook Configuration
311
+ // ---------------------------------------------------------------------------
312
+
313
+ const COMMON_HOOKS = [
314
+ { key: 'session-start', event: 'SessionStart', label: 'Session Start greeting', command: "echo 'Codex session started'" },
315
+ { key: 'pre-commit-lint', event: 'PreToolUse', label: 'Pre-commit lint check', command: 'npm run lint --silent' },
316
+ { key: 'post-test', event: 'PostToolUse', label: 'Post-tool test runner', command: 'npm test --silent' },
317
+ { key: 'security-scan', event: 'PreToolUse', label: 'Security pattern scan', command: "grep -rn 'TODO:SECURITY' . || true" },
318
+ ];
319
+
320
+ async function stageHooks(rl, _ctx, state) {
321
+ printStageHeader(5);
322
+
323
+ console.log(' Configure Codex hooks (event-driven scripts that run during sessions):');
324
+ console.log('');
325
+
326
+ const answer = await ask(rl, c(' Enable hooks? (y/n, b=back, q=quit) [y]: ', 'magenta'));
327
+ const trimmed = answer.trim().toLowerCase();
328
+ if (trimmed === 'b') return 'back';
329
+ if (trimmed === 'q') return 'quit';
330
+
331
+ if (trimmed === 'n') {
332
+ state.hooks = [];
333
+ state.hooksEnabled = false;
334
+ console.log(c(' → Hooks disabled.', 'dim'));
335
+ return 'next';
336
+ }
337
+
338
+ state.hooksEnabled = true;
339
+ console.log('');
340
+ console.log(' Common hook patterns:');
341
+ console.log('');
342
+
343
+ COMMON_HOOKS.forEach((hook, i) => {
344
+ console.log(` ${c(`${i + 1}`, 'bold')}. ${c(hook.label, 'blue')} (${hook.event})`);
345
+ console.log(c(` ${hook.command}`, 'dim'));
346
+ });
347
+ console.log('');
348
+
349
+ const hookAnswer = await ask(rl, c(' Select hooks (comma-separated numbers, a=all, n=none) [1]: ', 'magenta'));
350
+ const hookTrimmed = hookAnswer.trim().toLowerCase();
351
+
352
+ let selectedHooks;
353
+ if (hookTrimmed === 'n' || hookTrimmed === 'none') {
354
+ selectedHooks = [];
355
+ } else if (hookTrimmed === 'a' || hookTrimmed === 'all') {
356
+ selectedHooks = [...COMMON_HOOKS];
357
+ } else if (hookTrimmed === '') {
358
+ selectedHooks = [COMMON_HOOKS[0]];
359
+ } else {
360
+ const indices = hookTrimmed.split(',').map(s => parseInt(s.trim(), 10) - 1).filter(i => i >= 0 && i < COMMON_HOOKS.length);
361
+ selectedHooks = indices.map(i => COMMON_HOOKS[i]);
362
+ }
363
+
364
+ state.hooks = selectedHooks;
365
+ console.log(c(` → Selected ${selectedHooks.length} hook(s): ${selectedHooks.map(h => h.label).join(', ') || 'none'}`, 'green'));
366
+
367
+ return 'next';
368
+ }
369
+
370
+ // ---------------------------------------------------------------------------
371
+ // Stage 7 — CI Integration
372
+ // ---------------------------------------------------------------------------
373
+
374
+ async function stageCi(rl, _ctx, state) {
375
+ printStageHeader(6);
376
+
377
+ console.log(' Optionally generate a GitHub Actions workflow for Codex-based PR review.');
378
+ console.log(c(' This creates .github/workflows/codex-review.yml', 'dim'));
379
+ console.log('');
380
+
381
+ const answer = await ask(rl, c(' Generate CI workflow? (y/n, b=back, q=quit) [n]: ', 'magenta'));
382
+ const trimmed = answer.trim().toLowerCase();
383
+ if (trimmed === 'b') return 'back';
384
+ if (trimmed === 'q') return 'quit';
385
+
386
+ state.enableCi = trimmed === 'y' || trimmed === 'yes';
387
+ console.log(c(` → CI workflow: ${state.enableCi ? 'will be generated' : 'skipped'}`, state.enableCi ? 'green' : 'dim'));
388
+
389
+ return 'next';
390
+ }
391
+
392
+ // ---------------------------------------------------------------------------
393
+ // Stage 8 — Review & Generate
394
+ // ---------------------------------------------------------------------------
395
+
396
+ async function stageReviewAndGenerate(rl, ctx, state, options) {
397
+ printStageHeader(7);
398
+
399
+ console.log(c(' Setup Summary:', 'bold'));
400
+ console.log('');
401
+ console.log(` ${c('Directory:', 'dim')} ${ctx.dir}`);
402
+ console.log(` ${c('Stacks:', 'dim')} ${(state.stacks || []).map(s => s.label).join(', ') || 'none detected'}`);
403
+ console.log(` ${c('Migration:', 'dim')} ${state.migrationMode || 'create'}`);
404
+ console.log(` ${c('Approval:', 'dim')} ${state.approvalPolicy || 'suggest'}`);
405
+ console.log(` ${c('Sandbox:', 'dim')} ${state.sandboxMode || 'workspace-write'}`);
406
+ console.log(` ${c('Agent mode:', 'dim')} ${state.agentMode === 'multi' ? 'Multi-agent' : 'Single agent'}`);
407
+ console.log(` ${c('Domain packs:', 'dim')} ${(state.domainPacks || []).map(p => p.label).join(', ') || 'none'}`);
408
+ console.log(` ${c('MCP packs:', 'dim')} ${(state.mcpPacks || []).map(p => p.label).join(', ') || 'none'}`);
409
+ console.log(` ${c('Hooks:', 'dim')} ${state.hooksEnabled ? `${(state.hooks || []).length} hook(s)` : 'disabled'}`);
410
+ console.log(` ${c('CI workflow:', 'dim')} ${state.enableCi ? 'yes' : 'no'}`);
411
+ console.log('');
412
+
413
+ // List artifacts that will be generated
414
+ const artifacts = ['AGENTS.md', '.codex/config.toml'];
415
+ if (state.agentMode === 'multi') artifacts.push('.codex/agents/ (sub-agent starters)');
416
+ if ((state.domainPacks || []).length > 0) artifacts.push('.codex/rules/ (domain rules)');
417
+ if ((state.mcpPacks || []).length > 0) artifacts.push('.codex/config.toml (MCP sections)');
418
+ if (state.hooksEnabled && (state.hooks || []).length > 0) artifacts.push('.codex/hooks.json');
419
+ if (state.enableCi) artifacts.push('.github/workflows/codex-review.yml');
420
+ artifacts.push('.agents/skills/ (skill starter)');
421
+
422
+ console.log(c(' Artifacts to generate:', 'bold'));
423
+ for (const a of artifacts) {
424
+ console.log(c(` + ${a}`, 'green'));
425
+ }
426
+ console.log('');
427
+
428
+ const answer = await ask(rl, c(' Proceed with generation? (y/n, b=back) [y]: ', 'magenta'));
429
+ const trimmed = answer.trim().toLowerCase();
430
+ if (trimmed === 'b') return 'back';
431
+ if (trimmed === 'n' || trimmed === 'q') return 'quit';
432
+
433
+ // Build module list from wizard selections
434
+ const modules = ['rules', 'skills'];
435
+ if (state.agentMode === 'multi') modules.push('subagents');
436
+ if ((state.mcpPacks || []).length > 0) modules.push('mcp');
437
+ if (state.hooksEnabled && (state.hooks || []).length > 0) modules.push('hooks');
438
+ if (state.enableCi) modules.push('ci');
439
+
440
+ console.log('');
441
+ console.log(c(' Generating artifacts...', 'bold'));
442
+ console.log('');
443
+
444
+ // Write custom hooks.json if hooks were selected
445
+ if (state.hooksEnabled && (state.hooks || []).length > 0) {
446
+ const hooksPayload = {
447
+ "$schema": "https://docs.codex.ai/hooks-schema.json",
448
+ hooks: state.hooks.map(h => ({
449
+ event: h.event,
450
+ command: h.command,
451
+ description: h.label,
452
+ timeout_ms: 10000,
453
+ })),
454
+ };
455
+ const hooksDir = path.join(ctx.dir, '.codex');
456
+ fs.mkdirSync(hooksDir, { recursive: true });
457
+ const hooksPath = path.join(hooksDir, 'hooks.json');
458
+ if (state.migrationMode !== 'merge' || !fs.existsSync(hooksPath)) {
459
+ fs.writeFileSync(hooksPath, JSON.stringify(hooksPayload, null, 2) + '\n', 'utf8');
460
+ console.log(c(' + Created .codex/hooks.json', 'green'));
461
+ } else {
462
+ console.log(c(' ~ Skipped .codex/hooks.json (exists, merge mode)', 'dim'));
463
+ }
464
+ }
465
+
466
+ // Write custom config overrides before running setupCodex
467
+ // (setupCodex creates the base config; we patch approval/sandbox after)
468
+ const result = await setupCodex({
469
+ ...options,
470
+ dir: ctx.dir,
471
+ modules,
472
+ domainPacks: state.domainPacks || [],
473
+ silent: true,
474
+ });
475
+
476
+ // Patch config.toml with wizard-selected trust settings
477
+ const configPath = path.join(ctx.dir, '.codex', 'config.toml');
478
+ if (fs.existsSync(configPath)) {
479
+ let configContent = fs.readFileSync(configPath, 'utf8');
480
+
481
+ const approvalPolicy = state.approvalPolicy || 'suggest';
482
+ const sandboxMode = state.sandboxMode || 'workspace-write';
483
+
484
+ // Map wizard approval keys to Codex config values
485
+ const approvalMap = {
486
+ 'suggest': 'on-request',
487
+ 'auto-edit': 'unless-allow-listed',
488
+ 'full-auto': 'never',
489
+ };
490
+ const configApproval = approvalMap[approvalPolicy] || 'on-request';
491
+
492
+ configContent = configContent.replace(
493
+ /^approval_policy\s*=\s*"[^"]*"/m,
494
+ `approval_policy = "${configApproval}"`
495
+ );
496
+ configContent = configContent.replace(
497
+ /^sandbox_mode\s*=\s*"[^"]*"/m,
498
+ `sandbox_mode = "${sandboxMode}"`
499
+ );
500
+
501
+ // Also patch the [profiles.safe] section
502
+ configContent = configContent.replace(
503
+ /(\[profiles\.safe\]\s*\n)approval_policy\s*=\s*"[^"]*"/m,
504
+ `$1approval_policy = "${configApproval}"`
505
+ );
506
+ configContent = configContent.replace(
507
+ /(\[profiles\.safe\]\s*\n[^\[]*?)sandbox_mode\s*=\s*"[^"]*"/m,
508
+ `$1sandbox_mode = "${sandboxMode}"`
509
+ );
510
+
511
+ fs.writeFileSync(configPath, configContent, 'utf8');
512
+ }
513
+
514
+ // Report results
515
+ console.log('');
516
+ for (const file of result.writtenFiles || []) {
517
+ console.log(c(` + ${file}`, 'green'));
518
+ }
519
+ for (const file of result.preservedFiles || []) {
520
+ console.log(c(` ~ ${file} (preserved)`, 'dim'));
521
+ }
522
+
523
+ console.log('');
524
+ console.log(` ${c(String(result.created || 0), 'bold')} files created.`);
525
+ if (result.skipped > 0) {
526
+ console.log(` ${c(String(result.skipped), 'dim')} existing files preserved.`);
527
+ }
528
+ if (result.rollbackArtifact) {
529
+ console.log(` Rollback: ${c(result.rollbackArtifact, 'dim')}`);
530
+ }
531
+
532
+ return 'done';
533
+ }
534
+
535
+ // ---------------------------------------------------------------------------
536
+ // Main wizard loop with back-navigation
537
+ // ---------------------------------------------------------------------------
538
+
539
+ const STAGES = [
540
+ stageProjectDetection,
541
+ stageTrustPosture,
542
+ stageAgentStructure,
543
+ stageDomainPacks,
544
+ stageMcpPacks,
545
+ stageHooks,
546
+ stageCi,
547
+ stageReviewAndGenerate,
548
+ ];
549
+
550
+ async function codexInteractive(options = {}) {
551
+ const dir = options.dir || process.cwd();
552
+
553
+ // Non-interactive fallback: if no TTY, run direct setup
554
+ if (!isTTY()) {
555
+ console.log(c(' No interactive terminal detected — running direct setup.', 'dim'));
556
+ return setupCodex({ ...options, dir, silent: false });
557
+ }
558
+
559
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
560
+ const ctx = new CodexProjectContext(dir);
561
+ const state = {};
562
+
563
+ console.log('');
564
+ console.log(c(' +-------------------------------------------+', 'magenta'));
565
+ console.log(c(' | nerviq: Codex Interactive Wizard |', 'magenta'));
566
+ console.log(c(' +-------------------------------------------+', 'magenta'));
567
+ console.log('');
568
+ console.log(c(` Working directory: ${dir}`, 'dim'));
569
+
570
+ let stageIndex = 0;
571
+
572
+ while (stageIndex < STAGES.length) {
573
+ const stageFn = STAGES[stageIndex];
574
+ let result;
575
+
576
+ try {
577
+ result = await stageFn(rl, ctx, state, options);
578
+ } catch (err) {
579
+ console.log('');
580
+ console.log(c(` Error in stage: ${err.message}`, 'red'));
581
+ rl.close();
582
+ throw err;
583
+ }
584
+
585
+ if (result === 'quit') {
586
+ console.log('');
587
+ console.log(c(' Wizard cancelled. No changes were made.', 'dim'));
588
+ rl.close();
589
+ return { cancelled: true };
590
+ }
591
+
592
+ if (result === 'back') {
593
+ if (stageIndex > 0) {
594
+ stageIndex--;
595
+ } else {
596
+ console.log(c(' Already at the first stage.', 'dim'));
597
+ }
598
+ continue;
599
+ }
600
+
601
+ if (result === 'done') {
602
+ break;
603
+ }
604
+
605
+ // 'next' — advance
606
+ stageIndex++;
607
+ }
608
+
609
+ rl.close();
610
+
611
+ console.log('');
612
+ console.log(c(' Done! Run `npx nerviq --platform codex` to audit your setup.', 'green'));
613
+ console.log('');
614
+
615
+ return { cancelled: false, state };
616
+ }
617
+
618
+ module.exports = { codexInteractive };