@nerviq/cli 1.18.0 → 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 (187) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/bin/cli.js +130 -130
  4. package/package.json +1 -1
  5. package/src/activity.js +1039 -1039
  6. package/src/adoption-advisor.js +299 -299
  7. package/src/aider/config-parser.js +166 -166
  8. package/src/aider/context.js +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/deep-review.js +346 -346
  46. package/src/copilot/domain-packs.js +372 -372
  47. package/src/copilot/freshness.js +57 -57
  48. package/src/copilot/governance.js +222 -222
  49. package/src/copilot/interactive.js +406 -406
  50. package/src/copilot/mcp-packs.js +826 -826
  51. package/src/copilot/plans.js +253 -253
  52. package/src/copilot/premium.js +451 -451
  53. package/src/copilot/setup.js +488 -488
  54. package/src/cost-tracking.js +61 -61
  55. package/src/cursor/activity.js +301 -301
  56. package/src/cursor/config-parser.js +265 -265
  57. package/src/cursor/context.js +256 -256
  58. package/src/cursor/deep-review.js +334 -334
  59. package/src/cursor/domain-packs.js +368 -368
  60. package/src/cursor/freshness.js +65 -65
  61. package/src/cursor/governance.js +229 -229
  62. package/src/cursor/interactive.js +391 -391
  63. package/src/cursor/mcp-packs.js +828 -828
  64. package/src/cursor/plans.js +254 -254
  65. package/src/cursor/premium.js +469 -469
  66. package/src/cursor/setup.js +488 -488
  67. package/src/dashboard.js +493 -493
  68. package/src/deep-review.js +428 -428
  69. package/src/deprecation.js +98 -98
  70. package/src/diff-only.js +280 -280
  71. package/src/doctor.js +119 -119
  72. package/src/domain-pack-expansion.js +1033 -1033
  73. package/src/domain-packs.js +387 -387
  74. package/src/feedback.js +178 -178
  75. package/src/fix-engine.js +783 -783
  76. package/src/fix-prompts.js +122 -122
  77. package/src/formatters/sarif.js +115 -115
  78. package/src/freshness.js +74 -74
  79. package/src/gemini/config-parser.js +275 -275
  80. package/src/gemini/context.js +221 -221
  81. package/src/gemini/deep-review.js +559 -559
  82. package/src/gemini/domain-packs.js +393 -393
  83. package/src/gemini/freshness.js +66 -66
  84. package/src/gemini/governance.js +201 -201
  85. package/src/gemini/interactive.js +860 -860
  86. package/src/gemini/mcp-packs.js +915 -915
  87. package/src/gemini/plans.js +269 -269
  88. package/src/gemini/premium.js +760 -760
  89. package/src/gemini/setup.js +692 -692
  90. package/src/gemini/techniques.js +14 -14
  91. package/src/governance.js +72 -72
  92. package/src/harmony/add.js +68 -68
  93. package/src/harmony/advisor.js +333 -333
  94. package/src/harmony/canon.js +565 -565
  95. package/src/harmony/cli.js +591 -591
  96. package/src/harmony/drift.js +401 -401
  97. package/src/harmony/governance.js +313 -313
  98. package/src/harmony/memory.js +239 -239
  99. package/src/harmony/sync.js +475 -475
  100. package/src/harmony/watch.js +370 -370
  101. package/src/hook-validation.js +342 -342
  102. package/src/index.js +271 -271
  103. package/src/init.js +184 -184
  104. package/src/instruction-surfaces.js +185 -185
  105. package/src/integrations.js +144 -144
  106. package/src/interactive.js +118 -118
  107. package/src/locales/en.json +1 -1
  108. package/src/locales/es.json +1 -1
  109. package/src/mcp-packs.js +830 -830
  110. package/src/mcp-server.js +726 -726
  111. package/src/mcp-validation.js +337 -337
  112. package/src/nerviq-sync.json +7 -7
  113. package/src/opencode/config-parser.js +109 -109
  114. package/src/opencode/context.js +247 -247
  115. package/src/opencode/deep-review.js +313 -313
  116. package/src/opencode/domain-packs.js +262 -262
  117. package/src/opencode/freshness.js +66 -66
  118. package/src/opencode/governance.js +159 -159
  119. package/src/opencode/interactive.js +392 -392
  120. package/src/opencode/mcp-packs.js +705 -705
  121. package/src/opencode/patch.js +184 -184
  122. package/src/opencode/plans.js +231 -231
  123. package/src/opencode/premium.js +413 -413
  124. package/src/opencode/setup.js +449 -449
  125. package/src/opencode/techniques.js +27 -27
  126. package/src/operating-profile.js +574 -574
  127. package/src/org.js +152 -152
  128. package/src/permission-rules.js +218 -218
  129. package/src/plans.js +839 -839
  130. package/src/platform-change-manifest.js +86 -86
  131. package/src/plugins.js +110 -110
  132. package/src/policy-layers.js +210 -210
  133. package/src/profiles.js +124 -124
  134. package/src/prompt-injection.js +74 -74
  135. package/src/public-api.js +173 -173
  136. package/src/recommendation-rules.js +84 -84
  137. package/src/repo-archetype.js +386 -386
  138. package/src/secret-patterns.js +39 -39
  139. package/src/server.js +527 -527
  140. package/src/setup/analysis.js +607 -607
  141. package/src/setup/runtime.js +172 -172
  142. package/src/setup.js +677 -677
  143. package/src/shared/capabilities.js +194 -194
  144. package/src/source-urls.js +132 -132
  145. package/src/stack-checks.js +565 -565
  146. package/src/supplemental-checks.js +13 -13
  147. package/src/synergy/adaptive.js +261 -261
  148. package/src/synergy/compensation.js +137 -137
  149. package/src/synergy/evidence.js +193 -193
  150. package/src/synergy/learning.js +199 -199
  151. package/src/synergy/patterns.js +227 -227
  152. package/src/synergy/ranking.js +83 -83
  153. package/src/synergy/report.js +165 -165
  154. package/src/synergy/routing.js +146 -146
  155. package/src/techniques/api.js +407 -407
  156. package/src/techniques/automation.js +316 -316
  157. package/src/techniques/compliance.js +257 -257
  158. package/src/techniques/hygiene.js +294 -294
  159. package/src/techniques/instructions.js +243 -243
  160. package/src/techniques/observability.js +226 -226
  161. package/src/techniques/optimization.js +142 -142
  162. package/src/techniques/quality.js +318 -318
  163. package/src/techniques/security.js +237 -237
  164. package/src/techniques/shared.js +443 -443
  165. package/src/techniques/stacks.js +2294 -2294
  166. package/src/techniques/tools.js +106 -106
  167. package/src/techniques/workflow.js +413 -413
  168. package/src/techniques.js +81 -81
  169. package/src/terminology.js +73 -73
  170. package/src/token-estimate.js +35 -35
  171. package/src/usage-patterns.js +99 -99
  172. package/src/verification-metadata.js +145 -145
  173. package/src/watch.js +247 -247
  174. package/src/windsurf/activity.js +302 -302
  175. package/src/windsurf/config-parser.js +267 -267
  176. package/src/windsurf/context.js +249 -249
  177. package/src/windsurf/deep-review.js +337 -337
  178. package/src/windsurf/domain-packs.js +370 -370
  179. package/src/windsurf/freshness.js +36 -36
  180. package/src/windsurf/governance.js +231 -231
  181. package/src/windsurf/interactive.js +388 -388
  182. package/src/windsurf/mcp-packs.js +792 -792
  183. package/src/windsurf/plans.js +247 -247
  184. package/src/windsurf/premium.js +468 -468
  185. package/src/windsurf/setup.js +471 -471
  186. package/src/windsurf/techniques.js +17 -17
  187. package/src/workspace.js +375 -375
