@mycodemap/mycodemap 2.0.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 (424) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +59 -184
  3. package/dist/cli/commands/agent-metrics/human.d.ts +4 -0
  4. package/dist/cli/commands/agent-metrics/human.d.ts.map +1 -0
  5. package/dist/cli/commands/agent-metrics/human.js +134 -0
  6. package/dist/cli/commands/agent-metrics/human.js.map +1 -0
  7. package/dist/cli/commands/agent-metrics/index.d.ts +15 -0
  8. package/dist/cli/commands/agent-metrics/index.d.ts.map +1 -0
  9. package/dist/cli/commands/agent-metrics/index.js +116 -0
  10. package/dist/cli/commands/agent-metrics/index.js.map +1 -0
  11. package/dist/cli/commands/analyze.d.ts +3 -196
  12. package/dist/cli/commands/analyze.d.ts.map +1 -1
  13. package/dist/cli/commands/analyze.js +9 -1163
  14. package/dist/cli/commands/analyze.js.map +1 -1
  15. package/dist/cli/commands/benchmark.d.ts.map +1 -1
  16. package/dist/cli/commands/benchmark.js +5 -2
  17. package/dist/cli/commands/benchmark.js.map +1 -1
  18. package/dist/cli/commands/complexity.d.ts.map +1 -1
  19. package/dist/cli/commands/complexity.js +62 -95
  20. package/dist/cli/commands/complexity.js.map +1 -1
  21. package/dist/cli/commands/deps.d.ts +3 -60
  22. package/dist/cli/commands/deps.d.ts.map +1 -1
  23. package/dist/cli/commands/deps.js +16 -351
  24. package/dist/cli/commands/deps.js.map +1 -1
  25. package/dist/cli/commands/env-contract.d.ts +3 -0
  26. package/dist/cli/commands/env-contract.d.ts.map +1 -0
  27. package/dist/cli/commands/env-contract.js +221 -0
  28. package/dist/cli/commands/env-contract.js.map +1 -0
  29. package/dist/cli/commands/generate.d.ts +19 -1
  30. package/dist/cli/commands/generate.d.ts.map +1 -1
  31. package/dist/cli/commands/generate.js +735 -89
  32. package/dist/cli/commands/generate.js.map +1 -1
  33. package/dist/cli/commands/impact.d.ts +4 -38
  34. package/dist/cli/commands/impact.d.ts.map +1 -1
  35. package/dist/cli/commands/impact.js +133 -375
  36. package/dist/cli/commands/impact.js.map +1 -1
  37. package/dist/cli/commands/init.d.ts +1 -0
  38. package/dist/cli/commands/init.d.ts.map +1 -1
  39. package/dist/cli/commands/init.js +61 -2
  40. package/dist/cli/commands/init.js.map +1 -1
  41. package/dist/cli/commands/preview.d.ts +3 -0
  42. package/dist/cli/commands/preview.d.ts.map +1 -0
  43. package/dist/cli/commands/preview.js +216 -0
  44. package/dist/cli/commands/preview.js.map +1 -0
  45. package/dist/cli/commands/query.d.ts +2 -21
  46. package/dist/cli/commands/query.d.ts.map +1 -1
  47. package/dist/cli/commands/query.js +15 -683
  48. package/dist/cli/commands/query.js.map +1 -1
  49. package/dist/cli/commands/watch-foreground.d.ts.map +1 -1
  50. package/dist/cli/commands/watch-foreground.js +5 -1
  51. package/dist/cli/commands/watch-foreground.js.map +1 -1
  52. package/dist/cli/config-loader.d.ts.map +1 -1
  53. package/dist/cli/config-loader.js +51 -13
  54. package/dist/cli/config-loader.js.map +1 -1
  55. package/dist/cli/doctor/check-env-contract.d.ts +3 -0
  56. package/dist/cli/doctor/check-env-contract.d.ts.map +1 -0
  57. package/dist/cli/doctor/check-env-contract.js +96 -0
  58. package/dist/cli/doctor/check-env-contract.js.map +1 -0
  59. package/dist/cli/doctor/check-native-deps.d.ts.map +1 -1
  60. package/dist/cli/doctor/check-native-deps.js +20 -4
  61. package/dist/cli/doctor/check-native-deps.js.map +1 -1
  62. package/dist/cli/doctor/orchestrator.d.ts.map +1 -1
  63. package/dist/cli/doctor/orchestrator.js +5 -2
  64. package/dist/cli/doctor/orchestrator.js.map +1 -1
  65. package/dist/cli/env-contract/check.d.ts +18 -0
  66. package/dist/cli/env-contract/check.d.ts.map +1 -0
  67. package/dist/cli/env-contract/check.js +118 -0
  68. package/dist/cli/env-contract/check.js.map +1 -0
  69. package/dist/cli/env-contract/discovery.d.ts +12 -0
  70. package/dist/cli/env-contract/discovery.d.ts.map +1 -0
  71. package/dist/cli/env-contract/discovery.js +249 -0
  72. package/dist/cli/env-contract/discovery.js.map +1 -0
  73. package/dist/cli/env-contract/filters.d.ts +10 -0
  74. package/dist/cli/env-contract/filters.d.ts.map +1 -0
  75. package/dist/cli/env-contract/filters.js +23 -0
  76. package/dist/cli/env-contract/filters.js.map +1 -0
  77. package/dist/cli/env-contract/index.d.ts +6 -0
  78. package/dist/cli/env-contract/index.d.ts.map +1 -0
  79. package/dist/cli/env-contract/index.js +8 -0
  80. package/dist/cli/env-contract/index.js.map +1 -0
  81. package/dist/cli/env-contract/reminder-engine.d.ts +34 -0
  82. package/dist/cli/env-contract/reminder-engine.d.ts.map +1 -0
  83. package/dist/cli/env-contract/reminder-engine.js +51 -0
  84. package/dist/cli/env-contract/reminder-engine.js.map +1 -0
  85. package/dist/cli/env-contract/reminder-hook-runner.d.ts +45 -0
  86. package/dist/cli/env-contract/reminder-hook-runner.d.ts.map +1 -0
  87. package/dist/cli/env-contract/reminder-hook-runner.js +273 -0
  88. package/dist/cli/env-contract/reminder-hook-runner.js.map +1 -0
  89. package/dist/cli/env-contract/reminder-ledger.d.ts +11 -0
  90. package/dist/cli/env-contract/reminder-ledger.d.ts.map +1 -0
  91. package/dist/cli/env-contract/reminder-ledger.js +37 -0
  92. package/dist/cli/env-contract/reminder-ledger.js.map +1 -0
  93. package/dist/cli/env-contract/types.d.ts +48 -0
  94. package/dist/cli/env-contract/types.d.ts.map +1 -0
  95. package/dist/cli/env-contract/types.js +22 -0
  96. package/dist/cli/env-contract/types.js.map +1 -0
  97. package/dist/cli/env-contract/validation.d.ts +10 -0
  98. package/dist/cli/env-contract/validation.d.ts.map +1 -0
  99. package/dist/cli/env-contract/validation.js +116 -0
  100. package/dist/cli/env-contract/validation.js.map +1 -0
  101. package/dist/cli/first-run-guide.d.ts.map +1 -1
  102. package/dist/cli/first-run-guide.js +8 -3
  103. package/dist/cli/first-run-guide.js.map +1 -1
  104. package/dist/cli/index.js +23 -3
  105. package/dist/cli/index.js.map +1 -1
  106. package/dist/cli/init/assistant-plan.d.ts +14 -0
  107. package/dist/cli/init/assistant-plan.d.ts.map +1 -0
  108. package/dist/cli/init/assistant-plan.js +208 -0
  109. package/dist/cli/init/assistant-plan.js.map +1 -0
  110. package/dist/cli/init/detect.d.ts +28 -0
  111. package/dist/cli/init/detect.d.ts.map +1 -0
  112. package/dist/cli/init/detect.js +63 -0
  113. package/dist/cli/init/detect.js.map +1 -0
  114. package/dist/cli/init/env-contract-plan.d.ts +28 -0
  115. package/dist/cli/init/env-contract-plan.d.ts.map +1 -0
  116. package/dist/cli/init/env-contract-plan.js +184 -0
  117. package/dist/cli/init/env-contract-plan.js.map +1 -0
  118. package/dist/cli/init/manifest-extractors.d.ts +22 -0
  119. package/dist/cli/init/manifest-extractors.d.ts.map +1 -0
  120. package/dist/cli/init/manifest-extractors.js +185 -0
  121. package/dist/cli/init/manifest-extractors.js.map +1 -0
  122. package/dist/cli/init/profile-loader.d.ts +49 -0
  123. package/dist/cli/init/profile-loader.d.ts.map +1 -0
  124. package/dist/cli/init/profile-loader.js +107 -0
  125. package/dist/cli/init/profile-loader.js.map +1 -0
  126. package/dist/cli/init/profile-plan.d.ts +38 -0
  127. package/dist/cli/init/profile-plan.d.ts.map +1 -0
  128. package/dist/cli/init/profile-plan.js +120 -0
  129. package/dist/cli/init/profile-plan.js.map +1 -0
  130. package/dist/cli/init/profiles/generic.json +16 -0
  131. package/dist/cli/init/profiles/go.json +12 -0
  132. package/dist/cli/init/profiles/nodejs.json +16 -0
  133. package/dist/cli/init/profiles/python.json +17 -0
  134. package/dist/cli/init/profiles/rust.json +12 -0
  135. package/dist/cli/init/receipt.d.ts.map +1 -1
  136. package/dist/cli/init/receipt.js +107 -7
  137. package/dist/cli/init/receipt.js.map +1 -1
  138. package/dist/cli/init/reconciler.d.ts +10 -1
  139. package/dist/cli/init/reconciler.d.ts.map +1 -1
  140. package/dist/cli/init/reconciler.js +85 -15
  141. package/dist/cli/init/reconciler.js.map +1 -1
  142. package/dist/cli/interface-contract/commands/agent-metrics.d.ts +3 -0
  143. package/dist/cli/interface-contract/commands/agent-metrics.d.ts.map +1 -0
  144. package/dist/cli/interface-contract/commands/agent-metrics.js +217 -0
  145. package/dist/cli/interface-contract/commands/agent-metrics.js.map +1 -0
  146. package/dist/cli/interface-contract/commands/analyze.d.ts.map +1 -1
  147. package/dist/cli/interface-contract/commands/analyze.js +1 -0
  148. package/dist/cli/interface-contract/commands/analyze.js.map +1 -1
  149. package/dist/cli/interface-contract/commands/benchmark.d.ts.map +1 -1
  150. package/dist/cli/interface-contract/commands/benchmark.js +1 -0
  151. package/dist/cli/interface-contract/commands/benchmark.js.map +1 -1
  152. package/dist/cli/interface-contract/commands/deps.d.ts.map +1 -1
  153. package/dist/cli/interface-contract/commands/deps.js +1 -0
  154. package/dist/cli/interface-contract/commands/deps.js.map +1 -1
  155. package/dist/cli/interface-contract/commands/doctor.d.ts.map +1 -1
  156. package/dist/cli/interface-contract/commands/doctor.js +1 -0
  157. package/dist/cli/interface-contract/commands/doctor.js.map +1 -1
  158. package/dist/cli/interface-contract/commands/env-contract.d.ts +3 -0
  159. package/dist/cli/interface-contract/commands/env-contract.d.ts.map +1 -0
  160. package/dist/cli/interface-contract/commands/env-contract.js +168 -0
  161. package/dist/cli/interface-contract/commands/env-contract.js.map +1 -0
  162. package/dist/cli/interface-contract/commands/index.d.ts +5 -2
  163. package/dist/cli/interface-contract/commands/index.d.ts.map +1 -1
  164. package/dist/cli/interface-contract/commands/index.js +7 -1
  165. package/dist/cli/interface-contract/commands/index.js.map +1 -1
  166. package/dist/cli/interface-contract/commands/init.d.ts.map +1 -1
  167. package/dist/cli/interface-contract/commands/init.js +9 -0
  168. package/dist/cli/interface-contract/commands/init.js.map +1 -1
  169. package/dist/cli/interface-contract/commands/preview.d.ts +3 -0
  170. package/dist/cli/interface-contract/commands/preview.d.ts.map +1 -0
  171. package/dist/cli/interface-contract/commands/preview.js +118 -0
  172. package/dist/cli/interface-contract/commands/preview.js.map +1 -0
  173. package/dist/cli/interface-contract/commands/query.d.ts.map +1 -1
  174. package/dist/cli/interface-contract/commands/query.js +1 -0
  175. package/dist/cli/interface-contract/commands/query.js.map +1 -1
  176. package/dist/cli/interface-contract/index.d.ts +1 -1
  177. package/dist/cli/interface-contract/index.d.ts.map +1 -1
  178. package/dist/cli/interface-contract/index.js +2 -2
  179. package/dist/cli/interface-contract/index.js.map +1 -1
  180. package/dist/cli/interface-contract/schema.d.ts.map +1 -1
  181. package/dist/cli/interface-contract/schema.js +1 -0
  182. package/dist/cli/interface-contract/schema.js.map +1 -1
  183. package/dist/cli/interface-contract/types.d.ts +1 -0
  184. package/dist/cli/interface-contract/types.d.ts.map +1 -1
  185. package/dist/cli/output/error-codes.d.ts +2 -0
  186. package/dist/cli/output/error-codes.d.ts.map +1 -1
  187. package/dist/cli/output/error-codes.js +12 -0
  188. package/dist/cli/output/error-codes.js.map +1 -1
  189. package/dist/cli/output/errors.d.ts.map +1 -1
  190. package/dist/cli/output/errors.js +12 -0
  191. package/dist/cli/output/errors.js.map +1 -1
  192. package/dist/cli/output/wasm-fallback.d.ts +1 -0
  193. package/dist/cli/output/wasm-fallback.d.ts.map +1 -1
  194. package/dist/cli/output/wasm-fallback.js.map +1 -1
  195. package/dist/cli/preview/complexity-scanner.d.ts +21 -0
  196. package/dist/cli/preview/complexity-scanner.d.ts.map +1 -0
  197. package/dist/cli/preview/complexity-scanner.js +52 -0
  198. package/dist/cli/preview/complexity-scanner.js.map +1 -0
  199. package/dist/cli/preview/dependency-extractor.d.ts +38 -0
  200. package/dist/cli/preview/dependency-extractor.d.ts.map +1 -0
  201. package/dist/cli/preview/dependency-extractor.js +140 -0
  202. package/dist/cli/preview/dependency-extractor.js.map +1 -0
  203. package/dist/cli/preview/preview-renderer.d.ts +32 -0
  204. package/dist/cli/preview/preview-renderer.d.ts.map +1 -0
  205. package/dist/cli/preview/preview-renderer.js +54 -0
  206. package/dist/cli/preview/preview-renderer.js.map +1 -0
  207. package/dist/cli/storage-runtime.d.ts +7 -0
  208. package/dist/cli/storage-runtime.d.ts.map +1 -1
  209. package/dist/cli/storage-runtime.js +22 -0
  210. package/dist/cli/storage-runtime.js.map +1 -1
  211. package/dist/cli-new/index.js +1 -1
  212. package/dist/cli-new/index.js.map +1 -1
  213. package/dist/composition/parser-composition.d.ts +7 -0
  214. package/dist/composition/parser-composition.d.ts.map +1 -0
  215. package/dist/composition/parser-composition.js +15 -0
  216. package/dist/composition/parser-composition.js.map +1 -0
  217. package/dist/core/analyzer.d.ts.map +1 -1
  218. package/dist/core/analyzer.js +83 -67
  219. package/dist/core/analyzer.js.map +1 -1
  220. package/dist/core/ast-complexity-analyzer.d.ts +12 -6
  221. package/dist/core/ast-complexity-analyzer.d.ts.map +1 -1
  222. package/dist/core/ast-complexity-analyzer.js +368 -209
  223. package/dist/core/ast-complexity-analyzer.js.map +1 -1
  224. package/dist/core/file-discovery.d.ts +1 -1
  225. package/dist/core/file-discovery.d.ts.map +1 -1
  226. package/dist/core/file-discovery.js +3 -0
  227. package/dist/core/file-discovery.js.map +1 -1
  228. package/dist/core/global-index.d.ts +3 -1
  229. package/dist/core/global-index.d.ts.map +1 -1
  230. package/dist/core/global-index.js +69 -4
  231. package/dist/core/global-index.js.map +1 -1
  232. package/dist/domain/entities/CodeGraph.d.ts +3 -0
  233. package/dist/domain/entities/CodeGraph.d.ts.map +1 -1
  234. package/dist/domain/entities/CodeGraph.js +19 -2
  235. package/dist/domain/entities/CodeGraph.js.map +1 -1
  236. package/dist/domain/entities/Dependency.d.ts +5 -2
  237. package/dist/domain/entities/Dependency.d.ts.map +1 -1
  238. package/dist/domain/entities/Dependency.js +49 -3
  239. package/dist/domain/entities/Dependency.js.map +1 -1
  240. package/dist/domain/repositories/CodeGraphRepository.d.ts +5 -0
  241. package/dist/domain/repositories/CodeGraphRepository.d.ts.map +1 -1
  242. package/dist/domain/repositories/CodeGraphRepository.js.map +1 -1
  243. package/dist/execution/contract-tools/analyze.d.ts +205 -0
  244. package/dist/execution/contract-tools/analyze.d.ts.map +1 -0
  245. package/dist/execution/contract-tools/analyze.js +1215 -0
  246. package/dist/execution/contract-tools/analyze.js.map +1 -0
  247. package/dist/execution/contract-tools/deps.d.ts +62 -0
  248. package/dist/execution/contract-tools/deps.d.ts.map +1 -0
  249. package/dist/execution/contract-tools/deps.js +234 -0
  250. package/dist/execution/contract-tools/deps.js.map +1 -0
  251. package/dist/execution/contract-tools/index.d.ts +5 -0
  252. package/dist/execution/contract-tools/index.d.ts.map +1 -0
  253. package/dist/execution/contract-tools/index.js +7 -0
  254. package/dist/execution/contract-tools/index.js.map +1 -0
  255. package/dist/execution/contract-tools/query.d.ts +60 -0
  256. package/dist/execution/contract-tools/query.d.ts.map +1 -0
  257. package/dist/execution/contract-tools/query.js +532 -0
  258. package/dist/execution/contract-tools/query.js.map +1 -0
  259. package/dist/execution/contract-tools/types.d.ts +26 -0
  260. package/dist/execution/contract-tools/types.d.ts.map +1 -0
  261. package/dist/execution/contract-tools/types.js +32 -0
  262. package/dist/execution/contract-tools/types.js.map +1 -0
  263. package/dist/generator/index.d.ts.map +1 -1
  264. package/dist/generator/index.js +0 -3
  265. package/dist/generator/index.js.map +1 -1
  266. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.d.ts +12 -0
  267. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.d.ts.map +1 -0
  268. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.js +55 -0
  269. package/dist/infrastructure/parser/enhancers/TypeScriptTypeEnhancer.js.map +1 -0
  270. package/dist/infrastructure/parser/implementations/GoParser.d.ts +2 -1
  271. package/dist/infrastructure/parser/implementations/GoParser.d.ts.map +1 -1
  272. package/dist/infrastructure/parser/implementations/GoParser.js +13 -1
  273. package/dist/infrastructure/parser/implementations/GoParser.js.map +1 -1
  274. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.d.ts +114 -0
  275. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.d.ts.map +1 -0
  276. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.js +1022 -0
  277. package/dist/infrastructure/parser/implementations/PythonTreeSitterParser.js.map +1 -0
  278. package/dist/infrastructure/parser/implementations/TreeSitterParser.d.ts +78 -0
  279. package/dist/infrastructure/parser/implementations/TreeSitterParser.d.ts.map +1 -0
  280. package/dist/infrastructure/parser/implementations/TreeSitterParser.js +648 -0
  281. package/dist/infrastructure/parser/implementations/TreeSitterParser.js.map +1 -0
  282. package/dist/infrastructure/parser/implementations/TypeScriptParser.d.ts +3 -55
  283. package/dist/infrastructure/parser/implementations/TypeScriptParser.d.ts.map +1 -1
  284. package/dist/infrastructure/parser/implementations/TypeScriptParser.js +4 -411
  285. package/dist/infrastructure/parser/implementations/TypeScriptParser.js.map +1 -1
  286. package/dist/infrastructure/parser/index.d.ts +2 -0
  287. package/dist/infrastructure/parser/index.d.ts.map +1 -1
  288. package/dist/infrastructure/parser/index.js +9 -6
  289. package/dist/infrastructure/parser/index.js.map +1 -1
  290. package/dist/infrastructure/parser/interfaces/ParserBase.d.ts.map +1 -1
  291. package/dist/infrastructure/parser/interfaces/ParserBase.js +1 -0
  292. package/dist/infrastructure/parser/interfaces/ParserBase.js.map +1 -1
  293. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.d.ts +2 -0
  294. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.d.ts.map +1 -1
  295. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.js +4 -0
  296. package/dist/infrastructure/repositories/CodeGraphRepositoryImpl.js.map +1 -1
  297. package/dist/infrastructure/storage/StorageFactory.d.ts +5 -18
  298. package/dist/infrastructure/storage/StorageFactory.d.ts.map +1 -1
  299. package/dist/infrastructure/storage/StorageFactory.js +30 -98
  300. package/dist/infrastructure/storage/StorageFactory.js.map +1 -1
  301. package/dist/infrastructure/storage/adapters/SQLiteStorage.d.ts +13 -1
  302. package/dist/infrastructure/storage/adapters/SQLiteStorage.d.ts.map +1 -1
  303. package/dist/infrastructure/storage/adapters/SQLiteStorage.js +321 -75
  304. package/dist/infrastructure/storage/adapters/SQLiteStorage.js.map +1 -1
  305. package/dist/infrastructure/storage/adapters/sqlite-loader.d.ts +22 -0
  306. package/dist/infrastructure/storage/adapters/sqlite-loader.d.ts.map +1 -1
  307. package/dist/infrastructure/storage/adapters/sqlite-loader.js +78 -22
  308. package/dist/infrastructure/storage/adapters/sqlite-loader.js.map +1 -1
  309. package/dist/infrastructure/storage/community-helpers.d.ts +4 -0
  310. package/dist/infrastructure/storage/community-helpers.d.ts.map +1 -0
  311. package/dist/infrastructure/storage/community-helpers.js +392 -0
  312. package/dist/infrastructure/storage/community-helpers.js.map +1 -0
  313. package/dist/infrastructure/storage/graph-helpers.d.ts +22 -5
  314. package/dist/infrastructure/storage/graph-helpers.d.ts.map +1 -1
  315. package/dist/infrastructure/storage/graph-helpers.js +496 -91
  316. package/dist/infrastructure/storage/graph-helpers.js.map +1 -1
  317. package/dist/infrastructure/storage/index.d.ts +1 -1
  318. package/dist/infrastructure/storage/index.d.ts.map +1 -1
  319. package/dist/infrastructure/storage/index.js +1 -1
  320. package/dist/infrastructure/storage/index.js.map +1 -1
  321. package/dist/infrastructure/storage/interfaces/StorageBase.d.ts +2 -2
  322. package/dist/infrastructure/storage/interfaces/StorageBase.d.ts.map +1 -1
  323. package/dist/infrastructure/storage/interfaces/StorageBase.js.map +1 -1
  324. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.d.ts +2 -0
  325. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.d.ts.map +1 -1
  326. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.js +52 -12
  327. package/dist/infrastructure/storage/sqlite/GovernanceGraphCache.js.map +1 -1
  328. package/dist/infrastructure/storage/sqlite/schema.d.ts +2 -2
  329. package/dist/infrastructure/storage/sqlite/schema.d.ts.map +1 -1
  330. package/dist/infrastructure/storage/sqlite/schema.js +49 -1
  331. package/dist/infrastructure/storage/sqlite/schema.js.map +1 -1
  332. package/dist/interface/config/index.d.ts +5 -3
  333. package/dist/interface/config/index.d.ts.map +1 -1
  334. package/dist/interface/types/index.d.ts +37 -6
  335. package/dist/interface/types/index.d.ts.map +1 -1
  336. package/dist/interface/types/parser.d.ts +85 -0
  337. package/dist/interface/types/parser.d.ts.map +1 -1
  338. package/dist/interface/types/storage.d.ts +227 -10
  339. package/dist/interface/types/storage.d.ts.map +1 -1
  340. package/dist/orchestrator/agent-metrics-service.d.ts +126 -0
  341. package/dist/orchestrator/agent-metrics-service.d.ts.map +1 -0
  342. package/dist/orchestrator/agent-metrics-service.js +444 -0
  343. package/dist/orchestrator/agent-metrics-service.js.map +1 -0
  344. package/dist/parser/enhancers/PythonTypeEnhancer.d.ts +26 -0
  345. package/dist/parser/enhancers/PythonTypeEnhancer.d.ts.map +1 -0
  346. package/dist/parser/enhancers/PythonTypeEnhancer.js +440 -0
  347. package/dist/parser/enhancers/PythonTypeEnhancer.js.map +1 -0
  348. package/dist/parser/implementations/smart-parser.d.ts.map +1 -1
  349. package/dist/parser/implementations/smart-parser.js +7 -69
  350. package/dist/parser/implementations/smart-parser.js.map +1 -1
  351. package/dist/parser/implementations/tree-sitter-loader.d.ts +2 -0
  352. package/dist/parser/implementations/tree-sitter-loader.d.ts.map +1 -1
  353. package/dist/parser/implementations/tree-sitter-loader.js +46 -15
  354. package/dist/parser/implementations/tree-sitter-loader.js.map +1 -1
  355. package/dist/parser/index.d.ts +5 -3
  356. package/dist/parser/index.d.ts.map +1 -1
  357. package/dist/parser/index.js +68 -6
  358. package/dist/parser/index.js.map +1 -1
  359. package/dist/parser/interfaces/IParser.d.ts +19 -6
  360. package/dist/parser/interfaces/IParser.d.ts.map +1 -1
  361. package/dist/parser/interfaces/IParser.js +2 -3
  362. package/dist/parser/interfaces/IParser.js.map +1 -1
  363. package/dist/server/handlers/AnalysisHandler.d.ts +13 -2
  364. package/dist/server/handlers/AnalysisHandler.d.ts.map +1 -1
  365. package/dist/server/handlers/AnalysisHandler.js +24 -0
  366. package/dist/server/handlers/AnalysisHandler.js.map +1 -1
  367. package/dist/server/handlers/QueryHandler.d.ts.map +1 -1
  368. package/dist/server/handlers/QueryHandler.js +11 -30
  369. package/dist/server/handlers/QueryHandler.js.map +1 -1
  370. package/dist/server/mcp/context-tool.d.ts +9 -0
  371. package/dist/server/mcp/context-tool.d.ts.map +1 -0
  372. package/dist/server/mcp/context-tool.js +257 -0
  373. package/dist/server/mcp/context-tool.js.map +1 -0
  374. package/dist/server/mcp/schema-adapter.d.ts +11 -1
  375. package/dist/server/mcp/schema-adapter.d.ts.map +1 -1
  376. package/dist/server/mcp/schema-adapter.js +126 -7
  377. package/dist/server/mcp/schema-adapter.js.map +1 -1
  378. package/dist/server/mcp/server.d.ts +3 -3
  379. package/dist/server/mcp/server.d.ts.map +1 -1
  380. package/dist/server/mcp/server.js +114 -30
  381. package/dist/server/mcp/server.js.map +1 -1
  382. package/dist/server/mcp/service.d.ts +6 -2
  383. package/dist/server/mcp/service.d.ts.map +1 -1
  384. package/dist/server/mcp/service.js +138 -36
  385. package/dist/server/mcp/service.js.map +1 -1
  386. package/dist/server/mcp/stdio-transport.d.ts +23 -0
  387. package/dist/server/mcp/stdio-transport.d.ts.map +1 -0
  388. package/dist/server/mcp/stdio-transport.js +101 -0
  389. package/dist/server/mcp/stdio-transport.js.map +1 -0
  390. package/dist/server/mcp/types.d.ts +133 -8
  391. package/dist/server/mcp/types.d.ts.map +1 -1
  392. package/dist/server/routes/api.d.ts.map +1 -1
  393. package/dist/server/routes/api.js +11 -2
  394. package/dist/server/routes/api.js.map +1 -1
  395. package/docs/AI_ASSISTANT_SETUP.md +112 -0
  396. package/docs/API.md +170 -0
  397. package/docs/CONFIGURATION.md +141 -0
  398. package/docs/DEVELOPMENT.md +96 -0
  399. package/docs/GETTING-STARTED.md +114 -0
  400. package/docs/SETUP_GUIDE.md +49 -0
  401. package/docs/TESTING.md +81 -0
  402. package/docs/ai-guide/OUTPUT.md +51 -8
  403. package/docs/backlog.md +232 -144
  404. package/docs/brainstorms/2026-05-10-agent-effectiveness-validation-requirements.md +112 -0
  405. package/docs/generated/phase-58/subagent-evidence/claude-hook-example.json +15 -0
  406. package/docs/generated/phase-58/subagent-evidence/claude-session.md +146 -0
  407. package/docs/generated/phase-58/subagent-evidence/claude-subagent.json +28 -0
  408. package/docs/generated/phase-58/subagent-evidence/codex-agent-example.toml +19 -0
  409. package/docs/generated/phase-58/subagent-evidence/codex-session.md +150 -0
  410. package/docs/generated/phase-58/subagent-evidence/codex-subagent.json +20 -0
  411. package/docs/generated/phase-58/subagent-evidence/negative-no-retrieval.json +12 -0
  412. package/docs/generated/phase-58/subagent-evidence/verification-manifest.json +19 -0
  413. package/docs/ideation/2026-05-02-subagent-environment-contract-injection-ideation.md +183 -0
  414. package/docs/ideation/2026-05-04-subagent-hooks-deep-dive-ideation.md +133 -0
  415. package/docs/ideation/2026-05-10-agent-effectiveness-validation-ideation.md +219 -0
  416. package/package.json +8 -3
  417. package/scripts/copy-build-assets.mjs +23 -0
  418. package/scripts/hooks/templates/pre-commit +33 -2
  419. package/scripts/tests/test_rule_control_workflow.py +15 -1
  420. package/scripts/verify-subagent-env-contract.mjs +279 -0
  421. package/dist/parser/implementations/tree-sitter-parser.d.ts +0 -60
  422. package/dist/parser/implementations/tree-sitter-parser.d.ts.map +0 -1
  423. package/dist/parser/implementations/tree-sitter-parser.js +0 -380
  424. package/dist/parser/implementations/tree-sitter-parser.js.map +0 -1
