@nerviq/cli 1.17.3 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +4 -4
  3. package/bin/cli.js +61 -274
  4. package/package.json +60 -60
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +158 -158
  9. package/src/aider/deep-review.js +316 -316
  10. package/src/aider/domain-packs.js +303 -303
  11. package/src/aider/freshness.js +93 -93
  12. package/src/aider/governance.js +253 -253
  13. package/src/aider/interactive.js +334 -334
  14. package/src/aider/mcp-packs.js +329 -329
  15. package/src/aider/patch.js +214 -214
  16. package/src/aider/plans.js +186 -186
  17. package/src/aider/premium.js +360 -360
  18. package/src/aider/setup.js +404 -404
  19. package/src/aider/techniques.js +16 -16
  20. package/src/analyze.js +951 -951
  21. package/src/anti-patterns.js +485 -485
  22. package/src/audit/instruction-files.js +180 -180
  23. package/src/audit/recommendations.js +577 -577
  24. package/src/auto-suggest.js +154 -154
  25. package/src/badge.js +13 -13
  26. package/src/behavioral-drift.js +801 -801
  27. package/src/benchmark.js +67 -67
  28. package/src/catalog.js +103 -103
  29. package/src/certification.js +128 -128
  30. package/src/codex/config-parser.js +183 -183
  31. package/src/codex/context.js +223 -223
  32. package/src/codex/deep-review.js +493 -493
  33. package/src/codex/domain-packs.js +394 -394
  34. package/src/codex/freshness.js +84 -84
  35. package/src/codex/governance.js +192 -192
  36. package/src/codex/interactive.js +618 -618
  37. package/src/codex/mcp-packs.js +914 -914
  38. package/src/codex/patch.js +209 -209
  39. package/src/codex/plans.js +251 -251
  40. package/src/codex/premium.js +614 -614
  41. package/src/codex/setup.js +591 -591
  42. package/src/context.js +320 -320
  43. package/src/continuous-ops.js +681 -681
  44. package/src/copilot/activity.js +309 -309
  45. package/src/copilot/config-parser.js +280 -226
  46. package/src/copilot/context.js +218 -197
  47. package/src/copilot/deep-review.js +346 -346
  48. package/src/copilot/domain-packs.js +372 -372
  49. package/src/copilot/freshness.js +57 -57
  50. package/src/copilot/governance.js +222 -222
  51. package/src/copilot/interactive.js +406 -406
  52. package/src/copilot/mcp-packs.js +826 -826
  53. package/src/copilot/plans.js +253 -253
  54. package/src/copilot/premium.js +451 -451
  55. package/src/copilot/setup.js +488 -488
  56. package/src/copilot/techniques.js +219 -78
  57. package/src/cost-tracking.js +61 -61
  58. package/src/cursor/activity.js +301 -301
  59. package/src/cursor/config-parser.js +265 -265
  60. package/src/cursor/context.js +256 -256
  61. package/src/cursor/deep-review.js +334 -334
  62. package/src/cursor/domain-packs.js +368 -368
  63. package/src/cursor/freshness.js +65 -65
  64. package/src/cursor/governance.js +229 -229
  65. package/src/cursor/interactive.js +391 -391
  66. package/src/cursor/mcp-packs.js +828 -828
  67. package/src/cursor/plans.js +254 -254
  68. package/src/cursor/premium.js +469 -469
  69. package/src/cursor/setup.js +488 -488
  70. package/src/dashboard.js +493 -493
  71. package/src/deep-review.js +428 -428
  72. package/src/deprecation.js +98 -98
  73. package/src/diff-only.js +280 -280
  74. package/src/doctor.js +119 -119
  75. package/src/domain-pack-expansion.js +1033 -1033
  76. package/src/domain-packs.js +387 -387
  77. package/src/feedback.js +178 -178
  78. package/src/fix-engine.js +783 -0
  79. package/src/fix-prompts.js +122 -122
  80. package/src/formatters/sarif.js +115 -115
  81. package/src/freshness.js +74 -74
  82. package/src/gemini/config-parser.js +275 -275
  83. package/src/gemini/context.js +221 -221
  84. package/src/gemini/deep-review.js +559 -559
  85. package/src/gemini/domain-packs.js +393 -393
  86. package/src/gemini/freshness.js +66 -66
  87. package/src/gemini/governance.js +201 -201
  88. package/src/gemini/interactive.js +860 -860
  89. package/src/gemini/mcp-packs.js +915 -915
  90. package/src/gemini/plans.js +269 -269
  91. package/src/gemini/premium.js +760 -760
  92. package/src/gemini/setup.js +692 -692
  93. package/src/gemini/techniques.js +14 -14
  94. package/src/governance.js +72 -72
  95. package/src/harmony/add.js +68 -68
  96. package/src/harmony/advisor.js +333 -333
  97. package/src/harmony/canon.js +565 -565
  98. package/src/harmony/cli.js +591 -591
  99. package/src/harmony/drift.js +401 -401
  100. package/src/harmony/governance.js +313 -313
  101. package/src/harmony/memory.js +239 -239
  102. package/src/harmony/sync.js +475 -475
  103. package/src/harmony/watch.js +370 -370
  104. package/src/hook-validation.js +342 -342
  105. package/src/index.js +271 -271
  106. package/src/init.js +184 -184
  107. package/src/instruction-surfaces.js +185 -185
  108. package/src/integrations.js +144 -144
  109. package/src/interactive.js +118 -118
  110. package/src/locales/en.json +1 -1
  111. package/src/locales/es.json +1 -1
  112. package/src/mcp-packs.js +830 -830
  113. package/src/mcp-server.js +726 -726
  114. package/src/mcp-validation.js +337 -337
  115. package/src/nerviq-sync.json +7 -7
  116. package/src/opencode/config-parser.js +109 -109
  117. package/src/opencode/context.js +247 -247
  118. package/src/opencode/deep-review.js +313 -313
  119. package/src/opencode/domain-packs.js +262 -262
  120. package/src/opencode/freshness.js +66 -66
  121. package/src/opencode/governance.js +159 -159
  122. package/src/opencode/interactive.js +392 -392
  123. package/src/opencode/mcp-packs.js +705 -705
  124. package/src/opencode/patch.js +184 -184
  125. package/src/opencode/plans.js +231 -231
  126. package/src/opencode/premium.js +413 -413
  127. package/src/opencode/setup.js +449 -449
  128. package/src/opencode/techniques.js +27 -27
  129. package/src/operating-profile.js +574 -574
  130. package/src/org.js +152 -152
  131. package/src/permission-rules.js +218 -218
  132. package/src/plans.js +839 -839
  133. package/src/platform-change-manifest.js +86 -86
  134. package/src/plugins.js +110 -110
  135. package/src/policy-layers.js +210 -210
  136. package/src/profiles.js +124 -124
  137. package/src/prompt-injection.js +74 -74
  138. package/src/public-api.js +173 -173
  139. package/src/recommendation-rules.js +84 -84
  140. package/src/repo-archetype.js +386 -386
  141. package/src/secret-patterns.js +39 -39
  142. package/src/server.js +527 -527
  143. package/src/setup/analysis.js +607 -607
  144. package/src/setup/runtime.js +172 -172
  145. package/src/setup.js +677 -677
  146. package/src/shared/capabilities.js +194 -194
  147. package/src/source-urls.js +132 -132
  148. package/src/stack-checks.js +565 -565
  149. package/src/supplemental-checks.js +13 -13
  150. package/src/synergy/adaptive.js +261 -261
  151. package/src/synergy/compensation.js +137 -137
  152. package/src/synergy/evidence.js +193 -193
  153. package/src/synergy/learning.js +199 -199
  154. package/src/synergy/patterns.js +227 -227
  155. package/src/synergy/ranking.js +83 -83
  156. package/src/synergy/report.js +165 -165
  157. package/src/synergy/routing.js +146 -146
  158. package/src/techniques/api.js +407 -407
  159. package/src/techniques/automation.js +316 -316
  160. package/src/techniques/compliance.js +257 -257
  161. package/src/techniques/hygiene.js +294 -294
  162. package/src/techniques/instructions.js +243 -243
  163. package/src/techniques/observability.js +226 -226
  164. package/src/techniques/optimization.js +142 -142
  165. package/src/techniques/quality.js +318 -318
  166. package/src/techniques/security.js +237 -237
  167. package/src/techniques/shared.js +443 -443
  168. package/src/techniques/stacks.js +2294 -2294
  169. package/src/techniques/tools.js +106 -106
  170. package/src/techniques/workflow.js +413 -413
  171. package/src/techniques.js +81 -81
  172. package/src/terminology.js +73 -73
  173. package/src/token-estimate.js +35 -35
  174. package/src/usage-patterns.js +99 -99
  175. package/src/verification-metadata.js +145 -145
  176. package/src/watch.js +247 -247
  177. package/src/windsurf/activity.js +302 -302
  178. package/src/windsurf/config-parser.js +267 -267
  179. package/src/windsurf/context.js +249 -249
  180. package/src/windsurf/deep-review.js +337 -337
  181. package/src/windsurf/domain-packs.js +370 -370
  182. package/src/windsurf/freshness.js +36 -36
  183. package/src/windsurf/governance.js +231 -231
  184. package/src/windsurf/interactive.js +388 -388
  185. package/src/windsurf/mcp-packs.js +792 -792
  186. package/src/windsurf/plans.js +247 -247
  187. package/src/windsurf/premium.js +468 -468
  188. package/src/windsurf/setup.js +471 -471
  189. package/src/windsurf/techniques.js +17 -17
  190. package/src/workspace.js +375 -375
@@ -1,618 +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 };
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 };