-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_tools_discovery.py
More file actions
2934 lines (2600 loc) · 139 KB
/
Copy pathai_tools_discovery.py
File metadata and controls
2934 lines (2600 loc) · 139 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 python3
"""
AI Tools Discovery Script
Detects Cursor and Claude Code installations and extracts rules from all projects
on macOS and Windows
"""
import argparse
import copy
import json
import logging
import os
import platform
import signal
import sys
import threading
import time
import uuid
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Dict, Iterator, List, Optional, Callable
# Self-imposed run timeout (seconds). Discovery enforces its OWN deadline rather
# than only being force-killed by the parent onboard/setup subprocess timeout, so
# on a slow/hung scan it can release its lock + report the run failed BEFORE it is
# killed — a SIGKILL leaves a fresh-mtime lock that would otherwise block the next
# run. Kept in sync with the parent timeouts in setup/mdm/onboard.py and
# unbound-cli's discover.js (which pass --timeout and use a larger kill backstop).
# 150 minutes. Pass --timeout <=0 to disable.
DEFAULT_RUN_TIMEOUT_SECONDS = 9000
SCRIPT_VERSION = "1.1.0"
try:
from .coding_tool_base import BaseMCPConfigExtractor
from .coding_tool_factory import (
DeviceIdExtractorFactory,
ToolDetectorFactory,
CursorRulesExtractorFactory,
ClaudeRulesExtractorFactory,
WindsurfRulesExtractorFactory,
ClineRulesExtractorFactory,
RooRulesExtractorFactory,
AntigravityRulesExtractorFactory,
KiloCodeRulesExtractorFactory,
GeminiCliRulesExtractorFactory,
CodexRulesExtractorFactory,
OpenCodeRulesExtractorFactory,
CursorMCPConfigExtractorFactory,
ClaudeMCPConfigExtractorFactory,
ClaudeSettingsExtractorFactory,
ClaudeSkillsExtractorFactory,
ClaudeCoworkSkillsExtractorFactory,
CursorSettingsExtractorFactory,
WindsurfMCPConfigExtractorFactory,
RooMCPConfigExtractorFactory,
ClineMCPConfigExtractorFactory,
AntigravityMCPConfigExtractorFactory,
KiloCodeMCPConfigExtractorFactory,
GeminiCliMCPConfigExtractorFactory,
CodexMCPConfigExtractorFactory,
OpenCodeMCPConfigExtractorFactory,
JetBrainsMCPConfigExtractorFactory,
GitHubCopilotMCPConfigExtractorFactory,
GitHubCopilotRulesExtractorFactory,
CopilotCliMCPConfigExtractorFactory,
CopilotCliRulesExtractorFactory,
CopilotCliSettingsExtractorFactory,
CopilotCliSkillsExtractorFactory,
JunieMCPConfigExtractorFactory,
JunieRulesExtractorFactory,
CursorCliSettingsExtractorFactory,
CursorCliMCPConfigExtractorFactory,
CursorCliRulesExtractorFactory,
CursorSkillsExtractorFactory,
ClineSkillsExtractorFactory,
)
from .utils import send_report_to_backend, send_scan_event, send_discovery_metrics, get_user_info, get_all_users_macos, get_all_users_windows, get_all_users_linux, load_pending_reports, save_failed_reports, report_to_sentry, get_claude_subscription_type, get_cursor_subscription_type, in_container, _get_queue_file_path
from .linux_extraction_helpers import linux_home_for_user
from .logging_helpers import configure_logger, log_rules_details, log_mcp_details, log_settings_details
from .settings_transformers import transform_settings_to_backend_format
from .user_tool_detector import detect_tool_for_user, find_claude_binary_for_user
from .plugin_extraction_helpers import extract_claude_code_plugins, extract_cursor_plugins, build_plugin_install_path_lookup, extract_plugin_skills
from .s3_uploader import compute_payload_hash
from . import cache as discovery_cache
except ImportError:
# Running as script directly - add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from scripts.coding_discovery_tools.coding_tool_base import BaseMCPConfigExtractor
from scripts.coding_discovery_tools.coding_tool_factory import (
DeviceIdExtractorFactory,
ToolDetectorFactory,
CursorRulesExtractorFactory,
ClaudeRulesExtractorFactory,
WindsurfRulesExtractorFactory,
ClineRulesExtractorFactory,
RooRulesExtractorFactory,
AntigravityRulesExtractorFactory,
KiloCodeRulesExtractorFactory,
GeminiCliRulesExtractorFactory,
CodexRulesExtractorFactory,
OpenCodeRulesExtractorFactory,
CursorMCPConfigExtractorFactory,
ClaudeMCPConfigExtractorFactory,
ClaudeSettingsExtractorFactory,
ClaudeSkillsExtractorFactory,
ClaudeCoworkSkillsExtractorFactory,
CursorSettingsExtractorFactory,
WindsurfMCPConfigExtractorFactory,
RooMCPConfigExtractorFactory,
ClineMCPConfigExtractorFactory,
AntigravityMCPConfigExtractorFactory,
KiloCodeMCPConfigExtractorFactory,
GeminiCliMCPConfigExtractorFactory,
CodexMCPConfigExtractorFactory,
OpenCodeMCPConfigExtractorFactory,
JetBrainsMCPConfigExtractorFactory,
GitHubCopilotMCPConfigExtractorFactory,
GitHubCopilotRulesExtractorFactory,
CopilotCliMCPConfigExtractorFactory,
CopilotCliRulesExtractorFactory,
CopilotCliSettingsExtractorFactory,
CopilotCliSkillsExtractorFactory,
JunieMCPConfigExtractorFactory,
JunieRulesExtractorFactory,
CursorCliSettingsExtractorFactory,
CursorCliMCPConfigExtractorFactory,
CursorCliRulesExtractorFactory,
CursorSkillsExtractorFactory,
ClineSkillsExtractorFactory,
)
from scripts.coding_discovery_tools.utils import send_report_to_backend, send_scan_event, send_discovery_metrics, get_user_info, get_all_users_macos, get_all_users_windows, get_all_users_linux, load_pending_reports, save_failed_reports, report_to_sentry, get_claude_subscription_type, get_cursor_subscription_type, in_container, _get_queue_file_path
from scripts.coding_discovery_tools.linux_extraction_helpers import linux_home_for_user
from scripts.coding_discovery_tools.logging_helpers import configure_logger, log_rules_details, log_mcp_details, log_settings_details
from scripts.coding_discovery_tools.settings_transformers import transform_settings_to_backend_format
from scripts.coding_discovery_tools.user_tool_detector import detect_tool_for_user, find_claude_binary_for_user
from scripts.coding_discovery_tools.plugin_extraction_helpers import extract_claude_code_plugins, extract_cursor_plugins, build_plugin_install_path_lookup, extract_plugin_skills
from scripts.coding_discovery_tools.s3_uploader import compute_payload_hash
from scripts.coding_discovery_tools import cache as discovery_cache
logger = logging.getLogger(__name__)
payload_logger = logging.getLogger(__name__ + ".payload")
configure_logger()
def _normalise_path(p: str) -> str:
"""Normalise a path string for cross-platform comparison.
Forward-slashes separators, upper-cases a Windows drive letter, and strips a
trailing slash. Shared by ``filter_tool_projects_by_user`` and the per-user
Copilot CLI ownership gate so both compare paths identically (DRY).
"""
if not p:
return p
n = p.replace('\\', '/')
if len(n) >= 2 and n[1] == ':':
n = n[0].upper() + n[1:]
n = n.rstrip('/')
return n
def _copilot_cli_owned_by_user(tool_filtered: Dict, user_home) -> bool:
"""Whether a filtered Copilot CLI tool should be emitted for ``user_home``.
The per-user scan loop re-runs for every user, so emit only when the user owns
the detected config dir or the per-user filter produced data for them;
otherwise a non-owner gets a phantom install row. CLI-scoped: IDE tools
legitimately share a machine-wide install. Keys on ``_config_path`` (the
``~/.copilot`` dir), not ``install_path`` — install_path is now the binary,
which for a machine-global install lives outside any home. Older payloads
without ``_config_path`` fall back to ``install_path``.
"""
own_path = tool_filtered.get("_config_path") or tool_filtered.get("install_path", "")
own_norm = _normalise_path(own_path)
user_norm = _normalise_path(str(user_home))
owns_install = bool(own_norm) and (
own_norm == user_norm or own_norm.startswith(user_norm + "/")
)
has_data = bool(tool_filtered.get("projects")) or "permissions" in tool_filtered
return owns_install or has_data
class AIToolsDetector:
"""
Detector for AI coding tools on macOS and Windows.
Uses factory pattern to create OS-specific detectors and extractors, making it easy
to extend support for new tools or operating systems.
"""
def __init__(self, os_name: Optional[str] = None):
"""
Initialize the detector.
Args:
os_name: Operating system name (defaults to current OS)
"""
self.system = os_name or platform.system()
try:
# Initialize shared extractors
self._device_id_extractor = DeviceIdExtractorFactory.create(self.system)
self._tool_detectors = ToolDetectorFactory.create_all_tool_detectors(self.system)
# Initialize Cursor extractors
self._cursor_rules_extractor = CursorRulesExtractorFactory.create(self.system)
self._cursor_mcp_extractor = CursorMCPConfigExtractorFactory.create(self.system)
self._cursor_settings_extractor = CursorSettingsExtractorFactory.create(self.system)
self._cursor_skills_extractor = CursorSkillsExtractorFactory.create(self.system)
# Initialize Claude Code extractors
self._claude_rules_extractor = ClaudeRulesExtractorFactory.create(self.system)
self._claude_mcp_extractor = ClaudeMCPConfigExtractorFactory.create(self.system)
self._claude_settings_extractor = ClaudeSettingsExtractorFactory.create(self.system)
self._claude_skills_extractor = ClaudeSkillsExtractorFactory.create(self.system)
# Initialize Claude Cowork extractor (skills only; Cowork has no rules/MCP/settings)
self._cowork_skills_extractor = ClaudeCoworkSkillsExtractorFactory.create(self.system)
# Initialize Windsurf extractors
self._windsurf_rules_extractor = WindsurfRulesExtractorFactory.create(self.system)
self._windsurf_mcp_extractor = WindsurfMCPConfigExtractorFactory.create(self.system)
self._roo_rules_extractor = RooRulesExtractorFactory.create(self.system)
self._roo_mcp_extractor = RooMCPConfigExtractorFactory.create(self.system)
# Initialize Cline extractors (macOS and Windows)
self._cline_rules_extractor = ClineRulesExtractorFactory.create(self.system)
self._cline_mcp_extractor = ClineMCPConfigExtractorFactory.create(self.system)
self._cline_skills_extractor = ClineSkillsExtractorFactory.create(self.system)
# Initialize Antigravity extractors (macOS and Windows)
self._antigravity_rules_extractor = AntigravityRulesExtractorFactory.create(self.system)
self._antigravity_mcp_extractor = AntigravityMCPConfigExtractorFactory.create(self.system)
# Initialize Kilo Code extractors (macOS only, returns None for unsupported OS)
self._kilocode_rules_extractor = KiloCodeRulesExtractorFactory.create(self.system)
self._kilocode_mcp_extractor = KiloCodeMCPConfigExtractorFactory.create(self.system)
# Initialize Gemini CLI extractors (macOS only, returns None for unsupported OS)
self._gemini_cli_rules_extractor = GeminiCliRulesExtractorFactory.create(self.system)
self._gemini_cli_mcp_extractor = GeminiCliMCPConfigExtractorFactory.create(self.system)
# Initialize Codex extractors (macOS only, returns None for unsupported OS)
self._codex_rules_extractor = CodexRulesExtractorFactory.create(self.system)
self._codex_mcp_extractor = CodexMCPConfigExtractorFactory.create(self.system)
# Initialize OpenCode extractors (macOS only, returns None for unsupported OS)
self._opencode_rules_extractor = OpenCodeRulesExtractorFactory.create(self.system)
self._opencode_mcp_extractor = OpenCodeMCPConfigExtractorFactory.create(self.system)
# Initialize JetBrains extractors (macOS only, returns None for unsupported OS)
self._jetbrains_mcp_extractor = JetBrainsMCPConfigExtractorFactory.create(self.system)
self._github_copilot_mcp_extractor = GitHubCopilotMCPConfigExtractorFactory.create(self.system)
self._github_copilot_rules_extractor = GitHubCopilotRulesExtractorFactory.create(self.system)
# GitHub Copilot CLI MCP + rules + settings + skills extractors (macOS/Windows; None elsewhere)
self._copilot_cli_mcp_extractor = CopilotCliMCPConfigExtractorFactory.create(self.system)
self._copilot_cli_rules_extractor = CopilotCliRulesExtractorFactory.create(self.system)
self._copilot_cli_settings_extractor = CopilotCliSettingsExtractorFactory.create(self.system)
self._copilot_cli_skills_extractor = CopilotCliSkillsExtractorFactory.create(self.system)
# Shared Copilot skills (~/.copilot/skills etc.) are tool-identity-
# independent: both the CLI branch and the VS Code IDE branch attach
# them. Memoize so the (potentially whole-disk) walk runs at most once
# per scan, no matter how many Copilot rows are processed.
self._copilot_cli_skills_cache: Optional[Dict] = None
# Canonical VS Code Copilot row that should carry the shared skills,
# computed once per scan from the full detected-tools list (prefer the
# Chat row). None until set by the detection loop.
self._canonical_vscode_copilot: Optional[str] = None
self._junie_mcp_extractor = JunieMCPConfigExtractorFactory.create(self.system)
self._junie_rules_extractor = JunieRulesExtractorFactory.create(self.system)
# Initialize Cursor CLI extractors
self._cursor_cli_rules_extractor = CursorCliRulesExtractorFactory.create(self.system)
self._cursor_cli_settings_extractor = CursorCliSettingsExtractorFactory.create(self.system)
self._cursor_cli_mcp_extractor = CursorCliMCPConfigExtractorFactory.create(self.system)
except ValueError as e:
logger.error(f"Failed to initialize detectors: {e}")
raise
def get_device_id(self) -> str:
"""
Extract unique device identifier (serial number).
Returns:
Device serial number or hostname as fallback
"""
return self._device_id_extractor.extract_device_id()
def detect_all_tools(self, user_home: Optional[Path] = None) -> List[Dict]:
"""
Detect all supported AI tools.
Args:
user_home: Optional user home directory path. If provided, detects tools
for that specific user by checking their paths directly.
If None, uses current user's context.
Returns:
List of detected tools with their info
"""
tools = []
for detector in self._tool_detectors:
try:
# If user_home is provided, check user-specific paths first
if user_home:
tool_info = detect_tool_for_user(detector, user_home)
else:
tool_info = detector.detect()
if tool_info:
# Handle detectors that return a list (like JetBrains)
if isinstance(tool_info, list):
tools.extend(tool_info)
else:
tools.append(tool_info)
except Exception as e:
logger.warning(f"Error detecting {detector.tool_name}: {e}")
report_to_sentry(e, {"phase": "detect", "tool_name": detector.tool_name}, level="warning")
return tools
def detect_tool(self, tool_name: str) -> Optional[Dict]:
"""
Detect a specific tool by name.
Args:
tool_name: Name of the tool to detect (e.g., "Cursor", "Claude Code")
Returns:
Tool info dict or None if not found
"""
for detector in self._tool_detectors:
if detector.tool_name.lower() == tool_name.lower():
return detector.detect()
logger.warning(f"No detector found for tool: {tool_name}")
return None
def extract_all_cursor_rules(self) -> List[Dict]:
"""
Extract all Cursor rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
return self._cursor_rules_extractor.extract_all_cursor_rules()
except Exception as e:
logger.error(f"Error extracting Cursor rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Cursor rules"}, level="warning")
return []
def extract_all_claude_rules(self) -> Optional[Dict]:
"""
Extract all Claude Code rules from all projects.
Returns:
Dict with:
- user_rules: List of user-level rule dicts (global, scope: "user")
- project_rules: List of project dicts with project_root and rules
Returns None if extractor not available or on error.
"""
try:
if self._claude_rules_extractor:
return self._claude_rules_extractor.extract_all_claude_rules()
return None
except Exception as e:
logger.error(f"Error extracting Claude rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Claude rules"}, level="warning")
return None
def extract_all_claude_skills(self, plugin_lookup: Optional[Dict] = None) -> Optional[Dict]:
"""
Extract all Claude Code skills from all projects.
Args:
plugin_lookup: Optional dict mapping plugin install paths to provenance
metadata. When provided, skills under a plugin path are tagged with
source="plugin" and provenance fields.
Returns:
Dict with:
- user_skills: List of user-level skill dicts (global, scope: "user")
- project_skills: List of project dicts with project_root and skills
Returns None if extractor not available or on error.
"""
try:
if self._claude_skills_extractor:
return self._claude_skills_extractor.extract_all_skills(plugin_lookup=plugin_lookup)
return None
except Exception as e:
logger.error(f"Error extracting Claude skills: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Claude skills"}, level="warning")
return None
def extract_all_cowork_skills(self) -> Optional[Dict]:
"""
Extract all Claude Cowork skills from Claude Desktop's sessions tree.
Returns:
Dict with:
- user_skills: List of user-level skill dicts (scope: "user")
- project_skills: Always empty — Cowork has no project concept.
Returns None if extractor not available or on error.
"""
try:
if self._cowork_skills_extractor:
return self._cowork_skills_extractor.extract_all_skills()
return None
except Exception as e:
logger.error(f"Error extracting Cowork skills: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Cowork skills"}, level="warning")
return None
def extract_all_cursor_skills(self, plugin_lookup: Optional[Dict] = None) -> Optional[Dict]:
"""
Extract all Cursor skills from all projects.
Args:
plugin_lookup: Optional dict mapping plugin install paths to provenance
metadata. When provided, skills under a plugin path are tagged with
source="plugin" and provenance fields.
Returns:
Dict with:
- user_skills: List of user-level skill dicts (global, scope: "user")
- project_skills: List of project dicts with project_root and skills
Returns None if extractor not available or on error.
"""
try:
if self._cursor_skills_extractor:
return self._cursor_skills_extractor.extract_all_skills(plugin_lookup=plugin_lookup)
return None
except Exception as e:
logger.error(f"Error extracting Cursor skills: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Cursor skills"}, level="warning")
return None
def extract_all_cline_skills(self) -> Optional[Dict]:
"""
Extract all Cline skills from all projects.
Returns:
Dict with:
- user_skills: List of user-level skill dicts (global, scope: "user")
- project_skills: List of project dicts with project_root and skills
Returns None if extractor not available or on error.
"""
try:
if self._cline_skills_extractor:
return self._cline_skills_extractor.extract_all_skills()
return None
except Exception as e:
logger.error(f"Error extracting Cline skills: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Cline skills"}, level="warning")
return None
def extract_all_windsurf_rules(self) -> List[Dict]:
"""
Extract all Windsurf rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
return self._windsurf_rules_extractor.extract_all_windsurf_rules()
except Exception as e:
logger.error(f"Error extracting Windsurf rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Windsurf rules"}, level="warning")
return []
def extract_all_roo_rules(self) -> List[Dict]:
"""
Extract all Roo Code rules from all projects.
"""
try:
if self._roo_rules_extractor:
return self._roo_rules_extractor.extract_all_roo_rules()
return []
except Exception as e:
logger.error(f"Error extracting Roo Code rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Roo Code rules"}, level="warning")
return []
def extract_all_antigravity_rules(self) -> List[Dict]:
"""
Extract all Antigravity rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._antigravity_rules_extractor:
return self._antigravity_rules_extractor.extract_all_antigravity_rules()
return []
except Exception as e:
logger.error(f"Error extracting Antigravity rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Antigravity rules"}, level="warning")
return []
def extract_all_kilocode_rules(self) -> List[Dict]:
"""
Extract all Kilo Code rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._kilocode_rules_extractor:
return self._kilocode_rules_extractor.extract_all_kilocode_rules()
return []
except Exception as e:
logger.error(f"Error extracting Kilo Code rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Kilo Code rules"}, level="warning")
return []
def extract_all_gemini_cli_rules(self) -> List[Dict]:
"""
Extract all Gemini CLI rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._gemini_cli_rules_extractor:
return self._gemini_cli_rules_extractor.extract_all_gemini_cli_rules()
return []
except Exception as e:
logger.error(f"Error extracting Gemini CLI rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Gemini CLI rules"}, level="warning")
return []
def extract_all_codex_rules(self) -> List[Dict]:
"""
Extract all Codex rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._codex_rules_extractor:
return self._codex_rules_extractor.extract_all_codex_rules()
return []
except Exception as e:
logger.error(f"Error extracting Codex rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Codex rules"}, level="warning")
return []
def extract_all_opencode_rules(self) -> List[Dict]:
"""
Extract all OpenCode rules from all projects.
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._opencode_rules_extractor:
return self._opencode_rules_extractor.extract_all_opencode_rules()
return []
except Exception as e:
logger.error(f"Error extracting OpenCode rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "OpenCode rules"}, level="warning")
return []
def extract_all_github_copilot_rules(self, tool_name: str = None) -> List[Dict]:
"""
Extract GitHub Copilot rules from all projects.
Args:
tool_name: Name of the specific tool to extract rules for (e.g., "GitHub Copilot VS Code")
Returns:
List of project dicts, each containing:
- project_root: Path to the project root
- rules: List of rule file dicts with metadata
"""
try:
if self._github_copilot_rules_extractor:
return self._github_copilot_rules_extractor.extract_all_github_copilot_rules(tool_name=tool_name)
return []
except Exception as e:
logger.error(f"Error extracting GitHub Copilot rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "GitHub Copilot rules"}, level="warning")
return []
def extract_all_junie_rules(self) -> List[Dict]:
"""
Extract all Junie rules from all projects.
"""
try:
if self._junie_rules_extractor:
return self._junie_rules_extractor.extract_all_junie_rules()
return []
except Exception as e:
logger.error(f"Error extracting Junie rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Junie rules"}, level="warning")
return []
def extract_all_cursor_cli_rules(self) -> List[Dict]:
"""
Extract all Cursor CLI rules from all projects.
"""
try:
if self._cursor_cli_rules_extractor:
return self._cursor_cli_rules_extractor.extract_all_cursor_cli_rules()
return []
except Exception as e:
logger.error(f"Error extracting Cursor CLI rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": "Cursor CLI rules"}, level="warning")
return []
def _process_tool_with_rules_and_mcp(
self,
tool: Dict,
rules_extractor: Optional[object],
mcp_extractor: Optional[BaseMCPConfigExtractor],
extract_rules_func: Callable[[], List[Dict]],
merge_mcp_func: Optional[Callable[[List[Dict], Dict[str, Dict]], None]] = None
) -> Dict[str, Dict]:
"""
Helper method to process a tool that has both rules and MCP config extraction.
This method handles the common pattern of:
1. Logging processing header
2. Extracting rules (if extractor exists)
3. Building projects_dict from rules
4. Logging rules details
5. Extracting MCP configs (if extractor exists)
6. Merging MCP configs into projects (using custom merge function if provided)
7. Logging MCP details
Args:
tool: Tool info dict from detection
rules_extractor: Rules extractor instance (can be None)
mcp_extractor: MCP config extractor instance (can be None)
extract_rules_func: Callable that extracts rules and returns List[Dict]
merge_mcp_func: Optional custom merge function for MCP configs.
Defaults to _merge_mcp_configs_into_projects.
Should have signature: (mcp_projects: List[Dict], projects_dict: Dict[str, Dict]) -> None
Returns:
Dictionary mapping project_root to project dict
"""
tool_name = tool.get("name", "")
projects_dict = {}
logger.info("")
logger.info("=" * 70)
logger.info(f"Processing: {tool_name}")
logger.info("=" * 70)
# Extract rules
logger.info(f" Extracting {tool_name} rules...")
if rules_extractor:
try:
rules_projects = extract_rules_func()
num_projects_with_rules = len(rules_projects)
total_rules = sum(len(project.get("rules", [])) for project in rules_projects)
logger.info(f" ✓ Found {num_projects_with_rules} project(s) with {total_rules} total rule file(s)")
projects_dict = {
project["project_root"]: {
"path": project["project_root"],
"rules": project.get("rules", [])
}
for project in rules_projects
}
# Log rules details
if total_rules > 0:
log_rules_details(projects_dict, tool_name)
except Exception as e:
logger.error(f"Error extracting {tool_name} rules: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": tool_name}, level="warning")
projects_dict = {}
else:
logger.info(f" ⚠ {tool_name} rules extractor not available for this OS")
projects_dict = {}
# Extract and merge MCP configs
logger.info(f" Extracting {tool_name} MCP configs...")
if mcp_extractor:
try:
mcp_config = mcp_extractor.extract_mcp_config()
if mcp_config and "projects" in mcp_config:
num_mcp_projects = len(mcp_config["projects"])
logger.info(f" ✓ Found {num_mcp_projects} project(s) with MCP config(s)")
# Use custom merge function if provided, otherwise use default
merge_func = merge_mcp_func or self._merge_mcp_configs_into_projects
merge_func(mcp_config["projects"], projects_dict)
# Log MCP details
log_mcp_details(projects_dict, tool_name)
else:
logger.info(" ℹ No MCP configs found")
except Exception as e:
logger.error(f"Error extracting {tool_name} MCP configs: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": tool_name}, level="warning")
else:
logger.info(f" ⚠ {tool_name} MCP extractor not available for this OS")
return projects_dict
def _process_tool_with_mcp_only(
self,
tool: Dict,
mcp_extractor: Optional[BaseMCPConfigExtractor]
) -> Dict[str, Dict]:
"""
Helper method to process a tool that only has MCP config extraction (no rules).
Args:
tool: Tool info dict from detection
mcp_extractor: MCP config extractor instance (can be None)
Returns:
Dictionary mapping project_root to project dict
"""
tool_name = tool.get("name", "")
projects_dict = {}
logger.info("")
logger.info("=" * 70)
logger.info(f"Processing: {tool_name}")
logger.info("=" * 70)
# Extract and merge MCP configs
logger.info(f" Extracting {tool_name} MCP configs...")
if mcp_extractor:
try:
mcp_config = mcp_extractor.extract_mcp_config()
if mcp_config and "projects" in mcp_config:
num_mcp_projects = len(mcp_config["projects"])
logger.info(f" ✓ Found {num_mcp_projects} project(s) with MCP config(s)")
self._merge_mcp_configs_into_projects(
mcp_config["projects"],
projects_dict
)
# Log MCP details
log_mcp_details(projects_dict, tool_name)
else:
logger.info(" ⚠ No MCP configs found")
except Exception as e:
logger.error(f"Error extracting {tool_name} MCP configs: {e}", exc_info=True)
report_to_sentry(e, {"phase": "extract", "tool_name": tool_name}, level="warning")
else:
logger.info(f" ⚠ {tool_name} MCP extractor not available for this OS")
return projects_dict
@staticmethod
def _union_mcp_servers(existing: List[Dict], incoming: List[Dict]) -> List[Dict]:
"""Combine two MCP-server lists, de-duplicated by server name.
Multiple config sources can resolve to the same project path — most
notably a project whose root is the user's home directory, which yields
both a ``~/.claude.json`` ``projects[<home>]`` entry and a home-rooted
``~/.mcp.json`` entry. Unioning (instead of overwriting) keeps both
sources' servers; first-seen wins, so the higher-precedence source
merged earlier is preserved on a name conflict.
"""
merged = list(existing or [])
seen = {s.get("name") for s in merged if isinstance(s, dict)}
for server in (incoming or []):
name = server.get("name") if isinstance(server, dict) else None
if name is not None and name in seen:
continue
if name is not None:
seen.add(name)
merged.append(server)
return merged
def _merge_mcp_configs_into_projects(
self,
mcp_projects: List[Dict],
projects_dict: Dict[str, Dict]
) -> None:
"""
Merge MCP configs into projects dictionary.
Args:
mcp_projects: List of MCP project configs
projects_dict: Dictionary mapping project paths to project configs
"""
total_mcp_servers = 0
merged_count = 0
new_count = 0
for mcp_project in mcp_projects:
project_path = mcp_project["path"]
mcp_servers = mcp_project.get("mcpServers", [])
num_servers = len(mcp_servers)
total_mcp_servers += num_servers
if project_path in projects_dict:
# Merge (union) MCP config into existing project so a second
# source for the same path can't overwrite the first's servers.
projects_dict[project_path]["mcpServers"] = self._union_mcp_servers(
projects_dict[project_path].get("mcpServers", []), mcp_servers
)
merged_count += 1
logger.info(f" Merged MCP config into existing project: {project_path} ({num_servers} MCP servers)")
# Ensure rules field exists
if "rules" not in projects_dict[project_path]:
projects_dict[project_path]["rules"] = []
else:
# Create new project entry with MCP config and empty rules
projects_dict[project_path] = {
"path": project_path,
"mcpServers": mcp_servers,
"rules": []
}
new_count += 1
logger.info(f" Added new project from MCP config: {project_path} ({num_servers} MCP servers)")
if mcp_projects:
logger.info(f" MCP config merge complete: {len(mcp_projects)} projects processed ({merged_count} merged, {new_count} new), {total_mcp_servers} total MCP servers")
def _merge_claude_mcp_configs_into_projects(
self,
mcp_projects: List[Dict],
projects_dict: Dict[str, Dict]
) -> None:
"""
Merge Claude Code MCP configs into projects dictionary.
Includes additionalMcpData extraction for Claude Code specific fields.
Args:
mcp_projects: List of MCP project configs
projects_dict: Dictionary mapping project paths to project configs
"""
total_mcp_servers = 0
merged_count = 0
new_count = 0
for mcp_project in mcp_projects:
project_path = mcp_project["path"]
mcp_servers = mcp_project.get("mcpServers", [])
num_servers = len(mcp_servers)
total_mcp_servers += num_servers
additional_mcp_data = {}
# Extract Claude Code specific fields into additionalMcpData
if mcp_project.get("mcpContextUris"):
additional_mcp_data["mcpContextUris"] = mcp_project["mcpContextUris"]
if mcp_project.get("enabledMcpjsonServers"):
additional_mcp_data["enabledMcpjsonServers"] = mcp_project["enabledMcpjsonServers"]
if mcp_project.get("disabledMcpjsonServers"):
additional_mcp_data["disabledMcpjsonServers"] = mcp_project["disabledMcpjsonServers"]
if project_path in projects_dict:
# Merge (union) MCP config into existing project so a second
# source for the same path (e.g. a home-rooted ~/.mcp.json and
# ~/.claude.json projects[<home>]) can't overwrite the first's
# servers.
projects_dict[project_path]["mcpServers"] = self._union_mcp_servers(
projects_dict[project_path].get("mcpServers", []), mcp_servers
)
if additional_mcp_data and "additionalMcpData" not in projects_dict[project_path]:
projects_dict[project_path]["additionalMcpData"] = additional_mcp_data
merged_count += 1
logger.info(f" Merged Claude MCP config into existing project: {project_path} ({num_servers} MCP servers)")
# Ensure rules field exists
if "rules" not in projects_dict[project_path]:
projects_dict[project_path]["rules"] = []
else:
# Create new project entry with MCP config and empty rules
new_project = {
"path": project_path,
"mcpServers": mcp_servers,
"rules": []
}
if additional_mcp_data:
new_project["additionalMcpData"] = additional_mcp_data
projects_dict[project_path] = new_project
new_count += 1
logger.info(f" Added new project from Claude MCP config: {project_path} ({num_servers} MCP servers)")
if mcp_projects:
logger.info(f" Claude MCP config merge complete: {len(mcp_projects)} projects processed ({merged_count} merged, {new_count} new), {total_mcp_servers} total MCP servers")
def _merge_skills_into_projects(
self,
skills_projects: List[Dict],
projects_dict: Dict[str, Dict]
) -> None:
"""
Merge Claude Code skills into projects dictionary as a separate skills array.
Skills use the same field structure as rules with additional:
- type: "skill" to distinguish from regular rules
- skill_name: the skill directory name
Args:
skills_projects: List of skill project configs (with project_root and skills)
projects_dict: Dictionary mapping project paths to project configs
"""
total_skills = 0
merged_count = 0
new_count = 0
for skill_project in skills_projects:
# Skills projects use "project_root" instead of "path"
project_path = skill_project.get("project_root")
if not project_path:
continue
skills = skill_project.get("skills", [])
num_skills = len(skills)
total_skills += num_skills
if project_path in projects_dict:
# Merge skills into existing project's skills array
if "skills" not in projects_dict[project_path]:
projects_dict[project_path]["skills"] = []
projects_dict[project_path]["skills"].extend(skills)
merged_count += 1
logger.info(f" Merged skills into project: {project_path} ({num_skills} skills)")
else:
# Create new project entry with skills array
projects_dict[project_path] = {
"path": project_path,
"rules": [],
"skills": skills,
"mcpServers": []
}
new_count += 1
logger.info(f" Added new project from skills: {project_path} ({num_skills} skills)")
if skills_projects:
logger.info(f" Skills merge complete: {len(skills_projects)} projects processed ({merged_count} merged, {new_count} new), {total_skills} total skills")
def _merge_rules_into_projects(
self,
rules_projects: List[Dict],
projects_dict: Dict[str, Dict]
) -> None:
"""
Merge Claude Code rules into projects dictionary.
Args:
rules_projects: List of rule project configs (with project_root and rules)
projects_dict: Dictionary mapping project paths to project configs
"""
total_rules = 0
merged_count = 0
new_count = 0
for rules_project in rules_projects:
# Rules projects use "project_root" instead of "path"
project_path = rules_project.get("project_root")
if not project_path:
continue
rules = rules_project.get("rules", [])
num_rules = len(rules)
total_rules += num_rules
if project_path in projects_dict:
# Merge rules into existing project
if "rules" not in projects_dict[project_path]:
projects_dict[project_path]["rules"] = []
projects_dict[project_path]["rules"].extend(rules)
merged_count += 1
logger.info(f" Merged rules into existing project: {project_path} ({num_rules} rules)")
else:
# Create new project entry with rules
projects_dict[project_path] = {
"path": project_path,
"rules": rules,
"skills": [],
"mcpServers": []
}
new_count += 1
logger.info(f" Added new project from rules: {project_path} ({num_rules} rules)")