@@ -1,1113 +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
7
  import { resolveOutputMode, renderOutput, createProgressEmitter, formatError } from '../output/index.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
- /**
1109
- * 解析 CLI 参数
1110
- */
8
+ import { AnalyzeCommand, AnalyzeErrorCode, ERROR_MESSAGES, formatAnalyzeHuman, } from '../../execution/contract-tools/index.js';
1111
9
  function normalizeStringArray(value) {
1112
10
  if (typeof value === 'string') {
1113
11
  return [value];
@@ -1124,8 +22,7 @@ export function parseAnalyzeArgs(argv) {
1124
22
  allowPositionals: true,
1125
23
  options: ANALYZE_PARSE_OPTIONS,
1126
24
  });
1127
- // 合并位置参数和 --targets 参数作为 targets
1128
- const positionalTargets = positionals?.filter(p => !p.startsWith('-')) || [];
25
+ const positionalTargets = positionals?.filter(position => !position.startsWith('-')) ?? [];
1129
26
  const explicitTargets = normalizeStringArray(values.targets);
1130
27
  const allTargets = [...explicitTargets, ...positionalTargets];
1131
28
  const keywords = normalizeStringArray(values.keywords);
@@ -1134,7 +31,7 @@ export function parseAnalyzeArgs(argv) {
1134
31
  targets: allTargets.length > 0 ? allTargets : undefined,
1135
32
  keywords: keywords.length > 0 ? keywords : undefined,
1136
33
  scope: values.scope,
1137
- topK: values.topK ? parseInt(values.topK, 10) : undefined,
34
+ topK: values.topK ? Number.parseInt(values.topK, 10) : undefined,
1138
35
  includeTests: values['include-tests'],
1139
36
  includeGitHistory: values['include-git-history'],
1140
37
  json: values.json,
@@ -1147,70 +44,24 @@ export function parseAnalyzeArgs(argv) {
1147
44
  return {};
1148
45
  }
1149
46
  }
1150
- /**
1151
- * Human-readable renderer for analyze output (chalk + padEnd table pattern)
1152
- */
1153
- function formatAnalyzeHuman(output) {
1154
- const lines = [];
1155
- // Warnings
1156
- for (const warning of output.warnings || []) {
1157
- lines.push(chalk.yellow(`Warning: ${warning.message}`));
1158
- }
1159
- // Header
1160
- const intentLabel = output.intent?.toUpperCase() || 'ANALYSIS';
1161
- lines.push(chalk.bold(`\n${intentLabel} Analysis Results\n`));
1162
- // Table header
1163
- const TYPE_WIDTH = 12;
1164
- const NAME_WIDTH = 30;
1165
- const PATH_WIDTH = 40;
1166
- const header = 'TYPE'.padEnd(TYPE_WIDTH) +
1167
- 'NAME'.padEnd(NAME_WIDTH) +
1168
- 'PATH'.padEnd(PATH_WIDTH) +
1169
- 'RELEVANCE';
1170
- lines.push(header);
1171
- lines.push('-'.repeat(header.length));
1172
- // Data rows
1173
- for (const result of output.results || []) {
1174
- const type = (result.type || '').padEnd(TYPE_WIDTH);
1175
- const name = (result.id || '').substring(0, NAME_WIDTH - 1).padEnd(NAME_WIDTH);
1176
- const lineInfo = result.location?.line ? `:${result.location.line}` : '';
1177
- const filePath = `${result.file}${lineInfo}`.substring(0, PATH_WIDTH - 1).padEnd(PATH_WIDTH);
1178
- const relevance = `${(result.relevance * 100).toFixed(1)}%`;
1179
- lines.push(`${type}${name}${filePath}${relevance}`);
1180
- }
1181
- // Summary
1182
- if (output.results.length > 0) {
1183
- lines.push('');
1184
- }
1185
- lines.push(chalk.gray(`Tools: ${output.tool}, Confidence: ${output.confidence.level} (${output.confidence.score})`));
1186
- return lines.join('\n');
1187
- }
1188
- /**
1189
- * CLI 入口函数
1190
- */
1191
47
  export async function analyzeCommand(argv) {
1192
- // 过滤掉 'analyze' 命令名
1193
48
  const filteredArgv = argv.filter(arg => arg !== 'analyze');
1194
49
  const args = parseAnalyzeArgs(filteredArgv);
1195
- // 显示帮助
1196
50
  if (args.intent === 'help' || !args.intent) {
1197
- printHelp();
51
+ console.log(getAnalyzeHelpText());
1198
52
  return;
1199
53
  }
1200
- // Resolve output mode: --human/--json/no-flag = TTY auto-detect
1201
54
  const mode = resolveOutputMode({ json: args.json, human: args.human });
1202
55
  const progress = createProgressEmitter(mode, 'Analyzing...');
1203
56
  try {
1204
57
  progress.update(10, 'Starting analysis...');
1205
- const command = new AnalyzeCommand(args);
1206
- const output = await command.execute();
1207
- // If structured mode, strip content field from results
58
+ const output = await new AnalyzeCommand(args).execute();
1208
59
  let data = output;
1209
60
  if (args.structured) {
1210
61
  const structuredOutput = JSON.parse(JSON.stringify(output));
1211
62
  if (structuredOutput.results) {
1212
- structuredOutput.results = structuredOutput.results.map(r => {
1213
- const { content, ...rest } = r;
63
+ structuredOutput.results = structuredOutput.results.map(result => {
64
+ const { content, ...rest } = result;
1214
65
  void content;
1215
66
  return rest;
1216
67
  });
@@ -1226,10 +77,5 @@ export async function analyzeCommand(argv) {
1226
77
  process.exitCode = 1;
1227
78
  }
1228
79
  }
1229
- /**
1230
- * 打印帮助信息
1231
- */
1232
- function printHelp() {
1233
- console.log(getAnalyzeHelpText());
1234
- }
80
+ export { AnalyzeCommand, AnalyzeErrorCode, ERROR_MESSAGES };
1235
81
  //# sourceMappingURL=analyze.js.map