@nerviq/cli 1.20.0 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +23 -23
  2. package/README.md +2 -2
  3. package/bin/cli.js +1 -0
  4. package/package.json +2 -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 +6 -2
  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 +312 -67
  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 +10 -4
  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/deep-review.js +559 -559
  81. package/src/gemini/domain-packs.js +393 -393
  82. package/src/gemini/freshness.js +66 -66
  83. package/src/gemini/governance.js +201 -201
  84. package/src/gemini/interactive.js +860 -860
  85. package/src/gemini/mcp-packs.js +915 -915
  86. package/src/gemini/plans.js +269 -269
  87. package/src/gemini/premium.js +760 -760
  88. package/src/gemini/setup.js +692 -692
  89. package/src/governance.js +72 -72
  90. package/src/harmony/add.js +68 -68
  91. package/src/harmony/advisor.js +333 -333
  92. package/src/harmony/canon.js +565 -565
  93. package/src/harmony/cli.js +591 -591
  94. package/src/harmony/drift.js +401 -401
  95. package/src/harmony/governance.js +313 -313
  96. package/src/harmony/memory.js +239 -239
  97. package/src/harmony/sync.js +475 -475
  98. package/src/harmony/watch.js +370 -370
  99. package/src/hook-validation.js +342 -342
  100. package/src/index.js +271 -271
  101. package/src/init.js +184 -184
  102. package/src/instruction-surfaces.js +185 -185
  103. package/src/integrations.js +144 -144
  104. package/src/interactive.js +118 -118
  105. package/src/locales/en.json +1 -1
  106. package/src/locales/es.json +1 -1
  107. package/src/mcp-packs.js +830 -830
  108. package/src/mcp-server.js +726 -726
  109. package/src/mcp-validation.js +337 -337
  110. package/src/nerviq-sync.json +7 -7
  111. package/src/opencode/config-parser.js +109 -109
  112. package/src/opencode/context.js +247 -247
  113. package/src/opencode/deep-review.js +313 -313
  114. package/src/opencode/domain-packs.js +262 -262
  115. package/src/opencode/freshness.js +66 -66
  116. package/src/opencode/governance.js +159 -159
  117. package/src/opencode/interactive.js +392 -392
  118. package/src/opencode/mcp-packs.js +705 -705
  119. package/src/opencode/patch.js +184 -184
  120. package/src/opencode/plans.js +231 -231
  121. package/src/opencode/premium.js +413 -413
  122. package/src/opencode/setup.js +449 -449
  123. package/src/opencode/techniques.js +27 -27
  124. package/src/operating-profile.js +574 -574
  125. package/src/org.js +152 -152
  126. package/src/permission-rules.js +218 -218
  127. package/src/plans.js +839 -839
  128. package/src/platform-change-manifest.js +86 -86
  129. package/src/plugins.js +110 -110
  130. package/src/policy-layers.js +210 -210
  131. package/src/profiles.js +124 -124
  132. package/src/prompt-injection.js +74 -74
  133. package/src/public-api.js +173 -173
  134. package/src/recommendation-rules.js +84 -84
  135. package/src/repo-archetype.js +386 -386
  136. package/src/secret-patterns.js +39 -39
  137. package/src/server.js +527 -527
  138. package/src/setup/analysis.js +607 -607
  139. package/src/setup/runtime.js +172 -172
  140. package/src/setup.js +677 -677
  141. package/src/shared/capabilities.js +194 -194
  142. package/src/source-urls.js +132 -132
  143. package/src/stack-checks.js +565 -565
  144. package/src/supplemental-checks.js +13 -13
  145. package/src/synergy/adaptive.js +261 -261
  146. package/src/synergy/compensation.js +137 -137
  147. package/src/synergy/evidence.js +193 -193
  148. package/src/synergy/learning.js +199 -199
  149. package/src/synergy/patterns.js +227 -227
  150. package/src/synergy/ranking.js +83 -83
  151. package/src/synergy/report.js +165 -165
  152. package/src/synergy/routing.js +146 -146
  153. package/src/techniques/api.js +407 -407
  154. package/src/techniques/automation.js +316 -316
  155. package/src/techniques/compliance.js +257 -257
  156. package/src/techniques/hygiene.js +294 -294
  157. package/src/techniques/instructions.js +243 -243
  158. package/src/techniques/observability.js +226 -226
  159. package/src/techniques/optimization.js +142 -142
  160. package/src/techniques/quality.js +318 -318
  161. package/src/techniques/security.js +237 -237
  162. package/src/techniques/shared.js +443 -443
  163. package/src/techniques/stacks.js +2294 -2294
  164. package/src/techniques/tools.js +106 -106
  165. package/src/techniques/workflow.js +413 -413
  166. package/src/techniques.js +81 -81
  167. package/src/terminology.js +73 -73
  168. package/src/token-estimate.js +35 -35
  169. package/src/usage-patterns.js +99 -99
  170. package/src/verification-metadata.js +145 -145
  171. package/src/watch.js +247 -247
  172. package/src/windsurf/activity.js +302 -302
  173. package/src/windsurf/config-parser.js +267 -267
  174. package/src/windsurf/context.js +120 -10
  175. package/src/windsurf/deep-review.js +337 -337
  176. package/src/windsurf/domain-packs.js +370 -370
  177. package/src/windsurf/freshness.js +36 -36
  178. package/src/windsurf/governance.js +231 -231
  179. package/src/windsurf/interactive.js +388 -388
  180. package/src/windsurf/mcp-packs.js +792 -792
  181. package/src/windsurf/plans.js +247 -247
  182. package/src/windsurf/premium.js +468 -468
  183. package/src/windsurf/setup.js +471 -471
  184. package/src/windsurf/techniques.js +155 -33
  185. package/src/workspace.js +375 -375
