@vibecheckai/cli 3.5.0 → 3.5.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 (224) hide show
  1. package/bin/registry.js +214 -237
  2. package/bin/runners/cli-utils.js +33 -2
  3. package/bin/runners/context/analyzer.js +52 -1
  4. package/bin/runners/context/generators/cursor.js +2 -49
  5. package/bin/runners/context/git-context.js +3 -1
  6. package/bin/runners/context/team-conventions.js +33 -7
  7. package/bin/runners/lib/analysis-core.js +25 -5
  8. package/bin/runners/lib/analyzers.js +431 -481
  9. package/bin/runners/lib/default-config.js +127 -0
  10. package/bin/runners/lib/doctor/modules/security.js +3 -1
  11. package/bin/runners/lib/engine/ast-cache.js +210 -0
  12. package/bin/runners/lib/engine/auth-extractor.js +211 -0
  13. package/bin/runners/lib/engine/billing-extractor.js +112 -0
  14. package/bin/runners/lib/engine/enforcement-extractor.js +100 -0
  15. package/bin/runners/lib/engine/env-extractor.js +207 -0
  16. package/bin/runners/lib/engine/express-extractor.js +208 -0
  17. package/bin/runners/lib/engine/extractors.js +849 -0
  18. package/bin/runners/lib/engine/index.js +207 -0
  19. package/bin/runners/lib/engine/repo-index.js +514 -0
  20. package/bin/runners/lib/engine/types.js +124 -0
  21. package/bin/runners/lib/engines/accessibility-engine.js +18 -218
  22. package/bin/runners/lib/engines/api-consistency-engine.js +30 -335
  23. package/bin/runners/lib/engines/cross-file-analysis-engine.js +27 -292
  24. package/bin/runners/lib/engines/empty-catch-engine.js +17 -127
  25. package/bin/runners/lib/engines/mock-data-engine.js +10 -53
  26. package/bin/runners/lib/engines/performance-issues-engine.js +36 -176
  27. package/bin/runners/lib/engines/security-vulnerabilities-engine.js +54 -382
  28. package/bin/runners/lib/engines/type-aware-engine.js +39 -263
  29. package/bin/runners/lib/engines/vibecheck-engines/index.js +13 -122
  30. package/bin/runners/lib/engines/vibecheck-engines/lib/ast-cache.js +164 -0
  31. package/bin/runners/lib/engines/vibecheck-engines/lib/code-quality-engine.js +291 -0
  32. package/bin/runners/lib/engines/vibecheck-engines/lib/console-logs-engine.js +83 -0
  33. package/bin/runners/lib/engines/vibecheck-engines/lib/dead-code-engine.js +198 -0
  34. package/bin/runners/lib/engines/vibecheck-engines/lib/deprecated-api-engine.js +275 -0
  35. package/bin/runners/lib/engines/vibecheck-engines/lib/empty-catch-engine.js +167 -0
  36. package/bin/runners/lib/engines/vibecheck-engines/lib/file-filter.js +217 -0
  37. package/bin/runners/lib/engines/vibecheck-engines/lib/hardcoded-secrets-engine.js +73 -373
  38. package/bin/runners/lib/engines/vibecheck-engines/lib/mock-data-engine.js +140 -0
  39. package/bin/runners/lib/engines/vibecheck-engines/lib/parallel-processor.js +164 -0
  40. package/bin/runners/lib/engines/vibecheck-engines/lib/performance-issues-engine.js +234 -0
  41. package/bin/runners/lib/engines/vibecheck-engines/lib/type-aware-engine.js +217 -0
  42. package/bin/runners/lib/engines/vibecheck-engines/lib/unsafe-regex-engine.js +78 -0
  43. package/bin/runners/lib/entitlements-v2.js +73 -97
  44. package/bin/runners/lib/error-handler.js +44 -3
  45. package/bin/runners/lib/error-messages.js +289 -0
  46. package/bin/runners/lib/evidence-pack.js +7 -1
  47. package/bin/runners/lib/finding-id.js +69 -0
  48. package/bin/runners/lib/finding-sorter.js +89 -0
  49. package/bin/runners/lib/html-proof-report.js +700 -350
  50. package/bin/runners/lib/missions/plan.js +6 -46
  51. package/bin/runners/lib/missions/templates.js +0 -232
  52. package/bin/runners/lib/next-action.js +560 -0
  53. package/bin/runners/lib/prerequisites.js +149 -0
  54. package/bin/runners/lib/route-detection.js +137 -68
  55. package/bin/runners/lib/scan-output.js +91 -76
  56. package/bin/runners/lib/scan-runner.js +135 -0
  57. package/bin/runners/lib/schemas/ajv-validator.js +464 -0
  58. package/bin/runners/lib/schemas/error-envelope.schema.json +105 -0
  59. package/bin/runners/lib/schemas/finding-v3.schema.json +151 -0
  60. package/bin/runners/lib/schemas/report-artifact.schema.json +120 -0
  61. package/bin/runners/lib/schemas/run-request.schema.json +108 -0
  62. package/bin/runners/lib/schemas/validator.js +27 -0
  63. package/bin/runners/lib/schemas/verdict.schema.json +140 -0
  64. package/bin/runners/lib/ship-output-enterprise.js +23 -23
  65. package/bin/runners/lib/ship-output.js +75 -31
  66. package/bin/runners/lib/terminal-ui.js +6 -113
  67. package/bin/runners/lib/truth.js +351 -10
  68. package/bin/runners/lib/unified-cli-output.js +430 -603
  69. package/bin/runners/lib/unified-output.js +13 -9
  70. package/bin/runners/runAIAgent.js +10 -5
  71. package/bin/runners/runAgent.js +0 -3
  72. package/bin/runners/runAllowlist.js +389 -0
  73. package/bin/runners/runApprove.js +0 -33
  74. package/bin/runners/runAuth.js +73 -45
  75. package/bin/runners/runCheckpoint.js +51 -11
  76. package/bin/runners/runClassify.js +85 -21
  77. package/bin/runners/runContext.js +0 -3
  78. package/bin/runners/runDoctor.js +41 -28
  79. package/bin/runners/runEvidencePack.js +362 -0
  80. package/bin/runners/runFirewall.js +0 -3
  81. package/bin/runners/runFirewallHook.js +0 -3
  82. package/bin/runners/runFix.js +66 -76
  83. package/bin/runners/runGuard.js +18 -411
  84. package/bin/runners/runInit.js +113 -30
  85. package/bin/runners/runLabs.js +424 -0
  86. package/bin/runners/runMcp.js +19 -25
  87. package/bin/runners/runPolish.js +64 -240
  88. package/bin/runners/runPromptFirewall.js +12 -5
  89. package/bin/runners/runProve.js +57 -22
  90. package/bin/runners/runQuickstart.js +531 -0
  91. package/bin/runners/runReality.js +59 -68
  92. package/bin/runners/runReport.js +38 -33
  93. package/bin/runners/runRuntime.js +8 -5
  94. package/bin/runners/runScan.js +1413 -190
  95. package/bin/runners/runShip.js +113 -719
  96. package/bin/runners/runTruth.js +0 -3
  97. package/bin/runners/runValidate.js +13 -9
  98. package/bin/runners/runWatch.js +23 -14
  99. package/bin/scan.js +6 -1
  100. package/bin/vibecheck.js +204 -185
  101. package/mcp-server/deprecation-middleware.js +282 -0
  102. package/mcp-server/handlers/index.ts +15 -0
  103. package/mcp-server/handlers/tool-handler.ts +554 -0
  104. package/mcp-server/index-v1.js +698 -0
  105. package/mcp-server/index.js +210 -238
  106. package/mcp-server/lib/cache-wrapper.cjs +383 -0
  107. package/mcp-server/lib/error-envelope.js +138 -0
  108. package/mcp-server/lib/executor.ts +499 -0
  109. package/mcp-server/lib/index.ts +19 -0
  110. package/mcp-server/lib/rate-limiter.js +166 -0
  111. package/mcp-server/lib/sandbox.test.ts +519 -0
  112. package/mcp-server/lib/sandbox.ts +395 -0
  113. package/mcp-server/lib/types.ts +267 -0
  114. package/mcp-server/package.json +12 -3
  115. package/mcp-server/registry/tool-registry.js +794 -0
  116. package/mcp-server/registry/tools.json +605 -0
  117. package/mcp-server/registry.test.ts +334 -0
  118. package/mcp-server/tests/tier-gating.test.js +297 -0
  119. package/mcp-server/tier-auth.js +378 -45
  120. package/mcp-server/tools-v3.js +353 -442
  121. package/mcp-server/tsconfig.json +37 -0
  122. package/mcp-server/vibecheck-2.0-tools.js +14 -1
  123. package/package.json +1 -1
  124. package/bin/runners/lib/agent-firewall/learning/learning-engine.js +0 -849
  125. package/bin/runners/lib/audit-logger.js +0 -532
  126. package/bin/runners/lib/authority/authorities/architecture.js +0 -364
  127. package/bin/runners/lib/authority/authorities/compliance.js +0 -341
  128. package/bin/runners/lib/authority/authorities/human.js +0 -343
  129. package/bin/runners/lib/authority/authorities/quality.js +0 -420
  130. package/bin/runners/lib/authority/authorities/security.js +0 -228
  131. package/bin/runners/lib/authority/index.js +0 -293
  132. package/bin/runners/lib/bundle/bundle-intelligence.js +0 -846
  133. package/bin/runners/lib/cli-charts.js +0 -368
  134. package/bin/runners/lib/cli-config-display.js +0 -405
  135. package/bin/runners/lib/cli-demo.js +0 -275
  136. package/bin/runners/lib/cli-errors.js +0 -438
  137. package/bin/runners/lib/cli-help-formatter.js +0 -439
  138. package/bin/runners/lib/cli-interactive-menu.js +0 -509
  139. package/bin/runners/lib/cli-prompts.js +0 -441
  140. package/bin/runners/lib/cli-scan-cards.js +0 -362
  141. package/bin/runners/lib/compliance-reporter.js +0 -710
  142. package/bin/runners/lib/conductor/index.js +0 -671
  143. package/bin/runners/lib/easy/README.md +0 -123
  144. package/bin/runners/lib/easy/index.js +0 -140
  145. package/bin/runners/lib/easy/interactive-wizard.js +0 -788
  146. package/bin/runners/lib/easy/one-click-firewall.js +0 -564
  147. package/bin/runners/lib/easy/zero-config-reality.js +0 -714
  148. package/bin/runners/lib/engines/async-patterns-engine.js +0 -444
  149. package/bin/runners/lib/engines/bundle-size-engine.js +0 -433
  150. package/bin/runners/lib/engines/confidence-scoring.js +0 -276
  151. package/bin/runners/lib/engines/context-detection.js +0 -264
  152. package/bin/runners/lib/engines/database-patterns-engine.js +0 -429
  153. package/bin/runners/lib/engines/duplicate-code-engine.js +0 -354
  154. package/bin/runners/lib/engines/env-variables-engine.js +0 -458
  155. package/bin/runners/lib/engines/error-handling-engine.js +0 -437
  156. package/bin/runners/lib/engines/false-positive-prevention.js +0 -630
  157. package/bin/runners/lib/engines/framework-adapters/index.js +0 -607
  158. package/bin/runners/lib/engines/framework-detection.js +0 -508
  159. package/bin/runners/lib/engines/import-order-engine.js +0 -429
  160. package/bin/runners/lib/engines/naming-conventions-engine.js +0 -544
  161. package/bin/runners/lib/engines/noise-reduction-engine.js +0 -452
  162. package/bin/runners/lib/engines/orchestrator.js +0 -334
  163. package/bin/runners/lib/engines/react-patterns-engine.js +0 -457
  164. package/bin/runners/lib/engines/vibecheck-engines/lib/ai-hallucination-engine.js +0 -806
  165. package/bin/runners/lib/engines/vibecheck-engines/lib/smart-fix-engine.js +0 -577
  166. package/bin/runners/lib/engines/vibecheck-engines/lib/vibe-score-engine.js +0 -543
  167. package/bin/runners/lib/engines/vibecheck-engines.js +0 -514
  168. package/bin/runners/lib/enhanced-features/index.js +0 -305
  169. package/bin/runners/lib/enhanced-output.js +0 -631
  170. package/bin/runners/lib/enterprise.js +0 -300
  171. package/bin/runners/lib/firewall/command-validator.js +0 -351
  172. package/bin/runners/lib/firewall/config.js +0 -341
  173. package/bin/runners/lib/firewall/content-validator.js +0 -519
  174. package/bin/runners/lib/firewall/index.js +0 -101
  175. package/bin/runners/lib/firewall/path-validator.js +0 -256
  176. package/bin/runners/lib/intelligence/cross-repo-intelligence.js +0 -817
  177. package/bin/runners/lib/mcp-utils.js +0 -425
  178. package/bin/runners/lib/output/index.js +0 -1022
  179. package/bin/runners/lib/policy-engine.js +0 -652
  180. package/bin/runners/lib/polish/autofix/accessibility-fixes.js +0 -333
  181. package/bin/runners/lib/polish/autofix/async-handlers.js +0 -273
  182. package/bin/runners/lib/polish/autofix/dead-code.js +0 -280
  183. package/bin/runners/lib/polish/autofix/imports-optimizer.js +0 -344
  184. package/bin/runners/lib/polish/autofix/index.js +0 -200
  185. package/bin/runners/lib/polish/autofix/remove-consoles.js +0 -209
  186. package/bin/runners/lib/polish/autofix/strengthen-types.js +0 -245
  187. package/bin/runners/lib/polish/backend-checks.js +0 -148
  188. package/bin/runners/lib/polish/documentation-checks.js +0 -111
  189. package/bin/runners/lib/polish/frontend-checks.js +0 -168
  190. package/bin/runners/lib/polish/index.js +0 -71
  191. package/bin/runners/lib/polish/infrastructure-checks.js +0 -131
  192. package/bin/runners/lib/polish/library-detection.js +0 -175
  193. package/bin/runners/lib/polish/performance-checks.js +0 -100
  194. package/bin/runners/lib/polish/security-checks.js +0 -148
  195. package/bin/runners/lib/polish/utils.js +0 -203
  196. package/bin/runners/lib/prompt-builder.js +0 -540
  197. package/bin/runners/lib/proof-certificate.js +0 -634
  198. package/bin/runners/lib/reality/accessibility-audit.js +0 -946
  199. package/bin/runners/lib/reality/api-contract-validator.js +0 -1012
  200. package/bin/runners/lib/reality/chaos-engineering.js +0 -1084
  201. package/bin/runners/lib/reality/performance-tracker.js +0 -1077
  202. package/bin/runners/lib/reality/scenario-generator.js +0 -1404
  203. package/bin/runners/lib/reality/visual-regression.js +0 -852
  204. package/bin/runners/lib/reality-profiler.js +0 -717
  205. package/bin/runners/lib/replay/flight-recorder-viewer.js +0 -1160
  206. package/bin/runners/lib/review/ai-code-review.js +0 -832
  207. package/bin/runners/lib/rules/custom-rule-engine.js +0 -985
  208. package/bin/runners/lib/sbom-generator.js +0 -641
  209. package/bin/runners/lib/scan-output-enhanced.js +0 -512
  210. package/bin/runners/lib/security/owasp-scanner.js +0 -939
  211. package/bin/runners/lib/validators/contract-validator.js +0 -283
  212. package/bin/runners/lib/validators/dead-export-detector.js +0 -279
  213. package/bin/runners/lib/validators/dep-audit.js +0 -245
  214. package/bin/runners/lib/validators/env-validator.js +0 -319
  215. package/bin/runners/lib/validators/index.js +0 -120
  216. package/bin/runners/lib/validators/license-checker.js +0 -252
  217. package/bin/runners/lib/validators/route-validator.js +0 -290
  218. package/bin/runners/runAuthority.js +0 -528
  219. package/bin/runners/runConductor.js +0 -772
  220. package/bin/runners/runContainer.js +0 -366
  221. package/bin/runners/runEasy.js +0 -410
  222. package/bin/runners/runIaC.js +0 -372
  223. package/bin/runners/runVibe.js +0 -791
  224. package/mcp-server/tools.js +0 -495
