@mycodemap/mycodemap 1.9.0 → 2.7.0

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 (527) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +63 -978
  3. package/README.zh-CN.md +1096 -0
  4. package/dist/cli/commands/agent-metrics/human.d.ts +4 -0
  5. package/dist/cli/commands/agent-metrics/human.d.ts.map +1 -0
  6. package/dist/cli/commands/agent-metrics/human.js +134 -0
  7. package/dist/cli/commands/agent-metrics/human.js.map +1 -0
  8. package/dist/cli/commands/agent-metrics/index.d.ts +15 -0
  9. package/dist/cli/commands/agent-metrics/index.d.ts.map +1 -0
  10. package/dist/cli/commands/agent-metrics/index.js +116 -0
  11. package/dist/cli/commands/agent-metrics/index.js.map +1 -0
  12. package/dist/cli/commands/analyze-options.d.ts.map +1 -1
  13. package/dist/cli/commands/analyze-options.js +8 -0
  14. package/dist/cli/commands/analyze-options.js.map +1 -1
  15. package/dist/cli/commands/analyze.d.ts +3 -196
  16. package/dist/cli/commands/analyze.d.ts.map +1 -1
  17. package/dist/cli/commands/analyze.js +27 -1162
  18. package/dist/cli/commands/analyze.js.map +1 -1
  19. package/dist/cli/commands/benchmark.d.ts +8 -0
  20. package/dist/cli/commands/benchmark.d.ts.map +1 -0
  21. package/dist/cli/commands/benchmark.js +153 -0
  22. package/dist/cli/commands/benchmark.js.map +1 -0
  23. package/dist/cli/commands/complexity.d.ts.map +1 -1
  24. package/dist/cli/commands/complexity.js +62 -95
  25. package/dist/cli/commands/complexity.js.map +1 -1
  26. package/dist/cli/commands/deps.d.ts +3 -59
  27. package/dist/cli/commands/deps.d.ts.map +1 -1
  28. package/dist/cli/commands/deps.js +25 -331
  29. package/dist/cli/commands/deps.js.map +1 -1
  30. package/dist/cli/commands/doctor.d.ts +3 -0
  31. package/dist/cli/commands/doctor.d.ts.map +1 -0
  32. package/dist/cli/commands/doctor.js +34 -0
  33. package/dist/cli/commands/doctor.js.map +1 -0
  34. package/dist/cli/commands/env-contract.d.ts +3 -0
  35. package/dist/cli/commands/env-contract.d.ts.map +1 -0
  36. package/dist/cli/commands/env-contract.js +221 -0
  37. package/dist/cli/commands/env-contract.js.map +1 -0
  38. package/dist/cli/commands/generate.d.ts +19 -1
  39. package/dist/cli/commands/generate.d.ts.map +1 -1
  40. package/dist/cli/commands/generate.js +735 -89
  41. package/dist/cli/commands/generate.js.map +1 -1
  42. package/dist/cli/commands/impact.d.ts +4 -38
  43. package/dist/cli/commands/impact.d.ts.map +1 -1
  44. package/dist/cli/commands/impact.js +133 -375
  45. package/dist/cli/commands/impact.js.map +1 -1
  46. package/dist/cli/commands/init.d.ts +1 -0
  47. package/dist/cli/commands/init.d.ts.map +1 -1
  48. package/dist/cli/commands/init.js +61 -2
  49. package/dist/cli/commands/init.js.map +1 -1
  50. package/dist/cli/commands/preview.d.ts +3 -0
  51. package/dist/cli/commands/preview.d.ts.map +1 -0
  52. package/dist/cli/commands/preview.js +216 -0
  53. package/dist/cli/commands/preview.js.map +1 -0
  54. package/dist/cli/commands/query.d.ts +2 -20
  55. package/dist/cli/commands/query.d.ts.map +1 -1
  56. package/dist/cli/commands/query.js +23 -708
  57. package/dist/cli/commands/query.js.map +1 -1
  58. package/dist/cli/commands/watch-foreground.d.ts.map +1 -1
  59. package/dist/cli/commands/watch-foreground.js +5 -1
  60. package/dist/cli/commands/watch-foreground.js.map +1 -1
  61. package/dist/cli/config-loader.d.ts.map +1 -1
  62. package/dist/cli/config-loader.js +51 -13
  63. package/dist/cli/config-loader.js.map +1 -1
  64. package/dist/cli/doctor/check-agent.d.ts +3 -0
  65. package/dist/cli/doctor/check-agent.d.ts.map +1 -0
  66. package/dist/cli/doctor/check-agent.js +60 -0
  67. package/dist/cli/doctor/check-agent.js.map +1 -0
  68. package/dist/cli/doctor/check-env-contract.d.ts +3 -0
  69. package/dist/cli/doctor/check-env-contract.d.ts.map +1 -0
  70. package/dist/cli/doctor/check-env-contract.js +96 -0
  71. package/dist/cli/doctor/check-env-contract.js.map +1 -0
  72. package/dist/cli/doctor/check-ghost-commands.d.ts +3 -0
  73. package/dist/cli/doctor/check-ghost-commands.d.ts.map +1 -0
  74. package/dist/cli/doctor/check-ghost-commands.js +86 -0
  75. package/dist/cli/doctor/check-ghost-commands.js.map +1 -0
  76. package/dist/cli/doctor/check-native-deps.d.ts +3 -0
  77. package/dist/cli/doctor/check-native-deps.d.ts.map +1 -0
  78. package/dist/cli/doctor/check-native-deps.js +70 -0
  79. package/dist/cli/doctor/check-native-deps.js.map +1 -0
  80. package/dist/cli/doctor/check-workspace-drift.d.ts +3 -0
  81. package/dist/cli/doctor/check-workspace-drift.d.ts.map +1 -0
  82. package/dist/cli/doctor/check-workspace-drift.js +83 -0
  83. package/dist/cli/doctor/check-workspace-drift.js.map +1 -0
  84. package/dist/cli/doctor/formatter.d.ts +20 -0
  85. package/dist/cli/doctor/formatter.d.ts.map +1 -0
  86. package/dist/cli/doctor/formatter.js +91 -0
  87. package/dist/cli/doctor/formatter.js.map +1 -0
  88. package/dist/cli/doctor/index.d.ts +8 -0
  89. package/dist/cli/doctor/index.d.ts.map +1 -0
  90. package/dist/cli/doctor/index.js +9 -0
  91. package/dist/cli/doctor/index.js.map +1 -0
  92. package/dist/cli/doctor/orchestrator.d.ts +3 -0
  93. package/dist/cli/doctor/orchestrator.d.ts.map +1 -0
  94. package/dist/cli/doctor/orchestrator.js +40 -0
  95. package/dist/cli/doctor/orchestrator.js.map +1 -0
  96. package/dist/cli/doctor/types.d.ts +19 -0
  97. package/dist/cli/doctor/types.d.ts.map +1 -0
  98. package/dist/cli/doctor/types.js +4 -0
  99. package/dist/cli/doctor/types.js.map +1 -0
  100. package/dist/cli/env-contract/check.d.ts +18 -0
  101. package/dist/cli/env-contract/check.d.ts.map +1 -0
  102. package/dist/cli/env-contract/check.js +118 -0
  103. package/dist/cli/env-contract/check.js.map +1 -0
  104. package/dist/cli/env-contract/discovery.d.ts +12 -0
  105. package/dist/cli/env-contract/discovery.d.ts.map +1 -0
  106. package/dist/cli/env-contract/discovery.js +249 -0
  107. package/dist/cli/env-contract/discovery.js.map +1 -0
  108. package/dist/cli/env-contract/filters.d.ts +10 -0
  109. package/dist/cli/env-contract/filters.d.ts.map +1 -0
  110. package/dist/cli/env-contract/filters.js +23 -0
  111. package/dist/cli/env-contract/filters.js.map +1 -0
  112. package/dist/cli/env-contract/index.d.ts +6 -0
  113. package/dist/cli/env-contract/index.d.ts.map +1 -0
  114. package/dist/cli/env-contract/index.js +8 -0
  115. package/dist/cli/env-contract/index.js.map +1 -0
  116. package/dist/cli/env-contract/reminder-engine.d.ts +34 -0
  117. package/dist/cli/env-contract/reminder-engine.d.ts.map +1 -0
  118. package/dist/cli/env-contract/reminder-engine.js +51 -0
  119. package/dist/cli/env-contract/reminder-engine.js.map +1 -0
  120. package/dist/cli/env-contract/reminder-hook-runner.d.ts +45 -0
  121. package/dist/cli/env-contract/reminder-hook-runner.d.ts.map +1 -0
  122. package/dist/cli/env-contract/reminder-hook-runner.js +273 -0
  123. package/dist/cli/env-contract/reminder-hook-runner.js.map +1 -0
  124. package/dist/cli/env-contract/reminder-ledger.d.ts +11 -0
  125. package/dist/cli/env-contract/reminder-ledger.d.ts.map +1 -0
  126. package/dist/cli/env-contract/reminder-ledger.js +37 -0
  127. package/dist/cli/env-contract/reminder-ledger.js.map +1 -0
  128. package/dist/cli/env-contract/types.d.ts +48 -0
  129. package/dist/cli/env-contract/types.d.ts.map +1 -0
  130. package/dist/cli/env-contract/types.js +22 -0
  131. package/dist/cli/env-contract/types.js.map +1 -0
  132. package/dist/cli/env-contract/validation.d.ts +10 -0
  133. package/dist/cli/env-contract/validation.d.ts.map +1 -0
  134. package/dist/cli/env-contract/validation.js +116 -0
  135. package/dist/cli/env-contract/validation.js.map +1 -0
  136. package/dist/cli/first-run-guide.d.ts.map +1 -1
  137. package/dist/cli/first-run-guide.js +8 -3
  138. package/dist/cli/first-run-guide.js.map +1 -1
  139. package/dist/cli/index.js +94 -22
  140. package/dist/cli/index.js.map +1 -1
  141. package/dist/cli/init/assistant-plan.d.ts +14 -0
  142. package/dist/cli/init/assistant-plan.d.ts.map +1 -0
  143. package/dist/cli/init/assistant-plan.js +208 -0
  144. package/dist/cli/init/assistant-plan.js.map +1 -0
  145. package/dist/cli/init/detect.d.ts +28 -0
  146. package/dist/cli/init/detect.d.ts.map +1 -0
  147. package/dist/cli/init/detect.js +63 -0
  148. package/dist/cli/init/detect.js.map +1 -0
  149. package/dist/cli/init/env-contract-plan.d.ts +28 -0
  150. package/dist/cli/init/env-contract-plan.d.ts.map +1 -0
  151. package/dist/cli/init/env-contract-plan.js +184 -0
  152. package/dist/cli/init/env-contract-plan.js.map +1 -0
  153. package/dist/cli/init/manifest-extractors.d.ts +22 -0
  154. package/dist/cli/init/manifest-extractors.d.ts.map +1 -0
  155. package/dist/cli/init/manifest-extractors.js +185 -0
  156. package/dist/cli/init/manifest-extractors.js.map +1 -0
  157. package/dist/cli/init/profile-loader.d.ts +49 -0
  158. package/dist/cli/init/profile-loader.d.ts.map +1 -0
  159. package/dist/cli/init/profile-loader.js +107 -0
  160. package/dist/cli/init/profile-loader.js.map +1 -0
  161. package/dist/cli/init/profile-plan.d.ts +38 -0
  162. package/dist/cli/init/profile-plan.d.ts.map +1 -0
  163. package/dist/cli/init/profile-plan.js +120 -0
  164. package/dist/cli/init/profile-plan.js.map +1 -0
  165. package/dist/cli/init/profiles/generic.json +16 -0
  166. package/dist/cli/init/profiles/go.json +12 -0
  167. package/dist/cli/init/profiles/nodejs.json +16 -0
  168. package/dist/cli/init/profiles/python.json +17 -0
  169. package/dist/cli/init/profiles/rust.json +12 -0
  170. package/dist/cli/init/receipt.d.ts.map +1 -1
  171. package/dist/cli/init/receipt.js +107 -7
  172. package/dist/cli/init/receipt.js.map +1 -1
  173. package/dist/cli/init/reconciler.d.ts +10 -1
  174. package/dist/cli/init/reconciler.d.ts.map +1 -1
  175. package/dist/cli/init/reconciler.js +85 -15
  176. package/dist/cli/init/reconciler.js.map +1 -1
  177. package/dist/cli/interface-contract/commands/agent-metrics.d.ts +3 -0
  178. package/dist/cli/interface-contract/commands/agent-metrics.d.ts.map +1 -0
  179. package/dist/cli/interface-contract/commands/agent-metrics.js +217 -0
  180. package/dist/cli/interface-contract/commands/agent-metrics.js.map +1 -0
  181. package/dist/cli/interface-contract/commands/analyze.d.ts +3 -0
  182. package/dist/cli/interface-contract/commands/analyze.d.ts.map +1 -0
  183. package/dist/cli/interface-contract/commands/analyze.js +139 -0
  184. package/dist/cli/interface-contract/commands/analyze.js.map +1 -0
  185. package/dist/cli/interface-contract/commands/benchmark.d.ts +3 -0
  186. package/dist/cli/interface-contract/commands/benchmark.d.ts.map +1 -0
  187. package/dist/cli/interface-contract/commands/benchmark.js +108 -0
  188. package/dist/cli/interface-contract/commands/benchmark.js.map +1 -0
  189. package/dist/cli/interface-contract/commands/deps.d.ts +3 -0
  190. package/dist/cli/interface-contract/commands/deps.d.ts.map +1 -0
  191. package/dist/cli/interface-contract/commands/deps.js +130 -0
  192. package/dist/cli/interface-contract/commands/deps.js.map +1 -0
  193. package/dist/cli/interface-contract/commands/doctor.d.ts +3 -0
  194. package/dist/cli/interface-contract/commands/doctor.d.ts.map +1 -0
  195. package/dist/cli/interface-contract/commands/doctor.js +60 -0
  196. package/dist/cli/interface-contract/commands/doctor.js.map +1 -0
  197. package/dist/cli/interface-contract/commands/env-contract.d.ts +3 -0
  198. package/dist/cli/interface-contract/commands/env-contract.d.ts.map +1 -0
  199. package/dist/cli/interface-contract/commands/env-contract.js +168 -0
  200. package/dist/cli/interface-contract/commands/env-contract.js.map +1 -0
  201. package/dist/cli/interface-contract/commands/index.d.ts +12 -0
  202. package/dist/cli/interface-contract/commands/index.d.ts.map +1 -0
  203. package/dist/cli/interface-contract/commands/index.js +24 -0
  204. package/dist/cli/interface-contract/commands/index.js.map +1 -0
  205. package/dist/cli/interface-contract/commands/init.d.ts +3 -0
  206. package/dist/cli/interface-contract/commands/init.d.ts.map +1 -0
  207. package/dist/cli/interface-contract/commands/init.js +96 -0
  208. package/dist/cli/interface-contract/commands/init.js.map +1 -0
  209. package/dist/cli/interface-contract/commands/preview.d.ts +3 -0
  210. package/dist/cli/interface-contract/commands/preview.d.ts.map +1 -0
  211. package/dist/cli/interface-contract/commands/preview.js +118 -0
  212. package/dist/cli/interface-contract/commands/preview.js.map +1 -0
  213. package/dist/cli/interface-contract/commands/query.d.ts +3 -0
  214. package/dist/cli/interface-contract/commands/query.d.ts.map +1 -0
  215. package/dist/cli/interface-contract/commands/query.js +186 -0
  216. package/dist/cli/interface-contract/commands/query.js.map +1 -0
  217. package/dist/cli/interface-contract/index.d.ts +22 -0
  218. package/dist/cli/interface-contract/index.d.ts.map +1 -0
  219. package/dist/cli/interface-contract/index.js +41 -0
  220. package/dist/cli/interface-contract/index.js.map +1 -0
  221. package/dist/cli/interface-contract/schema.d.ts +30 -0
  222. package/dist/cli/interface-contract/schema.d.ts.map +1 -0
  223. package/dist/cli/interface-contract/schema.js +73 -0
  224. package/dist/cli/interface-contract/schema.js.map +1 -0
  225. package/dist/cli/interface-contract/types.d.ts +77 -0
  226. package/dist/cli/interface-contract/types.d.ts.map +1 -0
  227. package/dist/cli/interface-contract/types.js +4 -0
  228. package/dist/cli/interface-contract/types.js.map +1 -0
  229. package/dist/cli/output/apply-suggestion.d.ts +12 -0
  230. package/dist/cli/output/apply-suggestion.d.ts.map +1 -0
  231. package/dist/cli/output/apply-suggestion.js +29 -0
  232. package/dist/cli/output/apply-suggestion.js.map +1 -0
  233. package/dist/cli/output/error-codes.d.ts +24 -0
  234. package/dist/cli/output/error-codes.d.ts.map +1 -0
  235. package/dist/cli/output/error-codes.js +94 -0
  236. package/dist/cli/output/error-codes.js.map +1 -0
  237. package/dist/cli/output/errors.d.ts +14 -0
  238. package/dist/cli/output/errors.d.ts.map +1 -0
  239. package/dist/cli/output/errors.js +182 -0
  240. package/dist/cli/output/errors.js.map +1 -0
  241. package/dist/cli/output/index.d.ts +13 -0
  242. package/dist/cli/output/index.d.ts.map +1 -0
  243. package/dist/cli/output/index.js +11 -0
  244. package/dist/cli/output/index.js.map +1 -0
  245. package/dist/cli/output/mode.d.ts +12 -0
  246. package/dist/cli/output/mode.d.ts.map +1 -0
  247. package/dist/cli/output/mode.js +23 -0
  248. package/dist/cli/output/mode.js.map +1 -0
  249. package/dist/cli/output/progress.d.ts +9 -0
  250. package/dist/cli/output/progress.d.ts.map +1 -0
  251. package/dist/cli/output/progress.js +65 -0
  252. package/dist/cli/output/progress.js.map +1 -0
  253. package/dist/cli/output/render.d.ts +11 -0
  254. package/dist/cli/output/render.d.ts.map +1 -0
  255. package/dist/cli/output/render.js +18 -0
  256. package/dist/cli/output/render.js.map +1 -0
  257. package/dist/cli/output/types.d.ts +53 -0
  258. package/dist/cli/output/types.d.ts.map +1 -0
  259. package/dist/cli/output/types.js +14 -0
  260. package/dist/cli/output/types.js.map +1 -0
  261. package/dist/cli/output/wasm-fallback.d.ts +14 -0
  262. package/dist/cli/output/wasm-fallback.d.ts.map +1 -0
  263. package/dist/cli/output/wasm-fallback.js +92 -0
  264. package/dist/cli/output/wasm-fallback.js.map +1 -0
  265. package/dist/cli/preview/complexity-scanner.d.ts +21 -0
  266. package/dist/cli/preview/complexity-scanner.d.ts.map +1 -0
  267. package/dist/cli/preview/complexity-scanner.js +52 -0
  268. package/dist/cli/preview/complexity-scanner.js.map +1 -0
  269. package/dist/cli/preview/dependency-extractor.d.ts +38 -0
  270. package/dist/cli/preview/dependency-extractor.d.ts.map +1 -0
  271. package/dist/cli/preview/dependency-extractor.js +140 -0
  272. package/dist/cli/preview/dependency-extractor.js.map +1 -0
  273. package/dist/cli/preview/preview-renderer.d.ts +32 -0
  274. package/dist/cli/preview/preview-renderer.d.ts.map +1 -0
  275. package/dist/cli/preview/preview-renderer.js +54 -0
  276. package/dist/cli/preview/preview-renderer.js.map +1 -0
  277. package/dist/cli/storage-runtime.d.ts +7 -0
  278. package/dist/cli/storage-runtime.d.ts.map +1 -1
  279. package/dist/cli/storage-runtime.js +22 -0
  280. package/dist/cli/storage-runtime.js.map +1 -1
  281. package/dist/cli/tree-sitter-check.d.ts +6 -1
  282. package/dist/cli/tree-sitter-check.d.ts.map +1 -1
  283. package/dist/cli/tree-sitter-check.js +23 -1
  284. package/dist/cli/tree-sitter-check.js.map +1 -1
  285. package/dist/cli-new/index.js +1 -1
  286. package/dist/cli-new/index.js.map +1 -1
  287. package/dist/composition/parser-composition.d.ts +7 -0
  288. package/dist/composition/parser-composition.d.ts.map +1 -0
  289. package/dist/composition/parser-composition.js +15 -0
  290. package/dist/composition/parser-composition.js.map +1 -0
  291. package/dist/core/analyzer.d.ts.map +1 -1
  292. package/dist/core/analyzer.js +83 -67
  293. package/dist/core/analyzer.js.map +1 -1
  294. package/dist/core/ast-complexity-analyzer.d.ts +12 -6
  295. package/dist/core/ast-complexity-analyzer.d.ts.map +1 -1
  296. package/dist/core/ast-complexity-analyzer.js +368 -209
  297. package/dist/core/ast-complexity-analyzer.js.map +1 -1
  298. package/dist/core/file-discovery.d.ts +1 -1
  299. package/dist/core/file-discovery.d.ts.map +1 -1
  300. package/dist/core/file-discovery.js +3 -0
  301. package/dist/core/file-discovery.js.map +1 -1
  302. package/dist/core/global-index.d.ts +3 -1
  303. package/dist/core/global-index.d.ts.map +1 -1
  304. package/dist/core/global-index.js +69 -4
  305. package/dist/core/global-index.js.map +1 -1
  306. package/dist/domain/entities/CodeGraph.d.ts +3 -0
  307. package/dist/domain/entities/CodeGraph.d.ts.map +1 -1
  308. package/dist/domain/entities/CodeGraph.js +19 -2
  309. package/dist/domain/entities/CodeGraph.js.map +1 -1
  310. package/dist/domain/entities/Dependency.d.ts +5 -2
  311. package/dist/domain/entities/Dependency.d.ts.map +1 -1
  312. package/dist/domain/entities/Dependency.js +49 -3
  313. package/dist/domain/entities/Dependency.js.map +1 -1
  314. package/dist/domain/repositories/CodeGraphRepository.d.ts +5 -0
  315. package/dist/domain/repositories/CodeGraphRepository.d.ts.map +1 -1
  316. package/dist/domain/repositories/CodeGraphRepository.js.map +1 -1
  317. package/dist/execution/contract-tools/analyze.d.ts +205 -0
  318. package/dist/execution/contract-tools/analyze.d.ts.map +1 -0
  319. package/dist/execution/contract-tools/analyze.js +1215 -0
  320. package/dist/execution/contract-tools/analyze.js.map +1 -0
  321. package/dist/execution/contract-tools/deps.d.ts +62 -0
  322. package/dist/execution/contract-tools/deps.d.ts.map +1 -0
  323. package/dist/execution/contract-tools/deps.js +234 -0
  324. package/dist/execution/contract-tools/deps.js.map +1 -0
  325. package/dist/execution/contract-tools/index.d.ts +5 -0
  326. package/dist/execution/contract-tools/index.d.ts.map +1 -0
  327. package/dist/execution/contract-tools/index.js +7 -0
  328. package/dist/execution/contract-tools/index.js.map +1 -0
  329. package/dist/execution/contract-tools/query.d.ts +60 -0
  330. package/dist/execution/contract-tools/query.d.ts.map +1 -0
  331. package/dist/execution/contract-tools/query.js +532 -0
  332. package/dist/execution/contract-tools/query.js.map +1 -0
  333. package/dist/execution/contract-tools/types.d.ts +26 -0
  334. package/dist/execution/contract-tools/types.d.ts.map +1 -0
  335. package/dist/execution/contract-tools/types.js +32 -0
  336. package/dist/execution/contract-tools/types.js.map +1 -0
  337. package/dist/generator/index.d.ts.map +1 -1
  338. package/dist/generator/index.js +0 -3
  339. package/dist/generator/index.js.map +1 -1
  340. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.d.ts +12 -0
  341. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.d.ts.map +1 -0
  342. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.js +55 -0
  343. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.js.map +1 -0
  344. package/dist/infrastructure/parser/implementations/GoParser.d.ts +2 -1
  345. package/dist/infrastructure/parser/implementations/GoParser.d.ts.map +1 -1
  346. package/dist/infrastructure/parser/implementations/GoParser.js +13 -1
  347. package/dist/infrastructure/parser/implementations/GoParser.js.map +1 -1
  348. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.d.ts +114 -0
  349. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.d.ts.map +1 -0
  350. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.js +1022 -0
  351. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.js.map +1 -0
  352. package/dist/infrastructure/parser/implementations/TreeSitterParser.d.ts +78 -0
  353. package/dist/infrastructure/parser/implementations/TreeSitterParser.d.ts.map +1 -0
  354. package/dist/infrastructure/parser/implementations/TreeSitterParser.js +648 -0
  355. package/dist/infrastructure/parser/implementations/TreeSitterParser.js.map +1 -0
  356. package/dist/infrastructure/parser/implementations/TypeScriptParser.d.ts +3 -55
  357. package/dist/infrastructure/parser/implementations/TypeScriptParser.d.ts.map +1 -1
  358. package/dist/infrastructure/parser/implementations/TypeScriptParser.js +4 -411
  359. package/dist/infrastructure/parser/implementations/TypeScriptParser.js.map +1 -1
  360. package/dist/infrastructure/parser/index.d.ts +2 -0
  361. package/dist/infrastructure/parser/index.d.ts.map +1 -1
  362. package/dist/infrastructure/parser/index.js +9 -6
  363. package/dist/infrastructure/parser/index.js.map +1 -1
  364. package/dist/infrastructure/parser/interfaces/ParserBase.d.ts.map +1 -1
  365. package/dist/infrastructure/parser/interfaces/ParserBase.js +1 -0
  366. package/dist/infrastructure/parser/interfaces/ParserBase.js.map +1 -1
  367. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.d.ts +2 -0
  368. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.d.ts.map +1 -1
  369. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.js +4 -0
  370. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.js.map +1 -1
  371. package/dist/infrastructure/storage/StorageFactory.d.ts +5 -18
  372. package/dist/infrastructure/storage/StorageFactory.d.ts.map +1 -1
  373. package/dist/infrastructure/storage/StorageFactory.js +30 -98
  374. package/dist/infrastructure/storage/StorageFactory.js.map +1 -1
  375. package/dist/infrastructure/storage/adapters/SQLiteStorage.d.ts +13 -1
  376. package/dist/infrastructure/storage/adapters/SQLiteStorage.d.ts.map +1 -1
  377. package/dist/infrastructure/storage/adapters/SQLiteStorage.js +322 -76
  378. package/dist/infrastructure/storage/adapters/SQLiteStorage.js.map +1 -1
  379. package/dist/infrastructure/storage/adapters/sqlite-loader.d.ts +45 -0
  380. package/dist/infrastructure/storage/adapters/sqlite-loader.d.ts.map +1 -0
  381. package/dist/infrastructure/storage/adapters/sqlite-loader.js +266 -0
  382. package/dist/infrastructure/storage/adapters/sqlite-loader.js.map +1 -0
  383. package/dist/infrastructure/storage/community-helpers.d.ts +4 -0
  384. package/dist/infrastructure/storage/community-helpers.d.ts.map +1 -0
  385. package/dist/infrastructure/storage/community-helpers.js +392 -0
  386. package/dist/infrastructure/storage/community-helpers.js.map +1 -0
  387. package/dist/infrastructure/storage/graph-helpers.d.ts +22 -5
  388. package/dist/infrastructure/storage/graph-helpers.d.ts.map +1 -1
  389. package/dist/infrastructure/storage/graph-helpers.js +496 -91
  390. package/dist/infrastructure/storage/graph-helpers.js.map +1 -1
  391. package/dist/infrastructure/storage/index.d.ts +1 -1
  392. package/dist/infrastructure/storage/index.d.ts.map +1 -1
  393. package/dist/infrastructure/storage/index.js +1 -1
  394. package/dist/infrastructure/storage/index.js.map +1 -1
  395. package/dist/infrastructure/storage/interfaces/StorageBase.d.ts +2 -2
  396. package/dist/infrastructure/storage/interfaces/StorageBase.d.ts.map +1 -1
  397. package/dist/infrastructure/storage/interfaces/StorageBase.js.map +1 -1
  398. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.d.ts +2 -0
  399. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.d.ts.map +1 -1
  400. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.js +52 -12
  401. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.js.map +1 -1
  402. package/dist/infrastructure/storage/sqlite/schema.d.ts +2 -2
  403. package/dist/infrastructure/storage/sqlite/schema.d.ts.map +1 -1
  404. package/dist/infrastructure/storage/sqlite/schema.js +49 -1
  405. package/dist/infrastructure/storage/sqlite/schema.js.map +1 -1
  406. package/dist/interface/config/index.d.ts +5 -3
  407. package/dist/interface/config/index.d.ts.map +1 -1
  408. package/dist/interface/types/index.d.ts +37 -6
  409. package/dist/interface/types/index.d.ts.map +1 -1
  410. package/dist/interface/types/parser.d.ts +85 -0
  411. package/dist/interface/types/parser.d.ts.map +1 -1
  412. package/dist/interface/types/storage.d.ts +227 -10
  413. package/dist/interface/types/storage.d.ts.map +1 -1
  414. package/dist/orchestrator/agent-metrics-service.d.ts +126 -0
  415. package/dist/orchestrator/agent-metrics-service.d.ts.map +1 -0
  416. package/dist/orchestrator/agent-metrics-service.js +444 -0
  417. package/dist/orchestrator/agent-metrics-service.js.map +1 -0
  418. package/dist/orchestrator/types.d.ts +2 -0
  419. package/dist/orchestrator/types.d.ts.map +1 -1
  420. package/dist/orchestrator/types.js.map +1 -1
  421. package/dist/parser/enhancers/PythonTypeEnhancer.d.ts +26 -0
  422. package/dist/parser/enhancers/PythonTypeEnhancer.d.ts.map +1 -0
  423. package/dist/parser/enhancers/PythonTypeEnhancer.js +440 -0
  424. package/dist/parser/enhancers/PythonTypeEnhancer.js.map +1 -0
  425. package/dist/parser/implementations/smart-parser.d.ts.map +1 -1
  426. package/dist/parser/implementations/smart-parser.js +7 -69
  427. package/dist/parser/implementations/smart-parser.js.map +1 -1
  428. package/dist/parser/implementations/tree-sitter-loader.d.ts +18 -0
  429. package/dist/parser/implementations/tree-sitter-loader.d.ts.map +1 -0
  430. package/dist/parser/implementations/tree-sitter-loader.js +136 -0
  431. package/dist/parser/implementations/tree-sitter-loader.js.map +1 -0
  432. package/dist/parser/index.d.ts +5 -3
  433. package/dist/parser/index.d.ts.map +1 -1
  434. package/dist/parser/index.js +68 -6
  435. package/dist/parser/index.js.map +1 -1
  436. package/dist/parser/interfaces/IParser.d.ts +19 -6
  437. package/dist/parser/interfaces/IParser.d.ts.map +1 -1
  438. package/dist/parser/interfaces/IParser.js +2 -3
  439. package/dist/parser/interfaces/IParser.js.map +1 -1
  440. package/dist/server/handlers/AnalysisHandler.d.ts +13 -2
  441. package/dist/server/handlers/AnalysisHandler.d.ts.map +1 -1
  442. package/dist/server/handlers/AnalysisHandler.js +24 -0
  443. package/dist/server/handlers/AnalysisHandler.js.map +1 -1
  444. package/dist/server/handlers/QueryHandler.d.ts.map +1 -1
  445. package/dist/server/handlers/QueryHandler.js +11 -30
  446. package/dist/server/handlers/QueryHandler.js.map +1 -1
  447. package/dist/server/mcp/context-tool.d.ts +9 -0
  448. package/dist/server/mcp/context-tool.d.ts.map +1 -0
  449. package/dist/server/mcp/context-tool.js +257 -0
  450. package/dist/server/mcp/context-tool.js.map +1 -0
  451. package/dist/server/mcp/schema-adapter.d.ts +55 -0
  452. package/dist/server/mcp/schema-adapter.d.ts.map +1 -0
  453. package/dist/server/mcp/schema-adapter.js +409 -0
  454. package/dist/server/mcp/schema-adapter.js.map +1 -0
  455. package/dist/server/mcp/server.d.ts +3 -3
  456. package/dist/server/mcp/server.d.ts.map +1 -1
  457. package/dist/server/mcp/server.js +134 -20
  458. package/dist/server/mcp/server.js.map +1 -1
  459. package/dist/server/mcp/service.d.ts +6 -2
  460. package/dist/server/mcp/service.d.ts.map +1 -1
  461. package/dist/server/mcp/service.js +138 -36
  462. package/dist/server/mcp/service.js.map +1 -1
  463. package/dist/server/mcp/stdio-transport.d.ts +23 -0
  464. package/dist/server/mcp/stdio-transport.d.ts.map +1 -0
  465. package/dist/server/mcp/stdio-transport.js +101 -0
  466. package/dist/server/mcp/stdio-transport.js.map +1 -0
  467. package/dist/server/mcp/types.d.ts +133 -8
  468. package/dist/server/mcp/types.d.ts.map +1 -1
  469. package/dist/server/routes/api.d.ts.map +1 -1
  470. package/dist/server/routes/api.js +11 -2
  471. package/dist/server/routes/api.js.map +1 -1
  472. package/docs/AI_ASSISTANT_SETUP.md +281 -12
  473. package/docs/API.md +170 -0
  474. package/docs/CONFIGURATION.md +141 -0
  475. package/docs/DEVELOPMENT.md +96 -0
  476. package/docs/GETTING-STARTED.md +114 -0
  477. package/docs/README.md +40 -1
  478. package/docs/SETUP_GUIDE.md +60 -14
  479. package/docs/TESTING.md +81 -0
  480. package/docs/ai-guide/COMMANDS.md +68 -10
  481. package/docs/ai-guide/INTEGRATION.md +77 -10
  482. package/docs/ai-guide/OUTPUT.md +345 -9
  483. package/docs/ai-guide/PROMPTS.md +2 -2
  484. package/docs/ai-guide/QUICKSTART.md +28 -1
  485. package/docs/ai-guide/README.md +2 -2
  486. package/docs/archive/ideation/2026-04-15-executable-architecture-constitution-ideation-archive.md +70 -0
  487. package/docs/archive/ideation/2026-04-20-mycodemap-init-enhancements-ideation-archive.md +109 -0
  488. package/docs/archive/ideation/2026-04-22-rules-entry-docs-optimization-consolidated-ideation-archive.md +54 -0
  489. package/docs/backlog.md +232 -144
  490. package/docs/brainstorms/2026-05-10-agent-effectiveness-validation-requirements.md +112 -0
  491. package/docs/generated/phase-58/subagent-evidence/claude-hook-example.json +15 -0
  492. package/docs/generated/phase-58/subagent-evidence/claude-session.md +146 -0
  493. package/docs/generated/phase-58/subagent-evidence/claude-subagent.json +28 -0
  494. package/docs/generated/phase-58/subagent-evidence/codex-agent-example.toml +19 -0
  495. package/docs/generated/phase-58/subagent-evidence/codex-session.md +150 -0
  496. package/docs/generated/phase-58/subagent-evidence/codex-subagent.json +20 -0
  497. package/docs/generated/phase-58/subagent-evidence/negative-no-retrieval.json +12 -0
  498. package/docs/generated/phase-58/subagent-evidence/verification-manifest.json +19 -0
  499. package/docs/ideation/2026-04-15-executable-architecture-constitution-ideation.md +10 -22
  500. package/docs/ideation/2026-04-20-mycodemap-init-enhancements-ideation.md +15 -60
  501. package/docs/ideation/2026-04-22-rules-entry-docs-optimization-consolidated-ideation.md +47 -52
  502. package/docs/ideation/2026-04-29-ux-install-agent-experience-ideation.md +256 -0
  503. package/docs/ideation/2026-05-02-subagent-environment-contract-injection-ideation.md +183 -0
  504. package/docs/ideation/2026-05-04-subagent-hooks-deep-dive-ideation.md +133 -0
  505. package/docs/ideation/2026-05-10-agent-effectiveness-validation-ideation.md +219 -0
  506. package/docs/plans/2026-04-30-install-guide-and-repo-analyzer-design.md +394 -0
  507. package/docs/rules/README.md +1 -0
  508. package/docs/rules/architecture-guardrails.md +2 -1
  509. package/docs/rules/engineering-with-codex-openai.md +1 -1
  510. package/docs/rules/harness.md +106 -0
  511. package/docs/rules/pre-release-checklist.md +28 -0
  512. package/docs/rules/testing.md +51 -0
  513. package/examples/claude/skills/mycodemap-repo-analyzer/SKILL.md +294 -0
  514. package/examples/claude/skills/mycodemap-repo-analyzer/references/analysis-guide.md +166 -0
  515. package/examples/claude/skills/mycodemap-repo-analyzer/references/module-analysis-guide.md +150 -0
  516. package/package.json +12 -4
  517. package/scripts/copy-build-assets.mjs +23 -0
  518. package/scripts/hooks/templates/pre-commit +33 -2
  519. package/scripts/sync-analyze-docs.js +2 -2
  520. package/scripts/tests/test_rule_control_workflow.py +15 -1
  521. package/scripts/validate-docs.js +113 -16
  522. package/scripts/verify-subagent-env-contract.mjs +279 -0
  523. package/dist/parser/implementations/tree-sitter-parser.d.ts +0 -57
  524. package/dist/parser/implementations/tree-sitter-parser.d.ts.map +0 -1
  525. package/dist/parser/implementations/tree-sitter-parser.js +0 -375
  526. package/dist/parser/implementations/tree-sitter-parser.js.map +0 -1
  527. package/docs/references/tmp.md +0 -527
