-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkarpeslop-bin.js
More file actions
executable file
·1236 lines (1145 loc) · 50.5 KB
/
karpeslop-bin.js
File metadata and controls
executable file
·1236 lines (1145 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env npx tsx
/**
* AI Slop Detection Tool for Food Truck Finder Application
*
* This tool identifies common AI-generated code patterns that represent "AI Slop"
* including excessive use of `any` types, unsafe type assertions, and other problematic patterns.
*
* Follows industry best practices based on typescript-eslint patterns.
*/
import fs from 'fs';
import path from 'path';
import { glob } from 'glob';
import { fileURLToPath } from 'url';
// Phase 6: Configuration file support
class AISlopDetector {
issues = [];
targetExtensions = ['.ts', '.tsx', '.js', '.jsx'];
// Core application directories to prioritize in reporting
coreAppDirs = ['app/', 'components/', 'lib/', 'hooks/', 'services/'];
detectionPatterns = [
// ==================== AXIS 1: INFORMATION UTILITY (Noise) ====================
{
id: 'redundant_self_explanatory_comment',
pattern: /const\s+(\w+)\s*=\s*\1\s*;?\s*\/\/.?(?:set|assign|store)\s+\1\b/gi,
message: "Redundant comment explaining variable assignment to itself — peak AI slop",
severity: 'high',
description: 'e.g., const count = count; // assign count to count'
}, {
id: 'excessive_boilerplate_comment',
pattern: /\/\/\s*This (?:function|component|hook|variable|method).* (?:does|is|handles?|returns?|takes?|processes?)/gi,
message: "Boilerplate comment that restates the obvious — adds zero insight",
severity: 'medium',
description: 'AI-generated comments that explain the obvious'
}, {
id: 'debug_log_with_comment',
pattern: /console\.(log|debug|info)\([^)]+\)\s*;\s*\/\/\s*(?:debug|temp|test|check|log|print)/gi,
message: "Debug log with apologetic comment — AI trying to justify its existence",
severity: 'medium',
description: 'Debugging code that should not be in production',
skipTests: true
},
// ==================== AXIS 2: INFORMATION QUALITY (Hallucinations) ====================
{
id: 'hallucinated_react_import',
pattern: /import\s*{\s*(useRouter|useParams|useSearchParams|Link|Image|Script)\s*}\s*from\s*['"]react['"]/gi,
message: "Hallucinated React import — these do NOT exist in 'react'",
severity: 'critical',
description: 'React-specific APIs are NOT in the react package',
fix: "Import from correct package: 'next/router', 'next/link', 'next/image', 'next/script'",
learnMore: 'https://nextjs.org/docs/api-reference/next/router'
}, {
id: 'hallucinated_next_import',
pattern: /import\s*{\s*(getServerSideProps|getStaticProps|getStaticPaths)\s*}\s*from\s*['"]react['"]/gi,
message: "Next.js API imported from 'react' — 100% AI hallucination",
severity: 'critical',
description: 'Next.js APIs are NOT in the react package',
fix: "These are page-level exports, not imports. Export them from your page file directly.",
learnMore: 'https://nextjs.org/docs/basic-features/data-fetching'
}, {
id: 'todo_implementation_placeholder',
pattern: /\/\/\s*(?:TODO|FIXME|HACK).*(?:implement|add|finish|complete|your code|logic|here)/gi,
message: "AI gave up and wrote a TODO instead of thinking",
severity: 'high',
description: 'Placeholder comments where AI failed to implement',
fix: "Actually implement the logic, or if blocked, document WHY and create a tracking issue",
learnMore: 'https://refactoring.guru/smells/comments'
}, {
id: 'assumption_comment',
pattern: /\b(assuming|assumes?|presumably|apparently|it seems|seems like)\b.{0,50}\b(that|this|the|it)\b/gi,
message: "AI making unverified assumptions — dangerous in production",
severity: 'high',
description: 'Comments indicating unverified assumptions'
},
// ==================== AXIS 3: STYLE / TASTE (The Vibe Check) ====================
{
id: 'overconfident_comment',
pattern: /\/\/.*\b(obviously|clearly|simply|just|easy|trivial|basically|literally|of course|naturally|certainly|surely)\b/gi,
message: "Overconfident comment — AI pretending it understands when it doesn't",
severity: 'high',
description: 'Overconfident language indicating false certainty'
}, {
id: 'hedging_uncertainty_comment',
pattern: /\/\/.*\b(should work|hopefully|probably|might work|try this|i think|seems to|attempting to|looks like|appears to)\b/gi,
message: "AI hedging its bets — classic sign of low-confidence generation",
severity: 'high',
description: 'Uncertain language masked as implementation'
}, {
id: 'unnecessary_iife_wrapper',
pattern: /\bconst\s+\w+\s*=\s*\(\s*async\s*\(\)\s*=>\s*\{[\s\S]*?\}\)\(\)/g,
message: "Unnecessary IIFE wrapper — AI over-engineering a simple async call",
severity: 'medium',
description: 'Unnecessarily complex function wrapping'
}, {
id: 'vibe_coded_ternary_abuse',
pattern: /\?\s*['"][^'"]+['"]\s*:\s*['"][^'"]+['"]\s*\?\s*['"][^'"]+['"]\s*:\s*['"][^'"]+['"]/g,
message: "Nested ternary hell — AI trying to look clever",
severity: 'medium',
description: 'Overly complex nested ternary operations',
fix: "Extract to a switch statement or a lookup object for better readability"
}, {
id: 'magic_css_value',
pattern: /(\d{3,4}px|#[0-9a-fA-F]{3,8}\b|rgba?\([^)]+\)|hsl\(\d+)/g,
message: "Magic CSS value — extract to design token or const",
severity: 'low',
description: 'Hardcoded CSS values that should be constants',
fix: "Move to CSS variables, theme tokens, or a constants file"
},
// ==================== PHASE 5: REACT-SPECIFIC ANTI-PATTERNS ====================
{
id: 'useEffect_derived_state',
pattern: /useEffect\s*\(\s*\(\s*\)\s*=>\s*\{[^}]*set[A-Z]\w*\([^)]*\)/g,
message: "useEffect setting state from props/other state — consider useMemo or compute in render",
severity: 'high',
description: 'Using useEffect to derive state is often unnecessary',
fix: "If state depends only on props/other state, compute directly or use useMemo instead",
learnMore: 'https://react.dev/learn/you-might-not-need-an-effect'
}, {
id: 'useEffect_empty_deps_suspicious',
pattern: /useEffect\s*\([^,]+,\s*\[\s*\]\s*\)/g,
message: "useEffect with empty deps — verify this truly should only run on mount",
severity: 'medium',
description: 'Empty dependency arrays are often a sign of missing dependencies',
fix: "Review if effect depends on any props/state. Use eslint-plugin-react-hooks to catch issues.",
learnMore: 'https://react.dev/reference/react/useEffect#specifying-reactive-dependencies'
}, {
id: 'setState_in_loop',
pattern: /(?:for|while|forEach|map)\s*\([^)]+\)[^{]*\{[^}]*set[A-Z]\w*\(/g,
message: "setState inside a loop — may cause multiple re-renders",
severity: 'high',
description: 'Calling setState in a loop triggers multiple re-renders',
fix: "Batch updates by computing the final state outside the loop, then call setState once",
learnMore: 'https://react.dev/learn/queueing-a-series-of-state-updates'
}, {
id: 'useCallback_no_deps',
pattern: /useCallback\s*\([^,]+,\s*\[\s*\]\s*\)/g,
message: "useCallback with empty deps — the callback never updates",
severity: 'medium',
description: 'Empty deps means the callback is stale and may use outdated values',
fix: "Add all values used inside the callback to the dependency array",
learnMore: 'https://react.dev/reference/react/useCallback'
},
// ==================== ORIGINAL PATTERNS ====================
{
id: 'any_type_usage',
pattern: /:\s*any\b/g,
message: "Found 'any' type usage. Replace with specific type or unknown.",
severity: 'high',
description: 'Detects : any type annotations',
fix: "Replace with 'unknown' and use type guards to narrow, or define a proper interface",
learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html'
}, {
id: 'array_any_type',
pattern: /Array\s*<\s*any\s*>/g,
message: "Found Array<any> type usage. Replace with specific type or unknown[].",
severity: 'high',
description: 'Detects Array<any> patterns'
}, {
id: 'generic_any_type',
pattern: /<\s*any\s*>/g,
message: "Found generic <any> type usage. Replace with specific type or unknown.",
severity: 'high',
description: 'Detects generic type parameters with any'
}, {
id: 'function_param_any_type',
pattern: /\(\s*.*\s*:\s*any\s*\)/g,
message: "Found function parameter with 'any' type. Replace with specific type or unknown.",
severity: 'high',
description: 'Detects function parameters with any type'
}, {
id: 'unsafe_type_assertion',
pattern: /\s+as\s+any\b/g,
message: "Found unsafe 'as any' type assertion. Use proper type guards or validation.",
severity: 'high',
description: 'Detects unsafe as any assertions',
fix: "Use 'as unknown as TargetType' or implement a runtime type guard with validation",
learnMore: 'https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates'
}, {
id: 'unsafe_double_type_assertion',
pattern: /as\s+\w+\s+as\s+\w+/g,
message: "Found unsafe double type assertion. Consider using 'as unknown as Type' for safe conversions.",
severity: 'high',
description: 'Detects unsafe double type assertions'
}, {
id: 'index_signature_any',
pattern: /\[\s*["'`]?(\w+)["'`]?[^\]]*\]\s*:\s*any/g,
message: "Found index signature with 'any' type. Replace with specific type or unknown.",
severity: 'high',
description: 'Detects index signatures with any type'
}, {
id: 'missing_error_handling',
pattern: /\b(fetch|axios|http)\s*\(/g,
message: "Potential missing error handling for promise. Consider adding try/catch or .catch().",
severity: 'medium',
description: 'Detects calls that might need error handling',
fix: "Wrap in try/catch or add .catch() handler. Consider React Query or SWR for data fetching.",
learnMore: 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch',
skipTests: true
}, {
id: 'production_console_log',
pattern: /console\.(log|warn|error|info|debug|trace)\(/g,
message: "Found console logging in production code. Remove before deployment.",
severity: 'medium',
description: 'Detects console logs in production code',
skipTests: true,
skipMocks: true
}, {
id: 'todo_comment',
pattern: /\b(TODO|FIXME|HACK|XXX|BUG)\b/g,
message: "Found TODO/FIXME/HACK comment indicating incomplete implementation.",
severity: 'medium',
description: 'Detects incomplete implementation markers'
},
// Note: complex_nested_conditionals is handled separately below with improved logic
{
id: 'unsafe_member_access',
pattern: /\.\s*any\s*\[/g,
message: "Found potentially unsafe member access on 'any' type.",
severity: 'high',
description: 'Detects unsafe member access patterns'
}];
config = {};
customIgnorePaths = [];
constructor(rootDir) {
this.rootDir = rootDir;
this.loadConfig();
}
/**
* Validate configuration structure (Issue 3 fix)
* Basic validation without external dependencies
*/
validateConfig(config) {
if (typeof config !== 'object' || config === null) {
throw new Error('Config must be an object');
}
const validSeverities = ['critical', 'high', 'medium', 'low'];
const cfg = config;
// Validate customPatterns
if (cfg.customPatterns !== undefined) {
if (!Array.isArray(cfg.customPatterns)) {
throw new Error('customPatterns must be an array');
}
for (let i = 0; i < cfg.customPatterns.length; i++) {
const pattern = cfg.customPatterns[i];
if (!pattern.id || typeof pattern.id !== 'string') {
throw new Error(`customPatterns[${i}].id must be a string`);
}
if (!pattern.pattern || typeof pattern.pattern !== 'string') {
throw new Error(`customPatterns[${i}].pattern must be a string`);
}
if (!pattern.message || typeof pattern.message !== 'string') {
throw new Error(`customPatterns[${i}].message must be a string`);
}
if (!pattern.severity || !validSeverities.includes(pattern.severity)) {
throw new Error(`customPatterns[${i}].severity must be one of: ${validSeverities.join(', ')}`);
}
// Validate regex is valid
try {
new RegExp(pattern.pattern, 'gi');
} catch (e) {
throw new Error(`customPatterns[${i}].pattern is not a valid regex: ${pattern.pattern}`);
}
}
}
// Validate severityOverrides
if (cfg.severityOverrides !== undefined) {
if (typeof cfg.severityOverrides !== 'object' || cfg.severityOverrides === null) {
throw new Error('severityOverrides must be an object');
}
for (const [key, value] of Object.entries(cfg.severityOverrides)) {
if (!validSeverities.includes(value)) {
throw new Error(`severityOverrides.${key} must be one of: ${validSeverities.join(', ')}`);
}
}
}
// Validate ignorePaths
if (cfg.ignorePaths !== undefined) {
if (!Array.isArray(cfg.ignorePaths)) {
throw new Error('ignorePaths must be an array of strings');
}
for (let i = 0; i < cfg.ignorePaths.length; i++) {
if (typeof cfg.ignorePaths[i] !== 'string') {
throw new Error(`ignorePaths[${i}] must be a string`);
}
}
}
return cfg;
}
/**
* Load configuration from .karpesloprc.json if it exists
*/
loadConfig() {
const configPaths = [path.join(this.rootDir, '.karpesloprc.json'), path.join(this.rootDir, '.karpesloprc'), path.join(this.rootDir, 'karpeslop.config.json')];
for (const configPath of configPaths) {
if (fs.existsSync(configPath)) {
try {
const configContent = fs.readFileSync(configPath, 'utf-8');
const rawConfig = JSON.parse(configContent);
// Issue 3: Validate config before using
this.config = this.validateConfig(rawConfig);
console.log(`📋 Loaded config from ${path.basename(configPath)}\n`);
// Add custom patterns
if (this.config.customPatterns) {
for (const customPattern of this.config.customPatterns) {
this.detectionPatterns.push({
id: customPattern.id,
pattern: new RegExp(customPattern.pattern, 'gi'),
message: customPattern.message,
severity: customPattern.severity,
description: customPattern.description || customPattern.message,
fix: customPattern.fix,
learnMore: customPattern.learnMore
});
}
console.log(` Added ${this.config.customPatterns.length} custom pattern(s)`);
}
// Apply severity overrides
if (this.config.severityOverrides) {
for (const [patternId, newSeverity] of Object.entries(this.config.severityOverrides)) {
const pattern = this.detectionPatterns.find(p => p.id === patternId);
if (pattern) {
pattern.severity = newSeverity;
}
}
}
// Store ignore paths
if (this.config.ignorePaths) {
this.customIgnorePaths = this.config.ignorePaths;
}
break; // Stop after finding first valid config
} catch (error) {
console.warn(`⚠️ Failed to parse config at ${configPath}:`, error);
}
}
}
}
/**
* Run the AI Slop detection across the codebase
*/
async detect(quiet = false) {
console.log('🔍 Starting AI Slop detection...\n');
// 1. Find all TypeScript/JavaScript files
const allFiles = this.findAllFiles();
// Filter files based on quiet mode (skip non-core files if quiet is true)
const filesToAnalyze = quiet ? allFiles.filter(file => {
const relativePath = path.relative(this.rootDir, file).replace(/\\/g, '/');
return this.coreAppDirs.some(dir => relativePath.startsWith(dir));
}) : allFiles;
console.log(`📁 Found ${allFiles.length} files to analyze (${filesToAnalyze.length} in ${quiet ? 'quiet' : 'full'} mode)\n`);
// 2. Analyze each file for AI Slop patterns
for (const file of filesToAnalyze) {
this.analyzeFile(file, quiet);
}
// 3. Report findings
this.generateReport(quiet);
return this.issues;
}
/**
* Find all TypeScript/JavaScript files in the project
*/
findAllFiles() {
const allFiles = [];
for (const ext of this.targetExtensions) {
const pattern = path.join(this.rootDir, `**/*${ext}`).replace(/\\/g, '/');
const files = glob.sync(pattern, {
ignore: ['node_modules/**', '.next/**', 'dist/**', 'build/**', 'coverage/**', 'generated/**',
// Prisma generated files
'.vercel/**',
// Vercel build files
'.git/**',
// Git files
'**/types/**',
// Exclude type definition files
'**/node_modules/**', '**/.*',
// Hidden directories like .git (but not .tsx files)
'**/*.d.ts',
// Don't scan declaration files
'**/coverage/**',
// Coverage reports
'**/out/**',
// Next.js output directory
'**/temp/**',
// Temporary files
'scripts/ai-slop-detector.ts',
// Exclude the detector script itself to avoid false positives
'ai-slop-detector.ts',
// Also exclude when in root directory
'improved-ai-slop-detector.ts',
// Exclude the improved detector script to avoid false positives
...this.customIgnorePaths]
});
// Additional filtering to remove any generated files that may have slipped through
const filteredFiles = files.filter(file => {
const relativePath = path.relative(this.rootDir, file).replace(/\\/g, '/');
return !relativePath.includes('generated/') && !relativePath.includes('/generated') && !relativePath.startsWith('generated/') && !relativePath.includes('coverage/') && !relativePath.includes('.next/') && !relativePath.includes('node_modules/') && !relativePath.includes('dist/') && !relativePath.includes('build/') && !relativePath.includes('.git/') && !relativePath.includes('out/') && !relativePath.includes('temp/');
});
allFiles.push(...filteredFiles);
}
// Remove duplicates and return
return [...new Set(allFiles)];
}
/**
* Check if a fetch call is properly handled with try/catch or .catch()
*/
isFetchCallProperlyHandled(lines, fetchLineIndex) {
// Look in a reasonable range around the fetch call to see if it's in a try/catch block
// or has a .catch() or similar error handling
// First, find the function context containing this fetch call
let functionStart = -1;
let functionEnd = -1;
// Look backwards to find the start of the function
for (let i = fetchLineIndex; i >= Math.max(0, fetchLineIndex - 20); i--) {
const line = lines[i];
const isReactHook = line.includes('const') && (line.includes('useState') || line.includes('useEffect') || line.includes('useCallback') || line.includes('useMemo'));
if (line.includes('async function') || line.includes('function') || line.includes('=>') || isReactHook || line.includes('export default function')) {
// Check if this looks like the start of our function
if (line.includes('{') || line.includes('=>')) {
functionStart = i;
break;
}
}
// Check for arrow functions in the line above
if (i > 0 && (lines[i - 1] + line).includes('=>')) {
// Look for functions that end with an opening brace
if (line.trim().startsWith('{')) {
functionStart = i;
break;
}
}
}
// Look forwards to find the end of the function block
let braceCount = 0;
let inFunction = false;
for (let i = functionStart === -1 ? 0 : functionStart; i < lines.length && i < fetchLineIndex + 20; i++) {
const line = lines[i];
for (let j = 0; j < line.length; j++) {
if (line[j] === '{') {
braceCount++;
if (i === functionStart && braceCount === 1) {
inFunction = true;
}
} else if (line[j] === '}') {
braceCount--;
if (inFunction && braceCount === 0) {
functionEnd = i;
break;
}
}
}
if (functionEnd !== -1) break;
}
if (functionStart === -1 || functionEnd === -1) {
// If we can't find function boundaries, check the current line and nearby lines for error handling
// Check current line and 2 lines before and after
const start = Math.max(0, fetchLineIndex - 2);
const end = Math.min(lines.length, fetchLineIndex + 3);
for (let i = start; i < end; i++) {
const line = lines[i];
if (line.includes('.catch(') || line.includes('try {') || line.includes('try{') || i > 0 && lines[i - 1].includes('try') && line.includes('.catch(')) {
return true;
}
}
return false;
}
// Now check the entire function for try/catch or .catch
for (let i = functionStart; i <= functionEnd; i++) {
const line = lines[i];
if (line.includes('.catch(') || line.includes('try {') || line.includes('try{')) {
return true;
}
}
// Check if the fetch call is part of a promise chain that ends with .catch
const currentLine = lines[fetchLineIndex];
if (currentLine.includes('fetch(') && (currentLine.includes('.then(') || currentLine.includes('.catch('))) {
// Look for .catch in the same or following lines within the same statement
for (let i = fetchLineIndex; i < Math.min(lines.length, fetchLineIndex + 5); i++) {
const line = lines[i];
if (line.includes('.catch(')) {
return true;
}
// If we find another statement (not a continuation), stop looking
if (line.includes(';') && !line.trim().endsWith('\\') && !line.trim().endsWith(',')) {
break;
}
}
}
return false;
}
/**
* Analyze a single file for AI Slop patterns
*/
analyzeFile(filePath, quiet = false) {
const content = fs.readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
// Check if this is a test or mock file
const isTestFile = filePath.includes('__tests__') || filePath.includes('.test.') || filePath.includes('.spec.') || filePath.includes('__mocks__') || filePath.includes('test-');
const isMockFile = filePath.includes('__mocks__') || filePath.includes('mock');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNumber = i + 1;
// Apply each detection pattern
for (const pattern of this.detectionPatterns) {
// Skip certain patterns in test/mock files
if (pattern.skipTests && isTestFile || pattern.skipMocks && isMockFile) {
continue;
}
// Skip the complex_nested_conditionals pattern since we handle it separately
if (pattern.id === 'complex_nested_conditionals') {
continue;
}
// Create a new RegExp object for each check to reset lastIndex
const regex = new RegExp(pattern.pattern.source, pattern.pattern.flags);
let match;
while ((match = regex.exec(line)) !== null) {
// ========== PHASE 1: CONTEXT-AWARE WHITELISTING ==========
// Skip any pattern that has an explicit eslint-disable or ts-expect-error on the same or previous line
if (pattern.id.includes('any') || pattern.id.includes('unsafe')) {
const prevLine = i > 0 ? lines[i - 1] : '';
if (line.includes('eslint-disable') || line.includes('@ts-expect-error') || line.includes('@ts-ignore') || prevLine.includes('eslint-disable-next-line') || prevLine.includes('@ts-expect-error')) {
continue; // Developer explicitly acknowledged this
}
}
// Skip .d.ts declaration files entirely for 'any' related patterns
if (pattern.id.includes('any') && filePath.endsWith('.d.ts')) {
continue; // Declaration files often need 'any' for external library types
}
// Skip legitimate cases like expect.any() in tests
if (pattern.id === 'any_type_usage' && (line.includes('expect.any(') || line.includes('jest.fn()'))) {
continue;
}
// Skip JSX spread attributes which often legitimately use 'any'
if (pattern.id === 'any_type_usage' && line.includes('{...') && line.includes('as any')) {
continue;
}
// Skip legitimate JSON parsing patterns
if (pattern.id === 'any_type_usage' && (line.includes('JSON.parse(') || line.includes('.json') || line.includes('response.json'))) {
continue;
}
// Skip legitimate API response handling where 'any' is often unavoidable
if (pattern.id === 'any_type_usage' && (line.includes('ApiResponse') || line.includes('apiResponse') || line.includes('res.json') || line.includes('fetch') || line.includes('axios'))) {
continue;
}
// Skip legitimate uses of 'any' for dynamic data processing
if (pattern.id === 'any_type_usage' && (line.includes('data: any') || line.includes('(data: any)') || line.includes('result: any') || line.includes('response: any'))) {
// Check if it's in a function that processes dynamic data
if (line.includes('parse') || line.includes('process') || line.includes('transform')) {
continue;
}
}
// Special handling for function_param_any_type pattern
if (pattern.id === 'function_param_any_type') {
// Skip legitimate uses in data processing functions
if (line.includes('(data: any)') && (line.includes('parse') || line.includes('process') || line.includes('transform'))) {
continue;
}
// Skip legitimate uses in generic functions dealing with external data
if (line.includes('ApiResponse') || line.includes('apiResponse') || line.includes('JSON.parse') || line.includes('response: any')) {
continue;
}
}
// Special handling for missing error handling - look for properly handled fetch calls
if (pattern.id === 'missing_error_handling') {
const fullLine = line.trim();
// Skip matches inside comment lines (single-line, JSDoc, block)
if (fullLine.startsWith('//') || fullLine.startsWith('*') || fullLine.startsWith('/*')) {
continue;
}
// Check if this fetch call is part of a properly handled async function
const isProperlyHandled = this.isFetchCallProperlyHandled(lines, i);
if (isProperlyHandled) {
continue;
}
}
// Special handling for unsafe_double_type_assertion - skip legitimate UI library patterns
if (pattern.id === 'unsafe_double_type_assertion') {
const fullLine = line.trim();
// Skip patterns that are actually safe (as unknown as Type)
if (fullLine.includes('as unknown as')) {
continue;
}
// Skip matches inside comment lines (e.g., "as soon as React")
if (fullLine.startsWith('//') || fullLine.startsWith('*') || fullLine.startsWith('/*')) {
continue;
}
// Skip matches where the first word after "as" is a common English word
// indicating natural language rather than a type assertion
// e.g., "as soon as React hydrates" — "soon" is English, not a type
const firstWord = match[0].match(/^as\s+(\w+)/i)?.[1]?.toLowerCase();
const englishWords = ['soon', 'quick', 'quickly', 'fast', 'smooth', 'long', 'much', 'little', 'well', 'good', 'bad', 'easy', 'hard', 'simple', 'clear', 'many', 'few', 'close', 'far', 'near'];
if (firstWord && englishWords.includes(firstWord)) {
continue;
}
}
// Special handling for production_console_log - skip legitimate error handling and debugging patterns
if (pattern.id === 'production_console_log') {
const fullLine = line.trim();
// Skip console.error logs inside catch blocks (legitimate error handling)
if (fullLine.includes('console.error(') && this.isInTryCatchBlock(lines, i)) {
continue;
}
// Skip console calls guarded by a conditional on the same line
// e.g., if (isDev) console.log('debug');
if (/^if\s*\(/.test(fullLine)) {
continue;
}
// Skip console calls inside a conditional block opened on a prior line
if (i > 0) {
const prevLine = lines[i - 1].trim();
if (/^if\s*\(/.test(prevLine) && !prevLine.includes('function') && (prevLine.includes('{') || fullLine.startsWith('{') === false)) {
continue;
}
}
// Skip general debugging logs that might be intentional in development
if (fullLine.includes('console.log(') && (fullLine.includes('Debug') || fullLine.includes('debug') || fullLine.includes('debug:'))) {
continue;
}
// Skip console logs that contain the word 'error' in a non-error context (like error handling)
if ((fullLine.includes('console.log(') || fullLine.includes('console.info(')) && (fullLine.includes('error') || fullLine.includes('Error'))) {
continue;
}
}
// Special handling for hedging_uncertainty_comment - skip legitimate test patterns
if (pattern.id === 'hedging_uncertainty_comment' || pattern.id === 'assumption_comment') {
// Skip these patterns in test files where they might be legitimate test descriptions
if (filePath.includes('test') || filePath.includes('spec') || filePath.includes('__tests__')) {
continue;
}
// Skip common English phrases that are not code-related
const fullLine = line.trim().toLowerCase();
if (fullLine.includes('should work') && (fullLine.includes('//') || fullLine.includes('/*') || fullLine.includes('*/'))) {
// This is likely a comment in a test file
continue;
}
}
// Special handling for unsafe_type_assertion - skip legitimate test patterns
if (pattern.id === 'unsafe_type_assertion') {
// Skip these in test files where they might be legitimate for testing
if (filePath.includes('test') || filePath.includes('spec') || filePath.includes('__tests__')) {
continue;
}
}
// In quiet mode, skip test and mock files for all patterns except production console logs
if (quiet && pattern.id !== 'production_console_log') {
const isTestFile = filePath.includes('__tests__') || filePath.includes('.test.') || filePath.includes('.spec.') || filePath.includes('__mocks__') || filePath.includes('test-');
if (isTestFile) {
continue;
}
}
this.issues.push({
type: pattern.id,
file: filePath,
line: lineNumber,
column: match.index + 1,
code: match[0],
message: `${pattern.message} (${pattern.description})`,
severity: pattern.severity
});
}
}
// Now handle complex nested conditionals separately with improved logic
this.analyzeComplexNestedConditionals(filePath, lines, i, lineNumber, line);
}
}
/**
* Analyze complex nested conditionals using a more sophisticated approach
* This tracks nesting depth rather than just finding control structure keywords
*/
analyzeComplexNestedConditionals(filePath, lines, lineIndex, lineNumber, line) {
// Count opening braces in this line to determine if we're entering nested blocks
const ifMatches = line.match(/\bif\s*\(/g);
const forMatches = line.match(/\bfor\s*\(/g);
const whileMatches = line.match(/\bwhile\s*\(/g);
// Only flag if there are potentially nested control structures in a single line
// or if the line has multiple indicators of complexity
if (ifMatches && ifMatches.length > 1 || forMatches && forMatches.length > 1 || whileMatches && whileMatches.length > 1 || ifMatches && (forMatches || whileMatches) || forMatches && whileMatches) {
this.issues.push({
type: 'complex_nested_conditionals',
file: filePath,
line: lineNumber,
column: 1,
code: line.trim(),
message: "Found potentially complex nested control structures in a single line. Consider refactoring for readability.",
severity: 'medium'
});
}
// Also look for deeply nested if statements across multiple lines
// Count indentation to detect nesting
const indentation = line.search(/\S/); // Get leading whitespace length
if (indentation >= 16 && (line.includes('if (') || line.includes('for (') || line.includes('while ('))) {
// This might indicate a highly nested structure
// But first, verify it's not a simple case like formatting
const trimmedLine = line.trim();
if (!trimmedLine.startsWith('//') && !trimmedLine.includes('=>')) {
// Skip comments and arrow functions
this.issues.push({
type: 'complex_nested_conditionals',
file: filePath,
line: lineNumber,
column: indentation + 1,
code: line.trim(),
message: "Highly indented control structure suggests deep nesting. Consider refactoring for readability.",
severity: 'medium'
});
}
}
}
/**
* Check if a particular line is within a try-catch block
* Used to determine if console.error is legitimate error handling
*/
isInTryCatchBlock(lines, lineIndex) {
let braceDepth = 0;
let inCatchBlock = false;
let catchBlockDepth = -1;
let nestedDepth = 0;
let pendingExit = false;
for (let i = 0; i <= lineIndex; i++) {
const line = lines[i];
const hasCatch = line.includes('catch (') || line.includes('catch(');
const catchOnSameLineAsCloseBrace = hasCatch && line.trim().startsWith('}');
for (let j = 0; j < line.length; j++) {
if (line[j] === '{') {
if (inCatchBlock && !catchOnSameLineAsCloseBrace) {
if (braceDepth >= catchBlockDepth) {
nestedDepth++;
}
}
braceDepth++;
} else if (line[j] === '}') {
braceDepth--;
if (inCatchBlock) {
if (nestedDepth > 0) {
nestedDepth--;
if (nestedDepth === 0) {
pendingExit = true;
}
} else if (braceDepth <= catchBlockDepth) {
inCatchBlock = false;
nestedDepth = 0;
pendingExit = false;
}
}
}
}
if (pendingExit) {
pendingExit = false;
}
if (hasCatch) {
if (line.includes('{')) {
if (catchOnSameLineAsCloseBrace) {
const closeBraceIdx = line.indexOf('}');
const catchIdx = line.indexOf('catch');
const openBraceIdx = line.indexOf('{', catchIdx);
if (closeBraceIdx !== -1 && closeBraceIdx < catchIdx && openBraceIdx > catchIdx) {
braceDepth--;
}
for (let j = 0; j < openBraceIdx; j++) {
if (line[j] === '{') braceDepth++;
}
for (let j = openBraceIdx + 1; j < line.length; j++) {
if (line[j] === '{') nestedDepth++;else if (line[j] === '}') {
nestedDepth--;
if (nestedDepth === 0) {
pendingExit = true;
}
}
}
inCatchBlock = true;
catchBlockDepth = braceDepth;
nestedDepth = 0;
} else {
inCatchBlock = true;
catchBlockDepth = braceDepth - 1;
nestedDepth = 0;
pendingExit = false;
}
} else {
for (let j = i + 1; j < Math.min(i + 5, lines.length); j++) {
if (lines[j].includes('{')) {
inCatchBlock = true;
catchBlockDepth = braceDepth;
nestedDepth = 0;
pendingExit = false;
break;
}
}
}
}
}
return inCatchBlock;
}
/**
* Generate a detailed report of findings
*/
generateReport(quiet = false) {
console.log('📊 AI Slop Detection Report');
console.log('============================\n');
if (this.issues.length === 0) {
console.log('✅ No AI Slop issues detected!');
return;
}
// Group issues by severity
const bySeverity = {
critical: this.issues.filter(i => i.severity === 'critical'),
high: this.issues.filter(i => i.severity === 'high'),
medium: this.issues.filter(i => i.severity === 'medium'),
low: this.issues.filter(i => i.severity === 'low')
};
console.log(`Found ${this.issues.length} AI Slop issues:`);
console.log(` Critical: ${bySeverity.critical.length}`);
console.log(` High: ${bySeverity.high.length}`);
console.log(` Medium: ${bySeverity.medium.length}`);
console.log(` Low: ${bySeverity.low.length}\n`);
// Display top issues by severity
['critical', 'high', 'medium', 'low'].forEach(severity => {
const issues = bySeverity[severity];
if (issues.length > 0) {
console.log(`\n${severity.toUpperCase()} SEVERITY ISSUES:`);
console.log(''.padStart(80, '-'));
// Group by type for better organization
const byType = {};
issues.slice(0, 20).forEach(issue => {
if (!byType[issue.type]) {
byType[issue.type] = [];
}
byType[issue.type].push(issue);
});
Object.entries(byType).forEach(([type, typeIssues]) => {
const sampleIssue = typeIssues[0];
// Find the pattern to get fix and learnMore info
const patternInfo = this.detectionPatterns.find(p => p.id === type);
console.log(`\n📍 Pattern: ${type}`);
console.log(` Description: ${sampleIssue.message.split('(').pop()?.replace(')', '') || ''}`);
// Phase 2: Show fix suggestions and learn more links
if (patternInfo?.fix) {
console.log(` 💡 Fix: ${patternInfo.fix}`);
}
if (patternInfo?.learnMore) {
console.log(` 📚 Learn more: ${patternInfo.learnMore}`);
}
console.log(` Sample occurrences: ${typeIssues.length}`);
// Show a few specific examples
typeIssues.slice(0, 3).forEach(issue => {
const relativePath = path.relative(this.rootDir, issue.file);
console.log(` → ${relativePath}:${issue.line} - ${issue.code}`);
});
if (typeIssues.length > 3) {
console.log(` ... and ${typeIssues.length - 3} more instances`);
}
});
if (issues.length > 20) {
console.log(`\n ... and ${issues.length - 20} more issues of this severity`);
}
}
});
// Provide summary statistics
console.log(`\n📈 SUMMARY STATISTICS:`);
console.log(''.padStart(80, '-'));
// Count by type
const byType = {};
this.issues.forEach(issue => {
byType[issue.type] = (byType[issue.type] || 0) + 1;
});
console.log('\nIssues by type:');
Object.entries(byType).sort((a, b) => b[1] - a[1]) // Sort by count
.slice(0, 10).forEach(([type, count]) => {
console.log(` ${type}: ${count}`);
});
// Files with most issues - show core application files separately
const fileCounts = {};
this.issues.forEach(issue => {
fileCounts[issue.file] = (fileCounts[issue.file] || 0) + 1;
});
// Split files into core app files and others
const allFiles = Object.entries(fileCounts);
const coreAppFiles = allFiles.filter(([file]) => {
const relativePath = path.relative(this.rootDir, file).replace(/\\/g, '/');
return this.coreAppDirs.some(dir => relativePath.startsWith(dir));
});
const otherFiles = allFiles.filter(([file]) => {
const relativePath = path.relative(this.rootDir, file).replace(/\\/g, '/');
return !this.coreAppDirs.some(dir => relativePath.startsWith(dir));
});
// Show core application files separately
const topCoreFiles = coreAppFiles.sort((a, b) => b[1] - a[1]).slice(0, 10);
console.log('\nTop CORE APPLICATION files with AI Slop issues:');
if (topCoreFiles.length > 0) {
topCoreFiles.forEach(([file, count]) => {
const relativePath = path.relative(this.rootDir, file);
console.log(` ${relativePath}: ${count} issues ★`);
});
} else {
console.log(' No core application files found with issues');
}
// In quiet mode, don't show other files (tests, scripts, mocks, etc.)
if (!quiet) {
// Also show other notable files if there's space
const topOtherFiles = otherFiles.sort((a, b) => b[1] - a[1]).slice(0, 5);
if (topOtherFiles.length > 0) {
console.log('\nTop OTHER files with AI Slop issues (utilities, scripts, etc.):');
topOtherFiles.forEach(([file, count]) => {
const relativePath = path.relative(this.rootDir, file);
console.log(` ${relativePath}: ${count} issues`);
});
}
}
// Add KarpeSlop scoring
const score = this.calculateKarpeSlopScore();
console.log(`\nKARPATHY SLOP INDEX™`);
console.log('═'.repeat(50));
console.log(`Information Utility (Noise) : ${score.informationUtility} pts`);
console.log(`Information Quality (Lies) : ${score.informationQuality} pts`);
console.log(`Style / Taste (Soul) : ${score.style} pts`);
console.log(`TOTAL KARPE-SLOP SCORE : ${score.total} pts`);
if (score.total === 0) {
console.log(`\nCLEAN. Even Andrej would approve.`);
console.log(` "This codebase has taste." — @karpathy, probably`);
} else if (score.total > 50) {
console.log(`\nSUEEEY! Here piggy piggy... this codebase is 100% slop-fed.`);
} else {
console.log(`\nAcceptable. But Karpathy is watching.`);
}
console.log('\n🔧 Next Steps:');
console.log('=============');
console.log('1. Address critical and high severity issues first');
console.log('2. Focus on removing `any` types and replacing with proper types');
console.log('3. Add proper error handling to asynchronous operations');
console.log('4. Refactor complex functions for better readability');
console.log('5. Remove development artifacts like TODO comments and console logs');
}