@nerviq/cli 0.0.1 → 0.9.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -0
  4. package/bin/cli.js +749 -0
  5. package/content/case-study-template.md +91 -0
  6. package/content/claims-governance.md +37 -0
  7. package/content/claude-code/audit-repo/SKILL.md +20 -0
  8. package/content/claude-native-integration.md +60 -0
  9. package/content/devto-article.json +9 -0
  10. package/content/launch-posts.md +226 -0
  11. package/content/pilot-rollout-kit.md +30 -0
  12. package/content/release-checklist.md +31 -0
  13. package/package.json +53 -4
  14. package/src/activity.js +529 -0
  15. package/src/aider/activity.js +226 -0
  16. package/src/aider/config-parser.js +166 -0
  17. package/src/aider/context.js +158 -0
  18. package/src/aider/deep-review.js +316 -0
  19. package/src/aider/domain-packs.js +278 -0
  20. package/src/aider/freshness.js +168 -0
  21. package/src/aider/governance.js +253 -0
  22. package/src/aider/interactive.js +334 -0
  23. package/src/aider/mcp-packs.js +98 -0
  24. package/src/aider/patch.js +214 -0
  25. package/src/aider/plans.js +186 -0
  26. package/src/aider/premium.js +360 -0
  27. package/src/aider/setup.js +404 -0
  28. package/src/aider/techniques.js +1323 -0
  29. package/src/analyze.js +821 -0
  30. package/src/audit.js +1003 -0
  31. package/src/badge.js +13 -0
  32. package/src/benchmark.js +339 -0
  33. package/src/claudex-sync.json +7 -0
  34. package/src/codex/activity.js +324 -0
  35. package/src/codex/config-parser.js +183 -0
  36. package/src/codex/context.js +221 -0
  37. package/src/codex/deep-review.js +493 -0
  38. package/src/codex/domain-packs.js +372 -0
  39. package/src/codex/freshness.js +167 -0
  40. package/src/codex/governance.js +192 -0
  41. package/src/codex/interactive.js +618 -0
  42. package/src/codex/mcp-packs.js +660 -0
  43. package/src/codex/patch.js +209 -0
  44. package/src/codex/plans.js +251 -0
  45. package/src/codex/premium.js +614 -0
  46. package/src/codex/setup.js +603 -0
  47. package/src/codex/techniques.js +2649 -0
  48. package/src/context.js +272 -0
  49. package/src/copilot/activity.js +309 -0
  50. package/src/copilot/config-parser.js +226 -0
  51. package/src/copilot/context.js +197 -0
  52. package/src/copilot/deep-review.js +346 -0
  53. package/src/copilot/domain-packs.js +350 -0
  54. package/src/copilot/freshness.js +197 -0
  55. package/src/copilot/governance.js +222 -0
  56. package/src/copilot/interactive.js +406 -0
  57. package/src/copilot/mcp-packs.js +572 -0
  58. package/src/copilot/patch.js +238 -0
  59. package/src/copilot/plans.js +253 -0
  60. package/src/copilot/premium.js +450 -0
  61. package/src/copilot/setup.js +488 -0
  62. package/src/copilot/techniques.js +1822 -0
  63. package/src/cursor/activity.js +301 -0
  64. package/src/cursor/config-parser.js +265 -0
  65. package/src/cursor/context.js +236 -0
  66. package/src/cursor/deep-review.js +334 -0
  67. package/src/cursor/domain-packs.js +346 -0
  68. package/src/cursor/freshness.js +214 -0
  69. package/src/cursor/governance.js +229 -0
  70. package/src/cursor/interactive.js +391 -0
  71. package/src/cursor/mcp-packs.js +571 -0
  72. package/src/cursor/patch.js +243 -0
  73. package/src/cursor/plans.js +254 -0
  74. package/src/cursor/premium.js +468 -0
  75. package/src/cursor/setup.js +488 -0
  76. package/src/cursor/techniques.js +1786 -0
  77. package/src/deep-review.js +345 -0
  78. package/src/domain-packs.js +364 -0
  79. package/src/formatters/sarif.js +115 -0
  80. package/src/gemini/activity.js +402 -0
  81. package/src/gemini/config-parser.js +275 -0
  82. package/src/gemini/context.js +221 -0
  83. package/src/gemini/deep-review.js +559 -0
  84. package/src/gemini/domain-packs.js +371 -0
  85. package/src/gemini/freshness.js +204 -0
  86. package/src/gemini/governance.js +201 -0
  87. package/src/gemini/interactive.js +860 -0
  88. package/src/gemini/mcp-packs.js +658 -0
  89. package/src/gemini/patch.js +229 -0
  90. package/src/gemini/plans.js +269 -0
  91. package/src/gemini/premium.js +759 -0
  92. package/src/gemini/setup.js +692 -0
  93. package/src/gemini/techniques.js +2084 -0
  94. package/src/governance.js +523 -0
  95. package/src/harmony/advisor.js +383 -0
  96. package/src/harmony/audit.js +303 -0
  97. package/src/harmony/canon.js +444 -0
  98. package/src/harmony/cli.js +331 -0
  99. package/src/harmony/drift.js +401 -0
  100. package/src/harmony/governance.js +313 -0
  101. package/src/harmony/memory.js +238 -0
  102. package/src/harmony/sync.js +458 -0
  103. package/src/harmony/watch.js +336 -0
  104. package/src/index.js +256 -0
  105. package/src/insights.js +119 -0
  106. package/src/interactive.js +118 -0
  107. package/src/mcp-packs.js +597 -0
  108. package/src/opencode/activity.js +286 -0
  109. package/src/opencode/config-parser.js +109 -0
  110. package/src/opencode/context.js +247 -0
  111. package/src/opencode/deep-review.js +313 -0
  112. package/src/opencode/domain-packs.js +240 -0
  113. package/src/opencode/freshness.js +158 -0
  114. package/src/opencode/governance.js +159 -0
  115. package/src/opencode/interactive.js +392 -0
  116. package/src/opencode/mcp-packs.js +474 -0
  117. package/src/opencode/patch.js +184 -0
  118. package/src/opencode/plans.js +231 -0
  119. package/src/opencode/premium.js +413 -0
  120. package/src/opencode/setup.js +449 -0
  121. package/src/opencode/techniques.js +1713 -0
  122. package/src/plans.js +655 -0
  123. package/src/secret-patterns.js +30 -0
  124. package/src/setup.js +1274 -0
  125. package/src/synergy/adaptive.js +261 -0
  126. package/src/synergy/compensation.js +156 -0
  127. package/src/synergy/evidence.js +193 -0
  128. package/src/synergy/learning.js +184 -0
  129. package/src/synergy/patterns.js +227 -0
  130. package/src/synergy/ranking.js +83 -0
  131. package/src/synergy/report.js +163 -0
  132. package/src/synergy/routing.js +152 -0
  133. package/src/techniques.js +1354 -0
  134. package/src/watch.js +229 -0
  135. package/src/windsurf/activity.js +302 -0
  136. package/src/windsurf/config-parser.js +267 -0
  137. package/src/windsurf/context.js +249 -0
  138. package/src/windsurf/deep-review.js +337 -0
  139. package/src/windsurf/domain-packs.js +348 -0
  140. package/src/windsurf/freshness.js +215 -0
  141. package/src/windsurf/governance.js +231 -0
  142. package/src/windsurf/interactive.js +388 -0
  143. package/src/windsurf/mcp-packs.js +535 -0
  144. package/src/windsurf/patch.js +231 -0
  145. package/src/windsurf/plans.js +247 -0
  146. package/src/windsurf/premium.js +467 -0
  147. package/src/windsurf/setup.js +471 -0
  148. package/src/windsurf/techniques.js +1758 -0
