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