@@ -0,0 +1,1215 @@
1
+ /**
2
+ * [META] AnalyzeCommand - 统一分析入口
3
+ * [WHY] 为 CI 与人工调用提供统一分析输出,支持 machine/json 契约
4
+ */
5
+ import { readFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { parseArgs } from 'node:util';
8
+ import chalk from 'chalk';
9
+ import { ImpactCommand } from '../../cli/commands/impact.js';
10
+ import { DepsCommand } from '../../cli/commands/deps.js';
11
+ import { ComplexityCommand } from '../../cli/commands/complexity.js';
12
+ import { ANALYZE_PARSE_OPTIONS } from '../../cli/commands/analyze-options.js';
13
+ import { PUBLIC_INTENTS, calculateConfidenceLevel } from '../../orchestrator/types.js';
14
+ import { resolveTestFile } from '../../orchestrator/test-linker.js';
15
+ import { ToolOrchestrator } from '../../orchestrator/tool-orchestrator.js';
16
+ import { ResultFusion } from '../../orchestrator/result-fusion.js';
17
+ import { CodemapAdapter } from '../../orchestrator/adapters/codemap-adapter.js';
18
+ import { AstGrepAdapter } from '../../orchestrator/adapters/ast-grep-adapter.js';
19
+ import { IntentRouter } from '../../orchestrator/intent-router.js';
20
+ import { resolveDataPath, resolveOutputDir } from '../../cli/paths.js';
21
+ import { discoverProjectFiles } from '../../core/file-discovery.js';
22
+ import { loadCodemapConfig } from '../../cli/config-loader.js';
23
+ import { createContractError, createContractSuccess, normalizeExecutionError, } from './types.js';
24
+ /**
25
+ * 错误码定义
26
+ */
27
+ export var AnalyzeErrorCode;
28
+ (function (AnalyzeErrorCode) {
29
+ /** E0001: 无效 intent 值 */
30
+ AnalyzeErrorCode["E0001_INVALID_INTENT"] = "E0001";
31
+ /** E0002: 缺少必要参数 */
32
+ AnalyzeErrorCode["E0002_MISSING_REQUIRED_PARAM"] = "E0002";
33
+ /** E0003: 目标路径不存在 */
34
+ AnalyzeErrorCode["E0003_TARGET_NOT_FOUND"] = "E0003";
35
+ /** E0004: 工具执行超时 */
36
+ AnalyzeErrorCode["E0004_EXECUTION_TIMEOUT"] = "E0004";
37
+ /** E0005: 工具执行失败 */
38
+ AnalyzeErrorCode["E0005_EXECUTION_FAILED"] = "E0005";
39
+ /** E0006: 置信度过低 */
40
+ AnalyzeErrorCode["E0006_LOW_CONFIDENCE"] = "E0006";
41
+ })(AnalyzeErrorCode || (AnalyzeErrorCode = {}));
42
+ /**
43
+ * 错误信息映射
44
+ */
45
+ export const ERROR_MESSAGES = {
46
+ [AnalyzeErrorCode.E0001_INVALID_INTENT]: '无效的 intent 参数值',
47
+ [AnalyzeErrorCode.E0002_MISSING_REQUIRED_PARAM]: '缺少必要参数',
48
+ [AnalyzeErrorCode.E0003_TARGET_NOT_FOUND]: '目标路径不存在',
49
+ [AnalyzeErrorCode.E0004_EXECUTION_TIMEOUT]: '工具执行超时',
50
+ [AnalyzeErrorCode.E0005_EXECUTION_FAILED]: '工具执行失败',
51
+ [AnalyzeErrorCode.E0006_LOW_CONFIDENCE]: '置信度过低',
52
+ };
53
+ /**
54
+ * 支持的 intent 列表
55
+ */
56
+ export const VALID_INTENTS = [
57
+ ...PUBLIC_INTENTS,
58
+ ];
59
+ /**
60
+ * AnalyzeCommand 分析命令类
61
+ */
62
+ export class AnalyzeCommand {
63
+ args;
64
+ /**
65
+ * 构造函数
66
+ * @param args 分析命令参数
67
+ */
68
+ constructor(args) {
69
+ this.args = args;
70
+ }
71
+ /**
72
+ * 验证参数
73
+ * @throws AnalyzeError 当参数无效时
74
+ */
75
+ validate() {
76
+ if (!this.args.intent) {
77
+ throw this.createError(AnalyzeErrorCode.E0002_MISSING_REQUIRED_PARAM, '缺少必要参数: intent');
78
+ }
79
+ const intentRouter = new IntentRouter();
80
+ // 验证 intent
81
+ if (!intentRouter.isValidIntent(this.args.intent)) {
82
+ throw this.createError(AnalyzeErrorCode.E0001_INVALID_INTENT, `无效的 intent: ${this.args.intent}。支持的选项: ${VALID_INTENTS.join(', ')}`);
83
+ }
84
+ const routedIntent = intentRouter.route(this.args);
85
+ const normalizedIntent = routedIntent.intent;
86
+ const hasTargets = Boolean(this.args.targets && this.args.targets.length > 0);
87
+ const hasKeywords = Boolean(this.args.keywords && this.args.keywords.length > 0);
88
+ if (normalizedIntent === 'find') {
89
+ if (!hasTargets && !hasKeywords) {
90
+ throw this.createError(AnalyzeErrorCode.E0002_MISSING_REQUIRED_PARAM, '缺少必要参数: targets 或 keywords');
91
+ }
92
+ return;
93
+ }
94
+ if (normalizedIntent === 'link' &&
95
+ routedIntent.compatibility?.normalizedFrom === 'reference' &&
96
+ hasKeywords) {
97
+ return;
98
+ }
99
+ if (!hasTargets) {
100
+ throw this.createError(AnalyzeErrorCode.E0002_MISSING_REQUIRED_PARAM, '缺少必要参数: targets');
101
+ }
102
+ }
103
+ /**
104
+ * 创建错误对象
105
+ */
106
+ createError(code, message) {
107
+ const error = new Error(`[${code}] ${message}`);
108
+ error.code = code;
109
+ return error;
110
+ }
111
+ /**
112
+ * 执行分析
113
+ */
114
+ async execute() {
115
+ this.validate();
116
+ const intentRouter = new IntentRouter();
117
+ const intentObj = intentRouter.route(this.args);
118
+ const scope = intentObj.scope;
119
+ const topK = this.args.topK || 8;
120
+ switch (intentObj.intent) {
121
+ case 'read':
122
+ return this.executeRead(intentObj, scope, topK);
123
+ case 'link':
124
+ return this.executeLink(intentObj, topK);
125
+ case 'show':
126
+ return this.executeShow(intentObj, topK);
127
+ case 'find':
128
+ return this.executeFindWithFallback(intentObj, topK);
129
+ default:
130
+ throw this.createError(AnalyzeErrorCode.E0001_INVALID_INTENT, `无效的 intent: ${intentObj.intent}`);
131
+ }
132
+ }
133
+ /**
134
+ * `find` 优先走 orchestrator,失败时回退到 AstGrep 搜索
135
+ */
136
+ async executeFindWithFallback(intentObj, topK) {
137
+ try {
138
+ const orchestratedOutput = await this.executeWithOrchestrator(intentObj, topK);
139
+ if (orchestratedOutput.results.length > 0) {
140
+ return this.withCompatibility(this.withDiagnostics(orchestratedOutput, this.createSuccessDiagnostics()), intentObj.compatibility);
141
+ }
142
+ try {
143
+ await this.executeFind(intentObj, topK, { failOnScanError: true });
144
+ }
145
+ catch (scanError) {
146
+ return this.withCompatibility(await this.executeConfigAwareTextFallback(intentObj, topK, scanError, undefined), intentObj.compatibility);
147
+ }
148
+ return this.withCompatibility(this.withDiagnostics(orchestratedOutput, this.createSuccessDiagnostics()), intentObj.compatibility);
149
+ }
150
+ catch (orchestratorError) {
151
+ console.warn('[Analyze] Orchestrator not available, falling back to AstGrep search');
152
+ try {
153
+ return await this.executeFind(intentObj, topK, { failOnScanError: true });
154
+ }
155
+ catch (scanError) {
156
+ return this.withCompatibility(await this.executeConfigAwareTextFallback(intentObj, topK, scanError, orchestratorError), intentObj.compatibility);
157
+ }
158
+ }
159
+ }
160
+ /**
161
+ * 使用编排器执行分析
162
+ */
163
+ async executeWithOrchestrator(intentObj, topK) {
164
+ const orchestrator = new ToolOrchestrator();
165
+ // 注册适配器
166
+ const codemapAdapter = new CodemapAdapter({ codemapPath: resolveOutputDir().outputDir });
167
+ const astGrepAdapter = new AstGrepAdapter({ includeTests: this.args.includeTests ?? true });
168
+ orchestrator.registerAdapter(codemapAdapter);
169
+ orchestrator.registerAdapter(astGrepAdapter);
170
+ const fusion = new ResultFusion();
171
+ const effectiveIntent = intentObj.executionIntent ?? intentObj.intent;
172
+ let orchestratedResults = [];
173
+ let confidence;
174
+ if (intentObj.secondary) {
175
+ const tools = Array.from(new Set([intentObj.tool, intentObj.secondary]));
176
+ const resultsByTool = await orchestrator.executeParallel(intentObj, tools);
177
+ orchestratedResults = fusion.fuse(resultsByTool, {
178
+ topK,
179
+ intent: effectiveIntent,
180
+ keywordWeights: {},
181
+ maxTokens: 160,
182
+ });
183
+ const confidenceScore = this.calculateConfidence(orchestratedResults);
184
+ confidence = {
185
+ score: confidenceScore,
186
+ level: confidenceScore >= 0.7 ? 'high' : confidenceScore >= 0.4 ? 'medium' : 'low',
187
+ };
188
+ }
189
+ else {
190
+ const result = await orchestrator.executeWithFallback(intentObj, intentObj.tool);
191
+ orchestratedResults = result.results.slice(0, topK);
192
+ confidence = {
193
+ score: result.confidence?.score || 0,
194
+ level: result.confidence?.level || 'low',
195
+ };
196
+ }
197
+ // 为结果添加 location 字段
198
+ const resultsWithLocation = this.enrichWithLocation(orchestratedResults);
199
+ return {
200
+ schemaVersion: 'v1.0.0',
201
+ intent: intentObj.intent,
202
+ tool: 'codemap-orchestrated',
203
+ confidence,
204
+ results: resultsWithLocation,
205
+ metadata: {
206
+ total: orchestratedResults.length,
207
+ scope: intentObj.scope,
208
+ resultCount: orchestratedResults.length,
209
+ },
210
+ };
211
+ }
212
+ /**
213
+ * 为输出添加兼容期 warning
214
+ */
215
+ withCompatibility(output, compatibility) {
216
+ const warnings = this.buildCompatibilityWarnings(compatibility);
217
+ if (warnings.length === 0) {
218
+ return output;
219
+ }
220
+ return {
221
+ ...output,
222
+ warnings
223
+ };
224
+ }
225
+ /**
226
+ * 生成结构化兼容 warning
227
+ */
228
+ buildCompatibilityWarnings(compatibility) {
229
+ if (!compatibility?.isDeprecated || !compatibility.normalizedFrom) {
230
+ return [];
231
+ }
232
+ const replacementIntent = compatibility.normalizedFrom === 'search'
233
+ ? 'find'
234
+ : compatibility.normalizedFrom === 'impact' || compatibility.normalizedFrom === 'complexity'
235
+ ? 'read'
236
+ : compatibility.normalizedFrom === 'dependency' || compatibility.normalizedFrom === 'reference'
237
+ ? 'link'
238
+ : 'show';
239
+ return [{
240
+ code: 'deprecated-intent',
241
+ severity: 'warning',
242
+ message: `legacy intent "${compatibility.normalizedFrom}" 已弃用,请改用 "${replacementIntent}"`,
243
+ deprecatedIntent: compatibility.normalizedFrom,
244
+ replacementIntent,
245
+ sunsetPolicy: '2-minor-window'
246
+ }];
247
+ }
248
+ /**
249
+ * find fallback
250
+ */
251
+ async executeFind(intentObj, topK, options = {}) {
252
+ const searchTerms = intentObj.keywords.length > 0 ? intentObj.keywords : intentObj.targets;
253
+ const adapter = new AstGrepAdapter({
254
+ includeTests: this.args.includeTests ?? true,
255
+ failOnScanError: options.failOnScanError ?? false
256
+ });
257
+ const rawResults = await adapter.execute(searchTerms, {
258
+ topK,
259
+ includeTests: this.args.includeTests,
260
+ keywords: searchTerms
261
+ });
262
+ const results = this.enrichWithLocation(rawResults).slice(0, topK);
263
+ const confidence = this.buildConfidence(this.calculateConfidence(results));
264
+ return this.withCompatibility({
265
+ schemaVersion: 'v1.0.0',
266
+ intent: 'find',
267
+ tool: 'ast-grep-find',
268
+ confidence,
269
+ results,
270
+ diagnostics: this.createSuccessDiagnostics(),
271
+ metadata: {
272
+ total: results.length,
273
+ resultCount: results.length,
274
+ scope: intentObj.scope
275
+ }
276
+ }, intentObj.compatibility);
277
+ }
278
+ async executeConfigAwareTextFallback(intentObj, topK, scanError, orchestratorError) {
279
+ try {
280
+ const results = await this.runConfigAwareTextFallback(intentObj, topK);
281
+ const diagnostics = this.createPartialFailureDiagnostics(scanError, orchestratorError);
282
+ return {
283
+ schemaVersion: 'v1.0.0',
284
+ intent: 'find',
285
+ tool: 'codemap-find-fallback',
286
+ confidence: this.buildConfidence(results.length > 0 ? 0.65 : 0),
287
+ results,
288
+ diagnostics,
289
+ metadata: {
290
+ total: results.length,
291
+ resultCount: results.length,
292
+ scope: intentObj.scope
293
+ }
294
+ };
295
+ }
296
+ catch (fallbackError) {
297
+ if (this.isMachineOutputMode()) {
298
+ process.exitCode = 1;
299
+ }
300
+ return {
301
+ schemaVersion: 'v1.0.0',
302
+ intent: 'find',
303
+ tool: 'codemap-find-fallback',
304
+ confidence: this.buildConfidence(0),
305
+ results: [],
306
+ diagnostics: this.createFailureDiagnostics(scanError, fallbackError, orchestratorError),
307
+ metadata: {
308
+ total: 0,
309
+ resultCount: 0,
310
+ scope: intentObj.scope
311
+ }
312
+ };
313
+ }
314
+ }
315
+ async runConfigAwareTextFallback(intentObj, topK) {
316
+ const { config } = await loadCodemapConfig(process.cwd());
317
+ const discoveredFiles = await discoverProjectFiles({
318
+ rootDir: process.cwd(),
319
+ include: config.include,
320
+ exclude: config.exclude,
321
+ absolute: true,
322
+ gitignore: true
323
+ });
324
+ const { files, searchTerms, explicitPathMode } = this.resolveFallbackSearchScope(discoveredFiles, intentObj);
325
+ const results = [];
326
+ for (const file of files) {
327
+ const fileResults = await this.searchFileWithFallback(file, searchTerms, topK - results.length);
328
+ results.push(...fileResults);
329
+ if (results.length >= topK) {
330
+ return results.slice(0, topK);
331
+ }
332
+ }
333
+ if (explicitPathMode && intentObj.keywords.length === 0 && results.length === 0) {
334
+ const anchoredResults = await this.createExplicitPathFallbackResults(files, searchTerms, topK);
335
+ results.push(...anchoredResults);
336
+ }
337
+ return results.slice(0, topK);
338
+ }
339
+ resolveFallbackSearchScope(discoveredFiles, intentObj) {
340
+ const explicitPathTargets = intentObj.targets.filter(target => this.isPathLikeTarget(target));
341
+ const matchedTargetFiles = this.matchDiscoveredTargetFiles(discoveredFiles, explicitPathTargets);
342
+ if (matchedTargetFiles.length > 0) {
343
+ const pathTerms = explicitPathTargets.flatMap(target => {
344
+ const basename = path.basename(target);
345
+ return [basename, this.stripModuleExtension(basename)];
346
+ });
347
+ return {
348
+ files: matchedTargetFiles,
349
+ searchTerms: this.uniqueNonEmptyStrings(intentObj.keywords.length > 0 ? intentObj.keywords : pathTerms),
350
+ explicitPathMode: true
351
+ };
352
+ }
353
+ return {
354
+ files: discoveredFiles,
355
+ searchTerms: this.uniqueNonEmptyStrings(intentObj.keywords.length > 0 ? intentObj.keywords : intentObj.targets),
356
+ explicitPathMode: false
357
+ };
358
+ }
359
+ async searchFileWithFallback(file, searchTerms, remainingSlots) {
360
+ if (remainingSlots <= 0 || searchTerms.length === 0) {
361
+ return [];
362
+ }
363
+ const content = await readFile(file, 'utf-8');
364
+ const lines = content.split(/\r?\n/);
365
+ const results = [];
366
+ for (const [index, line] of lines.entries()) {
367
+ const matchedTerms = searchTerms.filter(term => line.includes(term));
368
+ if (matchedTerms.length === 0) {
369
+ continue;
370
+ }
371
+ const relativeFile = this.toProjectRelativePath(file);
372
+ const lineNumber = index + 1;
373
+ results.push(this.createFallbackResult(relativeFile, lineNumber, line, matchedTerms));
374
+ if (results.length >= remainingSlots) {
375
+ break;
376
+ }
377
+ }
378
+ return results;
379
+ }
380
+ async createExplicitPathFallbackResults(files, searchTerms, topK) {
381
+ const results = [];
382
+ for (const file of files) {
383
+ const content = await readFile(file, 'utf-8');
384
+ const firstLine = content.split(/\r?\n/, 1)[0] ?? '';
385
+ const relativeFile = this.toProjectRelativePath(file);
386
+ results.push(this.createFallbackResult(relativeFile, 1, firstLine || `Matched file path ${relativeFile}`, searchTerms));
387
+ if (results.length >= topK) {
388
+ break;
389
+ }
390
+ }
391
+ return results;
392
+ }
393
+ createFallbackResult(relativeFile, lineNumber, content, keywords) {
394
+ return {
395
+ id: `codemap-fallback:${relativeFile}:${lineNumber}`,
396
+ source: 'codemap-fallback',
397
+ toolScore: 0.65,
398
+ type: 'code',
399
+ file: relativeFile,
400
+ line: lineNumber,
401
+ location: {
402
+ file: relativeFile,
403
+ line: lineNumber,
404
+ column: 1
405
+ },
406
+ content: content.substring(0, 200),
407
+ relevance: 0.65,
408
+ keywords,
409
+ metadata: {
410
+ stability: true,
411
+ riskLevel: 'low'
412
+ }
413
+ };
414
+ }
415
+ matchDiscoveredTargetFiles(discoveredFiles, targets) {
416
+ const normalizedTargets = new Set(targets.flatMap(target => {
417
+ const absoluteTarget = path.resolve(process.cwd(), target);
418
+ return [
419
+ this.toPosixPath(absoluteTarget),
420
+ this.toPosixPath(path.relative(process.cwd(), absoluteTarget)),
421
+ this.toPosixPath(target)
422
+ ];
423
+ }));
424
+ return discoveredFiles.filter(file => {
425
+ const absoluteFile = path.resolve(file);
426
+ const relativeFile = path.relative(process.cwd(), absoluteFile);
427
+ return normalizedTargets.has(this.toPosixPath(absoluteFile))
428
+ || normalizedTargets.has(this.toPosixPath(relativeFile));
429
+ });
430
+ }
431
+ isPathLikeTarget(target) {
432
+ return target.includes('/') || target.includes('\\') || /\.[cm]?[jt]sx?$/i.test(target);
433
+ }
434
+ uniqueNonEmptyStrings(values) {
435
+ return Array.from(new Set(values.map(value => value.trim()).filter(Boolean)));
436
+ }
437
+ toProjectRelativePath(file) {
438
+ return this.toPosixPath(path.relative(process.cwd(), path.resolve(file)));
439
+ }
440
+ toPosixPath(filePath) {
441
+ return filePath.replace(/\\/g, '/');
442
+ }
443
+ withDiagnostics(output, diagnostics) {
444
+ return {
445
+ ...output,
446
+ diagnostics
447
+ };
448
+ }
449
+ createSuccessDiagnostics() {
450
+ return {
451
+ status: 'success',
452
+ items: []
453
+ };
454
+ }
455
+ createPartialFailureDiagnostics(scanError, orchestratorError) {
456
+ return {
457
+ status: 'partialFailure',
458
+ items: [
459
+ this.createDiagnostic('find-scanner-degraded', 'warning', `find 主扫描退化,已使用配置感知文本 fallback: ${this.errorMessage(scanError)}`, 'ast-grep', true, { orchestratorError: this.errorMessage(orchestratorError) })
460
+ ],
461
+ degradedTools: ['ast-grep']
462
+ };
463
+ }
464
+ createFailureDiagnostics(scanError, fallbackError, orchestratorError) {
465
+ return {
466
+ status: 'failure',
467
+ items: [
468
+ this.createDiagnostic('find-scanner-failed', 'error', `find 主扫描失败: ${this.errorMessage(scanError)}`, 'ast-grep', false, { orchestratorError: this.errorMessage(orchestratorError) }),
469
+ this.createDiagnostic('find-fallback-failed', 'error', `配置感知文本 fallback 失败: ${this.errorMessage(fallbackError)}`, 'codemap-find-fallback', false)
470
+ ],
471
+ failedTools: ['ast-grep', 'codemap-find-fallback']
472
+ };
473
+ }
474
+ createDiagnostic(code, severity, message, source, recoverable, details) {
475
+ return {
476
+ code,
477
+ severity,
478
+ message,
479
+ source,
480
+ recoverable,
481
+ ...(details ? { details } : {})
482
+ };
483
+ }
484
+ errorMessage(error) {
485
+ return error instanceof Error ? error.message : String(error);
486
+ }
487
+ isMachineOutputMode() {
488
+ return this.args.json === true || this.args.structured === true || this.args.outputMode === 'machine';
489
+ }
490
+ /**
491
+ * 执行 read 聚合
492
+ */
493
+ async executeRead(intentObj, scope, topK) {
494
+ const [impactOutput, complexityOutput] = await Promise.all([
495
+ this.executeImpact(scope, topK),
496
+ this.executeComplexity(topK)
497
+ ]);
498
+ const mergedResults = this.mergeUnifiedResults(impactOutput.results, complexityOutput.results);
499
+ const results = mergedResults.slice(0, topK);
500
+ const analysis = {
501
+ intent: 'read',
502
+ impact: impactOutput.results
503
+ .filter(result => result.content.startsWith('被 '))
504
+ .map(result => ({
505
+ file: result.file,
506
+ location: result.location,
507
+ changedFiles: [result.file],
508
+ transitiveDependencies: result.metadata?.dependencies ?? [],
509
+ impactCount: result.metadata?.impactCount ?? 0,
510
+ risk: result.metadata?.riskLevel ?? 'low'
511
+ })),
512
+ complexity: complexityOutput.results
513
+ .filter(result => Boolean(result.metadata?.complexityMetrics))
514
+ .map(result => ({
515
+ file: result.file,
516
+ location: result.location,
517
+ metrics: result.metadata?.complexityMetrics ?? {
518
+ cyclomatic: 0,
519
+ cognitive: 0,
520
+ maintainability: 0
521
+ },
522
+ risk: result.metadata?.riskLevel ?? 'low'
523
+ }))
524
+ };
525
+ return this.withCompatibility({
526
+ schemaVersion: 'v1.0.0',
527
+ intent: 'read',
528
+ tool: 'codemap-read',
529
+ confidence: this.combineConfidence([impactOutput.confidence, complexityOutput.confidence], results),
530
+ results,
531
+ analysis,
532
+ metadata: {
533
+ total: mergedResults.length,
534
+ resultCount: results.length,
535
+ scope
536
+ }
537
+ }, intentObj.compatibility);
538
+ }
539
+ /**
540
+ * 执行 link 聚合
541
+ */
542
+ async executeLink(intentObj, topK) {
543
+ const dependencyOutput = intentObj.targets.length > 0
544
+ ? await this.executeDeps(Math.max(topK, intentObj.targets.length))
545
+ : this.createEmptyOutput('link', 'codemap-link', intentObj.scope);
546
+ const codeMap = await this.loadCodeMap();
547
+ const dependency = codeMap
548
+ ? this.buildLinkDependencyAnalysis(codeMap, intentObj.targets)
549
+ : [];
550
+ const reference = codeMap
551
+ ? this.buildLinkReferenceAnalysis(codeMap, intentObj.targets, intentObj.keywords)
552
+ : [];
553
+ const referenceResults = this.buildReferenceResults(reference);
554
+ const mergedResults = this.mergeUnifiedResults(dependencyOutput.results, referenceResults);
555
+ const results = mergedResults.slice(0, topK);
556
+ const confidence = this.combineConfidence([
557
+ dependencyOutput.confidence,
558
+ this.buildConfidence(this.calculateConfidence(referenceResults))
559
+ ], results);
560
+ const analysis = {
561
+ intent: 'link',
562
+ ...(reference.length > 0 ? { reference } : {}),
563
+ ...(dependency.length > 0 ? { dependency } : {})
564
+ };
565
+ return this.withCompatibility({
566
+ schemaVersion: 'v1.0.0',
567
+ intent: 'link',
568
+ tool: 'codemap-link',
569
+ confidence,
570
+ results,
571
+ analysis,
572
+ metadata: {
573
+ total: mergedResults.length,
574
+ resultCount: results.length,
575
+ scope: intentObj.scope
576
+ }
577
+ }, intentObj.compatibility);
578
+ }
579
+ /**
580
+ * 执行 show 聚合
581
+ */
582
+ async executeShow(intentObj, topK) {
583
+ const codeMap = await this.loadCodeMap();
584
+ const modules = codeMap ? this.findMatchingModules(codeMap, intentObj.targets) : [];
585
+ const analysis = {
586
+ intent: 'show',
587
+ overview: modules.map(module => ({
588
+ title: path.basename(module.absolutePath),
589
+ file: this.toRelativePath(codeMap, module.absolutePath),
590
+ overview: module.overview ?? `模块 ${this.toRelativePath(codeMap, module.absolutePath)},导出 ${module.exports.length} 个符号,依赖 ${module.dependencies.length} 个模块`,
591
+ exports: module.exports.map(exp => exp.name)
592
+ })),
593
+ documentation: modules.map(module => ({
594
+ title: path.basename(module.absolutePath),
595
+ file: this.toRelativePath(codeMap, module.absolutePath),
596
+ content: module.overview
597
+ ?? `类型: ${module.type}; 代码行: ${module.stats.codeLines}; 导出: ${module.exports.map(exp => exp.name).join(', ') || '无'}`
598
+ }))
599
+ };
600
+ const results = this.buildShowResults(analysis).slice(0, topK);
601
+ return this.withCompatibility({
602
+ schemaVersion: 'v1.0.0',
603
+ intent: 'show',
604
+ tool: 'codemap-show',
605
+ confidence: this.buildConfidence(this.calculateConfidence(results)),
606
+ results,
607
+ analysis,
608
+ metadata: {
609
+ total: results.length,
610
+ resultCount: results.length,
611
+ scope: intentObj.scope
612
+ }
613
+ }, intentObj.compatibility);
614
+ }
615
+ /**
616
+ * 创建空输出
617
+ */
618
+ createEmptyOutput(intent, tool, scope) {
619
+ return {
620
+ schemaVersion: 'v1.0.0',
621
+ intent,
622
+ tool,
623
+ confidence: this.buildConfidence(0),
624
+ results: [],
625
+ metadata: {
626
+ total: 0,
627
+ resultCount: 0,
628
+ scope
629
+ }
630
+ };
631
+ }
632
+ /**
633
+ * 聚合多个 Confidence
634
+ */
635
+ combineConfidence(confidences, results) {
636
+ const effective = confidences.filter(confidence => Number.isFinite(confidence.score));
637
+ if (effective.length === 0) {
638
+ return this.buildConfidence(this.calculateConfidence(results));
639
+ }
640
+ const score = Math.round((effective.reduce((sum, confidence) => sum + confidence.score, 0) / effective.length) * 100) / 100;
641
+ return this.buildConfidence(score);
642
+ }
643
+ /**
644
+ * 构建 Confidence
645
+ */
646
+ buildConfidence(score) {
647
+ const normalizedScore = Math.round(Math.max(0, Math.min(score, 1)) * 100) / 100;
648
+ return {
649
+ score: normalizedScore,
650
+ level: calculateConfidenceLevel(normalizedScore)
651
+ };
652
+ }
653
+ /**
654
+ * 合并 UnifiedResult
655
+ */
656
+ mergeUnifiedResults(...collections) {
657
+ const merged = new Map();
658
+ for (const results of collections) {
659
+ for (const result of results) {
660
+ const key = `${result.file}:${result.location?.line ?? result.line ?? 1}`;
661
+ const existing = merged.get(key);
662
+ if (!existing || result.relevance > existing.relevance) {
663
+ merged.set(key, result);
664
+ }
665
+ }
666
+ }
667
+ return Array.from(merged.values()).sort((left, right) => right.relevance - left.relevance);
668
+ }
669
+ /**
670
+ * 加载 CodeMap 数据
671
+ */
672
+ async loadCodeMap() {
673
+ try {
674
+ const dataPath = resolveDataPath();
675
+ const raw = await readFile(dataPath, 'utf-8');
676
+ return JSON.parse(raw);
677
+ }
678
+ catch {
679
+ return null;
680
+ }
681
+ }
682
+ /**
683
+ * 查找目标模块
684
+ */
685
+ findMatchingModules(codeMap, targets) {
686
+ const seen = new Set();
687
+ const modules = [];
688
+ for (const target of targets) {
689
+ const module = this.findMatchingModule(codeMap, target);
690
+ if (module && !seen.has(module.id)) {
691
+ seen.add(module.id);
692
+ modules.push(module);
693
+ }
694
+ }
695
+ return modules;
696
+ }
697
+ /**
698
+ * 查找单个匹配模块
699
+ */
700
+ findMatchingModule(codeMap, target) {
701
+ return codeMap.modules.find(module => {
702
+ const relativePath = this.toRelativePath(codeMap, module.absolutePath);
703
+ return module.absolutePath.includes(target) || relativePath.includes(target);
704
+ });
705
+ }
706
+ /**
707
+ * 构建 link dependency analysis
708
+ */
709
+ buildLinkDependencyAnalysis(codeMap, targets) {
710
+ return this.findMatchingModules(codeMap, targets).map(module => ({
711
+ file: this.toRelativePath(codeMap, module.absolutePath),
712
+ location: {
713
+ file: this.toRelativePath(codeMap, module.absolutePath),
714
+ line: 1,
715
+ column: 1
716
+ },
717
+ imports: module.dependencies,
718
+ importedBy: module.dependents.map(id => {
719
+ const dependent = codeMap.modules.find(candidate => candidate.id === id);
720
+ return dependent ? this.toRelativePath(codeMap, dependent.absolutePath) : id;
721
+ }),
722
+ cycles: []
723
+ }));
724
+ }
725
+ /**
726
+ * 构建 link reference analysis
727
+ */
728
+ buildLinkReferenceAnalysis(codeMap, targets, keywords) {
729
+ const items = [];
730
+ for (const module of this.findMatchingModules(codeMap, targets)) {
731
+ items.push(this.buildModuleReferenceItem(codeMap, module));
732
+ }
733
+ for (const keyword of keywords) {
734
+ items.push(this.buildKeywordReferenceItem(codeMap, keyword));
735
+ }
736
+ const merged = new Map();
737
+ for (const item of items) {
738
+ const existing = merged.get(item.target);
739
+ if (!existing) {
740
+ merged.set(item.target, item);
741
+ continue;
742
+ }
743
+ merged.set(item.target, {
744
+ target: item.target,
745
+ callers: Array.from(new Set([...existing.callers, ...item.callers])),
746
+ callees: Array.from(new Set([...existing.callees, ...item.callees])),
747
+ matches: [...existing.matches, ...item.matches]
748
+ });
749
+ }
750
+ return Array.from(merged.values());
751
+ }
752
+ /**
753
+ * 基于模块构建 reference item
754
+ */
755
+ buildModuleReferenceItem(codeMap, module) {
756
+ const relativePath = this.toRelativePath(codeMap, module.absolutePath);
757
+ const exportedSymbols = new Set(module.exports.map(exp => exp.name));
758
+ const matchTokens = new Set([
759
+ relativePath,
760
+ this.stripModuleExtension(relativePath),
761
+ path.basename(relativePath),
762
+ this.stripModuleExtension(path.basename(relativePath)),
763
+ module.id
764
+ ]);
765
+ const callers = new Set();
766
+ const matches = [];
767
+ for (const candidate of codeMap.modules) {
768
+ if (candidate.id === module.id) {
769
+ continue;
770
+ }
771
+ const candidatePath = this.toRelativePath(codeMap, candidate.absolutePath);
772
+ for (const entry of candidate.imports) {
773
+ const sourceMatched = this.matchesModuleSource(entry.source, matchTokens);
774
+ const symbolMatched = entry.specifiers.some(specifier => exportedSymbols.has(specifier.name));
775
+ if (!sourceMatched && !symbolMatched) {
776
+ continue;
777
+ }
778
+ callers.add(candidatePath);
779
+ matches.push({
780
+ file: candidatePath,
781
+ line: 1,
782
+ snippet: entry.source
783
+ });
784
+ }
785
+ }
786
+ return {
787
+ target: relativePath,
788
+ callers: Array.from(callers),
789
+ callees: module.dependencies,
790
+ matches
791
+ };
792
+ }
793
+ /**
794
+ * 基于关键词构建 reference item
795
+ */
796
+ buildKeywordReferenceItem(codeMap, keyword) {
797
+ const callers = new Set();
798
+ const callees = new Set();
799
+ const matches = [];
800
+ for (const module of codeMap.modules) {
801
+ const relativePath = this.toRelativePath(codeMap, module.absolutePath);
802
+ const definesKeyword = module.exports.some(exp => exp.name === keyword)
803
+ || module.symbols.some(symbol => symbol.name === keyword);
804
+ if (definesKeyword) {
805
+ callees.add(relativePath);
806
+ }
807
+ for (const entry of module.imports) {
808
+ const sourceMatched = entry.source.toLowerCase().includes(keyword.toLowerCase());
809
+ const specifierMatched = entry.specifiers.some(specifier => specifier.name === keyword || specifier.alias === keyword);
810
+ if (!sourceMatched && !specifierMatched) {
811
+ continue;
812
+ }
813
+ callers.add(relativePath);
814
+ matches.push({
815
+ file: relativePath,
816
+ line: 1,
817
+ snippet: entry.source
818
+ });
819
+ }
820
+ }
821
+ return {
822
+ target: keyword,
823
+ callers: Array.from(callers),
824
+ callees: Array.from(callees),
825
+ matches
826
+ };
827
+ }
828
+ /**
829
+ * 将 reference analysis 转为 results
830
+ */
831
+ buildReferenceResults(items) {
832
+ return items.map(item => ({
833
+ id: `reference-${item.target}`,
834
+ source: 'codemap',
835
+ toolScore: 0.8,
836
+ type: 'symbol',
837
+ file: item.matches[0]?.file ?? item.callees[0] ?? item.target,
838
+ line: item.matches[0]?.line ?? 1,
839
+ location: {
840
+ file: item.matches[0]?.file ?? item.callees[0] ?? item.target,
841
+ line: item.matches[0]?.line ?? 1,
842
+ column: 1
843
+ },
844
+ content: `发现 ${item.callers.length} 个引用方,${item.callees.length} 个关联目标`,
845
+ relevance: Math.min(0.4 + item.callers.length * 0.1, 0.95),
846
+ keywords: [item.target],
847
+ metadata: {
848
+ dependencies: item.callees,
849
+ impactCount: item.callers.length,
850
+ stability: true,
851
+ riskLevel: item.callers.length > 10 ? 'high' : item.callers.length > 3 ? 'medium' : 'low'
852
+ }
853
+ }));
854
+ }
855
+ /**
856
+ * 构建 show 结果
857
+ */
858
+ buildShowResults(analysis) {
859
+ const results = [];
860
+ for (const section of analysis.overview ?? []) {
861
+ results.push({
862
+ id: `show-overview-${section.file}`,
863
+ source: 'codemap',
864
+ toolScore: 0.75,
865
+ type: 'documentation',
866
+ file: section.file,
867
+ line: 1,
868
+ location: {
869
+ file: section.file,
870
+ line: 1,
871
+ column: 1
872
+ },
873
+ content: section.overview,
874
+ relevance: 0.75,
875
+ keywords: section.exports,
876
+ metadata: {
877
+ stability: true,
878
+ riskLevel: 'low'
879
+ }
880
+ });
881
+ }
882
+ for (const section of analysis.documentation ?? []) {
883
+ results.push({
884
+ id: `show-documentation-${section.file}`,
885
+ source: 'codemap',
886
+ toolScore: 0.7,
887
+ type: 'documentation',
888
+ file: section.file,
889
+ line: 1,
890
+ location: {
891
+ file: section.file,
892
+ line: 1,
893
+ column: 1
894
+ },
895
+ content: section.content,
896
+ relevance: 0.7,
897
+ keywords: [],
898
+ metadata: {
899
+ stability: true,
900
+ riskLevel: 'low'
901
+ }
902
+ });
903
+ }
904
+ return this.mergeUnifiedResults(results);
905
+ }
906
+ /**
907
+ * 转为相对路径
908
+ */
909
+ toRelativePath(codeMap, filePath) {
910
+ return path.relative(codeMap.project.rootDir, filePath).replace(/\\/g, '/');
911
+ }
912
+ /**
913
+ * 去除模块扩展名
914
+ */
915
+ stripModuleExtension(value) {
916
+ return value.replace(/\.[cm]?[jt]sx?$/i, '');
917
+ }
918
+ /**
919
+ * 判断 import source 是否引用目标模块
920
+ */
921
+ matchesModuleSource(source, tokens) {
922
+ const normalizedSource = this.stripModuleExtension(source).replace(/\\/g, '/').toLowerCase();
923
+ for (const token of tokens) {
924
+ const normalizedToken = this.stripModuleExtension(token).replace(/\\/g, '/').toLowerCase();
925
+ if (!normalizedToken) {
926
+ continue;
927
+ }
928
+ if (normalizedSource === normalizedToken
929
+ || normalizedSource.endsWith(normalizedToken)
930
+ || normalizedSource.includes(normalizedToken)) {
931
+ return true;
932
+ }
933
+ }
934
+ return false;
935
+ }
936
+ /**
937
+ * 为 UnifiedResult 添加 location 字段
938
+ */
939
+ enrichWithLocation(results) {
940
+ return results.map(result => {
941
+ // 如果已经有 line 字段,构建完整的 location
942
+ if (result.line && result.line > 0) {
943
+ const location = {
944
+ file: result.file,
945
+ line: result.line,
946
+ column: 1, // 默认列号
947
+ };
948
+ return { ...result, location };
949
+ }
950
+ // 否则只添加 file
951
+ const location = {
952
+ file: result.file,
953
+ line: 1,
954
+ column: 1,
955
+ };
956
+ return { ...result, location };
957
+ });
958
+ }
959
+ /**
960
+ * 执行影响分析
961
+ */
962
+ async executeImpact(scope, topK) {
963
+ const command = new ImpactCommand();
964
+ const args = {
965
+ targets: this.args.targets || [],
966
+ scope: scope,
967
+ };
968
+ const results = await command.runEnhanced(args);
969
+ // 关联测试文件
970
+ const resultsWithTests = await this.attachTestFiles(results);
971
+ // 计算置信度
972
+ const confidenceScore = this.calculateConfidence(resultsWithTests);
973
+ const confidence = {
974
+ score: confidenceScore,
975
+ level: confidenceScore >= 0.7 ? 'high' : confidenceScore >= 0.4 ? 'medium' : 'low',
976
+ };
977
+ // 添加 location 字段
978
+ const resultsWithLocation = this.enrichWithLocation(resultsWithTests);
979
+ const typedResults = resultsWithLocation;
980
+ return {
981
+ schemaVersion: 'v1.0.0',
982
+ intent: 'read',
983
+ tool: 'codemap-impact',
984
+ confidence,
985
+ results: typedResults.slice(0, topK),
986
+ metadata: {
987
+ total: resultsWithTests.length,
988
+ scope,
989
+ resultCount: typedResults.slice(0, topK).length,
990
+ },
991
+ };
992
+ }
993
+ /**
994
+ * 计算置信度分数
995
+ */
996
+ calculateConfidence(results) {
997
+ if (!results || results.length === 0) {
998
+ return 0;
999
+ }
1000
+ // 基于结果数量和质量计算置信度
1001
+ const resultCount = results.length;
1002
+ // 假设至少有结果的情况下,基础置信度为 0.5
1003
+ // 结果越多置信度越高
1004
+ const score = Math.min(0.5 + (resultCount / 10), 1);
1005
+ return Math.round(score * 100) / 100;
1006
+ }
1007
+ /**
1008
+ * 执行依赖分析
1009
+ */
1010
+ async executeDeps(topK) {
1011
+ const command = new DepsCommand();
1012
+ const args = {
1013
+ targets: this.args.targets || [],
1014
+ };
1015
+ const results = await command.runEnhanced(args);
1016
+ // 关联测试文件
1017
+ const resultsWithTests = await this.attachTestFiles(results);
1018
+ // 计算置信度
1019
+ const confidenceScore = this.calculateConfidence(resultsWithTests);
1020
+ const confidence = {
1021
+ score: confidenceScore,
1022
+ level: confidenceScore >= 0.7 ? 'high' : confidenceScore >= 0.4 ? 'medium' : 'low',
1023
+ };
1024
+ // 添加 location 字段
1025
+ const resultsWithLocation = this.enrichWithLocation(resultsWithTests);
1026
+ const typedResults = resultsWithLocation;
1027
+ return {
1028
+ schemaVersion: 'v1.0.0',
1029
+ intent: 'link',
1030
+ tool: 'codemap-deps',
1031
+ confidence,
1032
+ results: typedResults.slice(0, topK),
1033
+ metadata: {
1034
+ total: resultsWithTests.length,
1035
+ resultCount: typedResults.slice(0, topK).length,
1036
+ },
1037
+ };
1038
+ }
1039
+ /**
1040
+ * 执行复杂度分析
1041
+ */
1042
+ async executeComplexity(topK) {
1043
+ const command = new ComplexityCommand();
1044
+ const args = {
1045
+ targets: this.args.targets || [],
1046
+ };
1047
+ const results = await command.runEnhanced(args);
1048
+ // 关联测试文件
1049
+ const resultsWithTests = await this.attachTestFiles(results);
1050
+ // 计算置信度
1051
+ const confidenceScore = this.calculateConfidence(resultsWithTests);
1052
+ const confidence = {
1053
+ score: confidenceScore,
1054
+ level: confidenceScore >= 0.7 ? 'high' : confidenceScore >= 0.4 ? 'medium' : 'low',
1055
+ };
1056
+ // 添加 location 字段
1057
+ const resultsWithLocation = this.enrichWithLocation(resultsWithTests);
1058
+ const typedResults = resultsWithLocation;
1059
+ return {
1060
+ schemaVersion: 'v1.0.0',
1061
+ intent: 'read',
1062
+ tool: 'codemap-complexity',
1063
+ confidence,
1064
+ results: typedResults.slice(0, topK),
1065
+ metadata: {
1066
+ total: resultsWithTests.length,
1067
+ resultCount: typedResults.slice(0, topK).length,
1068
+ },
1069
+ };
1070
+ }
1071
+ /**
1072
+ * 关联测试文件
1073
+ */
1074
+ async attachTestFiles(results) {
1075
+ if (!this.args.includeTests) {
1076
+ return results;
1077
+ }
1078
+ // 为每个结果附加测试文件信息
1079
+ for (const result of results) {
1080
+ if (result.file) {
1081
+ const testFile = await resolveTestFile(result.file);
1082
+ if (testFile) {
1083
+ result.metadata = result.metadata || {};
1084
+ result.metadata.testFile = testFile;
1085
+ }
1086
+ }
1087
+ }
1088
+ return results;
1089
+ }
1090
+ /**
1091
+ * 打印人类可读输出
1092
+ */
1093
+ printHumanOutput(results, intent) {
1094
+ console.log(chalk.bold(`\n📊 ${intent.toUpperCase()} 分析结果\n`));
1095
+ const resultsArray = results;
1096
+ for (const result of resultsArray) {
1097
+ const lineInfo = result.location?.line ? `:${result.location.line}` : '';
1098
+ console.log(chalk.cyan(`📁 ${result.file}${lineInfo}`));
1099
+ console.log(` ${result.content}`);
1100
+ console.log(chalk.gray(` 相关度: ${(result.relevance * 100).toFixed(1)}%`));
1101
+ if (result.metadata?.testFile) {
1102
+ console.log(chalk.green(` 🧪 测试: ${result.metadata.testFile}`));
1103
+ }
1104
+ console.log();
1105
+ }
1106
+ }
1107
+ }
1108
+ function normalizeStringArray(value) {
1109
+ if (typeof value === 'string') {
1110
+ return [value];
1111
+ }
1112
+ if (Array.isArray(value)) {
1113
+ return value.filter((item) => typeof item === 'string');
1114
+ }
1115
+ return [];
1116
+ }
1117
+ export function parseAnalyzeArgs(argv) {
1118
+ try {
1119
+ const { values, positionals } = parseArgs({
1120
+ args: argv,
1121
+ allowPositionals: true,
1122
+ options: ANALYZE_PARSE_OPTIONS,
1123
+ });
1124
+ const positionalTargets = positionals?.filter(position => !position.startsWith('-')) || [];
1125
+ const explicitTargets = normalizeStringArray(values.targets);
1126
+ const allTargets = [...explicitTargets, ...positionalTargets];
1127
+ const keywords = normalizeStringArray(values.keywords);
1128
+ return {
1129
+ intent: values.intent,
1130
+ targets: allTargets.length > 0 ? allTargets : undefined,
1131
+ keywords: keywords.length > 0 ? keywords : undefined,
1132
+ scope: values.scope,
1133
+ topK: values.topK ? Number.parseInt(values.topK, 10) : undefined,
1134
+ includeTests: values['include-tests'],
1135
+ includeGitHistory: values['include-git-history'],
1136
+ json: values.json,
1137
+ human: values.human,
1138
+ structured: values.structured,
1139
+ outputMode: values['output-mode'],
1140
+ };
1141
+ }
1142
+ catch {
1143
+ return {};
1144
+ }
1145
+ }
1146
+ export async function executeAnalyzeTool(args) {
1147
+ const startedAt = performance.now();
1148
+ try {
1149
+ const command = new AnalyzeCommand(args);
1150
+ const output = await command.execute();
1151
+ let result = output;
1152
+ if (args.structured) {
1153
+ const structuredOutput = JSON.parse(JSON.stringify(output));
1154
+ if (structuredOutput.results) {
1155
+ structuredOutput.results = structuredOutput.results.map(entry => {
1156
+ const { content, ...rest } = entry;
1157
+ void content;
1158
+ return rest;
1159
+ });
1160
+ }
1161
+ result = structuredOutput;
1162
+ }
1163
+ return createContractSuccess({
1164
+ tool: 'analyze',
1165
+ rootDir: process.cwd(),
1166
+ durationMs: performance.now() - startedAt,
1167
+ }, result);
1168
+ }
1169
+ catch (error) {
1170
+ return createContractError({
1171
+ tool: 'analyze',
1172
+ rootDir: process.cwd(),
1173
+ durationMs: performance.now() - startedAt,
1174
+ }, normalizeExecutionError(error));
1175
+ }
1176
+ }
1177
+ /**
1178
+ * Human-readable renderer for analyze output (chalk + padEnd table pattern)
1179
+ */
1180
+ export function formatAnalyzeHuman(output) {
1181
+ const lines = [];
1182
+ // Warnings
1183
+ for (const warning of output.warnings || []) {
1184
+ lines.push(chalk.yellow(`Warning: ${warning.message}`));
1185
+ }
1186
+ // Header
1187
+ const intentLabel = output.intent?.toUpperCase() || 'ANALYSIS';
1188
+ lines.push(chalk.bold(`\n${intentLabel} Analysis Results\n`));
1189
+ // Table header
1190
+ const TYPE_WIDTH = 12;
1191
+ const NAME_WIDTH = 30;
1192
+ const PATH_WIDTH = 40;
1193
+ const header = 'TYPE'.padEnd(TYPE_WIDTH) +
1194
+ 'NAME'.padEnd(NAME_WIDTH) +
1195
+ 'PATH'.padEnd(PATH_WIDTH) +
1196
+ 'RELEVANCE';
1197
+ lines.push(header);
1198
+ lines.push('-'.repeat(header.length));
1199
+ // Data rows
1200
+ for (const result of output.results || []) {
1201
+ const type = (result.type || '').padEnd(TYPE_WIDTH);
1202
+ const name = (result.id || '').substring(0, NAME_WIDTH - 1).padEnd(NAME_WIDTH);
1203
+ const lineInfo = result.location?.line ? `:${result.location.line}` : '';
1204
+ const filePath = `${result.file}${lineInfo}`.substring(0, PATH_WIDTH - 1).padEnd(PATH_WIDTH);
1205
+ const relevance = `${(result.relevance * 100).toFixed(1)}%`;
1206
+ lines.push(`${type}${name}${filePath}${relevance}`);
1207
+ }
1208
+ // Summary
1209
+ if (output.results.length > 0) {
1210
+ lines.push('');
1211
+ }
1212
+ lines.push(chalk.gray(`Tools: ${output.tool}, Confidence: ${output.confidence.level} (${output.confidence.score})`));
1213
+ return lines.join('\n');
1214
+ }
1215
+ //# sourceMappingURL=analyze.js.map