@@ -1,832 +0,0 @@
1
- /**
2
- * AI Code Review Agent
3
- *
4
- * ═══════════════════════════════════════════════════════════════════════════════
5
- * COMPETITIVE MOAT FEATURE - Intelligent Automated Code Review
6
- * ═══════════════════════════════════════════════════════════════════════════════
7
- *
8
- * This engine provides automated code review capabilities that go beyond linting.
9
- * It understands context, business logic, and provides actionable suggestions.
10
- *
11
- * Review Categories:
12
- * - Security vulnerabilities (injection, XSS, auth issues)
13
- * - Performance anti-patterns (N+1 queries, memory leaks)
14
- * - Code quality (complexity, maintainability)
15
- * - Best practices (framework-specific patterns)
16
- * - Business logic issues (state management, race conditions)
17
- * - Test coverage gaps
18
- * - Documentation needs
19
- *
20
- * Features:
21
- * - Context-aware review (understands the full PR)
22
- * - Suggested fixes with confidence levels
23
- * - PR comment generation
24
- * - Learning from feedback
25
- * - Custom review rules
26
- */
27
-
28
- "use strict";
29
-
30
- const fs = require("fs");
31
- const path = require("path");
32
- const crypto = require("crypto");
33
-
34
- // ═══════════════════════════════════════════════════════════════════════════════
35
- // REVIEW CATEGORIES AND RULES
36
- // ═══════════════════════════════════════════════════════════════════════════════
37
-
38
- const REVIEW_CATEGORIES = {
39
- security: {
40
- name: "Security",
41
- icon: "🔒",
42
- rules: [
43
- {
44
- id: "sql-injection",
45
- name: "SQL Injection Risk",
46
- severity: "critical",
47
- pattern: /(\$\{.*\}|`.*\$\{.*\}`)\s*(?:SELECT|INSERT|UPDATE|DELETE|FROM|WHERE)/i,
48
- message: "Potential SQL injection vulnerability. Use parameterized queries.",
49
- fix: "Use prepared statements or an ORM with parameterized queries"
50
- },
51
- {
52
- id: "xss-risk",
53
- name: "Cross-Site Scripting Risk",
54
- severity: "critical",
55
- pattern: /innerHTML\s*=|dangerouslySetInnerHTML|v-html/,
56
- message: "Potential XSS vulnerability. Avoid direct HTML injection.",
57
- fix: "Sanitize input or use safe rendering methods"
58
- },
59
- {
60
- id: "hardcoded-secret",
61
- name: "Hardcoded Secret",
62
- severity: "critical",
63
- pattern: /(api[_-]?key|secret|password|token)\s*[:=]\s*['"][^'"]{8,}['"]/i,
64
- message: "Possible hardcoded secret detected.",
65
- fix: "Move secrets to environment variables"
66
- },
67
- {
68
- id: "eval-usage",
69
- name: "Dangerous eval() Usage",
70
- severity: "high",
71
- pattern: /\beval\s*\(|new\s+Function\s*\(/,
72
- message: "eval() and Function constructor can execute arbitrary code.",
73
- fix: "Avoid eval() - use safer alternatives like JSON.parse()"
74
- },
75
- {
76
- id: "crypto-weak",
77
- name: "Weak Cryptography",
78
- severity: "high",
79
- pattern: /createHash\(['"]md5['"]\)|createHash\(['"]sha1['"]\)/,
80
- message: "MD5 and SHA1 are cryptographically weak.",
81
- fix: "Use SHA-256 or stronger hash algorithms"
82
- }
83
- ]
84
- },
85
-
86
- performance: {
87
- name: "Performance",
88
- icon: "⚡",
89
- rules: [
90
- {
91
- id: "n-plus-one",
92
- name: "Potential N+1 Query",
93
- severity: "high",
94
- pattern: /for\s*\([^)]*\)\s*\{[^}]*await[^}]*(?:findOne|findById|query|fetch)/,
95
- message: "Possible N+1 query pattern. Consider batch loading.",
96
- fix: "Use batch queries or eager loading"
97
- },
98
- {
99
- id: "sync-fs",
100
- name: "Synchronous File Operation",
101
- severity: "medium",
102
- pattern: /fs\.(readFileSync|writeFileSync|appendFileSync|existsSync)/,
103
- message: "Synchronous file operations block the event loop.",
104
- fix: "Use async versions: fs.promises.readFile, etc."
105
- },
106
- {
107
- id: "missing-memo",
108
- name: "Missing React.memo",
109
- severity: "low",
110
- pattern: /export\s+(?:default\s+)?function\s+\w+.*\(\s*\{\s*\w+/,
111
- context: /\.tsx?$/,
112
- message: "Component receiving props might benefit from React.memo.",
113
- fix: "Wrap with React.memo() if re-renders are expensive"
114
- },
115
- {
116
- id: "large-bundle-import",
117
- name: "Large Bundle Import",
118
- severity: "medium",
119
- pattern: /import\s+(?:\*\s+as\s+\w+|{\s*\w+(?:,\s*\w+)*\s*})\s+from\s+['"](?:lodash|moment|date-fns|rxjs)['"]/,
120
- message: "Importing from large libraries can bloat bundle size.",
121
- fix: "Use tree-shakeable imports: import debounce from 'lodash/debounce'"
122
- },
123
- {
124
- id: "missing-cleanup",
125
- name: "Missing useEffect Cleanup",
126
- severity: "medium",
127
- pattern: /useEffect\(\s*\(\)\s*=>\s*\{[^}]*(?:addEventListener|setInterval|setTimeout|subscribe)[^}]*\}\s*,/,
128
- negativePattern: /return\s*\(\s*\)\s*=>/,
129
- message: "useEffect with subscriptions should return a cleanup function.",
130
- fix: "Add return () => cleanup() to prevent memory leaks"
131
- }
132
- ]
133
- },
134
-
135
- quality: {
136
- name: "Code Quality",
137
- icon: "✨",
138
- rules: [
139
- {
140
- id: "high-complexity",
141
- name: "High Cyclomatic Complexity",
142
- severity: "medium",
143
- check: (code) => {
144
- const branches = (code.match(/if|else|switch|case|\?|&&|\|\||for|while|catch/g) || []).length;
145
- return branches > 15;
146
- },
147
- message: "Function has high cyclomatic complexity.",
148
- fix: "Break down into smaller functions"
149
- },
150
- {
151
- id: "long-function",
152
- name: "Long Function",
153
- severity: "low",
154
- check: (code, lines) => lines > 50,
155
- message: "Function is longer than 50 lines.",
156
- fix: "Extract logic into separate functions"
157
- },
158
- {
159
- id: "magic-numbers",
160
- name: "Magic Numbers",
161
- severity: "low",
162
- pattern: /(?<![a-zA-Z_$])(?:86400|3600|1000|60|24|365|100|1024)\b/,
163
- message: "Consider using named constants for magic numbers.",
164
- fix: "Extract to named constant: const SECONDS_PER_DAY = 86400"
165
- },
166
- {
167
- id: "console-left",
168
- name: "Console Statement",
169
- severity: "low",
170
- pattern: /console\.(log|warn|error|debug|info)\(/,
171
- message: "Console statements should be removed before production.",
172
- fix: "Remove or replace with proper logging"
173
- },
174
- {
175
- id: "todo-fixme",
176
- name: "TODO/FIXME Comment",
177
- severity: "info",
178
- pattern: /\/\/\s*(TODO|FIXME|XXX|HACK|BUG):/i,
179
- message: "Unresolved TODO/FIXME comment.",
180
- fix: "Address the TODO or create a ticket"
181
- }
182
- ]
183
- },
184
-
185
- bestPractices: {
186
- name: "Best Practices",
187
- icon: "📚",
188
- rules: [
189
- {
190
- id: "any-type",
191
- name: "TypeScript 'any' Type",
192
- severity: "medium",
193
- pattern: /:\s*any\b|as\s+any\b/,
194
- context: /\.tsx?$/,
195
- message: "Using 'any' type defeats TypeScript's type safety.",
196
- fix: "Use proper types or 'unknown' with type guards"
197
- },
198
- {
199
- id: "async-await-consistency",
200
- name: "Mixed Async Patterns",
201
- severity: "low",
202
- pattern: /\.then\s*\([^)]*\).*await|await.*\.then\s*\(/,
203
- message: "Mixing .then() and await can be confusing.",
204
- fix: "Use consistent async/await pattern"
205
- },
206
- {
207
- id: "empty-catch",
208
- name: "Empty Catch Block",
209
- severity: "medium",
210
- pattern: /catch\s*\([^)]*\)\s*\{\s*\}/,
211
- message: "Empty catch blocks swallow errors silently.",
212
- fix: "Log the error or rethrow if can't handle"
213
- },
214
- {
215
- id: "var-usage",
216
- name: "Using 'var' Declaration",
217
- severity: "low",
218
- pattern: /\bvar\s+\w+/,
219
- message: "Prefer 'const' or 'let' over 'var'.",
220
- fix: "Replace var with const (preferred) or let"
221
- },
222
- {
223
- id: "prop-drilling",
224
- name: "Excessive Prop Drilling",
225
- severity: "low",
226
- check: (code) => {
227
- const props = code.match(/\{[^}]*\.\.\.[a-z]/gi) || [];
228
- return props.length > 3;
229
- },
230
- message: "Consider using Context or state management for deep prop passing.",
231
- fix: "Use React Context, Redux, or Zustand"
232
- }
233
- ]
234
- },
235
-
236
- testing: {
237
- name: "Testing",
238
- icon: "🧪",
239
- rules: [
240
- {
241
- id: "missing-test",
242
- name: "Missing Test File",
243
- severity: "info",
244
- checkFile: (filePath) => {
245
- if (filePath.includes(".test.") || filePath.includes(".spec.")) return false;
246
- const testPath = filePath.replace(/\.(ts|tsx|js|jsx)$/, ".test.$1");
247
- const specPath = filePath.replace(/\.(ts|tsx|js|jsx)$/, ".spec.$1");
248
- return !fs.existsSync(testPath) && !fs.existsSync(specPath);
249
- },
250
- message: "No corresponding test file found.",
251
- fix: "Add unit tests for this file"
252
- },
253
- {
254
- id: "test-implementation",
255
- name: "Test Implementation Details",
256
- severity: "low",
257
- pattern: /getByTestId|querySelector|\.className/,
258
- context: /\.(test|spec)\./,
259
- message: "Testing implementation details can make tests brittle.",
260
- fix: "Test behavior, not implementation. Use accessible queries."
261
- },
262
- {
263
- id: "mock-not-restored",
264
- name: "Mock Not Restored",
265
- severity: "medium",
266
- pattern: /jest\.spyOn|jest\.mock|vi\.spyOn|vi\.mock/,
267
- negativePattern: /afterEach|afterAll|\.mockRestore\(\)/,
268
- context: /\.(test|spec)\./,
269
- message: "Mocks should be restored after each test.",
270
- fix: "Add jest.restoreAllMocks() in afterEach"
271
- }
272
- ]
273
- },
274
-
275
- documentation: {
276
- name: "Documentation",
277
- icon: "📝",
278
- rules: [
279
- {
280
- id: "missing-jsdoc",
281
- name: "Missing JSDoc",
282
- severity: "info",
283
- pattern: /export\s+(?:async\s+)?function\s+[A-Z]\w+/,
284
- negativePattern: /\/\*\*[\s\S]*?\*\/\s*export/,
285
- message: "Exported function missing JSDoc documentation.",
286
- fix: "Add JSDoc with @param and @returns"
287
- },
288
- {
289
- id: "outdated-comment",
290
- name: "Potentially Outdated Comment",
291
- severity: "info",
292
- check: (code) => {
293
- const hasOldDate = /(?:19|20)\d{2}/.test(code);
294
- const hasVersion = /v?\d+\.\d+\.\d+/.test(code);
295
- return hasOldDate || hasVersion;
296
- },
297
- message: "Comment may contain outdated version/date references.",
298
- fix: "Verify comment accuracy"
299
- }
300
- ]
301
- }
302
- };
303
-
304
- // ═══════════════════════════════════════════════════════════════════════════════
305
- // CODE REVIEW ENGINE
306
- // ═══════════════════════════════════════════════════════════════════════════════
307
-
308
- class AICodeReviewEngine {
309
- constructor(options = {}) {
310
- this.projectRoot = options.projectRoot || process.cwd();
311
- this.categories = { ...REVIEW_CATEGORIES, ...options.customCategories };
312
- this.ignorePaths = options.ignorePaths || [
313
- "**/node_modules/**",
314
- "**/dist/**",
315
- "**/build/**",
316
- "**/*.min.js",
317
- "**/coverage/**"
318
- ];
319
- this.results = [];
320
- this.feedback = new Map(); // Store feedback for learning
321
- }
322
-
323
- /**
324
- * Review a single file
325
- */
326
- reviewFile(filePath, content = null) {
327
- const findings = [];
328
-
329
- // Read file if content not provided
330
- if (content === null) {
331
- const fullPath = path.isAbsolute(filePath)
332
- ? filePath
333
- : path.join(this.projectRoot, filePath);
334
-
335
- if (!fs.existsSync(fullPath)) {
336
- return { file: filePath, findings: [], error: "File not found" };
337
- }
338
-
339
- content = fs.readFileSync(fullPath, "utf8");
340
- }
341
-
342
- const lines = content.split("\n");
343
-
344
- // Apply each category's rules
345
- for (const [categoryId, category] of Object.entries(this.categories)) {
346
- for (const rule of category.rules) {
347
- // Check file context match
348
- if (rule.context && !rule.context.test(filePath)) {
349
- continue;
350
- }
351
-
352
- // Check file-level rules
353
- if (rule.checkFile) {
354
- if (rule.checkFile(filePath)) {
355
- findings.push(this.createFinding(rule, categoryId, filePath, 0, null));
356
- }
357
- continue;
358
- }
359
-
360
- // Check custom function
361
- if (rule.check) {
362
- if (rule.check(content, lines.length)) {
363
- findings.push(this.createFinding(rule, categoryId, filePath, 0, null));
364
- }
365
- continue;
366
- }
367
-
368
- // Check pattern match
369
- if (rule.pattern) {
370
- const regex = new RegExp(rule.pattern.source, "gm");
371
- let match;
372
-
373
- while ((match = regex.exec(content)) !== null) {
374
- // Check negative pattern (should NOT match)
375
- if (rule.negativePattern) {
376
- const surrounding = content.substring(
377
- Math.max(0, match.index - 500),
378
- Math.min(content.length, match.index + match[0].length + 500)
379
- );
380
- if (rule.negativePattern.test(surrounding)) {
381
- continue; // Skip - negative pattern found
382
- }
383
- }
384
-
385
- const line = content.substring(0, match.index).split("\n").length;
386
- findings.push(this.createFinding(
387
- rule,
388
- categoryId,
389
- filePath,
390
- line,
391
- match[0]
392
- ));
393
- }
394
- }
395
- }
396
- }
397
-
398
- return {
399
- file: filePath,
400
- findings,
401
- summary: this.summarizeFindings(findings)
402
- };
403
- }
404
-
405
- /**
406
- * Review multiple files (e.g., a PR diff)
407
- */
408
- reviewFiles(files) {
409
- this.results = [];
410
-
411
- for (const file of files) {
412
- // Skip ignored paths
413
- if (this.shouldIgnore(file.path || file)) {
414
- continue;
415
- }
416
-
417
- const result = this.reviewFile(
418
- file.path || file,
419
- file.content || null
420
- );
421
-
422
- if (result.findings.length > 0) {
423
- this.results.push(result);
424
- }
425
- }
426
-
427
- return {
428
- files: this.results,
429
- totalFindings: this.results.reduce((sum, r) => sum + r.findings.length, 0),
430
- summary: this.generateOverallSummary()
431
- };
432
- }
433
-
434
- /**
435
- * Review a git diff
436
- */
437
- async reviewDiff(diffContent) {
438
- const files = this.parseDiff(diffContent);
439
- return this.reviewFiles(files);
440
- }
441
-
442
- /**
443
- * Parse git diff format
444
- */
445
- parseDiff(diffContent) {
446
- const files = [];
447
- const diffRegex = /diff --git a\/(.+?) b\/(.+?)$/gm;
448
- const hunkRegex = /@@\s*-\d+,?\d*\s*\+(\d+),?(\d*)\s*@@/g;
449
-
450
- let match;
451
- let lastIndex = 0;
452
- const diffs = [];
453
-
454
- // Find all file diffs
455
- while ((match = diffRegex.exec(diffContent)) !== null) {
456
- if (diffs.length > 0) {
457
- diffs[diffs.length - 1].end = match.index;
458
- }
459
- diffs.push({
460
- path: match[2],
461
- start: match.index,
462
- end: diffContent.length
463
- });
464
- }
465
-
466
- // Extract added content for each file
467
- for (const diff of diffs) {
468
- const diffSection = diffContent.substring(diff.start, diff.end);
469
- const addedLines = [];
470
-
471
- // Get added lines (starting with +)
472
- const lines = diffSection.split("\n");
473
- for (const line of lines) {
474
- if (line.startsWith("+") && !line.startsWith("+++")) {
475
- addedLines.push(line.substring(1));
476
- }
477
- }
478
-
479
- if (addedLines.length > 0) {
480
- files.push({
481
- path: diff.path,
482
- content: addedLines.join("\n"),
483
- isPartial: true
484
- });
485
- }
486
- }
487
-
488
- return files;
489
- }
490
-
491
- /**
492
- * Create a finding object
493
- */
494
- createFinding(rule, categoryId, filePath, line, match) {
495
- const category = this.categories[categoryId];
496
-
497
- return {
498
- id: crypto.randomBytes(4).toString("hex"),
499
- ruleId: rule.id,
500
- ruleName: rule.name,
501
- category: categoryId,
502
- categoryName: category.name,
503
- categoryIcon: category.icon,
504
- severity: rule.severity,
505
- file: filePath,
506
- line,
507
- match: match ? match.substring(0, 100) : null,
508
- message: rule.message,
509
- fix: rule.fix,
510
- confidence: this.calculateConfidence(rule, match)
511
- };
512
- }
513
-
514
- /**
515
- * Calculate confidence based on rule and match
516
- */
517
- calculateConfidence(rule, match) {
518
- let confidence = 0.8; // Base confidence
519
-
520
- // Adjust based on severity
521
- if (rule.severity === "critical") confidence += 0.1;
522
- if (rule.severity === "info") confidence -= 0.1;
523
-
524
- // Adjust based on previous feedback
525
- const feedbackKey = rule.id;
526
- const feedback = this.feedback.get(feedbackKey);
527
- if (feedback) {
528
- confidence += (feedback.accepted - feedback.rejected) * 0.05;
529
- }
530
-
531
- return Math.max(0.3, Math.min(0.99, confidence));
532
- }
533
-
534
- /**
535
- * Check if path should be ignored
536
- */
537
- shouldIgnore(filePath) {
538
- for (const pattern of this.ignorePaths) {
539
- const regex = new RegExp(
540
- pattern
541
- .replace(/\*\*/g, ".*")
542
- .replace(/\*/g, "[^/]*")
543
- );
544
- if (regex.test(filePath)) {
545
- return true;
546
- }
547
- }
548
- return false;
549
- }
550
-
551
- /**
552
- * Summarize findings for a file
553
- */
554
- summarizeFindings(findings) {
555
- const bySeverity = {
556
- critical: findings.filter(f => f.severity === "critical").length,
557
- high: findings.filter(f => f.severity === "high").length,
558
- medium: findings.filter(f => f.severity === "medium").length,
559
- low: findings.filter(f => f.severity === "low").length,
560
- info: findings.filter(f => f.severity === "info").length
561
- };
562
-
563
- return {
564
- total: findings.length,
565
- bySeverity,
566
- needsAttention: bySeverity.critical > 0 || bySeverity.high > 0
567
- };
568
- }
569
-
570
- /**
571
- * Generate overall summary
572
- */
573
- generateOverallSummary() {
574
- const allFindings = this.results.flatMap(r => r.findings);
575
-
576
- const bySeverity = {
577
- critical: allFindings.filter(f => f.severity === "critical"),
578
- high: allFindings.filter(f => f.severity === "high"),
579
- medium: allFindings.filter(f => f.severity === "medium"),
580
- low: allFindings.filter(f => f.severity === "low"),
581
- info: allFindings.filter(f => f.severity === "info")
582
- };
583
-
584
- const byCategory = {};
585
- for (const finding of allFindings) {
586
- if (!byCategory[finding.category]) {
587
- byCategory[finding.category] = [];
588
- }
589
- byCategory[finding.category].push(finding);
590
- }
591
-
592
- return {
593
- filesReviewed: this.results.length,
594
- totalFindings: allFindings.length,
595
- bySeverity: {
596
- critical: bySeverity.critical.length,
597
- high: bySeverity.high.length,
598
- medium: bySeverity.medium.length,
599
- low: bySeverity.low.length,
600
- info: bySeverity.info.length
601
- },
602
- byCategory: Object.fromEntries(
603
- Object.entries(byCategory).map(([k, v]) => [k, v.length])
604
- ),
605
- blockers: bySeverity.critical.length + bySeverity.high.length,
606
- verdict: this.calculateVerdict(bySeverity)
607
- };
608
- }
609
-
610
- /**
611
- * Calculate review verdict
612
- */
613
- calculateVerdict(bySeverity) {
614
- if (bySeverity.critical.length > 0) {
615
- return {
616
- status: "BLOCK",
617
- message: `${bySeverity.critical.length} critical issue(s) must be fixed`,
618
- icon: "🛑"
619
- };
620
- }
621
-
622
- if (bySeverity.high.length > 2) {
623
- return {
624
- status: "REQUEST_CHANGES",
625
- message: `${bySeverity.high.length} high-severity issues need attention`,
626
- icon: "⚠️"
627
- };
628
- }
629
-
630
- if (bySeverity.high.length > 0 || bySeverity.medium.length > 5) {
631
- return {
632
- status: "COMMENT",
633
- message: "Some issues to consider before merging",
634
- icon: "💬"
635
- };
636
- }
637
-
638
- return {
639
- status: "APPROVE",
640
- message: "Code looks good!",
641
- icon: "✅"
642
- };
643
- }
644
-
645
- // ═══════════════════════════════════════════════════════════════════════════
646
- // PR COMMENT GENERATION
647
- // ═══════════════════════════════════════════════════════════════════════════
648
-
649
- /**
650
- * Generate PR comment markdown
651
- */
652
- generatePRComment() {
653
- const summary = this.generateOverallSummary();
654
-
655
- let comment = `## ${summary.verdict.icon} Code Review - ${summary.verdict.status}\n\n`;
656
- comment += `${summary.verdict.message}\n\n`;
657
-
658
- // Summary table
659
- comment += `### Summary\n`;
660
- comment += `| Metric | Value |\n`;
661
- comment += `|--------|-------|\n`;
662
- comment += `| Files Reviewed | ${summary.filesReviewed} |\n`;
663
- comment += `| Total Findings | ${summary.totalFindings} |\n`;
664
- comment += `| Critical | ${summary.bySeverity.critical} |\n`;
665
- comment += `| High | ${summary.bySeverity.high} |\n`;
666
- comment += `| Medium | ${summary.bySeverity.medium} |\n`;
667
- comment += `| Low + Info | ${summary.bySeverity.low + summary.bySeverity.info} |\n\n`;
668
-
669
- // Critical and high severity findings
670
- const urgent = this.results.flatMap(r => r.findings)
671
- .filter(f => f.severity === "critical" || f.severity === "high");
672
-
673
- if (urgent.length > 0) {
674
- comment += `### 🚨 Issues Requiring Attention\n\n`;
675
-
676
- for (const finding of urgent.slice(0, 10)) {
677
- comment += `<details>\n`;
678
- comment += `<summary><strong>${finding.categoryIcon} ${finding.ruleName}</strong> - ${finding.file}:${finding.line}</summary>\n\n`;
679
- comment += `**Severity:** ${finding.severity.toUpperCase()}\n\n`;
680
- comment += `**Issue:** ${finding.message}\n\n`;
681
- if (finding.match) {
682
- comment += `**Code:**\n\`\`\`\n${finding.match}\n\`\`\`\n\n`;
683
- }
684
- comment += `**Suggested Fix:** ${finding.fix}\n\n`;
685
- comment += `</details>\n\n`;
686
- }
687
-
688
- if (urgent.length > 10) {
689
- comment += `\n_...and ${urgent.length - 10} more urgent issues_\n\n`;
690
- }
691
- }
692
-
693
- // Other findings grouped by category
694
- comment += `### Other Findings by Category\n\n`;
695
-
696
- for (const [categoryId, category] of Object.entries(this.categories)) {
697
- const categoryFindings = this.results.flatMap(r => r.findings)
698
- .filter(f => f.category === categoryId &&
699
- f.severity !== "critical" &&
700
- f.severity !== "high");
701
-
702
- if (categoryFindings.length > 0) {
703
- comment += `<details>\n`;
704
- comment += `<summary>${category.icon} ${category.name} (${categoryFindings.length})</summary>\n\n`;
705
-
706
- for (const finding of categoryFindings.slice(0, 5)) {
707
- comment += `- **${finding.ruleName}** - \`${finding.file}:${finding.line}\`\n`;
708
- comment += ` ${finding.message}\n\n`;
709
- }
710
-
711
- if (categoryFindings.length > 5) {
712
- comment += `_...and ${categoryFindings.length - 5} more_\n`;
713
- }
714
-
715
- comment += `</details>\n\n`;
716
- }
717
- }
718
-
719
- // Footer
720
- comment += `---\n`;
721
- comment += `_Automated review by Vibecheck AI Code Review_\n`;
722
-
723
- return comment;
724
- }
725
-
726
- /**
727
- * Generate inline comments for PR
728
- */
729
- generateInlineComments() {
730
- const comments = [];
731
-
732
- for (const result of this.results) {
733
- for (const finding of result.findings) {
734
- comments.push({
735
- path: finding.file,
736
- line: finding.line,
737
- body: `${finding.categoryIcon} **${finding.ruleName}**\n\n` +
738
- `${finding.message}\n\n` +
739
- `**Suggested fix:** ${finding.fix}\n\n` +
740
- `_Severity: ${finding.severity} | Confidence: ${(finding.confidence * 100).toFixed(0)}%_`
741
- });
742
- }
743
- }
744
-
745
- return comments;
746
- }
747
-
748
- // ═══════════════════════════════════════════════════════════════════════════
749
- // FEEDBACK & LEARNING
750
- // ═══════════════════════════════════════════════════════════════════════════
751
-
752
- /**
753
- * Record feedback on a finding
754
- */
755
- recordFeedback(findingId, accepted) {
756
- const finding = this.results
757
- .flatMap(r => r.findings)
758
- .find(f => f.id === findingId);
759
-
760
- if (!finding) return;
761
-
762
- const key = finding.ruleId;
763
- if (!this.feedback.has(key)) {
764
- this.feedback.set(key, { accepted: 0, rejected: 0 });
765
- }
766
-
767
- const fb = this.feedback.get(key);
768
- if (accepted) {
769
- fb.accepted++;
770
- } else {
771
- fb.rejected++;
772
- }
773
- }
774
-
775
- /**
776
- * Export feedback for persistence
777
- */
778
- exportFeedback() {
779
- return Object.fromEntries(this.feedback);
780
- }
781
-
782
- /**
783
- * Import feedback from persistence
784
- */
785
- importFeedback(data) {
786
- this.feedback = new Map(Object.entries(data));
787
- }
788
-
789
- // ═══════════════════════════════════════════════════════════════════════════
790
- // CUSTOM RULES
791
- // ═══════════════════════════════════════════════════════════════════════════
792
-
793
- /**
794
- * Add a custom rule
795
- */
796
- addRule(categoryId, rule) {
797
- if (!this.categories[categoryId]) {
798
- this.categories[categoryId] = {
799
- name: categoryId,
800
- icon: "📋",
801
- rules: []
802
- };
803
- }
804
-
805
- // Compile pattern if string
806
- if (typeof rule.pattern === "string") {
807
- rule.pattern = new RegExp(rule.pattern, "gm");
808
- }
809
-
810
- this.categories[categoryId].rules.push(rule);
811
- }
812
-
813
- /**
814
- * Add a custom category
815
- */
816
- addCategory(categoryId, category) {
817
- this.categories[categoryId] = {
818
- name: category.name || categoryId,
819
- icon: category.icon || "📋",
820
- rules: category.rules || []
821
- };
822
- }
823
- }
824
-
825
- // ═══════════════════════════════════════════════════════════════════════════════
826
- // EXPORTS
827
- // ═══════════════════════════════════════════════════════════════════════════════
828
-
829
- module.exports = {
830
- AICodeReviewEngine,
831
- REVIEW_CATEGORIES
832
- };