-
-
Notifications
You must be signed in to change notification settings - Fork 234
Expand file tree
/
Copy pathcheck-code-patterns.js
More file actions
executable file
·961 lines (853 loc) · 35.8 KB
/
check-code-patterns.js
File metadata and controls
executable file
·961 lines (853 loc) · 35.8 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
#!/usr/bin/env node
/**
* XcodeBuildMCP Code Pattern Violations Checker
*
* Validates that all code files follow XcodeBuildMCP-specific architectural patterns.
* This script focuses on domain-specific rules that ESLint cannot express.
*
* USAGE:
* node scripts/check-code-patterns.js [--pattern=vitest|execsync|handler|handler-testing|all]
* node scripts/check-code-patterns.js --help
*
* ARCHITECTURAL RULES ENFORCED:
* 1. External boundaries in tests should use dependency-injection utilities
* 2. NO execSync usage in production code (use CommandExecutor instead)
* 3. NO handler signature violations (handlers must have exact MCP SDK signatures)
* 4. NO handler testing violations (test logic functions, not handlers directly)
*
* For comprehensive code quality documentation, see docs/dev/CODE_QUALITY.md
*
* Note: General code quality rules (TypeScript, ESLint) are handled by other tools.
* This script only enforces XcodeBuildMCP-specific architectural patterns.
*/
import { readFileSync, readdirSync, statSync } from 'fs';
import { join, relative } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const projectRoot = join(__dirname, '..');
// Parse command line arguments
const args = process.argv.slice(2);
const patternFilter = args.find((arg) => arg.startsWith('--pattern='))?.split('=')[1] || 'all';
const showHelp = args.includes('--help') || args.includes('-h');
if (showHelp) {
console.log(`
XcodeBuildMCP Code Pattern Violations Checker
USAGE:
node scripts/check-code-patterns.js [options]
OPTIONS:
--pattern=TYPE Check specific pattern type (vitest|execsync|handler|handler-testing|server-typing|all) [default: all]
--help, -h Show this help message
PATTERN TYPES:
vitest Check only custom vitest policy violations (currently none)
execsync Check only execSync usage in production code
handler Check only handler signature violations
handler-testing Check only handler testing violations (testing handlers instead of logic functions)
server-typing Check only improper server typing violations (Record<string, unknown> casts)
all Check all pattern violations (default)
Note: General code quality (TypeScript, etc.) is handled by ESLint
EXAMPLES:
node scripts/check-code-patterns.js
node scripts/check-code-patterns.js --pattern=vitest
node scripts/check-code-patterns.js --pattern=handler
node scripts/check-code-patterns.js --pattern=handler-testing
node scripts/check-code-patterns.js --pattern=server-typing
`);
process.exit(0);
}
// Patterns for execSync usage in production code (FORBIDDEN)
// Note: execSync is allowed in test files for mocking, but not in production code
const EXECSYNC_PATTERNS = [
/\bexecSync\s*\(/, // Direct execSync usage
/\bexecSyncFn\s*[=:]/, // execSyncFn parameter or assignment
/^import\s+(?!type\s)[^}]*from\s+['"]child_process['"]/m, // Importing from child_process (except type-only imports)
/^import\s+{[^}]*(?:exec|spawn|execSync)[^}]*}\s+from\s+['"](?:node:)?child_process['"]/m, // Named imports of functions
];
// Vitest mocking is allowed for internal collaborators.
// Keep this list empty unless a specific project policy requires certain vitest patterns to be blocked.
const VITEST_GENERIC_PATTERNS = [];
// APPROVED mock utilities - ONLY these are allowed
const APPROVED_MOCK_PATTERNS = [
/\bcreateMockExecutor\b/,
/\bcreateMockFileSystemExecutor\b/,
/\bcreateNoopExecutor\b/,
/\bcreateNoopFileSystemExecutor\b/,
/\bcreateCommandMatchingMockExecutor\b/,
/\bcreateMockEnvironmentDetector\b/,
];
// Custom vitest restrictions can be added here if needed.
const UNAPPROVED_MOCK_PATTERNS = [];
// Function to check if a line contains unapproved mock patterns
function hasUnapprovedMockPattern(line) {
// Skip lines that contain approved patterns
const hasApprovedPattern = APPROVED_MOCK_PATTERNS.some((pattern) => pattern.test(line));
if (hasApprovedPattern) {
return false;
}
// Check for unapproved patterns
return UNAPPROVED_MOCK_PATTERNS.some((pattern) => pattern.test(line));
}
// Combined pattern checker for backward compatibility
const VITEST_MOCKING_PATTERNS = VITEST_GENERIC_PATTERNS;
// CRITICAL: ARCHITECTURAL VIOLATIONS - Utilities bypassing CommandExecutor (BANNED)
const UTILITY_BYPASS_PATTERNS = [
/spawn\s*\(/, // Direct Node.js spawn usage in utilities - BANNED
/exec\s*\(/, // Direct Node.js exec usage in utilities - BANNED
/execSync\s*\(/, // Direct Node.js execSync usage in utilities - BANNED
/child_process\./, // Direct child_process module usage in utilities - BANNED
];
// TypeScript patterns are now handled by ESLint - removed from domain-specific checks
// ESLint has comprehensive TypeScript rules with proper test file exceptions
// CRITICAL: HANDLER SIGNATURE VIOLATIONS ARE FORBIDDEN
// MCP SDK requires handlers to have exact signatures:
// Tools: (args: Record<string, unknown>) => Promise<ToolResponse>
// Resources: (uri: URL) => Promise<{ contents: Array<{ text: string }> }>
const HANDLER_SIGNATURE_VIOLATIONS = [
/async\s+handler\s*\([^)]*:\s*[^,)]+,\s*[^)]+\s*:/ms, // Handler with multiple parameters separated by comma - BANNED
/async\s+handler\s*\(\s*args\?\s*:/ms, // Handler with optional args parameter - BANNED (should be required)
/async\s+handler\s*\([^)]*,\s*[^)]*CommandExecutor/ms, // Handler with CommandExecutor parameter - BANNED
/async\s+handler\s*\([^)]*,\s*[^)]*FileSystemExecutor/ms, // Handler with FileSystemExecutor parameter - BANNED
/async\s+handler\s*\([^)]*,\s*[^)]*Dependencies/ms, // Handler with Dependencies parameter - BANNED
/async\s+handler\s*\([^)]*,\s*[^)]*executor\s*:/ms, // Handler with executor parameter - BANNED
/async\s+handler\s*\([^)]*,\s*[^)]*dependencies\s*:/ms, // Handler with dependencies parameter - BANNED
];
// CRITICAL: HANDLER TESTING IN TESTS IS FORBIDDEN
// Tests must ONLY call logic functions with dependency injection, NEVER handlers directly
// Handlers are thin wrappers for MCP SDK - testing them violates dependency injection architecture
const HANDLER_TESTING_VIOLATIONS = [
/\.handler\s*\(/, // Direct handler calls in tests - BANNED
/await\s+\w+\.handler\s*\(/, // Awaited handler calls - BANNED
/const\s+result\s*=\s*await\s+\w+\.handler/, // Handler result assignment - BANNED
/expect\s*\(\s*await\s+\w+\.handler/, // Handler expectation calls - BANNED
];
// CRITICAL: IMPROPER SERVER TYPING PATTERNS ARE FORBIDDEN
// Server instances must use proper MCP SDK types, not generic Record<string, unknown> casts
const IMPROPER_SERVER_TYPING_VIOLATIONS = [
/as Record<string, unknown>.*server/, // Casting server to Record - BANNED
/server.*as Record<string, unknown>/, // Casting server to Record - BANNED
/mcpServer\?\s*:\s*Record<string, unknown>/, // Typing server as Record - BANNED
/server\.server\?\?\s*server.*as Record/, // Complex server casting - BANNED
/interface\s+MCPServerInterface\s*{/, // Custom MCP interfaces when SDK types exist - BANNED
];
// ALLOWED PATTERNS for cleanup (not mocking)
const ALLOWED_CLEANUP_PATTERNS = [
// All cleanup patterns removed - no exceptions allowed
];
// Patterns that indicate TRUE dependency injection approach
const DEPENDENCY_INJECTION_PATTERNS = [
/createMockExecutor/, // createMockExecutor usage
/createMockFileSystemExecutor/, // createMockFileSystemExecutor usage
/executor\?\s*:\s*CommandExecutor/, // executor?: CommandExecutor parameter
];
function findTestFiles(dir) {
const testFiles = [];
function traverse(currentDir) {
const items = readdirSync(currentDir);
for (const item of items) {
const fullPath = join(currentDir, item);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// Skip node_modules and other non-relevant directories
if (
!item.startsWith('.') &&
item !== 'node_modules' &&
item !== 'dist' &&
item !== 'build'
) {
traverse(fullPath);
}
} else if (item.endsWith('.test.ts') || item.endsWith('.test.js')) {
testFiles.push(fullPath);
}
}
}
traverse(dir);
return testFiles;
}
function findToolAndResourceFiles(dir) {
const toolFiles = [];
function traverse(currentDir) {
const items = readdirSync(currentDir);
for (const item of items) {
const fullPath = join(currentDir, item);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// Skip test directories and other non-relevant directories
if (
!item.startsWith('.') &&
item !== '__tests__' &&
item !== 'node_modules' &&
item !== 'dist' &&
item !== 'build'
) {
traverse(fullPath);
}
} else if (
(item.endsWith('.ts') || item.endsWith('.js')) &&
!item.includes('.test.') &&
item !== 'index.ts' &&
item !== 'index.js'
) {
toolFiles.push(fullPath);
}
}
}
traverse(dir);
return toolFiles;
}
function findUtilityFiles(dir) {
const utilityFiles = [];
function traverse(currentDir) {
const items = readdirSync(currentDir);
for (const item of items) {
const fullPath = join(currentDir, item);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
// Skip test directories and other non-relevant directories
if (
!item.startsWith('.') &&
item !== '__tests__' &&
item !== 'node_modules' &&
item !== 'dist' &&
item !== 'build'
) {
traverse(fullPath);
}
} else if (
(item.endsWith('.ts') || item.endsWith('.js')) &&
!item.includes('.test.') &&
item !== 'index.ts' &&
item !== 'index.js'
) {
// Only include key utility files that should use CommandExecutor
// Exclude command.ts itself as it's the core implementation that is allowed to use spawn()
if (
fullPath.includes('/utils/') &&
(fullPath.includes('log_capture.ts') ||
fullPath.includes('build.ts') ||
fullPath.includes('simctl.ts')) &&
!fullPath.includes('command.ts')
) {
utilityFiles.push(fullPath);
}
}
}
}
traverse(dir);
return utilityFiles;
}
// Helper function to determine if a file is a test file
function isTestFile(filePath) {
return (
filePath.includes('__tests__') || filePath.endsWith('.test.ts') || filePath.endsWith('.test.js')
);
}
// Helper function to determine if a file is a production file
function isProductionFile(filePath) {
return !isTestFile(filePath) && (filePath.endsWith('.ts') || filePath.endsWith('.js'));
}
// Helper function to determine if a file is allowed to use child_process
function isAllowedChildProcessFile(filePath) {
// These files need direct child_process access for their core functionality
return (
filePath.includes('command.ts') || // Core CommandExecutor implementation
filePath.includes('swift_package_run.ts')
); // Needs spawn for background process management
}
function analyzeTestFile(filePath) {
try {
const content = readFileSync(filePath, 'utf8');
const relativePath = relative(projectRoot, filePath);
// Check for vitest mocking patterns using new robust approach
const vitestMockingDetails = [];
const lines = content.split('\n');
// 1. Check generic vi.* patterns (always violations)
lines.forEach((line, index) => {
VITEST_GENERIC_PATTERNS.forEach((pattern) => {
if (pattern.test(line)) {
vitestMockingDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
type: 'vitest-generic',
});
}
});
// 2. Check for unapproved mock patterns
if (hasUnapprovedMockPattern(line)) {
// Find which specific pattern matched for better reporting
const matchedPattern = UNAPPROVED_MOCK_PATTERNS.find((pattern) => pattern.test(line));
vitestMockingDetails.push({
line: index + 1,
content: line.trim(),
pattern: matchedPattern ? matchedPattern.source : 'unapproved mock pattern',
type: 'unapproved-mock',
});
}
});
const hasVitestMockingPatterns = vitestMockingDetails.length > 0;
// TypeScript patterns now handled by ESLint
const hasTypescriptAntipatterns = false;
// Check for handler testing violations (FORBIDDEN - ARCHITECTURAL VIOLATION)
const hasHandlerTestingViolations = HANDLER_TESTING_VIOLATIONS.some((pattern) =>
pattern.test(content),
);
// Check for improper server typing violations (FORBIDDEN - ARCHITECTURAL VIOLATION)
const hasImproperServerTypingViolations = IMPROPER_SERVER_TYPING_VIOLATIONS.some((pattern) =>
pattern.test(content),
);
// Check for dependency injection patterns (TRUE DI)
const hasDIPatterns = DEPENDENCY_INJECTION_PATTERNS.some((pattern) => pattern.test(content));
// Extract specific pattern occurrences for details
const execSyncDetails = []; // Not applicable to test files
const typescriptAntipatternDetails = []; // Unused - TypeScript handled by ESLint
const handlerTestingDetails = [];
const improperServerTypingDetails = [];
lines.forEach((line, index) => {
// TypeScript anti-patterns now handled by ESLint - removed from domain checks
HANDLER_TESTING_VIOLATIONS.forEach((pattern) => {
if (pattern.test(line)) {
handlerTestingDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
});
}
});
IMPROPER_SERVER_TYPING_VIOLATIONS.forEach((pattern) => {
if (pattern.test(line)) {
improperServerTypingDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
});
}
});
});
return {
filePath: relativePath,
hasExecSyncPatterns: false, // Not applicable to test files
hasVitestMockingPatterns,
hasTypescriptAntipatterns,
hasHandlerTestingViolations,
hasImproperServerTypingViolations,
hasDIPatterns,
execSyncDetails,
vitestMockingDetails,
typescriptAntipatternDetails,
handlerTestingDetails,
improperServerTypingDetails,
needsConversion:
hasVitestMockingPatterns ||
hasHandlerTestingViolations ||
hasImproperServerTypingViolations,
isConverted:
hasDIPatterns &&
!hasVitestMockingPatterns &&
!hasHandlerTestingViolations &&
!hasImproperServerTypingViolations,
isMixed:
(hasVitestMockingPatterns ||
hasHandlerTestingViolations ||
hasImproperServerTypingViolations) &&
hasDIPatterns,
};
} catch (error) {
console.error(`Error reading file ${filePath}: ${error.message}`);
return null;
}
}
function analyzeToolOrResourceFile(filePath) {
try {
const content = readFileSync(filePath, 'utf8');
const relativePath = relative(projectRoot, filePath);
// Check for execSync patterns in production code (excluding allowed files)
const hasExecSyncPatterns =
isProductionFile(filePath) &&
!isAllowedChildProcessFile(filePath) &&
EXECSYNC_PATTERNS.some((pattern) => pattern.test(content));
// Check for vitest mocking patterns using new robust approach
const vitestMockingDetails = [];
const lines = content.split('\n');
// 1. Check generic vi.* patterns (always violations)
lines.forEach((line, index) => {
VITEST_GENERIC_PATTERNS.forEach((pattern) => {
if (pattern.test(line)) {
vitestMockingDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
type: 'vitest-generic',
});
}
});
// 2. Check for unapproved mock patterns
if (hasUnapprovedMockPattern(line)) {
// Find which specific pattern matched for better reporting
const matchedPattern = UNAPPROVED_MOCK_PATTERNS.find((pattern) => pattern.test(line));
vitestMockingDetails.push({
line: index + 1,
content: line.trim(),
pattern: matchedPattern ? matchedPattern.source : 'unapproved mock pattern',
type: 'unapproved-mock',
});
}
});
const hasVitestMockingPatterns = vitestMockingDetails.length > 0;
// TypeScript patterns now handled by ESLint
const hasTypescriptAntipatterns = false;
// Check for dependency injection patterns (TRUE DI)
const hasDIPatterns = DEPENDENCY_INJECTION_PATTERNS.some((pattern) => pattern.test(content));
// Check for handler signature violations (FORBIDDEN)
const hasHandlerSignatureViolations = HANDLER_SIGNATURE_VIOLATIONS.some((pattern) =>
pattern.test(content),
);
// Check for improper server typing violations (FORBIDDEN - ARCHITECTURAL VIOLATION)
const hasImproperServerTypingViolations = IMPROPER_SERVER_TYPING_VIOLATIONS.some((pattern) =>
pattern.test(content),
);
// Check for utility bypass patterns (ARCHITECTURAL VIOLATION)
const hasUtilityBypassPatterns = UTILITY_BYPASS_PATTERNS.some((pattern) =>
pattern.test(content),
);
// Extract specific pattern occurrences for details
const execSyncDetails = [];
const typescriptAntipatternDetails = []; // Unused - TypeScript handled by ESLint
const handlerSignatureDetails = [];
const improperServerTypingDetails = [];
const utilityBypassDetails = [];
lines.forEach((line, index) => {
if (isProductionFile(filePath) && !isAllowedChildProcessFile(filePath)) {
EXECSYNC_PATTERNS.forEach((pattern) => {
if (pattern.test(line)) {
execSyncDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
});
}
});
}
// TypeScript anti-patterns now handled by ESLint - removed from domain checks
IMPROPER_SERVER_TYPING_VIOLATIONS.forEach((pattern) => {
if (pattern.test(line)) {
improperServerTypingDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
});
}
});
UTILITY_BYPASS_PATTERNS.forEach((pattern) => {
if (pattern.test(line)) {
utilityBypassDetails.push({
line: index + 1,
content: line.trim(),
pattern: pattern.source,
});
}
});
});
if (hasHandlerSignatureViolations) {
// Use regex to find the violation and its line number
const lines = content.split('\n');
const fullContent = content;
HANDLER_SIGNATURE_VIOLATIONS.forEach((pattern) => {
let match;
const globalPattern = new RegExp(pattern.source, pattern.flags + 'g');
while ((match = globalPattern.exec(fullContent)) !== null) {
// Find which line this match is on
const beforeMatch = fullContent.substring(0, match.index);
const lineNumber = beforeMatch.split('\n').length;
handlerSignatureDetails.push({
line: lineNumber,
content: match[0].replace(/\s+/g, ' ').trim(),
pattern: pattern.source,
});
}
});
}
return {
filePath: relativePath,
hasExecSyncPatterns,
hasVitestMockingPatterns,
hasTypescriptAntipatterns,
hasDIPatterns,
hasHandlerSignatureViolations,
hasImproperServerTypingViolations,
hasUtilityBypassPatterns,
execSyncDetails,
vitestMockingDetails,
typescriptAntipatternDetails,
handlerSignatureDetails,
improperServerTypingDetails,
utilityBypassDetails,
needsConversion:
hasExecSyncPatterns ||
hasVitestMockingPatterns ||
hasHandlerSignatureViolations ||
hasImproperServerTypingViolations ||
hasUtilityBypassPatterns,
isConverted:
hasDIPatterns &&
!hasExecSyncPatterns &&
!hasVitestMockingPatterns &&
!hasHandlerSignatureViolations &&
!hasImproperServerTypingViolations &&
!hasUtilityBypassPatterns,
isMixed:
(hasExecSyncPatterns ||
hasVitestMockingPatterns ||
hasHandlerSignatureViolations ||
hasImproperServerTypingViolations ||
hasUtilityBypassPatterns) &&
hasDIPatterns,
};
} catch (error) {
console.error(`Error reading file ${filePath}: ${error.message}`);
return null;
}
}
function main() {
console.log('🔍 XcodeBuildMCP Code Pattern Violations Checker\n');
console.log(`🎯 Checking pattern type: ${patternFilter.toUpperCase()}\n`);
console.log('CODE GUIDELINES ENFORCED:');
console.log('✅ External boundaries in tests should use createMockExecutor()/createMockFileSystemExecutor()');
console.log('✅ Vitest mocking is allowed for internal collaborators');
console.log('❌ BANNED: execSync usage in production code (use CommandExecutor instead)');
console.log('ℹ️ TypeScript patterns: Handled by ESLint with proper test exceptions');
console.log(
'❌ BANNED: handler signature violations (handlers must have exact MCP SDK signatures)',
);
console.log(
'❌ BANNED: handler testing violations (test logic functions, not handlers directly)',
);
console.log(
'❌ BANNED: improper server typing (use McpServer type, not Record<string, unknown>)\n',
);
const testFiles = findTestFiles(join(projectRoot, 'src'));
const testResults = testFiles.map(analyzeTestFile).filter(Boolean);
// Also check tool and resource files for TypeScript anti-patterns AND handler signature violations
const toolFiles = findToolAndResourceFiles(join(projectRoot, 'src', 'mcp', 'tools'));
const resourceFiles = findToolAndResourceFiles(join(projectRoot, 'src', 'mcp', 'resources'));
const allToolAndResourceFiles = [...toolFiles, ...resourceFiles];
const toolResults = allToolAndResourceFiles.map(analyzeToolOrResourceFile).filter(Boolean);
// Check utility files for architectural violations (bypassing CommandExecutor)
const utilityFiles = findUtilityFiles(join(projectRoot, 'src'));
const utilityResults = utilityFiles.map(analyzeToolOrResourceFile).filter(Boolean);
// Combine test, tool, and utility file results for analysis
const results = [...testResults, ...toolResults, ...utilityResults];
const handlerResults = toolResults;
const utilityBypassResults = utilityResults.filter((r) => r.hasUtilityBypassPatterns);
// Filter results based on pattern type
let filteredResults;
let filteredHandlerResults = [];
switch (patternFilter) {
case 'vitest':
filteredResults = results.filter((r) => r.hasVitestMockingPatterns);
console.log(
`Filtering to show only vitest mocking violations (${filteredResults.length} files)`,
);
break;
case 'execsync':
filteredResults = results.filter((r) => r.hasExecSyncPatterns);
console.log(`Filtering to show only execSync violations (${filteredResults.length} files)`);
break;
// TypeScript case removed - now handled by ESLint
case 'handler':
filteredResults = [];
filteredHandlerResults = handlerResults.filter((r) => r.hasHandlerSignatureViolations);
console.log(
`Filtering to show only handler signature violations (${filteredHandlerResults.length} files)`,
);
break;
case 'handler-testing':
filteredResults = results.filter((r) => r.hasHandlerTestingViolations);
console.log(
`Filtering to show only handler testing violations (${filteredResults.length} files)`,
);
break;
case 'server-typing':
filteredResults = results.filter((r) => r.hasImproperServerTypingViolations);
console.log(
`Filtering to show only improper server typing violations (${filteredResults.length} files)`,
);
break;
case 'all':
default:
filteredResults = results.filter((r) => r.needsConversion);
filteredHandlerResults = handlerResults.filter((r) => r.hasHandlerSignatureViolations);
console.log(
`Showing all pattern violations (${filteredResults.length} test files + ${filteredHandlerResults.length} handler files)`,
);
break;
}
const needsConversion = filteredResults;
const converted = results.filter((r) => r.isConverted);
const mixed = results.filter((r) => r.isMixed);
const execSyncOnly = results.filter(
(r) =>
r.hasExecSyncPatterns &&
!r.hasVitestMockingPatterns &&
true &&
!r.hasHandlerTestingViolations &&
!r.hasImproperServerTypingViolations &&
!r.hasDIPatterns,
);
const vitestMockingOnly = results.filter(
(r) =>
r.hasVitestMockingPatterns &&
!r.hasExecSyncPatterns &&
true &&
!r.hasHandlerTestingViolations &&
!r.hasImproperServerTypingViolations &&
!r.hasDIPatterns,
);
const typescriptOnly = results.filter(
(r) =>
r.false &&
!r.hasExecSyncPatterns &&
!r.hasVitestMockingPatterns &&
!r.hasHandlerTestingViolations &&
!r.hasImproperServerTypingViolations &&
!r.hasDIPatterns,
);
const handlerTestingOnly = results.filter(
(r) =>
r.hasHandlerTestingViolations &&
!r.hasExecSyncPatterns &&
!r.hasVitestMockingPatterns &&
true &&
!r.hasImproperServerTypingViolations &&
!r.hasDIPatterns,
);
const improperServerTypingOnly = results.filter(
(r) =>
r.hasImproperServerTypingViolations &&
!r.hasExecSyncPatterns &&
!r.hasVitestMockingPatterns &&
!r.hasHandlerTestingViolations &&
!r.hasDIPatterns,
);
const noPatterns = results.filter(
(r) =>
!r.hasExecSyncPatterns &&
!r.hasVitestMockingPatterns &&
true &&
!r.hasHandlerTestingViolations &&
!r.hasImproperServerTypingViolations &&
!r.hasDIPatterns,
);
console.log(`📊 CODE PATTERN VIOLATION ANALYSIS`);
console.log(`=================================`);
console.log(`Total files analyzed: ${results.length}`);
console.log(`🚨 FILES WITH VIOLATIONS: ${needsConversion.length}`);
console.log(` └─ execSync production violations: ${execSyncOnly.length}`);
console.log(` └─ vitest mocking violations: ${vitestMockingOnly.length}`);
// TypeScript anti-patterns now handled by ESLint
console.log(` └─ handler testing violations: ${handlerTestingOnly.length}`);
console.log(` └─ improper server typing violations: ${improperServerTypingOnly.length}`);
console.log(`🚨 ARCHITECTURAL VIOLATIONS: ${utilityBypassResults.length}`);
console.log(`✅ COMPLIANT (best practices): ${converted.length}`);
console.log(`⚠️ MIXED VIOLATIONS: ${mixed.length}`);
console.log(`📝 No patterns detected: ${noPatterns.length}`);
console.log('');
if (needsConversion.length > 0) {
console.log(`❌ FILES THAT NEED CONVERSION (${needsConversion.length}):`);
console.log(`=====================================`);
needsConversion.forEach((result, index) => {
console.log(`${index + 1}. ${result.filePath}`);
if (result.execSyncDetails && result.execSyncDetails.length > 0) {
console.log(` 🚨 EXECSYNC PATTERNS (${result.execSyncDetails.length}):`);
result.execSyncDetails.slice(0, 2).forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
if (result.execSyncDetails.length > 2) {
console.log(` ... and ${result.execSyncDetails.length - 2} more execSync patterns`);
}
console.log(` 🔧 FIX: Replace execSync with CommandExecutor dependency injection`);
}
if (result.vitestMockingDetails.length > 0) {
console.log(` 🧪 VITEST MOCKING PATTERNS (${result.vitestMockingDetails.length}):`);
result.vitestMockingDetails.slice(0, 2).forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
if (result.vitestMockingDetails.length > 2) {
console.log(` ... and ${result.vitestMockingDetails.length - 2} more vitest patterns`);
}
}
// TypeScript violations now handled by ESLint - removed from domain checks
if (result.handlerTestingDetails && result.handlerTestingDetails.length > 0) {
console.log(` 🚨 HANDLER TESTING VIOLATIONS (${result.handlerTestingDetails.length}):`);
result.handlerTestingDetails.slice(0, 2).forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
if (result.handlerTestingDetails.length > 2) {
console.log(
` ... and ${result.handlerTestingDetails.length - 2} more handler testing violations`,
);
}
console.log(
` 🔧 FIX: Replace handler calls with logic function calls using dependency injection`,
);
}
if (result.improperServerTypingDetails && result.improperServerTypingDetails.length > 0) {
console.log(
` 🔧 IMPROPER SERVER TYPING VIOLATIONS (${result.improperServerTypingDetails.length}):`,
);
result.improperServerTypingDetails.slice(0, 2).forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
if (result.improperServerTypingDetails.length > 2) {
console.log(
` ... and ${result.improperServerTypingDetails.length - 2} more server typing violations`,
);
}
console.log(
` 🔧 FIX: Import McpServer from SDK and use proper typing instead of Record<string, unknown>`,
);
}
console.log('');
});
}
// Utility bypass violations reporting
if (utilityBypassResults.length > 0) {
console.log(`🚨 CRITICAL: UTILITY ARCHITECTURAL VIOLATIONS (${utilityBypassResults.length}):`);
console.log(`=======================================================`);
console.log('⚠️ These utilities bypass CommandExecutor and break our testing architecture!');
console.log('');
utilityBypassResults.forEach((result, index) => {
console.log(`${index + 1}. ${result.filePath}`);
if (result.utilityBypassDetails.length > 0) {
console.log(` 🚨 BYPASS PATTERNS (${result.utilityBypassDetails.length}):`);
result.utilityBypassDetails.forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
}
console.log(
' 🔧 FIX: Refactor to accept CommandExecutor and use it instead of direct spawn/exec calls',
);
console.log('');
});
}
// Handler signature violations reporting
if (filteredHandlerResults.length > 0) {
console.log(`🚨 HANDLER SIGNATURE VIOLATIONS (${filteredHandlerResults.length}):`);
console.log(`===========================================`);
filteredHandlerResults.forEach((result, index) => {
console.log(`${index + 1}. ${result.filePath}`);
if (result.handlerSignatureDetails.length > 0) {
console.log(` 🛠️ HANDLER VIOLATIONS (${result.handlerSignatureDetails.length}):`);
result.handlerSignatureDetails.forEach((detail) => {
console.log(` Line ${detail.line}: ${detail.content}`);
});
}
console.log('');
});
}
if (mixed.length > 0) {
console.log(`⚠️ FILES WITH MIXED PATTERNS (${mixed.length}):`);
console.log(`===================================`);
mixed.forEach((result, index) => {
console.log(`${index + 1}. ${result.filePath}`);
console.log(` ⚠️ Contains both setTimeout and dependency injection patterns`);
console.log('');
});
}
if (converted.length > 0) {
console.log(`✅ SUCCESSFULLY CONVERTED FILES (${converted.length}):`);
console.log(`====================================`);
converted.forEach((result, index) => {
console.log(`${index + 1}. ${result.filePath}`);
});
console.log('');
}
// Summary for next steps
const hasViolations =
needsConversion.length > 0 ||
filteredHandlerResults.length > 0 ||
utilityBypassResults.length > 0;
if (needsConversion.length > 0) {
console.log(`🚨 CRITICAL ACTION REQUIRED (TEST FILES):`);
console.log(`=======================================`);
console.log(`1. Fix architectural violations in ${needsConversion.length} files`);
console.log(
`2. BANNED: Testing handlers directly (.handler()) - test logic functions with dependency injection`,
);
console.log(`3. Use injected executors/filesystem mocks for external side effects`);
console.log(`4. Update plugin implementations to accept executor?: CommandExecutor parameter`);
console.log(`5. Run this script again after each fix to track progress`);
console.log('');
// Show top files by total violation count
const sortedByPatterns = needsConversion
.sort((a, b) => {
const totalA =
(a.execSyncDetails?.length || 0) +
a.vitestMockingDetails.length +
(a.handlerTestingDetails?.length || 0) +
(a.improperServerTypingDetails?.length || 0);
const totalB =
(b.execSyncDetails?.length || 0) +
b.vitestMockingDetails.length +
(b.handlerTestingDetails?.length || 0) +
(b.improperServerTypingDetails?.length || 0);
return totalB - totalA;
})
.slice(0, 5);
console.log(`🚨 TOP 5 FILES WITH MOST VIOLATIONS:`);
sortedByPatterns.forEach((result, index) => {
const totalPatterns =
(result.execSyncDetails?.length || 0) +
result.vitestMockingDetails.length +
(result.handlerTestingDetails?.length || 0) +
(result.improperServerTypingDetails?.length || 0);
console.log(
`${index + 1}. ${result.filePath} (${totalPatterns} violations: ${result.execSyncDetails?.length || 0} execSync + ${result.vitestMockingDetails.length} vitest + ${result.handlerTestingDetails?.length || 0} handler + ${result.improperServerTypingDetails?.length || 0} server)`,
);
});
console.log('');
}
if (utilityBypassResults.length > 0) {
console.log(`🚨 CRITICAL ACTION REQUIRED (UTILITY FILES):`);
console.log(`==========================================`);
console.log(
`1. IMMEDIATELY fix ALL architectural violations in ${utilityBypassResults.length} files`,
);
console.log(`2. Refactor utilities to accept CommandExecutor parameter`);
console.log(`3. Replace direct spawn/exec calls with executor calls`);
console.log(`4. These violations break our entire testing strategy`);
console.log(`5. Run this script again after each fix to track progress`);
console.log('');
}
if (filteredHandlerResults.length > 0) {
console.log(`🚨 CRITICAL ACTION REQUIRED (HANDLER FILES):`);
console.log(`==========================================`);
console.log(
`1. IMMEDIATELY fix ALL handler signature violations in ${filteredHandlerResults.length} files`,
);
console.log(
`2. Tools: Handler must be: async handler(args: Record<string, unknown>): Promise<ToolResponse>`,
);
console.log(
`3. Resources: Handler must be: async handler(uri: URL): Promise<{ contents: Array<{ text: string }> }>`,
);
console.log(
`4. Inject dependencies INSIDE handler body: const executor = getDefaultCommandExecutor()`,
);
console.log(`5. Run this script again after each fix to track progress`);
console.log('');
}
if (!hasViolations && mixed.length === 0) {
console.log(`🎉 ALL FILES COMPLY WITH PROJECT STANDARDS!`);
console.log(`==========================================`);
console.log(`✅ External boundary tests use injected executors/filesystem dependencies`);
console.log(`✅ All files follow TypeScript best practices (no unsafe casts)`);
console.log(`✅ All handler signatures comply with MCP SDK requirements`);
console.log(`✅ All utilities properly use CommandExecutor dependency injection`);
console.log(`✅ No violations detected!`);
}
// Exit with appropriate code
process.exit(hasViolations || mixed.length > 0 ? 1 : 0);
}
main();