-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1405 lines (1231 loc) · 41.7 KB
/
index.js
File metadata and controls
executable file
·1405 lines (1231 loc) · 41.7 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
/**
* Claude Hooks Manager - Enhanced CLI with interactive features
*/
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const inquirer = require('inquirer');
const ora = require('ora');
// Hook metadata
const hooks = {
'pre-commit-validator': {
description: 'Enforces coding standards before commits',
event: 'before_tool_call',
tools: ['Bash']
},
'validate-git-commit': {
description: 'Validates commit message format',
event: 'after_tool_call',
tools: ['Bash']
},
'database-extension-check': {
description: 'Validates database migration files',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit']
},
'duplicate-detector': {
description: 'Detects code duplication',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit']
},
'style-consistency': {
description: 'Enforces consistent coding style',
event: 'after_tool_call',
tools: ['Write', 'MultiEdit', 'Edit']
},
'api-endpoint-verifier': {
description: 'Validates API endpoints',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit']
},
'validate-dart-task': {
description: 'Validates Dart task creation',
event: 'before_tool_call',
tools: ['mcp__dart__create_task', 'mcp__dart__update_task']
},
'sync-docs-to-dart': {
description: 'Syncs documentation to Dart',
event: 'after_tool_call',
tools: ['Write']
},
'log-commands': {
description: 'Logs all executed commands',
event: 'after_tool_call',
tools: ['Bash']
},
'mcp-tool-enforcer': {
description: 'Enforces MCP tool usage policies',
event: 'before_tool_call',
tools: ['Task']
},
'session-end-summary': {
description: 'Provides session summary on exit',
event: 'on_exit',
tools: []
},
'api-docs-enforcer': {
description: 'Ensures API documentation completeness',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit']
},
'no-mock-code': {
description: 'Prevents placeholder/mock code',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit', 'Edit']
},
'secret-scanner': {
description: 'Detects and blocks secrets',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit', 'Edit']
},
'env-sync-validator': {
description: 'Keeps .env files synchronized',
event: 'after_tool_call',
tools: ['Write', 'MultiEdit', 'Edit']
},
'gitignore-enforcer': {
description: 'Ensures proper .gitignore configuration',
event: 'before_tool_call',
tools: ['Write', 'MultiEdit']
},
'readme-update-validator': {
description: 'Reminds to update documentation',
event: 'after_tool_call',
tools: ['Write', 'MultiEdit', 'Edit']
},
'timestamp-validator': {
description: 'Validates dates and timestamps for accuracy',
event: 'before_tool_call',
tools: ['Write', 'Edit', 'MultiEdit', 'Bash']
}
};
// Main function
async function main() {
const args = process.argv.slice(2);
const command = args[0];
// If no command, show interactive menu
if (!command) {
return showInteractiveMenu();
}
switch (command) {
case 'list':
listHooks();
break;
case 'info':
if (args[1]) {
showHookInfo(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'install':
await installHooks();
break;
case 'test':
runTests();
break;
case 'status':
await showStatus();
break;
case 'enable':
if (args[1]) {
await enableHook(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'disable':
if (args[1]) {
await disableHook(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'init':
await initProject();
break;
case 'doctor':
await runDoctor();
break;
case 'create':
if (args[1]) {
await createHook(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'edit':
if (args[1]) {
await editHook(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'remove':
if (args[1]) {
await removeHook(args[1]);
} else {
console.error(chalk.red('Please specify a hook name'));
process.exit(1);
}
break;
case 'config':
await configureSettings();
break;
case '--version':
case '-v':
showVersion();
break;
case '--help':
case '-h':
showHelp();
break;
default:
console.error(chalk.red(`Unknown command: ${command}`));
showHelp();
process.exit(1);
}
}
// Interactive menu
async function showInteractiveMenu() {
console.log(chalk.cyan('\n🪝 Claude Hooks Manager Interactive Menu\n'));
const { action } = await inquirer.prompt([
{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
{ name: '📦 Install hooks to Claude', value: 'install' },
{ name: '📋 List all available hooks', value: 'list' },
{ name: '🔍 Get info about a specific hook', value: 'info' },
{ name: '✅ Check installation status', value: 'status' },
new inquirer.Separator('─── Hook Management ───'),
{ name: '🟢 Enable a hook', value: 'enable' },
{ name: '🔴 Disable a hook', value: 'disable' },
{ name: '➕ Create new hook', value: 'create' },
{ name: '✏️ Edit existing hook', value: 'edit' },
{ name: '🗑️ Remove a hook', value: 'remove' },
new inquirer.Separator('─── Configuration ───'),
{ name: '⚙️ Configure settings', value: 'config' },
{ name: '🚀 Initialize project hooks', value: 'init' },
{ name: '🩺 Run diagnostics (doctor)', value: 'doctor' },
{ name: '🧪 Run tests', value: 'test' },
new inquirer.Separator('─── Dart Integration ───'),
{ name: '🎯 Initialize Dart config', value: 'dart-init' },
{ name: '📝 Edit Dart config', value: 'dart-edit' },
new inquirer.Separator(),
{ name: '❌ Exit', value: 'exit' }
]
}
]);
switch (action) {
case 'install':
await installHooks();
break;
case 'list':
listHooks();
await promptToContinue();
break;
case 'info':
await selectAndShowHookInfo();
break;
case 'status':
await showStatus();
await promptToContinue();
break;
case 'enable':
await selectAndEnableHook();
break;
case 'disable':
await selectAndDisableHook();
break;
case 'create':
await promptAndCreateHook();
break;
case 'edit':
await selectAndEditHook();
break;
case 'remove':
await selectAndRemoveHook();
break;
case 'config':
await configureSettings();
break;
case 'test':
runTests();
break;
case 'doctor':
await runDoctor();
await promptToContinue();
break;
case 'init':
await initProject();
break;
case 'dart-init':
await initDartConfig();
break;
case 'dart-edit':
await editDartConfig();
break;
case 'exit':
console.log(chalk.green('\nThanks for using Claude Hooks Manager! 👋\n'));
process.exit(0);
}
// Return to menu unless exited
if (action !== 'exit') {
await showInteractiveMenu();
}
}
async function promptToContinue() {
await inquirer.prompt([
{
type: 'input',
name: 'continue',
message: 'Press Enter to continue...'
}
]);
}
async function selectAndShowHookInfo() {
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const { hookName } = await inquirer.prompt([
{
type: 'list',
name: 'hookName',
message: 'Select a hook to learn more:',
choices: Object.keys(hooks).map(name => {
// Check status
const hookPath = path.join(hooksDir, `${name}.py`);
const disabledPath = path.join(hooksDir, `${name}.py.disabled`);
let status = '';
if (fs.existsSync(hookPath)) {
status = chalk.green('●') + ' ';
} else if (fs.existsSync(disabledPath)) {
status = chalk.red('●') + ' ';
} else {
status = chalk.gray('○') + ' ';
}
return {
name: `${status}${name} - ${hooks[name].description}`,
value: name
};
})
}
]);
showHookInfo(hookName);
await promptToContinue();
}
async function selectAndEnableHook() {
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const disabledHooks = fs.readdirSync(hooksDir)
.filter(f => f.endsWith('.py.disabled') || f.endsWith('.py.original'))
.map(f => f.replace(/\.py\.(disabled|original)$/, ''));
// Remove duplicates
const uniqueDisabledHooks = [...new Set(disabledHooks)];
if (uniqueDisabledHooks.length === 0) {
console.log(chalk.yellow('\nNo disabled hooks found.'));
await promptToContinue();
return;
}
const { hookName } = await inquirer.prompt([
{
type: 'list',
name: 'hookName',
message: 'Select a hook to enable:',
choices: uniqueDisabledHooks
}
]);
await enableHook(hookName);
await promptToContinue();
}
async function selectAndDisableHook() {
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const pyFiles = fs.readdirSync(hooksDir)
.filter(f => f.endsWith('.py') && !f.endsWith('.disabled') && !f.endsWith('.original'));
// Filter out stub files
const enabledHooks = [];
for (const file of pyFiles) {
const hookName = file.replace('.py', '');
const hookPath = path.join(hooksDir, file);
// Check if there's an .original file (which means it's disabled)
if (!fs.existsSync(path.join(hooksDir, `${hookName}.py.original`))) {
try {
const content = fs.readFileSync(hookPath, 'utf8');
// Skip if it's a stub file
if (!content.includes('Stub for disabled hook:')) {
enabledHooks.push(hookName);
}
} catch {
// If we can't read the file, assume it's enabled
enabledHooks.push(hookName);
}
}
}
if (enabledHooks.length === 0) {
console.log(chalk.yellow('\nNo enabled hooks found.'));
await promptToContinue();
return;
}
const { hookName } = await inquirer.prompt([
{
type: 'list',
name: 'hookName',
message: 'Select a hook to disable:',
choices: enabledHooks
}
]);
await disableHook(hookName);
await promptToContinue();
}
async function promptAndCreateHook() {
const { hookName } = await inquirer.prompt([
{
type: 'input',
name: 'hookName',
message: 'Enter name for new hook (without .py):',
validate: (input) => {
if (!input) return 'Hook name is required';
if (!/^[a-z0-9-_]+$/.test(input)) return 'Use only lowercase letters, numbers, hyphens, and underscores';
return true;
}
}
]);
await createHook(hookName);
await promptToContinue();
}
async function selectAndEditHook() {
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const allHooks = fs.readdirSync(hooksDir)
.filter(f => f.endsWith('.py'))
.map(f => f.replace('.py', ''));
if (allHooks.length === 0) {
console.log(chalk.yellow('\nNo hooks found to edit.'));
await promptToContinue();
return;
}
const { hookName } = await inquirer.prompt([
{
type: 'list',
name: 'hookName',
message: 'Select a hook to edit:',
choices: allHooks
}
]);
await editHook(hookName);
await promptToContinue();
}
async function selectAndRemoveHook() {
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const allHooks = fs.readdirSync(hooksDir)
.filter(f => f.endsWith('.py') || f.endsWith('.py.disabled') || f.endsWith('.py.original'))
.map(f => f.replace(/\.py(\.disabled|\.original)?$/, ''));
// Remove duplicates
const uniqueHooks = [...new Set(allHooks)];
if (uniqueHooks.length === 0) {
console.log(chalk.yellow('\nNo hooks found to remove.'));
await promptToContinue();
return;
}
const { hookName } = await inquirer.prompt([
{
type: 'list',
name: 'hookName',
message: 'Select a hook to remove:',
choices: uniqueHooks
}
]);
await removeHook(hookName);
await promptToContinue();
}
function listHooks() {
console.log(chalk.cyan('\nAvailable Claude Hooks:\n'));
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
Object.entries(hooks).forEach(([name, info]) => {
// Check if hook is enabled or disabled
const hookPath = path.join(hooksDir, `${name}.py`);
const originalPath = path.join(hooksDir, `${name}.py.original`);
const disabledPath = path.join(hooksDir, `${name}.py.disabled`);
let status = '';
if (fs.existsSync(originalPath)) {
// New disable mechanism - hook is disabled with stub in place
status = chalk.red('●') + ' '; // Red dot for disabled
} else if (fs.existsSync(disabledPath)) {
// Old disable mechanism - backward compatibility
status = chalk.red('●') + ' '; // Red dot for disabled
} else if (fs.existsSync(hookPath)) {
// Check if it's a stub file
try {
const content = fs.readFileSync(hookPath, 'utf8');
if (content.includes('Stub for disabled hook:')) {
status = chalk.red('●') + ' '; // Red dot for disabled (stub)
} else {
status = chalk.green('●') + ' '; // Green dot for enabled
}
} catch {
status = chalk.green('●') + ' '; // Green dot for enabled
}
} else {
status = chalk.gray('○') + ' '; // Gray circle for not installed
}
console.log(` ${status}${chalk.yellow(`${name}.py`.padEnd(33))} ${chalk.gray(info.description)}`);
});
console.log('\n' + chalk.gray(' ● Enabled ● Disabled ○ Not Installed'));
console.log();
}
function showHookInfo(hookName) {
const hook = hooks[hookName];
if (!hook) {
console.error(chalk.red(`Hook not found: ${hookName}`));
console.log(chalk.gray('Run "claude-hooks list" to see available hooks'));
return;
}
console.log(chalk.cyan(`\nHook: ${hookName}.py`));
console.log(chalk.gray('─'.repeat(50)));
console.log(`${chalk.bold('Description:')} ${hook.description}`);
console.log(`${chalk.bold('Event:')} ${hook.event}`);
console.log(`${chalk.bold('Tools:')} ${hook.tools.length > 0 ? hook.tools.join(', ') : 'All tools'}`);
const hookPath = path.join(__dirname, 'hooks', `${hookName}.py`);
if (fs.existsSync(hookPath)) {
console.log(`${chalk.bold('Location:')} ${hookPath}`);
}
console.log();
}
async function installHooks() {
const spinner = ora('Installing hooks to Claude directory...').start();
try {
// Hide spinner output during install script
spinner.stop();
execSync('./install.sh', { stdio: 'inherit' });
spinner.succeed('Hooks installed successfully!');
console.log(chalk.green('\n✅ All hooks have been copied to ~/.claude/hooks/'));
console.log(chalk.gray('Restart Claude for the hooks to take effect.\n'));
} catch (error) {
spinner.fail('Installation failed');
console.error(chalk.red('Error during installation:'), error.message);
process.exit(1);
}
}
async function showStatus() {
console.log(chalk.cyan('\n🔍 Checking Claude Hooks Manager Status...\n'));
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
const settingsFile = path.join(process.env.HOME, '.claude', 'settings.json');
// Check hooks directory
if (fs.existsSync(hooksDir)) {
console.log(chalk.green('✅ Hooks directory exists'));
// Count hooks by status
const allFiles = fs.readdirSync(hooksDir);
const enabledHooks = allFiles.filter(f => f.endsWith('.py') && !f.endsWith('.disabled'));
const disabledHooks = allFiles.filter(f => f.endsWith('.py.disabled'));
console.log(chalk.gray(` ${chalk.green('●')} ${enabledHooks.length} hooks enabled`));
console.log(chalk.gray(` ${chalk.red('●')} ${disabledHooks.length} hooks disabled`));
console.log(chalk.gray(` ${enabledHooks.length + disabledHooks.length} total hooks installed`));
} else {
console.log(chalk.red('❌ Hooks directory not found'));
console.log(chalk.gray(' Run "claude-hooks install" to set up'));
}
// Check settings file
if (fs.existsSync(settingsFile)) {
console.log(chalk.green('✅ Settings file exists'));
} else {
console.log(chalk.yellow('⚠️ Settings file not found'));
console.log(chalk.gray(' Hooks may not be configured'));
}
console.log();
}
async function enableHook(hookName) {
const hookPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py`);
const originalPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.original`);
const disabledPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.disabled`);
// Check if we have an .original file (new disable mechanism)
if (fs.existsSync(originalPath)) {
try {
// Read the stub to check if it's our stub
const currentContent = fs.readFileSync(hookPath, 'utf8');
if (currentContent.includes('Stub for disabled hook:')) {
// Delete the stub
fs.unlinkSync(hookPath);
}
// Restore the original
fs.renameSync(originalPath, hookPath);
console.log(chalk.green(`✅ Enabled ${hookName}`));
} catch (error) {
console.error(chalk.red(`Failed to enable ${hookName}:`), error.message);
}
return;
}
// Check for old .disabled file format (backward compatibility)
if (fs.existsSync(disabledPath)) {
try {
fs.renameSync(disabledPath, hookPath);
console.log(chalk.green(`✅ Enabled ${hookName}`));
} catch (error) {
console.error(chalk.red(`Failed to enable ${hookName}:`), error.message);
}
return;
}
// Check if already enabled
if (fs.existsSync(hookPath)) {
const content = fs.readFileSync(hookPath, 'utf8');
if (content.includes('Stub for disabled hook:')) {
console.log(chalk.yellow(`Hook ${hookName} is disabled (stub file present)`));
console.log(chalk.gray('This indicates an error in the disable/enable process'));
} else {
console.log(chalk.yellow(`Hook ${hookName} is already enabled`));
}
return;
}
console.error(chalk.red(`Hook ${hookName} not found`));
console.log(chalk.gray('Run "claude-hooks list" to see available hooks'));
}
async function disableHook(hookName) {
const hookPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py`);
const originalPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.original`);
// Check if already disabled
if (fs.existsSync(originalPath)) {
console.log(chalk.yellow(`Hook ${hookName} is already disabled`));
return;
}
if (!fs.existsSync(hookPath)) {
console.error(chalk.red(`Hook ${hookName} not found`));
return;
}
try {
// Move the actual hook to .original
fs.renameSync(hookPath, originalPath);
// Create a stub that exits cleanly
const stubContent = `#!/usr/bin/env python3
"""
Stub for disabled hook: ${hookName}
This hook has been disabled but remains in place to prevent errors.
To re-enable, use: claude-hooks enable ${hookName}
"""
import json
import sys
# Read input to prevent broken pipe errors
try:
json.load(sys.stdin)
except:
pass
# Exit cleanly with a message
print(f"Hook '${hookName}' is currently disabled", file=sys.stderr)
sys.exit(0)
`;
fs.writeFileSync(hookPath, stubContent);
fs.chmodSync(hookPath, '755');
console.log(chalk.green(`✅ Disabled ${hookName}`));
console.log(chalk.gray('The hook will not run until re-enabled'));
} catch (error) {
console.error(chalk.red(`Failed to disable ${hookName}:`), error.message);
}
}
async function initProject() {
console.log(chalk.cyan('\n🚀 Initializing Claude Hooks Manager for this project...\n'));
const { setupType } = await inquirer.prompt([
{
type: 'list',
name: 'setupType',
message: 'How would you like to configure hooks for this project?',
choices: [
{ name: 'Use recommended hooks for general development', value: 'general' },
{ name: 'Use strict hooks for production code', value: 'strict' },
{ name: 'Select hooks manually', value: 'manual' },
{ name: 'Skip project configuration', value: 'skip' }
]
}
]);
if (setupType === 'skip') {
return;
}
// Create .claude directory in project
const projectClaudeDir = path.join(process.cwd(), '.claude');
if (!fs.existsSync(projectClaudeDir)) {
fs.mkdirSync(projectClaudeDir, { recursive: true });
}
console.log(chalk.green(`\n✅ Created ${projectClaudeDir}`));
console.log(chalk.gray('Add project-specific configuration here.\n'));
// Ask about Dart integration
const { setupDart } = await inquirer.prompt([
{
type: 'confirm',
name: 'setupDart',
message: 'Would you like to set up Dart integration for this project?',
default: true
}
]);
if (setupDart) {
await initDartConfig();
} else {
// Ask about CLAUDE.md without Dart
const { createClaudeMd } = await inquirer.prompt([
{
type: 'confirm',
name: 'createClaudeMd',
message: 'Would you like to create a CLAUDE.md file with project instructions?',
default: true
}
]);
if (createClaudeMd) {
await createClaudeInstructions({}, process.cwd());
}
}
}
async function runDoctor() {
console.log(chalk.cyan('\n🩺 Running Claude Hooks Manager Diagnostics...\n'));
const spinner = ora('Checking installation...').start();
const issues = [];
const suggestions = [];
// Check Node.js version
const nodeVersion = process.version;
if (nodeVersion < 'v14.0.0') {
issues.push('Node.js version is below v14.0.0');
suggestions.push('Update Node.js to v14.0.0 or higher');
}
// Check hooks directory
const hooksDir = path.join(process.env.HOME, '.claude', 'hooks');
if (!fs.existsSync(hooksDir)) {
issues.push('Hooks directory not found');
suggestions.push('Run "claude-hooks install" to create it');
}
// Check Python
try {
execSync('python3 --version', { stdio: 'pipe' });
} catch {
issues.push('Python 3 not found');
suggestions.push('Install Python 3.6 or higher');
}
// Check for settings.json
const settingsFile = path.join(process.env.HOME, '.claude', 'settings.json');
if (!fs.existsSync(settingsFile)) {
issues.push('Claude settings file not found');
suggestions.push('Copy settings.example.json to ~/.claude/settings.json');
}
spinner.stop();
if (issues.length === 0) {
console.log(chalk.green('✅ No issues found! Everything looks good.\n'));
} else {
console.log(chalk.red(`❌ Found ${issues.length} issue(s):\n`));
issues.forEach((issue, i) => {
console.log(chalk.red(` ${i + 1}. ${issue}`));
console.log(chalk.gray(` → ${suggestions[i]}`));
});
console.log();
}
}
async function createHook(hookName) {
console.log(chalk.cyan(`\n🔨 Creating new hook: ${hookName}.py\n`));
const { hookType } = await inquirer.prompt([
{
type: 'list',
name: 'hookType',
message: 'Select hook event type:',
choices: [
{ name: 'before_tool_call - Run before a tool is called', value: 'before_tool_call' },
{ name: 'after_tool_call - Run after a tool is called', value: 'after_tool_call' },
{ name: 'on_exit - Run when session ends', value: 'on_exit' }
]
}
]);
const { tools } = await inquirer.prompt([
{
type: 'checkbox',
name: 'tools',
message: 'Select tools to monitor (leave empty for all):',
choices: ['Bash', 'Write', 'Edit', 'MultiEdit', 'Read', 'Task', 'WebFetch', 'WebSearch']
}
]);
const template = `#!/usr/bin/env python3
"""
${hookName} hook for Claude.
Created: ${new Date().toISOString().split('T')[0]}
"""
import json
import sys
def main():
try:
# Read input from Claude
input_data = json.load(sys.stdin)
tool_name = input_data.get('tool_name', '')
tool_input = input_data.get('tool_input', {})
# Add your hook logic here
# Example: Check something and provide feedback
# Exit code 0 = continue (with optional warning)
# Exit code 2 = block the operation
sys.exit(0)
except json.JSONDecodeError:
print("Error: Invalid JSON input", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
`;
const hookPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py`);
try {
fs.writeFileSync(hookPath, template);
fs.chmodSync(hookPath, 0o755);
console.log(chalk.green(`✅ Created ${hookPath}`));
console.log(chalk.gray('\nNext steps:'));
console.log(chalk.gray(`1. Edit the hook: claude-hooks edit ${hookName}`));
console.log(chalk.gray(`2. Update ~/.claude/settings.json to register the hook`));
} catch (error) {
console.error(chalk.red('Failed to create hook:'), error.message);
}
}
async function editHook(hookName) {
const hookPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py`);
const originalPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.original`);
const disabledPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.disabled`);
let pathToEdit = hookPath;
// Check if the hook is disabled
if (fs.existsSync(originalPath)) {
console.log(chalk.yellow(`Note: ${hookName} is currently disabled`));
pathToEdit = originalPath;
} else if (fs.existsSync(disabledPath)) {
console.log(chalk.yellow(`Note: ${hookName} is currently disabled (old format)`));
pathToEdit = disabledPath;
} else if (fs.existsSync(hookPath)) {
// Check if it's a stub
try {
const content = fs.readFileSync(hookPath, 'utf8');
if (content.includes('Stub for disabled hook:')) {
console.log(chalk.yellow(`Note: ${hookName} is currently disabled (stub)`));
console.log(chalk.gray('Enable the hook first to edit the actual code'));
return;
}
} catch {
// Continue with normal edit
}
} else {
console.error(chalk.red(`Hook ${hookName} not found`));
return;
}
const editor = process.env.EDITOR || 'nano';
console.log(chalk.cyan(`Opening ${path.basename(pathToEdit)} in ${editor}...`));
try {
execSync(`${editor} "${pathToEdit}"`, { stdio: 'inherit' });
} catch (error) {
console.error(chalk.red('Failed to open editor:'), error.message);
console.log(chalk.gray(`You can manually edit: ${pathToEdit}`));
}
}
async function removeHook(hookName) {
const hookPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py`);
const disabledPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.disabled`);
const originalPath = path.join(process.env.HOME, '.claude', 'hooks', `${hookName}.py.original`);
if (!fs.existsSync(hookPath) && !fs.existsSync(disabledPath) && !fs.existsSync(originalPath)) {
console.error(chalk.red(`Hook ${hookName} not found`));
return;
}
const { confirm } = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: `Are you sure you want to remove ${hookName}?`,
default: false
}
]);
if (!confirm) {
console.log(chalk.yellow('Cancelled'));
return;
}
try {
if (fs.existsSync(hookPath)) fs.unlinkSync(hookPath);
if (fs.existsSync(disabledPath)) fs.unlinkSync(disabledPath);
if (fs.existsSync(originalPath)) fs.unlinkSync(originalPath);
console.log(chalk.green(`✅ Removed ${hookName}`));
} catch (error) {
console.error(chalk.red('Failed to remove hook:'), error.message);
}
}
async function configureSettings() {
const settingsPath = path.join(process.env.HOME, '.claude', 'settings.json');
if (!fs.existsSync(settingsPath)) {
console.log(chalk.yellow('Settings file not found. Creating from template...'));
try {
const templatePath = path.join(__dirname, 'settings.example.json');
fs.copyFileSync(templatePath, settingsPath);
console.log(chalk.green('✅ Created settings.json'));
} catch (error) {
console.error(chalk.red('Failed to create settings:'), error.message);
return;
}
}
const editor = process.env.EDITOR || 'nano';
console.log(chalk.cyan(`Opening settings.json in ${editor}...`));
try {
execSync(`${editor} "${settingsPath}"`, { stdio: 'inherit' });
} catch (error) {
console.error(chalk.red('Failed to open editor:'), error.message);
console.log(chalk.gray(`You can manually edit: ${settingsPath}`));
}
}
function runTests() {
console.log(chalk.cyan('\nRunning tests...\n'));
try {
execSync('./tests/run_tests.sh', { stdio: 'inherit' });
} catch (error) {
console.error(chalk.red('Tests failed'));
process.exit(1);
}
}
async function initDartConfig() {
console.log(chalk.cyan('\n🎯 Initializing Dart Configuration\n'));
const projectRoot = process.cwd();
const projectName = path.basename(projectRoot);
const dartFile = path.join(projectRoot, '.dart');