autosnippet 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +230 -324
  2. package/bin/api-server.js +1 -1
  3. package/bin/cli.js +204 -244
  4. package/bin/mcp-server.js +5 -3
  5. package/config/knowledge-base.config.js +132 -132
  6. package/dashboard/dist/assets/{icons-CEfgGaZi.js → icons-Cdq22n2i.js} +95 -100
  7. package/dashboard/dist/assets/index-ClkyPkDX.js +133 -0
  8. package/dashboard/dist/assets/index-t4QrJwv1.css +1 -0
  9. package/dashboard/dist/index.html +3 -3
  10. package/lib/bootstrap.js +8 -8
  11. package/lib/cli/AiScanService.js +86 -40
  12. package/lib/cli/KnowledgeSyncService.js +113 -74
  13. package/lib/cli/SetupService.js +439 -277
  14. package/lib/cli/UpgradeService.js +63 -100
  15. package/lib/core/AstAnalyzer.js +276 -597
  16. package/lib/core/ast/ProjectGraph.js +101 -40
  17. package/lib/core/ast/ensure-grammars.js +232 -0
  18. package/lib/core/ast/index.js +115 -0
  19. package/lib/core/ast/lang-dart.js +661 -0
  20. package/lib/core/ast/lang-go.js +530 -0
  21. package/lib/core/ast/lang-java.js +435 -0
  22. package/lib/core/ast/lang-javascript.js +272 -0
  23. package/lib/core/ast/lang-kotlin.js +423 -0
  24. package/lib/core/ast/lang-objc.js +388 -0
  25. package/lib/core/ast/lang-python.js +371 -0
  26. package/lib/core/ast/lang-swift.js +337 -0
  27. package/lib/core/ast/lang-typescript.js +503 -0
  28. package/lib/core/capability/CapabilityProbe.js +18 -9
  29. package/lib/core/constitution/Constitution.js +2 -3
  30. package/lib/core/constitution/ConstitutionValidator.js +65 -24
  31. package/lib/core/discovery/DartDiscoverer.js +534 -0
  32. package/lib/core/discovery/DiscovererRegistry.js +83 -0
  33. package/lib/core/discovery/GenericDiscoverer.js +225 -0
  34. package/lib/core/discovery/GoDiscoverer.js +541 -0
  35. package/lib/core/discovery/JvmDiscoverer.js +506 -0
  36. package/lib/core/discovery/NodeDiscoverer.js +466 -0
  37. package/lib/core/discovery/ProjectDiscoverer.js +93 -0
  38. package/lib/core/discovery/PythonDiscoverer.js +338 -0
  39. package/lib/core/discovery/SpmDiscoverer.js +5 -0
  40. package/lib/core/discovery/index.js +53 -0
  41. package/lib/core/enhancement/EnhancementPack.js +71 -0
  42. package/lib/core/enhancement/EnhancementRegistry.js +47 -0
  43. package/lib/core/enhancement/android-enhancement.js +102 -0
  44. package/lib/core/enhancement/django-enhancement.js +70 -0
  45. package/lib/core/enhancement/fastapi-enhancement.js +63 -0
  46. package/lib/core/enhancement/go-grpc-enhancement.js +152 -0
  47. package/lib/core/enhancement/go-web-enhancement.js +201 -0
  48. package/lib/core/enhancement/index.js +65 -0
  49. package/lib/core/enhancement/node-server-enhancement.js +88 -0
  50. package/lib/core/enhancement/react-enhancement.js +86 -0
  51. package/lib/core/enhancement/spring-enhancement.js +112 -0
  52. package/lib/core/enhancement/vue-enhancement.js +96 -0
  53. package/lib/core/gateway/Gateway.js +8 -9
  54. package/lib/core/gateway/GatewayActionRegistry.js +1 -1
  55. package/lib/core/permission/PermissionManager.js +12 -8
  56. package/lib/domain/index.js +13 -9
  57. package/lib/domain/knowledge/KnowledgeEntry.js +111 -101
  58. package/lib/domain/knowledge/KnowledgeRepository.js +0 -1
  59. package/lib/domain/knowledge/Lifecycle.js +22 -22
  60. package/lib/domain/knowledge/index.js +9 -12
  61. package/lib/domain/knowledge/values/Constraints.js +31 -21
  62. package/lib/domain/knowledge/values/Content.js +21 -13
  63. package/lib/domain/knowledge/values/Quality.js +31 -18
  64. package/lib/domain/knowledge/values/Reasoning.js +20 -12
  65. package/lib/domain/knowledge/values/Relations.js +37 -25
  66. package/lib/domain/knowledge/values/Stats.js +18 -12
  67. package/lib/domain/knowledge/values/index.js +4 -3
  68. package/lib/domain/snippet/Snippet.js +35 -10
  69. package/lib/external/ai/AiFactory.js +48 -16
  70. package/lib/external/ai/AiProvider.js +184 -90
  71. package/lib/external/ai/providers/ClaudeProvider.js +25 -12
  72. package/lib/external/ai/providers/GoogleGeminiProvider.js +59 -30
  73. package/lib/external/ai/providers/MockProvider.js +9 -3
  74. package/lib/external/ai/providers/OpenAiProvider.js +51 -29
  75. package/lib/external/mcp/McpServer.js +66 -36
  76. package/lib/external/mcp/errorHandler.js +23 -11
  77. package/lib/external/mcp/handlers/LanguageExtensions.js +138 -53
  78. package/lib/external/mcp/handlers/TargetClassifier.js +52 -16
  79. package/lib/external/mcp/handlers/bootstrap/pipeline/BootstrapSnapshot.js +81 -20
  80. package/lib/external/mcp/handlers/bootstrap/pipeline/EpisodicMemory.js +71 -42
  81. package/lib/external/mcp/handlers/bootstrap/pipeline/IncrementalBootstrap.js +9 -17
  82. package/lib/external/mcp/handlers/bootstrap/pipeline/ToolResultCache.js +14 -9
  83. package/lib/external/mcp/handlers/bootstrap/pipeline/dimension-context.js +15 -7
  84. package/lib/external/mcp/handlers/bootstrap/pipeline/orchestrator.js +352 -153
  85. package/lib/external/mcp/handlers/bootstrap/pipeline/tier-scheduler.js +52 -12
  86. package/lib/external/mcp/handlers/bootstrap/skills.js +143 -39
  87. package/lib/external/mcp/handlers/bootstrap.js +691 -168
  88. package/lib/external/mcp/handlers/browse.js +66 -22
  89. package/lib/external/mcp/handlers/candidate.js +118 -35
  90. package/lib/external/mcp/handlers/consolidated.js +49 -17
  91. package/lib/external/mcp/handlers/guard.js +104 -39
  92. package/lib/external/mcp/handlers/knowledge.js +60 -36
  93. package/lib/external/mcp/handlers/search.js +43 -14
  94. package/lib/external/mcp/handlers/skill.js +120 -45
  95. package/lib/external/mcp/handlers/structure.js +240 -86
  96. package/lib/external/mcp/handlers/system.js +42 -12
  97. package/lib/external/mcp/handlers/wiki.js +58 -33
  98. package/lib/external/mcp/tools.js +306 -123
  99. package/lib/http/HttpServer.js +72 -47
  100. package/lib/http/middleware/RateLimiter.js +5 -3
  101. package/lib/http/middleware/errorHandler.js +6 -1
  102. package/lib/http/middleware/requestLogger.js +14 -3
  103. package/lib/http/middleware/roleResolver.js +30 -23
  104. package/lib/http/routes/ai.js +387 -265
  105. package/lib/http/routes/auth.js +81 -61
  106. package/lib/http/routes/candidates.js +430 -320
  107. package/lib/http/routes/commands.js +289 -189
  108. package/lib/http/routes/extract.js +158 -125
  109. package/lib/http/routes/guardRules.js +309 -217
  110. package/lib/http/routes/knowledge.js +213 -154
  111. package/lib/http/routes/modules.js +578 -0
  112. package/lib/http/routes/monitoring.js +6 -6
  113. package/lib/http/routes/recipes.js +104 -93
  114. package/lib/http/routes/search.js +361 -305
  115. package/lib/http/routes/skills.js +145 -98
  116. package/lib/http/routes/snippets.js +42 -30
  117. package/lib/http/routes/spm.js +3 -405
  118. package/lib/http/routes/violations.js +113 -93
  119. package/lib/http/routes/wiki.js +211 -170
  120. package/lib/http/utils/routeHelpers.js +3 -1
  121. package/lib/http/utils/sse-sessions.js +16 -6
  122. package/lib/http/utils/sse.js +15 -5
  123. package/lib/infrastructure/audit/AuditLogger.js +5 -2
  124. package/lib/infrastructure/audit/AuditStore.js +10 -7
  125. package/lib/infrastructure/cache/CacheService.js +3 -1
  126. package/lib/infrastructure/cache/GraphCache.js +8 -4
  127. package/lib/infrastructure/cache/UnifiedCacheAdapter.js +1 -1
  128. package/lib/infrastructure/config/ConfigLoader.js +9 -5
  129. package/lib/infrastructure/config/Defaults.js +30 -10
  130. package/lib/infrastructure/config/Paths.js +28 -8
  131. package/lib/infrastructure/config/TriggerSymbol.js +22 -10
  132. package/lib/infrastructure/database/DatabaseConnection.js +15 -10
  133. package/lib/infrastructure/database/migrations/001_initial_schema.js +0 -1
  134. package/lib/infrastructure/external/ClipboardManager.js +6 -2
  135. package/lib/infrastructure/external/NativeUi.js +50 -43
  136. package/lib/infrastructure/external/OpenBrowser.js +14 -17
  137. package/lib/infrastructure/external/XcodeAutomation.js +14 -258
  138. package/lib/infrastructure/logging/Logger.js +46 -30
  139. package/lib/infrastructure/monitoring/ErrorTracker.js +7 -5
  140. package/lib/infrastructure/monitoring/PerformanceMonitor.js +12 -4
  141. package/lib/infrastructure/paths/HeaderResolver.js +25 -9
  142. package/lib/infrastructure/paths/PathFinder.js +34 -12
  143. package/lib/infrastructure/plugin/PluginManager.js +26 -8
  144. package/lib/infrastructure/realtime/RealtimeService.js +2 -2
  145. package/lib/infrastructure/vector/Chunker.js +22 -7
  146. package/lib/infrastructure/vector/IndexingPipeline.js +46 -22
  147. package/lib/infrastructure/vector/JsonVectorAdapter.js +90 -53
  148. package/lib/infrastructure/vector/VectorStore.js +28 -10
  149. package/lib/injection/ServiceContainer.js +247 -93
  150. package/lib/platform/ios/index.js +63 -0
  151. package/lib/platform/ios/routes/spm.js +437 -0
  152. package/lib/platform/ios/snippet/PlaceholderConverter.js +55 -0
  153. package/lib/platform/ios/snippet/XcodeCodec.js +112 -0
  154. package/lib/{service → platform/ios}/spm/DependencyGraph.js +41 -17
  155. package/lib/{service → platform/ios}/spm/PackageSwiftParser.js +41 -14
  156. package/lib/{service → platform/ios}/spm/PolicyEngine.js +9 -4
  157. package/lib/platform/ios/spm/SpmDiscoverer.js +122 -0
  158. package/lib/{service → platform/ios}/spm/SpmService.js +385 -127
  159. package/lib/{service/automation → platform/ios/xcode}/SaveEventFilter.js +8 -7
  160. package/lib/platform/ios/xcode/XcodeAutomation.js +350 -0
  161. package/lib/{service/automation → platform/ios/xcode}/XcodeIntegration.js +325 -145
  162. package/lib/repository/base/BaseRepository.js +7 -9
  163. package/lib/repository/knowledge/KnowledgeRepository.impl.js +98 -75
  164. package/lib/repository/token/TokenUsageStore.js +4 -2
  165. package/lib/service/automation/ActionPipeline.js +1 -1
  166. package/lib/service/automation/AutomationOrchestrator.js +8 -4
  167. package/lib/service/automation/ContextCollector.js +7 -5
  168. package/lib/service/automation/DirectiveDetector.js +23 -16
  169. package/lib/service/automation/FileWatcher.js +112 -56
  170. package/lib/service/automation/TriggerResolver.js +6 -4
  171. package/lib/service/automation/handlers/AlinkHandler.js +24 -12
  172. package/lib/service/automation/handlers/CreateHandler.js +19 -20
  173. package/lib/service/automation/handlers/DraftHandler.js +14 -8
  174. package/lib/service/automation/handlers/GuardHandler.js +93 -63
  175. package/lib/service/automation/handlers/HeaderHandler.js +1 -6
  176. package/lib/service/automation/handlers/SearchHandler.js +155 -88
  177. package/lib/service/bootstrap/BootstrapTaskManager.js +77 -35
  178. package/lib/service/candidate/SimilarityService.js +25 -9
  179. package/lib/service/chat/AnalystAgent.js +50 -24
  180. package/lib/service/chat/CandidateGuardrail.js +143 -17
  181. package/lib/service/chat/ChatAgent.js +655 -260
  182. package/lib/service/chat/ContextWindow.js +116 -71
  183. package/lib/service/chat/ConversationStore.js +77 -36
  184. package/lib/service/chat/EpisodicConsolidator.js +47 -23
  185. package/lib/service/chat/HandoffProtocol.js +98 -22
  186. package/lib/service/chat/Memory.js +34 -14
  187. package/lib/service/chat/ProducerAgent.js +40 -20
  188. package/lib/service/chat/ProjectSemanticMemory.js +109 -78
  189. package/lib/service/chat/ReasoningLayer.js +148 -70
  190. package/lib/service/chat/ReasoningTrace.js +44 -32
  191. package/lib/service/chat/TaskPipeline.js +39 -19
  192. package/lib/service/chat/ToolRegistry.js +48 -29
  193. package/lib/service/chat/WorkingMemory.js +44 -18
  194. package/lib/service/chat/tools.js +1096 -494
  195. package/lib/service/context/RecipeExtractor.js +132 -51
  196. package/lib/service/cursor/CursorDeliveryPipeline.js +82 -37
  197. package/lib/service/cursor/KnowledgeCompressor.js +25 -22
  198. package/lib/service/cursor/RulesGenerator.js +13 -7
  199. package/lib/service/cursor/SkillsSyncer.js +77 -27
  200. package/lib/service/cursor/TokenBudget.js +2 -2
  201. package/lib/service/cursor/TopicClassifier.js +54 -20
  202. package/lib/service/guard/ComplianceReporter.js +55 -43
  203. package/lib/service/guard/ExclusionManager.js +67 -29
  204. package/lib/service/guard/GuardCheckEngine.js +381 -86
  205. package/lib/service/guard/GuardFeedbackLoop.js +22 -10
  206. package/lib/service/guard/GuardService.js +29 -19
  207. package/lib/service/guard/RuleLearner.js +55 -23
  208. package/lib/service/guard/SourceFileCollector.js +27 -20
  209. package/lib/service/guard/ViolationsStore.js +43 -38
  210. package/lib/service/knowledge/CodeEntityGraph.js +147 -82
  211. package/lib/service/knowledge/ConfidenceRouter.js +12 -10
  212. package/lib/service/knowledge/KnowledgeFileWriter.js +147 -56
  213. package/lib/service/knowledge/KnowledgeGraphService.js +81 -34
  214. package/lib/service/knowledge/KnowledgeService.js +222 -112
  215. package/lib/service/module/ModuleService.js +969 -0
  216. package/lib/service/quality/FeedbackCollector.js +27 -15
  217. package/lib/service/quality/QualityScorer.js +78 -24
  218. package/lib/service/recipe/RecipeCandidateValidator.js +110 -44
  219. package/lib/service/recipe/RecipeParser.js +78 -45
  220. package/lib/service/search/CoarseRanker.js +43 -28
  221. package/lib/service/search/CrossEncoderReranker.js +32 -21
  222. package/lib/service/search/InvertedIndex.js +21 -7
  223. package/lib/service/search/MultiSignalRanker.js +90 -28
  224. package/lib/service/search/RetrievalFunnel.js +45 -24
  225. package/lib/service/search/SearchEngine.js +255 -103
  226. package/lib/service/skills/EventAggregator.js +32 -15
  227. package/lib/service/skills/SignalCollector.js +140 -64
  228. package/lib/service/skills/SkillAdvisor.js +79 -42
  229. package/lib/service/skills/SkillHooks.js +16 -14
  230. package/lib/service/snippet/PlaceholderConverter.js +5 -0
  231. package/lib/service/snippet/SnippetFactory.js +116 -99
  232. package/lib/service/snippet/SnippetInstaller.js +234 -62
  233. package/lib/service/snippet/codecs/SnippetCodec.js +67 -0
  234. package/lib/service/snippet/codecs/VSCodeCodec.js +102 -0
  235. package/lib/service/snippet/codecs/XcodeCodec.js +5 -0
  236. package/lib/service/wiki/WikiGenerator.js +637 -263
  237. package/lib/shared/DimensionCopyRegistry.js +472 -0
  238. package/lib/shared/LanguageService.js +399 -0
  239. package/lib/shared/PathGuard.js +45 -28
  240. package/lib/shared/RecipeReadinessChecker.js +72 -12
  241. package/lib/shared/constants.js +41 -41
  242. package/lib/shared/errors/BaseError.js +2 -2
  243. package/lib/shared/errors/index.js +4 -4
  244. package/lib/shared/similarity.js +25 -8
  245. package/lib/shared/token-utils.js +6 -2
  246. package/lib/shared/utils/common.js +12 -4
  247. package/package.json +49 -13
  248. package/scripts/bench-real-projects.mjs +256 -0
  249. package/scripts/build-native-ui.js +30 -30
  250. package/scripts/clear-old-vector-index.js +5 -35
  251. package/scripts/clear-vector-cache.js +7 -37
  252. package/scripts/collect-test-project-stats.mjs +160 -0
  253. package/scripts/diagnose-mcp.js +41 -32
  254. package/scripts/ensure-parse-package.js +6 -9
  255. package/scripts/generate-recipe-drafts.js +116 -77
  256. package/scripts/init-db.js +3 -20
  257. package/scripts/init-snippets.js +305 -0
  258. package/scripts/init-vector-db.js +173 -170
  259. package/scripts/install-cursor-skill.js +148 -104
  260. package/scripts/install-full.js +8 -21
  261. package/scripts/install-vscode-copilot.js +146 -145
  262. package/scripts/migrate-md-to-knowledge.mjs +139 -151
  263. package/scripts/postinstall-safe.js +5 -17
  264. package/scripts/recipe-audit.js +106 -82
  265. package/scripts/release.js +283 -323
  266. package/scripts/setup-mcp-config.js +60 -52
  267. package/scripts/verify-context-api.js +20 -20
  268. package/skills/autosnippet-analysis/SKILL.md +10 -6
  269. package/skills/autosnippet-candidates/SKILL.md +27 -26
  270. package/skills/autosnippet-coldstart/SKILL.md +555 -38
  271. package/skills/autosnippet-concepts/SKILL.md +349 -337
  272. package/skills/autosnippet-create/SKILL.md +5 -5
  273. package/skills/autosnippet-reference-dart/SKILL.md +543 -0
  274. package/skills/autosnippet-reference-go/SKILL.md +539 -0
  275. package/skills/autosnippet-reference-java/SKILL.md +534 -0
  276. package/skills/autosnippet-reference-jsts/SKILL.md +41 -9
  277. package/skills/autosnippet-reference-kotlin/SKILL.md +526 -0
  278. package/skills/autosnippet-reference-objc/SKILL.md +29 -6
  279. package/skills/autosnippet-reference-python/SKILL.md +800 -0
  280. package/skills/autosnippet-reference-swift/SKILL.md +70 -14
  281. package/skills/autosnippet-structure/SKILL.md +4 -4
  282. package/templates/cursor-rules/autosnippet-conventions.mdc +2 -2
  283. package/templates/recipes-setup/README.md +2 -2
  284. package/templates/recipes-setup/_template.md +1 -1
  285. package/dashboard/dist/assets/index-Bun3ld_J.css +0 -1
  286. package/dashboard/dist/assets/index-_Sk_Dmg3.js +0 -143
  287. package/resources/asd-entry/main.swift +0 -159
  288. package/scripts/build-asd-entry.js +0 -51
  289. package/scripts/init-xcode-snippets.js +0 -311
  290. package/template.json +0 -39