package/src/analyze.js CHANGED
@@ -1,951 +1,951 @@
1
- /**
2
- * Project scanner + recommendation layer for augment and suggest-only modes.
3
- * Produces a structured repo-aware analysis without writing files.
4
- */
5
-
6
- const path = require('path');
7
- const { audit } = require('./audit');
8
- const { ProjectContext } = require('./context');
9
- const { CodexProjectContext } = require('./codex/context');
10
- const { STACKS } = require('./techniques');
11
- const { detectDomainPacks } = require('./domain-packs');
12
- const { detectCodexDomainPacks } = require('./codex/domain-packs');
13
- const { recommendMcpPacks } = require('./mcp-packs');
14
- const { collectClaudeDenyRules } = require('./permission-rules');
15
- const { buildRepoArchetypeProfile } = require('./repo-archetype');
16
- const { buildOperatingProfile } = require('./operating-profile');
17
- const { buildAdoptionAdvisor } = require('./adoption-advisor');
18
-
19
- const COLORS = {
20
- reset: '\x1b[0m',
21
- bold: '\x1b[1m',
22
- dim: '\x1b[2m',
23
- red: '\x1b[31m',
24
- green: '\x1b[32m',
25
- yellow: '\x1b[33m',
26
- blue: '\x1b[36m',
27
- magenta: '\x1b[35m',
28
- };
29
-
30
- function c(text, color) {
31
- return `${COLORS[color] || ''}${text}${COLORS.reset}`;
32
- }
33
-
34
- function escapeRegex(value) {
35
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
- }
37
-
38
- function extractTomlSection(content, sectionName) {
39
- const pattern = new RegExp(`\\[${escapeRegex(sectionName)}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`);
40
- const match = content.match(pattern);
41
- return match ? match[1] : null;
42
- }
43
-
44
- function extractTomlValue(sectionContent, key) {
45
- if (!sectionContent) return null;
46
- const pattern = new RegExp(`^\\s*${escapeRegex(key)}\\s*=\\s*["']([^"']+)["']`, 'm');
47
- const match = sectionContent.match(pattern);
48
- return match ? match[1].trim() : null;
49
- }
50
-
51
- function detectProjectMetadata(ctx) {
52
- const pkg = ctx.jsonFile('package.json');
53
- if (pkg && (pkg.name || pkg.description)) {
54
- return {
55
- name: pkg.name || path.basename(ctx.dir),
56
- description: pkg.description || '',
57
- };
58
- }
59
-
60
- const pyproject = ctx.fileContent('pyproject.toml') || '';
61
- if (pyproject) {
62
- const projectSection = extractTomlSection(pyproject, 'project');
63
- const poetrySection = extractTomlSection(pyproject, 'tool.poetry');
64
- const name = extractTomlValue(projectSection, 'name') ||
65
- extractTomlValue(poetrySection, 'name');
66
- const description = extractTomlValue(projectSection, 'description') ||
67
- extractTomlValue(poetrySection, 'description');
68
-
69
- if (name || description) {
70
- return {
71
- name: name || path.basename(ctx.dir),
72
- description: description || '',
73
- };
74
- }
75
- }
76
-
77
- return {
78
- name: path.basename(ctx.dir),
79
- description: '',
80
- };
81
- }
82
-
83
- function detectMainDirs(ctx) {
84
- const candidates = [
85
- 'src', 'lib', 'app', 'pages', 'components', 'api', 'routes', 'utils', 'helpers',
86
- 'services', 'models', 'controllers', 'views', 'public', 'assets', 'config', 'tests',
87
- 'test', '__tests__', 'spec', 'scripts', 'prisma', 'db', 'middleware', 'hooks',
88
- 'agents', 'chains', 'workers', 'jobs', 'dags', 'macros', 'migrations',
89
- 'src/components', 'src/app', 'src/pages', 'src/api', 'src/lib', 'src/hooks',
90
- 'src/utils', 'src/services', 'src/models', 'src/middleware', 'src/agents',
91
- 'src/chains', 'src/workers', 'src/jobs', 'src/app/api', 'app/api',
92
- 'models/staging', 'models/marts'
93
- ];
94
-
95
- const dirs = [];
96
- for (const dir of candidates) {
97
- if (ctx.hasDir(dir)) {
98
- dirs.push(dir);
99
- }
100
- }
101
- return dirs;
102
- }
103
-
104
- function collectClaudeAssets(ctx) {
105
- const sharedSettings = ctx.jsonFile('.claude/settings.json');
106
- const localSettings = ctx.jsonFile('.claude/settings.local.json');
107
- const settings = sharedSettings || localSettings || null;
108
- const denyRules = collectClaudeDenyRules(ctx);
109
-
110
- const assetFiles = {
111
- claudeMd: ctx.fileContent('CLAUDE.md') ? 'CLAUDE.md' : (ctx.fileContent('.claude/CLAUDE.md') ? '.claude/CLAUDE.md' : null),
112
- settings: sharedSettings ? '.claude/settings.json' : (localSettings ? '.claude/settings.local.json' : null),
113
- commands: ctx.hasDir('.claude/commands') ? ctx.dirFiles('.claude/commands') : [],
114
- rules: ctx.hasDir('.claude/rules') ? ctx.dirFiles('.claude/rules') : [],
115
- hooks: ctx.hasDir('.claude/hooks') ? ctx.dirFiles('.claude/hooks') : [],
116
- agents: ctx.hasDir('.claude/agents') ? ctx.dirFiles('.claude/agents') : [],
117
- skills: ctx.hasDir('.claude/skills') ? ctx.dirFiles('.claude/skills') : [],
118
- };
119
-
120
- return {
121
- label: 'Claude',
122
- instructionLabel: 'CLAUDE.md',
123
- configLabel: 'Settings',
124
- instructionPath: assetFiles.claudeMd,
125
- configPath: assetFiles.settings,
126
- files: assetFiles,
127
- counts: {
128
- commands: assetFiles.commands.length,
129
- rules: assetFiles.rules.length,
130
- hooks: assetFiles.hooks.length,
131
- agents: assetFiles.agents.length,
132
- skills: assetFiles.skills.length,
133
- mcpServers: settings && settings.mcpServers ? Object.keys(settings.mcpServers).length : 0,
134
- },
135
- permissions: settings && settings.permissions ? {
136
- defaultMode: settings.permissions.defaultMode || null,
137
- hasDenyRules: denyRules.length > 0,
138
- } : null,
139
- settingsSource: assetFiles.settings,
140
- summaryLine: `Commands: ${assetFiles.commands.length} | Rules: ${assetFiles.rules.length} | Hooks: ${assetFiles.hooks.length} | Agents: ${assetFiles.agents.length} | Skills: ${assetFiles.skills.length} | MCP servers: ${settings && settings.mcpServers ? Object.keys(settings.mcpServers).length : 0}`,
141
- };
142
- }
143
-
144
- function collectCodexAssets(ctx) {
145
- const agentsMd = ctx.agentsMdPath ? ctx.agentsMdPath() : null;
146
- const configPath = ctx.fileContent('.codex/config.toml') ? '.codex/config.toml' : null;
147
- const hooksJson = ctx.hooksJsonContent ? ctx.hooksJsonContent() : null;
148
- const rules = ctx.ruleFiles ? ctx.ruleFiles() : [];
149
- const skills = ctx.skillDirs ? ctx.skillDirs().map((name) => `.agents/skills/${name}`) : [];
150
- const agents = ctx.customAgentFiles ? ctx.customAgentFiles().map((file) => `.codex/agents/${file}`) : [];
151
- const workflows = ctx.workflowFiles ? ctx.workflowFiles() : [];
152
- const mcpServers = ctx.mcpServers ? Object.keys(ctx.mcpServers() || {}).length : 0;
153
-
154
- return {
155
- label: 'Codex',
156
- instructionLabel: 'AGENTS.md',
157
- configLabel: 'Config',
158
- instructionPath: agentsMd,
159
- configPath,
160
- files: {
161
- agentsMd,
162
- config: configPath,
163
- rules,
164
- hooks: hooksJson ? ['.codex/hooks.json'] : [],
165
- skills,
166
- agents,
167
- workflows,
168
- },
169
- counts: {
170
- rules: rules.length,
171
- hooks: hooksJson ? 1 : 0,
172
- skills: skills.length,
173
- agents: agents.length,
174
- workflows: workflows.length,
175
- mcpServers,
176
- },
177
- trust: {
178
- approvalPolicy: ctx.configValue ? (ctx.configValue('approval_policy') || null) : null,
179
- sandboxMode: ctx.configValue ? (ctx.configValue('sandbox_mode') || null) : null,
180
- isTrustedProject: ctx.isProjectTrusted ? ctx.isProjectTrusted() : false,
181
- },
182
- summaryLine: `Rules: ${rules.length} | Hooks: ${hooksJson ? 1 : 0} | Skills: ${skills.length} | Subagents: ${agents.length} | Workflows: ${workflows.length} | MCP servers: ${mcpServers}`,
183
- };
184
- }
185
-
186
- function detectMaturity(platform, assets) {
187
- if (platform === 'codex') {
188
- let score = 0;
189
- if (assets.instructionPath) score += 2;
190
- if (assets.configPath) score += 2;
191
- if (assets.counts.rules > 0) score += 1;
192
- if (assets.counts.hooks > 0) score += 1;
193
- if (assets.counts.skills > 0) score += 1;
194
- if (assets.counts.agents > 0) score += 1;
195
- if (assets.counts.workflows > 0) score += 1;
196
- if (assets.counts.mcpServers > 0) score += 1;
197
-
198
- if (score === 0) return 'none';
199
- if (score <= 2) return 'starter';
200
- if (score <= 5) return 'developing';
201
- return 'mature';
202
- }
203
-
204
- let score = 0;
205
- if (assets.files.claudeMd) score += 2;
206
- if (assets.files.settings) score += 1;
207
- if (assets.counts.rules > 0) score += 1;
208
- if (assets.counts.commands > 0) score += 1;
209
- if (assets.counts.hooks > 0) score += 1;
210
- if (assets.counts.agents > 0) score += 1;
211
- if (assets.counts.skills > 0) score += 1;
212
-
213
- if (score === 0) return 'none';
214
- if (score <= 2) return 'starter';
215
- if (score <= 5) return 'developing';
216
- return 'mature';
217
- }
218
-
219
- function riskFromImpact(impact) {
220
- if (impact === 'critical') return 'high';
221
- if (impact === 'high') return 'medium';
222
- return 'low';
223
- }
224
-
225
- function moduleFromCategory(category) {
226
- const map = {
227
- memory: 'CLAUDE.md',
228
- instructions: 'AGENTS.md / instructions',
229
- config: 'config.toml',
230
- trust: 'trust-and-safety',
231
- rules: 'rules',
232
- hooks: 'hooks',
233
- mcp: 'mcp',
234
- skills: 'skills',
235
- agents: 'subagents',
236
- review: 'review',
237
- automation: 'automation',
238
- local: 'local-environments',
239
- quality: 'verification',
240
- git: 'safety',
241
- workflow: 'commands-agents-skills',
242
- security: 'permissions',
243
- automation: 'hooks',
244
- design: 'design-rules',
245
- devops: 'ci-devops',
246
- hygiene: 'project-hygiene',
247
- performance: 'context-management',
248
- tools: 'mcp-tools',
249
- prompting: 'prompt-structure',
250
- features: 'modern-claude-features',
251
- 'quality-deep': 'quality-deep',
252
- };
253
- return map[category] || category;
254
- }
255
-
256
- const STRENGTH_REASONS = {
257
- claudeMd: 'Foundation of Claude workflow. Every session benefits from this.',
258
- mermaidArchitecture: 'Architecture diagram saves 73% tokens vs prose — high-value asset.',
259
- verificationLoop: 'Claude can self-verify, catching errors before human review.',
260
- hooks: 'Automated enforcement (100% vs 80% from instructions alone).',
261
- hooksInSettings: 'Hook registration in settings ensures consistent automation.',
262
- preToolUseHook: 'Pre-execution validation adds a safety layer.',
263
- postToolUseHook: 'Post-execution automation catches issues immediately.',
264
- sessionStartHook: 'Session initialization ensures consistent starting state.',
265
- customCommands: 'Reusable workflows encoded as one-liner commands.',
266
- settingsPermissions: 'Explicit permissions prevent accidental dangerous operations.',
267
- permissionDeny: 'Deny rules block risky operations at the system level.',
268
- pathRules: 'Scoped rules ensure different code areas get appropriate guidance.',
269
- fewShotExamples: 'Code examples guide Claude to match your conventions.',
270
- constraintBlocks: 'XML constraint blocks improve rule adherence by 40%.',
271
- xmlTags: 'Structured prompt sections improve consistency.',
272
- context7Mcp: 'Real-time docs eliminate version-mismatch hallucinations.',
273
- mcpServers: 'External tool integration extends Claude capabilities.',
274
- compactionAwareness: 'Context management keeps sessions efficient.',
275
- agents: 'Specialized agents delegate complex tasks effectively.',
276
- noSecretsInClaude: 'No secrets in config — good security hygiene.',
277
- gitIgnoreEnv: 'Environment files are properly excluded from git.',
278
- codexAgentsMd: 'Codex has a repo-native instruction surface instead of starting cold.',
279
- codexAgentsMdSubstantive: 'A substantive AGENTS.md reduces drift and gives Codex a stable repo contract.',
280
- codexAgentsVerificationCommands: 'Codex can verify its changes because the repo states how to test and build.',
281
- codexAgentsArchitecture: 'Codex has a repo map to orient itself before editing.',
282
- codexConfigExists: 'Codex runtime posture is reviewable because the project config is versioned.',
283
- codexModelExplicit: 'The primary Codex model is explicit instead of silently inheriting defaults.',
284
- codexReasoningEffortExplicit: 'Reasoning depth is explicit and reviewable.',
285
- codexWeakTaskModelExplicit: 'Delegation for weaker tasks is explicit and cost-aware.',
286
- codexApprovalPolicyExplicit: 'Approval behavior is explicit, predictable, and reviewable.',
287
- codexSandboxExplicit: 'Sandbox posture is explicit instead of accidental.',
288
- codexHistorySendToServerExplicit: 'History sync posture is reviewable in version control.',
289
- codexRulesForRiskyCommands: 'Risky command classes are governed by Codex-native rules.',
290
- codexHooksFeatureExplicit: 'Hook posture is explicit instead of implied.',
291
- codexMcpExternalToolsConfigured: 'Codex has live MCP context instead of relying only on static repo files.',
292
- codexSkillsDirPresentWhenUsed: 'Repo-local skills keep specialization versioned and reviewable.',
293
- codexSkillsHaveMetadata: 'Skill metadata is explicit enough for reliable invocation.',
294
- codexCustomAgentsRequiredFields: 'Custom subagents are structured and reviewable.',
295
- codexExecUsageSafe: 'Codex automation posture is documented and safer to operate.',
296
- codexGitHubActionSafeStrategy: 'CI posture is explicit and safer for Codex in automation.',
297
- codexReviewWorkflowDocumented: 'A documented review path makes risky Codex changes easier to control.',
298
- codexArtifactsSharedIntentionally: 'Codex repo artifacts are shared intentionally instead of being hidden from the team.',
299
- codexAgentsMentionModernFeatures: 'AGENTS.md acknowledges the modern Codex surfaces the repo actually uses.',
300
- };
301
-
302
- function toStrengths(results) {
303
- return results
304
- .filter(r => r.passed === true && (r.impact === 'critical' || r.impact === 'high' || r.impact === 'medium'))
305
- .sort((a, b) => {
306
- const order = { critical: 3, high: 2, medium: 1, low: 0 };
307
- return (order[b.impact] || 0) - (order[a.impact] || 0);
308
- })
309
- .slice(0, 10)
310
- .map(r => ({
311
- key: r.key,
312
- name: r.name,
313
- impact: r.impact,
314
- category: r.category,
315
- why: STRENGTH_REASONS[r.key] || `Already configured and working: ${r.name}.`,
316
- }));
317
- }
318
-
319
- const GAP_REASONS = {
320
- noBypassPermissions: 'bypassPermissions skips all safety checks. Use explicit allow rules for control without risk.',
321
- secretsProtection: 'Without deny rules for .env, Claude can read secrets and potentially expose them in outputs.',
322
- testCommand: 'Without a test command, Claude cannot verify its changes work before you review them.',
323
- lintCommand: 'Without a lint command, Claude may produce inconsistently formatted code.',
324
- buildCommand: 'Without a build command, Claude cannot catch compilation errors early.',
325
- ciPipeline: 'CI ensures every change is automatically tested. Without it, bugs reach main branch faster.',
326
- securityReview: 'Claude Code has built-in OWASP Top 10 scanning. Not using it leaves vulnerabilities undetected.',
327
- skills: 'Skills encode domain expertise as reusable components. Without them, you repeat context every session.',
328
- multipleAgents: 'Multiple agents enable parallel specialized work (security review + code writing simultaneously).',
329
- multipleMcpServers: 'More MCP servers give Claude access to more external context (docs, databases, APIs).',
330
- roleDefinition: 'A role definition helps Claude calibrate response depth and technical level.',
331
- importSyntax: '@import keeps CLAUDE.md lean while still providing deep instructions in focused modules.',
332
- };
333
-
334
- function toGaps(results) {
335
- return results
336
- .filter(r => r.passed === false)
337
- .sort((a, b) => {
338
- const order = { critical: 3, high: 2, medium: 1, low: 0 };
339
- return (order[b.impact] || 0) - (order[a.impact] || 0);
340
- })
341
- .slice(0, 8)
342
- .map(r => ({
343
- key: r.key,
344
- name: r.name,
345
- impact: r.impact,
346
- category: r.category,
347
- fix: r.fix,
348
- why: GAP_REASONS[r.key] || r.fix,
349
- }));
350
- }
351
-
352
- function toRecommendations(auditResult) {
353
- const failed = auditResult.results.filter(r => r.passed === false);
354
- const topActionOrder = new Map((auditResult.topNextActions || []).map((item, index) => [item.key, index]));
355
- failed.sort((a, b) => {
356
- const rankedA = topActionOrder.has(a.key) ? topActionOrder.get(a.key) : Number.MAX_SAFE_INTEGER;
357
- const rankedB = topActionOrder.has(b.key) ? topActionOrder.get(b.key) : Number.MAX_SAFE_INTEGER;
358
- if (rankedA !== rankedB) return rankedA - rankedB;
359
- const order = { critical: 3, high: 2, medium: 1, low: 0 };
360
- return (order[b.impact] || 0) - (order[a.impact] || 0);
361
- });
362
-
363
- return failed.slice(0, 10).map((r, index) => ({
364
- priority: index + 1,
365
- key: r.key,
366
- name: r.name,
367
- impact: r.impact,
368
- module: moduleFromCategory(r.category),
369
- risk: riskFromImpact(r.impact),
370
- why: r.fix,
371
- evidenceClass: (auditResult.topNextActions || []).find(item => item.key === r.key)?.evidenceClass || 'estimated',
372
- rankingAdjustment: (auditResult.topNextActions || []).find(item => item.key === r.key)?.rankingAdjustment || 0,
373
- }));
374
- }
375
-
376
- function buildOptionalModules(platform, stacks, assets, recommendedDomainPacks = []) {
377
- if (platform === 'codex') {
378
- const modules = [];
379
-
380
- if (!assets.instructionPath) modules.push('AGENTS.md baseline');
381
- if (!assets.configPath) modules.push('Codex config baseline');
382
- if (assets.counts.rules === 0) modules.push('Codex rules baseline');
383
- if (assets.counts.hooks === 0) modules.push('Hooks scaffold');
384
- if (assets.counts.skills === 0) modules.push('Repo-local skills starter');
385
- if (assets.counts.agents === 0) modules.push('Subagents starter');
386
- if (assets.counts.mcpServers === 0) modules.push('MCP baseline');
387
- if (assets.counts.workflows === 0) modules.push('CI / review workflow starter');
388
- for (const pack of recommendedDomainPacks) {
389
- for (const moduleName of pack.recommendedModules || []) {
390
- modules.push(moduleName);
391
- }
392
- }
393
-
394
- return [...new Set(modules)].slice(0, 8);
395
- }
396
-
397
- const stackKeys = stacks.map(s => s.key);
398
- const modules = [];
399
-
400
- if (!assets.files.claudeMd) modules.push('CLAUDE.md baseline');
401
- if (assets.counts.commands === 0) modules.push('Slash commands');
402
- if (assets.counts.hooks === 0) modules.push('Hooks automation');
403
- if (!assets.permissions || !assets.permissions.hasDenyRules) modules.push('Permission safety profile');
404
- if (assets.counts.rules === 0) modules.push('Path-specific rules');
405
- if (stackKeys.some(k => ['react', 'nextjs', 'vue', 'angular', 'svelte'].includes(k))) modules.push('Frontend pack');
406
- if (stackKeys.some(k => ['node', 'python', 'django', 'fastapi', 'go', 'rust', 'java'].includes(k))) modules.push('Backend pack');
407
- if (stackKeys.some(k => ['docker', 'terraform', 'kubernetes'].includes(k))) modules.push('DevOps pack');
408
- if (assets.counts.agents === 0) modules.push('Specialized agents');
409
-
410
- return [...new Set(modules)].slice(0, 8);
411
- }
412
-
413
- function buildRiskNotes(platform, auditResult, assets, maturity) {
414
- if (platform === 'codex') {
415
- const notes = [];
416
- if (!assets.instructionPath) notes.push('No AGENTS.md exists yet, so Codex starts without repo-specific instructions.');
417
- if (!assets.configPath) notes.push('No .codex/config.toml exists yet, so approval, sandbox, and history posture are implicit.');
418
- if (assets.trust && assets.trust.approvalPolicy === 'never') {
419
- notes.push('approval_policy is set to `never`; make sure that autonomy level is truly intended for this repo.');
420
- }
421
- if (assets.trust && assets.trust.sandboxMode === 'danger-full-access') {
422
- notes.push('sandbox_mode is `danger-full-access`, which removes Codex runtime guardrails and should stay exceptional.');
423
- }
424
- if (assets.counts.mcpServers > 0 && assets.trust && !assets.trust.isTrustedProject) {
425
- notes.push('This repo appears to rely on project-scoped MCP, but the project trust path is not clearly established.');
426
- }
427
- if (maturity === 'mature') {
428
- notes.push('This repo already has meaningful Codex assets, so advisory mode should preserve and extend them instead of flattening them.');
429
- }
430
- for (const caveat of auditResult.platformCaveats || []) {
431
- if (caveat && caveat.message) {
432
- notes.push(caveat.message);
433
- }
434
- }
435
- return [...new Set(notes)].slice(0, 5);
436
- }
437
-
438
- const notes = [];
439
- if (!assets.files.claudeMd) notes.push('No CLAUDE.md exists yet, so Claude has no persistent project-specific guidance.');
440
- if (assets.permissions && assets.permissions.defaultMode === 'bypassPermissions') {
441
- notes.push('Current settings use bypassPermissions, which is risky for broader team adoption.');
442
- }
443
- if (!assets.permissions || !assets.permissions.hasDenyRules) {
444
- notes.push('Permissions lack deny rules, so secret access and destructive commands are not strongly guarded.');
445
- }
446
- if (maturity === 'mature') {
447
- notes.push('This repo already has meaningful Claude assets, so augment mode should preserve existing structure instead of overwriting it.');
448
- }
449
- if (auditResult.results.some(r => r.key === 'ciPipeline' && r.passed === false)) {
450
- notes.push('Without CI enforcement, readiness can drift after setup.');
451
- }
452
- return notes.slice(0, 5);
453
- }
454
-
455
- function buildRolloutOrder(report) {
456
- if (report.platform === 'codex') {
457
- const steps = [];
458
- if (!report.existingPlatformAssets.instructionPath) steps.push('Create a project-specific AGENTS.md baseline');
459
- if (!report.existingPlatformAssets.configPath) steps.push('Create a safe `.codex/config.toml` baseline with explicit trust settings');
460
- if (report.recommendedDomainPacks.length > 0) {
461
- steps.push(`Start from the ${report.recommendedDomainPacks.map((pack) => pack.label).join(' + ')} pack guidance before adding optional Codex surfaces`);
462
- }
463
- if (report.gapsIdentified.some(g => g.category === 'trust' || g.category === 'config')) steps.push('Make approval, sandbox, history, and network posture explicit');
464
- if (report.gapsIdentified.some(g => g.category === 'rules')) steps.push('Add Codex rules for risky command classes before expanding automation');
465
- if (report.gapsIdentified.some(g => g.category === 'mcp')) steps.push('Add MCP only where the repo really needs live external context and the trust boundary is clear');
466
- if (report.gapsIdentified.some(g => g.category === 'skills' || g.category === 'agents')) steps.push('Add skills and subagents only after the baseline contract is stable');
467
- if (report.gapsIdentified.some(g => g.category === 'review' || g.category === 'automation')) steps.push('Add review and CI automation after local verification is explicit');
468
- return steps.length > 0 ? steps : ['Preserve the current Codex baseline and tighten remaining quality-deep items'];
469
- }
470
-
471
- const steps = [];
472
- if (!report.existingClaudeAssets.claudeMd) steps.push('Create a project-specific CLAUDE.md baseline');
473
- if (report.gapsIdentified.some(g => g.category === 'security')) steps.push('Add safe settings and deny rules');
474
- if (report.gapsIdentified.some(g => g.category === 'automation')) steps.push('Add hooks and automate verification');
475
- if (report.gapsIdentified.some(g => g.category === 'workflow')) steps.push('Add commands, rules, and specialization modules');
476
- if (report.gapsIdentified.some(g => g.category === 'devops')) steps.push('Connect CI threshold enforcement');
477
- if (steps.length === 0) steps.push('Tighten quality-deep items and preserve the current setup');
478
- return steps;
479
- }
480
-
481
- /**
482
- * Analyze a project's Claude Code setup and produce a structured recommendation report.
483
- * @param {Object} options - Analysis options.
484
- * @param {string} options.dir - Project directory to analyze.
485
- * @param {string} [options.mode='augment'] - Analysis mode ('augment' or 'suggest-only').
486
- * @returns {Promise<Object>} Structured report with project summary, gaps, strengths, and recommendations.
487
- */
488
- async function analyzeProject(options) {
489
- const mode = options.mode || 'augment';
490
- const platform = options.platform === 'codex' ? 'codex' : 'claude';
491
- const platformLabel = platform === 'codex' ? 'Codex' : 'Claude';
492
- const ContextClass = platform === 'codex' ? CodexProjectContext : ProjectContext;
493
- const ctx = new ContextClass(options.dir);
494
- const stacks = ctx.detectStacks(STACKS);
495
- const auditResult = await audit({ ...options, silent: true, platform });
496
- const assets = platform === 'codex' ? collectCodexAssets(ctx) : collectClaudeAssets(ctx);
497
- const metadata = detectProjectMetadata(ctx);
498
- const maturity = detectMaturity(platform, assets);
499
- const mainDirs = detectMainDirs(ctx);
500
- const recommendedDomainPacks = platform === 'codex'
501
- ? detectCodexDomainPacks(ctx, stacks, assets)
502
- : detectDomainPacks(ctx, stacks, assets);
503
- const recommendedMcpPacks = platform === 'claude' ? recommendMcpPacks(stacks, recommendedDomainPacks, { ctx, assets }) : [];
504
- const repoArchetype = buildRepoArchetypeProfile({
505
- ctx,
506
- platform,
507
- stacks,
508
- assets,
509
- recommendedDomainPacks,
510
- recommendedMcpPacks,
511
- maturity,
512
- });
513
- const recommendedOperatingProfile = buildOperatingProfile({
514
- dir: options.dir,
515
- platform,
516
- repoArchetype,
517
- recommendedDomainPacks,
518
- recommendedMcpPacks,
519
- });
520
- const adoptionGuidance = buildAdoptionAdvisor({
521
- platform,
522
- repoArchetype,
523
- recommendedOperatingProfile,
524
- recommendedDomainPacks,
525
- recommendedMcpPacks,
526
- env: options.env || {},
527
- });
528
-
529
- const report = {
530
- platform,
531
- platformLabel,
532
- mode,
533
- writeBehavior: 'No files are written in this mode.',
534
- projectSummary: {
535
- name: metadata.name,
536
- description: metadata.description,
537
- directory: options.dir,
538
- stacks: stacks.map(s => s.label),
539
- domains: recommendedDomainPacks.map(pack => pack.label),
540
- maturity,
541
- archetype: repoArchetype.label,
542
- workflow: repoArchetype.primaryWorkflow.label,
543
- riskLevel: repoArchetype.riskProfile.label,
544
- operatingProfile: recommendedOperatingProfile.label,
545
- adoptionPlan: adoptionGuidance.summary.label,
546
- score: auditResult.score,
547
- organicScore: auditResult.organicScore,
548
- checkCount: auditResult.checkCount,
549
- },
550
- platformScopeNote: auditResult.platformScopeNote || null,
551
- platformCaveats: auditResult.platformCaveats || [],
552
- repoArchetype,
553
- recommendedOperatingProfile,
554
- adoptionGuidance,
555
- detectedArchitecture: {
556
- repoType: stacks.length > 0 ? 'stack-detected repo' : 'generic repo',
557
- mainDirectories: mainDirs,
558
- stackSignals: stacks.map(s => s.key),
559
- stackFamily: repoArchetype.stackFamily.label,
560
- topology: repoArchetype.topology.label,
561
- workflow: repoArchetype.primaryWorkflow.label,
562
- riskLevel: repoArchetype.riskProfile.label,
563
- },
564
- existingPlatformAssets: assets,
565
- strengthsPreserved: toStrengths(auditResult.results),
566
- gapsIdentified: toGaps(auditResult.results),
567
- topNextActions: auditResult.topNextActions || auditResult.quickWins,
568
- recommendedImprovements: toRecommendations(auditResult),
569
- recommendedDomainPacks,
570
- recommendedMcpPacks,
571
- riskNotes: buildRiskNotes(platform, auditResult, assets, maturity),
572
- optionalModules: buildOptionalModules(platform, stacks, assets, recommendedDomainPacks),
573
- };
574
-
575
- if (platform === 'claude') {
576
- report.existingClaudeAssets = {
577
- claudeMd: assets.files.claudeMd,
578
- settings: assets.settingsSource,
579
- commands: assets.files.commands,
580
- rules: assets.files.rules,
581
- hooks: assets.files.hooks,
582
- agents: assets.files.agents,
583
- skills: assets.files.skills,
584
- mcpServers: assets.counts.mcpServers,
585
- };
586
- } else {
587
- report.existingCodexAssets = {
588
- agentsMd: assets.instructionPath,
589
- config: assets.configPath,
590
- rules: assets.files.rules,
591
- hooks: assets.files.hooks,
592
- skills: assets.files.skills,
593
- agents: assets.files.agents,
594
- workflows: assets.files.workflows,
595
- mcpServers: assets.counts.mcpServers,
596
- };
597
- }
598
-
599
- report.suggestedRolloutOrder = buildRolloutOrder(report);
600
- return report;
601
- }
602
-
603
- function printAnalysis(report, options = {}) {
604
- if (options.json) {
605
- console.log(JSON.stringify(report, null, 2));
606
- return;
607
- }
608
-
609
- const modeLabel = report.mode === 'suggest-only' ? 'suggest-only' : report.mode;
610
- console.log('');
611
- console.log(c(` nerviq ${report.platform === 'codex' ? 'codex ' : ''}${modeLabel}`, 'bold'));
612
- console.log(c(' ═══════════════════════════════════════', 'dim'));
613
- console.log(c(` ${report.writeBehavior}`, 'dim'));
614
- if (report.platformScopeNote) {
615
- console.log(c(` ${report.platformScopeNote.message}`, 'dim'));
616
- }
617
- console.log('');
618
-
619
- console.log(c(' Project Summary', 'blue'));
620
- console.log(` ${report.projectSummary.name}${report.projectSummary.description ? ` — ${report.projectSummary.description}` : ''}`);
621
- console.log(c(` Stack: ${report.projectSummary.stacks.join(', ') || 'Unknown'}`, 'dim'));
622
- if (report.platform === 'claude') {
623
- console.log(c(` Domain packs: ${report.projectSummary.domains.join(', ') || 'Baseline General'}`, 'dim'));
624
- } else {
625
- console.log(c(` Platform: ${report.platformLabel}`, 'dim'));
626
- }
627
- console.log(c(` Archetype: ${report.repoArchetype.label} | Workflow: ${report.repoArchetype.primaryWorkflow.label} | Risk: ${report.repoArchetype.riskProfile.label}`, 'dim'));
628
- console.log(c(` Maturity: ${report.projectSummary.maturity} | Score: ${report.projectSummary.score}/100 | Organic: ${report.projectSummary.organicScore}/100`, 'dim'));
629
- console.log('');
630
-
631
- console.log(c(' Detected Architecture', 'blue'));
632
- console.log(c(` Stack family: ${report.repoArchetype.stackFamily.label} | Topology: ${report.repoArchetype.topology.label} | Confidence: ${report.repoArchetype.confidence}`, 'dim'));
633
- console.log(c(` Main directories: ${report.detectedArchitecture.mainDirectories.join(', ') || 'No strong structure detected yet'}`, 'dim'));
634
- console.log(c(` Signals: ${report.repoArchetype.signals.join(' | ') || 'No strong archetype signals yet'}`, 'dim'));
635
- console.log('');
636
-
637
- console.log(c(` Existing ${report.existingPlatformAssets.label} Assets`, 'blue'));
638
- console.log(c(` ${report.existingPlatformAssets.instructionLabel}: ${report.existingPlatformAssets.instructionPath || 'missing'}`, 'dim'));
639
- console.log(c(` ${report.existingPlatformAssets.configLabel}: ${report.existingPlatformAssets.configPath || 'missing'}`, 'dim'));
640
- console.log(c(` ${report.existingPlatformAssets.summaryLine}`, 'dim'));
641
- if (report.platform === 'codex' && report.existingPlatformAssets.trust) {
642
- const trustBits = [
643
- `Approval: ${report.existingPlatformAssets.trust.approvalPolicy || 'implicit'}`,
644
- `Sandbox: ${report.existingPlatformAssets.trust.sandboxMode || 'implicit'}`,
645
- `Trusted path: ${report.existingPlatformAssets.trust.isTrustedProject ? 'yes' : 'no'}`,
646
- ];
647
- console.log(c(` ${trustBits.join(' | ')}`, 'dim'));
648
- }
649
- console.log('');
650
-
651
- if (report.strengthsPreserved.length > 0) {
652
- console.log(c(` ${'\u2705'} Strengths Preserved (don't change these)`, 'green'));
653
- for (const item of report.strengthsPreserved) {
654
- const impactLabel = item.impact ? ` (${item.impact})` : '';
655
- console.log(` ${c('\u2022', 'green')} ${item.name}${c(impactLabel, 'dim')}`);
656
- }
657
- console.log('');
658
- }
659
-
660
- if (report.gapsIdentified.length > 0) {
661
- console.log(c(' Gaps Identified', 'yellow'));
662
- for (const item of report.gapsIdentified.slice(0, 5)) {
663
- console.log(` - [${item.impact}] ${item.name}`);
664
- console.log(c(` ${item.fix}`, 'dim'));
665
- }
666
- console.log('');
667
- }
668
-
669
- if (report.topNextActions.length > 0) {
670
- console.log(c(' Top 5 Next Actions', 'magenta'));
671
- report.topNextActions.slice(0, 5).forEach((item, index) => {
672
- console.log(` ${index + 1}. ${item.name}`);
673
- console.log(c(` Why: ${item.why || item.fix}`, 'dim'));
674
- if (Array.isArray(item.signals) && item.signals.length > 0) {
675
- console.log(c(` Trace: ${item.signals.join(' | ')}`, 'dim'));
676
- }
677
- if (item.risk || item.confidence) {
678
- console.log(c(` Risk: ${item.risk || 'low'} | Confidence: ${item.confidence || 'medium'}`, 'dim'));
679
- }
680
- if (item.fix && item.fix !== item.why) {
681
- console.log(c(` Fix: ${item.fix}`, 'dim'));
682
- }
683
- });
684
- console.log('');
685
- }
686
-
687
- if (report.recommendedDomainPacks.length > 0) {
688
- console.log(c(' Recommended Domain Packs', 'blue'));
689
- for (const pack of report.recommendedDomainPacks) {
690
- console.log(` - ${pack.label}`);
691
- console.log(c(` ${pack.useWhen}`, 'dim'));
692
- }
693
- console.log('');
694
- }
695
-
696
- if (report.recommendedMcpPacks.length > 0) {
697
- console.log(c(' Recommended MCP Packs', 'blue'));
698
- for (const pack of report.recommendedMcpPacks) {
699
- console.log(` - ${pack.label}`);
700
- console.log(c(` ${pack.adoption}`, 'dim'));
701
- }
702
- console.log('');
703
- }
704
-
705
- if (report.platformCaveats && report.platformCaveats.length > 0) {
706
- console.log(c(' Platform Caveats', 'yellow'));
707
- for (const item of report.platformCaveats) {
708
- console.log(` - ${item.title}`);
709
- console.log(c(` ${item.message}`, 'dim'));
710
- }
711
- console.log('');
712
- }
713
-
714
- if (report.riskNotes.length > 0) {
715
- console.log(c(' Risk Notes', 'red'));
716
- for (const note of report.riskNotes) {
717
- console.log(` - ${note}`);
718
- }
719
- console.log('');
720
- }
721
-
722
- if (report.optionalModules.length > 0) {
723
- console.log(c(' Optional Modules', 'blue'));
724
- console.log(c(` ${report.optionalModules.join(' | ')}`, 'dim'));
725
- console.log('');
726
- }
727
-
728
- if (report.recommendedOperatingProfile) {
729
- console.log(c(' Recommended Operating Profile', 'blue'));
730
- console.log(` ${report.recommendedOperatingProfile.label}`);
731
- console.log(c(` Permission: ${report.recommendedOperatingProfile.permissionProfile.label} | Governance pack: ${report.recommendedOperatingProfile.governancePack.label}`, 'dim'));
732
- console.log(c(` CI shape: ${report.recommendedOperatingProfile.ciShape.label} | Platforms: ${(report.recommendedOperatingProfile.platformSupport.recommended || []).join(', ') || report.platformLabel}`, 'dim'));
733
- console.log(c(` Hooks: ${report.recommendedOperatingProfile.hooks.map((hook) => hook.key).join(', ')}`, 'dim'));
734
- console.log(c(` Verification: ${report.recommendedOperatingProfile.verification.required.join(', ')}`, 'dim'));
735
- console.log('');
736
- }
737
-
738
- if (report.adoptionGuidance && Array.isArray(report.adoptionGuidance.items) && report.adoptionGuidance.items.length > 0) {
739
- console.log(c(' Adopt / Defer / Ignore', 'blue'));
740
- console.log(c(` ${report.adoptionGuidance.summary.label}`, 'dim'));
741
- const groups = [
742
- ['adopt', 'Adopt now'],
743
- ['defer', 'Defer until prerequisites are ready'],
744
- ['ignore', 'Ignore for this repo shape'],
745
- ];
746
- for (const [decision, label] of groups) {
747
- const items = report.adoptionGuidance.items.filter((item) => item.decision === decision).slice(0, 3);
748
- if (items.length === 0) continue;
749
- console.log(` ${label}`);
750
- for (const item of items) {
751
- console.log(` - ${item.label}`);
752
- console.log(c(` ${item.why}`, 'dim'));
753
- }
754
- }
755
- console.log('');
756
- }
757
-
758
- if (report.suggestedRolloutOrder.length > 0) {
759
- console.log(c(' Suggested Rollout Order', 'blue'));
760
- report.suggestedRolloutOrder.forEach((item, index) => {
761
- console.log(` ${index + 1}. ${item}`);
762
- });
763
- console.log('');
764
- }
765
- }
766
-
767
- /**
768
- * Export an analysis report as a formatted markdown string.
769
- * @param {Object} report - The report object returned by analyzeProject().
770
- * @returns {string} Markdown-formatted report content.
771
- */
772
- function exportMarkdown(report) {
773
- const lines = [];
774
- lines.push(`# Nerviq Analysis Report`);
775
- lines.push(`## ${report.platformLabel} ${report.mode === 'suggest-only' ? 'Suggest-Only' : 'Augment'} Mode`);
776
- lines.push('');
777
- lines.push(`**Project:** ${report.projectSummary.name}${report.projectSummary.description ? ` — ${report.projectSummary.description}` : ''}`);
778
- lines.push(`**Date:** ${new Date().toISOString().split('T')[0]}`);
779
- lines.push(`**Platform:** ${report.platformLabel}`);
780
- lines.push(`**Score:** ${report.projectSummary.score}/100 | **Organic:** ${report.projectSummary.organicScore}/100`);
781
- lines.push(`**Stacks:** ${report.projectSummary.stacks.join(', ') || 'None detected'}`);
782
- if (report.platform === 'claude') {
783
- lines.push(`**Domain Packs:** ${report.projectSummary.domains.join(', ') || 'Baseline General'}`);
784
- }
785
- lines.push(`**Archetype:** ${report.repoArchetype.label}`);
786
- lines.push(`**Workflow:** ${report.repoArchetype.primaryWorkflow.label}`);
787
- lines.push(`**Risk posture:** ${report.repoArchetype.riskProfile.label}`);
788
- lines.push(`**Operating profile:** ${report.recommendedOperatingProfile.label}`);
789
- lines.push(`**Adoption plan:** ${report.adoptionGuidance.summary.label}`);
790
- lines.push(`**Maturity:** ${report.projectSummary.maturity}`);
791
- lines.push('');
792
-
793
- if (report.platformScopeNote) {
794
- lines.push(`> ${report.platformScopeNote.message}`);
795
- lines.push('');
796
- }
797
-
798
- lines.push(`## Existing ${report.existingPlatformAssets.label} Assets`);
799
- lines.push('');
800
- lines.push(`- **${report.existingPlatformAssets.instructionLabel}:** ${report.existingPlatformAssets.instructionPath || 'missing'}`);
801
- lines.push(`- **${report.existingPlatformAssets.configLabel}:** ${report.existingPlatformAssets.configPath || 'missing'}`);
802
- lines.push(`- **Summary:** ${report.existingPlatformAssets.summaryLine}`);
803
- if (report.platform === 'codex' && report.existingPlatformAssets.trust) {
804
- lines.push(`- **Approval policy:** ${report.existingPlatformAssets.trust.approvalPolicy || 'implicit'}`);
805
- lines.push(`- **Sandbox mode:** ${report.existingPlatformAssets.trust.sandboxMode || 'implicit'}`);
806
- lines.push(`- **Trusted project path:** ${report.existingPlatformAssets.trust.isTrustedProject ? 'yes' : 'no'}`);
807
- }
808
- lines.push('');
809
-
810
- lines.push('## Repo Archetype');
811
- lines.push('');
812
- lines.push(`- **Label:** ${report.repoArchetype.label}`);
813
- lines.push(`- **Summary:** ${report.repoArchetype.summary}`);
814
- lines.push(`- **Stack family:** ${report.repoArchetype.stackFamily.label}`);
815
- lines.push(`- **Topology:** ${report.repoArchetype.topology.label}`);
816
- lines.push(`- **Primary workflow:** ${report.repoArchetype.primaryWorkflow.label}`);
817
- lines.push(`- **Risk posture:** ${report.repoArchetype.riskProfile.label}`);
818
- lines.push(`- **Confidence:** ${report.repoArchetype.confidence}`);
819
- if (report.repoArchetype.signals.length > 0) {
820
- lines.push(`- **Signals:** ${report.repoArchetype.signals.join(', ')}`);
821
- }
822
- lines.push('');
823
-
824
- lines.push('## Recommended Operating Profile');
825
- lines.push('');
826
- lines.push(`- **Label:** ${report.recommendedOperatingProfile.label}`);
827
- lines.push(`- **Summary:** ${report.recommendedOperatingProfile.summary}`);
828
- lines.push(`- **Permission profile:** ${report.recommendedOperatingProfile.permissionProfile.label}`);
829
- lines.push(`- **Governance pack:** ${report.recommendedOperatingProfile.governancePack.label}`);
830
- lines.push(`- **Platform support:** ${(report.recommendedOperatingProfile.platformSupport.recommended || []).join(', ') || report.platformLabel}`);
831
- if (report.recommendedOperatingProfile.platformSupport.optionalExpansion) {
832
- lines.push(`- **Optional expansion:** ${report.recommendedOperatingProfile.platformSupport.optionalExpansion}`);
833
- }
834
- lines.push(`- **CI shape:** ${report.recommendedOperatingProfile.ciShape.label}`);
835
- lines.push(`- **Verification:** ${report.recommendedOperatingProfile.verification.required.join(', ')}`);
836
- lines.push(`- **Hooks:** ${report.recommendedOperatingProfile.hooks.map((hook) => hook.key).join(', ')}`);
837
- lines.push('');
838
-
839
- lines.push('## Adopt / Defer / Ignore');
840
- lines.push('');
841
- const decisionGroups = [
842
- ['adopt', 'Adopt now'],
843
- ['defer', 'Defer'],
844
- ['ignore', 'Ignore'],
845
- ];
846
- for (const [decision, label] of decisionGroups) {
847
- const items = report.adoptionGuidance.items.filter((item) => item.decision === decision);
848
- if (items.length === 0) continue;
849
- lines.push(`### ${label}`);
850
- lines.push('');
851
- for (const item of items) {
852
- lines.push(`- **${item.label}** — ${item.why}`);
853
- lines.push(` Evidence: ${item.evidence.join(' | ')}`);
854
- lines.push(` Prerequisites: ${item.prerequisites.length > 0 ? item.prerequisites.join(' | ') : 'None'}`);
855
- lines.push(` Expected benefit: ${item.expectedBenefit}`);
856
- lines.push(` Rollback safety: ${item.rollbackSafety}`);
857
- }
858
- lines.push('');
859
- }
860
-
861
- if (report.strengthsPreserved.length > 0) {
862
- lines.push('## Strengths Preserved (don\'t change these)');
863
- lines.push('');
864
- for (const item of report.strengthsPreserved) {
865
- const impactLabel = item.impact ? ` (${item.impact})` : '';
866
- lines.push(`- **${item.name}**${impactLabel} — ${item.why || 'Already configured.'}`);
867
- }
868
- lines.push('');
869
- }
870
-
871
- if (report.gapsIdentified.length > 0) {
872
- lines.push('## Gaps Identified');
873
- lines.push('');
874
- lines.push('| Gap | Impact | Fix |');
875
- lines.push('|-----|--------|-----|');
876
- for (const item of report.gapsIdentified) {
877
- lines.push(`| ${item.name} | ${item.impact} | ${item.fix} |`);
878
- }
879
- lines.push('');
880
- }
881
-
882
- if (report.topNextActions.length > 0) {
883
- lines.push('## Top Next Actions');
884
- lines.push('');
885
- report.topNextActions.slice(0, 5).forEach((item, index) => {
886
- lines.push(`${index + 1}. **${item.name}**`);
887
- lines.push(` - Why: ${item.why || item.fix}`);
888
- if (Array.isArray(item.signals) && item.signals.length > 0) {
889
- lines.push(` - Trace: ${item.signals.join(' | ')}`);
890
- }
891
- if (item.risk || item.confidence) {
892
- lines.push(` - Risk / Confidence: ${item.risk || 'low'} / ${item.confidence || 'medium'}`);
893
- }
894
- if (item.fix && item.fix !== item.why) {
895
- lines.push(` - Fix: ${item.fix}`);
896
- }
897
- });
898
- lines.push('');
899
- }
900
-
901
- if (report.recommendedDomainPacks.length > 0) {
902
- lines.push('## Recommended Domain Packs');
903
- lines.push('');
904
- for (const pack of report.recommendedDomainPacks) {
905
- lines.push(`- **${pack.label}**: ${pack.useWhen}`);
906
- }
907
- lines.push('');
908
- }
909
-
910
- if (report.recommendedMcpPacks.length > 0) {
911
- lines.push('## Recommended MCP Packs');
912
- lines.push('');
913
- for (const pack of report.recommendedMcpPacks) {
914
- lines.push(`- **${pack.label}**: ${pack.useWhen}`);
915
- }
916
- lines.push('');
917
- }
918
-
919
- if (report.platformCaveats && report.platformCaveats.length > 0) {
920
- lines.push('## Platform Caveats');
921
- lines.push('');
922
- for (const item of report.platformCaveats) {
923
- lines.push(`- **${item.title}**: ${item.message}`);
924
- }
925
- lines.push('');
926
- }
927
-
928
- if (report.riskNotes.length > 0) {
929
- lines.push('## Risk Notes');
930
- lines.push('');
931
- for (const note of report.riskNotes) {
932
- lines.push(`- ⚠️ ${note}`);
933
- }
934
- lines.push('');
935
- }
936
-
937
- if (report.suggestedRolloutOrder.length > 0) {
938
- lines.push('## Suggested Rollout Order');
939
- lines.push('');
940
- report.suggestedRolloutOrder.forEach((item, index) => {
941
- lines.push(`${index + 1}. ${item}`);
942
- });
943
- lines.push('');
944
- }
945
-
946
- lines.push('---');
947
- lines.push(`*Generated by nerviq v${require('../package.json').version}*`);
948
- return lines.join('\n');
949
- }
950
-
951
- module.exports = { analyzeProject, printAnalysis, exportMarkdown };
1
+ /**
2
+ * Project scanner + recommendation layer for augment and suggest-only modes.
3
+ * Produces a structured repo-aware analysis without writing files.
4
+ */
5
+
6
+ const path = require('path');
7
+ const { audit } = require('./audit');
8
+ const { ProjectContext } = require('./context');
9
+ const { CodexProjectContext } = require('./codex/context');
10
+ const { STACKS } = require('./techniques');
11
+ const { detectDomainPacks } = require('./domain-packs');
12
+ const { detectCodexDomainPacks } = require('./codex/domain-packs');
13
+ const { recommendMcpPacks } = require('./mcp-packs');
14
+ const { collectClaudeDenyRules } = require('./permission-rules');
15
+ const { buildRepoArchetypeProfile } = require('./repo-archetype');
16
+ const { buildOperatingProfile } = require('./operating-profile');
17
+ const { buildAdoptionAdvisor } = require('./adoption-advisor');
18
+
19
+ const COLORS = {
20
+ reset: '\x1b[0m',
21
+ bold: '\x1b[1m',
22
+ dim: '\x1b[2m',
23
+ red: '\x1b[31m',
24
+ green: '\x1b[32m',
25
+ yellow: '\x1b[33m',
26
+ blue: '\x1b[36m',
27
+ magenta: '\x1b[35m',
28
+ };
29
+
30
+ function c(text, color) {
31
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
32
+ }
33
+
34
+ function escapeRegex(value) {
35
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
+ }
37
+
38
+ function extractTomlSection(content, sectionName) {
39
+ const pattern = new RegExp(`\\[${escapeRegex(sectionName)}\\]([\\s\\S]*?)(?:\\n\\s*\\[|$)`);
40
+ const match = content.match(pattern);
41
+ return match ? match[1] : null;
42
+ }
43
+
44
+ function extractTomlValue(sectionContent, key) {
45
+ if (!sectionContent) return null;
46
+ const pattern = new RegExp(`^\\s*${escapeRegex(key)}\\s*=\\s*["']([^"']+)["']`, 'm');
47
+ const match = sectionContent.match(pattern);
48
+ return match ? match[1].trim() : null;
49
+ }
50
+
51
+ function detectProjectMetadata(ctx) {
52
+ const pkg = ctx.jsonFile('package.json');
53
+ if (pkg && (pkg.name || pkg.description)) {
54
+ return {
55
+ name: pkg.name || path.basename(ctx.dir),
56
+ description: pkg.description || '',
57
+ };
58
+ }
59
+
60
+ const pyproject = ctx.fileContent('pyproject.toml') || '';
61
+ if (pyproject) {
62
+ const projectSection = extractTomlSection(pyproject, 'project');
63
+ const poetrySection = extractTomlSection(pyproject, 'tool.poetry');
64
+ const name = extractTomlValue(projectSection, 'name') ||
65
+ extractTomlValue(poetrySection, 'name');
66
+ const description = extractTomlValue(projectSection, 'description') ||
67
+ extractTomlValue(poetrySection, 'description');
68
+
69
+ if (name || description) {
70
+ return {
71
+ name: name || path.basename(ctx.dir),
72
+ description: description || '',
73
+ };
74
+ }
75
+ }
76
+
77
+ return {
78
+ name: path.basename(ctx.dir),
79
+ description: '',
80
+ };
81
+ }
82
+
83
+ function detectMainDirs(ctx) {
84
+ const candidates = [
85
+ 'src', 'lib', 'app', 'pages', 'components', 'api', 'routes', 'utils', 'helpers',
86
+ 'services', 'models', 'controllers', 'views', 'public', 'assets', 'config', 'tests',
87
+ 'test', '__tests__', 'spec', 'scripts', 'prisma', 'db', 'middleware', 'hooks',
88
+ 'agents', 'chains', 'workers', 'jobs', 'dags', 'macros', 'migrations',
89
+ 'src/components', 'src/app', 'src/pages', 'src/api', 'src/lib', 'src/hooks',
90
+ 'src/utils', 'src/services', 'src/models', 'src/middleware', 'src/agents',
91
+ 'src/chains', 'src/workers', 'src/jobs', 'src/app/api', 'app/api',
92
+ 'models/staging', 'models/marts'
93
+ ];
94
+
95
+ const dirs = [];
96
+ for (const dir of candidates) {
97
+ if (ctx.hasDir(dir)) {
98
+ dirs.push(dir);
99
+ }
100
+ }
101
+ return dirs;
102
+ }
103
+
104
+ function collectClaudeAssets(ctx) {
105
+ const sharedSettings = ctx.jsonFile('.claude/settings.json');
106
+ const localSettings = ctx.jsonFile('.claude/settings.local.json');
107
+ const settings = sharedSettings || localSettings || null;
108
+ const denyRules = collectClaudeDenyRules(ctx);
109
+
110
+ const assetFiles = {
111
+ claudeMd: ctx.fileContent('CLAUDE.md') ? 'CLAUDE.md' : (ctx.fileContent('.claude/CLAUDE.md') ? '.claude/CLAUDE.md' : null),
112
+ settings: sharedSettings ? '.claude/settings.json' : (localSettings ? '.claude/settings.local.json' : null),
113
+ commands: ctx.hasDir('.claude/commands') ? ctx.dirFiles('.claude/commands') : [],
114
+ rules: ctx.hasDir('.claude/rules') ? ctx.dirFiles('.claude/rules') : [],
115
+ hooks: ctx.hasDir('.claude/hooks') ? ctx.dirFiles('.claude/hooks') : [],
116
+ agents: ctx.hasDir('.claude/agents') ? ctx.dirFiles('.claude/agents') : [],
117
+ skills: ctx.hasDir('.claude/skills') ? ctx.dirFiles('.claude/skills') : [],
118
+ };
119
+
120
+ return {
121
+ label: 'Claude',
122
+ instructionLabel: 'CLAUDE.md',
123
+ configLabel: 'Settings',
124
+ instructionPath: assetFiles.claudeMd,
125
+ configPath: assetFiles.settings,
126
+ files: assetFiles,
127
+ counts: {
128
+ commands: assetFiles.commands.length,
129
+ rules: assetFiles.rules.length,
130
+ hooks: assetFiles.hooks.length,
131
+ agents: assetFiles.agents.length,
132
+ skills: assetFiles.skills.length,
133
+ mcpServers: settings && settings.mcpServers ? Object.keys(settings.mcpServers).length : 0,
134
+ },
135
+ permissions: settings && settings.permissions ? {
136
+ defaultMode: settings.permissions.defaultMode || null,
137
+ hasDenyRules: denyRules.length > 0,
138
+ } : null,
139
+ settingsSource: assetFiles.settings,
140
+ summaryLine: `Commands: ${assetFiles.commands.length} | Rules: ${assetFiles.rules.length} | Hooks: ${assetFiles.hooks.length} | Agents: ${assetFiles.agents.length} | Skills: ${assetFiles.skills.length} | MCP servers: ${settings && settings.mcpServers ? Object.keys(settings.mcpServers).length : 0}`,
141
+ };
142
+ }
143
+
144
+ function collectCodexAssets(ctx) {
145
+ const agentsMd = ctx.agentsMdPath ? ctx.agentsMdPath() : null;
146
+ const configPath = ctx.fileContent('.codex/config.toml') ? '.codex/config.toml' : null;
147
+ const hooksJson = ctx.hooksJsonContent ? ctx.hooksJsonContent() : null;
148
+ const rules = ctx.ruleFiles ? ctx.ruleFiles() : [];
149
+ const skills = ctx.skillDirs ? ctx.skillDirs().map((name) => `.agents/skills/${name}`) : [];
150
+ const agents = ctx.customAgentFiles ? ctx.customAgentFiles().map((file) => `.codex/agents/${file}`) : [];
151
+ const workflows = ctx.workflowFiles ? ctx.workflowFiles() : [];
152
+ const mcpServers = ctx.mcpServers ? Object.keys(ctx.mcpServers() || {}).length : 0;
153
+
154
+ return {
155
+ label: 'Codex',
156
+ instructionLabel: 'AGENTS.md',
157
+ configLabel: 'Config',
158
+ instructionPath: agentsMd,
159
+ configPath,
160
+ files: {
161
+ agentsMd,
162
+ config: configPath,
163
+ rules,
164
+ hooks: hooksJson ? ['.codex/hooks.json'] : [],
165
+ skills,
166
+ agents,
167
+ workflows,
168
+ },
169
+ counts: {
170
+ rules: rules.length,
171
+ hooks: hooksJson ? 1 : 0,
172
+ skills: skills.length,
173
+ agents: agents.length,
174
+ workflows: workflows.length,
175
+ mcpServers,
176
+ },
177
+ trust: {
178
+ approvalPolicy: ctx.configValue ? (ctx.configValue('approval_policy') || null) : null,
179
+ sandboxMode: ctx.configValue ? (ctx.configValue('sandbox_mode') || null) : null,
180
+ isTrustedProject: ctx.isProjectTrusted ? ctx.isProjectTrusted() : false,
181
+ },
182
+ summaryLine: `Rules: ${rules.length} | Hooks: ${hooksJson ? 1 : 0} | Skills: ${skills.length} | Subagents: ${agents.length} | Workflows: ${workflows.length} | MCP servers: ${mcpServers}`,
183
+ };
184
+ }
185
+
186
+ function detectMaturity(platform, assets) {
187
+ if (platform === 'codex') {
188
+ let score = 0;
189
+ if (assets.instructionPath) score += 2;
190
+ if (assets.configPath) score += 2;
191
+ if (assets.counts.rules > 0) score += 1;
192
+ if (assets.counts.hooks > 0) score += 1;
193
+ if (assets.counts.skills > 0) score += 1;
194
+ if (assets.counts.agents > 0) score += 1;
195
+ if (assets.counts.workflows > 0) score += 1;
196
+ if (assets.counts.mcpServers > 0) score += 1;
197
+
198
+ if (score === 0) return 'none';
199
+ if (score <= 2) return 'starter';
200
+ if (score <= 5) return 'developing';
201
+ return 'mature';
202
+ }
203
+
204
+ let score = 0;
205
+ if (assets.files.claudeMd) score += 2;
206
+ if (assets.files.settings) score += 1;
207
+ if (assets.counts.rules > 0) score += 1;
208
+ if (assets.counts.commands > 0) score += 1;
209
+ if (assets.counts.hooks > 0) score += 1;
210
+ if (assets.counts.agents > 0) score += 1;
211
+ if (assets.counts.skills > 0) score += 1;
212
+
213
+ if (score === 0) return 'none';
214
+ if (score <= 2) return 'starter';
215
+ if (score <= 5) return 'developing';
216
+ return 'mature';
217
+ }
218
+
219
+ function riskFromImpact(impact) {
220
+ if (impact === 'critical') return 'high';
221
+ if (impact === 'high') return 'medium';
222
+ return 'low';
223
+ }
224
+
225
+ function moduleFromCategory(category) {
226
+ const map = {
227
+ memory: 'CLAUDE.md',
228
+ instructions: 'AGENTS.md / instructions',
229
+ config: 'config.toml',
230
+ trust: 'trust-and-safety',
231
+ rules: 'rules',
232
+ hooks: 'hooks',
233
+ mcp: 'mcp',
234
+ skills: 'skills',
235
+ agents: 'subagents',
236
+ review: 'review',
237
+ automation: 'automation',
238
+ local: 'local-environments',
239
+ quality: 'verification',
240
+ git: 'safety',
241
+ workflow: 'commands-agents-skills',
242
+ security: 'permissions',
243
+ automation: 'hooks',
244
+ design: 'design-rules',
245
+ devops: 'ci-devops',
246
+ hygiene: 'project-hygiene',
247
+ performance: 'context-management',
248
+ tools: 'mcp-tools',
249
+ prompting: 'prompt-structure',
250
+ features: 'modern-claude-features',
251
+ 'quality-deep': 'quality-deep',
252
+ };
253
+ return map[category] || category;
254
+ }
255
+
256
+ const STRENGTH_REASONS = {
257
+ claudeMd: 'Foundation of Claude workflow. Every session benefits from this.',
258
+ mermaidArchitecture: 'Architecture diagram saves 73% tokens vs prose — high-value asset.',
259
+ verificationLoop: 'Claude can self-verify, catching errors before human review.',
260
+ hooks: 'Automated enforcement (100% vs 80% from instructions alone).',
261
+ hooksInSettings: 'Hook registration in settings ensures consistent automation.',
262
+ preToolUseHook: 'Pre-execution validation adds a safety layer.',
263
+ postToolUseHook: 'Post-execution automation catches issues immediately.',
264
+ sessionStartHook: 'Session initialization ensures consistent starting state.',
265
+ customCommands: 'Reusable workflows encoded as one-liner commands.',
266
+ settingsPermissions: 'Explicit permissions prevent accidental dangerous operations.',
267
+ permissionDeny: 'Deny rules block risky operations at the system level.',
268
+ pathRules: 'Scoped rules ensure different code areas get appropriate guidance.',
269
+ fewShotExamples: 'Code examples guide Claude to match your conventions.',
270
+ constraintBlocks: 'XML constraint blocks improve rule adherence by 40%.',
271
+ xmlTags: 'Structured prompt sections improve consistency.',
272
+ context7Mcp: 'Real-time docs eliminate version-mismatch hallucinations.',
273
+ mcpServers: 'External tool integration extends Claude capabilities.',
274
+ compactionAwareness: 'Context management keeps sessions efficient.',
275
+ agents: 'Specialized agents delegate complex tasks effectively.',
276
+ noSecretsInClaude: 'No secrets in config — good security hygiene.',
277
+ gitIgnoreEnv: 'Environment files are properly excluded from git.',
278
+ codexAgentsMd: 'Codex has a repo-native instruction surface instead of starting cold.',
279
+ codexAgentsMdSubstantive: 'A substantive AGENTS.md reduces drift and gives Codex a stable repo contract.',
280
+ codexAgentsVerificationCommands: 'Codex can verify its changes because the repo states how to test and build.',
281
+ codexAgentsArchitecture: 'Codex has a repo map to orient itself before editing.',
282
+ codexConfigExists: 'Codex runtime posture is reviewable because the project config is versioned.',
283
+ codexModelExplicit: 'The primary Codex model is explicit instead of silently inheriting defaults.',
284
+ codexReasoningEffortExplicit: 'Reasoning depth is explicit and reviewable.',
285
+ codexWeakTaskModelExplicit: 'Delegation for weaker tasks is explicit and cost-aware.',
286
+ codexApprovalPolicyExplicit: 'Approval behavior is explicit, predictable, and reviewable.',
287
+ codexSandboxExplicit: 'Sandbox posture is explicit instead of accidental.',
288
+ codexHistorySendToServerExplicit: 'History sync posture is reviewable in version control.',
289
+ codexRulesForRiskyCommands: 'Risky command classes are governed by Codex-native rules.',
290
+ codexHooksFeatureExplicit: 'Hook posture is explicit instead of implied.',
291
+ codexMcpExternalToolsConfigured: 'Codex has live MCP context instead of relying only on static repo files.',
292
+ codexSkillsDirPresentWhenUsed: 'Repo-local skills keep specialization versioned and reviewable.',
293
+ codexSkillsHaveMetadata: 'Skill metadata is explicit enough for reliable invocation.',
294
+ codexCustomAgentsRequiredFields: 'Custom subagents are structured and reviewable.',
295
+ codexExecUsageSafe: 'Codex automation posture is documented and safer to operate.',
296
+ codexGitHubActionSafeStrategy: 'CI posture is explicit and safer for Codex in automation.',
297
+ codexReviewWorkflowDocumented: 'A documented review path makes risky Codex changes easier to control.',
298
+ codexArtifactsSharedIntentionally: 'Codex repo artifacts are shared intentionally instead of being hidden from the team.',
299
+ codexAgentsMentionModernFeatures: 'AGENTS.md acknowledges the modern Codex surfaces the repo actually uses.',
300
+ };
301
+
302
+ function toStrengths(results) {
303
+ return results
304
+ .filter(r => r.passed === true && (r.impact === 'critical' || r.impact === 'high' || r.impact === 'medium'))
305
+ .sort((a, b) => {
306
+ const order = { critical: 3, high: 2, medium: 1, low: 0 };
307
+ return (order[b.impact] || 0) - (order[a.impact] || 0);
308
+ })
309
+ .slice(0, 10)
310
+ .map(r => ({
311
+ key: r.key,
312
+ name: r.name,
313
+ impact: r.impact,
314
+ category: r.category,
315
+ why: STRENGTH_REASONS[r.key] || `Already configured and working: ${r.name}.`,
316
+ }));
317
+ }
318
+
319
+ const GAP_REASONS = {
320
+ noBypassPermissions: 'bypassPermissions skips all safety checks. Use explicit allow rules for control without risk.',
321
+ secretsProtection: 'Without deny rules for .env, Claude can read secrets and potentially expose them in outputs.',
322
+ testCommand: 'Without a test command, Claude cannot verify its changes work before you review them.',
323
+ lintCommand: 'Without a lint command, Claude may produce inconsistently formatted code.',
324
+ buildCommand: 'Without a build command, Claude cannot catch compilation errors early.',
325
+ ciPipeline: 'CI ensures every change is automatically tested. Without it, bugs reach main branch faster.',
326
+ securityReview: 'Claude Code has built-in OWASP Top 10 scanning. Not using it leaves vulnerabilities undetected.',
327
+ skills: 'Skills encode domain expertise as reusable components. Without them, you repeat context every session.',
328
+ multipleAgents: 'Multiple agents enable parallel specialized work (security review + code writing simultaneously).',
329
+ multipleMcpServers: 'More MCP servers give Claude access to more external context (docs, databases, APIs).',
330
+ roleDefinition: 'A role definition helps Claude calibrate response depth and technical level.',
331
+ importSyntax: '@import keeps CLAUDE.md lean while still providing deep instructions in focused modules.',
332
+ };
333
+
334
+ function toGaps(results) {
335
+ return results
336
+ .filter(r => r.passed === false)
337
+ .sort((a, b) => {
338
+ const order = { critical: 3, high: 2, medium: 1, low: 0 };
339
+ return (order[b.impact] || 0) - (order[a.impact] || 0);
340
+ })
341
+ .slice(0, 8)
342
+ .map(r => ({
343
+ key: r.key,
344
+ name: r.name,
345
+ impact: r.impact,
346
+ category: r.category,
347
+ fix: r.fix,
348
+ why: GAP_REASONS[r.key] || r.fix,
349
+ }));
350
+ }
351
+
352
+ function toRecommendations(auditResult) {
353
+ const failed = auditResult.results.filter(r => r.passed === false);
354
+ const topActionOrder = new Map((auditResult.topNextActions || []).map((item, index) => [item.key, index]));
355
+ failed.sort((a, b) => {
356
+ const rankedA = topActionOrder.has(a.key) ? topActionOrder.get(a.key) : Number.MAX_SAFE_INTEGER;
357
+ const rankedB = topActionOrder.has(b.key) ? topActionOrder.get(b.key) : Number.MAX_SAFE_INTEGER;
358
+ if (rankedA !== rankedB) return rankedA - rankedB;
359
+ const order = { critical: 3, high: 2, medium: 1, low: 0 };
360
+ return (order[b.impact] || 0) - (order[a.impact] || 0);
361
+ });
362
+
363
+ return failed.slice(0, 10).map((r, index) => ({
364
+ priority: index + 1,
365
+ key: r.key,
366
+ name: r.name,
367
+ impact: r.impact,
368
+ module: moduleFromCategory(r.category),
369
+ risk: riskFromImpact(r.impact),
370
+ why: r.fix,
371
+ evidenceClass: (auditResult.topNextActions || []).find(item => item.key === r.key)?.evidenceClass || 'estimated',
372
+ rankingAdjustment: (auditResult.topNextActions || []).find(item => item.key === r.key)?.rankingAdjustment || 0,
373
+ }));
374
+ }
375
+
376
+ function buildOptionalModules(platform, stacks, assets, recommendedDomainPacks = []) {
377
+ if (platform === 'codex') {
378
+ const modules = [];
379
+
380
+ if (!assets.instructionPath) modules.push('AGENTS.md baseline');
381
+ if (!assets.configPath) modules.push('Codex config baseline');
382
+ if (assets.counts.rules === 0) modules.push('Codex rules baseline');
383
+ if (assets.counts.hooks === 0) modules.push('Hooks scaffold');
384
+ if (assets.counts.skills === 0) modules.push('Repo-local skills starter');
385
+ if (assets.counts.agents === 0) modules.push('Subagents starter');
386
+ if (assets.counts.mcpServers === 0) modules.push('MCP baseline');
387
+ if (assets.counts.workflows === 0) modules.push('CI / review workflow starter');
388
+ for (const pack of recommendedDomainPacks) {
389
+ for (const moduleName of pack.recommendedModules || []) {
390
+ modules.push(moduleName);
391
+ }
392
+ }
393
+
394
+ return [...new Set(modules)].slice(0, 8);
395
+ }
396
+
397
+ const stackKeys = stacks.map(s => s.key);
398
+ const modules = [];
399
+
400
+ if (!assets.files.claudeMd) modules.push('CLAUDE.md baseline');
401
+ if (assets.counts.commands === 0) modules.push('Slash commands');
402
+ if (assets.counts.hooks === 0) modules.push('Hooks automation');
403
+ if (!assets.permissions || !assets.permissions.hasDenyRules) modules.push('Permission safety profile');
404
+ if (assets.counts.rules === 0) modules.push('Path-specific rules');
405
+ if (stackKeys.some(k => ['react', 'nextjs', 'vue', 'angular', 'svelte'].includes(k))) modules.push('Frontend pack');
406
+ if (stackKeys.some(k => ['node', 'python', 'django', 'fastapi', 'go', 'rust', 'java'].includes(k))) modules.push('Backend pack');
407
+ if (stackKeys.some(k => ['docker', 'terraform', 'kubernetes'].includes(k))) modules.push('DevOps pack');
408
+ if (assets.counts.agents === 0) modules.push('Specialized agents');
409
+
410
+ return [...new Set(modules)].slice(0, 8);
411
+ }
412
+
413
+ function buildRiskNotes(platform, auditResult, assets, maturity) {
414
+ if (platform === 'codex') {
415
+ const notes = [];
416
+ if (!assets.instructionPath) notes.push('No AGENTS.md exists yet, so Codex starts without repo-specific instructions.');
417
+ if (!assets.configPath) notes.push('No .codex/config.toml exists yet, so approval, sandbox, and history posture are implicit.');
418
+ if (assets.trust && assets.trust.approvalPolicy === 'never') {
419
+ notes.push('approval_policy is set to `never`; make sure that autonomy level is truly intended for this repo.');
420
+ }
421
+ if (assets.trust && assets.trust.sandboxMode === 'danger-full-access') {
422
+ notes.push('sandbox_mode is `danger-full-access`, which removes Codex runtime guardrails and should stay exceptional.');
423
+ }
424
+ if (assets.counts.mcpServers > 0 && assets.trust && !assets.trust.isTrustedProject) {
425
+ notes.push('This repo appears to rely on project-scoped MCP, but the project trust path is not clearly established.');
426
+ }
427
+ if (maturity === 'mature') {
428
+ notes.push('This repo already has meaningful Codex assets, so advisory mode should preserve and extend them instead of flattening them.');
429
+ }
430
+ for (const caveat of auditResult.platformCaveats || []) {
431
+ if (caveat && caveat.message) {
432
+ notes.push(caveat.message);
433
+ }
434
+ }
435
+ return [...new Set(notes)].slice(0, 5);
436
+ }
437
+
438
+ const notes = [];
439
+ if (!assets.files.claudeMd) notes.push('No CLAUDE.md exists yet, so Claude has no persistent project-specific guidance.');
440
+ if (assets.permissions && assets.permissions.defaultMode === 'bypassPermissions') {
441
+ notes.push('Current settings use bypassPermissions, which is risky for broader team adoption.');
442
+ }
443
+ if (!assets.permissions || !assets.permissions.hasDenyRules) {
444
+ notes.push('Permissions lack deny rules, so secret access and destructive commands are not strongly guarded.');
445
+ }
446
+ if (maturity === 'mature') {
447
+ notes.push('This repo already has meaningful Claude assets, so augment mode should preserve existing structure instead of overwriting it.');
448
+ }
449
+ if (auditResult.results.some(r => r.key === 'ciPipeline' && r.passed === false)) {
450
+ notes.push('Without CI enforcement, readiness can drift after setup.');
451
+ }
452
+ return notes.slice(0, 5);
453
+ }
454
+
455
+ function buildRolloutOrder(report) {
456
+ if (report.platform === 'codex') {
457
+ const steps = [];
458
+ if (!report.existingPlatformAssets.instructionPath) steps.push('Create a project-specific AGENTS.md baseline');
459
+ if (!report.existingPlatformAssets.configPath) steps.push('Create a safe `.codex/config.toml` baseline with explicit trust settings');
460
+ if (report.recommendedDomainPacks.length > 0) {
461
+ steps.push(`Start from the ${report.recommendedDomainPacks.map((pack) => pack.label).join(' + ')} pack guidance before adding optional Codex surfaces`);
462
+ }
463
+ if (report.gapsIdentified.some(g => g.category === 'trust' || g.category === 'config')) steps.push('Make approval, sandbox, history, and network posture explicit');
464
+ if (report.gapsIdentified.some(g => g.category === 'rules')) steps.push('Add Codex rules for risky command classes before expanding automation');
465
+ if (report.gapsIdentified.some(g => g.category === 'mcp')) steps.push('Add MCP only where the repo really needs live external context and the trust boundary is clear');
466
+ if (report.gapsIdentified.some(g => g.category === 'skills' || g.category === 'agents')) steps.push('Add skills and subagents only after the baseline contract is stable');
467
+ if (report.gapsIdentified.some(g => g.category === 'review' || g.category === 'automation')) steps.push('Add review and CI automation after local verification is explicit');
468
+ return steps.length > 0 ? steps : ['Preserve the current Codex baseline and tighten remaining quality-deep items'];
469
+ }
470
+
471
+ const steps = [];
472
+ if (!report.existingClaudeAssets.claudeMd) steps.push('Create a project-specific CLAUDE.md baseline');
473
+ if (report.gapsIdentified.some(g => g.category === 'security')) steps.push('Add safe settings and deny rules');
474
+ if (report.gapsIdentified.some(g => g.category === 'automation')) steps.push('Add hooks and automate verification');
475
+ if (report.gapsIdentified.some(g => g.category === 'workflow')) steps.push('Add commands, rules, and specialization modules');
476
+ if (report.gapsIdentified.some(g => g.category === 'devops')) steps.push('Connect CI threshold enforcement');
477
+ if (steps.length === 0) steps.push('Tighten quality-deep items and preserve the current setup');
478
+ return steps;
479
+ }
480
+
481
+ /**
482
+ * Analyze a project's Claude Code setup and produce a structured recommendation report.
483
+ * @param {Object} options - Analysis options.
484
+ * @param {string} options.dir - Project directory to analyze.
485
+ * @param {string} [options.mode='augment'] - Analysis mode ('augment' or 'suggest-only').
486
+ * @returns {Promise<Object>} Structured report with project summary, gaps, strengths, and recommendations.
487
+ */
488
+ async function analyzeProject(options) {
489
+ const mode = options.mode || 'augment';
490
+ const platform = options.platform === 'codex' ? 'codex' : 'claude';
491
+ const platformLabel = platform === 'codex' ? 'Codex' : 'Claude';
492
+ const ContextClass = platform === 'codex' ? CodexProjectContext : ProjectContext;
493
+ const ctx = new ContextClass(options.dir);
494
+ const stacks = ctx.detectStacks(STACKS);
495
+ const auditResult = await audit({ ...options, silent: true, platform });
496
+ const assets = platform === 'codex' ? collectCodexAssets(ctx) : collectClaudeAssets(ctx);
497
+ const metadata = detectProjectMetadata(ctx);
498
+ const maturity = detectMaturity(platform, assets);
499
+ const mainDirs = detectMainDirs(ctx);
500
+ const recommendedDomainPacks = platform === 'codex'
501
+ ? detectCodexDomainPacks(ctx, stacks, assets)
502
+ : detectDomainPacks(ctx, stacks, assets);
503
+ const recommendedMcpPacks = platform === 'claude' ? recommendMcpPacks(stacks, recommendedDomainPacks, { ctx, assets }) : [];
504
+ const repoArchetype = buildRepoArchetypeProfile({
505
+ ctx,
506
+ platform,
507
+ stacks,
508
+ assets,
509
+ recommendedDomainPacks,
510
+ recommendedMcpPacks,
511
+ maturity,
512
+ });
513
+ const recommendedOperatingProfile = buildOperatingProfile({
514
+ dir: options.dir,
515
+ platform,
516
+ repoArchetype,
517
+ recommendedDomainPacks,
518
+ recommendedMcpPacks,
519
+ });
520
+ const adoptionGuidance = buildAdoptionAdvisor({
521
+ platform,
522
+ repoArchetype,
523
+ recommendedOperatingProfile,
524
+ recommendedDomainPacks,
525
+ recommendedMcpPacks,
526
+ env: options.env || {},
527
+ });
528
+
529
+ const report = {
530
+ platform,
531
+ platformLabel,
532
+ mode,
533
+ writeBehavior: 'No files are written in this mode.',
534
+ projectSummary: {
535
+ name: metadata.name,
536
+ description: metadata.description,
537
+ directory: options.dir,
538
+ stacks: stacks.map(s => s.label),
539
+ domains: recommendedDomainPacks.map(pack => pack.label),
540
+ maturity,
541
+ archetype: repoArchetype.label,
542
+ workflow: repoArchetype.primaryWorkflow.label,
543
+ riskLevel: repoArchetype.riskProfile.label,
544
+ operatingProfile: recommendedOperatingProfile.label,
545
+ adoptionPlan: adoptionGuidance.summary.label,
546
+ score: auditResult.score,
547
+ organicScore: auditResult.organicScore,
548
+ checkCount: auditResult.checkCount,
549
+ },
550
+ platformScopeNote: auditResult.platformScopeNote || null,
551
+ platformCaveats: auditResult.platformCaveats || [],
552
+ repoArchetype,
553
+ recommendedOperatingProfile,
554
+ adoptionGuidance,
555
+ detectedArchitecture: {
556
+ repoType: stacks.length > 0 ? 'stack-detected repo' : 'generic repo',
557
+ mainDirectories: mainDirs,
558
+ stackSignals: stacks.map(s => s.key),
559
+ stackFamily: repoArchetype.stackFamily.label,
560
+ topology: repoArchetype.topology.label,
561
+ workflow: repoArchetype.primaryWorkflow.label,
562
+ riskLevel: repoArchetype.riskProfile.label,
563
+ },
564
+ existingPlatformAssets: assets,
565
+ strengthsPreserved: toStrengths(auditResult.results),
566
+ gapsIdentified: toGaps(auditResult.results),
567
+ topNextActions: auditResult.topNextActions || auditResult.quickWins,
568
+ recommendedImprovements: toRecommendations(auditResult),
569
+ recommendedDomainPacks,
570
+ recommendedMcpPacks,
571
+ riskNotes: buildRiskNotes(platform, auditResult, assets, maturity),
572
+ optionalModules: buildOptionalModules(platform, stacks, assets, recommendedDomainPacks),
573
+ };
574
+
575
+ if (platform === 'claude') {
576
+ report.existingClaudeAssets = {
577
+ claudeMd: assets.files.claudeMd,
578
+ settings: assets.settingsSource,
579
+ commands: assets.files.commands,
580
+ rules: assets.files.rules,
581
+ hooks: assets.files.hooks,
582
+ agents: assets.files.agents,
583
+ skills: assets.files.skills,
584
+ mcpServers: assets.counts.mcpServers,
585
+ };
586
+ } else {
587
+ report.existingCodexAssets = {
588
+ agentsMd: assets.instructionPath,
589
+ config: assets.configPath,
590
+ rules: assets.files.rules,
591
+ hooks: assets.files.hooks,
592
+ skills: assets.files.skills,
593
+ agents: assets.files.agents,
594
+ workflows: assets.files.workflows,
595
+ mcpServers: assets.counts.mcpServers,
596
+ };
597
+ }
598
+
599
+ report.suggestedRolloutOrder = buildRolloutOrder(report);
600
+ return report;
601
+ }
602
+
603
+ function printAnalysis(report, options = {}) {
604
+ if (options.json) {
605
+ console.log(JSON.stringify(report, null, 2));
606
+ return;
607
+ }
608
+
609
+ const modeLabel = report.mode === 'suggest-only' ? 'suggest-only' : report.mode;
610
+ console.log('');
611
+ console.log(c(` nerviq ${report.platform === 'codex' ? 'codex ' : ''}${modeLabel}`, 'bold'));
612
+ console.log(c(' ═══════════════════════════════════════', 'dim'));
613
+ console.log(c(` ${report.writeBehavior}`, 'dim'));
614
+ if (report.platformScopeNote) {
615
+ console.log(c(` ${report.platformScopeNote.message}`, 'dim'));
616
+ }
617
+ console.log('');
618
+
619
+ console.log(c(' Project Summary', 'blue'));
620
+ console.log(` ${report.projectSummary.name}${report.projectSummary.description ? ` — ${report.projectSummary.description}` : ''}`);
621
+ console.log(c(` Stack: ${report.projectSummary.stacks.join(', ') || 'Unknown'}`, 'dim'));
622
+ if (report.platform === 'claude') {
623
+ console.log(c(` Domain packs: ${report.projectSummary.domains.join(', ') || 'Baseline General'}`, 'dim'));
624
+ } else {
625
+ console.log(c(` Platform: ${report.platformLabel}`, 'dim'));
626
+ }
627
+ console.log(c(` Archetype: ${report.repoArchetype.label} | Workflow: ${report.repoArchetype.primaryWorkflow.label} | Risk: ${report.repoArchetype.riskProfile.label}`, 'dim'));
628
+ console.log(c(` Maturity: ${report.projectSummary.maturity} | Score: ${report.projectSummary.score}/100 | Organic: ${report.projectSummary.organicScore}/100`, 'dim'));
629
+ console.log('');
630
+
631
+ console.log(c(' Detected Architecture', 'blue'));
632
+ console.log(c(` Stack family: ${report.repoArchetype.stackFamily.label} | Topology: ${report.repoArchetype.topology.label} | Confidence: ${report.repoArchetype.confidence}`, 'dim'));
633
+ console.log(c(` Main directories: ${report.detectedArchitecture.mainDirectories.join(', ') || 'No strong structure detected yet'}`, 'dim'));
634
+ console.log(c(` Signals: ${report.repoArchetype.signals.join(' | ') || 'No strong archetype signals yet'}`, 'dim'));
635
+ console.log('');
636
+
637
+ console.log(c(` Existing ${report.existingPlatformAssets.label} Assets`, 'blue'));
638
+ console.log(c(` ${report.existingPlatformAssets.instructionLabel}: ${report.existingPlatformAssets.instructionPath || 'missing'}`, 'dim'));
639
+ console.log(c(` ${report.existingPlatformAssets.configLabel}: ${report.existingPlatformAssets.configPath || 'missing'}`, 'dim'));
640
+ console.log(c(` ${report.existingPlatformAssets.summaryLine}`, 'dim'));
641
+ if (report.platform === 'codex' && report.existingPlatformAssets.trust) {
642
+ const trustBits = [
643
+ `Approval: ${report.existingPlatformAssets.trust.approvalPolicy || 'implicit'}`,
644
+ `Sandbox: ${report.existingPlatformAssets.trust.sandboxMode || 'implicit'}`,
645
+ `Trusted path: ${report.existingPlatformAssets.trust.isTrustedProject ? 'yes' : 'no'}`,
646
+ ];
647
+ console.log(c(` ${trustBits.join(' | ')}`, 'dim'));
648
+ }
649
+ console.log('');
650
+
651
+ if (report.strengthsPreserved.length > 0) {
652
+ console.log(c(` ${'\u2705'} Strengths Preserved (don't change these)`, 'green'));
653
+ for (const item of report.strengthsPreserved) {
654
+ const impactLabel = item.impact ? ` (${item.impact})` : '';
655
+ console.log(` ${c('\u2022', 'green')} ${item.name}${c(impactLabel, 'dim')}`);
656
+ }
657
+ console.log('');
658
+ }
659
+
660
+ if (report.gapsIdentified.length > 0) {
661
+ console.log(c(' Gaps Identified', 'yellow'));
662
+ for (const item of report.gapsIdentified.slice(0, 5)) {
663
+ console.log(` - [${item.impact}] ${item.name}`);
664
+ console.log(c(` ${item.fix}`, 'dim'));
665
+ }
666
+ console.log('');
667
+ }
668
+
669
+ if (report.topNextActions.length > 0) {
670
+ console.log(c(' Top 5 Next Actions', 'magenta'));
671
+ report.topNextActions.slice(0, 5).forEach((item, index) => {
672
+ console.log(` ${index + 1}. ${item.name}`);
673
+ console.log(c(` Why: ${item.why || item.fix}`, 'dim'));
674
+ if (Array.isArray(item.signals) && item.signals.length > 0) {
675
+ console.log(c(` Trace: ${item.signals.join(' | ')}`, 'dim'));
676
+ }
677
+ if (item.risk || item.confidence) {
678
+ console.log(c(` Risk: ${item.risk || 'low'} | Confidence: ${item.confidence || 'medium'}`, 'dim'));
679
+ }
680
+ if (item.fix && item.fix !== item.why) {
681
+ console.log(c(` Fix: ${item.fix}`, 'dim'));
682
+ }
683
+ });
684
+ console.log('');
685
+ }
686
+
687
+ if (report.recommendedDomainPacks.length > 0) {
688
+ console.log(c(' Recommended Domain Packs', 'blue'));
689
+ for (const pack of report.recommendedDomainPacks) {
690
+ console.log(` - ${pack.label}`);
691
+ console.log(c(` ${pack.useWhen}`, 'dim'));
692
+ }
693
+ console.log('');
694
+ }
695
+
696
+ if (report.recommendedMcpPacks.length > 0) {
697
+ console.log(c(' Recommended MCP Packs', 'blue'));
698
+ for (const pack of report.recommendedMcpPacks) {
699
+ console.log(` - ${pack.label}`);
700
+ console.log(c(` ${pack.adoption}`, 'dim'));
701
+ }
702
+ console.log('');
703
+ }
704
+
705
+ if (report.platformCaveats && report.platformCaveats.length > 0) {
706
+ console.log(c(' Platform Caveats', 'yellow'));
707
+ for (const item of report.platformCaveats) {
708
+ console.log(` - ${item.title}`);
709
+ console.log(c(` ${item.message}`, 'dim'));
710
+ }
711
+ console.log('');
712
+ }
713
+
714
+ if (report.riskNotes.length > 0) {
715
+ console.log(c(' Risk Notes', 'red'));
716
+ for (const note of report.riskNotes) {
717
+ console.log(` - ${note}`);
718
+ }
719
+ console.log('');
720
+ }
721
+
722
+ if (report.optionalModules.length > 0) {
723
+ console.log(c(' Optional Modules', 'blue'));
724
+ console.log(c(` ${report.optionalModules.join(' | ')}`, 'dim'));
725
+ console.log('');
726
+ }
727
+
728
+ if (report.recommendedOperatingProfile) {
729
+ console.log(c(' Recommended Operating Profile', 'blue'));
730
+ console.log(` ${report.recommendedOperatingProfile.label}`);
731
+ console.log(c(` Permission: ${report.recommendedOperatingProfile.permissionProfile.label} | Governance pack: ${report.recommendedOperatingProfile.governancePack.label}`, 'dim'));
732
+ console.log(c(` CI shape: ${report.recommendedOperatingProfile.ciShape.label} | Platforms: ${(report.recommendedOperatingProfile.platformSupport.recommended || []).join(', ') || report.platformLabel}`, 'dim'));
733
+ console.log(c(` Hooks: ${report.recommendedOperatingProfile.hooks.map((hook) => hook.key).join(', ')}`, 'dim'));
734
+ console.log(c(` Verification: ${report.recommendedOperatingProfile.verification.required.join(', ')}`, 'dim'));
735
+ console.log('');
736
+ }
737
+
738
+ if (report.adoptionGuidance && Array.isArray(report.adoptionGuidance.items) && report.adoptionGuidance.items.length > 0) {
739
+ console.log(c(' Adopt / Defer / Ignore', 'blue'));
740
+ console.log(c(` ${report.adoptionGuidance.summary.label}`, 'dim'));
741
+ const groups = [
742
+ ['adopt', 'Adopt now'],
743
+ ['defer', 'Defer until prerequisites are ready'],
744
+ ['ignore', 'Ignore for this repo shape'],
745
+ ];
746
+ for (const [decision, label] of groups) {
747
+ const items = report.adoptionGuidance.items.filter((item) => item.decision === decision).slice(0, 3);
748
+ if (items.length === 0) continue;
749
+ console.log(` ${label}`);
750
+ for (const item of items) {
751
+ console.log(` - ${item.label}`);
752
+ console.log(c(` ${item.why}`, 'dim'));
753
+ }
754
+ }
755
+ console.log('');
756
+ }
757
+
758
+ if (report.suggestedRolloutOrder.length > 0) {
759
+ console.log(c(' Suggested Rollout Order', 'blue'));
760
+ report.suggestedRolloutOrder.forEach((item, index) => {
761
+ console.log(` ${index + 1}. ${item}`);
762
+ });
763
+ console.log('');
764
+ }
765
+ }
766
+
767
+ /**
768
+ * Export an analysis report as a formatted markdown string.
769
+ * @param {Object} report - The report object returned by analyzeProject().
770
+ * @returns {string} Markdown-formatted report content.
771
+ */
772
+ function exportMarkdown(report) {
773
+ const lines = [];
774
+ lines.push(`# Nerviq Analysis Report`);
775
+ lines.push(`## ${report.platformLabel} ${report.mode === 'suggest-only' ? 'Suggest-Only' : 'Augment'} Mode`);
776
+ lines.push('');
777
+ lines.push(`**Project:** ${report.projectSummary.name}${report.projectSummary.description ? ` — ${report.projectSummary.description}` : ''}`);
778
+ lines.push(`**Date:** ${new Date().toISOString().split('T')[0]}`);
779
+ lines.push(`**Platform:** ${report.platformLabel}`);
780
+ lines.push(`**Score:** ${report.projectSummary.score}/100 | **Organic:** ${report.projectSummary.organicScore}/100`);
781
+ lines.push(`**Stacks:** ${report.projectSummary.stacks.join(', ') || 'None detected'}`);
782
+ if (report.platform === 'claude') {
783
+ lines.push(`**Domain Packs:** ${report.projectSummary.domains.join(', ') || 'Baseline General'}`);
784
+ }
785
+ lines.push(`**Archetype:** ${report.repoArchetype.label}`);
786
+ lines.push(`**Workflow:** ${report.repoArchetype.primaryWorkflow.label}`);
787
+ lines.push(`**Risk posture:** ${report.repoArchetype.riskProfile.label}`);
788
+ lines.push(`**Operating profile:** ${report.recommendedOperatingProfile.label}`);
789
+ lines.push(`**Adoption plan:** ${report.adoptionGuidance.summary.label}`);
790
+ lines.push(`**Maturity:** ${report.projectSummary.maturity}`);
791
+ lines.push('');
792
+
793
+ if (report.platformScopeNote) {
794
+ lines.push(`> ${report.platformScopeNote.message}`);
795
+ lines.push('');
796
+ }
797
+
798
+ lines.push(`## Existing ${report.existingPlatformAssets.label} Assets`);
799
+ lines.push('');
800
+ lines.push(`- **${report.existingPlatformAssets.instructionLabel}:** ${report.existingPlatformAssets.instructionPath || 'missing'}`);
801
+ lines.push(`- **${report.existingPlatformAssets.configLabel}:** ${report.existingPlatformAssets.configPath || 'missing'}`);
802
+ lines.push(`- **Summary:** ${report.existingPlatformAssets.summaryLine}`);
803
+ if (report.platform === 'codex' && report.existingPlatformAssets.trust) {
804
+ lines.push(`- **Approval policy:** ${report.existingPlatformAssets.trust.approvalPolicy || 'implicit'}`);
805
+ lines.push(`- **Sandbox mode:** ${report.existingPlatformAssets.trust.sandboxMode || 'implicit'}`);
806
+ lines.push(`- **Trusted project path:** ${report.existingPlatformAssets.trust.isTrustedProject ? 'yes' : 'no'}`);
807
+ }
808
+ lines.push('');
809
+
810
+ lines.push('## Repo Archetype');
811
+ lines.push('');
812
+ lines.push(`- **Label:** ${report.repoArchetype.label}`);
813
+ lines.push(`- **Summary:** ${report.repoArchetype.summary}`);
814
+ lines.push(`- **Stack family:** ${report.repoArchetype.stackFamily.label}`);
815
+ lines.push(`- **Topology:** ${report.repoArchetype.topology.label}`);
816
+ lines.push(`- **Primary workflow:** ${report.repoArchetype.primaryWorkflow.label}`);
817
+ lines.push(`- **Risk posture:** ${report.repoArchetype.riskProfile.label}`);
818
+ lines.push(`- **Confidence:** ${report.repoArchetype.confidence}`);
819
+ if (report.repoArchetype.signals.length > 0) {
820
+ lines.push(`- **Signals:** ${report.repoArchetype.signals.join(', ')}`);
821
+ }
822
+ lines.push('');
823
+
824
+ lines.push('## Recommended Operating Profile');
825
+ lines.push('');
826
+ lines.push(`- **Label:** ${report.recommendedOperatingProfile.label}`);
827
+ lines.push(`- **Summary:** ${report.recommendedOperatingProfile.summary}`);
828
+ lines.push(`- **Permission profile:** ${report.recommendedOperatingProfile.permissionProfile.label}`);
829
+ lines.push(`- **Governance pack:** ${report.recommendedOperatingProfile.governancePack.label}`);
830
+ lines.push(`- **Platform support:** ${(report.recommendedOperatingProfile.platformSupport.recommended || []).join(', ') || report.platformLabel}`);
831
+ if (report.recommendedOperatingProfile.platformSupport.optionalExpansion) {
832
+ lines.push(`- **Optional expansion:** ${report.recommendedOperatingProfile.platformSupport.optionalExpansion}`);
833
+ }
834
+ lines.push(`- **CI shape:** ${report.recommendedOperatingProfile.ciShape.label}`);
835
+ lines.push(`- **Verification:** ${report.recommendedOperatingProfile.verification.required.join(', ')}`);
836
+ lines.push(`- **Hooks:** ${report.recommendedOperatingProfile.hooks.map((hook) => hook.key).join(', ')}`);
837
+ lines.push('');
838
+
839
+ lines.push('## Adopt / Defer / Ignore');
840
+ lines.push('');
841
+ const decisionGroups = [
842
+ ['adopt', 'Adopt now'],
843
+ ['defer', 'Defer'],
844
+ ['ignore', 'Ignore'],
845
+ ];
846
+ for (const [decision, label] of decisionGroups) {
847
+ const items = report.adoptionGuidance.items.filter((item) => item.decision === decision);
848
+ if (items.length === 0) continue;
849
+ lines.push(`### ${label}`);
850
+ lines.push('');
851
+ for (const item of items) {
852
+ lines.push(`- **${item.label}** — ${item.why}`);
853
+ lines.push(` Evidence: ${item.evidence.join(' | ')}`);
854
+ lines.push(` Prerequisites: ${item.prerequisites.length > 0 ? item.prerequisites.join(' | ') : 'None'}`);
855
+ lines.push(` Expected benefit: ${item.expectedBenefit}`);
856
+ lines.push(` Rollback safety: ${item.rollbackSafety}`);
857
+ }
858
+ lines.push('');
859
+ }
860
+
861
+ if (report.strengthsPreserved.length > 0) {
862
+ lines.push('## Strengths Preserved (don\'t change these)');
863
+ lines.push('');
864
+ for (const item of report.strengthsPreserved) {
865
+ const impactLabel = item.impact ? ` (${item.impact})` : '';
866
+ lines.push(`- **${item.name}**${impactLabel} — ${item.why || 'Already configured.'}`);
867
+ }
868
+ lines.push('');
869
+ }
870
+
871
+ if (report.gapsIdentified.length > 0) {
872
+ lines.push('## Gaps Identified');
873
+ lines.push('');
874
+ lines.push('| Gap | Impact | Fix |');
875
+ lines.push('|-----|--------|-----|');
876
+ for (const item of report.gapsIdentified) {
877
+ lines.push(`| ${item.name} | ${item.impact} | ${item.fix} |`);
878
+ }
879
+ lines.push('');
880
+ }
881
+
882
+ if (report.topNextActions.length > 0) {
883
+ lines.push('## Top Next Actions');
884
+ lines.push('');
885
+ report.topNextActions.slice(0, 5).forEach((item, index) => {
886
+ lines.push(`${index + 1}. **${item.name}**`);
887
+ lines.push(` - Why: ${item.why || item.fix}`);
888
+ if (Array.isArray(item.signals) && item.signals.length > 0) {
889
+ lines.push(` - Trace: ${item.signals.join(' | ')}`);
890
+ }
891
+ if (item.risk || item.confidence) {
892
+ lines.push(` - Risk / Confidence: ${item.risk || 'low'} / ${item.confidence || 'medium'}`);
893
+ }
894
+ if (item.fix && item.fix !== item.why) {
895
+ lines.push(` - Fix: ${item.fix}`);
896
+ }
897
+ });
898
+ lines.push('');
899
+ }
900
+
901
+ if (report.recommendedDomainPacks.length > 0) {
902
+ lines.push('## Recommended Domain Packs');
903
+ lines.push('');
904
+ for (const pack of report.recommendedDomainPacks) {
905
+ lines.push(`- **${pack.label}**: ${pack.useWhen}`);
906
+ }
907
+ lines.push('');
908
+ }
909
+
910
+ if (report.recommendedMcpPacks.length > 0) {
911
+ lines.push('## Recommended MCP Packs');
912
+ lines.push('');
913
+ for (const pack of report.recommendedMcpPacks) {
914
+ lines.push(`- **${pack.label}**: ${pack.useWhen}`);
915
+ }
916
+ lines.push('');
917
+ }
918
+
919
+ if (report.platformCaveats && report.platformCaveats.length > 0) {
920
+ lines.push('## Platform Caveats');
921
+ lines.push('');
922
+ for (const item of report.platformCaveats) {
923
+ lines.push(`- **${item.title}**: ${item.message}`);
924
+ }
925
+ lines.push('');
926
+ }
927
+
928
+ if (report.riskNotes.length > 0) {
929
+ lines.push('## Risk Notes');
930
+ lines.push('');
931
+ for (const note of report.riskNotes) {
932
+ lines.push(`- ⚠️ ${note}`);
933
+ }
934
+ lines.push('');
935
+ }
936
+
937
+ if (report.suggestedRolloutOrder.length > 0) {
938
+ lines.push('## Suggested Rollout Order');
939
+ lines.push('');
940
+ report.suggestedRolloutOrder.forEach((item, index) => {
941
+ lines.push(`${index + 1}. ${item}`);
942
+ });
943
+ lines.push('');
944
+ }
945
+
946
+ lines.push('---');
947
+ lines.push(`*Generated by nerviq v${require('../package.json').version}*`);
948
+ return lines.join('\n');
949
+ }
950
+
951
+ module.exports = { analyzeProject, printAnalysis, exportMarkdown };