-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduction-qa-watcher.js
More file actions
3582 lines (3072 loc) · 108 KB
/
Copy pathproduction-qa-watcher.js
File metadata and controls
3582 lines (3072 loc) · 108 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 node
/**
* Production QA Watcher v2.5.0
*
* Autonomous code review system that monitors file changes and uses
* Claude Code headless mode to detect production deployment issues.
*
* Usage:
* npm run qa-watch # Start watching
* npm run qa-watch:verbose # Verbose output
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const { spawn, execSync } = require('child_process');
// ============================================================================
// PLATFORM DETECTION & CROSS-PLATFORM UTILITIES
// ============================================================================
const IS_WINDOWS = process.platform === 'win32';
const IS_MAC = process.platform === 'darwin';
const IS_LINUX = process.platform === 'linux';
/**
* Find Claude CLI path across all platforms
* Priority: 1) CLAUDE_CLI_PATH env var, 2) Config file, 3) Auto-detect
*/
function findClaudeCLI() {
// 1. Check environment variable first
if (process.env.CLAUDE_CLI_PATH) {
if (fs.existsSync(process.env.CLAUDE_CLI_PATH)) {
return process.env.CLAUDE_CLI_PATH;
}
log(`Warning: CLAUDE_CLI_PATH set but file not found: ${process.env.CLAUDE_CLI_PATH}`, 'warning');
}
// 2. Try to find in PATH using 'which' or 'where'
try {
const cmd = IS_WINDOWS ? 'where claude' : 'which claude';
const result = execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
if (result && fs.existsSync(result.split('\n')[0])) {
return result.split('\n')[0];
}
} catch {
// Not in PATH, continue searching
}
// 3. Platform-specific default locations
const homeDir = os.homedir();
const possiblePaths = [];
if (IS_WINDOWS) {
// VS Code extensions (all versions)
const vscodeExtDir = path.join(homeDir, '.vscode', 'extensions');
if (fs.existsSync(vscodeExtDir)) {
try {
const extensions = fs.readdirSync(vscodeExtDir);
const claudeExts = extensions.filter(e => e.startsWith('anthropic.claude-code-')).sort().reverse();
for (const ext of claudeExts) {
possiblePaths.push(path.join(vscodeExtDir, ext, 'resources', 'native-binary', 'claude.exe'));
}
} catch {}
}
// AppData locations
possiblePaths.push(path.join(homeDir, 'AppData', 'Local', 'Programs', 'claude', 'claude.exe'));
possiblePaths.push(path.join(homeDir, 'AppData', 'Local', 'Claude', 'claude.exe'));
// Scoop
possiblePaths.push(path.join(homeDir, 'scoop', 'shims', 'claude.exe'));
} else if (IS_MAC) {
// VS Code extensions
const vscodeExtDir = path.join(homeDir, '.vscode', 'extensions');
if (fs.existsSync(vscodeExtDir)) {
try {
const extensions = fs.readdirSync(vscodeExtDir);
const claudeExts = extensions.filter(e => e.startsWith('anthropic.claude-code-')).sort().reverse();
for (const ext of claudeExts) {
possiblePaths.push(path.join(vscodeExtDir, ext, 'resources', 'native-binary', 'claude'));
}
} catch {}
}
// Homebrew
possiblePaths.push('/opt/homebrew/bin/claude');
possiblePaths.push('/usr/local/bin/claude');
// Application bundle
possiblePaths.push('/Applications/Claude.app/Contents/MacOS/claude');
// Home local bin
possiblePaths.push(path.join(homeDir, '.local', 'bin', 'claude'));
} else {
// Linux
const vscodeExtDir = path.join(homeDir, '.vscode', 'extensions');
if (fs.existsSync(vscodeExtDir)) {
try {
const extensions = fs.readdirSync(vscodeExtDir);
const claudeExts = extensions.filter(e => e.startsWith('anthropic.claude-code-')).sort().reverse();
for (const ext of claudeExts) {
possiblePaths.push(path.join(vscodeExtDir, ext, 'resources', 'native-binary', 'claude'));
}
} catch {}
}
// Standard Linux paths
possiblePaths.push('/usr/local/bin/claude');
possiblePaths.push('/usr/bin/claude');
possiblePaths.push(path.join(homeDir, '.local', 'bin', 'claude'));
// Snap
possiblePaths.push('/snap/bin/claude');
}
// Try each possible path
for (const p of possiblePaths) {
if (fs.existsSync(p)) {
return p;
}
}
return null;
}
/**
* Get skill file path using os.homedir()
*/
function getSkillFilePath() {
return path.join(os.homedir(), '.claude', 'production-readiness-checklist-skill.md');
}
/**
* Execute a command using platform-appropriate shell
* Returns: { shell: string, args: string[], options: object }
*/
function getPlatformSpawnConfig(claudePath, prompt, options = {}) {
const { allowedTools, maxTurns } = options;
// Escape the prompt for the shell
let escapedPrompt;
let shell, args;
if (IS_WINDOWS) {
// PowerShell - escape single quotes by doubling them
escapedPrompt = prompt.replace(/'/g, "''");
const psCmd = `& '${claudePath}' -p '${escapedPrompt}' --output-format json --max-turns ${maxTurns} --allowedTools ${allowedTools}`;
shell = 'powershell';
args = ['-Command', psCmd];
} else {
// Bash/sh - escape single quotes with '\''
escapedPrompt = prompt.replace(/'/g, "'\\''");
shell = '/bin/sh';
args = ['-c', `'${claudePath}' -p '${escapedPrompt}' --output-format json --max-turns ${maxTurns} --allowedTools ${allowedTools}`];
}
const spawnOptions = {
cwd: process.cwd(),
stdio: ['pipe', 'pipe', 'pipe']
};
// Windows-specific: hide console window
if (IS_WINDOWS) {
spawnOptions.windowsHide = true;
}
return { shell, args, options: spawnOptions };
}
// ============================================================================
// CONFIGURATION
// ============================================================================
// Auto-detect Claude CLI path
const detectedClaudePath = findClaudeCLI();
const CONFIG = {
// Paths (auto-detected, can be overridden by config file)
claudePath: detectedClaudePath,
skillFile: getSkillFilePath(),
logDir: './qa-reviews',
// File watching
watchPaths: [
'./src',
'./components',
'./pages',
'./app',
'./lib',
'./utils'
],
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/.next/**',
'**/dist/**',
'**/build/**',
'**/*.test.ts',
'**/*.test.tsx',
'**/*.test.js',
'**/*.spec.ts',
'**/*.spec.tsx',
'**/*.spec.js',
'**/.env',
'**/.env.*',
'**/qa-reviews/**',
'**/*.log',
'**/*.md'
],
// File extensions to review
extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs'],
// Timing
debounceDelay: 1000, // 1 second after last change
// Claude Code configuration
claudeConfig: {
outputFormat: 'json',
detection: {
allowedTools: 'Read,Grep',
maxTurns: 10 // Increased for multi-file reviews
},
fixing: {
allowedTools: 'Read,Grep,Edit',
maxTurns: 5
}
},
// Auto-fix configuration
autoFix: {
enabled: process.argv.includes('--fix'),
dryRun: !process.argv.includes('--fix'), // Dry-run by default unless --fix flag
backupFiles: true,
verifyAfterFix: true,
// Safe patterns to auto-fix (high confidence)
safePatterns: [
'hardcoded-localhost', // http://localhost:* → process.env.NEXT_PUBLIC_APP_URL
'console-log', // console.log(...) → remove
'debugger-statement' // debugger; → remove
]
},
// Notifications with clickable HTML reports
notifications: {
enabled: true,
criticalOnly: false, // Now supports all notification types
throttle: 60000, // 1 minute between notifications
sound: true,
openReportOnClick: true, // Open HTML report when notification clicked
types: {
detection: true, // "Fixes Needed" after detection
fixes: true, // "Fixes Applied" after fixing
remaining: true // "Manual Review Needed" after verification
}
},
// Logging
logging: {
verbose: process.argv.includes('--verbose'),
debug: process.argv.includes('--debug'), // Show stack traces and detailed errors
timestampFormat: 'YYYY-MM-DDTHH-mm-ss'
},
// Ralph Mode (autonomous loop)
ralph: {
enabled: process.argv.includes('--ralph'),
maxCycles: (() => {
const idx = process.argv.indexOf('--max-ralph-cycles');
return idx !== -1 ? parseInt(process.argv[idx + 1]) || 10 : 10;
})(),
scope: (() => {
const idx = process.argv.indexOf('--ralph-scope');
return idx !== -1 ? process.argv[idx + 1] : null;
})(),
budgetWarning: 5.00, // Warn at $5
budgetHard: 20.00 // Stop at $20
},
// Dashboard (real-time web UI for Ralph mode)
dashboard: {
enabled: !process.argv.includes('--no-dashboard'),
port: 3000,
autoOpen: true
},
// Pre-commit hook mode (scan staged files only)
scanStaged: process.argv.includes('--scan-staged'),
// Tech stack (for tailored reviews)
techStack: {
framework: '',
database: '',
auth: '',
hosting: '',
orm: '',
ui: '',
testing: ''
}
};
// ============================================================================
// CONFIGURATION FILE SUPPORT
// ============================================================================
const CONFIG_FILE_NAME = '.qawatch.json';
/**
* Get the path to the config file in the current directory
*/
function getConfigPath() {
return path.join(process.cwd(), CONFIG_FILE_NAME);
}
/**
* Validate the user config structure
* @param {Object} config - User configuration object
* @returns {string[]} - Array of validation errors (empty if valid)
*/
function validateConfig(config) {
const errors = [];
// Validate array fields
if (config.watchPaths !== undefined && !Array.isArray(config.watchPaths)) {
errors.push('watchPaths must be an array of directory paths');
}
if (config.ignored !== undefined && !Array.isArray(config.ignored)) {
errors.push('ignored must be an array of glob patterns');
}
if (config.extensions !== undefined && !Array.isArray(config.extensions)) {
errors.push('extensions must be an array of file extensions');
}
// Validate autoFix
if (config.autoFix !== undefined) {
if (typeof config.autoFix !== 'object') {
errors.push('autoFix must be an object');
} else {
if (config.autoFix.safePatterns !== undefined && !Array.isArray(config.autoFix.safePatterns)) {
errors.push('autoFix.safePatterns must be an array');
}
if (config.autoFix.backupFiles !== undefined && typeof config.autoFix.backupFiles !== 'boolean') {
errors.push('autoFix.backupFiles must be a boolean');
}
if (config.autoFix.verifyAfterFix !== undefined && typeof config.autoFix.verifyAfterFix !== 'boolean') {
errors.push('autoFix.verifyAfterFix must be a boolean');
}
}
}
// Validate ralph
if (config.ralph !== undefined) {
if (typeof config.ralph !== 'object') {
errors.push('ralph must be an object');
} else {
if (config.ralph.maxCycles !== undefined && typeof config.ralph.maxCycles !== 'number') {
errors.push('ralph.maxCycles must be a number');
}
if (config.ralph.budgetWarning !== undefined && typeof config.ralph.budgetWarning !== 'number') {
errors.push('ralph.budgetWarning must be a number');
}
if (config.ralph.budgetHard !== undefined && typeof config.ralph.budgetHard !== 'number') {
errors.push('ralph.budgetHard must be a number');
}
}
}
// Validate notifications
if (config.notifications !== undefined) {
if (typeof config.notifications !== 'object') {
errors.push('notifications must be an object');
} else {
if (config.notifications.enabled !== undefined && typeof config.notifications.enabled !== 'boolean') {
errors.push('notifications.enabled must be a boolean');
}
if (config.notifications.throttle !== undefined && typeof config.notifications.throttle !== 'number') {
errors.push('notifications.throttle must be a number (milliseconds)');
}
}
}
// Validate dashboard
if (config.dashboard !== undefined) {
if (typeof config.dashboard !== 'object') {
errors.push('dashboard must be an object');
} else {
if (config.dashboard.port !== undefined && typeof config.dashboard.port !== 'number') {
errors.push('dashboard.port must be a number');
}
}
}
return errors;
}
/**
* Generate default configuration file
* @param {string} configPath - Path to write the config file
*/
function generateDefaultConfig(configPath) {
const defaultConfig = {
watchPaths: ['./src', './components', './pages', './app', './lib', './utils'],
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/.next/**',
'**/dist/**',
'**/build/**',
'**/*.test.ts',
'**/*.test.tsx',
'**/*.spec.ts',
'**/*.spec.tsx',
'**/qa-reviews/**',
'**/*.log'
],
extensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs'],
autoFix: {
backupFiles: true,
verifyAfterFix: true,
safePatterns: ['hardcoded-localhost', 'console-log', 'debugger-statement']
},
ralph: {
maxCycles: 10,
budgetWarning: 5.00,
budgetHard: 20.00
},
notifications: {
enabled: true,
criticalOnly: false,
sound: true
},
dashboard: {
port: 3000,
autoOpen: true
},
techStack: {
framework: '',
database: '',
auth: '',
hosting: '',
orm: '',
ui: '',
testing: ''
}
};
// Write with comment header (JSON doesn't support comments, so we use a _comment field)
const configWithComment = {
_comment: 'Production QA Watcher Configuration. See .qawatch.json.example for detailed documentation.',
...defaultConfig
};
fs.writeFileSync(configPath, JSON.stringify(configWithComment, null, 2));
console.log(`\n📝 Created default configuration: ${configPath}`);
console.log(' Edit this file to customize QA Watcher settings.\n');
}
/**
* Deep merge user config with defaults
* @param {Object} defaults - Default configuration
* @param {Object} userConfig - User configuration (partial)
* @returns {Object} - Merged configuration
*/
function mergeConfig(defaults, userConfig) {
if (!userConfig) return defaults;
const merged = { ...defaults };
// Simple array/value overrides
if (userConfig.watchPaths) merged.watchPaths = userConfig.watchPaths;
if (userConfig.ignored) merged.ignored = userConfig.ignored;
if (userConfig.extensions) merged.extensions = userConfig.extensions;
if (userConfig.debounceDelay !== undefined) merged.debounceDelay = userConfig.debounceDelay;
// Nested object merges
if (userConfig.autoFix) {
merged.autoFix = { ...defaults.autoFix, ...userConfig.autoFix };
}
if (userConfig.ralph) {
merged.ralph = { ...defaults.ralph, ...userConfig.ralph };
}
if (userConfig.notifications) {
merged.notifications = { ...defaults.notifications, ...userConfig.notifications };
if (userConfig.notifications.types) {
merged.notifications.types = { ...defaults.notifications.types, ...userConfig.notifications.types };
}
}
if (userConfig.dashboard) {
merged.dashboard = { ...defaults.dashboard, ...userConfig.dashboard };
}
if (userConfig.techStack) {
merged.techStack = { ...defaults.techStack, ...userConfig.techStack };
}
if (userConfig.claudeConfig) {
merged.claudeConfig = { ...defaults.claudeConfig, ...userConfig.claudeConfig };
if (userConfig.claudeConfig.detection) {
merged.claudeConfig.detection = { ...defaults.claudeConfig.detection, ...userConfig.claudeConfig.detection };
}
if (userConfig.claudeConfig.fixing) {
merged.claudeConfig.fixing = { ...defaults.claudeConfig.fixing, ...userConfig.claudeConfig.fixing };
}
}
return merged;
}
/**
* Load configuration from .qawatch.json
* @returns {Object|null} - User configuration or null if not found
*/
function loadConfigFile() {
const configPath = getConfigPath();
if (!fs.existsSync(configPath)) {
// Generate default config on first run
generateDefaultConfig(configPath);
return null;
}
try {
const content = fs.readFileSync(configPath, 'utf8');
const userConfig = JSON.parse(content);
// Remove comment field if present
delete userConfig._comment;
// Validate configuration
const errors = validateConfig(userConfig);
if (errors.length > 0) {
console.error('\n❌ Invalid .qawatch.json configuration:');
errors.forEach(e => console.error(` - ${e}`));
console.error('\n See .qawatch.json.example for valid configuration options.\n');
process.exit(1);
}
return userConfig;
} catch (error) {
if (error instanceof SyntaxError) {
console.error(`\n❌ Invalid JSON in ${CONFIG_FILE_NAME}:`);
console.error(` ${error.message}`);
console.error('\n Please fix the JSON syntax and try again.\n');
} else {
console.error(`\n❌ Error loading ${CONFIG_FILE_NAME}:`);
console.error(` ${error.message}\n`);
}
process.exit(1);
}
}
/**
* Apply user configuration to CONFIG
*/
function applyUserConfig() {
const userConfig = loadConfigFile();
const mergedConfig = mergeConfig(CONFIG, userConfig);
// Apply merged values back to CONFIG
Object.assign(CONFIG, mergedConfig);
// CLI arguments still take precedence
if (process.argv.includes('--fix')) {
CONFIG.autoFix.enabled = true;
CONFIG.autoFix.dryRun = false;
}
if (process.argv.includes('--verbose')) {
CONFIG.logging.verbose = true;
}
// Ralph mode CLI overrides
const maxCyclesIdx = process.argv.indexOf('--max-ralph-cycles');
if (maxCyclesIdx !== -1 && process.argv[maxCyclesIdx + 1]) {
CONFIG.ralph.maxCycles = parseInt(process.argv[maxCyclesIdx + 1]) || CONFIG.ralph.maxCycles;
}
const scopeIdx = process.argv.indexOf('--ralph-scope');
if (scopeIdx !== -1 && process.argv[scopeIdx + 1]) {
CONFIG.ralph.scope = process.argv[scopeIdx + 1];
}
if (process.argv.includes('--no-dashboard')) {
CONFIG.dashboard.enabled = false;
}
}
/**
* Print current configuration and exit
*/
function showConfig() {
console.log('\n📋 Current QA Watcher Configuration:\n');
console.log(JSON.stringify(CONFIG, null, 2));
console.log('\n Config file:', getConfigPath());
console.log(' CLI overrides applied: --fix, --verbose, --ralph, etc.\n');
process.exit(0);
}
// ============================================================================
// CUSTOM RULES
// ============================================================================
const RULES_DIR = path.join(process.cwd(), '.qawatch', 'rules');
let loadedCustomRules = [];
/**
* Get the path to the custom rules directory
*/
function getRulesDir() {
return RULES_DIR;
}
/**
* Ensure the rules directory exists, create with example if not
*/
function ensureRulesDir() {
if (!fs.existsSync(RULES_DIR)) {
fs.mkdirSync(RULES_DIR, { recursive: true });
// Create example rule on first run
createExampleRule();
log('Created custom rules directory at .qawatch/rules/', 'info');
}
}
/**
* Create an example rule file with documentation
*/
function createExampleRule() {
const exampleRule = {
"_comment": "Example custom rule. Copy and modify for your own patterns. Set enabled:true to activate.",
"name": "example-todo-comment",
"enabled": false,
"pattern": "// TODO:",
"severity": "low",
"type": "quality",
"message": "TODO comment found - consider creating a GitHub issue",
"fix": "Create a GitHub issue to track this TODO",
"autoFixable": false,
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"ignoreFiles": ["*.test.*", "*.spec.*"]
};
const examplePath = path.join(RULES_DIR, 'example-rule.json');
fs.writeFileSync(examplePath, JSON.stringify(exampleRule, null, 2));
}
/**
* Validate a single rule object
* @param {Object} rule - Rule configuration object
* @param {string} filename - Source filename for error messages
* @returns {string[]} - Array of validation errors (empty if valid)
*/
function validateRule(rule, filename) {
const errors = [];
// Required fields
if (!rule.name) errors.push('Missing required field: name');
if (!rule.pattern) errors.push('Missing required field: pattern');
if (!rule.severity) errors.push('Missing required field: severity');
if (!rule.message) errors.push('Missing required field: message');
// Valid severity
const validSeverities = ['critical', 'high', 'medium', 'low'];
if (rule.severity && !validSeverities.includes(rule.severity)) {
errors.push(`Invalid severity "${rule.severity}". Must be: ${validSeverities.join(', ')}`);
}
// Valid pattern (string or regex wrapped in /)
if (rule.pattern) {
if (rule.pattern.startsWith('/') && rule.pattern.endsWith('/')) {
try {
new RegExp(rule.pattern.slice(1, -1));
} catch (e) {
errors.push(`Invalid regex pattern: ${e.message}`);
}
}
}
// Validate optional array fields
if (rule.files !== undefined && !Array.isArray(rule.files)) {
errors.push('files must be an array of glob patterns');
}
if (rule.ignoreFiles !== undefined && !Array.isArray(rule.ignoreFiles)) {
errors.push('ignoreFiles must be an array of glob patterns');
}
return errors;
}
/**
* Load all custom rules from the rules directory
* @returns {Object[]} - Array of valid, enabled rules
*/
function loadCustomRules() {
const rules = [];
if (!fs.existsSync(RULES_DIR)) {
return rules;
}
const files = fs.readdirSync(RULES_DIR).filter(f => f.endsWith('.json'));
const seenNames = new Set();
for (const file of files) {
const filepath = path.join(RULES_DIR, file);
try {
const content = fs.readFileSync(filepath, 'utf8');
const rule = JSON.parse(content);
// Validate
const errors = validateRule(rule, file);
if (errors.length > 0) {
log(`Skipping invalid rule ${file}: ${errors.join(', ')}`, 'warning');
continue;
}
// Skip disabled rules
if (rule.enabled === false) {
logVerbose(`Skipping disabled rule: ${rule.name}`);
continue;
}
// Warn on duplicate names (use last one)
if (seenNames.has(rule.name)) {
log(`Duplicate rule name "${rule.name}" in ${file} - using this version`, 'warning');
}
seenNames.add(rule.name);
rules.push({ ...rule, _file: file });
} catch (e) {
if (e instanceof SyntaxError) {
log(`Invalid JSON in ${file}: ${e.message}`, 'warning');
} else {
log(`Error loading ${file}: ${e.message}`, 'warning');
}
}
}
loadedCustomRules = rules;
return rules;
}
/**
* Format custom rules for inclusion in the Claude detection prompt
* @param {Object[]} rules - Array of validated rules
* @returns {string} - Formatted prompt section for custom rules
*/
function formatRulesForPrompt(rules) {
if (rules.length === 0) return '';
const ruleDescriptions = rules.map(r => {
const patternDesc = r.pattern.startsWith('/')
? `regex pattern ${r.pattern}`
: `literal text "${r.pattern}"`;
return `- ${r.name} (${r.severity}): Look for ${patternDesc}. ${r.message}`;
}).join('\n');
return `
Also check for these user-defined patterns:
${ruleDescriptions}
For custom rules, use the rule name as the "type" field in your response.`;
}
/**
* List all rules (built-in + custom) to console
*/
function listRules() {
console.log('\n📋 QA Watcher Rules\n');
// Built-in patterns
console.log('Built-in Patterns:');
console.log(' - hardcoded-localhost (critical) - Hardcoded localhost URLs');
console.log(' - api-key (critical) - Exposed API keys');
console.log(' - database-credentials (critical) - Database credentials in code');
console.log(' - console-log (medium) - console.log statements');
console.log(' - debugger-statement (medium) - debugger statements');
console.log(' - security-disabled (high) - Disabled security settings');
// Custom rules
ensureRulesDir();
const customRules = loadCustomRules();
console.log(`\nCustom Rules (${customRules.length} enabled):`);
// Also show disabled rules
const allFiles = fs.existsSync(RULES_DIR)
? fs.readdirSync(RULES_DIR).filter(f => f.endsWith('.json'))
: [];
if (allFiles.length === 0) {
console.log(' No custom rules found. Create rules in .qawatch/rules/');
} else {
for (const file of allFiles) {
try {
const content = fs.readFileSync(path.join(RULES_DIR, file), 'utf8');
const rule = JSON.parse(content);
const status = rule.enabled === false ? ' [disabled]' : '';
const errors = validateRule(rule, file);
const invalid = errors.length > 0 ? ' [invalid]' : '';
console.log(` - ${rule.name || file} (${rule.severity || 'unknown'})${status}${invalid} - ${rule.message || 'No description'}`);
} catch (e) {
console.log(` - ${file} [error: ${e.message}]`);
}
}
}
console.log('\nRules directory:', RULES_DIR);
console.log('');
}
/**
* Validate all custom rules and report errors
*/
function validateAllRules() {
console.log('\n🔍 Validating Custom Rules\n');
if (!fs.existsSync(RULES_DIR)) {
console.log('No rules directory found at .qawatch/rules/');
console.log('Run any qa-watch command to create it with an example rule.\n');
return;
}
const files = fs.readdirSync(RULES_DIR).filter(f => f.endsWith('.json'));
if (files.length === 0) {
console.log('No rule files found in .qawatch/rules/\n');
return;
}
let valid = 0;
let invalid = 0;
for (const file of files) {
const filepath = path.join(RULES_DIR, file);
try {
const content = fs.readFileSync(filepath, 'utf8');
const rule = JSON.parse(content);
const errors = validateRule(rule, file);
if (errors.length > 0) {
console.log(`❌ ${file}:`);
errors.forEach(e => console.log(` - ${e}`));
invalid++;
} else {
const status = rule.enabled === false ? ' (disabled)' : '';
console.log(`✅ ${file}${status} - valid`);
valid++;
}
} catch (e) {
console.log(`❌ ${file}: ${e.message}`);
invalid++;
}
}
console.log(`\nSummary: ${valid} valid, ${invalid} invalid\n`);
}
// ============================================================================
// QA IGNORE SUPPORT
// ============================================================================
const QAIGNORE_FILE = '.qaignore';
let loadedIgnorePatterns = [];
/**
* Load and parse .qaignore file
* Supports gitignore-style patterns with negation
* @returns {Array} Array of parsed patterns
*/
function loadQaIgnore() {
const ignorePath = path.join(process.cwd(), QAIGNORE_FILE);
const patterns = [];
if (!fs.existsSync(ignorePath)) {
loadedIgnorePatterns = patterns;
return patterns;
}
try {
const content = fs.readFileSync(ignorePath, 'utf8');
const lines = content.split('\n');
for (const line of lines) {
const trimmed = line.trim();
// Skip empty lines and comments
if (!trimmed || trimmed.startsWith('#')) {
continue;
}
// Handle negation patterns
const isNegation = trimmed.startsWith('!');
const pattern = isNegation ? trimmed.slice(1) : trimmed;
try {
patterns.push({
pattern: pattern,
negation: isNegation,
regex: patternToRegex(pattern)
});
} catch (e) {
log(`Invalid pattern in .qaignore: ${pattern} - ${e.message}`, 'warning');
}
}
loadedIgnorePatterns = patterns;
if (patterns.length > 0) {
logVerbose(`Loaded ${patterns.length} patterns from .qaignore`);
}
} catch (e) {
log(`Error reading .qaignore: ${e.message}`, 'warning');
}
return patterns;
}
/**
* Convert gitignore-style pattern to regex
* @param {string} pattern - Glob pattern
* @returns {RegExp} Compiled regex
*/
function patternToRegex(pattern) {
// Remove trailing slash (directory marker - we treat files and dirs the same)
let p = pattern.replace(/\/$/, '');
// Handle leading slash (root anchor)
const isRootAnchored = p.startsWith('/');
if (isRootAnchored) {
p = p.slice(1);
}
// Escape regex special chars except * and ?
p = p.replace(/[.+^${}()|[\]\\]/g, '\\$&');
// Convert glob patterns to regex
// Use placeholder to avoid double-replacement
p = p.replace(/\*\*/g, '{{GLOBSTAR}}');
p = p.replace(/\*/g, '[^/]*');
p = p.replace(/{{GLOBSTAR}}/g, '.*');
p = p.replace(/\?/g, '.');
// Anchor pattern appropriately
if (isRootAnchored) {
p = '^' + p;
} else {
// Match anywhere in path
p = '(^|/)' + p;
}
// Match end of string or followed by path separator
p = p + '($|/)';
return new RegExp(p);
}
/**
* Check if a file should be ignored based on .qaignore patterns
* @param {string} filePath - Path to check
* @returns {boolean} True if file should be ignored
*/
function isFileIgnored(filePath) {
if (loadedIgnorePatterns.length === 0) {
return false;
}
// Normalize path separators for consistent matching
const normalizedPath = filePath.replace(/\\/g, '/');
// Process patterns in order - later patterns can override earlier ones
let ignored = false;
for (const { negation, regex } of loadedIgnorePatterns) {
if (regex.test(normalizedPath)) {
// If negation pattern matches, UN-ignore the file
// Otherwise, ignore it
ignored = !negation;
}
}
return ignored;
}
/**
* Get inline ignore instructions for Claude prompt
* @returns {string} Instruction text to add to prompt
*/
function getIgnoreInstructionForPrompt() {
return `
IMPORTANT: If you encounter these inline comments in the code, skip checking that code:
- // qa-ignore-next-line - skip checking the next line
- // qa-ignore - skip checking this line (at end of line)
- /* qa-ignore-start */ ... /* qa-ignore-end */ - skip the entire block
- // qa-ignore: rule-name - skip only the specified rule on next line
- // qa-ignore: rule1, rule2 - skip multiple specific rules on next line
Do NOT report issues on lines that have these ignore comments.`;
}
// ============================================================================
// STATE
// ============================================================================