@@ -1,591 +1,591 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const os = require('os');
4
- const { version } = require('../../package.json');
5
- const { STACKS } = require('../techniques');
6
- const { writeActivityArtifact, writeRollbackArtifact } = require('../activity');
7
- const { CodexProjectContext } = require('./context');
8
- const { recommendCodexMcpPacks, packsToToml } = require('./mcp-packs');
9
-
10
- function detectScripts(ctx) {
11
- const pkg = ctx.jsonFile('package.json');
12
- if (!pkg || !pkg.scripts) return {};
13
- return pkg.scripts;
14
- }
15
-
16
- function detectProjectName(ctx) {
17
- const pkg = ctx.jsonFile('package.json');
18
- if (pkg && pkg.name) return pkg.name;
19
- return path.basename(ctx.dir);
20
- }
21
-
22
- function hasStack(stacks, key) {
23
- return stacks.some((item) => item.key === key);
24
- }
25
-
26
- function buildMermaid(stacks) {
27
- if (hasStack(stacks, 'nextjs')) {
28
- return [
29
- '```mermaid',
30
- 'graph TD',
31
- ' UI[App Router / Pages] --> Logic[Server Actions or API Routes]',
32
- ' Logic --> Data[Data Layer]',
33
- ' Data --> External[External Services / DB]',
34
- '```',
35
- ].join('\n');
36
- }
37
-
38
- if (hasStack(stacks, 'fastapi') || hasStack(stacks, 'django') || hasStack(stacks, 'python')) {
39
- return [
40
- '```mermaid',
41
- 'graph TD',
42
- ' API[API / CLI Entry] --> Services[Service Layer]',
43
- ' Services --> Models[Models / Schemas]',
44
- ' Models --> Data[Database or External APIs]',
45
- '```',
46
- ].join('\n');
47
- }
48
-
49
- if (hasStack(stacks, 'go')) {
50
- return [
51
- '```mermaid',
52
- 'graph TD',
53
- ' Cmd[cmd/ or main package] --> Internal[internal/ packages]',
54
- ' Internal --> Data[Storage / APIs]',
55
- '```',
56
- ].join('\n');
57
- }
58
-
59
- if (hasStack(stacks, 'rust')) {
60
- return [
61
- '```mermaid',
62
- 'graph TD',
63
- ' Bin[src/main.rs] --> Core[src/lib.rs]',
64
- ' Core --> Modules[domain / adapters / services]',
65
- '```',
66
- ].join('\n');
67
- }
68
-
69
- return [
70
- '```mermaid',
71
- 'graph TD',
72
- ' Entry[Entry Point] --> Core[Core Logic]',
73
- ' Core --> Data[Data / External Services]',
74
- '```',
75
- ].join('\n');
76
- }
77
-
78
- function buildVerificationCommands(ctx) {
79
- const scripts = detectScripts(ctx);
80
- const commands = [];
81
-
82
- if (scripts.test) commands.push(`- Test: \`npm test\``);
83
- if (scripts.lint) commands.push(`- Lint: \`npm run lint\``);
84
- if (scripts.build) commands.push(`- Build: \`npm run build\``);
85
-
86
- if (commands.length === 0 && ctx.fileContent('pyproject.toml')) {
87
- commands.push('- Test: `python -m pytest`');
88
- }
89
- if (commands.length === 0 && ctx.fileContent('requirements.txt')) {
90
- commands.push('- Test: `python -m pytest`');
91
- }
92
- if (commands.length === 0 && ctx.fileContent('go.mod')) {
93
- commands.push('- Test: `go test ./...`');
94
- commands.push('- Build: `go build ./...`');
95
- }
96
- if (commands.length === 0 && ctx.fileContent('Cargo.toml')) {
97
- commands.push('- Test: `cargo test`');
98
- commands.push('- Build: `cargo build`');
99
- }
100
-
101
- if (commands.length === 0) {
102
- commands.push('- Test: add the repo test command');
103
- commands.push('- Lint: add the repo lint command');
104
- commands.push('- Build: add the repo build command');
105
- }
106
-
107
- return commands;
108
- }
109
-
110
- function buildCodingConventions(stacks) {
111
- const lines = [];
112
-
113
- if (hasStack(stacks, 'typescript')) {
114
- lines.push('- Keep TypeScript strict and prefer typed boundaries over implicit `any`.');
115
- }
116
- if (hasStack(stacks, 'react') || hasStack(stacks, 'nextjs')) {
117
- lines.push('- Prefer small, reviewable component changes and document risky UI state assumptions before refactors.');
118
- }
119
- if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
120
- lines.push('- Prefer explicit validation, typed schemas, and focused service functions over large route handlers.');
121
- }
122
- if (hasStack(stacks, 'go')) {
123
- lines.push('- Keep packages small, avoid cross-package cycles, and prefer table-driven tests.');
124
- }
125
- if (hasStack(stacks, 'rust')) {
126
- lines.push('- Prefer explicit ownership-safe refactors and small module-scoped changes over broad rewrites.');
127
- }
128
- if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
129
- lines.push('- Treat infrastructure changes as high-risk: prefer diffs that are easy to plan, review, and roll back.');
130
- }
131
-
132
- if (lines.length === 0) {
133
- lines.push('- Prefer small, reviewable diffs and explicit reasoning over broad rewrites.');
134
- }
135
-
136
- return lines;
137
- }
138
-
139
- function buildSecurityNotes(stacks) {
140
- const lines = [
141
- '- Never commit secrets, tokens, or `.env` values into tracked files.',
142
- '- Prefer the repo verification commands before handoff, and explain any command you could not run.',
143
- ];
144
-
145
- if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
146
- lines.push('- Validate auth, permissions, and data-handling changes carefully before touching production-sensitive paths.');
147
- }
148
- if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
149
- lines.push('- Review blast radius before changing infra, deployment, or cluster configuration.');
150
- }
151
-
152
- return lines;
153
- }
154
-
155
- function buildAgentsMd(ctx, stacks) {
156
- const stackLabels = stacks.map((item) => item.label).join(', ') || 'General repo';
157
- const verificationCommands = buildVerificationCommands(ctx);
158
- const codingConventions = buildCodingConventions(stacks);
159
- const securityNotes = buildSecurityNotes(stacks);
160
-
161
- return [
162
- `# ${detectProjectName(ctx)}`,
163
- '',
164
- '## Scope',
165
- '- Primary platform: Codex CLI',
166
- `- Detected stack: ${stackLabels}`,
167
- '- Keep this file focused on Codex-specific guidance when the repo also uses Claude or other agents.',
168
- '',
169
- '## Architecture',
170
- buildMermaid(stacks),
171
- '- Replace the default diagram and bullets with the real entry points, boundaries, and high-risk subsystems for this repo.',
172
- '',
173
- '## Verification',
174
- ...verificationCommands,
175
- '',
176
- '## Coding Conventions',
177
- ...codingConventions,
178
- '',
179
- '## Review Workflow',
180
- '- Use `codex review --uncommitted` before handoff on risky diffs or broad refactors.',
181
- '- Explain which verification commands ran successfully and which were skipped.',
182
- '- Keep working-tree expectations explicit: do not silently mix unrelated edits into the same handoff.',
183
- '',
184
- '## Security',
185
- ...securityNotes,
186
- '',
187
- '## Cost & Automation',
188
- '- Reserve heavy reasoning or long automation chains for tasks that actually need them.',
189
- '- Test Codex automation manually or in workflow_dispatch before turning it into a scheduled workflow.',
190
- '',
191
- '## Notes',
192
- '- If this repo also uses Claude, keep Claude-specific instructions in `CLAUDE.md` and use AGENTS.md for Codex-native behavior.',
193
- '- If you add repo-local skills, place them under `.agents/skills/<skill-name>/SKILL.md` and keep names kebab-case.',
194
- '- If you add custom agents, keep them under `.codex/agents/*.toml` with narrow sandbox overrides.',
195
- '',
196
- `_Generated by nerviq v${version} for Codex. Customize this file before relying on it in production flows._`,
197
- '',
198
- ].join('\n');
199
- }
200
-
201
- function buildConfigToml() {
202
- // Updated 2026-04-05: removed stale keys (model_for_weak_tasks, full_auto_error_mode,
203
- // history.send_to_server) that no longer exist in official Codex config schema
204
- return [
205
- 'model = "gpt-5.4"',
206
- 'model_reasoning_effort = "medium"',
207
- 'approval_policy = "on-request"',
208
- 'sandbox_mode = "workspace-write"',
209
- 'project_doc_fallback_filenames = ["AGENTS.md"]',
210
- '',
211
- '[sandbox_workspace_write]',
212
- 'network_access = false',
213
- '',
214
- '[agents]',
215
- 'max_threads = 4',
216
- 'max_depth = 2',
217
- '',
218
- ].join('\n');
219
- }
220
-
221
- function buildCodexSetupFiles(options = {}) {
222
- const ctx = new CodexProjectContext(options.dir);
223
- const stacks = ctx.detectStacks(STACKS);
224
- const files = [];
225
-
226
- const agentsPath = path.join(options.dir, 'AGENTS.md');
227
- if (!fs.existsSync(agentsPath)) {
228
- files.push({
229
- path: 'AGENTS.md',
230
- action: 'create',
231
- content: buildAgentsMd(ctx, stacks),
232
- currentState: 'AGENTS.md is missing',
233
- proposedState: 'create a Codex-native AGENTS.md baseline with verification, architecture, review, and trust guidance',
234
- });
235
- }
236
-
237
- const configPath = path.join(options.dir, '.codex', 'config.toml');
238
- if (!fs.existsSync(configPath)) {
239
- files.push({
240
- path: '.codex/config.toml',
241
- action: 'create',
242
- content: buildConfigToml(),
243
- currentState: '.codex/config.toml is missing',
244
- proposedState: 'create a safe Codex baseline config with explicit approvals, sandbox, history, network, and agents settings',
245
- });
246
- }
247
-
248
- // --- CP-04: Optional setup families ---
249
- const modules = options.modules || 'all';
250
- const wantModule = (name) => modules === 'all' || (Array.isArray(modules) && modules.includes(name));
251
-
252
- // Rules starter
253
- if (wantModule('rules')) {
254
- const rulesDir = path.join(options.dir, '.codex', 'rules');
255
- const rulesReadme = path.join(rulesDir, 'README.md');
256
- if (!fs.existsSync(rulesReadme)) {
257
- files.push({
258
- path: '.codex/rules/README.md',
259
- action: 'create',
260
- family: 'codex-rules',
261
- content: buildRulesStarter(),
262
- currentState: '.codex/rules/ directory is missing or empty',
263
- proposedState: 'create a Codex rules starter with guidance on writing sandbox-escape rules',
264
- });
265
- }
266
- }
267
-
268
- // Hooks scaffold (skip on Windows)
269
- if (wantModule('hooks') && os.platform() !== 'win32') {
270
- const hooksPath = path.join(options.dir, '.codex', 'hooks.json');
271
- if (!fs.existsSync(hooksPath)) {
272
- files.push({
273
- path: '.codex/hooks.json',
274
- action: 'create',
275
- family: 'codex-hooks',
276
- content: buildHooksStarter(),
277
- currentState: '.codex/hooks.json is missing',
278
- proposedState: 'create a Codex hooks scaffold with SessionStart example',
279
- });
280
- }
281
- }
282
-
283
- // Skills starter
284
- if (wantModule('skills')) {
285
- const skillsDir = path.join(options.dir, '.agents', 'skills');
286
- const skillsReadme = path.join(skillsDir, 'README.md');
287
- if (!fs.existsSync(skillsReadme) && !fs.existsSync(skillsDir)) {
288
- files.push({
289
- path: '.agents/skills/README.md',
290
- action: 'create',
291
- family: 'codex-skills',
292
- content: buildSkillsStarter(),
293
- currentState: '.agents/skills/ directory is missing',
294
- proposedState: 'create a Codex skills starter with SKILL.md conventions and kebab-case naming guidance',
295
- });
296
- }
297
- }
298
-
299
- // Subagents starter
300
- if (wantModule('subagents')) {
301
- const agentsDir = path.join(options.dir, '.codex', 'agents');
302
- if (!fs.existsSync(agentsDir)) {
303
- files.push({
304
- path: '.codex/agents/README.md',
305
- action: 'create',
306
- family: 'codex-subagents',
307
- content: buildSubagentsStarter(),
308
- currentState: '.codex/agents/ directory is missing',
309
- proposedState: 'create a Codex custom agents starter with TOML conventions',
310
- });
311
- }
312
- }
313
-
314
- // MCP starter
315
- if (wantModule('mcp')) {
316
- const configContent = ctx.configContent ? ctx.configContent() : '';
317
- const hasMcpSection = configContent && /\[mcp_servers\./i.test(configContent);
318
- if (!hasMcpSection) {
319
- const domainPacks = options.domainPacks || [];
320
- const mcpRecs = recommendCodexMcpPacks(stacks, domainPacks, { ctx });
321
- if (mcpRecs.length > 0) {
322
- const mcpToml = packsToToml(mcpRecs.map(p => p.key));
323
- files.push({
324
- path: '.codex/config.toml (MCP append)',
325
- action: 'append',
326
- family: 'codex-mcp',
327
- content: mcpToml,
328
- currentState: 'No MCP servers configured in .codex/config.toml',
329
- proposedState: `add ${mcpRecs.length} recommended MCP packs: ${mcpRecs.map(p => p.label).join(', ')}`,
330
- });
331
- }
332
- }
333
- }
334
-
335
- // CI / Review workflow starter
336
- if (wantModule('ci')) {
337
- const workflowDir = path.join(options.dir, '.github', 'workflows');
338
- const codexWorkflow = path.join(workflowDir, 'codex-review.yml');
339
- if (!fs.existsSync(codexWorkflow)) {
340
- files.push({
341
- path: '.github/workflows/codex-review.yml',
342
- action: 'create',
343
- family: 'codex-ci-review',
344
- content: buildCiReviewStarter(),
345
- currentState: 'No Codex CI review workflow exists',
346
- proposedState: 'create a GitHub Actions workflow for Codex-based PR review',
347
- });
348
- }
349
- }
350
-
351
- return { ctx, stacks, files };
352
- }
353
-
354
- // --- New starter builders for CP-04 ---
355
-
356
- function buildRulesStarter() {
357
- return [
358
- '# Codex Rules',
359
- '',
360
- 'Place rule files in this directory to control Codex sandbox-escape behavior.',
361
- '',
362
- '## Rule format',
363
- '',
364
- 'Each rule file should be a `.md` file with:',
365
- '- A clear description of what commands the rule allows',
366
- '- `match` examples showing commands that should be allowed',
367
- '- `not_match` examples showing commands that should be blocked',
368
- '',
369
- '## Example rule',
370
- '',
371
- '```markdown',
372
- '# Allow npm commands',
373
- '',
374
- 'Allow npm and npx commands for package management.',
375
- '',
376
- '- match: `npm install`',
377
- '- match: `npx jest`',
378
- '- not_match: `npm publish` (requires manual approval)',
379
- '```',
380
- '',
381
- '## Best practices',
382
- '',
383
- '- Use specific patterns, not wildcards',
384
- '- Document the reason for each allowed command class',
385
- '- Review rules when adding new workflow surfaces',
386
- '',
387
- `_Generated by nerviq v${version}_`,
388
- '',
389
- ].join('\n');
390
- }
391
-
392
- function buildHooksStarter() {
393
- return JSON.stringify({
394
- "$schema": "https://docs.codex.ai/hooks-schema.json",
395
- "hooks": [
396
- {
397
- "event": "SessionStart",
398
- "command": "echo 'Codex session started'",
399
- "description": "Example SessionStart hook — customize or remove",
400
- "timeout_ms": 5000,
401
- }
402
- ]
403
- }, null, 2) + '\n';
404
- }
405
-
406
- function buildSkillsStarter() {
407
- return [
408
- '# Codex Skills',
409
- '',
410
- 'Place skill directories here. Each skill needs a `SKILL.md` file.',
411
- '',
412
- '## Directory structure',
413
- '',
414
- '```',
415
- '.agents/skills/',
416
- ' my-skill/',
417
- ' SKILL.md # Required: name, description, instructions',
418
- ' helpers.js # Optional: supporting files',
419
- '```',
420
- '',
421
- '## SKILL.md format',
422
- '',
423
- '```markdown',
424
- '---',
425
- 'name: my-skill',
426
- 'description: Short description for implicit invocation',
427
- '---',
428
- '',
429
- '# My Skill',
430
- '',
431
- 'Instructions for Codex when this skill is invoked.',
432
- '```',
433
- '',
434
- '## Critical naming rules',
435
- '',
436
- '- Use **kebab-case** for skill directory names (e.g., `code-review`, not `CodeReview`)',
437
- '- PascalCase names have 0% implicit invocation success rate',
438
- '- Keep descriptions short for bounded context cost',
439
- '',
440
- `_Generated by nerviq v${version}_`,
441
- '',
442
- ].join('\n');
443
- }
444
-
445
- function buildSubagentsStarter() {
446
- return [
447
- '# Codex Custom Agents',
448
- '',
449
- 'Place custom agent TOML files here.',
450
- '',
451
- '## Format',
452
- '',
453
- '```toml',
454
- 'name = "my-agent"',
455
- 'description = "What this agent does"',
456
- 'developer_instructions = "Detailed instructions for the agent"',
457
- '',
458
- '[sandbox]',
459
- 'mode = "workspace-write"',
460
- '```',
461
- '',
462
- '## Configuration notes',
463
- '',
464
- '- `max_threads` is hardcoded at 6 (system ceiling)',
465
- '- `max_depth` defaults to 1 — increase only with justification',
466
- '- Per-agent sandbox overrides should be as narrow as possible',
467
- '- Cloud tasks run in a different trust class than local CLI',
468
- '',
469
- `_Generated by nerviq v${version}_`,
470
- '',
471
- ].join('\n');
472
- }
473
-
474
- function buildCiReviewStarter() {
475
- return [
476
- 'name: Codex Review',
477
- '',
478
- 'on:',
479
- ' pull_request:',
480
- ' types: [opened, synchronize]',
481
- '',
482
- 'permissions:',
483
- ' contents: read',
484
- ' pull-requests: write',
485
- '',
486
- 'jobs:',
487
- ' codex-review:',
488
- ' runs-on: ubuntu-latest',
489
- ' steps:',
490
- ' - uses: actions/checkout@v4',
491
- ' - name: Codex Review',
492
- ' uses: openai/codex-action@v1',
493
- ' with:',
494
- ' safety-strategy: review-only',
495
- ' env:',
496
- ' CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}',
497
- ].join('\n') + '\n';
498
- }
499
-
500
- async function setupCodex(options) {
501
- const silent = options.silent === true;
502
- const { ctx, stacks, files } = buildCodexSetupFiles(options);
503
- const writtenFiles = [];
504
- const preservedFiles = [];
505
-
506
- function log(message = '') {
507
- if (!silent) {
508
- console.log(message);
509
- }
510
- }
511
-
512
- log('');
513
- log('\x1b[1m nerviq codex setup\x1b[0m');
514
- log('\x1b[2m ═══════════════════════════════════════\x1b[0m');
515
- if (stacks.length > 0) {
516
- log(`\x1b[36m Detected: ${stacks.map((s) => s.label).join(', ')}\x1b[0m`);
517
- }
518
- log('');
519
-
520
- for (const file of files) {
521
- const fullPath = path.join(options.dir, file.path);
522
- if (fs.existsSync(fullPath)) {
523
- preservedFiles.push(file.path);
524
- log(` \x1b[2m⏭️ Skipped ${file.path} (already exists — your version is kept)\x1b[0m`);
525
- continue;
526
- }
527
-
528
- fs.mkdirSync(path.dirname(fullPath), { recursive: true });
529
- fs.writeFileSync(fullPath, file.content, 'utf8');
530
- writtenFiles.push(file.path);
531
- log(` \x1b[32m✅\x1b[0m Created ${file.path}`);
532
- }
533
-
534
- const skippedSet = new Set(preservedFiles);
535
- if (!skippedSet.has('AGENTS.md') && fs.existsSync(path.join(options.dir, 'AGENTS.md')) && !writtenFiles.includes('AGENTS.md')) {
536
- preservedFiles.push('AGENTS.md');
537
- }
538
- if (!skippedSet.has('.codex/config.toml') && fs.existsSync(path.join(options.dir, '.codex', 'config.toml')) && !writtenFiles.includes('.codex/config.toml')) {
539
- preservedFiles.push('.codex/config.toml');
540
- }
541
-
542
- let rollbackArtifact = null;
543
- let activityArtifact = null;
544
- if (writtenFiles.length > 0) {
545
- rollbackArtifact = writeRollbackArtifact(options.dir, {
546
- sourcePlan: 'codex-setup',
547
- createdFiles: writtenFiles,
548
- patchedFiles: [],
549
- rollbackInstructions: writtenFiles.map((file) => `Delete ${file}`),
550
- });
551
- activityArtifact = writeActivityArtifact(options.dir, 'codex-setup', {
552
- platform: 'codex',
553
- createdFiles: writtenFiles,
554
- preservedFiles,
555
- stackLabels: stacks.map((item) => item.label),
556
- rollbackArtifact: rollbackArtifact.relativePath,
557
- });
558
- }
559
-
560
- log('');
561
- log(` \x1b[1m${writtenFiles.length} files created.\x1b[0m`);
562
- if (preservedFiles.length > 0) {
563
- log(` \x1b[2m${preservedFiles.length} existing files preserved (not overwritten).\x1b[0m`);
564
- }
565
- if (rollbackArtifact) {
566
- log(` Rollback: \x1b[1m${rollbackArtifact.relativePath}\x1b[0m`);
567
- }
568
- if (activityArtifact) {
569
- log(` Activity log: \x1b[1m${activityArtifact.relativePath}\x1b[0m`);
570
- }
571
- log('');
572
- log(' Run \x1b[1mnpx nerviq --platform codex\x1b[0m to audit your Codex setup.');
573
- log('');
574
-
575
- return {
576
- created: writtenFiles.length,
577
- skipped: preservedFiles.length,
578
- writtenFiles,
579
- preservedFiles,
580
- stacks,
581
- rollbackArtifact: rollbackArtifact ? rollbackArtifact.relativePath : null,
582
- activityArtifact: activityArtifact ? activityArtifact.relativePath : null,
583
- };
584
- }
585
-
586
- module.exports = {
587
- buildAgentsMd,
588
- buildConfigToml,
589
- buildCodexSetupFiles,
590
- setupCodex,
591
- };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { version } = require('../../package.json');
5
+ const { STACKS } = require('../techniques');
6
+ const { writeActivityArtifact, writeRollbackArtifact } = require('../activity');
7
+ const { CodexProjectContext } = require('./context');
8
+ const { recommendCodexMcpPacks, packsToToml } = require('./mcp-packs');
9
+
10
+ function detectScripts(ctx) {
11
+ const pkg = ctx.jsonFile('package.json');
12
+ if (!pkg || !pkg.scripts) return {};
13
+ return pkg.scripts;
14
+ }
15
+
16
+ function detectProjectName(ctx) {
17
+ const pkg = ctx.jsonFile('package.json');
18
+ if (pkg && pkg.name) return pkg.name;
19
+ return path.basename(ctx.dir);
20
+ }
21
+
22
+ function hasStack(stacks, key) {
23
+ return stacks.some((item) => item.key === key);
24
+ }
25
+
26
+ function buildMermaid(stacks) {
27
+ if (hasStack(stacks, 'nextjs')) {
28
+ return [
29
+ '```mermaid',
30
+ 'graph TD',
31
+ ' UI[App Router / Pages] --> Logic[Server Actions or API Routes]',
32
+ ' Logic --> Data[Data Layer]',
33
+ ' Data --> External[External Services / DB]',
34
+ '```',
35
+ ].join('\n');
36
+ }
37
+
38
+ if (hasStack(stacks, 'fastapi') || hasStack(stacks, 'django') || hasStack(stacks, 'python')) {
39
+ return [
40
+ '```mermaid',
41
+ 'graph TD',
42
+ ' API[API / CLI Entry] --> Services[Service Layer]',
43
+ ' Services --> Models[Models / Schemas]',
44
+ ' Models --> Data[Database or External APIs]',
45
+ '```',
46
+ ].join('\n');
47
+ }
48
+
49
+ if (hasStack(stacks, 'go')) {
50
+ return [
51
+ '```mermaid',
52
+ 'graph TD',
53
+ ' Cmd[cmd/ or main package] --> Internal[internal/ packages]',
54
+ ' Internal --> Data[Storage / APIs]',
55
+ '```',
56
+ ].join('\n');
57
+ }
58
+
59
+ if (hasStack(stacks, 'rust')) {
60
+ return [
61
+ '```mermaid',
62
+ 'graph TD',
63
+ ' Bin[src/main.rs] --> Core[src/lib.rs]',
64
+ ' Core --> Modules[domain / adapters / services]',
65
+ '```',
66
+ ].join('\n');
67
+ }
68
+
69
+ return [
70
+ '```mermaid',
71
+ 'graph TD',
72
+ ' Entry[Entry Point] --> Core[Core Logic]',
73
+ ' Core --> Data[Data / External Services]',
74
+ '```',
75
+ ].join('\n');
76
+ }
77
+
78
+ function buildVerificationCommands(ctx) {
79
+ const scripts = detectScripts(ctx);
80
+ const commands = [];
81
+
82
+ if (scripts.test) commands.push(`- Test: \`npm test\``);
83
+ if (scripts.lint) commands.push(`- Lint: \`npm run lint\``);
84
+ if (scripts.build) commands.push(`- Build: \`npm run build\``);
85
+
86
+ if (commands.length === 0 && ctx.fileContent('pyproject.toml')) {
87
+ commands.push('- Test: `python -m pytest`');
88
+ }
89
+ if (commands.length === 0 && ctx.fileContent('requirements.txt')) {
90
+ commands.push('- Test: `python -m pytest`');
91
+ }
92
+ if (commands.length === 0 && ctx.fileContent('go.mod')) {
93
+ commands.push('- Test: `go test ./...`');
94
+ commands.push('- Build: `go build ./...`');
95
+ }
96
+ if (commands.length === 0 && ctx.fileContent('Cargo.toml')) {
97
+ commands.push('- Test: `cargo test`');
98
+ commands.push('- Build: `cargo build`');
99
+ }
100
+
101
+ if (commands.length === 0) {
102
+ commands.push('- Test: add the repo test command');
103
+ commands.push('- Lint: add the repo lint command');
104
+ commands.push('- Build: add the repo build command');
105
+ }
106
+
107
+ return commands;
108
+ }
109
+
110
+ function buildCodingConventions(stacks) {
111
+ const lines = [];
112
+
113
+ if (hasStack(stacks, 'typescript')) {
114
+ lines.push('- Keep TypeScript strict and prefer typed boundaries over implicit `any`.');
115
+ }
116
+ if (hasStack(stacks, 'react') || hasStack(stacks, 'nextjs')) {
117
+ lines.push('- Prefer small, reviewable component changes and document risky UI state assumptions before refactors.');
118
+ }
119
+ if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
120
+ lines.push('- Prefer explicit validation, typed schemas, and focused service functions over large route handlers.');
121
+ }
122
+ if (hasStack(stacks, 'go')) {
123
+ lines.push('- Keep packages small, avoid cross-package cycles, and prefer table-driven tests.');
124
+ }
125
+ if (hasStack(stacks, 'rust')) {
126
+ lines.push('- Prefer explicit ownership-safe refactors and small module-scoped changes over broad rewrites.');
127
+ }
128
+ if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
129
+ lines.push('- Treat infrastructure changes as high-risk: prefer diffs that are easy to plan, review, and roll back.');
130
+ }
131
+
132
+ if (lines.length === 0) {
133
+ lines.push('- Prefer small, reviewable diffs and explicit reasoning over broad rewrites.');
134
+ }
135
+
136
+ return lines;
137
+ }
138
+
139
+ function buildSecurityNotes(stacks) {
140
+ const lines = [
141
+ '- Never commit secrets, tokens, or `.env` values into tracked files.',
142
+ '- Prefer the repo verification commands before handoff, and explain any command you could not run.',
143
+ ];
144
+
145
+ if (hasStack(stacks, 'python') || hasStack(stacks, 'fastapi') || hasStack(stacks, 'django')) {
146
+ lines.push('- Validate auth, permissions, and data-handling changes carefully before touching production-sensitive paths.');
147
+ }
148
+ if (hasStack(stacks, 'terraform') || hasStack(stacks, 'kubernetes')) {
149
+ lines.push('- Review blast radius before changing infra, deployment, or cluster configuration.');
150
+ }
151
+
152
+ return lines;
153
+ }
154
+
155
+ function buildAgentsMd(ctx, stacks) {
156
+ const stackLabels = stacks.map((item) => item.label).join(', ') || 'General repo';
157
+ const verificationCommands = buildVerificationCommands(ctx);
158
+ const codingConventions = buildCodingConventions(stacks);
159
+ const securityNotes = buildSecurityNotes(stacks);
160
+
161
+ return [
162
+ `# ${detectProjectName(ctx)}`,
163
+ '',
164
+ '## Scope',
165
+ '- Primary platform: Codex CLI',
166
+ `- Detected stack: ${stackLabels}`,
167
+ '- Keep this file focused on Codex-specific guidance when the repo also uses Claude or other agents.',
168
+ '',
169
+ '## Architecture',
170
+ buildMermaid(stacks),
171
+ '- Replace the default diagram and bullets with the real entry points, boundaries, and high-risk subsystems for this repo.',
172
+ '',
173
+ '## Verification',
174
+ ...verificationCommands,
175
+ '',
176
+ '## Coding Conventions',
177
+ ...codingConventions,
178
+ '',
179
+ '## Review Workflow',
180
+ '- Use `codex review --uncommitted` before handoff on risky diffs or broad refactors.',
181
+ '- Explain which verification commands ran successfully and which were skipped.',
182
+ '- Keep working-tree expectations explicit: do not silently mix unrelated edits into the same handoff.',
183
+ '',
184
+ '## Security',
185
+ ...securityNotes,
186
+ '',
187
+ '## Cost & Automation',
188
+ '- Reserve heavy reasoning or long automation chains for tasks that actually need them.',
189
+ '- Test Codex automation manually or in workflow_dispatch before turning it into a scheduled workflow.',
190
+ '',
191
+ '## Notes',
192
+ '- If this repo also uses Claude, keep Claude-specific instructions in `CLAUDE.md` and use AGENTS.md for Codex-native behavior.',
193
+ '- If you add repo-local skills, place them under `.agents/skills/<skill-name>/SKILL.md` and keep names kebab-case.',
194
+ '- If you add custom agents, keep them under `.codex/agents/*.toml` with narrow sandbox overrides.',
195
+ '',
196
+ `_Generated by nerviq v${version} for Codex. Customize this file before relying on it in production flows._`,
197
+ '',
198
+ ].join('\n');
199
+ }
200
+
201
+ function buildConfigToml() {
202
+ // Updated 2026-04-05: removed stale keys (model_for_weak_tasks, full_auto_error_mode,
203
+ // history.send_to_server) that no longer exist in official Codex config schema
204
+ return [
205
+ 'model = "gpt-5.4"',
206
+ 'model_reasoning_effort = "medium"',
207
+ 'approval_policy = "on-request"',
208
+ 'sandbox_mode = "workspace-write"',
209
+ 'project_doc_fallback_filenames = ["AGENTS.md"]',
210
+ '',
211
+ '[sandbox_workspace_write]',
212
+ 'network_access = false',
213
+ '',
214
+ '[agents]',
215
+ 'max_threads = 4',
216
+ 'max_depth = 2',
217
+ '',
218
+ ].join('\n');
219
+ }
220
+
221
+ function buildCodexSetupFiles(options = {}) {
222
+ const ctx = new CodexProjectContext(options.dir);
223
+ const stacks = ctx.detectStacks(STACKS);
224
+ const files = [];
225
+
226
+ const agentsPath = path.join(options.dir, 'AGENTS.md');
227
+ if (!fs.existsSync(agentsPath)) {
228
+ files.push({
229
+ path: 'AGENTS.md',
230
+ action: 'create',
231
+ content: buildAgentsMd(ctx, stacks),
232
+ currentState: 'AGENTS.md is missing',
233
+ proposedState: 'create a Codex-native AGENTS.md baseline with verification, architecture, review, and trust guidance',
234
+ });
235
+ }
236
+
237
+ const configPath = path.join(options.dir, '.codex', 'config.toml');
238
+ if (!fs.existsSync(configPath)) {
239
+ files.push({
240
+ path: '.codex/config.toml',
241
+ action: 'create',
242
+ content: buildConfigToml(),
243
+ currentState: '.codex/config.toml is missing',
244
+ proposedState: 'create a safe Codex baseline config with explicit approvals, sandbox, history, network, and agents settings',
245
+ });
246
+ }
247
+
248
+ // --- CP-04: Optional setup families ---
249
+ const modules = options.modules || 'all';
250
+ const wantModule = (name) => modules === 'all' || (Array.isArray(modules) && modules.includes(name));
251
+
252
+ // Rules starter
253
+ if (wantModule('rules')) {
254
+ const rulesDir = path.join(options.dir, '.codex', 'rules');
255
+ const rulesReadme = path.join(rulesDir, 'README.md');
256
+ if (!fs.existsSync(rulesReadme)) {
257
+ files.push({
258
+ path: '.codex/rules/README.md',
259
+ action: 'create',
260
+ family: 'codex-rules',
261
+ content: buildRulesStarter(),
262
+ currentState: '.codex/rules/ directory is missing or empty',
263
+ proposedState: 'create a Codex rules starter with guidance on writing sandbox-escape rules',
264
+ });
265
+ }
266
+ }
267
+
268
+ // Hooks scaffold (skip on Windows)
269
+ if (wantModule('hooks') && os.platform() !== 'win32') {
270
+ const hooksPath = path.join(options.dir, '.codex', 'hooks.json');
271
+ if (!fs.existsSync(hooksPath)) {
272
+ files.push({
273
+ path: '.codex/hooks.json',
274
+ action: 'create',
275
+ family: 'codex-hooks',
276
+ content: buildHooksStarter(),
277
+ currentState: '.codex/hooks.json is missing',
278
+ proposedState: 'create a Codex hooks scaffold with SessionStart example',
279
+ });
280
+ }
281
+ }
282
+
283
+ // Skills starter
284
+ if (wantModule('skills')) {
285
+ const skillsDir = path.join(options.dir, '.agents', 'skills');
286
+ const skillsReadme = path.join(skillsDir, 'README.md');
287
+ if (!fs.existsSync(skillsReadme) && !fs.existsSync(skillsDir)) {
288
+ files.push({
289
+ path: '.agents/skills/README.md',
290
+ action: 'create',
291
+ family: 'codex-skills',
292
+ content: buildSkillsStarter(),
293
+ currentState: '.agents/skills/ directory is missing',
294
+ proposedState: 'create a Codex skills starter with SKILL.md conventions and kebab-case naming guidance',
295
+ });
296
+ }
297
+ }
298
+
299
+ // Subagents starter
300
+ if (wantModule('subagents')) {
301
+ const agentsDir = path.join(options.dir, '.codex', 'agents');
302
+ if (!fs.existsSync(agentsDir)) {
303
+ files.push({
304
+ path: '.codex/agents/README.md',
305
+ action: 'create',
306
+ family: 'codex-subagents',
307
+ content: buildSubagentsStarter(),
308
+ currentState: '.codex/agents/ directory is missing',
309
+ proposedState: 'create a Codex custom agents starter with TOML conventions',
310
+ });
311
+ }
312
+ }
313
+
314
+ // MCP starter
315
+ if (wantModule('mcp')) {
316
+ const configContent = ctx.configContent ? ctx.configContent() : '';
317
+ const hasMcpSection = configContent && /\[mcp_servers\./i.test(configContent);
318
+ if (!hasMcpSection) {
319
+ const domainPacks = options.domainPacks || [];
320
+ const mcpRecs = recommendCodexMcpPacks(stacks, domainPacks, { ctx });
321
+ if (mcpRecs.length > 0) {
322
+ const mcpToml = packsToToml(mcpRecs.map(p => p.key));
323
+ files.push({
324
+ path: '.codex/config.toml (MCP append)',
325
+ action: 'append',
326
+ family: 'codex-mcp',
327
+ content: mcpToml,
328
+ currentState: 'No MCP servers configured in .codex/config.toml',
329
+ proposedState: `add ${mcpRecs.length} recommended MCP packs: ${mcpRecs.map(p => p.label).join(', ')}`,
330
+ });
331
+ }
332
+ }
333
+ }
334
+
335
+ // CI / Review workflow starter
336
+ if (wantModule('ci')) {
337
+ const workflowDir = path.join(options.dir, '.github', 'workflows');
338
+ const codexWorkflow = path.join(workflowDir, 'codex-review.yml');
339
+ if (!fs.existsSync(codexWorkflow)) {
340
+ files.push({
341
+ path: '.github/workflows/codex-review.yml',
342
+ action: 'create',
343
+ family: 'codex-ci-review',
344
+ content: buildCiReviewStarter(),
345
+ currentState: 'No Codex CI review workflow exists',
346
+ proposedState: 'create a GitHub Actions workflow for Codex-based PR review',
347
+ });
348
+ }
349
+ }
350
+
351
+ return { ctx, stacks, files };
352
+ }
353
+
354
+ // --- New starter builders for CP-04 ---
355
+
356
+ function buildRulesStarter() {
357
+ return [
358
+ '# Codex Rules',
359
+ '',
360
+ 'Place rule files in this directory to control Codex sandbox-escape behavior.',
361
+ '',
362
+ '## Rule format',
363
+ '',
364
+ 'Each rule file should be a `.md` file with:',
365
+ '- A clear description of what commands the rule allows',
366
+ '- `match` examples showing commands that should be allowed',
367
+ '- `not_match` examples showing commands that should be blocked',
368
+ '',
369
+ '## Example rule',
370
+ '',
371
+ '```markdown',
372
+ '# Allow npm commands',
373
+ '',
374
+ 'Allow npm and npx commands for package management.',
375
+ '',
376
+ '- match: `npm install`',
377
+ '- match: `npx jest`',
378
+ '- not_match: `npm publish` (requires manual approval)',
379
+ '```',
380
+ '',
381
+ '## Best practices',
382
+ '',
383
+ '- Use specific patterns, not wildcards',
384
+ '- Document the reason for each allowed command class',
385
+ '- Review rules when adding new workflow surfaces',
386
+ '',
387
+ `_Generated by nerviq v${version}_`,
388
+ '',
389
+ ].join('\n');
390
+ }
391
+
392
+ function buildHooksStarter() {
393
+ return JSON.stringify({
394
+ "$schema": "https://docs.codex.ai/hooks-schema.json",
395
+ "hooks": [
396
+ {
397
+ "event": "SessionStart",
398
+ "command": "echo 'Codex session started'",
399
+ "description": "Example SessionStart hook — customize or remove",
400
+ "timeout_ms": 5000,
401
+ }
402
+ ]
403
+ }, null, 2) + '\n';
404
+ }
405
+
406
+ function buildSkillsStarter() {
407
+ return [
408
+ '# Codex Skills',
409
+ '',
410
+ 'Place skill directories here. Each skill needs a `SKILL.md` file.',
411
+ '',
412
+ '## Directory structure',
413
+ '',
414
+ '```',
415
+ '.agents/skills/',
416
+ ' my-skill/',
417
+ ' SKILL.md # Required: name, description, instructions',
418
+ ' helpers.js # Optional: supporting files',
419
+ '```',
420
+ '',
421
+ '## SKILL.md format',
422
+ '',
423
+ '```markdown',
424
+ '---',
425
+ 'name: my-skill',
426
+ 'description: Short description for implicit invocation',
427
+ '---',
428
+ '',
429
+ '# My Skill',
430
+ '',
431
+ 'Instructions for Codex when this skill is invoked.',
432
+ '```',
433
+ '',
434
+ '## Critical naming rules',
435
+ '',
436
+ '- Use **kebab-case** for skill directory names (e.g., `code-review`, not `CodeReview`)',
437
+ '- PascalCase names have 0% implicit invocation success rate',
438
+ '- Keep descriptions short for bounded context cost',
439
+ '',
440
+ `_Generated by nerviq v${version}_`,
441
+ '',
442
+ ].join('\n');
443
+ }
444
+
445
+ function buildSubagentsStarter() {
446
+ return [
447
+ '# Codex Custom Agents',
448
+ '',
449
+ 'Place custom agent TOML files here.',
450
+ '',
451
+ '## Format',
452
+ '',
453
+ '```toml',
454
+ 'name = "my-agent"',
455
+ 'description = "What this agent does"',
456
+ 'developer_instructions = "Detailed instructions for the agent"',
457
+ '',
458
+ '[sandbox]',
459
+ 'mode = "workspace-write"',
460
+ '```',
461
+ '',
462
+ '## Configuration notes',
463
+ '',
464
+ '- `max_threads` is hardcoded at 6 (system ceiling)',
465
+ '- `max_depth` defaults to 1 — increase only with justification',
466
+ '- Per-agent sandbox overrides should be as narrow as possible',
467
+ '- Cloud tasks run in a different trust class than local CLI',
468
+ '',
469
+ `_Generated by nerviq v${version}_`,
470
+ '',
471
+ ].join('\n');
472
+ }
473
+
474
+ function buildCiReviewStarter() {
475
+ return [
476
+ 'name: Codex Review',
477
+ '',
478
+ 'on:',
479
+ ' pull_request:',
480
+ ' types: [opened, synchronize]',
481
+ '',
482
+ 'permissions:',
483
+ ' contents: read',
484
+ ' pull-requests: write',
485
+ '',
486
+ 'jobs:',
487
+ ' codex-review:',
488
+ ' runs-on: ubuntu-latest',
489
+ ' steps:',
490
+ ' - uses: actions/checkout@v4',
491
+ ' - name: Codex Review',
492
+ ' uses: openai/codex-action@v1',
493
+ ' with:',
494
+ ' safety-strategy: review-only',
495
+ ' env:',
496
+ ' CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}',
497
+ ].join('\n') + '\n';
498
+ }
499
+
500
+ async function setupCodex(options) {
501
+ const silent = options.silent === true;
502
+ const { ctx, stacks, files } = buildCodexSetupFiles(options);
503
+ const writtenFiles = [];
504
+ const preservedFiles = [];
505
+
506
+ function log(message = '') {
507
+ if (!silent) {
508
+ console.log(message);
509
+ }
510
+ }
511
+
512
+ log('');
513
+ log('\x1b[1m nerviq codex setup\x1b[0m');
514
+ log('\x1b[2m ═══════════════════════════════════════\x1b[0m');
515
+ if (stacks.length > 0) {
516
+ log(`\x1b[36m Detected: ${stacks.map((s) => s.label).join(', ')}\x1b[0m`);
517
+ }
518
+ log('');
519
+
520
+ for (const file of files) {
521
+ const fullPath = path.join(options.dir, file.path);
522
+ if (fs.existsSync(fullPath)) {
523
+ preservedFiles.push(file.path);
524
+ log(` \x1b[2m⏭️ Skipped ${file.path} (already exists — your version is kept)\x1b[0m`);
525
+ continue;
526
+ }
527
+
528
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
529
+ fs.writeFileSync(fullPath, file.content, 'utf8');
530
+ writtenFiles.push(file.path);
531
+ log(` \x1b[32m✅\x1b[0m Created ${file.path}`);
532
+ }
533
+
534
+ const skippedSet = new Set(preservedFiles);
535
+ if (!skippedSet.has('AGENTS.md') && fs.existsSync(path.join(options.dir, 'AGENTS.md')) && !writtenFiles.includes('AGENTS.md')) {
536
+ preservedFiles.push('AGENTS.md');
537
+ }
538
+ if (!skippedSet.has('.codex/config.toml') && fs.existsSync(path.join(options.dir, '.codex', 'config.toml')) && !writtenFiles.includes('.codex/config.toml')) {
539
+ preservedFiles.push('.codex/config.toml');
540
+ }
541
+
542
+ let rollbackArtifact = null;
543
+ let activityArtifact = null;
544
+ if (writtenFiles.length > 0) {
545
+ rollbackArtifact = writeRollbackArtifact(options.dir, {
546
+ sourcePlan: 'codex-setup',
547
+ createdFiles: writtenFiles,
548
+ patchedFiles: [],
549
+ rollbackInstructions: writtenFiles.map((file) => `Delete ${file}`),
550
+ });
551
+ activityArtifact = writeActivityArtifact(options.dir, 'codex-setup', {
552
+ platform: 'codex',
553
+ createdFiles: writtenFiles,
554
+ preservedFiles,
555
+ stackLabels: stacks.map((item) => item.label),
556
+ rollbackArtifact: rollbackArtifact.relativePath,
557
+ });
558
+ }
559
+
560
+ log('');
561
+ log(` \x1b[1m${writtenFiles.length} files created.\x1b[0m`);
562
+ if (preservedFiles.length > 0) {
563
+ log(` \x1b[2m${preservedFiles.length} existing files preserved (not overwritten).\x1b[0m`);
564
+ }
565
+ if (rollbackArtifact) {
566
+ log(` Rollback: \x1b[1m${rollbackArtifact.relativePath}\x1b[0m`);
567
+ }
568
+ if (activityArtifact) {
569
+ log(` Activity log: \x1b[1m${activityArtifact.relativePath}\x1b[0m`);
570
+ }
571
+ log('');
572
+ log(' Run \x1b[1mnpx nerviq --platform codex\x1b[0m to audit your Codex setup.');
573
+ log('');
574
+
575
+ return {
576
+ created: writtenFiles.length,
577
+ skipped: preservedFiles.length,
578
+ writtenFiles,
579
+ preservedFiles,
580
+ stacks,
581
+ rollbackArtifact: rollbackArtifact ? rollbackArtifact.relativePath : null,
582
+ activityArtifact: activityArtifact ? activityArtifact.relativePath : null,
583
+ };
584
+ }
585
+
586
+ module.exports = {
587
+ buildAgentsMd,
588
+ buildConfigToml,
589
+ buildCodexSetupFiles,
590
+ setupCodex,
591
+ };