@@ -0,0 +1,541 @@
1
+ /**
2
+ * @module GoDiscoverer
3
+ * @description Go 项目结构发现器
4
+ *
5
+ * 检测信号: go.mod, go.sum, *.go
6
+ * 支持: 单 Module 项目、Go Workspace (go.work)、标准目录布局 (cmd/ internal/ pkg/)
7
+ */
8
+
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
10
+ import { basename, extname, join, relative } from 'node:path';
11
+ import { ProjectDiscoverer } from './ProjectDiscoverer.js';
12
+
13
+ const SOURCE_EXTENSIONS = new Set(['.go']);
14
+
15
+ const EXCLUDE_DIRS = new Set([
16
+ '.git',
17
+ 'vendor',
18
+ 'node_modules',
19
+ 'testdata',
20
+ '.cache',
21
+ 'dist',
22
+ 'build',
23
+ '_output',
24
+ ]);
25
+
26
+ export class GoDiscoverer extends ProjectDiscoverer {
27
+ #projectRoot = null;
28
+ #targets = [];
29
+ #depGraph = { nodes: [], edges: [] };
30
+ #modulePath = null;
31
+
32
+ get id() {
33
+ return 'go';
34
+ }
35
+ get displayName() {
36
+ return 'Go (modules)';
37
+ }
38
+
39
+ async detect(projectRoot) {
40
+ let confidence = 0;
41
+ const reasons = [];
42
+
43
+ if (existsSync(join(projectRoot, 'go.mod'))) {
44
+ confidence = 0.92;
45
+ reasons.push('go.mod exists');
46
+ }
47
+ if (existsSync(join(projectRoot, 'go.sum'))) {
48
+ confidence = Math.max(confidence, 0.7);
49
+ if (confidence < 0.92) {
50
+ confidence += 0.1;
51
+ }
52
+ reasons.push('go.sum exists');
53
+ }
54
+ if (existsSync(join(projectRoot, 'go.work'))) {
55
+ confidence = Math.max(confidence, 0.95);
56
+ reasons.push('go.work exists (workspace)');
57
+ }
58
+
59
+ // 兜底: 根目录有 .go 文件
60
+ if (confidence === 0) {
61
+ try {
62
+ const entries = readdirSync(projectRoot);
63
+ if (entries.some((e) => e.endsWith('.go'))) {
64
+ confidence = 0.5;
65
+ reasons.push('*.go files found at root');
66
+ }
67
+ } catch {
68
+ /* skip */
69
+ }
70
+ }
71
+
72
+ return {
73
+ match: confidence > 0,
74
+ confidence: Math.min(confidence, 1.0),
75
+ reason: reasons.join(', ') || 'No Go markers found',
76
+ };
77
+ }
78
+
79
+ async load(projectRoot) {
80
+ this.#projectRoot = projectRoot;
81
+ this.#targets = [];
82
+ this.#depGraph = { nodes: [], edges: [] };
83
+
84
+ // 解析 go.mod
85
+ this.#modulePath = this.#parseGoMod(projectRoot);
86
+ const projectName = this.#modulePath
87
+ ? this.#modulePath.split('/').pop()
88
+ : basename(projectRoot);
89
+
90
+ // 主 Target — 始终覆盖整个 module(Go 项目根目录递归收集所有 .go 文件)
91
+ const framework = this.#detectFramework(projectRoot);
92
+ this.#targets.push({
93
+ name: projectName,
94
+ path: projectRoot,
95
+ type: 'library',
96
+ language: 'go',
97
+ framework,
98
+ metadata: { modulePath: this.#modulePath },
99
+ });
100
+ this.#depGraph.nodes.push(projectName);
101
+
102
+ // cmd/ 下的子命令作为独立 Target
103
+ const cmdTargets = this.#discoverCmdTargets(projectRoot);
104
+ for (const t of cmdTargets) {
105
+ this.#targets.push(t);
106
+ this.#depGraph.nodes.push(t.name);
107
+ }
108
+
109
+ // 检测 test 目录(如果存在独立的 tests/ 或 test/)
110
+ for (const testDir of ['test', 'tests', 'e2e']) {
111
+ const testPath = join(projectRoot, testDir);
112
+ if (existsSync(testPath) && !this.#targets.some((t) => t.name === testDir)) {
113
+ this.#targets.push({
114
+ name: testDir,
115
+ path: testPath,
116
+ type: 'test',
117
+ language: 'go',
118
+ });
119
+ }
120
+ }
121
+
122
+ // 发现内部子包(binding/, render/, internal/ 等)
123
+ this.#discoverInternalPackages(projectRoot);
124
+
125
+ // 解析 go.mod 外部依赖(同时添加为 node)
126
+ this.#parseDependencies(projectRoot);
127
+
128
+ // 解析内部 import 关系
129
+ this.#parseInternalImports(projectRoot);
130
+ }
131
+
132
+ async listTargets() {
133
+ return this.#targets;
134
+ }
135
+
136
+ async getTargetFiles(target) {
137
+ const targetPath =
138
+ typeof target === 'string'
139
+ ? this.#targets.find((t) => t.name === target)?.path || this.#projectRoot
140
+ : target.path;
141
+
142
+ if (!targetPath || !existsSync(targetPath)) {
143
+ return [];
144
+ }
145
+
146
+ const files = [];
147
+ this.#collectGoFiles(targetPath, targetPath, files);
148
+ return files;
149
+ }
150
+
151
+ async getDependencyGraph() {
152
+ return this.#depGraph;
153
+ }
154
+
155
+ // ── 内部实现 ──
156
+
157
+ /**
158
+ * 解析 go.mod 提取 module path
159
+ */
160
+ #parseGoMod(projectRoot) {
161
+ const goModPath = join(projectRoot, 'go.mod');
162
+ if (!existsSync(goModPath)) {
163
+ return null;
164
+ }
165
+ try {
166
+ const content = readFileSync(goModPath, 'utf8');
167
+ const match = content.match(/^module\s+(\S+)/m);
168
+ return match ? match[1] : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 发现 Go 标准约定目录: pkg/, internal/, api/
176
+ */
177
+ #discoverConventionDirs(projectRoot) {
178
+ const dirs = [];
179
+ const conventionNames = [
180
+ { name: 'pkg', type: 'library' },
181
+ { name: 'internal', type: 'library' },
182
+ { name: 'api', type: 'library' },
183
+ { name: 'server', type: 'application' },
184
+ { name: 'service', type: 'application' },
185
+ ];
186
+
187
+ const framework = this.#detectFramework(projectRoot);
188
+
189
+ for (const conv of conventionNames) {
190
+ const dirPath = join(projectRoot, conv.name);
191
+ if (existsSync(dirPath)) {
192
+ try {
193
+ const entries = readdirSync(dirPath, { withFileTypes: true });
194
+ const hasGoFiles = entries.some(
195
+ (e) => e.isFile() && e.name.endsWith('.go')
196
+ );
197
+ const hasGoSubDirs = entries.some(
198
+ (e) => e.isDirectory() && !e.name.startsWith('.') && !EXCLUDE_DIRS.has(e.name)
199
+ );
200
+ if (hasGoFiles || hasGoSubDirs) {
201
+ dirs.push({
202
+ name: conv.name,
203
+ path: dirPath,
204
+ type: conv.type,
205
+ language: 'go',
206
+ framework,
207
+ metadata: { modulePath: this.#modulePath },
208
+ });
209
+ }
210
+ } catch {
211
+ /* skip */
212
+ }
213
+ }
214
+ }
215
+
216
+ return dirs;
217
+ }
218
+
219
+ /**
220
+ * 发现 cmd/ 下的子命令—每个含 main.go 的子目录为一个 binary Target
221
+ */
222
+ #discoverCmdTargets(projectRoot) {
223
+ const cmdDir = join(projectRoot, 'cmd');
224
+ if (!existsSync(cmdDir)) {
225
+ return [];
226
+ }
227
+
228
+ const targets = [];
229
+ const framework = this.#detectFramework(projectRoot);
230
+
231
+ try {
232
+ const entries = readdirSync(cmdDir, { withFileTypes: true });
233
+ for (const entry of entries) {
234
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
235
+ const subDir = join(cmdDir, entry.name);
236
+ targets.push({
237
+ name: `cmd/${entry.name}`,
238
+ path: subDir,
239
+ type: 'application',
240
+ language: 'go',
241
+ framework,
242
+ metadata: { modulePath: this.#modulePath, isCmdBinary: true },
243
+ });
244
+ }
245
+ }
246
+ } catch {
247
+ /* skip */
248
+ }
249
+
250
+ // cmd/ 根目录本身有 main.go
251
+ if (targets.length === 0) {
252
+ try {
253
+ const entries = readdirSync(cmdDir);
254
+ if (entries.some((e) => e.endsWith('.go'))) {
255
+ targets.push({
256
+ name: 'cmd',
257
+ path: cmdDir,
258
+ type: 'application',
259
+ language: 'go',
260
+ framework,
261
+ metadata: { modulePath: this.#modulePath },
262
+ });
263
+ }
264
+ } catch {
265
+ /* skip */
266
+ }
267
+ }
268
+
269
+ return targets;
270
+ }
271
+
272
+ /**
273
+ * 检测 Go Web 框架
274
+ */
275
+ #detectFramework(projectRoot) {
276
+ const goModPath = join(projectRoot, 'go.mod');
277
+ if (!existsSync(goModPath)) {
278
+ return null;
279
+ }
280
+
281
+ try {
282
+ const content = readFileSync(goModPath, 'utf8');
283
+
284
+ if (/github\.com\/gin-gonic\/gin\b/.test(content)) {
285
+ return 'gin';
286
+ }
287
+ if (/github\.com\/labstack\/echo\b/.test(content)) {
288
+ return 'echo';
289
+ }
290
+ if (/github\.com\/gofiber\/fiber\b/.test(content)) {
291
+ return 'fiber';
292
+ }
293
+ if (/github\.com\/gorilla\/mux\b/.test(content)) {
294
+ return 'gorilla';
295
+ }
296
+ if (/github\.com\/beego\b|github\.com\/astaxie\/beego\b/.test(content)) {
297
+ return 'beego';
298
+ }
299
+ if (/google\.golang\.org\/grpc\b/.test(content)) {
300
+ return 'grpc';
301
+ }
302
+ if (/github\.com\/go-chi\/chi\b/.test(content)) {
303
+ return 'chi';
304
+ }
305
+ } catch {
306
+ /* skip */
307
+ }
308
+
309
+ return null;
310
+ }
311
+
312
+ /**
313
+ * 发现内部子包——目录中包含 .go 文件即为一个 Go package
314
+ */
315
+ #discoverInternalPackages(projectRoot) {
316
+ const nodeSet = new Set(this.#depGraph.nodes.map(n => (typeof n === 'string' ? n : n.id)));
317
+
318
+ const walk = (dir, relPath, depth) => {
319
+ if (depth > 6) return;
320
+ try {
321
+ const entries = readdirSync(dir, { withFileTypes: true });
322
+ for (const entry of entries) {
323
+ if (!entry.isDirectory() || entry.name.startsWith('.') || EXCLUDE_DIRS.has(entry.name)) continue;
324
+ const subDir = join(dir, entry.name);
325
+ const subRel = relPath ? `${relPath}/${entry.name}` : entry.name;
326
+
327
+ // 检查目录中是否包含 .go 文件
328
+ try {
329
+ const subEntries = readdirSync(subDir);
330
+ const hasGoFiles = subEntries.some(e => e.endsWith('.go'));
331
+ if (hasGoFiles && !nodeSet.has(subRel)) {
332
+ this.#depGraph.nodes.push({ id: subRel, label: subRel, type: 'internal' });
333
+ nodeSet.add(subRel);
334
+ }
335
+ } catch { /* skip */ }
336
+
337
+ walk(subDir, subRel, depth + 1);
338
+ }
339
+ } catch { /* skip */ }
340
+ };
341
+
342
+ walk(projectRoot, '', 0);
343
+ }
344
+
345
+ /**
346
+ * 解析 go.mod 依赖到 depGraph(同时将直接依赖添加为 node)
347
+ */
348
+ #parseDependencies(projectRoot) {
349
+ const goModPath = join(projectRoot, 'go.mod');
350
+ if (!existsSync(goModPath)) {
351
+ return;
352
+ }
353
+
354
+ const nodeSet = new Set(this.#depGraph.nodes.map(n => (typeof n === 'string' ? n : n.id)));
355
+ const rootNode = (typeof this.#depGraph.nodes[0] === 'string')
356
+ ? this.#depGraph.nodes[0]
357
+ : this.#depGraph.nodes[0]?.id || 'root';
358
+
359
+ const addExtDep = (fullPath, indirect) => {
360
+ const shortName = fullPath.split('/').pop();
361
+ // 添加为 node(如果不存在)
362
+ if (!nodeSet.has(shortName)) {
363
+ this.#depGraph.nodes.push({
364
+ id: shortName,
365
+ label: shortName,
366
+ type: 'external',
367
+ fullPath,
368
+ indirect,
369
+ });
370
+ nodeSet.add(shortName);
371
+ }
372
+ // 添加 edge
373
+ this.#depGraph.edges.push({
374
+ from: rootNode,
375
+ to: shortName,
376
+ type: indirect ? 'indirect' : 'dependency',
377
+ });
378
+ };
379
+
380
+ try {
381
+ const content = readFileSync(goModPath, 'utf8');
382
+
383
+ // 块 require
384
+ const requireBlocks = content.matchAll(/require\s*\(([\s\S]*?)\)/g);
385
+ for (const block of requireBlocks) {
386
+ const lines = block[1].split('\n');
387
+ for (const line of lines) {
388
+ const trimmed = line.trim();
389
+ if (trimmed && !trimmed.startsWith('//')) {
390
+ const parts = trimmed.split(/\s+/);
391
+ if (parts.length >= 2) {
392
+ const indirect = trimmed.includes('// indirect');
393
+ addExtDep(parts[0], indirect);
394
+ }
395
+ }
396
+ }
397
+ }
398
+
399
+ // 单行 require(排除 block 语法 `require (`)
400
+ const singleRequires = content.matchAll(/^require\s+([^\s(]\S*)\s+\S+/gm);
401
+ for (const m of singleRequires) {
402
+ const indirect = m[0].includes('// indirect');
403
+ addExtDep(m[1], indirect);
404
+ }
405
+ } catch {
406
+ /* skip */
407
+ }
408
+ }
409
+
410
+ /**
411
+ * 解析内部 Go import 语句,构建子包间依赖关系
412
+ */
413
+ #parseInternalImports(projectRoot) {
414
+ if (!this.#modulePath) return;
415
+
416
+ const internalNodes = new Set(
417
+ this.#depGraph.nodes
418
+ .filter(n => (typeof n === 'object' && n.type === 'internal'))
419
+ .map(n => n.id)
420
+ );
421
+
422
+ // 也包含根包
423
+ const rootNodeId = typeof this.#depGraph.nodes[0] === 'string'
424
+ ? this.#depGraph.nodes[0]
425
+ : this.#depGraph.nodes[0]?.id;
426
+
427
+ const edgeSet = new Set();
428
+
429
+ const scanPkgImports = (dir, pkgId) => {
430
+ try {
431
+ const entries = readdirSync(dir);
432
+ for (const entry of entries) {
433
+ if (!entry.endsWith('.go')) continue;
434
+ try {
435
+ const content = readFileSync(join(dir, entry), 'utf8');
436
+ // 匹配 import 块和单行 import
437
+ const importBlocks = content.matchAll(/import\s*\(([\s\S]*?)\)/g);
438
+ for (const block of importBlocks) {
439
+ const lines = block[1].split('\n');
440
+ for (const line of lines) {
441
+ this.#matchInternalImport(line, pkgId, rootNodeId, internalNodes, edgeSet);
442
+ }
443
+ }
444
+ const singleImports = content.matchAll(/^import\s+(?:\w+\s+)?"([^"]+)"/gm);
445
+ for (const m of singleImports) {
446
+ this.#matchInternalImport(`"${m[1]}"`, pkgId, rootNodeId, internalNodes, edgeSet);
447
+ }
448
+ } catch { /* skip */ }
449
+ }
450
+ } catch { /* skip */ }
451
+ };
452
+
453
+ // 扫描根包
454
+ scanPkgImports(projectRoot, rootNodeId);
455
+
456
+ // 扫描各内部子包
457
+ for (const pkgId of internalNodes) {
458
+ scanPkgImports(join(projectRoot, pkgId), pkgId);
459
+ }
460
+ }
461
+
462
+ /**
463
+ * 从 import 行中匹配内部包引用
464
+ */
465
+ #matchInternalImport(line, fromPkgId, rootNodeId, internalNodes, edgeSet) {
466
+ const match = line.match(/"([^"]+)"/);
467
+ if (!match) return;
468
+
469
+ const importPath = match[1];
470
+ if (!importPath.startsWith(this.#modulePath + '/')) return;
471
+
472
+ // 去掉 module path 前缀得到相对路径
473
+ const relImport = importPath.slice(this.#modulePath.length + 1);
474
+
475
+ // 确定目标节点
476
+ let targetId = null;
477
+ if (internalNodes.has(relImport)) {
478
+ targetId = relImport;
479
+ } else {
480
+ // 可能是子路径,匹配最近的已知包
481
+ for (const nodeId of internalNodes) {
482
+ if (relImport.startsWith(nodeId + '/') || relImport === nodeId) {
483
+ targetId = nodeId;
484
+ break;
485
+ }
486
+ }
487
+ }
488
+
489
+ if (targetId && targetId !== fromPkgId) {
490
+ const edgeKey = `${fromPkgId}->${targetId}`;
491
+ if (!edgeSet.has(edgeKey)) {
492
+ edgeSet.add(edgeKey);
493
+ this.#depGraph.edges.push({
494
+ from: fromPkgId,
495
+ to: targetId,
496
+ type: 'internal',
497
+ });
498
+ }
499
+ }
500
+ }
501
+
502
+ /**
503
+ * 递归收集 .go 文件
504
+ */
505
+ #collectGoFiles(dir, rootDir, files, depth = 0) {
506
+ if (depth > 15) {
507
+ return;
508
+ }
509
+
510
+ try {
511
+ const entries = readdirSync(dir, { withFileTypes: true });
512
+ for (const entry of entries) {
513
+ if (entry.name.startsWith('.')) {
514
+ continue;
515
+ }
516
+
517
+ if (entry.isDirectory()) {
518
+ if (EXCLUDE_DIRS.has(entry.name)) {
519
+ continue;
520
+ }
521
+ this.#collectGoFiles(join(dir, entry.name), rootDir, files, depth + 1);
522
+ } else if (entry.isFile() && SOURCE_EXTENSIONS.has(extname(entry.name))) {
523
+ const fullPath = join(dir, entry.name);
524
+ try {
525
+ const content = readFileSync(fullPath, 'utf8');
526
+ files.push({
527
+ name: entry.name,
528
+ path: fullPath,
529
+ relativePath: relative(rootDir, fullPath),
530
+ content,
531
+ });
532
+ } catch {
533
+ /* unreadable */
534
+ }
535
+ }
536
+ }
537
+ } catch {
538
+ /* permission error */
539
+ }
540
+ }
541
+ }