package/src/audit.js ADDED
@@ -0,0 +1,1003 @@
1
+ /**
2
+ * Audit engine - evaluates project against CLAUDEX technique database.
3
+ */
4
+
5
+ const { TECHNIQUES: CLAUDE_TECHNIQUES, STACKS } = require('./techniques');
6
+ const { ProjectContext } = require('./context');
7
+ const { CODEX_TECHNIQUES } = require('./codex/techniques');
8
+ const { detectCodexDomainPacks } = require('./codex/domain-packs');
9
+ const { CodexProjectContext, detectCodexVersion } = require('./codex/context');
10
+ const { GEMINI_TECHNIQUES } = require('./gemini/techniques');
11
+ const { detectGeminiDomainPacks } = require('./gemini/domain-packs');
12
+ const { GeminiProjectContext, detectGeminiVersion } = require('./gemini/context');
13
+ const { COPILOT_TECHNIQUES } = require('./copilot/techniques');
14
+ const { detectCopilotDomainPacks } = require('./copilot/domain-packs');
15
+ const { CopilotProjectContext } = require('./copilot/context');
16
+ const { CURSOR_TECHNIQUES } = require('./cursor/techniques');
17
+ const { detectCursorDomainPacks } = require('./cursor/domain-packs');
18
+ const { CursorProjectContext } = require('./cursor/context');
19
+ const { WINDSURF_TECHNIQUES } = require('./windsurf/techniques');
20
+ const { WindsurfProjectContext } = require('./windsurf/context');
21
+ const { AIDER_TECHNIQUES } = require('./aider/techniques');
22
+ const { AiderProjectContext } = require('./aider/context');
23
+ const { OPENCODE_TECHNIQUES } = require('./opencode/techniques');
24
+ const { OpenCodeProjectContext } = require('./opencode/context');
25
+ const { getBadgeMarkdown } = require('./badge');
26
+ const { sendInsights, getLocalInsights } = require('./insights');
27
+ const { getRecommendationOutcomeSummary, getRecommendationAdjustment } = require('./activity');
28
+ const { formatSarif } = require('./formatters/sarif');
29
+
30
+ const COLORS = {
31
+ reset: '\x1b[0m',
32
+ bold: '\x1b[1m',
33
+ dim: '\x1b[2m',
34
+ red: '\x1b[31m',
35
+ green: '\x1b[32m',
36
+ yellow: '\x1b[33m',
37
+ blue: '\x1b[36m',
38
+ magenta: '\x1b[35m',
39
+ };
40
+
41
+ function colorize(text, color) {
42
+ return `${COLORS[color] || ''}${text}${COLORS.reset}`;
43
+ }
44
+
45
+ function progressBar(score, max = 100, width = 20) {
46
+ const filled = Math.round((score / max) * width);
47
+ const empty = width - filled;
48
+ const color = score >= 70 ? 'green' : score >= 40 ? 'yellow' : 'red';
49
+ return colorize('█'.repeat(filled), color) + colorize('░'.repeat(empty), 'dim');
50
+ }
51
+
52
+ function formatLocation(file, line) {
53
+ if (!file) return null;
54
+ return line ? `${file}:${line}` : file;
55
+ }
56
+
57
+ const IMPACT_ORDER = { critical: 3, high: 2, medium: 1, low: 0 };
58
+ const WEIGHTS = { critical: 15, high: 10, medium: 5, low: 2 };
59
+ const CATEGORY_MODULES = {
60
+ memory: 'CLAUDE.md',
61
+ quality: 'verification',
62
+ git: 'safety',
63
+ workflow: 'commands-agents-skills',
64
+ security: 'permissions',
65
+ automation: 'hooks',
66
+ design: 'design-rules',
67
+ devops: 'ci-devops',
68
+ hygiene: 'project-hygiene',
69
+ performance: 'context-management',
70
+ tools: 'mcp-tools',
71
+ prompting: 'prompt-structure',
72
+ features: 'modern-claude-features',
73
+ 'quality-deep': 'quality-deep',
74
+ skills: 'skills',
75
+ agents: 'subagents',
76
+ review: 'review-workflow',
77
+ local: 'local-environment',
78
+ };
79
+ const ACTION_RATIONALES = {
80
+ noBypassPermissions: 'bypassPermissions skips the main safety layer. Explicit allow and deny rules create safer autonomy.',
81
+ secretsProtection: 'Without secret protection, Claude can accidentally inspect sensitive files and leak them into outputs.',
82
+ permissionDeny: 'Deny rules are the strongest way to prevent dangerous reads and destructive operations.',
83
+ settingsPermissions: 'Explicit permission settings make the workflow safer, more governable, and easier to review.',
84
+ testCommand: 'Without a test command, Claude cannot verify that its changes actually work before handoff.',
85
+ lintCommand: 'Without a lint command, Claude will miss formatting and style regressions that teams expect to catch automatically.',
86
+ buildCommand: 'Without a build command, compile and packaging failures stay invisible until later in the workflow.',
87
+ ciPipeline: 'CI is what turns a local setup improvement into a repeatable team-wide standard.',
88
+ securityReview: 'If you do not wire in security review guidance, high-risk changes are easier to ship without the right scrutiny.',
89
+ skills: 'Skills package reusable expertise so Claude does not need the same context re-explained every session.',
90
+ multipleAgents: 'Specialized agents unlock role-based work such as security review, implementation, and QA in parallel.',
91
+ multipleMcpServers: 'A richer MCP surface gives Claude access to live tools and documentation instead of stale assumptions.',
92
+ roleDefinition: 'A clear role definition calibrates how Claude thinks, explains, and validates work in this repo.',
93
+ importSyntax: 'Imported modules keep CLAUDE.md maintainable as the workflow grows more sophisticated.',
94
+ claudeMd: 'CLAUDE.md is the foundation of project-specific context. Without it, Claude starts every task half-blind.',
95
+ hooks: 'Hooks enforce the rules programmatically, which is much more reliable than relying on instructions alone.',
96
+ pathRules: 'Path-specific rules help Claude behave differently in different parts of the repo without global noise.',
97
+ context7Mcp: 'Live documentation reduces version drift and cuts down on confident but outdated answers.',
98
+ codexAgentsMd: 'AGENTS.md is the main Codex instruction surface. Without it, Codex starts without repo-specific guidance.',
99
+ codexAgentsMdSubstantive: 'A thin AGENTS.md is almost as bad as no AGENTS.md because Codex still lacks the repo context it needs.',
100
+ codexAgentsVerificationCommands: 'If AGENTS.md does not document how to verify work, Codex cannot reliably prove its own changes are safe.',
101
+ codexAgentsArchitecture: 'A small architecture map reduces navigation drift and helps Codex change the right part of the repo first.',
102
+ codexConfigExists: 'Without .codex/config.toml, trust and model behavior are implicit instead of explicit.',
103
+ codexReasoningEffortExplicit: 'Reasoning depth should be intentional for cost and latency, not left to implicit defaults.',
104
+ codexApprovalPolicyExplicit: 'Explicit approvals make Codex behavior predictable and reviewable across sessions.',
105
+ codexNoDangerFullAccess: 'danger-full-access removes the main safety boundary and should be treated as a critical risk.',
106
+ codexHistorySendToServerExplicit: 'History sync is a privacy and governance surface. Teams should decide it explicitly, not inherit it accidentally.',
107
+ codexNoSecretsInAgents: 'Secrets in AGENTS.md can leak directly into agent context, outputs, and logs.',
108
+ codexHooksWindowsCaveat: 'Windows does not support Codex hooks today, so relying on them there creates a false sense of runtime enforcement.',
109
+ codexSkillsDirPresentWhenUsed: 'Versioned repo-local skills are the safest way to keep Codex expertise reviewable and consistent across contributors.',
110
+ codexSkillsHaveMetadata: 'Without a usable SKILL.md, Codex cannot reliably decide when a skill should run or what it is for.',
111
+ codexSkillNamesKebabCase: 'Consistent skill naming improves discoverability and avoids invocation drift.',
112
+ codexSkillDescriptionsBounded: 'A bounded skill description helps Codex invoke the right skill without inflating prompt context.',
113
+ codexSkillsNoAutoRunRisk: 'Skills should guide Codex, not silently authorize risky automation or destructive actions.',
114
+ codexCustomAgentsRequiredFields: 'Custom agents need clear metadata and developer instructions so delegation stays predictable.',
115
+ codexMaxThreadsExplicit: 'Explicit fanout limits make Codex delegation safer and easier to reason about.',
116
+ codexMaxDepthExplicit: 'Nested delegation should be deliberate, not accidental.',
117
+ codexPerAgentSandboxOverridesSafe: 'Per-agent overrides can quietly bypass the main trust model if they are not constrained.',
118
+ codexExecUsageSafe: 'Unsafe Codex automation quickly turns small workflow mistakes into real repo damage.',
119
+ codexGitHubActionSafeStrategy: 'CI safety posture should be visible and intentional, especially when Codex is acting in automation.',
120
+ codexCiAuthUsesManagedKey: 'Managed secrets are the minimum trust boundary for Codex in CI.',
121
+ codexAutomationManuallyTested: 'Manual dry-runs catch automation footguns before they become scheduled failures.',
122
+ codexReviewWorkflowDocumented: 'A documented review path makes Codex safer to use on risky diffs and refactors.',
123
+ codexReviewModelOverrideExplicit: 'Explicit review model selection keeps review quality and cost predictable when automation is involved.',
124
+ codexWorkingTreeReviewExpectations: 'Codex reviews are much safer when the repo states how to treat staged, unstaged, and unrelated changes.',
125
+ codexCostAwarenessDocumented: 'Heavy workflows should be intentional, not the invisible default.',
126
+ codexArtifactsSharedIntentionally: 'If `.codex` is hidden from version control, the team loses a shared and reviewable Codex contract.',
127
+ codexLifecycleScriptsPlatformSafe: 'Local setup/teardown scripts are part of the trust model and should not surprise contributors on other platforms.',
128
+ codexActionsNotRedundant: 'Redundant automation expands the surface area without adding real value.',
129
+ codexWorktreeLifecycleDocumented: 'Parallel worktree flows need explicit setup and cleanup expectations.',
130
+ codexAgentsMentionModernFeatures: 'When the repo uses modern Codex surfaces, AGENTS.md should tell Codex they exist.',
131
+ codexNoDeprecatedPatterns: 'Deprecated Codex patterns create silent drift and confusing behavior over time.',
132
+ codexProfilesUsedWhenNeeded: 'Profiles become more important as Codex automation and delegation get more complex.',
133
+ codexPluginConfigValid: 'Broken plugin metadata creates discoverability and tooling drift.',
134
+ codexUndoExplicit: 'Undo is a user-facing safety feature and should be an explicit repo choice.',
135
+ };
136
+ const CODEX_HARD_FAIL_KEYS = new Set([
137
+ 'codexAgentsMd',
138
+ 'codexConfigValidToml',
139
+ 'codexNoDangerFullAccess',
140
+ 'codexApprovalPolicyExplicit',
141
+ 'codexNoSecretsInAgents',
142
+ 'codexHooksWindowsCaveat',
143
+ ]);
144
+ const CODEX_EVIDENCE_CLASSES = {
145
+ 'CX-A01': 'runtime',
146
+ 'CX-A02': 'derived',
147
+ 'CX-A03': 'derived',
148
+ 'CX-A04': 'derived',
149
+ 'CX-A05': 'mixed',
150
+ 'CX-A06': 'source',
151
+ 'CX-A07': 'derived',
152
+ 'CX-A08': 'derived',
153
+ 'CX-B01': 'runtime',
154
+ 'CX-B02': 'mixed',
155
+ 'CX-B03': 'mixed',
156
+ 'CX-B04': 'source',
157
+ 'CX-B05': 'source',
158
+ 'CX-B06': 'source',
159
+ 'CX-B07': 'source',
160
+ 'CX-B08': 'source',
161
+ 'CX-B09': 'source',
162
+ 'CX-C01': 'mixed',
163
+ 'CX-C02': 'mixed',
164
+ 'CX-C03': 'mixed',
165
+ 'CX-C04': 'derived',
166
+ 'CX-C05': 'source',
167
+ 'CX-C06': 'source',
168
+ 'CX-C07': 'mixed',
169
+ 'CX-C08': 'source',
170
+ 'CX-C09': 'mixed',
171
+ 'CX-D01': 'runtime',
172
+ 'CX-D02': 'mixed',
173
+ 'CX-D03': 'source',
174
+ 'CX-D04': 'mixed',
175
+ 'CX-D05': 'mixed',
176
+ 'CX-E01': 'mixed',
177
+ 'CX-E02': 'runtime',
178
+ 'CX-E03': 'mixed',
179
+ 'CX-E04': 'mixed',
180
+ 'CX-E05': 'source',
181
+ 'CX-F01': 'mixed',
182
+ 'CX-F02': 'mixed',
183
+ 'CX-F03': 'source',
184
+ 'CX-F04': 'mixed',
185
+ 'CX-F05': 'source',
186
+ 'CX-F06': 'source',
187
+ 'CX-G01': 'mixed',
188
+ 'CX-G02': 'source',
189
+ 'CX-G03': 'source',
190
+ 'CX-G04': 'derived',
191
+ 'CX-G05': 'derived',
192
+ 'CX-H01': 'source',
193
+ 'CX-H02': 'runtime',
194
+ 'CX-H03': 'runtime',
195
+ 'CX-H04': 'source',
196
+ 'CX-I01': 'mixed',
197
+ 'CX-I02': 'mixed',
198
+ 'CX-I03': 'source',
199
+ 'CX-I04': 'source',
200
+ 'CX-J01': 'source',
201
+ 'CX-J02': 'source',
202
+ 'CX-J03': 'source',
203
+ 'CX-J04': 'source',
204
+ 'CX-K01': 'source',
205
+ 'CX-K02': 'source',
206
+ 'CX-K03': 'source',
207
+ 'CX-K04': 'source',
208
+ 'CX-L01': 'derived',
209
+ 'CX-L02': 'source',
210
+ 'CX-L03': 'derived',
211
+ 'CX-L04': 'source',
212
+ 'CX-L05': 'source',
213
+ };
214
+ const CODEX_QUICKWIN_CONFIG_KEYS = new Set([
215
+ 'codexConfigExists',
216
+ 'codexModelExplicit',
217
+ 'codexReasoningEffortExplicit',
218
+ 'codexWeakModelExplicit',
219
+ 'codexProfilesUsedAppropriately',
220
+ 'codexFullAutoErrorModeExplicit',
221
+ 'codexHistorySendToServerExplicit',
222
+ 'codexNetworkAccessExplicit',
223
+ 'codexHooksDeliberate',
224
+ 'codexMcpStartupTimeoutReasonable',
225
+ 'codexMaxThreadsExplicit',
226
+ 'codexMaxDepthExplicit',
227
+ ]);
228
+ const CODEX_QUICKWIN_FILE_KEYS = new Set([
229
+ 'codexAgentsMd',
230
+ 'codexHooksJsonExistsWhenClaimed',
231
+ 'codexSkillsDirPresentWhenUsed',
232
+ ]);
233
+ const CODEX_QUICKWIN_DOC_KEYS = new Set([
234
+ 'codexAgentsArchitecture',
235
+ 'codexOverrideDocumented',
236
+ 'codexNoGenericFiller',
237
+ 'codexNoInstructionContradictions',
238
+ 'codexRulesExamplesPresent',
239
+ 'codexRuleWrapperRiskDocumented',
240
+ 'codexSkillsHaveMetadata',
241
+ 'codexSkillNamesKebabCase',
242
+ 'codexSkillDescriptionsBounded',
243
+ 'codexAutomationManuallyTested',
244
+ 'codexReviewWorkflowDocumented',
245
+ 'codexWorkingTreeReviewExpectations',
246
+ 'codexCostAwarenessDocumented',
247
+ ]);
248
+ const CODEX_QUICKWIN_POLICY_KEYS = new Set([
249
+ 'codexRulesSpecificPatterns',
250
+ 'codexNoBroadAllowAllRules',
251
+ 'codexMcpWhitelistsExplicit',
252
+ 'codexNoDeprecatedMcpTransport',
253
+ 'codexGitHubActionSafeStrategy',
254
+ 'codexProfilesUsedWhenNeeded',
255
+ 'codexUndoExplicit',
256
+ ]);
257
+ const CODEX_QUICKWIN_AVOID_KEYS = new Set([
258
+ 'codexNoDangerFullAccess',
259
+ 'codexApprovalPolicyExplicit',
260
+ 'codexGitHubActionUnsafeJustified',
261
+ 'codexProjectScopedMcpTrusted',
262
+ 'codexMcpAuthDocumented',
263
+ 'codexHooksWindowsCaveat',
264
+ 'codexNoSecretsInAgents',
265
+ 'codexPerAgentSandboxOverridesSafe',
266
+ 'codexExecUsageSafe',
267
+ 'codexCiAuthUsesManagedKey',
268
+ 'codexLifecycleScriptsPlatformSafe',
269
+ ]);
270
+
271
+ function getAuditSpec(platform = 'claude') {
272
+ if (platform === 'codex') {
273
+ return {
274
+ platform: 'codex',
275
+ platformLabel: 'Codex',
276
+ techniques: CODEX_TECHNIQUES,
277
+ ContextClass: CodexProjectContext,
278
+ platformVersion: detectCodexVersion(),
279
+ };
280
+ }
281
+
282
+ if (platform === 'gemini') {
283
+ return {
284
+ platform: 'gemini',
285
+ platformLabel: 'Gemini CLI',
286
+ techniques: GEMINI_TECHNIQUES,
287
+ ContextClass: GeminiProjectContext,
288
+ platformVersion: detectGeminiVersion(),
289
+ };
290
+ }
291
+
292
+ if (platform === 'copilot') {
293
+ return {
294
+ platform: 'copilot',
295
+ platformLabel: 'GitHub Copilot',
296
+ techniques: COPILOT_TECHNIQUES,
297
+ ContextClass: CopilotProjectContext,
298
+ platformVersion: null,
299
+ };
300
+ }
301
+
302
+ if (platform === 'cursor') {
303
+ return {
304
+ platform: 'cursor',
305
+ platformLabel: 'Cursor',
306
+ techniques: CURSOR_TECHNIQUES,
307
+ ContextClass: CursorProjectContext,
308
+ platformVersion: null,
309
+ };
310
+ }
311
+
312
+ if (platform === 'windsurf') {
313
+ return {
314
+ platform: 'windsurf',
315
+ platformLabel: 'Windsurf',
316
+ techniques: WINDSURF_TECHNIQUES,
317
+ ContextClass: WindsurfProjectContext,
318
+ platformVersion: null,
319
+ };
320
+ }
321
+
322
+ if (platform === 'aider') {
323
+ return {
324
+ platform: 'aider',
325
+ platformLabel: 'Aider',
326
+ techniques: AIDER_TECHNIQUES,
327
+ ContextClass: AiderProjectContext,
328
+ platformVersion: null,
329
+ };
330
+ }
331
+
332
+ if (platform === 'opencode') {
333
+ return {
334
+ platform: 'opencode',
335
+ platformLabel: 'OpenCode',
336
+ techniques: OPENCODE_TECHNIQUES,
337
+ ContextClass: OpenCodeProjectContext,
338
+ platformVersion: null,
339
+ };
340
+ }
341
+
342
+ return {
343
+ platform: 'claude',
344
+ platformLabel: 'Claude',
345
+ techniques: CLAUDE_TECHNIQUES,
346
+ ContextClass: ProjectContext,
347
+ platformVersion: null,
348
+ };
349
+ }
350
+
351
+ function riskFromImpact(impact) {
352
+ if (impact === 'critical') return 'high';
353
+ if (impact === 'high') return 'medium';
354
+ return 'low';
355
+ }
356
+
357
+ function confidenceFromImpact(impact) {
358
+ return impact === 'critical' || impact === 'high' ? 'high' : 'medium';
359
+ }
360
+
361
+ function getPrioritizedFailed(failed) {
362
+ const prioritized = failed.filter(r => !(r.category === 'hygiene' && r.impact === 'low'));
363
+ return prioritized.length > 0 ? prioritized : failed;
364
+ }
365
+
366
+ function codexEvidenceClass(item) {
367
+ return CODEX_EVIDENCE_CLASSES[item.id] || 'derived';
368
+ }
369
+
370
+ function codexCategoryBonus(category) {
371
+ if (category === 'trust' || category === 'config') return 12;
372
+ if (category === 'rules' || category === 'hooks' || category === 'mcp') return 8;
373
+ if (category === 'instructions') return 4;
374
+ return 0;
375
+ }
376
+
377
+ function codexEvidenceBonus(item) {
378
+ const evidenceClass = codexEvidenceClass(item);
379
+ if (evidenceClass === 'runtime') return 8;
380
+ if (evidenceClass === 'mixed') return 6;
381
+ if (evidenceClass === 'source') return 3;
382
+ return 0;
383
+ }
384
+
385
+ function codexPriorityScore(item, outcomeSummaryByKey = {}) {
386
+ const impactBase = item.impact === 'critical'
387
+ ? 60
388
+ : item.impact === 'high'
389
+ ? 40
390
+ : item.impact === 'medium'
391
+ ? 20
392
+ : 8;
393
+ const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key) * 10;
394
+ const hardFailBonus = CODEX_HARD_FAIL_KEYS.has(item.key) ? 12 : 0;
395
+ return Math.max(0, Math.min(100, impactBase + codexCategoryBonus(item.category) + codexEvidenceBonus(item) + hardFailBonus + feedbackAdjustment));
396
+ }
397
+
398
+ function codexQuickWinScore(item) {
399
+ if (CODEX_QUICKWIN_AVOID_KEYS.has(item.key)) {
400
+ return -100;
401
+ }
402
+
403
+ let score = 0;
404
+ if (CODEX_QUICKWIN_CONFIG_KEYS.has(item.key)) {
405
+ score += 40;
406
+ } else if (CODEX_QUICKWIN_FILE_KEYS.has(item.key)) {
407
+ score += 34;
408
+ } else if (CODEX_QUICKWIN_DOC_KEYS.has(item.key)) {
409
+ score += 26;
410
+ } else if (CODEX_QUICKWIN_POLICY_KEYS.has(item.key)) {
411
+ score += 20;
412
+ }
413
+
414
+ score += item.impact === 'low' ? 8 : item.impact === 'medium' ? 6 : item.impact === 'high' ? 4 : 0;
415
+ score -= Math.min((item.fix || '').length, 240) / 24;
416
+ return score;
417
+ }
418
+
419
+ function getQuickWins(failed, options = {}) {
420
+ const pool = getPrioritizedFailed(failed);
421
+
422
+ if (options.platform === 'codex') {
423
+ const codexPool = pool.filter((item) => !CODEX_QUICKWIN_AVOID_KEYS.has(item.key));
424
+ const rankedPool = (codexPool.length > 0 ? codexPool : pool)
425
+ .slice()
426
+ .sort((a, b) => codexQuickWinScore(b) - codexQuickWinScore(a));
427
+ return rankedPool.slice(0, 3);
428
+ }
429
+
430
+ // QuickWins prioritize short fixes (easy to implement) first, then impact
431
+ return [...pool]
432
+ .sort((a, b) => {
433
+ const fixLenA = (a.fix || '').length;
434
+ const fixLenB = (b.fix || '').length;
435
+ if (fixLenA !== fixLenB) return fixLenA - fixLenB;
436
+ const impactA = IMPACT_ORDER[a.impact] ?? 0;
437
+ const impactB = IMPACT_ORDER[b.impact] ?? 0;
438
+ return impactB - impactA;
439
+ })
440
+ .slice(0, 3);
441
+ }
442
+
443
+ function getRecommendationPriorityScore(item, outcomeSummaryByKey = {}) {
444
+ const impactScore = (IMPACT_ORDER[item.impact] ?? 0) * 100;
445
+ const feedbackAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, item.key);
446
+ const brevityPenalty = Math.min((item.fix || '').length, 240) / 20;
447
+ return impactScore + (feedbackAdjustment * 10) - brevityPenalty;
448
+ }
449
+
450
+ function buildTopNextActions(failed, limit = 5, outcomeSummaryByKey = {}, options = {}) {
451
+ const pool = getPrioritizedFailed(failed);
452
+
453
+ return [...pool]
454
+ .sort((a, b) => {
455
+ const scoreB = options.platform === 'codex'
456
+ ? codexPriorityScore(b, outcomeSummaryByKey)
457
+ : getRecommendationPriorityScore(b, outcomeSummaryByKey);
458
+ const scoreA = options.platform === 'codex'
459
+ ? codexPriorityScore(a, outcomeSummaryByKey)
460
+ : getRecommendationPriorityScore(a, outcomeSummaryByKey);
461
+ return scoreB - scoreA;
462
+ })
463
+ .slice(0, limit)
464
+ .map(({ key, id, name, impact, fix, category }) => {
465
+ const feedback = outcomeSummaryByKey[key] || null;
466
+ const rankingAdjustment = getRecommendationAdjustment(outcomeSummaryByKey, key);
467
+ const signals = [
468
+ `failed-check:${key}`,
469
+ `impact:${impact}`,
470
+ `category:${category}`,
471
+ ];
472
+ if (feedback) {
473
+ signals.push(`feedback:${feedback.total}`);
474
+ signals.push(`ranking-adjustment:${rankingAdjustment >= 0 ? '+' : ''}${rankingAdjustment}`);
475
+ }
476
+
477
+ const fullItem = pool.find((item) => item.key === key) || { key, id, name, impact, fix, category };
478
+ const evidenceClass = options.platform === 'codex' ? codexEvidenceClass(fullItem) : (feedback ? 'measured' : 'estimated');
479
+ const priorityScore = options.platform === 'codex'
480
+ ? codexPriorityScore(fullItem, outcomeSummaryByKey)
481
+ : Math.max(0, Math.min(100, Math.round(getRecommendationPriorityScore(fullItem, outcomeSummaryByKey) / 3)));
482
+
483
+ signals.push(`evidence:${evidenceClass}`);
484
+ if (options.platform === 'codex' && CODEX_HARD_FAIL_KEYS.has(key)) {
485
+ signals.push('hard-fail:true');
486
+ }
487
+
488
+ return ({
489
+ key,
490
+ id,
491
+ name,
492
+ impact,
493
+ category,
494
+ module: CATEGORY_MODULES[category] || category,
495
+ fix,
496
+ priorityScore,
497
+ why: ACTION_RATIONALES[key] || fix,
498
+ risk: riskFromImpact(impact),
499
+ confidence: confidenceFromImpact(impact),
500
+ signals,
501
+ evidenceClass,
502
+ rankingAdjustment,
503
+ feedback: feedback ? {
504
+ total: feedback.total,
505
+ accepted: feedback.accepted,
506
+ rejected: feedback.rejected,
507
+ deferred: feedback.deferred,
508
+ positive: feedback.positive,
509
+ negative: feedback.negative,
510
+ avgScoreDelta: feedback.avgScoreDelta,
511
+ } : null,
512
+ });
513
+ });
514
+ }
515
+
516
+ function computeCategoryScores(applicable, passed) {
517
+ const grouped = {};
518
+
519
+ for (const item of applicable) {
520
+ const category = item.category || 'unknown';
521
+ if (!grouped[category]) {
522
+ grouped[category] = { passed: 0, total: 0, earnedPoints: 0, maxPoints: 0 };
523
+ }
524
+ grouped[category].total += 1;
525
+ grouped[category].maxPoints += WEIGHTS[item.impact] || 5;
526
+ }
527
+
528
+ for (const item of passed) {
529
+ const category = item.category || 'unknown';
530
+ if (!grouped[category]) continue;
531
+ grouped[category].passed += 1;
532
+ grouped[category].earnedPoints += WEIGHTS[item.impact] || 5;
533
+ }
534
+
535
+ const result = {};
536
+ for (const [category, summary] of Object.entries(grouped)) {
537
+ result[category] = {
538
+ ...summary,
539
+ score: summary.maxPoints > 0 ? Math.round((summary.earnedPoints / summary.maxPoints) * 100) : 0,
540
+ };
541
+ }
542
+
543
+ return result;
544
+ }
545
+
546
+ function inferSuggestedNextCommand(result) {
547
+ if (result.platform === 'codex') {
548
+ if (result.failed === 0) {
549
+ return 'npx nerviq --platform codex augment';
550
+ }
551
+
552
+ const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
553
+ if (
554
+ result.score < 50 ||
555
+ actionKeys.has('codexAgentsMd') ||
556
+ actionKeys.has('codexConfigExists') ||
557
+ actionKeys.has('codexNoDangerFullAccess') ||
558
+ actionKeys.has('codexApprovalPolicyExplicit')
559
+ ) {
560
+ return 'npx nerviq --platform codex suggest-only';
561
+ }
562
+
563
+ return 'npx nerviq --platform codex augment';
564
+ }
565
+
566
+ const actionKeys = new Set((result.topNextActions || []).map(item => item.key));
567
+
568
+ if (result.failed === 0) {
569
+ return 'npx nerviq augment';
570
+ }
571
+
572
+ if (
573
+ result.score < 50 ||
574
+ actionKeys.has('claudeMd') ||
575
+ actionKeys.has('hooks') ||
576
+ actionKeys.has('settingsPermissions') ||
577
+ actionKeys.has('permissionDeny')
578
+ ) {
579
+ return 'npx nerviq setup';
580
+ }
581
+
582
+ if (result.score < 80) {
583
+ return 'npx nerviq suggest-only';
584
+ }
585
+
586
+ return 'npx nerviq augment';
587
+ }
588
+
589
+ function getPlatformScopeNote(spec, ctx) {
590
+ if (spec.platform !== 'codex') {
591
+ return null;
592
+ }
593
+
594
+ const hasClaudeSurface = Boolean(
595
+ (typeof ctx.fileContent === 'function' && ctx.fileContent('CLAUDE.md')) ||
596
+ (typeof ctx.hasDir === 'function' && ctx.hasDir('.claude'))
597
+ );
598
+
599
+ if (!hasClaudeSurface) {
600
+ return null;
601
+ }
602
+
603
+ return {
604
+ kind: 'codex-only-pass',
605
+ message: 'This is a Codex-only pass. Claude Code surfaces were also detected and should be audited separately with `npx nerviq`.',
606
+ };
607
+ }
608
+
609
+ function getPlatformCaveats(spec, ctx) {
610
+ if (spec.platform !== 'codex') {
611
+ return [];
612
+ }
613
+
614
+ const caveats = [];
615
+ const hooksJson = typeof ctx.hooksJsonContent === 'function' ? (ctx.hooksJsonContent() || '') : '';
616
+ const agentsContent = typeof ctx.agentsMdContent === 'function' ? (ctx.agentsMdContent() || '') : '';
617
+ const hooksClaimed = Boolean(
618
+ hooksJson ||
619
+ (typeof ctx.hasDir === 'function' && ctx.hasDir('.codex/hooks')) ||
620
+ /\bhooks?\b|\bSessionStart\b|\bPreToolUse\b|\bPostToolUse\b|\bUserPromptSubmit\b|\bStop\b/i.test(agentsContent)
621
+ );
622
+
623
+ if (process.platform === 'win32') {
624
+ caveats.push({
625
+ key: 'codex-windows-hooks',
626
+ severity: hooksClaimed ? 'critical' : 'info',
627
+ title: 'Codex hooks are not available on Windows',
628
+ message: hooksClaimed
629
+ ? 'This repo claims Codex hooks, but native Windows sessions do not execute them. Keep enforcement in rules, CI, or another documented fallback.'
630
+ : 'Native Windows sessions do not execute Codex hooks. If you add hooks later, treat them as non-enforcing on Windows and keep critical enforcement in rules or CI.',
631
+ file: hooksJson ? '.codex/hooks.json' : null,
632
+ line: hooksJson ? 1 : null,
633
+ });
634
+ }
635
+
636
+ const maxThreads = typeof ctx.configValue === 'function' ? ctx.configValue('agents.max_threads') : undefined;
637
+ caveats.push({
638
+ key: 'codex-max-threads-default',
639
+ severity: typeof maxThreads === 'number' && maxThreads > 6 ? 'warning' : 'info',
640
+ title: 'Codex agent thread concurrency defaults to 6 when unset',
641
+ message: typeof maxThreads === 'number'
642
+ ? `This repo sets agents.max_threads = ${maxThreads}. Codex defaults to 6 when unset, so any higher concurrency assumption should be validated in the runtime you actually use.`
643
+ : 'Codex defaults agents.max_threads to 6 when unset. If your workflow depends on heavy parallel subagent usage, set it intentionally and validate the behavior in your real runtime.',
644
+ file: typeof ctx.fileContent === 'function' && ctx.fileContent('.codex/config.toml') ? '.codex/config.toml' : null,
645
+ line: typeof ctx.lineNumber === 'function' ? (ctx.lineNumber('.codex/config.toml', /\bagents\.max_threads\b|\bmax_threads\b/i) || null) : null,
646
+ });
647
+
648
+ return caveats;
649
+ }
650
+
651
+ function getCodexDomainPackSignals(ctx) {
652
+ return {
653
+ instructionPath: typeof ctx.agentsMdPath === 'function' ? ctx.agentsMdPath() : null,
654
+ trust: {
655
+ approvalPolicy: typeof ctx.configValue === 'function' ? (ctx.configValue('approval_policy') || null) : null,
656
+ sandboxMode: typeof ctx.configValue === 'function' ? (ctx.configValue('sandbox_mode') || null) : null,
657
+ isTrustedProject: typeof ctx.isProjectTrusted === 'function' ? ctx.isProjectTrusted() : false,
658
+ },
659
+ counts: {
660
+ rules: typeof ctx.ruleFiles === 'function' ? ctx.ruleFiles().length : 0,
661
+ workflows: typeof ctx.workflowFiles === 'function' ? ctx.workflowFiles().length : 0,
662
+ mcpServers: typeof ctx.mcpServers === 'function' ? Object.keys(ctx.mcpServers() || {}).length : 0,
663
+ },
664
+ };
665
+ }
666
+
667
+ function printLiteAudit(result, dir) {
668
+ console.log('');
669
+ const productLabel = result.platform === 'codex' ? 'nerviq codex quick scan' : 'nerviq quick scan';
670
+ console.log(colorize(` ${productLabel}`, 'bold'));
671
+ console.log(colorize(' ═══════════════════════════════════════', 'dim'));
672
+ console.log(colorize(` Scanning: ${dir}`, 'dim'));
673
+ console.log('');
674
+ console.log(` Score: ${colorize(`${result.score}/100`, 'bold')}`);
675
+ if (result.platformScopeNote) {
676
+ console.log(colorize(` Scope: ${result.platformScopeNote.message}`, 'dim'));
677
+ }
678
+ if (result.platformCaveats && result.platformCaveats.length > 0) {
679
+ console.log(colorize(' Platform caveats:', 'yellow'));
680
+ result.platformCaveats.slice(0, 2).forEach((item) => {
681
+ console.log(colorize(` - ${item.title}: ${item.message}`, 'dim'));
682
+ });
683
+ }
684
+ console.log('');
685
+
686
+ if (result.failed === 0) {
687
+ const platformLabel = result.platform === 'codex' ? 'Codex' : 'Claude';
688
+ console.log(colorize(` Your ${platformLabel} setup looks solid.`, 'green'));
689
+ console.log(` Next: ${colorize(result.suggestedNextCommand, 'bold')}`);
690
+ if (result.platform === 'codex') {
691
+ console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
692
+ }
693
+ console.log('');
694
+ return;
695
+ }
696
+
697
+ console.log(colorize(' Top 3 things to fix right now:', 'magenta'));
698
+ console.log('');
699
+ result.liteSummary.topNextActions.forEach((item, index) => {
700
+ console.log(` ${index + 1}. ${colorize(item.name, 'bold')}`);
701
+ console.log(colorize(` Why: ${item.why}`, 'dim'));
702
+ console.log(colorize(` Fix: ${item.fix}`, 'dim'));
703
+ });
704
+ console.log('');
705
+ console.log(` Ready? Run: ${colorize(result.suggestedNextCommand, 'bold')}`);
706
+ if (result.platform === 'codex') {
707
+ console.log(colorize(' Note: Codex now supports no-write advisory flows via augment and suggest-only before setup/apply.', 'dim'));
708
+ }
709
+ console.log('');
710
+ }
711
+
712
+ /**
713
+ * Run a full audit of a project's Claude Code setup against the CLAUDEX technique database.
714
+ * @param {Object} options - Audit options.
715
+ * @param {string} options.dir - Project directory to audit.
716
+ * @param {boolean} [options.silent] - Skip all console output, return result only.
717
+ * @param {boolean} [options.json] - Output result as JSON.
718
+ * @param {boolean} [options.lite] - Show short top-3 quick scan.
719
+ * @param {boolean} [options.verbose] - Show all recommendations including medium-impact.
720
+ * @returns {Promise<Object>} Audit result with score, passed/failed counts, quickWins, and topNextActions.
721
+ */
722
+ async function audit(options) {
723
+ const spec = getAuditSpec(options.platform || 'claude');
724
+ const silent = options.silent || false;
725
+ const ctx = new spec.ContextClass(options.dir);
726
+ const stacks = ctx.detectStacks(STACKS);
727
+ const results = [];
728
+ const outcomeSummary = getRecommendationOutcomeSummary(options.dir);
729
+
730
+ // Run all technique checks
731
+ for (const [key, technique] of Object.entries(spec.techniques)) {
732
+ const passed = technique.check(ctx);
733
+ const file = typeof technique.file === 'function' ? (technique.file(ctx) ?? null) : (technique.file ?? null);
734
+ const line = typeof technique.line === 'function' ? (technique.line(ctx) ?? null) : (technique.line ?? null);
735
+ results.push({
736
+ key,
737
+ ...technique,
738
+ file,
739
+ line: Number.isFinite(line) ? line : null,
740
+ passed,
741
+ });
742
+ }
743
+
744
+ // null = not applicable (skip), true = pass, false = fail
745
+ const applicable = results.filter(r => r.passed !== null);
746
+ const skipped = results.filter(r => r.passed === null);
747
+ const passed = applicable.filter(r => r.passed);
748
+ const failed = applicable.filter(r => !r.passed);
749
+ const critical = failed.filter(r => r.impact === 'critical');
750
+ const high = failed.filter(r => r.impact === 'high');
751
+ const medium = failed.filter(r => r.impact === 'medium');
752
+
753
+ // Calculate score only from applicable checks
754
+ const maxScore = applicable.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
755
+ const earnedScore = passed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
756
+ const score = maxScore > 0 ? Math.round((earnedScore / maxScore) * 100) : 0;
757
+
758
+ // Detect scaffolded vs organic: if CLAUDE.md contains our version stamp, some checks
759
+ // are passing because WE generated them, not the user
760
+ const instructionSource = spec.platform === 'codex'
761
+ ? (ctx.agentsMdContent ? (ctx.agentsMdContent() || '') : '')
762
+ : (ctx.claudeMdContent() || '');
763
+ const isScaffolded = instructionSource.includes('Generated by nerviq') ||
764
+ instructionSource.includes('nerviq');
765
+ // Scaffolded checks: things our setup creates (CLAUDE.md / AGENTS.md, hooks, commands, agents, rules, skills)
766
+ const scaffoldedKeys = spec.platform === 'codex'
767
+ ? new Set([
768
+ 'codexAgentsMd',
769
+ 'codexAgentsMdSubstantive',
770
+ 'codexAgentsVerificationCommands',
771
+ 'codexAgentsArchitecture',
772
+ 'codexConfigExists',
773
+ 'codexModelExplicit',
774
+ 'codexReasoningEffortExplicit',
775
+ 'codexWeakModelExplicit',
776
+ 'codexSandboxModeExplicit',
777
+ 'codexApprovalPolicyExplicit',
778
+ 'codexFullAutoErrorModeExplicit',
779
+ 'codexHistorySendToServerExplicit',
780
+ ])
781
+ : new Set(['claudeMd', 'mermaidArchitecture', 'verificationLoop',
782
+ 'hooks', 'customCommands', 'multipleCommands', 'agents', 'pathRules', 'multipleRules',
783
+ 'skills', 'hooksConfigured', 'preToolUseHook', 'postToolUseHook', 'fewShotExamples',
784
+ 'constraintBlocks', 'xmlTags']);
785
+ const organicPassed = passed.filter(r => !scaffoldedKeys.has(r.key));
786
+ const scaffoldedPassed = passed.filter(r => scaffoldedKeys.has(r.key));
787
+ const organicEarned = organicPassed.reduce((sum, r) => sum + (WEIGHTS[r.impact] || 5), 0);
788
+ const organicScore = maxScore > 0 ? Math.round((organicEarned / maxScore) * 100) : 0;
789
+ const quickWins = getQuickWins(failed, { platform: spec.platform });
790
+ const topNextActions = buildTopNextActions(failed, 5, outcomeSummary.byKey, { platform: spec.platform });
791
+ const categoryScores = computeCategoryScores(applicable, passed);
792
+ const platformScopeNote = getPlatformScopeNote(spec, ctx);
793
+ const platformCaveats = getPlatformCaveats(spec, ctx);
794
+ const recommendedDomainPacks = spec.platform === 'codex'
795
+ ? detectCodexDomainPacks(ctx, stacks, getCodexDomainPackSignals(ctx))
796
+ : [];
797
+ const result = {
798
+ platform: spec.platform,
799
+ platformLabel: spec.platformLabel,
800
+ platformVersion: spec.platformVersion,
801
+ score,
802
+ organicScore,
803
+ earnedPoints: earnedScore,
804
+ maxPoints: maxScore,
805
+ isScaffolded,
806
+ passed: passed.length,
807
+ failed: failed.length,
808
+ skipped: skipped.length,
809
+ checkCount: applicable.length,
810
+ stacks,
811
+ results,
812
+ categoryScores,
813
+ quickWins: quickWins.map(({ key, name, impact, fix, category }) => ({ key, name, impact, category, fix })),
814
+ topNextActions,
815
+ recommendationOutcomes: {
816
+ totalEntries: outcomeSummary.totalEntries,
817
+ keysTracked: outcomeSummary.keys,
818
+ },
819
+ platformScopeNote,
820
+ platformCaveats,
821
+ recommendedDomainPacks,
822
+ };
823
+ result.suggestedNextCommand = inferSuggestedNextCommand(result);
824
+ result.liteSummary = {
825
+ topNextActions: topNextActions.slice(0, 3),
826
+ nextCommand: result.suggestedNextCommand,
827
+ platformCaveats: platformCaveats.slice(0, 2),
828
+ };
829
+
830
+ // Silent mode: skip all output, just return result
831
+ if (silent) {
832
+ return result;
833
+ }
834
+
835
+ if (options.json) {
836
+ const { version } = require('../package.json');
837
+ console.log(JSON.stringify({
838
+ version,
839
+ timestamp: new Date().toISOString(),
840
+ ...result
841
+ }, null, 2));
842
+ return result;
843
+ }
844
+
845
+ if (options.format === 'sarif') {
846
+ console.log(JSON.stringify(formatSarif(result, { dir: options.dir }), null, 2));
847
+ return result;
848
+ }
849
+
850
+ if (options.lite) {
851
+ printLiteAudit(result, options.dir);
852
+ sendInsights(result);
853
+ return result;
854
+ }
855
+
856
+ // Display results
857
+ console.log('');
858
+ const auditTitle = spec.platform === 'codex' ? 'nerviq codex audit' : 'nerviq audit';
859
+ console.log(colorize(` ${auditTitle}`, 'bold'));
860
+ console.log(colorize(' ═══════════════════════════════════════', 'dim'));
861
+ console.log(colorize(` Scanning: ${options.dir}`, 'dim'));
862
+ if (spec.platformVersion) {
863
+ console.log(colorize(` Platform: ${spec.platformLabel} (${spec.platformVersion})`, 'blue'));
864
+ }
865
+ if (spec.platform === 'codex' && recommendedDomainPacks.length > 0) {
866
+ console.log(colorize(` Domain packs: ${recommendedDomainPacks.map((pack) => pack.label).join(', ')}`, 'dim'));
867
+ }
868
+ if (platformScopeNote) {
869
+ console.log(colorize(` Scope: ${platformScopeNote.message}`, 'dim'));
870
+ }
871
+ if (platformCaveats.length > 0) {
872
+ console.log(colorize(' Platform caveats', 'yellow'));
873
+ for (const caveat of platformCaveats) {
874
+ console.log(colorize(` ${caveat.title}`, 'bold'));
875
+ console.log(colorize(` → ${caveat.message}`, 'dim'));
876
+ if (caveat.file) {
877
+ console.log(colorize(` at ${formatLocation(caveat.file, caveat.line)}`, 'dim'));
878
+ }
879
+ }
880
+ console.log('');
881
+ }
882
+
883
+ if (stacks.length > 0) {
884
+ console.log(colorize(` Detected: ${stacks.map(s => s.label).join(', ')}`, 'blue'));
885
+ }
886
+
887
+ console.log('');
888
+
889
+ // Score
890
+ console.log(` ${progressBar(score)} ${colorize(`${score}/100`, 'bold')}`);
891
+ if (isScaffolded && scaffoldedPassed.length > 0) {
892
+ console.log(colorize(` Organic: ${organicScore}/100 (without nerviq generated files)`, 'dim'));
893
+ }
894
+ console.log('');
895
+
896
+ // Passed
897
+ if (passed.length > 0) {
898
+ console.log(colorize(' ✅ Passing', 'green'));
899
+ for (const r of passed) {
900
+ console.log(colorize(` ${r.name}`, 'dim'));
901
+ }
902
+ console.log('');
903
+ }
904
+
905
+ // Failed - by priority
906
+ if (critical.length > 0) {
907
+ console.log(colorize(' 🔴 Critical (fix immediately)', 'red'));
908
+ for (const r of critical) {
909
+ console.log(` ${colorize(r.name, 'bold')}`);
910
+ if (r.file) {
911
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
912
+ }
913
+ console.log(colorize(` → ${r.fix}`, 'dim'));
914
+ }
915
+ console.log('');
916
+ }
917
+
918
+ if (high.length > 0) {
919
+ console.log(colorize(' 🟡 High Impact', 'yellow'));
920
+ for (const r of high) {
921
+ console.log(` ${colorize(r.name, 'bold')}`);
922
+ if (r.file) {
923
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
924
+ }
925
+ console.log(colorize(` → ${r.fix}`, 'dim'));
926
+ }
927
+ console.log('');
928
+ }
929
+
930
+ if (medium.length > 0 && options.verbose) {
931
+ console.log(colorize(' 🔵 Recommended', 'blue'));
932
+ for (const r of medium) {
933
+ console.log(` ${colorize(r.name, 'bold')}`);
934
+ if (r.file) {
935
+ console.log(colorize(` at ${formatLocation(r.file, r.line)}`, 'dim'));
936
+ }
937
+ console.log(colorize(` → ${r.fix}`, 'dim'));
938
+ }
939
+ console.log('');
940
+ } else if (medium.length > 0) {
941
+ console.log(colorize(` 🔵 ${medium.length} more recommendations (use --verbose)`, 'blue'));
942
+ console.log('');
943
+ }
944
+
945
+ // Top next actions
946
+ if (topNextActions.length > 0) {
947
+ console.log(colorize(' ⚡ Top 5 Next Actions', 'magenta'));
948
+ for (let i = 0; i < topNextActions.length; i++) {
949
+ const item = topNextActions[i];
950
+ console.log(` ${i + 1}. ${colorize(item.name, 'bold')}`);
951
+ console.log(colorize(` Why: ${item.why}`, 'dim'));
952
+ console.log(colorize(` Trace: ${item.signals.join(' | ')}`, 'dim'));
953
+ console.log(colorize(` Risk: ${item.risk} | Confidence: ${item.confidence}`, 'dim'));
954
+ const sourceResult = result.results.find(r => r.key === item.key);
955
+ if (sourceResult && sourceResult.file) {
956
+ console.log(colorize(` Evidence: ${formatLocation(sourceResult.file, sourceResult.line)}`, 'dim'));
957
+ }
958
+ if (item.feedback) {
959
+ const avgDelta = Number.isFinite(item.feedback.avgScoreDelta) ? ` | Avg score delta: ${item.feedback.avgScoreDelta >= 0 ? '+' : ''}${item.feedback.avgScoreDelta}` : '';
960
+ console.log(colorize(` Feedback: accepted ${item.feedback.accepted}, rejected ${item.feedback.rejected}, positive ${item.feedback.positive}, negative ${item.feedback.negative}${avgDelta}`, 'dim'));
961
+ }
962
+ console.log(colorize(` Fix: ${item.fix}`, 'dim'));
963
+ }
964
+ console.log('');
965
+ }
966
+
967
+ // Summary
968
+ console.log(colorize(' ─────────────────────────────────────', 'dim'));
969
+ console.log(` ${colorize(`${passed.length}/${applicable.length}`, 'bold')} checks passing${skipped.length > 0 ? colorize(` (${skipped.length} not applicable)`, 'dim') : ''}`);
970
+
971
+ if (failed.length > 0) {
972
+ console.log(` Next command: ${colorize(result.suggestedNextCommand, 'bold')}`);
973
+ if (result.platform === 'codex') {
974
+ console.log(colorize(' Codex now supports advisory no-write flows through augment and suggest-only before setup/apply.', 'dim'));
975
+ }
976
+ }
977
+
978
+ console.log('');
979
+ console.log(` Add to README: ${getBadgeMarkdown(score)}`);
980
+ console.log('');
981
+
982
+ // Weakest categories insight
983
+ const insights = getLocalInsights({ score, results });
984
+ if (insights.weakest.length > 0) {
985
+ console.log(colorize(' Weakest areas:', 'dim'));
986
+ for (const w of insights.weakest) {
987
+ const bar = w.score === 0 ? colorize('none', 'red') : `${w.score}%`;
988
+ console.log(colorize(` ${w.name}: ${bar} (${w.passed}/${w.total})`, 'dim'));
989
+ }
990
+ console.log('');
991
+ }
992
+
993
+ console.log(colorize(` Backed by CLAUDEX research and evidence for ${spec.platformLabel}`, 'dim'));
994
+ console.log(colorize(' https://github.com/nerviq/nerviq', 'dim'));
995
+ console.log('');
996
+
997
+ // Send anonymous insights (opt-in, privacy-first, fire-and-forget)
998
+ sendInsights(result);
999
+
1000
+ return result;
1001
+ }
1002
+
1003
+ module.exports = { audit, buildTopNextActions };