opkg 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1546) hide show
  1. package/bin/openpackage +1 -1
  2. package/dist/core/install/preprocessing/base-resolver.js +37 -17
  3. package/dist/core/install/preprocessing/base-resolver.js.map +1 -1
  4. package/dist/core/install/preprocessing/index.js +1 -1
  5. package/dist/core/install/preprocessing/index.js.map +1 -1
  6. package/dist/core/install/resolution/installation-planner.js +7 -22
  7. package/dist/core/install/resolution/installation-planner.js.map +1 -1
  8. package/dist/core/install/unified/context-builders.js +25 -5
  9. package/dist/core/install/unified/context-builders.js.map +1 -1
  10. package/dist/utils/git-clone.js +9 -3
  11. package/dist/utils/git-clone.js.map +1 -1
  12. package/package.json +10 -10
  13. package/packages/cli/bin/openpackage +5 -0
  14. package/packages/cli/dist/add-AFORN4DK.js +624 -0
  15. package/packages/cli/dist/add-AFORN4DK.js.map +7 -0
  16. package/packages/cli/dist/add-TASDXRAL.js +608 -0
  17. package/packages/cli/dist/add-TASDXRAL.js.map +7 -0
  18. package/packages/cli/dist/chunk-2NGVXUNT.js +108 -0
  19. package/packages/cli/dist/chunk-2NGVXUNT.js.map +7 -0
  20. package/packages/cli/dist/chunk-2PMMVTRN.js +44 -0
  21. package/packages/cli/dist/chunk-2PMMVTRN.js.map +7 -0
  22. package/packages/cli/dist/chunk-3RORRNJN.js +31 -0
  23. package/packages/cli/dist/chunk-3RORRNJN.js.map +7 -0
  24. package/packages/cli/dist/chunk-4TCVCEPB.js +274 -0
  25. package/packages/cli/dist/chunk-4TCVCEPB.js.map +7 -0
  26. package/packages/cli/dist/chunk-5EFWGD33.js +70 -0
  27. package/packages/cli/dist/chunk-5EFWGD33.js.map +7 -0
  28. package/packages/cli/dist/chunk-5HSDD3SL.js +100 -0
  29. package/packages/cli/dist/chunk-5HSDD3SL.js.map +7 -0
  30. package/packages/cli/dist/chunk-5XEDHH4X.js +371 -0
  31. package/packages/cli/dist/chunk-5XEDHH4X.js.map +7 -0
  32. package/packages/cli/dist/chunk-6HEBGHXK.js +302 -0
  33. package/packages/cli/dist/chunk-6HEBGHXK.js.map +7 -0
  34. package/packages/cli/dist/chunk-6YZNE3MU.js +29 -0
  35. package/packages/cli/dist/chunk-6YZNE3MU.js.map +7 -0
  36. package/packages/cli/dist/chunk-A6ISKBNM.js +48 -0
  37. package/packages/cli/dist/chunk-A6ISKBNM.js.map +7 -0
  38. package/packages/cli/dist/chunk-AMHDY5PC.js +31 -0
  39. package/packages/cli/dist/chunk-AMHDY5PC.js.map +7 -0
  40. package/packages/cli/dist/chunk-ATYT3SA6.js +172 -0
  41. package/packages/cli/dist/chunk-ATYT3SA6.js.map +7 -0
  42. package/packages/cli/dist/chunk-AUYRGQIJ.js +99 -0
  43. package/packages/cli/dist/chunk-AUYRGQIJ.js.map +7 -0
  44. package/packages/cli/dist/chunk-BCYZDID6.js +60 -0
  45. package/packages/cli/dist/chunk-BCYZDID6.js.map +7 -0
  46. package/packages/cli/dist/chunk-BGSNTCZP.js +172 -0
  47. package/packages/cli/dist/chunk-BGSNTCZP.js.map +7 -0
  48. package/packages/cli/dist/chunk-BM66UY63.js +413 -0
  49. package/packages/cli/dist/chunk-BM66UY63.js.map +7 -0
  50. package/packages/cli/dist/chunk-BN3JSWOU.js +371 -0
  51. package/packages/cli/dist/chunk-BN3JSWOU.js.map +7 -0
  52. package/packages/cli/dist/chunk-BRRTF7CU.js +99 -0
  53. package/packages/cli/dist/chunk-BRRTF7CU.js.map +7 -0
  54. package/packages/cli/dist/chunk-CBLKT6WA.js +48 -0
  55. package/packages/cli/dist/chunk-CBLKT6WA.js.map +7 -0
  56. package/packages/cli/dist/chunk-DFRQACQV.js +1168 -0
  57. package/packages/cli/dist/chunk-DFRQACQV.js.map +7 -0
  58. package/packages/cli/dist/chunk-DN7RINDJ.js +975 -0
  59. package/packages/cli/dist/chunk-DN7RINDJ.js.map +7 -0
  60. package/packages/cli/dist/chunk-E2DVTD75.js +196 -0
  61. package/packages/cli/dist/chunk-E2DVTD75.js.map +7 -0
  62. package/packages/cli/dist/chunk-E2HYZWNV.js +32 -0
  63. package/packages/cli/dist/chunk-E2HYZWNV.js.map +7 -0
  64. package/packages/cli/dist/chunk-EGAP6GNA.js +31 -0
  65. package/packages/cli/dist/chunk-EGAP6GNA.js.map +7 -0
  66. package/packages/cli/dist/chunk-ELCB4RC2.js +1121 -0
  67. package/packages/cli/dist/chunk-ELCB4RC2.js.map +7 -0
  68. package/packages/cli/dist/chunk-FRYA3JAQ.js +48 -0
  69. package/packages/cli/dist/chunk-FRYA3JAQ.js.map +7 -0
  70. package/packages/cli/dist/chunk-GJWX5XPU.js +274 -0
  71. package/packages/cli/dist/chunk-GJWX5XPU.js.map +7 -0
  72. package/packages/cli/dist/chunk-GKEHDSL4.js +732 -0
  73. package/packages/cli/dist/chunk-GKEHDSL4.js.map +7 -0
  74. package/packages/cli/dist/chunk-GP5FJYSS.js +186 -0
  75. package/packages/cli/dist/chunk-GP5FJYSS.js.map +7 -0
  76. package/packages/cli/dist/chunk-GXPSKN7J.js +538 -0
  77. package/packages/cli/dist/chunk-GXPSKN7J.js.map +7 -0
  78. package/packages/cli/dist/chunk-GZIV2HZM.js +195 -0
  79. package/packages/cli/dist/chunk-GZIV2HZM.js.map +7 -0
  80. package/packages/cli/dist/chunk-IBIYIU3K.js +23 -0
  81. package/packages/cli/dist/chunk-IBIYIU3K.js.map +7 -0
  82. package/packages/cli/dist/chunk-ID4SVDQZ.js +61 -0
  83. package/packages/cli/dist/chunk-ID4SVDQZ.js.map +7 -0
  84. package/packages/cli/dist/chunk-IVM4PQP4.js +568 -0
  85. package/packages/cli/dist/chunk-IVM4PQP4.js.map +7 -0
  86. package/packages/cli/dist/chunk-IXOEIRDT.js +1028 -0
  87. package/packages/cli/dist/chunk-IXOEIRDT.js.map +7 -0
  88. package/packages/cli/dist/chunk-J2OQQZFA.js +48 -0
  89. package/packages/cli/dist/chunk-J2OQQZFA.js.map +7 -0
  90. package/packages/cli/dist/chunk-J4IFFBLP.js +103 -0
  91. package/packages/cli/dist/chunk-J4IFFBLP.js.map +7 -0
  92. package/packages/cli/dist/chunk-K3FCWE4I.js +1168 -0
  93. package/packages/cli/dist/chunk-K3FCWE4I.js.map +7 -0
  94. package/packages/cli/dist/chunk-KGBDKY5V.js +113 -0
  95. package/packages/cli/dist/chunk-KGBDKY5V.js.map +7 -0
  96. package/packages/cli/dist/chunk-LVPD45D5.js +61 -0
  97. package/packages/cli/dist/chunk-LVPD45D5.js.map +7 -0
  98. package/packages/cli/dist/chunk-MLYYVOS3.js +498 -0
  99. package/packages/cli/dist/chunk-MLYYVOS3.js.map +7 -0
  100. package/packages/cli/dist/chunk-OFM3UWJJ.js +190 -0
  101. package/packages/cli/dist/chunk-OFM3UWJJ.js.map +7 -0
  102. package/packages/cli/dist/chunk-PXL2RUMX.js +14 -0
  103. package/packages/cli/dist/chunk-PXL2RUMX.js.map +7 -0
  104. package/packages/cli/dist/chunk-Q2N6OZJC.js +258 -0
  105. package/packages/cli/dist/chunk-Q2N6OZJC.js.map +7 -0
  106. package/packages/cli/dist/chunk-QQFDQPT3.js +86 -0
  107. package/packages/cli/dist/chunk-QQFDQPT3.js.map +7 -0
  108. package/packages/cli/dist/chunk-QTQYI4L5.js +155 -0
  109. package/packages/cli/dist/chunk-QTQYI4L5.js.map +7 -0
  110. package/packages/cli/dist/chunk-QURLGVA4.js +74 -0
  111. package/packages/cli/dist/chunk-QURLGVA4.js.map +7 -0
  112. package/packages/cli/dist/chunk-S47F4OG4.js +173 -0
  113. package/packages/cli/dist/chunk-S47F4OG4.js.map +7 -0
  114. package/packages/cli/dist/chunk-S6OARUVQ.js +376 -0
  115. package/packages/cli/dist/chunk-S6OARUVQ.js.map +7 -0
  116. package/packages/cli/dist/chunk-SHKYQQJJ.js +11 -0
  117. package/packages/cli/dist/chunk-SHKYQQJJ.js.map +7 -0
  118. package/packages/cli/dist/chunk-SSHWUJEG.js +788 -0
  119. package/packages/cli/dist/chunk-SSHWUJEG.js.map +7 -0
  120. package/packages/cli/dist/chunk-SVEFLCC2.js +25 -0
  121. package/packages/cli/dist/chunk-SVEFLCC2.js.map +7 -0
  122. package/packages/cli/dist/chunk-TFQ4JBVO.js +222 -0
  123. package/packages/cli/dist/chunk-TFQ4JBVO.js.map +7 -0
  124. package/packages/cli/dist/chunk-UDAWJRKD.js +63 -0
  125. package/packages/cli/dist/chunk-UDAWJRKD.js.map +7 -0
  126. package/packages/cli/dist/chunk-UR6VJWA3.js +108 -0
  127. package/packages/cli/dist/chunk-UR6VJWA3.js.map +7 -0
  128. package/packages/cli/dist/chunk-UVWARZQC.js +52 -0
  129. package/packages/cli/dist/chunk-UVWARZQC.js.map +7 -0
  130. package/packages/cli/dist/chunk-V2JKF46L.js +61 -0
  131. package/packages/cli/dist/chunk-V2JKF46L.js.map +7 -0
  132. package/packages/cli/dist/chunk-V5OW4YEB.js +92 -0
  133. package/packages/cli/dist/chunk-V5OW4YEB.js.map +7 -0
  134. package/packages/cli/dist/chunk-VN22A7NW.js +145 -0
  135. package/packages/cli/dist/chunk-VN22A7NW.js.map +7 -0
  136. package/packages/cli/dist/chunk-WQG6LPP3.js +190 -0
  137. package/packages/cli/dist/chunk-WQG6LPP3.js.map +7 -0
  138. package/packages/cli/dist/chunk-XEPVYZO3.js +130 -0
  139. package/packages/cli/dist/chunk-XEPVYZO3.js.map +7 -0
  140. package/packages/cli/dist/chunk-YMKK4XPN.js +38 -0
  141. package/packages/cli/dist/chunk-YMKK4XPN.js.map +7 -0
  142. package/packages/cli/dist/chunk-YXLKLL3V.js +253 -0
  143. package/packages/cli/dist/chunk-YXLKLL3V.js.map +7 -0
  144. package/packages/cli/dist/configure-CBKHH5ZC.js +107 -0
  145. package/packages/cli/dist/configure-CBKHH5ZC.js.map +7 -0
  146. package/packages/cli/dist/configure-IW22RQIX.js +107 -0
  147. package/packages/cli/dist/configure-IW22RQIX.js.map +7 -0
  148. package/packages/cli/dist/errors-X5KO3GTP.js +23 -0
  149. package/packages/cli/dist/errors-X5KO3GTP.js.map +7 -0
  150. package/packages/cli/dist/file-format-detector-DEAVQPAT.js +22 -0
  151. package/packages/cli/dist/file-format-detector-DEAVQPAT.js.map +7 -0
  152. package/packages/cli/dist/format-distribution-analyzer-MIFCFIAJ.js +91 -0
  153. package/packages/cli/dist/format-distribution-analyzer-MIFCFIAJ.js.map +7 -0
  154. package/packages/cli/dist/index.js +212 -0
  155. package/packages/cli/dist/index.js.map +7 -0
  156. package/packages/cli/dist/install-WS7D32ND.js +7694 -0
  157. package/packages/cli/dist/install-WS7D32ND.js.map +7 -0
  158. package/packages/cli/dist/install-ZR42VB5K.js +7770 -0
  159. package/packages/cli/dist/install-ZR42VB5K.js.map +7 -0
  160. package/packages/cli/dist/list-GSBJJXQT.js +327 -0
  161. package/packages/cli/dist/list-GSBJJXQT.js.map +7 -0
  162. package/packages/cli/dist/list-L7DYJYXO.js +126 -0
  163. package/packages/cli/dist/list-L7DYJYXO.js.map +7 -0
  164. package/packages/cli/dist/logger-WHZJRF6G.js +8 -0
  165. package/packages/cli/dist/logger-WHZJRF6G.js.map +7 -0
  166. package/packages/cli/dist/login-5KPCJJYE.js +121 -0
  167. package/packages/cli/dist/login-5KPCJJYE.js.map +7 -0
  168. package/packages/cli/dist/login-TUPFY4I2.js +151 -0
  169. package/packages/cli/dist/login-TUPFY4I2.js.map +7 -0
  170. package/packages/cli/dist/logout-FCOJT6KE.js +40 -0
  171. package/packages/cli/dist/logout-FCOJT6KE.js.map +7 -0
  172. package/packages/cli/dist/logout-GTYZM3NQ.js +40 -0
  173. package/packages/cli/dist/logout-GTYZM3NQ.js.map +7 -0
  174. package/packages/cli/dist/new-FMYTAQD2.js +277 -0
  175. package/packages/cli/dist/new-FMYTAQD2.js.map +7 -0
  176. package/packages/cli/dist/new-UJ3HI5MZ.js +275 -0
  177. package/packages/cli/dist/new-UJ3HI5MZ.js.map +7 -0
  178. package/packages/cli/dist/package-marker-detector-JELOHCL7.js +80 -0
  179. package/packages/cli/dist/package-marker-detector-JELOHCL7.js.map +7 -0
  180. package/packages/cli/dist/package-yml-33CZZC3T.js +16 -0
  181. package/packages/cli/dist/package-yml-33CZZC3T.js.map +7 -0
  182. package/packages/cli/dist/plugin-naming-Z2RD7XOF.js +29 -0
  183. package/packages/cli/dist/plugin-naming-Z2RD7XOF.js.map +7 -0
  184. package/packages/cli/dist/publish-NHZEF7NP.js +621 -0
  185. package/packages/cli/dist/publish-NHZEF7NP.js.map +7 -0
  186. package/packages/cli/dist/publish-VXEPM3TI.js +619 -0
  187. package/packages/cli/dist/publish-VXEPM3TI.js.map +7 -0
  188. package/packages/cli/dist/remove-S5DT4F7A.js +508 -0
  189. package/packages/cli/dist/remove-S5DT4F7A.js.map +7 -0
  190. package/packages/cli/dist/remove-Z5YY2PZZ.js +542 -0
  191. package/packages/cli/dist/remove-Z5YY2PZZ.js.map +7 -0
  192. package/packages/cli/dist/resource-discoverer-QF3Q4QAE.js +17 -0
  193. package/packages/cli/dist/resource-discoverer-QF3Q4QAE.js.map +7 -0
  194. package/packages/cli/dist/save-RRBXRROU.js +1726 -0
  195. package/packages/cli/dist/save-RRBXRROU.js.map +7 -0
  196. package/packages/cli/dist/save-YHCXQDLA.js +1728 -0
  197. package/packages/cli/dist/save-YHCXQDLA.js.map +7 -0
  198. package/packages/cli/dist/search-65S4VUKZ.js +157 -0
  199. package/packages/cli/dist/search-65S4VUKZ.js.map +7 -0
  200. package/packages/cli/dist/search-RW5EX76L.js +157 -0
  201. package/packages/cli/dist/search-RW5EX76L.js.map +7 -0
  202. package/packages/cli/dist/set-CGYGCM3C.js +251 -0
  203. package/packages/cli/dist/set-CGYGCM3C.js.map +7 -0
  204. package/packages/cli/dist/set-SGEPTBDB.js +251 -0
  205. package/packages/cli/dist/set-SGEPTBDB.js.map +7 -0
  206. package/packages/cli/dist/uninstall-7EJCVTLD.js +868 -0
  207. package/packages/cli/dist/uninstall-7EJCVTLD.js.map +7 -0
  208. package/packages/cli/dist/uninstall-UBZTRBEK.js +540 -0
  209. package/packages/cli/dist/uninstall-UBZTRBEK.js.map +7 -0
  210. package/packages/cli/dist/unpublish-V4PMWZVD.js +243 -0
  211. package/packages/cli/dist/unpublish-V4PMWZVD.js.map +7 -0
  212. package/packages/cli/dist/unpublish-YMHUZ4EZ.js +243 -0
  213. package/packages/cli/dist/unpublish-YMHUZ4EZ.js.map +7 -0
  214. package/packages/cli/dist/view-62MJAH7O.js +452 -0
  215. package/packages/cli/dist/view-62MJAH7O.js.map +7 -0
  216. package/packages/cli/dist/view-TVWVUS3B.js +488 -0
  217. package/packages/cli/dist/view-TVWVUS3B.js.map +7 -0
  218. package/packages/cli/package.json +45 -0
  219. package/packages/core/dist/constants/index.d.ts +151 -0
  220. package/packages/core/dist/constants/index.d.ts.map +1 -0
  221. package/packages/core/dist/constants/index.js +155 -0
  222. package/packages/core/dist/constants/index.js.map +1 -0
  223. package/packages/core/dist/constants/workspace.d.ts +3 -0
  224. package/packages/core/dist/constants/workspace.d.ts.map +1 -0
  225. package/packages/core/dist/constants/workspace.js +9 -0
  226. package/packages/core/dist/constants/workspace.js.map +1 -0
  227. package/packages/core/dist/core/add/add-conflict-handler.d.ts +17 -0
  228. package/packages/core/dist/core/add/add-conflict-handler.d.ts.map +1 -0
  229. package/packages/core/dist/core/add/add-conflict-handler.js +107 -0
  230. package/packages/core/dist/core/add/add-conflict-handler.js.map +1 -0
  231. package/packages/core/dist/core/add/add-dependency-flow.d.ts +14 -0
  232. package/packages/core/dist/core/add/add-dependency-flow.d.ts.map +1 -0
  233. package/packages/core/dist/core/add/add-dependency-flow.js +93 -0
  234. package/packages/core/dist/core/add/add-dependency-flow.js.map +1 -0
  235. package/packages/core/dist/core/add/add-input-classifier.d.ts +34 -0
  236. package/packages/core/dist/core/add/add-input-classifier.d.ts.map +1 -0
  237. package/packages/core/dist/core/add/add-input-classifier.js +159 -0
  238. package/packages/core/dist/core/add/add-input-classifier.js.map +1 -0
  239. package/packages/core/dist/core/add/add-orchestrator.d.ts +40 -0
  240. package/packages/core/dist/core/add/add-orchestrator.d.ts.map +1 -0
  241. package/packages/core/dist/core/add/add-orchestrator.js +81 -0
  242. package/packages/core/dist/core/add/add-orchestrator.js.map +1 -0
  243. package/packages/core/dist/core/add/add-to-source-pipeline.d.ts +22 -0
  244. package/packages/core/dist/core/add/add-to-source-pipeline.d.ts.map +1 -0
  245. package/packages/core/dist/core/add/add-to-source-pipeline.js +164 -0
  246. package/packages/core/dist/core/add/add-to-source-pipeline.js.map +1 -0
  247. package/packages/core/dist/core/add/package-index-updater.d.ts +24 -0
  248. package/packages/core/dist/core/add/package-index-updater.d.ts.map +1 -0
  249. package/packages/core/dist/core/add/package-index-updater.js +324 -0
  250. package/packages/core/dist/core/add/package-index-updater.js.map +1 -0
  251. package/packages/core/dist/core/add/platform-path-transformer.d.ts +7 -0
  252. package/packages/core/dist/core/add/platform-path-transformer.d.ts.map +1 -0
  253. package/packages/core/dist/core/add/platform-path-transformer.js +50 -0
  254. package/packages/core/dist/core/add/platform-path-transformer.js.map +1 -0
  255. package/packages/core/dist/core/add/source-collector.d.ts +12 -0
  256. package/packages/core/dist/core/add/source-collector.d.ts.map +1 -0
  257. package/packages/core/dist/core/add/source-collector.js +76 -0
  258. package/packages/core/dist/core/add/source-collector.js.map +1 -0
  259. package/packages/core/dist/core/api-keys.d.ts +21 -0
  260. package/packages/core/dist/core/api-keys.d.ts.map +1 -0
  261. package/packages/core/dist/core/api-keys.js +29 -0
  262. package/packages/core/dist/core/api-keys.js.map +1 -0
  263. package/packages/core/dist/core/auth.d.ts +32 -0
  264. package/packages/core/dist/core/auth.d.ts.map +1 -0
  265. package/packages/core/dist/core/auth.js +132 -0
  266. package/packages/core/dist/core/auth.js.map +1 -0
  267. package/packages/core/dist/core/cache-manager.d.ts +22 -0
  268. package/packages/core/dist/core/cache-manager.d.ts.map +1 -0
  269. package/packages/core/dist/core/cache-manager.js +104 -0
  270. package/packages/core/dist/core/cache-manager.js.map +1 -0
  271. package/packages/core/dist/core/config.d.ts +64 -0
  272. package/packages/core/dist/core/config.d.ts.map +1 -0
  273. package/packages/core/dist/core/config.js +189 -0
  274. package/packages/core/dist/core/config.js.map +1 -0
  275. package/packages/core/dist/core/conversion-context/creation.d.ts +50 -0
  276. package/packages/core/dist/core/conversion-context/creation.d.ts.map +1 -0
  277. package/packages/core/dist/core/conversion-context/creation.js +153 -0
  278. package/packages/core/dist/core/conversion-context/creation.js.map +1 -0
  279. package/packages/core/dist/core/conversion-context/index.d.ts +12 -0
  280. package/packages/core/dist/core/conversion-context/index.d.ts.map +1 -0
  281. package/packages/core/dist/core/conversion-context/index.js +13 -0
  282. package/packages/core/dist/core/conversion-context/index.js.map +1 -0
  283. package/packages/core/dist/core/conversion-context/serialization.d.ts +38 -0
  284. package/packages/core/dist/core/conversion-context/serialization.d.ts.map +1 -0
  285. package/packages/core/dist/core/conversion-context/serialization.js +129 -0
  286. package/packages/core/dist/core/conversion-context/serialization.js.map +1 -0
  287. package/packages/core/dist/core/conversion-context/validation.d.ts +49 -0
  288. package/packages/core/dist/core/conversion-context/validation.d.ts.map +1 -0
  289. package/packages/core/dist/core/conversion-context/validation.js +200 -0
  290. package/packages/core/dist/core/conversion-context/validation.js.map +1 -0
  291. package/packages/core/dist/core/dependency-resolver/display.d.ts +10 -0
  292. package/packages/core/dist/core/dependency-resolver/display.d.ts.map +1 -0
  293. package/packages/core/dist/core/dependency-resolver/display.js +32 -0
  294. package/packages/core/dist/core/dependency-resolver/display.js.map +1 -0
  295. package/packages/core/dist/core/dependency-resolver/index.d.ts +19 -0
  296. package/packages/core/dist/core/dependency-resolver/index.d.ts.map +1 -0
  297. package/packages/core/dist/core/dependency-resolver/index.js +22 -0
  298. package/packages/core/dist/core/dependency-resolver/index.js.map +1 -0
  299. package/packages/core/dist/core/dependency-resolver/prompts.d.ts +9 -0
  300. package/packages/core/dist/core/dependency-resolver/prompts.d.ts.map +1 -0
  301. package/packages/core/dist/core/dependency-resolver/prompts.js +12 -0
  302. package/packages/core/dist/core/dependency-resolver/prompts.js.map +1 -0
  303. package/packages/core/dist/core/dependency-resolver/resolver.d.ts +36 -0
  304. package/packages/core/dist/core/dependency-resolver/resolver.d.ts.map +1 -0
  305. package/packages/core/dist/core/dependency-resolver/resolver.js +672 -0
  306. package/packages/core/dist/core/dependency-resolver/resolver.js.map +1 -0
  307. package/packages/core/dist/core/dependency-resolver/tree-utils.d.ts +14 -0
  308. package/packages/core/dist/core/dependency-resolver/tree-utils.d.ts.map +1 -0
  309. package/packages/core/dist/core/dependency-resolver/tree-utils.js +96 -0
  310. package/packages/core/dist/core/dependency-resolver/tree-utils.js.map +1 -0
  311. package/packages/core/dist/core/dependency-resolver/types.d.ts +52 -0
  312. package/packages/core/dist/core/dependency-resolver/types.d.ts.map +1 -0
  313. package/packages/core/dist/core/dependency-resolver/types.js +2 -0
  314. package/packages/core/dist/core/dependency-resolver/types.js.map +1 -0
  315. package/packages/core/dist/core/dependency-resolver.d.ts +14 -0
  316. package/packages/core/dist/core/dependency-resolver.d.ts.map +1 -0
  317. package/packages/core/dist/core/dependency-resolver.js +15 -0
  318. package/packages/core/dist/core/dependency-resolver.js.map +1 -0
  319. package/packages/core/dist/core/device-auth.d.ts +25 -0
  320. package/packages/core/dist/core/device-auth.d.ts.map +1 -0
  321. package/packages/core/dist/core/device-auth.js +95 -0
  322. package/packages/core/dist/core/device-auth.js.map +1 -0
  323. package/packages/core/dist/core/directory.d.ts +74 -0
  324. package/packages/core/dist/core/directory.d.ts.map +1 -0
  325. package/packages/core/dist/core/directory.js +203 -0
  326. package/packages/core/dist/core/directory.js.map +1 -0
  327. package/packages/core/dist/core/discovery/file-discovery.d.ts +17 -0
  328. package/packages/core/dist/core/discovery/file-discovery.d.ts.map +1 -0
  329. package/packages/core/dist/core/discovery/file-discovery.js +61 -0
  330. package/packages/core/dist/core/discovery/file-discovery.js.map +1 -0
  331. package/packages/core/dist/core/discovery/platform-files-discovery.d.ts +3 -0
  332. package/packages/core/dist/core/discovery/platform-files-discovery.d.ts.map +1 -0
  333. package/packages/core/dist/core/discovery/platform-files-discovery.js +101 -0
  334. package/packages/core/dist/core/discovery/platform-files-discovery.js.map +1 -0
  335. package/packages/core/dist/core/execution-context.d.ts +47 -0
  336. package/packages/core/dist/core/execution-context.d.ts.map +1 -0
  337. package/packages/core/dist/core/execution-context.js +146 -0
  338. package/packages/core/dist/core/execution-context.js.map +1 -0
  339. package/packages/core/dist/core/flows/flow-execution-coordinator.d.ts +87 -0
  340. package/packages/core/dist/core/flows/flow-execution-coordinator.d.ts.map +1 -0
  341. package/packages/core/dist/core/flows/flow-execution-coordinator.js +294 -0
  342. package/packages/core/dist/core/flows/flow-execution-coordinator.js.map +1 -0
  343. package/packages/core/dist/core/flows/flow-executor.d.ts +190 -0
  344. package/packages/core/dist/core/flows/flow-executor.d.ts.map +1 -0
  345. package/packages/core/dist/core/flows/flow-executor.js +1138 -0
  346. package/packages/core/dist/core/flows/flow-executor.js.map +1 -0
  347. package/packages/core/dist/core/flows/flow-key-extractor.d.ts +40 -0
  348. package/packages/core/dist/core/flows/flow-key-extractor.d.ts.map +1 -0
  349. package/packages/core/dist/core/flows/flow-key-extractor.js +101 -0
  350. package/packages/core/dist/core/flows/flow-key-extractor.js.map +1 -0
  351. package/packages/core/dist/core/flows/flow-key-mapper.d.ts +27 -0
  352. package/packages/core/dist/core/flows/flow-key-mapper.d.ts.map +1 -0
  353. package/packages/core/dist/core/flows/flow-key-mapper.js +283 -0
  354. package/packages/core/dist/core/flows/flow-key-mapper.js.map +1 -0
  355. package/packages/core/dist/core/flows/flow-source-discovery.d.ts +106 -0
  356. package/packages/core/dist/core/flows/flow-source-discovery.d.ts.map +1 -0
  357. package/packages/core/dist/core/flows/flow-source-discovery.js +311 -0
  358. package/packages/core/dist/core/flows/flow-source-discovery.js.map +1 -0
  359. package/packages/core/dist/core/flows/flow-transforms.d.ts +129 -0
  360. package/packages/core/dist/core/flows/flow-transforms.d.ts.map +1 -0
  361. package/packages/core/dist/core/flows/flow-transforms.js +613 -0
  362. package/packages/core/dist/core/flows/flow-transforms.js.map +1 -0
  363. package/packages/core/dist/core/flows/map-pipeline/context.d.ts +30 -0
  364. package/packages/core/dist/core/flows/map-pipeline/context.d.ts.map +1 -0
  365. package/packages/core/dist/core/flows/map-pipeline/context.js +73 -0
  366. package/packages/core/dist/core/flows/map-pipeline/context.js.map +1 -0
  367. package/packages/core/dist/core/flows/map-pipeline/index.d.ts +48 -0
  368. package/packages/core/dist/core/flows/map-pipeline/index.d.ts.map +1 -0
  369. package/packages/core/dist/core/flows/map-pipeline/index.js +176 -0
  370. package/packages/core/dist/core/flows/map-pipeline/index.js.map +1 -0
  371. package/packages/core/dist/core/flows/map-pipeline/operations/copy.d.ts +32 -0
  372. package/packages/core/dist/core/flows/map-pipeline/operations/copy.d.ts.map +1 -0
  373. package/packages/core/dist/core/flows/map-pipeline/operations/copy.js +104 -0
  374. package/packages/core/dist/core/flows/map-pipeline/operations/copy.js.map +1 -0
  375. package/packages/core/dist/core/flows/map-pipeline/operations/pipe.d.ts +37 -0
  376. package/packages/core/dist/core/flows/map-pipeline/operations/pipe.d.ts.map +1 -0
  377. package/packages/core/dist/core/flows/map-pipeline/operations/pipe.js +70 -0
  378. package/packages/core/dist/core/flows/map-pipeline/operations/pipe.js.map +1 -0
  379. package/packages/core/dist/core/flows/map-pipeline/operations/rename.d.ts +26 -0
  380. package/packages/core/dist/core/flows/map-pipeline/operations/rename.d.ts.map +1 -0
  381. package/packages/core/dist/core/flows/map-pipeline/operations/rename.js +102 -0
  382. package/packages/core/dist/core/flows/map-pipeline/operations/rename.js.map +1 -0
  383. package/packages/core/dist/core/flows/map-pipeline/operations/set.d.ts +24 -0
  384. package/packages/core/dist/core/flows/map-pipeline/operations/set.d.ts.map +1 -0
  385. package/packages/core/dist/core/flows/map-pipeline/operations/set.js +50 -0
  386. package/packages/core/dist/core/flows/map-pipeline/operations/set.js.map +1 -0
  387. package/packages/core/dist/core/flows/map-pipeline/operations/switch.d.ts +31 -0
  388. package/packages/core/dist/core/flows/map-pipeline/operations/switch.d.ts.map +1 -0
  389. package/packages/core/dist/core/flows/map-pipeline/operations/switch.js +84 -0
  390. package/packages/core/dist/core/flows/map-pipeline/operations/switch.js.map +1 -0
  391. package/packages/core/dist/core/flows/map-pipeline/operations/transform.d.ts +22 -0
  392. package/packages/core/dist/core/flows/map-pipeline/operations/transform.d.ts.map +1 -0
  393. package/packages/core/dist/core/flows/map-pipeline/operations/transform.js +576 -0
  394. package/packages/core/dist/core/flows/map-pipeline/operations/transform.js.map +1 -0
  395. package/packages/core/dist/core/flows/map-pipeline/operations/unset.d.ts +27 -0
  396. package/packages/core/dist/core/flows/map-pipeline/operations/unset.d.ts.map +1 -0
  397. package/packages/core/dist/core/flows/map-pipeline/operations/unset.js +65 -0
  398. package/packages/core/dist/core/flows/map-pipeline/operations/unset.js.map +1 -0
  399. package/packages/core/dist/core/flows/map-pipeline/types.d.ts +358 -0
  400. package/packages/core/dist/core/flows/map-pipeline/types.d.ts.map +1 -0
  401. package/packages/core/dist/core/flows/map-pipeline/types.js +8 -0
  402. package/packages/core/dist/core/flows/map-pipeline/types.js.map +1 -0
  403. package/packages/core/dist/core/flows/map-pipeline/utils.d.ts +104 -0
  404. package/packages/core/dist/core/flows/map-pipeline/utils.d.ts.map +1 -0
  405. package/packages/core/dist/core/flows/map-pipeline/utils.js +278 -0
  406. package/packages/core/dist/core/flows/map-pipeline/utils.js.map +1 -0
  407. package/packages/core/dist/core/flows/markdown.d.ts +22 -0
  408. package/packages/core/dist/core/flows/markdown.d.ts.map +1 -0
  409. package/packages/core/dist/core/flows/markdown.js +51 -0
  410. package/packages/core/dist/core/flows/markdown.js.map +1 -0
  411. package/packages/core/dist/core/flows/platform-converter.d.ts +90 -0
  412. package/packages/core/dist/core/flows/platform-converter.d.ts.map +1 -0
  413. package/packages/core/dist/core/flows/platform-converter.js +366 -0
  414. package/packages/core/dist/core/flows/platform-converter.js.map +1 -0
  415. package/packages/core/dist/core/flows/platform-suffix-handler.d.ts +97 -0
  416. package/packages/core/dist/core/flows/platform-suffix-handler.d.ts.map +1 -0
  417. package/packages/core/dist/core/flows/platform-suffix-handler.js +212 -0
  418. package/packages/core/dist/core/flows/platform-suffix-handler.js.map +1 -0
  419. package/packages/core/dist/core/flows/source-resolver.d.ts +99 -0
  420. package/packages/core/dist/core/flows/source-resolver.d.ts.map +1 -0
  421. package/packages/core/dist/core/flows/source-resolver.js +192 -0
  422. package/packages/core/dist/core/flows/source-resolver.js.map +1 -0
  423. package/packages/core/dist/core/flows/switch-resolver.d.ts +48 -0
  424. package/packages/core/dist/core/flows/switch-resolver.d.ts.map +1 -0
  425. package/packages/core/dist/core/flows/switch-resolver.js +205 -0
  426. package/packages/core/dist/core/flows/switch-resolver.js.map +1 -0
  427. package/packages/core/dist/core/git-clone-registry.d.ts +19 -0
  428. package/packages/core/dist/core/git-clone-registry.d.ts.map +1 -0
  429. package/packages/core/dist/core/git-clone-registry.js +88 -0
  430. package/packages/core/dist/core/git-clone-registry.js.map +1 -0
  431. package/packages/core/dist/core/git-clone.d.ts +27 -0
  432. package/packages/core/dist/core/git-clone.d.ts.map +1 -0
  433. package/packages/core/dist/core/git-clone.js +282 -0
  434. package/packages/core/dist/core/git-clone.js.map +1 -0
  435. package/packages/core/dist/core/glob-target-mapping.d.ts +18 -0
  436. package/packages/core/dist/core/glob-target-mapping.d.ts.map +1 -0
  437. package/packages/core/dist/core/glob-target-mapping.js +88 -0
  438. package/packages/core/dist/core/glob-target-mapping.js.map +1 -0
  439. package/packages/core/dist/core/http-client.d.ts +54 -0
  440. package/packages/core/dist/core/http-client.d.ts.map +1 -0
  441. package/packages/core/dist/core/http-client.js +235 -0
  442. package/packages/core/dist/core/http-client.js.map +1 -0
  443. package/packages/core/dist/core/install/ambiguity-prompts.d.ts +46 -0
  444. package/packages/core/dist/core/install/ambiguity-prompts.d.ts.map +1 -0
  445. package/packages/core/dist/core/install/ambiguity-prompts.js +108 -0
  446. package/packages/core/dist/core/install/ambiguity-prompts.js.map +1 -0
  447. package/packages/core/dist/core/install/base-detector.d.ts +50 -0
  448. package/packages/core/dist/core/install/base-detector.d.ts.map +1 -0
  449. package/packages/core/dist/core/install/base-detector.js +312 -0
  450. package/packages/core/dist/core/install/base-detector.js.map +1 -0
  451. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.d.ts +215 -0
  452. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.d.ts.map +1 -0
  453. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.js +599 -0
  454. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.js.map +1 -0
  455. package/packages/core/dist/core/install/convenience-matchers.d.ts +82 -0
  456. package/packages/core/dist/core/install/convenience-matchers.d.ts.map +1 -0
  457. package/packages/core/dist/core/install/convenience-matchers.js +355 -0
  458. package/packages/core/dist/core/install/convenience-matchers.js.map +1 -0
  459. package/packages/core/dist/core/install/conversion-context.d.ts +146 -0
  460. package/packages/core/dist/core/install/conversion-context.d.ts.map +1 -0
  461. package/packages/core/dist/core/install/conversion-context.js +163 -0
  462. package/packages/core/dist/core/install/conversion-context.js.map +1 -0
  463. package/packages/core/dist/core/install/conversion-coordinator.d.ts +91 -0
  464. package/packages/core/dist/core/install/conversion-coordinator.d.ts.map +1 -0
  465. package/packages/core/dist/core/install/conversion-coordinator.js +273 -0
  466. package/packages/core/dist/core/install/conversion-coordinator.js.map +1 -0
  467. package/packages/core/dist/core/install/detection-types.d.ts +216 -0
  468. package/packages/core/dist/core/install/detection-types.d.ts.map +1 -0
  469. package/packages/core/dist/core/install/detection-types.js +8 -0
  470. package/packages/core/dist/core/install/detection-types.js.map +1 -0
  471. package/packages/core/dist/core/install/download-keys.d.ts +10 -0
  472. package/packages/core/dist/core/install/download-keys.d.ts.map +1 -0
  473. package/packages/core/dist/core/install/download-keys.js +34 -0
  474. package/packages/core/dist/core/install/download-keys.js.map +1 -0
  475. package/packages/core/dist/core/install/file-format-detector.d.ts +52 -0
  476. package/packages/core/dist/core/install/file-format-detector.d.ts.map +1 -0
  477. package/packages/core/dist/core/install/file-format-detector.js +317 -0
  478. package/packages/core/dist/core/install/file-format-detector.js.map +1 -0
  479. package/packages/core/dist/core/install/file-updater.d.ts +7 -0
  480. package/packages/core/dist/core/install/file-updater.d.ts.map +1 -0
  481. package/packages/core/dist/core/install/file-updater.js +28 -0
  482. package/packages/core/dist/core/install/file-updater.js.map +1 -0
  483. package/packages/core/dist/core/install/flow-based-installer.d.ts +30 -0
  484. package/packages/core/dist/core/install/flow-based-installer.d.ts.map +1 -0
  485. package/packages/core/dist/core/install/flow-based-installer.js +85 -0
  486. package/packages/core/dist/core/install/flow-based-installer.js.map +1 -0
  487. package/packages/core/dist/core/install/flow-index-installer.d.ts +46 -0
  488. package/packages/core/dist/core/install/flow-index-installer.d.ts.map +1 -0
  489. package/packages/core/dist/core/install/flow-index-installer.js +319 -0
  490. package/packages/core/dist/core/install/flow-index-installer.js.map +1 -0
  491. package/packages/core/dist/core/install/format-detector.d.ts +85 -0
  492. package/packages/core/dist/core/install/format-detector.d.ts.map +1 -0
  493. package/packages/core/dist/core/install/format-detector.js +327 -0
  494. package/packages/core/dist/core/install/format-detector.js.map +1 -0
  495. package/packages/core/dist/core/install/format-distribution-analyzer.d.ts +98 -0
  496. package/packages/core/dist/core/install/format-distribution-analyzer.d.ts.map +1 -0
  497. package/packages/core/dist/core/install/format-distribution-analyzer.js +215 -0
  498. package/packages/core/dist/core/install/format-distribution-analyzer.js.map +1 -0
  499. package/packages/core/dist/core/install/format-group-merger.d.ts +66 -0
  500. package/packages/core/dist/core/install/format-group-merger.d.ts.map +1 -0
  501. package/packages/core/dist/core/install/format-group-merger.js +206 -0
  502. package/packages/core/dist/core/install/format-group-merger.js.map +1 -0
  503. package/packages/core/dist/core/install/git-package-loader.d.ts +17 -0
  504. package/packages/core/dist/core/install/git-package-loader.d.ts.map +1 -0
  505. package/packages/core/dist/core/install/git-package-loader.js +52 -0
  506. package/packages/core/dist/core/install/git-package-loader.js.map +1 -0
  507. package/packages/core/dist/core/install/handlers/index.d.ts +5 -0
  508. package/packages/core/dist/core/install/handlers/index.d.ts.map +1 -0
  509. package/packages/core/dist/core/install/handlers/index.js +6 -0
  510. package/packages/core/dist/core/install/handlers/index.js.map +1 -0
  511. package/packages/core/dist/core/install/helpers/conflict-detection.d.ts +41 -0
  512. package/packages/core/dist/core/install/helpers/conflict-detection.d.ts.map +1 -0
  513. package/packages/core/dist/core/install/helpers/conflict-detection.js +71 -0
  514. package/packages/core/dist/core/install/helpers/conflict-detection.js.map +1 -0
  515. package/packages/core/dist/core/install/helpers/file-discovery.d.ts +9 -0
  516. package/packages/core/dist/core/install/helpers/file-discovery.d.ts.map +1 -0
  517. package/packages/core/dist/core/install/helpers/file-discovery.js +63 -0
  518. package/packages/core/dist/core/install/helpers/file-discovery.js.map +1 -0
  519. package/packages/core/dist/core/install/helpers/format-detection.d.ts +42 -0
  520. package/packages/core/dist/core/install/helpers/format-detection.d.ts.map +1 -0
  521. package/packages/core/dist/core/install/helpers/format-detection.js +66 -0
  522. package/packages/core/dist/core/install/helpers/format-detection.js.map +1 -0
  523. package/packages/core/dist/core/install/helpers/index.d.ts +10 -0
  524. package/packages/core/dist/core/install/helpers/index.d.ts.map +1 -0
  525. package/packages/core/dist/core/install/helpers/index.js +14 -0
  526. package/packages/core/dist/core/install/helpers/index.js.map +1 -0
  527. package/packages/core/dist/core/install/helpers/result-aggregation.d.ts +58 -0
  528. package/packages/core/dist/core/install/helpers/result-aggregation.d.ts.map +1 -0
  529. package/packages/core/dist/core/install/helpers/result-aggregation.js +107 -0
  530. package/packages/core/dist/core/install/helpers/result-aggregation.js.map +1 -0
  531. package/packages/core/dist/core/install/helpers/result-logging.d.ts +47 -0
  532. package/packages/core/dist/core/install/helpers/result-logging.d.ts.map +1 -0
  533. package/packages/core/dist/core/install/helpers/result-logging.js +85 -0
  534. package/packages/core/dist/core/install/helpers/result-logging.js.map +1 -0
  535. package/packages/core/dist/core/install/import-flow-converter.d.ts +89 -0
  536. package/packages/core/dist/core/install/import-flow-converter.d.ts.map +1 -0
  537. package/packages/core/dist/core/install/import-flow-converter.js +436 -0
  538. package/packages/core/dist/core/install/import-flow-converter.js.map +1 -0
  539. package/packages/core/dist/core/install/index-based-installer.d.ts +35 -0
  540. package/packages/core/dist/core/install/index-based-installer.d.ts.map +1 -0
  541. package/packages/core/dist/core/install/index-based-installer.js +459 -0
  542. package/packages/core/dist/core/install/index-based-installer.js.map +1 -0
  543. package/packages/core/dist/core/install/input-classifier-base.d.ts +65 -0
  544. package/packages/core/dist/core/install/input-classifier-base.d.ts.map +1 -0
  545. package/packages/core/dist/core/install/input-classifier-base.js +173 -0
  546. package/packages/core/dist/core/install/input-classifier-base.js.map +1 -0
  547. package/packages/core/dist/core/install/install-errors.d.ts +6 -0
  548. package/packages/core/dist/core/install/install-errors.d.ts.map +1 -0
  549. package/packages/core/dist/core/install/install-errors.js +41 -0
  550. package/packages/core/dist/core/install/install-errors.js.map +1 -0
  551. package/packages/core/dist/core/install/install-helpers.d.ts +36 -0
  552. package/packages/core/dist/core/install/install-helpers.d.ts.map +1 -0
  553. package/packages/core/dist/core/install/install-helpers.js +89 -0
  554. package/packages/core/dist/core/install/install-helpers.js.map +1 -0
  555. package/packages/core/dist/core/install/install-reporting.d.ts +42 -0
  556. package/packages/core/dist/core/install/install-reporting.d.ts.map +1 -0
  557. package/packages/core/dist/core/install/install-reporting.js +182 -0
  558. package/packages/core/dist/core/install/install-reporting.js.map +1 -0
  559. package/packages/core/dist/core/install/list-handler.d.ts +18 -0
  560. package/packages/core/dist/core/install/list-handler.d.ts.map +1 -0
  561. package/packages/core/dist/core/install/list-handler.js +112 -0
  562. package/packages/core/dist/core/install/list-handler.js.map +1 -0
  563. package/packages/core/dist/core/install/local-source-resolution.d.ts +30 -0
  564. package/packages/core/dist/core/install/local-source-resolution.d.ts.map +1 -0
  565. package/packages/core/dist/core/install/local-source-resolution.js +103 -0
  566. package/packages/core/dist/core/install/local-source-resolution.js.map +1 -0
  567. package/packages/core/dist/core/install/marketplace-handler.d.ts +129 -0
  568. package/packages/core/dist/core/install/marketplace-handler.d.ts.map +1 -0
  569. package/packages/core/dist/core/install/marketplace-handler.js +631 -0
  570. package/packages/core/dist/core/install/marketplace-handler.js.map +1 -0
  571. package/packages/core/dist/core/install/operations/conflict-handler.d.ts +13 -0
  572. package/packages/core/dist/core/install/operations/conflict-handler.d.ts.map +1 -0
  573. package/packages/core/dist/core/install/operations/conflict-handler.js +73 -0
  574. package/packages/core/dist/core/install/operations/conflict-handler.js.map +1 -0
  575. package/packages/core/dist/core/install/operations/index.d.ts +8 -0
  576. package/packages/core/dist/core/install/operations/index.d.ts.map +1 -0
  577. package/packages/core/dist/core/install/operations/index.js +8 -0
  578. package/packages/core/dist/core/install/operations/index.js.map +1 -0
  579. package/packages/core/dist/core/install/operations/installation-executor.d.ts +48 -0
  580. package/packages/core/dist/core/install/operations/installation-executor.d.ts.map +1 -0
  581. package/packages/core/dist/core/install/operations/installation-executor.js +174 -0
  582. package/packages/core/dist/core/install/operations/installation-executor.js.map +1 -0
  583. package/packages/core/dist/core/install/operations/root-files.d.ts +37 -0
  584. package/packages/core/dist/core/install/operations/root-files.d.ts.map +1 -0
  585. package/packages/core/dist/core/install/operations/root-files.js +173 -0
  586. package/packages/core/dist/core/install/operations/root-files.js.map +1 -0
  587. package/packages/core/dist/core/install/orchestrator/index.d.ts +5 -0
  588. package/packages/core/dist/core/install/orchestrator/index.d.ts.map +1 -0
  589. package/packages/core/dist/core/install/orchestrator/index.js +4 -0
  590. package/packages/core/dist/core/install/orchestrator/index.js.map +1 -0
  591. package/packages/core/dist/core/install/orchestrator/orchestrator.d.ts +96 -0
  592. package/packages/core/dist/core/install/orchestrator/orchestrator.d.ts.map +1 -0
  593. package/packages/core/dist/core/install/orchestrator/orchestrator.js +684 -0
  594. package/packages/core/dist/core/install/orchestrator/orchestrator.js.map +1 -0
  595. package/packages/core/dist/core/install/orchestrator/strategies/base.d.ts +34 -0
  596. package/packages/core/dist/core/install/orchestrator/strategies/base.d.ts.map +1 -0
  597. package/packages/core/dist/core/install/orchestrator/strategies/base.js +43 -0
  598. package/packages/core/dist/core/install/orchestrator/strategies/base.js.map +1 -0
  599. package/packages/core/dist/core/install/orchestrator/strategies/bulk-strategy.d.ts +17 -0
  600. package/packages/core/dist/core/install/orchestrator/strategies/bulk-strategy.d.ts.map +1 -0
  601. package/packages/core/dist/core/install/orchestrator/strategies/bulk-strategy.js +52 -0
  602. package/packages/core/dist/core/install/orchestrator/strategies/bulk-strategy.js.map +1 -0
  603. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.d.ts +15 -0
  604. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.d.ts.map +1 -0
  605. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.js +112 -0
  606. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.js.map +1 -0
  607. package/packages/core/dist/core/install/orchestrator/strategies/index.d.ts +11 -0
  608. package/packages/core/dist/core/install/orchestrator/strategies/index.d.ts.map +1 -0
  609. package/packages/core/dist/core/install/orchestrator/strategies/index.js +21 -0
  610. package/packages/core/dist/core/install/orchestrator/strategies/index.js.map +1 -0
  611. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.d.ts +17 -0
  612. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.d.ts.map +1 -0
  613. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.js +61 -0
  614. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.js.map +1 -0
  615. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.d.ts +17 -0
  616. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.d.ts.map +1 -0
  617. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.js +38 -0
  618. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.js.map +1 -0
  619. package/packages/core/dist/core/install/orchestrator/subsumption-resolver.d.ts +75 -0
  620. package/packages/core/dist/core/install/orchestrator/subsumption-resolver.d.ts.map +1 -0
  621. package/packages/core/dist/core/install/orchestrator/subsumption-resolver.js +193 -0
  622. package/packages/core/dist/core/install/orchestrator/subsumption-resolver.js.map +1 -0
  623. package/packages/core/dist/core/install/orchestrator/types.d.ts +104 -0
  624. package/packages/core/dist/core/install/orchestrator/types.d.ts.map +1 -0
  625. package/packages/core/dist/core/install/orchestrator/types.js +2 -0
  626. package/packages/core/dist/core/install/orchestrator/types.js.map +1 -0
  627. package/packages/core/dist/core/install/package-input.d.ts +28 -0
  628. package/packages/core/dist/core/install/package-input.d.ts.map +1 -0
  629. package/packages/core/dist/core/install/package-input.js +99 -0
  630. package/packages/core/dist/core/install/package-input.js.map +1 -0
  631. package/packages/core/dist/core/install/package-installation.d.ts +13 -0
  632. package/packages/core/dist/core/install/package-installation.d.ts.map +1 -0
  633. package/packages/core/dist/core/install/package-installation.js +30 -0
  634. package/packages/core/dist/core/install/package-installation.js.map +1 -0
  635. package/packages/core/dist/core/install/package-marker-detector.d.ts +93 -0
  636. package/packages/core/dist/core/install/package-marker-detector.d.ts.map +1 -0
  637. package/packages/core/dist/core/install/package-marker-detector.js +185 -0
  638. package/packages/core/dist/core/install/package-marker-detector.js.map +1 -0
  639. package/packages/core/dist/core/install/path-package-loader.d.ts +42 -0
  640. package/packages/core/dist/core/install/path-package-loader.d.ts.map +1 -0
  641. package/packages/core/dist/core/install/path-package-loader.js +173 -0
  642. package/packages/core/dist/core/install/path-package-loader.js.map +1 -0
  643. package/packages/core/dist/core/install/platform-resolution.d.ts +15 -0
  644. package/packages/core/dist/core/install/platform-resolution.d.ts.map +1 -0
  645. package/packages/core/dist/core/install/platform-resolution.js +31 -0
  646. package/packages/core/dist/core/install/platform-resolution.js.map +1 -0
  647. package/packages/core/dist/core/install/plugin-detector.d.ts +46 -0
  648. package/packages/core/dist/core/install/plugin-detector.d.ts.map +1 -0
  649. package/packages/core/dist/core/install/plugin-detector.js +126 -0
  650. package/packages/core/dist/core/install/plugin-detector.js.map +1 -0
  651. package/packages/core/dist/core/install/plugin-metadata-resolver.d.ts +62 -0
  652. package/packages/core/dist/core/install/plugin-metadata-resolver.d.ts.map +1 -0
  653. package/packages/core/dist/core/install/plugin-metadata-resolver.js +125 -0
  654. package/packages/core/dist/core/install/plugin-metadata-resolver.js.map +1 -0
  655. package/packages/core/dist/core/install/plugin-sources.d.ts +59 -0
  656. package/packages/core/dist/core/install/plugin-sources.d.ts.map +1 -0
  657. package/packages/core/dist/core/install/plugin-sources.js +122 -0
  658. package/packages/core/dist/core/install/plugin-sources.js.map +1 -0
  659. package/packages/core/dist/core/install/plugin-transformer.d.ts +29 -0
  660. package/packages/core/dist/core/install/plugin-transformer.d.ts.map +1 -0
  661. package/packages/core/dist/core/install/plugin-transformer.js +159 -0
  662. package/packages/core/dist/core/install/plugin-transformer.js.map +1 -0
  663. package/packages/core/dist/core/install/preprocessing/base-resolver.d.ts +61 -0
  664. package/packages/core/dist/core/install/preprocessing/base-resolver.d.ts.map +1 -0
  665. package/packages/core/dist/core/install/preprocessing/base-resolver.js +135 -0
  666. package/packages/core/dist/core/install/preprocessing/base-resolver.js.map +1 -0
  667. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.d.ts +11 -0
  668. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.d.ts.map +1 -0
  669. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.js +22 -0
  670. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.js.map +1 -0
  671. package/packages/core/dist/core/install/preprocessing/index.d.ts +6 -0
  672. package/packages/core/dist/core/install/preprocessing/index.d.ts.map +1 -0
  673. package/packages/core/dist/core/install/preprocessing/index.js +5 -0
  674. package/packages/core/dist/core/install/preprocessing/index.js.map +1 -0
  675. package/packages/core/dist/core/install/preprocessing/input-classifier.d.ts +21 -0
  676. package/packages/core/dist/core/install/preprocessing/input-classifier.d.ts.map +1 -0
  677. package/packages/core/dist/core/install/preprocessing/input-classifier.js +66 -0
  678. package/packages/core/dist/core/install/preprocessing/input-classifier.js.map +1 -0
  679. package/packages/core/dist/core/install/preprocessing/options-normalizer.d.ts +19 -0
  680. package/packages/core/dist/core/install/preprocessing/options-normalizer.d.ts.map +1 -0
  681. package/packages/core/dist/core/install/preprocessing/options-normalizer.js +41 -0
  682. package/packages/core/dist/core/install/preprocessing/options-normalizer.js.map +1 -0
  683. package/packages/core/dist/core/install/remote-flow.d.ts +38 -0
  684. package/packages/core/dist/core/install/remote-flow.d.ts.map +1 -0
  685. package/packages/core/dist/core/install/remote-flow.js +180 -0
  686. package/packages/core/dist/core/install/remote-flow.js.map +1 -0
  687. package/packages/core/dist/core/install/remote-reporting.d.ts +11 -0
  688. package/packages/core/dist/core/install/remote-reporting.d.ts.map +1 -0
  689. package/packages/core/dist/core/install/remote-reporting.js +63 -0
  690. package/packages/core/dist/core/install/remote-reporting.js.map +1 -0
  691. package/packages/core/dist/core/install/resolution/content-root-cache.d.ts +32 -0
  692. package/packages/core/dist/core/install/resolution/content-root-cache.d.ts.map +1 -0
  693. package/packages/core/dist/core/install/resolution/content-root-cache.js +87 -0
  694. package/packages/core/dist/core/install/resolution/content-root-cache.js.map +1 -0
  695. package/packages/core/dist/core/install/resolution/executor.d.ts +23 -0
  696. package/packages/core/dist/core/install/resolution/executor.d.ts.map +1 -0
  697. package/packages/core/dist/core/install/resolution/executor.js +187 -0
  698. package/packages/core/dist/core/install/resolution/executor.js.map +1 -0
  699. package/packages/core/dist/core/install/resolution/graph-builder.d.ts +31 -0
  700. package/packages/core/dist/core/install/resolution/graph-builder.d.ts.map +1 -0
  701. package/packages/core/dist/core/install/resolution/graph-builder.js +299 -0
  702. package/packages/core/dist/core/install/resolution/graph-builder.js.map +1 -0
  703. package/packages/core/dist/core/install/resolution/id-generator.d.ts +19 -0
  704. package/packages/core/dist/core/install/resolution/id-generator.d.ts.map +1 -0
  705. package/packages/core/dist/core/install/resolution/id-generator.js +70 -0
  706. package/packages/core/dist/core/install/resolution/id-generator.js.map +1 -0
  707. package/packages/core/dist/core/install/resolution/index.d.ts +15 -0
  708. package/packages/core/dist/core/install/resolution/index.d.ts.map +1 -0
  709. package/packages/core/dist/core/install/resolution/index.js +13 -0
  710. package/packages/core/dist/core/install/resolution/index.js.map +1 -0
  711. package/packages/core/dist/core/install/resolution/installation-planner.d.ts +23 -0
  712. package/packages/core/dist/core/install/resolution/installation-planner.d.ts.map +1 -0
  713. package/packages/core/dist/core/install/resolution/installation-planner.js +158 -0
  714. package/packages/core/dist/core/install/resolution/installation-planner.js.map +1 -0
  715. package/packages/core/dist/core/install/resolution/manifest-reader.d.ts +34 -0
  716. package/packages/core/dist/core/install/resolution/manifest-reader.d.ts.map +1 -0
  717. package/packages/core/dist/core/install/resolution/manifest-reader.js +112 -0
  718. package/packages/core/dist/core/install/resolution/manifest-reader.js.map +1 -0
  719. package/packages/core/dist/core/install/resolution/package-loader.d.ts +22 -0
  720. package/packages/core/dist/core/install/resolution/package-loader.d.ts.map +1 -0
  721. package/packages/core/dist/core/install/resolution/package-loader.js +176 -0
  722. package/packages/core/dist/core/install/resolution/package-loader.js.map +1 -0
  723. package/packages/core/dist/core/install/resolution/types.d.ts +290 -0
  724. package/packages/core/dist/core/install/resolution/types.d.ts.map +1 -0
  725. package/packages/core/dist/core/install/resolution/types.js +6 -0
  726. package/packages/core/dist/core/install/resolution/types.js.map +1 -0
  727. package/packages/core/dist/core/install/resolution/version-solver.d.ts +43 -0
  728. package/packages/core/dist/core/install/resolution/version-solver.d.ts.map +1 -0
  729. package/packages/core/dist/core/install/resolution/version-solver.js +166 -0
  730. package/packages/core/dist/core/install/resolution/version-solver.js.map +1 -0
  731. package/packages/core/dist/core/install/resource-discoverer.d.ts +21 -0
  732. package/packages/core/dist/core/install/resource-discoverer.d.ts.map +1 -0
  733. package/packages/core/dist/core/install/resource-discoverer.js +233 -0
  734. package/packages/core/dist/core/install/resource-discoverer.js.map +1 -0
  735. package/packages/core/dist/core/install/resource-selection-menu.d.ts +25 -0
  736. package/packages/core/dist/core/install/resource-selection-menu.d.ts.map +1 -0
  737. package/packages/core/dist/core/install/resource-selection-menu.js +250 -0
  738. package/packages/core/dist/core/install/resource-selection-menu.js.map +1 -0
  739. package/packages/core/dist/core/install/resource-types.d.ts +62 -0
  740. package/packages/core/dist/core/install/resource-types.d.ts.map +1 -0
  741. package/packages/core/dist/core/install/resource-types.js +5 -0
  742. package/packages/core/dist/core/install/resource-types.js.map +1 -0
  743. package/packages/core/dist/core/install/schema-registry.d.ts +69 -0
  744. package/packages/core/dist/core/install/schema-registry.d.ts.map +1 -0
  745. package/packages/core/dist/core/install/schema-registry.js +219 -0
  746. package/packages/core/dist/core/install/schema-registry.js.map +1 -0
  747. package/packages/core/dist/core/install/sources/base.d.ts +77 -0
  748. package/packages/core/dist/core/install/sources/base.d.ts.map +1 -0
  749. package/packages/core/dist/core/install/sources/base.js +12 -0
  750. package/packages/core/dist/core/install/sources/base.js.map +1 -0
  751. package/packages/core/dist/core/install/sources/git-source.d.ts +11 -0
  752. package/packages/core/dist/core/install/sources/git-source.d.ts.map +1 -0
  753. package/packages/core/dist/core/install/sources/git-source.js +132 -0
  754. package/packages/core/dist/core/install/sources/git-source.js.map +1 -0
  755. package/packages/core/dist/core/install/sources/loader-factory.d.ts +7 -0
  756. package/packages/core/dist/core/install/sources/loader-factory.d.ts.map +1 -0
  757. package/packages/core/dist/core/install/sources/loader-factory.js +24 -0
  758. package/packages/core/dist/core/install/sources/loader-factory.js.map +1 -0
  759. package/packages/core/dist/core/install/sources/path-source.d.ts +11 -0
  760. package/packages/core/dist/core/install/sources/path-source.d.ts.map +1 -0
  761. package/packages/core/dist/core/install/sources/path-source.js +124 -0
  762. package/packages/core/dist/core/install/sources/path-source.js.map +1 -0
  763. package/packages/core/dist/core/install/sources/registry-source.d.ts +11 -0
  764. package/packages/core/dist/core/install/sources/registry-source.d.ts.map +1 -0
  765. package/packages/core/dist/core/install/sources/registry-source.js +85 -0
  766. package/packages/core/dist/core/install/sources/registry-source.js.map +1 -0
  767. package/packages/core/dist/core/install/sources/workspace-source.d.ts +11 -0
  768. package/packages/core/dist/core/install/sources/workspace-source.d.ts.map +1 -0
  769. package/packages/core/dist/core/install/sources/workspace-source.js +78 -0
  770. package/packages/core/dist/core/install/sources/workspace-source.js.map +1 -0
  771. package/packages/core/dist/core/install/strategies/base-strategy.d.ts +56 -0
  772. package/packages/core/dist/core/install/strategies/base-strategy.d.ts.map +1 -0
  773. package/packages/core/dist/core/install/strategies/base-strategy.js +128 -0
  774. package/packages/core/dist/core/install/strategies/base-strategy.js.map +1 -0
  775. package/packages/core/dist/core/install/strategies/conversion-strategy.d.ts +43 -0
  776. package/packages/core/dist/core/install/strategies/conversion-strategy.d.ts.map +1 -0
  777. package/packages/core/dist/core/install/strategies/conversion-strategy.js +146 -0
  778. package/packages/core/dist/core/install/strategies/conversion-strategy.js.map +1 -0
  779. package/packages/core/dist/core/install/strategies/flow-based-strategy.d.ts +50 -0
  780. package/packages/core/dist/core/install/strategies/flow-based-strategy.d.ts.map +1 -0
  781. package/packages/core/dist/core/install/strategies/flow-based-strategy.js +326 -0
  782. package/packages/core/dist/core/install/strategies/flow-based-strategy.js.map +1 -0
  783. package/packages/core/dist/core/install/strategies/helpers/flow-helpers.d.ts +12 -0
  784. package/packages/core/dist/core/install/strategies/helpers/flow-helpers.d.ts.map +1 -0
  785. package/packages/core/dist/core/install/strategies/helpers/flow-helpers.js +22 -0
  786. package/packages/core/dist/core/install/strategies/helpers/flow-helpers.js.map +1 -0
  787. package/packages/core/dist/core/install/strategies/helpers/platform-filtering.d.ts +21 -0
  788. package/packages/core/dist/core/install/strategies/helpers/platform-filtering.d.ts.map +1 -0
  789. package/packages/core/dist/core/install/strategies/helpers/platform-filtering.js +53 -0
  790. package/packages/core/dist/core/install/strategies/helpers/platform-filtering.js.map +1 -0
  791. package/packages/core/dist/core/install/strategies/helpers/result-converter.d.ts +22 -0
  792. package/packages/core/dist/core/install/strategies/helpers/result-converter.d.ts.map +1 -0
  793. package/packages/core/dist/core/install/strategies/helpers/result-converter.js +60 -0
  794. package/packages/core/dist/core/install/strategies/helpers/result-converter.js.map +1 -0
  795. package/packages/core/dist/core/install/strategies/helpers/temp-directory.d.ts +45 -0
  796. package/packages/core/dist/core/install/strategies/helpers/temp-directory.d.ts.map +1 -0
  797. package/packages/core/dist/core/install/strategies/helpers/temp-directory.js +77 -0
  798. package/packages/core/dist/core/install/strategies/helpers/temp-directory.js.map +1 -0
  799. package/packages/core/dist/core/install/strategies/index.d.ts +16 -0
  800. package/packages/core/dist/core/install/strategies/index.d.ts.map +1 -0
  801. package/packages/core/dist/core/install/strategies/index.js +18 -0
  802. package/packages/core/dist/core/install/strategies/index.js.map +1 -0
  803. package/packages/core/dist/core/install/strategies/strategy-selector.d.ts +20 -0
  804. package/packages/core/dist/core/install/strategies/strategy-selector.d.ts.map +1 -0
  805. package/packages/core/dist/core/install/strategies/strategy-selector.js +34 -0
  806. package/packages/core/dist/core/install/strategies/strategy-selector.js.map +1 -0
  807. package/packages/core/dist/core/install/strategies/types.d.ts +89 -0
  808. package/packages/core/dist/core/install/strategies/types.d.ts.map +1 -0
  809. package/packages/core/dist/core/install/strategies/types.js +7 -0
  810. package/packages/core/dist/core/install/strategies/types.js.map +1 -0
  811. package/packages/core/dist/core/install/types.d.ts +12 -0
  812. package/packages/core/dist/core/install/types.d.ts.map +1 -0
  813. package/packages/core/dist/core/install/types.js +5 -0
  814. package/packages/core/dist/core/install/types.js.map +1 -0
  815. package/packages/core/dist/core/install/unified/context-builders.d.ts +52 -0
  816. package/packages/core/dist/core/install/unified/context-builders.d.ts.map +1 -0
  817. package/packages/core/dist/core/install/unified/context-builders.js +396 -0
  818. package/packages/core/dist/core/install/unified/context-builders.js.map +1 -0
  819. package/packages/core/dist/core/install/unified/context-helpers.d.ts +22 -0
  820. package/packages/core/dist/core/install/unified/context-helpers.d.ts.map +1 -0
  821. package/packages/core/dist/core/install/unified/context-helpers.js +80 -0
  822. package/packages/core/dist/core/install/unified/context-helpers.js.map +1 -0
  823. package/packages/core/dist/core/install/unified/context.d.ts +124 -0
  824. package/packages/core/dist/core/install/unified/context.d.ts.map +1 -0
  825. package/packages/core/dist/core/install/unified/context.js +2 -0
  826. package/packages/core/dist/core/install/unified/context.js.map +1 -0
  827. package/packages/core/dist/core/install/unified/index.d.ts +12 -0
  828. package/packages/core/dist/core/install/unified/index.d.ts.map +1 -0
  829. package/packages/core/dist/core/install/unified/index.js +13 -0
  830. package/packages/core/dist/core/install/unified/index.js.map +1 -0
  831. package/packages/core/dist/core/install/unified/multi-context-pipeline.d.ts +10 -0
  832. package/packages/core/dist/core/install/unified/multi-context-pipeline.d.ts.map +1 -0
  833. package/packages/core/dist/core/install/unified/multi-context-pipeline.js +86 -0
  834. package/packages/core/dist/core/install/unified/multi-context-pipeline.js.map +1 -0
  835. package/packages/core/dist/core/install/unified/phases/conflicts.d.ts +7 -0
  836. package/packages/core/dist/core/install/unified/phases/conflicts.d.ts.map +1 -0
  837. package/packages/core/dist/core/install/unified/phases/conflicts.js +17 -0
  838. package/packages/core/dist/core/install/unified/phases/conflicts.js.map +1 -0
  839. package/packages/core/dist/core/install/unified/phases/convert.d.ts +22 -0
  840. package/packages/core/dist/core/install/unified/phases/convert.d.ts.map +1 -0
  841. package/packages/core/dist/core/install/unified/phases/convert.js +228 -0
  842. package/packages/core/dist/core/install/unified/phases/convert.js.map +1 -0
  843. package/packages/core/dist/core/install/unified/phases/execute.d.ts +26 -0
  844. package/packages/core/dist/core/install/unified/phases/execute.d.ts.map +1 -0
  845. package/packages/core/dist/core/install/unified/phases/execute.js +82 -0
  846. package/packages/core/dist/core/install/unified/phases/execute.js.map +1 -0
  847. package/packages/core/dist/core/install/unified/phases/load-package.d.ts +11 -0
  848. package/packages/core/dist/core/install/unified/phases/load-package.d.ts.map +1 -0
  849. package/packages/core/dist/core/install/unified/phases/load-package.js +121 -0
  850. package/packages/core/dist/core/install/unified/phases/load-package.js.map +1 -0
  851. package/packages/core/dist/core/install/unified/phases/manifest.d.ts +6 -0
  852. package/packages/core/dist/core/install/unified/phases/manifest.d.ts.map +1 -0
  853. package/packages/core/dist/core/install/unified/phases/manifest.js +73 -0
  854. package/packages/core/dist/core/install/unified/phases/manifest.js.map +1 -0
  855. package/packages/core/dist/core/install/unified/phases/report.d.ts +11 -0
  856. package/packages/core/dist/core/install/unified/phases/report.d.ts.map +1 -0
  857. package/packages/core/dist/core/install/unified/phases/report.js +62 -0
  858. package/packages/core/dist/core/install/unified/phases/report.js.map +1 -0
  859. package/packages/core/dist/core/install/unified/phases/resolve-dependencies.d.ts +6 -0
  860. package/packages/core/dist/core/install/unified/phases/resolve-dependencies.d.ts.map +1 -0
  861. package/packages/core/dist/core/install/unified/phases/resolve-dependencies.js +122 -0
  862. package/packages/core/dist/core/install/unified/phases/resolve-dependencies.js.map +1 -0
  863. package/packages/core/dist/core/install/unified/pipeline.d.ts +13 -0
  864. package/packages/core/dist/core/install/unified/pipeline.d.ts.map +1 -0
  865. package/packages/core/dist/core/install/unified/pipeline.js +114 -0
  866. package/packages/core/dist/core/install/unified/pipeline.js.map +1 -0
  867. package/packages/core/dist/core/install/validators/index.d.ts +3 -0
  868. package/packages/core/dist/core/install/validators/index.d.ts.map +1 -0
  869. package/packages/core/dist/core/install/validators/index.js +3 -0
  870. package/packages/core/dist/core/install/validators/index.js.map +1 -0
  871. package/packages/core/dist/core/install/validators/options-validator.d.ts +16 -0
  872. package/packages/core/dist/core/install/validators/options-validator.d.ts.map +1 -0
  873. package/packages/core/dist/core/install/validators/options-validator.js +28 -0
  874. package/packages/core/dist/core/install/validators/options-validator.js.map +1 -0
  875. package/packages/core/dist/core/install/validators/target-validator.d.ts +6 -0
  876. package/packages/core/dist/core/install/validators/target-validator.d.ts.map +1 -0
  877. package/packages/core/dist/core/install/validators/target-validator.js +19 -0
  878. package/packages/core/dist/core/install/validators/target-validator.js.map +1 -0
  879. package/packages/core/dist/core/install/version-selection.d.ts +51 -0
  880. package/packages/core/dist/core/install/version-selection.d.ts.map +1 -0
  881. package/packages/core/dist/core/install/version-selection.js +272 -0
  882. package/packages/core/dist/core/install/version-selection.js.map +1 -0
  883. package/packages/core/dist/core/interaction-policy.d.ts +40 -0
  884. package/packages/core/dist/core/interaction-policy.d.ts.map +1 -0
  885. package/packages/core/dist/core/interaction-policy.js +60 -0
  886. package/packages/core/dist/core/interaction-policy.js.map +1 -0
  887. package/packages/core/dist/core/list/list-pipeline.d.ts +80 -0
  888. package/packages/core/dist/core/list/list-pipeline.d.ts.map +1 -0
  889. package/packages/core/dist/core/list/list-pipeline.js +550 -0
  890. package/packages/core/dist/core/list/list-pipeline.js.map +1 -0
  891. package/packages/core/dist/core/list/list-printers.d.ts +16 -0
  892. package/packages/core/dist/core/list/list-printers.d.ts.map +1 -0
  893. package/packages/core/dist/core/list/list-printers.js +191 -0
  894. package/packages/core/dist/core/list/list-printers.js.map +1 -0
  895. package/packages/core/dist/core/list/list-tree-renderer.d.ts +95 -0
  896. package/packages/core/dist/core/list/list-tree-renderer.d.ts.map +1 -0
  897. package/packages/core/dist/core/list/list-tree-renderer.js +147 -0
  898. package/packages/core/dist/core/list/list-tree-renderer.js.map +1 -0
  899. package/packages/core/dist/core/list/remote-list-resolver.d.ts +22 -0
  900. package/packages/core/dist/core/list/remote-list-resolver.d.ts.map +1 -0
  901. package/packages/core/dist/core/list/remote-list-resolver.js +219 -0
  902. package/packages/core/dist/core/list/remote-list-resolver.js.map +1 -0
  903. package/packages/core/dist/core/list/scope-data-collector.d.ts +59 -0
  904. package/packages/core/dist/core/list/scope-data-collector.d.ts.map +1 -0
  905. package/packages/core/dist/core/list/scope-data-collector.js +307 -0
  906. package/packages/core/dist/core/list/scope-data-collector.js.map +1 -0
  907. package/packages/core/dist/core/list/untracked-files-scanner.d.ts +62 -0
  908. package/packages/core/dist/core/list/untracked-files-scanner.d.ts.map +1 -0
  909. package/packages/core/dist/core/list/untracked-files-scanner.js +471 -0
  910. package/packages/core/dist/core/list/untracked-files-scanner.js.map +1 -0
  911. package/packages/core/dist/core/list/view-metadata.d.ts +12 -0
  912. package/packages/core/dist/core/list/view-metadata.d.ts.map +1 -0
  913. package/packages/core/dist/core/list/view-metadata.js +31 -0
  914. package/packages/core/dist/core/list/view-metadata.js.map +1 -0
  915. package/packages/core/dist/core/markdown-frontmatter.d.ts +54 -0
  916. package/packages/core/dist/core/markdown-frontmatter.d.ts.map +1 -0
  917. package/packages/core/dist/core/markdown-frontmatter.js +224 -0
  918. package/packages/core/dist/core/markdown-frontmatter.js.map +1 -0
  919. package/packages/core/dist/core/openpackage.d.ts +46 -0
  920. package/packages/core/dist/core/openpackage.d.ts.map +1 -0
  921. package/packages/core/dist/core/openpackage.js +303 -0
  922. package/packages/core/dist/core/openpackage.js.map +1 -0
  923. package/packages/core/dist/core/package-context.d.ts +99 -0
  924. package/packages/core/dist/core/package-context.d.ts.map +1 -0
  925. package/packages/core/dist/core/package-context.js +220 -0
  926. package/packages/core/dist/core/package-context.js.map +1 -0
  927. package/packages/core/dist/core/package-creation.d.ts +45 -0
  928. package/packages/core/dist/core/package-creation.d.ts.map +1 -0
  929. package/packages/core/dist/core/package-creation.js +160 -0
  930. package/packages/core/dist/core/package-creation.js.map +1 -0
  931. package/packages/core/dist/core/package-management.d.ts +70 -0
  932. package/packages/core/dist/core/package-management.d.ts.map +1 -0
  933. package/packages/core/dist/core/package-management.js +416 -0
  934. package/packages/core/dist/core/package-management.js.map +1 -0
  935. package/packages/core/dist/core/package-name-resolution.d.ts +110 -0
  936. package/packages/core/dist/core/package-name-resolution.d.ts.map +1 -0
  937. package/packages/core/dist/core/package-name-resolution.js +327 -0
  938. package/packages/core/dist/core/package-name-resolution.js.map +1 -0
  939. package/packages/core/dist/core/package-versioning.d.ts +37 -0
  940. package/packages/core/dist/core/package-versioning.d.ts.map +1 -0
  941. package/packages/core/dist/core/package-versioning.js +107 -0
  942. package/packages/core/dist/core/package-versioning.js.map +1 -0
  943. package/packages/core/dist/core/package.d.ts +50 -0
  944. package/packages/core/dist/core/package.d.ts.map +1 -0
  945. package/packages/core/dist/core/package.js +243 -0
  946. package/packages/core/dist/core/package.js.map +1 -0
  947. package/packages/core/dist/core/platform/directory-preservation.d.ts +52 -0
  948. package/packages/core/dist/core/platform/directory-preservation.d.ts.map +1 -0
  949. package/packages/core/dist/core/platform/directory-preservation.js +101 -0
  950. package/packages/core/dist/core/platform/directory-preservation.js.map +1 -0
  951. package/packages/core/dist/core/platform/platform-file.d.ts +42 -0
  952. package/packages/core/dist/core/platform/platform-file.d.ts.map +1 -0
  953. package/packages/core/dist/core/platform/platform-file.js +133 -0
  954. package/packages/core/dist/core/platform/platform-file.js.map +1 -0
  955. package/packages/core/dist/core/platform/platform-mapper.d.ts +74 -0
  956. package/packages/core/dist/core/platform/platform-mapper.d.ts.map +1 -0
  957. package/packages/core/dist/core/platform/platform-mapper.js +541 -0
  958. package/packages/core/dist/core/platform/platform-mapper.js.map +1 -0
  959. package/packages/core/dist/core/platform/platform-root-files.d.ts +25 -0
  960. package/packages/core/dist/core/platform/platform-root-files.d.ts.map +1 -0
  961. package/packages/core/dist/core/platform/platform-root-files.js +44 -0
  962. package/packages/core/dist/core/platform/platform-root-files.js.map +1 -0
  963. package/packages/core/dist/core/platform/platform-specific-paths.d.ts +20 -0
  964. package/packages/core/dist/core/platform/platform-specific-paths.d.ts.map +1 -0
  965. package/packages/core/dist/core/platform/platform-specific-paths.js +81 -0
  966. package/packages/core/dist/core/platform/platform-specific-paths.js.map +1 -0
  967. package/packages/core/dist/core/platform/platform-utils.d.ts +23 -0
  968. package/packages/core/dist/core/platform/platform-utils.d.ts.map +1 -0
  969. package/packages/core/dist/core/platform/platform-utils.js +65 -0
  970. package/packages/core/dist/core/platform/platform-utils.js.map +1 -0
  971. package/packages/core/dist/core/platform/registry-entry-filter.d.ts +29 -0
  972. package/packages/core/dist/core/platform/registry-entry-filter.d.ts.map +1 -0
  973. package/packages/core/dist/core/platform/registry-entry-filter.js +91 -0
  974. package/packages/core/dist/core/platform/registry-entry-filter.js.map +1 -0
  975. package/packages/core/dist/core/platform/root-file-uninstaller.d.ts +15 -0
  976. package/packages/core/dist/core/platform/root-file-uninstaller.d.ts.map +1 -0
  977. package/packages/core/dist/core/platform/root-file-uninstaller.js +74 -0
  978. package/packages/core/dist/core/platform/root-file-uninstaller.js.map +1 -0
  979. package/packages/core/dist/core/platform-yaml-merge.d.ts +9 -0
  980. package/packages/core/dist/core/platform-yaml-merge.d.ts.map +1 -0
  981. package/packages/core/dist/core/platform-yaml-merge.js +35 -0
  982. package/packages/core/dist/core/platform-yaml-merge.js.map +1 -0
  983. package/packages/core/dist/core/platforms.d.ts +197 -0
  984. package/packages/core/dist/core/platforms.d.ts.map +1 -0
  985. package/packages/core/dist/core/platforms.js +939 -0
  986. package/packages/core/dist/core/platforms.js.map +1 -0
  987. package/packages/core/dist/core/ports/console-output.d.ts +10 -0
  988. package/packages/core/dist/core/ports/console-output.d.ts.map +1 -0
  989. package/packages/core/dist/core/ports/console-output.js +64 -0
  990. package/packages/core/dist/core/ports/console-output.js.map +1 -0
  991. package/packages/core/dist/core/ports/console-progress.d.ts +21 -0
  992. package/packages/core/dist/core/ports/console-progress.d.ts.map +1 -0
  993. package/packages/core/dist/core/ports/console-progress.js +101 -0
  994. package/packages/core/dist/core/ports/console-progress.js.map +1 -0
  995. package/packages/core/dist/core/ports/console-prompt.d.ts +13 -0
  996. package/packages/core/dist/core/ports/console-prompt.d.ts.map +1 -0
  997. package/packages/core/dist/core/ports/console-prompt.js +32 -0
  998. package/packages/core/dist/core/ports/console-prompt.js.map +1 -0
  999. package/packages/core/dist/core/ports/index.d.ts +15 -0
  1000. package/packages/core/dist/core/ports/index.d.ts.map +1 -0
  1001. package/packages/core/dist/core/ports/index.js +12 -0
  1002. package/packages/core/dist/core/ports/index.js.map +1 -0
  1003. package/packages/core/dist/core/ports/output.d.ts +50 -0
  1004. package/packages/core/dist/core/ports/output.d.ts.map +1 -0
  1005. package/packages/core/dist/core/ports/output.js +13 -0
  1006. package/packages/core/dist/core/ports/output.js.map +1 -0
  1007. package/packages/core/dist/core/ports/progress.d.ts +131 -0
  1008. package/packages/core/dist/core/ports/progress.d.ts.map +1 -0
  1009. package/packages/core/dist/core/ports/progress.js +19 -0
  1010. package/packages/core/dist/core/ports/progress.js.map +1 -0
  1011. package/packages/core/dist/core/ports/prompt.d.ts +64 -0
  1012. package/packages/core/dist/core/ports/prompt.d.ts.map +1 -0
  1013. package/packages/core/dist/core/ports/prompt.js +14 -0
  1014. package/packages/core/dist/core/ports/prompt.js.map +1 -0
  1015. package/packages/core/dist/core/ports/resolve.d.ts +50 -0
  1016. package/packages/core/dist/core/ports/resolve.d.ts.map +1 -0
  1017. package/packages/core/dist/core/ports/resolve.js +64 -0
  1018. package/packages/core/dist/core/ports/resolve.js.map +1 -0
  1019. package/packages/core/dist/core/profiles.d.ts +54 -0
  1020. package/packages/core/dist/core/profiles.d.ts.map +1 -0
  1021. package/packages/core/dist/core/profiles.js +230 -0
  1022. package/packages/core/dist/core/profiles.js.map +1 -0
  1023. package/packages/core/dist/core/publish/local-publish-pipeline.d.ts +17 -0
  1024. package/packages/core/dist/core/publish/local-publish-pipeline.d.ts.map +1 -0
  1025. package/packages/core/dist/core/publish/local-publish-pipeline.js +162 -0
  1026. package/packages/core/dist/core/publish/local-publish-pipeline.js.map +1 -0
  1027. package/packages/core/dist/core/publish/publish-errors.d.ts +8 -0
  1028. package/packages/core/dist/core/publish/publish-errors.d.ts.map +1 -0
  1029. package/packages/core/dist/core/publish/publish-errors.js +57 -0
  1030. package/packages/core/dist/core/publish/publish-errors.js.map +1 -0
  1031. package/packages/core/dist/core/publish/publish-output.d.ts +29 -0
  1032. package/packages/core/dist/core/publish/publish-output.d.ts.map +1 -0
  1033. package/packages/core/dist/core/publish/publish-output.js +62 -0
  1034. package/packages/core/dist/core/publish/publish-output.js.map +1 -0
  1035. package/packages/core/dist/core/publish/publish-pipeline.d.ts +7 -0
  1036. package/packages/core/dist/core/publish/publish-pipeline.d.ts.map +1 -0
  1037. package/packages/core/dist/core/publish/publish-pipeline.js +238 -0
  1038. package/packages/core/dist/core/publish/publish-pipeline.js.map +1 -0
  1039. package/packages/core/dist/core/publish/publish-types.d.ts +18 -0
  1040. package/packages/core/dist/core/publish/publish-types.d.ts.map +1 -0
  1041. package/packages/core/dist/core/publish/publish-types.js +2 -0
  1042. package/packages/core/dist/core/publish/publish-types.js.map +1 -0
  1043. package/packages/core/dist/core/publish/publish-upload.d.ts +9 -0
  1044. package/packages/core/dist/core/publish/publish-upload.d.ts.map +1 -0
  1045. package/packages/core/dist/core/publish/publish-upload.js +51 -0
  1046. package/packages/core/dist/core/publish/publish-upload.js.map +1 -0
  1047. package/packages/core/dist/core/registry-writer.d.ts +22 -0
  1048. package/packages/core/dist/core/registry-writer.d.ts.map +1 -0
  1049. package/packages/core/dist/core/registry-writer.js +93 -0
  1050. package/packages/core/dist/core/registry-writer.js.map +1 -0
  1051. package/packages/core/dist/core/remote-pull.d.ts +93 -0
  1052. package/packages/core/dist/core/remote-pull.d.ts.map +1 -0
  1053. package/packages/core/dist/core/remote-pull.js +514 -0
  1054. package/packages/core/dist/core/remote-pull.js.map +1 -0
  1055. package/packages/core/dist/core/remove/removal-collector.d.ts +13 -0
  1056. package/packages/core/dist/core/remove/removal-collector.d.ts.map +1 -0
  1057. package/packages/core/dist/core/remove/removal-collector.js +52 -0
  1058. package/packages/core/dist/core/remove/removal-collector.js.map +1 -0
  1059. package/packages/core/dist/core/remove/removal-confirmation.d.ts +26 -0
  1060. package/packages/core/dist/core/remove/removal-confirmation.d.ts.map +1 -0
  1061. package/packages/core/dist/core/remove/removal-confirmation.js +30 -0
  1062. package/packages/core/dist/core/remove/removal-confirmation.js.map +1 -0
  1063. package/packages/core/dist/core/remove/remove-dependency-flow.d.ts +18 -0
  1064. package/packages/core/dist/core/remove/remove-dependency-flow.d.ts.map +1 -0
  1065. package/packages/core/dist/core/remove/remove-dependency-flow.js +23 -0
  1066. package/packages/core/dist/core/remove/remove-dependency-flow.js.map +1 -0
  1067. package/packages/core/dist/core/remove/remove-from-source-pipeline.d.ts +32 -0
  1068. package/packages/core/dist/core/remove/remove-from-source-pipeline.d.ts.map +1 -0
  1069. package/packages/core/dist/core/remove/remove-from-source-pipeline.js +260 -0
  1070. package/packages/core/dist/core/remove/remove-from-source-pipeline.js.map +1 -0
  1071. package/packages/core/dist/core/remove/remove-input-classifier.d.ts +22 -0
  1072. package/packages/core/dist/core/remove/remove-input-classifier.d.ts.map +1 -0
  1073. package/packages/core/dist/core/remove/remove-input-classifier.js +53 -0
  1074. package/packages/core/dist/core/remove/remove-input-classifier.js.map +1 -0
  1075. package/packages/core/dist/core/resources/disambiguation-prompt.d.ts +38 -0
  1076. package/packages/core/dist/core/resources/disambiguation-prompt.d.ts.map +1 -0
  1077. package/packages/core/dist/core/resources/disambiguation-prompt.js +60 -0
  1078. package/packages/core/dist/core/resources/disambiguation-prompt.js.map +1 -0
  1079. package/packages/core/dist/core/resources/installed-resources.d.ts +4 -0
  1080. package/packages/core/dist/core/resources/installed-resources.d.ts.map +1 -0
  1081. package/packages/core/dist/core/resources/installed-resources.js +35 -0
  1082. package/packages/core/dist/core/resources/installed-resources.js.map +1 -0
  1083. package/packages/core/dist/core/resources/markdown-metadata.d.ts +7 -0
  1084. package/packages/core/dist/core/resources/markdown-metadata.d.ts.map +1 -0
  1085. package/packages/core/dist/core/resources/markdown-metadata.js +24 -0
  1086. package/packages/core/dist/core/resources/markdown-metadata.js.map +1 -0
  1087. package/packages/core/dist/core/resources/resource-builder.d.ts +52 -0
  1088. package/packages/core/dist/core/resources/resource-builder.d.ts.map +1 -0
  1089. package/packages/core/dist/core/resources/resource-builder.js +140 -0
  1090. package/packages/core/dist/core/resources/resource-builder.js.map +1 -0
  1091. package/packages/core/dist/core/resources/resource-catalog.d.ts +26 -0
  1092. package/packages/core/dist/core/resources/resource-catalog.d.ts.map +1 -0
  1093. package/packages/core/dist/core/resources/resource-catalog.js +20 -0
  1094. package/packages/core/dist/core/resources/resource-catalog.js.map +1 -0
  1095. package/packages/core/dist/core/resources/resource-namespace.d.ts +25 -0
  1096. package/packages/core/dist/core/resources/resource-namespace.d.ts.map +1 -0
  1097. package/packages/core/dist/core/resources/resource-namespace.js +84 -0
  1098. package/packages/core/dist/core/resources/resource-namespace.js.map +1 -0
  1099. package/packages/core/dist/core/resources/resource-naming.d.ts +11 -0
  1100. package/packages/core/dist/core/resources/resource-naming.d.ts.map +1 -0
  1101. package/packages/core/dist/core/resources/resource-naming.js +29 -0
  1102. package/packages/core/dist/core/resources/resource-naming.js.map +1 -0
  1103. package/packages/core/dist/core/resources/resource-registry.d.ts +14 -0
  1104. package/packages/core/dist/core/resources/resource-registry.d.ts.map +1 -0
  1105. package/packages/core/dist/core/resources/resource-registry.js +43 -0
  1106. package/packages/core/dist/core/resources/resource-registry.js.map +1 -0
  1107. package/packages/core/dist/core/resources/resource-resolver.d.ts +42 -0
  1108. package/packages/core/dist/core/resources/resource-resolver.d.ts.map +1 -0
  1109. package/packages/core/dist/core/resources/resource-resolver.js +67 -0
  1110. package/packages/core/dist/core/resources/resource-resolver.js.map +1 -0
  1111. package/packages/core/dist/core/resources/scope-traversal.d.ts +37 -0
  1112. package/packages/core/dist/core/resources/scope-traversal.d.ts.map +1 -0
  1113. package/packages/core/dist/core/resources/scope-traversal.js +52 -0
  1114. package/packages/core/dist/core/resources/scope-traversal.js.map +1 -0
  1115. package/packages/core/dist/core/resources/source-key-classifier.d.ts +6 -0
  1116. package/packages/core/dist/core/resources/source-key-classifier.d.ts.map +1 -0
  1117. package/packages/core/dist/core/resources/source-key-classifier.js +22 -0
  1118. package/packages/core/dist/core/resources/source-key-classifier.js.map +1 -0
  1119. package/packages/core/dist/core/save/save-candidate-builder.d.ts +57 -0
  1120. package/packages/core/dist/core/save/save-candidate-builder.d.ts.map +1 -0
  1121. package/packages/core/dist/core/save/save-candidate-builder.js +293 -0
  1122. package/packages/core/dist/core/save/save-candidate-builder.js.map +1 -0
  1123. package/packages/core/dist/core/save/save-conflict-analyzer.d.ts +120 -0
  1124. package/packages/core/dist/core/save/save-conflict-analyzer.d.ts.map +1 -0
  1125. package/packages/core/dist/core/save/save-conflict-analyzer.js +305 -0
  1126. package/packages/core/dist/core/save/save-conflict-analyzer.js.map +1 -0
  1127. package/packages/core/dist/core/save/save-conversion-helper.d.ts +84 -0
  1128. package/packages/core/dist/core/save/save-conversion-helper.d.ts.map +1 -0
  1129. package/packages/core/dist/core/save/save-conversion-helper.js +522 -0
  1130. package/packages/core/dist/core/save/save-conversion-helper.js.map +1 -0
  1131. package/packages/core/dist/core/save/save-group-builder.d.ts +49 -0
  1132. package/packages/core/dist/core/save/save-group-builder.d.ts.map +1 -0
  1133. package/packages/core/dist/core/save/save-group-builder.js +233 -0
  1134. package/packages/core/dist/core/save/save-group-builder.js.map +1 -0
  1135. package/packages/core/dist/core/save/save-interactive-resolver.d.ts +73 -0
  1136. package/packages/core/dist/core/save/save-interactive-resolver.d.ts.map +1 -0
  1137. package/packages/core/dist/core/save/save-interactive-resolver.js +300 -0
  1138. package/packages/core/dist/core/save/save-interactive-resolver.js.map +1 -0
  1139. package/packages/core/dist/core/save/save-merge-extractor.d.ts +61 -0
  1140. package/packages/core/dist/core/save/save-merge-extractor.d.ts.map +1 -0
  1141. package/packages/core/dist/core/save/save-merge-extractor.js +272 -0
  1142. package/packages/core/dist/core/save/save-merge-extractor.js.map +1 -0
  1143. package/packages/core/dist/core/save/save-platform-handler.d.ts +51 -0
  1144. package/packages/core/dist/core/save/save-platform-handler.d.ts.map +1 -0
  1145. package/packages/core/dist/core/save/save-platform-handler.js +93 -0
  1146. package/packages/core/dist/core/save/save-platform-handler.js.map +1 -0
  1147. package/packages/core/dist/core/save/save-resolution-executor.d.ts +40 -0
  1148. package/packages/core/dist/core/save/save-resolution-executor.d.ts.map +1 -0
  1149. package/packages/core/dist/core/save/save-resolution-executor.js +197 -0
  1150. package/packages/core/dist/core/save/save-resolution-executor.js.map +1 -0
  1151. package/packages/core/dist/core/save/save-result-reporter.d.ts +109 -0
  1152. package/packages/core/dist/core/save/save-result-reporter.d.ts.map +1 -0
  1153. package/packages/core/dist/core/save/save-result-reporter.js +176 -0
  1154. package/packages/core/dist/core/save/save-result-reporter.js.map +1 -0
  1155. package/packages/core/dist/core/save/save-to-source-pipeline.d.ts +45 -0
  1156. package/packages/core/dist/core/save/save-to-source-pipeline.d.ts.map +1 -0
  1157. package/packages/core/dist/core/save/save-to-source-pipeline.js +234 -0
  1158. package/packages/core/dist/core/save/save-to-source-pipeline.js.map +1 -0
  1159. package/packages/core/dist/core/save/save-types.d.ts +157 -0
  1160. package/packages/core/dist/core/save/save-types.d.ts.map +1 -0
  1161. package/packages/core/dist/core/save/save-types.js +8 -0
  1162. package/packages/core/dist/core/save/save-types.js.map +1 -0
  1163. package/packages/core/dist/core/save/save-write-coordinator.d.ts +36 -0
  1164. package/packages/core/dist/core/save/save-write-coordinator.d.ts.map +1 -0
  1165. package/packages/core/dist/core/save/save-write-coordinator.js +571 -0
  1166. package/packages/core/dist/core/save/save-write-coordinator.js.map +1 -0
  1167. package/packages/core/dist/core/scope-resolution.d.ts +64 -0
  1168. package/packages/core/dist/core/scope-resolution.d.ts.map +1 -0
  1169. package/packages/core/dist/core/scope-resolution.js +143 -0
  1170. package/packages/core/dist/core/scope-resolution.js.map +1 -0
  1171. package/packages/core/dist/core/scoping/package-scoping.d.ts +35 -0
  1172. package/packages/core/dist/core/scoping/package-scoping.d.ts.map +1 -0
  1173. package/packages/core/dist/core/scoping/package-scoping.js +234 -0
  1174. package/packages/core/dist/core/scoping/package-scoping.js.map +1 -0
  1175. package/packages/core/dist/core/search/search-pipeline.d.ts +55 -0
  1176. package/packages/core/dist/core/search/search-pipeline.d.ts.map +1 -0
  1177. package/packages/core/dist/core/search/search-pipeline.js +120 -0
  1178. package/packages/core/dist/core/search/search-pipeline.js.map +1 -0
  1179. package/packages/core/dist/core/set/set-output.d.ts +23 -0
  1180. package/packages/core/dist/core/set/set-output.d.ts.map +1 -0
  1181. package/packages/core/dist/core/set/set-output.js +77 -0
  1182. package/packages/core/dist/core/set/set-output.js.map +1 -0
  1183. package/packages/core/dist/core/set/set-pipeline.d.ts +13 -0
  1184. package/packages/core/dist/core/set/set-pipeline.d.ts.map +1 -0
  1185. package/packages/core/dist/core/set/set-pipeline.js +334 -0
  1186. package/packages/core/dist/core/set/set-pipeline.js.map +1 -0
  1187. package/packages/core/dist/core/set/set-types.d.ts +50 -0
  1188. package/packages/core/dist/core/set/set-types.d.ts.map +1 -0
  1189. package/packages/core/dist/core/set/set-types.js +5 -0
  1190. package/packages/core/dist/core/set/set-types.js.map +1 -0
  1191. package/packages/core/dist/core/source-mutability.d.ts +6 -0
  1192. package/packages/core/dist/core/source-mutability.d.ts.map +1 -0
  1193. package/packages/core/dist/core/source-mutability.js +15 -0
  1194. package/packages/core/dist/core/source-mutability.js.map +1 -0
  1195. package/packages/core/dist/core/source-resolution/dependency-graph.d.ts +8 -0
  1196. package/packages/core/dist/core/source-resolution/dependency-graph.d.ts.map +1 -0
  1197. package/packages/core/dist/core/source-resolution/dependency-graph.js +115 -0
  1198. package/packages/core/dist/core/source-resolution/dependency-graph.js.map +1 -0
  1199. package/packages/core/dist/core/source-resolution/resolve-mutable-source.d.ts +31 -0
  1200. package/packages/core/dist/core/source-resolution/resolve-mutable-source.d.ts.map +1 -0
  1201. package/packages/core/dist/core/source-resolution/resolve-mutable-source.js +110 -0
  1202. package/packages/core/dist/core/source-resolution/resolve-mutable-source.js.map +1 -0
  1203. package/packages/core/dist/core/source-resolution/resolve-package-source.d.ts +3 -0
  1204. package/packages/core/dist/core/source-resolution/resolve-package-source.d.ts.map +1 -0
  1205. package/packages/core/dist/core/source-resolution/resolve-package-source.js +29 -0
  1206. package/packages/core/dist/core/source-resolution/resolve-package-source.js.map +1 -0
  1207. package/packages/core/dist/core/source-resolution/resolve-registry-version.d.ts +31 -0
  1208. package/packages/core/dist/core/source-resolution/resolve-registry-version.d.ts.map +1 -0
  1209. package/packages/core/dist/core/source-resolution/resolve-registry-version.js +47 -0
  1210. package/packages/core/dist/core/source-resolution/resolve-registry-version.js.map +1 -0
  1211. package/packages/core/dist/core/source-resolution/types.d.ts +39 -0
  1212. package/packages/core/dist/core/source-resolution/types.d.ts.map +1 -0
  1213. package/packages/core/dist/core/source-resolution/types.js +2 -0
  1214. package/packages/core/dist/core/source-resolution/types.js.map +1 -0
  1215. package/packages/core/dist/core/telemetry.d.ts +59 -0
  1216. package/packages/core/dist/core/telemetry.d.ts.map +1 -0
  1217. package/packages/core/dist/core/telemetry.js +166 -0
  1218. package/packages/core/dist/core/telemetry.js.map +1 -0
  1219. package/packages/core/dist/core/uninstall/direct-uninstall-flow.d.ts +37 -0
  1220. package/packages/core/dist/core/uninstall/direct-uninstall-flow.d.ts.map +1 -0
  1221. package/packages/core/dist/core/uninstall/direct-uninstall-flow.js +88 -0
  1222. package/packages/core/dist/core/uninstall/direct-uninstall-flow.js.map +1 -0
  1223. package/packages/core/dist/core/uninstall/flow-aware-uninstaller.d.ts +34 -0
  1224. package/packages/core/dist/core/uninstall/flow-aware-uninstaller.d.ts.map +1 -0
  1225. package/packages/core/dist/core/uninstall/flow-aware-uninstaller.js +189 -0
  1226. package/packages/core/dist/core/uninstall/flow-aware-uninstaller.js.map +1 -0
  1227. package/packages/core/dist/core/uninstall/uninstall-executor.d.ts +15 -0
  1228. package/packages/core/dist/core/uninstall/uninstall-executor.d.ts.map +1 -0
  1229. package/packages/core/dist/core/uninstall/uninstall-executor.js +85 -0
  1230. package/packages/core/dist/core/uninstall/uninstall-executor.js.map +1 -0
  1231. package/packages/core/dist/core/uninstall/uninstall-pipeline.d.ts +8 -0
  1232. package/packages/core/dist/core/uninstall/uninstall-pipeline.d.ts.map +1 -0
  1233. package/packages/core/dist/core/uninstall/uninstall-pipeline.js +178 -0
  1234. package/packages/core/dist/core/uninstall/uninstall-pipeline.js.map +1 -0
  1235. package/packages/core/dist/core/uninstall/uninstall-reporter.d.ts +26 -0
  1236. package/packages/core/dist/core/uninstall/uninstall-reporter.d.ts.map +1 -0
  1237. package/packages/core/dist/core/uninstall/uninstall-reporter.js +76 -0
  1238. package/packages/core/dist/core/uninstall/uninstall-reporter.js.map +1 -0
  1239. package/packages/core/dist/core/uninstall/workspace-resource-collector.d.ts +68 -0
  1240. package/packages/core/dist/core/uninstall/workspace-resource-collector.d.ts.map +1 -0
  1241. package/packages/core/dist/core/uninstall/workspace-resource-collector.js +221 -0
  1242. package/packages/core/dist/core/uninstall/workspace-resource-collector.js.map +1 -0
  1243. package/packages/core/dist/core/universal-patterns.d.ts +26 -0
  1244. package/packages/core/dist/core/universal-patterns.d.ts.map +1 -0
  1245. package/packages/core/dist/core/universal-patterns.js +64 -0
  1246. package/packages/core/dist/core/universal-patterns.js.map +1 -0
  1247. package/packages/core/dist/core/unpublish/interactive-unpublish-flow.d.ts +33 -0
  1248. package/packages/core/dist/core/unpublish/interactive-unpublish-flow.d.ts.map +1 -0
  1249. package/packages/core/dist/core/unpublish/interactive-unpublish-flow.js +118 -0
  1250. package/packages/core/dist/core/unpublish/interactive-unpublish-flow.js.map +1 -0
  1251. package/packages/core/dist/core/unpublish/local-unpublish-pipeline.d.ts +8 -0
  1252. package/packages/core/dist/core/unpublish/local-unpublish-pipeline.d.ts.map +1 -0
  1253. package/packages/core/dist/core/unpublish/local-unpublish-pipeline.js +174 -0
  1254. package/packages/core/dist/core/unpublish/local-unpublish-pipeline.js.map +1 -0
  1255. package/packages/core/dist/core/unpublish/unpublish-output.d.ts +7 -0
  1256. package/packages/core/dist/core/unpublish/unpublish-output.d.ts.map +1 -0
  1257. package/packages/core/dist/core/unpublish/unpublish-output.js +27 -0
  1258. package/packages/core/dist/core/unpublish/unpublish-output.js.map +1 -0
  1259. package/packages/core/dist/core/unpublish/unpublish-pipeline.d.ts +6 -0
  1260. package/packages/core/dist/core/unpublish/unpublish-pipeline.d.ts.map +1 -0
  1261. package/packages/core/dist/core/unpublish/unpublish-pipeline.js +17 -0
  1262. package/packages/core/dist/core/unpublish/unpublish-pipeline.js.map +1 -0
  1263. package/packages/core/dist/core/unpublish/unpublish-types.d.ts +17 -0
  1264. package/packages/core/dist/core/unpublish/unpublish-types.d.ts.map +1 -0
  1265. package/packages/core/dist/core/unpublish/unpublish-types.js +2 -0
  1266. package/packages/core/dist/core/unpublish/unpublish-types.js.map +1 -0
  1267. package/packages/core/dist/core/view/view-helpers.d.ts +17 -0
  1268. package/packages/core/dist/core/view/view-helpers.d.ts.map +1 -0
  1269. package/packages/core/dist/core/view/view-helpers.js +32 -0
  1270. package/packages/core/dist/core/view/view-helpers.js.map +1 -0
  1271. package/packages/core/dist/core/view/view-pipeline.d.ts +71 -0
  1272. package/packages/core/dist/core/view/view-pipeline.d.ts.map +1 -0
  1273. package/packages/core/dist/core/view/view-pipeline.js +267 -0
  1274. package/packages/core/dist/core/view/view-pipeline.js.map +1 -0
  1275. package/packages/core/dist/core/view/view-printers.d.ts +21 -0
  1276. package/packages/core/dist/core/view/view-printers.d.ts.map +1 -0
  1277. package/packages/core/dist/core/view/view-printers.js +124 -0
  1278. package/packages/core/dist/core/view/view-printers.js.map +1 -0
  1279. package/packages/core/dist/core/workspace-package-context.d.ts +54 -0
  1280. package/packages/core/dist/core/workspace-package-context.d.ts.map +1 -0
  1281. package/packages/core/dist/core/workspace-package-context.js +68 -0
  1282. package/packages/core/dist/core/workspace-package-context.js.map +1 -0
  1283. package/packages/core/dist/generated/version.d.ts +2 -0
  1284. package/packages/core/dist/generated/version.d.ts.map +1 -0
  1285. package/packages/core/dist/generated/version.js +3 -0
  1286. package/packages/core/dist/generated/version.js.map +1 -0
  1287. package/packages/core/dist/index.d.ts +48 -0
  1288. package/packages/core/dist/index.d.ts.map +1 -0
  1289. package/packages/core/dist/index.js +72 -0
  1290. package/packages/core/dist/index.js.map +1 -0
  1291. package/packages/core/dist/types/api.d.ts +47 -0
  1292. package/packages/core/dist/types/api.d.ts.map +1 -0
  1293. package/packages/core/dist/types/api.js +5 -0
  1294. package/packages/core/dist/types/api.js.map +1 -0
  1295. package/packages/core/dist/types/conversion-context.d.ts +175 -0
  1296. package/packages/core/dist/types/conversion-context.d.ts.map +1 -0
  1297. package/packages/core/dist/types/conversion-context.js +11 -0
  1298. package/packages/core/dist/types/conversion-context.js.map +1 -0
  1299. package/packages/core/dist/types/execution-context.d.ts +122 -0
  1300. package/packages/core/dist/types/execution-context.d.ts.map +1 -0
  1301. package/packages/core/dist/types/execution-context.js +8 -0
  1302. package/packages/core/dist/types/execution-context.js.map +1 -0
  1303. package/packages/core/dist/types/flows.d.ts +360 -0
  1304. package/packages/core/dist/types/flows.d.ts.map +1 -0
  1305. package/packages/core/dist/types/flows.js +8 -0
  1306. package/packages/core/dist/types/flows.js.map +1 -0
  1307. package/packages/core/dist/types/index.d.ts +271 -0
  1308. package/packages/core/dist/types/index.d.ts.map +1 -0
  1309. package/packages/core/dist/types/index.js +36 -0
  1310. package/packages/core/dist/types/index.js.map +1 -0
  1311. package/packages/core/dist/types/install.d.ts +5 -0
  1312. package/packages/core/dist/types/install.d.ts.map +1 -0
  1313. package/packages/core/dist/types/install.js +5 -0
  1314. package/packages/core/dist/types/install.js.map +1 -0
  1315. package/packages/core/dist/types/platform-flows.d.ts +349 -0
  1316. package/packages/core/dist/types/platform-flows.d.ts.map +1 -0
  1317. package/packages/core/dist/types/platform-flows.js +8 -0
  1318. package/packages/core/dist/types/platform-flows.js.map +1 -0
  1319. package/packages/core/dist/types/platform.d.ts +32 -0
  1320. package/packages/core/dist/types/platform.d.ts.map +1 -0
  1321. package/packages/core/dist/types/platform.js +6 -0
  1322. package/packages/core/dist/types/platform.js.map +1 -0
  1323. package/packages/core/dist/types/resources.d.ts +14 -0
  1324. package/packages/core/dist/types/resources.d.ts.map +1 -0
  1325. package/packages/core/dist/types/resources.js +5 -0
  1326. package/packages/core/dist/types/resources.js.map +1 -0
  1327. package/packages/core/dist/types/workspace-index.d.ts +60 -0
  1328. package/packages/core/dist/types/workspace-index.d.ts.map +1 -0
  1329. package/packages/core/dist/types/workspace-index.js +6 -0
  1330. package/packages/core/dist/types/workspace-index.js.map +1 -0
  1331. package/packages/core/dist/utils/cleanup-empty-parents.d.ts +20 -0
  1332. package/packages/core/dist/utils/cleanup-empty-parents.d.ts.map +1 -0
  1333. package/packages/core/dist/utils/cleanup-empty-parents.js +56 -0
  1334. package/packages/core/dist/utils/cleanup-empty-parents.js.map +1 -0
  1335. package/packages/core/dist/utils/custom-path-resolution.d.ts +69 -0
  1336. package/packages/core/dist/utils/custom-path-resolution.d.ts.map +1 -0
  1337. package/packages/core/dist/utils/custom-path-resolution.js +160 -0
  1338. package/packages/core/dist/utils/custom-path-resolution.js.map +1 -0
  1339. package/packages/core/dist/utils/entity-detector.d.ts +33 -0
  1340. package/packages/core/dist/utils/entity-detector.d.ts.map +1 -0
  1341. package/packages/core/dist/utils/entity-detector.js +78 -0
  1342. package/packages/core/dist/utils/entity-detector.js.map +1 -0
  1343. package/packages/core/dist/utils/error-reasons.d.ts +9 -0
  1344. package/packages/core/dist/utils/error-reasons.d.ts.map +1 -0
  1345. package/packages/core/dist/utils/error-reasons.js +51 -0
  1346. package/packages/core/dist/utils/error-reasons.js.map +1 -0
  1347. package/packages/core/dist/utils/errors.d.ts +36 -0
  1348. package/packages/core/dist/utils/errors.d.ts.map +1 -0
  1349. package/packages/core/dist/utils/errors.js +73 -0
  1350. package/packages/core/dist/utils/errors.js.map +1 -0
  1351. package/packages/core/dist/utils/expand-directory-selections.d.ts +37 -0
  1352. package/packages/core/dist/utils/expand-directory-selections.d.ts.map +1 -0
  1353. package/packages/core/dist/utils/expand-directory-selections.js +101 -0
  1354. package/packages/core/dist/utils/expand-directory-selections.js.map +1 -0
  1355. package/packages/core/dist/utils/file-processing.d.ts +26 -0
  1356. package/packages/core/dist/utils/file-processing.d.ts.map +1 -0
  1357. package/packages/core/dist/utils/file-processing.js +91 -0
  1358. package/packages/core/dist/utils/file-processing.js.map +1 -0
  1359. package/packages/core/dist/utils/file-scanner.d.ts +62 -0
  1360. package/packages/core/dist/utils/file-scanner.d.ts.map +1 -0
  1361. package/packages/core/dist/utils/file-scanner.js +168 -0
  1362. package/packages/core/dist/utils/file-scanner.js.map +1 -0
  1363. package/packages/core/dist/utils/file-walker.d.ts +69 -0
  1364. package/packages/core/dist/utils/file-walker.d.ts.map +1 -0
  1365. package/packages/core/dist/utils/file-walker.js +144 -0
  1366. package/packages/core/dist/utils/file-walker.js.map +1 -0
  1367. package/packages/core/dist/utils/formatters.d.ts +93 -0
  1368. package/packages/core/dist/utils/formatters.d.ts.map +1 -0
  1369. package/packages/core/dist/utils/formatters.js +196 -0
  1370. package/packages/core/dist/utils/formatters.js.map +1 -0
  1371. package/packages/core/dist/utils/fs.d.ts +94 -0
  1372. package/packages/core/dist/utils/fs.d.ts.map +1 -0
  1373. package/packages/core/dist/utils/fs.js +362 -0
  1374. package/packages/core/dist/utils/fs.js.map +1 -0
  1375. package/packages/core/dist/utils/git-cache.d.ts +91 -0
  1376. package/packages/core/dist/utils/git-cache.d.ts.map +1 -0
  1377. package/packages/core/dist/utils/git-cache.js +196 -0
  1378. package/packages/core/dist/utils/git-cache.js.map +1 -0
  1379. package/packages/core/dist/utils/git-spec.d.ts +19 -0
  1380. package/packages/core/dist/utils/git-spec.d.ts.map +1 -0
  1381. package/packages/core/dist/utils/git-spec.js +96 -0
  1382. package/packages/core/dist/utils/git-spec.js.map +1 -0
  1383. package/packages/core/dist/utils/git-url-detection.d.ts +92 -0
  1384. package/packages/core/dist/utils/git-url-detection.d.ts.map +1 -0
  1385. package/packages/core/dist/utils/git-url-detection.js +327 -0
  1386. package/packages/core/dist/utils/git-url-detection.js.map +1 -0
  1387. package/packages/core/dist/utils/git-url-parser.d.ts +53 -0
  1388. package/packages/core/dist/utils/git-url-parser.d.ts.map +1 -0
  1389. package/packages/core/dist/utils/git-url-parser.js +113 -0
  1390. package/packages/core/dist/utils/git-url-parser.js.map +1 -0
  1391. package/packages/core/dist/utils/hash-utils.d.ts +14 -0
  1392. package/packages/core/dist/utils/hash-utils.d.ts.map +1 -0
  1393. package/packages/core/dist/utils/hash-utils.js +40 -0
  1394. package/packages/core/dist/utils/hash-utils.js.map +1 -0
  1395. package/packages/core/dist/utils/home-directory.d.ts +41 -0
  1396. package/packages/core/dist/utils/home-directory.d.ts.map +1 -0
  1397. package/packages/core/dist/utils/home-directory.js +71 -0
  1398. package/packages/core/dist/utils/home-directory.js.map +1 -0
  1399. package/packages/core/dist/utils/ini.d.ts +43 -0
  1400. package/packages/core/dist/utils/ini.d.ts.map +1 -0
  1401. package/packages/core/dist/utils/ini.js +120 -0
  1402. package/packages/core/dist/utils/ini.js.map +1 -0
  1403. package/packages/core/dist/utils/install-error-messages.d.ts +32 -0
  1404. package/packages/core/dist/utils/install-error-messages.d.ts.map +1 -0
  1405. package/packages/core/dist/utils/install-error-messages.js +176 -0
  1406. package/packages/core/dist/utils/install-error-messages.js.map +1 -0
  1407. package/packages/core/dist/utils/install-helpers.d.ts +6 -0
  1408. package/packages/core/dist/utils/install-helpers.d.ts.map +1 -0
  1409. package/packages/core/dist/utils/install-helpers.js +6 -0
  1410. package/packages/core/dist/utils/install-helpers.js.map +1 -0
  1411. package/packages/core/dist/utils/jsonc.d.ts +18 -0
  1412. package/packages/core/dist/utils/jsonc.d.ts.map +1 -0
  1413. package/packages/core/dist/utils/jsonc.js +79 -0
  1414. package/packages/core/dist/utils/jsonc.js.map +1 -0
  1415. package/packages/core/dist/utils/logger.d.ts +19 -0
  1416. package/packages/core/dist/utils/logger.d.ts.map +1 -0
  1417. package/packages/core/dist/utils/logger.js +78 -0
  1418. package/packages/core/dist/utils/logger.js.map +1 -0
  1419. package/packages/core/dist/utils/manifest-paths.d.ts +10 -0
  1420. package/packages/core/dist/utils/manifest-paths.d.ts.map +1 -0
  1421. package/packages/core/dist/utils/manifest-paths.js +19 -0
  1422. package/packages/core/dist/utils/manifest-paths.js.map +1 -0
  1423. package/packages/core/dist/utils/package-copy.d.ts +40 -0
  1424. package/packages/core/dist/utils/package-copy.d.ts.map +1 -0
  1425. package/packages/core/dist/utils/package-copy.js +101 -0
  1426. package/packages/core/dist/utils/package-copy.js.map +1 -0
  1427. package/packages/core/dist/utils/package-filters.d.ts +2 -0
  1428. package/packages/core/dist/utils/package-filters.d.ts.map +1 -0
  1429. package/packages/core/dist/utils/package-filters.js +29 -0
  1430. package/packages/core/dist/utils/package-filters.js.map +1 -0
  1431. package/packages/core/dist/utils/package-index-yml.d.ts +26 -0
  1432. package/packages/core/dist/utils/package-index-yml.d.ts.map +1 -0
  1433. package/packages/core/dist/utils/package-index-yml.js +172 -0
  1434. package/packages/core/dist/utils/package-index-yml.js.map +1 -0
  1435. package/packages/core/dist/utils/package-merge.d.ts +13 -0
  1436. package/packages/core/dist/utils/package-merge.d.ts.map +1 -0
  1437. package/packages/core/dist/utils/package-merge.js +48 -0
  1438. package/packages/core/dist/utils/package-merge.js.map +1 -0
  1439. package/packages/core/dist/utils/package-name.d.ts +84 -0
  1440. package/packages/core/dist/utils/package-name.d.ts.map +1 -0
  1441. package/packages/core/dist/utils/package-name.js +265 -0
  1442. package/packages/core/dist/utils/package-name.js.map +1 -0
  1443. package/packages/core/dist/utils/package-yml.d.ts +11 -0
  1444. package/packages/core/dist/utils/package-yml.d.ts.map +1 -0
  1445. package/packages/core/dist/utils/package-yml.js +280 -0
  1446. package/packages/core/dist/utils/package-yml.js.map +1 -0
  1447. package/packages/core/dist/utils/package.d.ts +5 -0
  1448. package/packages/core/dist/utils/package.d.ts.map +1 -0
  1449. package/packages/core/dist/utils/package.js +8 -0
  1450. package/packages/core/dist/utils/package.js.map +1 -0
  1451. package/packages/core/dist/utils/path-comparison.d.ts +52 -0
  1452. package/packages/core/dist/utils/path-comparison.d.ts.map +1 -0
  1453. package/packages/core/dist/utils/path-comparison.js +110 -0
  1454. package/packages/core/dist/utils/path-comparison.js.map +1 -0
  1455. package/packages/core/dist/utils/path-normalization.d.ts +54 -0
  1456. package/packages/core/dist/utils/path-normalization.d.ts.map +1 -0
  1457. package/packages/core/dist/utils/path-normalization.js +116 -0
  1458. package/packages/core/dist/utils/path-normalization.js.map +1 -0
  1459. package/packages/core/dist/utils/path-resolution.d.ts +36 -0
  1460. package/packages/core/dist/utils/path-resolution.d.ts.map +1 -0
  1461. package/packages/core/dist/utils/path-resolution.js +106 -0
  1462. package/packages/core/dist/utils/path-resolution.js.map +1 -0
  1463. package/packages/core/dist/utils/paths.d.ts +35 -0
  1464. package/packages/core/dist/utils/paths.d.ts.map +1 -0
  1465. package/packages/core/dist/utils/paths.js +70 -0
  1466. package/packages/core/dist/utils/paths.js.map +1 -0
  1467. package/packages/core/dist/utils/pattern-matcher.d.ts +66 -0
  1468. package/packages/core/dist/utils/pattern-matcher.d.ts.map +1 -0
  1469. package/packages/core/dist/utils/pattern-matcher.js +195 -0
  1470. package/packages/core/dist/utils/pattern-matcher.js.map +1 -0
  1471. package/packages/core/dist/utils/platform-yaml-merge.d.ts +6 -0
  1472. package/packages/core/dist/utils/platform-yaml-merge.d.ts.map +1 -0
  1473. package/packages/core/dist/utils/platform-yaml-merge.js +6 -0
  1474. package/packages/core/dist/utils/platform-yaml-merge.js.map +1 -0
  1475. package/packages/core/dist/utils/plugin-naming.d.ts +160 -0
  1476. package/packages/core/dist/utils/plugin-naming.d.ts.map +1 -0
  1477. package/packages/core/dist/utils/plugin-naming.js +401 -0
  1478. package/packages/core/dist/utils/plugin-naming.js.map +1 -0
  1479. package/packages/core/dist/utils/resolution-mode.d.ts +10 -0
  1480. package/packages/core/dist/utils/resolution-mode.d.ts.map +1 -0
  1481. package/packages/core/dist/utils/resolution-mode.js +16 -0
  1482. package/packages/core/dist/utils/resolution-mode.js.map +1 -0
  1483. package/packages/core/dist/utils/resource-arg-parser.d.ts +48 -0
  1484. package/packages/core/dist/utils/resource-arg-parser.d.ts.map +1 -0
  1485. package/packages/core/dist/utils/resource-arg-parser.js +231 -0
  1486. package/packages/core/dist/utils/resource-arg-parser.js.map +1 -0
  1487. package/packages/core/dist/utils/root-file-extractor.d.ts +55 -0
  1488. package/packages/core/dist/utils/root-file-extractor.d.ts.map +1 -0
  1489. package/packages/core/dist/utils/root-file-extractor.js +115 -0
  1490. package/packages/core/dist/utils/root-file-extractor.js.map +1 -0
  1491. package/packages/core/dist/utils/root-file-merger.d.ts +15 -0
  1492. package/packages/core/dist/utils/root-file-merger.d.ts.map +1 -0
  1493. package/packages/core/dist/utils/root-file-merger.js +57 -0
  1494. package/packages/core/dist/utils/root-file-merger.js.map +1 -0
  1495. package/packages/core/dist/utils/source-operation-arguments.d.ts +48 -0
  1496. package/packages/core/dist/utils/source-operation-arguments.d.ts.map +1 -0
  1497. package/packages/core/dist/utils/source-operation-arguments.js +66 -0
  1498. package/packages/core/dist/utils/source-operation-arguments.js.map +1 -0
  1499. package/packages/core/dist/utils/tarball.d.ts +30 -0
  1500. package/packages/core/dist/utils/tarball.d.ts.map +1 -0
  1501. package/packages/core/dist/utils/tarball.js +200 -0
  1502. package/packages/core/dist/utils/tarball.js.map +1 -0
  1503. package/packages/core/dist/utils/validation/index.d.ts +4 -0
  1504. package/packages/core/dist/utils/validation/index.d.ts.map +1 -0
  1505. package/packages/core/dist/utils/validation/index.js +5 -0
  1506. package/packages/core/dist/utils/validation/index.js.map +1 -0
  1507. package/packages/core/dist/utils/validation/manifest.d.ts +16 -0
  1508. package/packages/core/dist/utils/validation/manifest.d.ts.map +1 -0
  1509. package/packages/core/dist/utils/validation/manifest.js +27 -0
  1510. package/packages/core/dist/utils/validation/manifest.js.map +1 -0
  1511. package/packages/core/dist/utils/validation/package-files.d.ts +13 -0
  1512. package/packages/core/dist/utils/validation/package-files.d.ts.map +1 -0
  1513. package/packages/core/dist/utils/validation/package-files.js +15 -0
  1514. package/packages/core/dist/utils/validation/package-files.js.map +1 -0
  1515. package/packages/core/dist/utils/validation/version.d.ts +24 -0
  1516. package/packages/core/dist/utils/validation/version.d.ts.map +1 -0
  1517. package/packages/core/dist/utils/validation/version.js +42 -0
  1518. package/packages/core/dist/utils/validation/version.js.map +1 -0
  1519. package/packages/core/dist/utils/version-generator.d.ts +58 -0
  1520. package/packages/core/dist/utils/version-generator.d.ts.map +1 -0
  1521. package/packages/core/dist/utils/version-generator.js +132 -0
  1522. package/packages/core/dist/utils/version-generator.js.map +1 -0
  1523. package/packages/core/dist/utils/version-ranges.d.ts +88 -0
  1524. package/packages/core/dist/utils/version-ranges.d.ts.map +1 -0
  1525. package/packages/core/dist/utils/version-ranges.js +342 -0
  1526. package/packages/core/dist/utils/version-ranges.js.map +1 -0
  1527. package/packages/core/dist/utils/workspace-index-helpers.d.ts +17 -0
  1528. package/packages/core/dist/utils/workspace-index-helpers.d.ts.map +1 -0
  1529. package/packages/core/dist/utils/workspace-index-helpers.js +28 -0
  1530. package/packages/core/dist/utils/workspace-index-helpers.js.map +1 -0
  1531. package/packages/core/dist/utils/workspace-index-ownership.d.ts +32 -0
  1532. package/packages/core/dist/utils/workspace-index-ownership.d.ts.map +1 -0
  1533. package/packages/core/dist/utils/workspace-index-ownership.js +111 -0
  1534. package/packages/core/dist/utils/workspace-index-ownership.js.map +1 -0
  1535. package/packages/core/dist/utils/workspace-index-yml.d.ts +9 -0
  1536. package/packages/core/dist/utils/workspace-index-yml.d.ts.map +1 -0
  1537. package/packages/core/dist/utils/workspace-index-yml.js +300 -0
  1538. package/packages/core/dist/utils/workspace-index-yml.js.map +1 -0
  1539. package/packages/core/dist/utils/workspace-package-context.d.ts +6 -0
  1540. package/packages/core/dist/utils/workspace-package-context.d.ts.map +1 -0
  1541. package/packages/core/dist/utils/workspace-package-context.js +6 -0
  1542. package/packages/core/dist/utils/workspace-package-context.js.map +1 -0
  1543. package/packages/core/package.json +96 -0
  1544. package/packages/gui/package.json +24 -0
  1545. package/packages/gui/src-tauri/Cargo.toml +14 -0
  1546. package/turbo.json +15 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../core/src/core/install/orchestrator/orchestrator.ts", "../../core/src/core/install/ambiguity-prompts.ts", "../../core/src/core/install/marketplace-handler.ts", "../../core/src/core/install/unified/context-builders.ts", "../../core/src/core/install/sources/base.ts", "../../core/src/core/install/local-source-resolution.ts", "../../core/src/core/source-resolution/resolve-registry-version.ts", "../../core/src/core/install/version-selection.ts", "../../core/src/core/install/download-keys.ts", "../../core/src/utils/error-reasons.ts", "../../core/src/core/install/remote-reporting.ts", "../../core/src/core/install/sources/registry-source.ts", "../../core/src/core/install/sources/path-source.ts", "../../core/src/core/install/base-detector.ts", "../../core/src/utils/pattern-matcher.ts", "../../core/src/utils/install-error-messages.ts", "../../core/src/core/install/sources/git-source.ts", "../../core/src/core/install/sources/workspace-source.ts", "../../core/src/core/install/sources/loader-factory.ts", "../../core/src/core/install/unified/context-helpers.ts", "../../core/src/core/install/unified/phases/load-package.ts", "../../core/src/core/install/import-flow-converter.ts", "../../core/src/core/install/format-group-merger.ts", "../../core/src/core/install/conversion-context.ts", "../../core/src/core/install/conversion-coordinator.ts", "../../core/src/core/install/unified/phases/convert.ts", "../../core/src/core/install/strategies/helpers/temp-directory.ts", "../../core/src/core/install/unified/phases/resolve-dependencies.ts", "../../core/src/core/install/install-helpers.ts", "../../core/src/core/install/install-errors.ts", "../../core/src/core/install/remote-flow.ts", "../../core/src/core/dependency-resolver/resolver.ts", "../../core/src/core/openpackage.ts", "../../core/src/core/dependency-resolver/prompts.ts", "../../core/src/core/install/operations/conflict-handler.ts", "../../core/src/core/install/unified/phases/conflicts.ts", "../../core/src/core/install/helpers/file-discovery.ts", "../../core/src/core/install/operations/root-files.ts", "../../core/src/core/install/flow-index-installer.ts", "../../core/src/core/install/strategies/conversion-strategy.ts", "../../core/src/core/install/strategies/helpers/result-converter.ts", "../../core/src/core/install/strategies/helpers/flow-helpers.ts", "../../core/src/core/install/helpers/result-logging.ts", "../../core/src/core/install/strategies/base-strategy.ts", "../../core/src/core/flows/platform-converter.ts", "../../core/src/core/install/strategies/flow-based-strategy.ts", "../../core/src/core/install/strategies/helpers/platform-filtering.ts", "../../core/src/core/flows/flow-source-discovery.ts", "../../core/src/core/flows/flow-execution-coordinator.ts", "../../core/src/core/install/conflicts/file-conflict-resolver.ts", "../../core/src/core/install/index-based-installer.ts", "../../core/src/core/install/strategies/strategy-selector.ts", "../../core/src/core/install/helpers/format-detection.ts", "../../core/src/core/install/flow-based-installer.ts", "../../core/src/core/install/helpers/result-aggregation.ts", "../../core/src/core/install/operations/installation-executor.ts", "../../core/src/core/dependency-resolver/display.ts", "../../core/src/core/install/package-installation.ts", "../../core/src/core/install/platform-resolution.ts", "../../core/src/core/install/unified/phases/execute.ts", "../../core/src/core/install/unified/phases/manifest.ts", "../../core/src/core/install/install-reporting.ts", "../../core/src/core/install/unified/phases/report.ts", "../../core/src/core/install/unified/pipeline.ts", "../../core/src/core/install/unified/multi-context-pipeline.ts", "../../core/src/core/install/resource-selection-menu.ts", "../../core/src/core/install/plugin-sources.ts", "../../core/src/core/install/validators/target-validator.ts", "../../core/src/core/install/orchestrator/strategies/base.ts", "../../core/src/core/install/orchestrator/strategies/git-strategy.ts", "../../core/src/core/install/orchestrator/strategies/path-strategy.ts", "../../core/src/core/install/orchestrator/strategies/registry-strategy.ts", "../../core/src/core/install/orchestrator/strategies/bulk-strategy.ts", "../../core/src/core/install/orchestrator/strategies/index.ts", "../../core/src/core/install/resolution/graph-builder.ts", "../../core/src/core/install/resolution/id-generator.ts", "../../core/src/core/install/resolution/manifest-reader.ts", "../../core/src/core/install/resolution/content-root-cache.ts", "../../core/src/core/install/resolution/package-loader.ts", "../../core/src/core/install/resolution/installation-planner.ts", "../../core/src/core/install/resolution/version-solver.ts", "../../core/src/core/install/resolution/executor.ts", "../../core/src/core/install/list-handler.ts", "../../core/src/core/install/orchestrator/subsumption-resolver.ts", "../../core/src/core/telemetry.ts", "../src/commands/install.ts"],
4
+ "sourcesContent": ["import { relative, resolve } from 'path';\nimport type { CommandResult, InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport type { InstallationContext } from '../unified/context.js';\nimport type { \n NormalizedInstallOptions, \n InputClassification, \n PreprocessResult,\n InstallStrategy \n} from './types.js';\nimport { \n promptBaseSelection, \n handleAmbiguityNonInteractive,\n type BaseMatch \n} from '../ambiguity-prompts.js';\nimport { createInteractionPolicy, PromptTier } from '../../interaction-policy.js';\nimport type { InteractionPolicy } from '../../interaction-policy.js';\nimport type { OutputPort } from '../../ports/output.js';\nimport { resolveOutput, resolvePrompt } from '../../ports/resolve.js';\nimport {\n parseMarketplace,\n promptPluginSelection,\n promptInstallMode,\n installMarketplacePlugins,\n validatePluginNames,\n resolvePluginContentRoots,\n type MarketplaceManifest\n} from '../marketplace-handler.js';\nimport { resolvePlatforms } from '../platform-resolution.js';\nimport { classifyInput } from '../preprocessing/input-classifier.js';\nimport { assertTargetDirOutsideMetadata, validateResolutionFlags } from '../validators/index.js';\nimport { runUnifiedInstallPipeline } from '../unified/pipeline.js';\nimport { runMultiContextPipeline } from '../unified/multi-context-pipeline.js';\nimport { createAllStrategies } from './strategies/index.js';\nimport { DependencyResolutionExecutor } from '../resolution/executor.js';\nimport { getManifestPathAtContentRoot } from '../resolution/manifest-reader.js';\nimport { handleListSelection } from '../list-handler.js';\nimport { discoverResources } from '../resource-discoverer.js';\nimport { promptResourceSelection, displaySelectionSummary } from '../resource-selection-menu.js';\nimport { buildResourceInstallContexts } from '../unified/context-builders.js';\nimport { logger } from '../../../utils/logger.js';\nimport type { ResourceInstallationSpec } from '../convenience-matchers.js';\nimport type { SelectedResource, ResourceDiscoveryResult, DiscoveredResource, ResourceType } from '../resource-types.js';\nimport { checkSubsumption, resolveSubsumption } from './subsumption-resolver.js';\n\n/**\n * InstallOrchestrator coordinates the entire install flow.\n * \n * Responsibilities:\n * 1. Classify input \u2192 select strategy\n * 2. Build context via strategy\n * 3. Preprocess (load, detect base, check special cases)\n * 4. Route based on PreprocessResult:\n * - marketplace \u2192 marketplace handler\n * - ambiguous \u2192 ambiguity handler \u2192 pipeline\n * - multi-resource \u2192 multi-context pipeline\n * - normal \u2192 unified pipeline\n */\nexport class InstallOrchestrator {\n private strategies: InstallStrategy[] = [];\n \n /**\n * Register an install strategy.\n */\n registerStrategy(strategy: InstallStrategy): void {\n this.strategies.push(strategy);\n }\n \n /**\n * Execute the install flow.\n * \n * @param input - Package input (undefined for bulk install)\n * @param options - Normalized install options\n * @param execContext - Execution context (sourceCwd, targetDir, isGlobal)\n */\n async execute(\n input: string | undefined,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<CommandResult> {\n // Step 1: Validate\n assertTargetDirOutsideMetadata(execContext.targetDir);\n validateResolutionFlags(options);\n \n // Step 1.5: Create interaction policy (single source of truth for prompting)\n // This validates --interactive + TTY requirement and throws early if invalid\n const policy = createInteractionPolicy({\n interactive: options.interactive,\n force: options.force,\n });\n execContext.interactionPolicy = policy;\n \n const out = resolveOutput(execContext);\n \n // Step 2: Classify input (use sourceCwd for resolving input paths)\n const classification = await classifyInput(input, options, execContext);\n logger.info('Classified install input', { \n type: classification.type,\n features: classification.features \n });\n \n // Step 3: Select strategy\n const strategy = this.selectStrategy(classification);\n if (!strategy) {\n throw new Error(`No strategy found for input type: ${classification.type}`);\n }\n \n // Step 4: Build context (pass ExecutionContext)\n const context = await strategy.buildContext(classification, options, execContext);\n \n // Step 5: Preprocess (load, detect base, check special handling)\n const preprocessResult = await strategy.preprocess(context, options, execContext);\n \n // Step 6: Route based on result\n return this.routeToHandler(preprocessResult, options, execContext, policy, out);\n }\n \n /**\n * Select the appropriate strategy for the given classification.\n */\n private selectStrategy(classification: InputClassification): InstallStrategy | undefined {\n for (const strategy of this.strategies) {\n if (strategy.canHandle(classification)) {\n return strategy;\n }\n }\n return undefined;\n }\n \n /**\n * Route to appropriate handler based on preprocess result.\n */\n private async routeToHandler(\n result: PreprocessResult,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext,\n policy: InteractionPolicy,\n out: OutputPort\n ): Promise<CommandResult> {\n const { context, specialHandling } = result;\n\n switch (specialHandling) {\n case 'marketplace':\n return this.handleMarketplace(result, options, execContext, policy, out);\n \n case 'ambiguous':\n return this.handleAmbiguous(result, options, execContext, policy);\n \n case 'multi-resource':\n return this.handleMultiResource(result, options, execContext, policy);\n \n default: {\n // Handle --interactive option (interactive resource selection)\n if (policy.mode === 'always' && options.interactive) {\n return this.handleList(context, options, execContext);\n }\n \n // Check for subsumption (resource/package overlap)\n const subsumptionResult = await this.checkAndResolveSubsumption(context, options, out);\n if (subsumptionResult) {\n return subsumptionResult;\n }\n \n // Normal pipeline flow: resolve platforms once if not set\n if (context.platforms.length === 0) {\n context.platforms = await resolvePlatforms(context.targetDir, options.platforms, { interactive: policy.canPrompt(PromptTier.Required) });\n }\n // For path/git sources with manifests, install root first (updates manifest),\n // then run executor for dependencies only (with skipManifestUpdate)\n const isPathOrGit = context.source.type === 'path' || context.source.type === 'git';\n const contentRoot = context.source.contentRoot;\n const rootManifestPath =\n isPathOrGit && contentRoot ? await getManifestPathAtContentRoot(contentRoot) : null;\n if (rootManifestPath) {\n // Install root package first (this updates the workspace manifest)\n const rootResult = await runUnifiedInstallPipeline(context);\n // Then install dependencies via executor (skipManifestUpdate for deps)\n return this.installDependenciesOnly(rootManifestPath, rootResult, context, options, execContext);\n }\n return runUnifiedInstallPipeline(context);\n }\n }\n }\n\n /**\n * Check for subsumption (resource/package overlap) and resolve if needed.\n * \n * Returns a CommandResult if the install should be skipped (already-covered),\n * or null to proceed with normal installation.\n * \n * For upgrade scenarios (resource -> full package), cleans up the old entries\n * and returns null so the full install proceeds.\n */\n private async checkAndResolveSubsumption(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n out: OutputPort\n ): Promise<CommandResult | null> {\n // --force bypasses subsumption checks entirely\n if (options.force) {\n return null;\n }\n\n try {\n const result = await checkSubsumption(context.source, context.targetDir);\n\n switch (result.type) {\n case 'upgrade': {\n // Resource entries exist that will be subsumed by the full package\n const names = result.entriesToRemove.map(e => e.packageName).join(', ');\n out.info(`Upgrading to full package ${context.source.packageName} (replacing: ${names})`);\n await resolveSubsumption(result, context.targetDir);\n return null; // Proceed with install\n }\n\n case 'already-covered': {\n // Full package already installed; skip resource install\n const resourcePath = context.source.resourcePath || \n context.source.packageName.replace(/^.*?\\/[^/]+\\/[^/]+\\//, '');\n out.info(`Skipped: ${resourcePath} is already installed via ${result.coveringPackage}`);\n return {\n success: true,\n data: {\n packageName: context.source.packageName,\n installed: 0,\n skipped: 1,\n reason: `Already installed via ${result.coveringPackage}`\n }\n };\n }\n\n case 'none':\n default:\n return null;\n }\n } catch (error) {\n // Subsumption check is non-fatal; log and proceed with normal install\n logger.warn(`Subsumption check failed (proceeding with install): ${error}`);\n return null;\n }\n }\n\n /**\n * Install dependencies only (after root package is already installed).\n * The root package is installed separately via unified pipeline to ensure manifest is updated.\n */\n private async installDependenciesOnly(\n rootManifestPath: string,\n rootResult: CommandResult,\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<CommandResult> {\n const policy = execContext.interactionPolicy;\n const platforms =\n context.platforms.length > 0\n ? context.platforms\n : await resolvePlatforms(context.targetDir, options.platforms, { interactive: policy?.canPrompt(PromptTier.Required) ?? false });\n\n const skipCache = options.resolutionMode === 'remote-primary';\n \n const executor = new DependencyResolutionExecutor(execContext, {\n graphOptions: {\n workspaceRoot: execContext.targetDir,\n rootManifestPath,\n includeRoot: false, // Root already installed, just deps\n includeDev: true,\n maxDepth: 10,\n skipCache\n },\n loaderOptions: {\n parallel: true,\n cacheEnabled: !skipCache,\n installOptions: { ...options, skipManifestUpdate: true }\n },\n plannerOptions: {\n platforms,\n installOptions: { ...options, skipManifestUpdate: true },\n force: options.force ?? false\n },\n dryRun: options.dryRun ?? false,\n failFast: false\n });\n\n const execResult = await executor.execute();\n \n // Combine root result with dependency results\n const rootInstalled = (rootResult.data as { installed?: number })?.installed ?? 0;\n const depInstalled = execResult.summary?.installed ?? 0;\n const depSkipped = (execResult.summary?.skipped ?? 0) + (execResult.summary?.failed ?? 0);\n\n return {\n success: rootResult.success && execResult.success,\n data: {\n packageName: context.source.packageName,\n installed: rootInstalled + depInstalled,\n skipped: depSkipped,\n results: execResult.results\n },\n error: execResult.error ?? rootResult.error,\n warnings: execResult.warnings ?? rootResult.warnings\n };\n }\n \n /**\n * Handle marketplace installation.\n * Delegates to marketplace-handler.ts\n */\n private async handleMarketplace(\n result: PreprocessResult,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext,\n policy: InteractionPolicy,\n out: OutputPort\n ): Promise<CommandResult> {\n const { context } = result;\n \n if (!context.source.pluginMetadata?.manifestPath) {\n throw new Error('Marketplace manifest not found');\n }\n \n const spinner = out.spinner();\n spinner.start('Loading marketplace');\n \n const marketplace = await parseMarketplace(\n context.source.pluginMetadata.manifestPath, \n { repoPath: context.source.contentRoot }\n );\n \n spinner.stop(`Marketplace: ${marketplace.name}`);\n \n // Marketplace already has interactive plugin selection (promptPluginSelection, promptInstallMode).\n // Per InstallOptions.interactive: \"Ignored for marketplace sources (which already have plugin selection).\"\n // Using -i here would trigger handleMarketplaceList which loads ALL plugins upfront (e.g. 56 git clones)\n // before any prompt\u2014causing a long hang. Use the normal flow: pick plugin first, then load only that one.\n\n let selectedPlugin: string;\n let installMode: 'full' | 'partial' = 'full';\n \n if (options.plugins && options.plugins.length > 0) {\n // Non-interactive: validate provided plugin names and install all as full\n const { valid, invalid } = validatePluginNames(marketplace, options.plugins);\n \n if (invalid.length > 0) {\n const errorMsg = [\n `Error: The following plugins were not found in marketplace '${marketplace.name}':`,\n ...invalid.map(name => ` - ${name}`),\n `\\nAvailable plugins: ${marketplace.plugins.map(p => p.name).join(', ')}`\n ].join('\\n');\n out.error(errorMsg);\n return {\n success: false,\n error: `Plugins not found: ${invalid.join(', ')}`\n };\n }\n \n if (valid.length === 0) {\n out.info('No valid plugins specified. Installation cancelled.');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n out.info(`Marketplace: ${marketplace.name}`);\n out.message(`Installing ${valid.length} plugin${valid.length === 1 ? '' : 's'}: ${valid.join(', ')}`);\n \n // Install each plugin in full mode (non-interactive)\n const results: CommandResult[] = [];\n for (const pluginName of valid) {\n const commitSha = (context.source as any)._commitSha || '';\n if (!commitSha) {\n throw new Error('Marketplace commit SHA not available');\n }\n \n const result = await installMarketplacePlugins(\n context.source.contentRoot!,\n marketplace,\n pluginName,\n 'full',\n context.source.gitUrl!,\n context.source.gitRef,\n commitSha,\n options,\n execContext,\n { agents: options.agents, skills: options.skills, rules: options.rules, commands: options.commands }\n );\n \n results.push(result);\n }\n \n // Return combined result\n const allSuccess = results.every(r => r.success);\n const anySuccess = results.some(r => r.success);\n \n return {\n success: anySuccess,\n error: allSuccess ? undefined : 'Some plugins failed to install'\n };\n } else if (policy.canPrompt(PromptTier.Required)) {\n // Interactive: prompt user for single plugin selection\n selectedPlugin = await promptPluginSelection(marketplace, execContext);\n \n if (!selectedPlugin) {\n out.warn('No plugin selected. Installation cancelled.');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n // Prompt for install mode\n const mode = await promptInstallMode(selectedPlugin, execContext);\n \n if (!mode) {\n out.warn('Installation cancelled.');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n installMode = mode;\n } else {\n // Non-interactive without --plugins: error with actionable message\n const pluginNames = marketplace.plugins.map(p => p.name).join(', ');\n throw new Error(\n `Marketplace '${marketplace.name}' requires plugin selection.\\n` +\n `Use --plugins to specify plugins in non-interactive mode.\\n` +\n `Available plugins: ${pluginNames}`\n );\n }\n \n // Verify it's a git source\n if (context.source.type !== 'git' || !context.source.gitUrl) {\n throw new Error('Marketplace must be from a git source');\n }\n \n const commitSha = (context.source as any)._commitSha || '';\n if (!commitSha) {\n throw new Error('Marketplace commit SHA not available');\n }\n \n return await installMarketplacePlugins(\n context.source.contentRoot!,\n marketplace,\n selectedPlugin,\n installMode,\n context.source.gitUrl,\n context.source.gitRef,\n commitSha,\n options,\n execContext,\n {\n agents: options.agents,\n skills: options.skills,\n rules: options.rules,\n commands: options.commands\n }\n );\n }\n \n /**\n * Handle --interactive for marketplace: discover resources across specified plugins\n * and present a combined interactive selection menu.\n * \n * If --plugins is specified, only those plugins are included.\n * Otherwise, all marketplace plugins are included.\n */\n private async handleMarketplaceList(\n context: InstallationContext,\n marketplace: MarketplaceManifest,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<CommandResult> {\n const out = resolveOutput(execContext);\n // Determine which plugins to list\n let pluginNames: string[];\n \n if (options.plugins && options.plugins.length > 0) {\n const { valid, invalid } = validatePluginNames(marketplace, options.plugins);\n \n if (invalid.length > 0) {\n const errorMsg = [\n `Error: The following plugins were not found in marketplace '${marketplace.name}':`,\n ...invalid.map(name => ` - ${name}`),\n `\\nAvailable plugins: ${marketplace.plugins.map(p => p.name).join(', ')}`\n ].join('\\n');\n out.error(errorMsg);\n return {\n success: false,\n error: `Plugins not found: ${invalid.join(', ')}`\n };\n }\n \n pluginNames = valid;\n } else {\n // No --plugins: list all marketplace plugins\n pluginNames = marketplace.plugins.map(p => p.name);\n }\n \n if (pluginNames.length === 0) {\n out.info('No plugins to list.');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n out.info(`Marketplace: ${marketplace.name}`);\n \n const commitSha = (context.source as any)._commitSha || '';\n if (!commitSha) {\n throw new Error('Marketplace commit SHA not available');\n }\n \n // Resolve content roots for all plugins\n const s = out.spinner();\n s.start(`Discovering resources across ${pluginNames.length} plugin${pluginNames.length === 1 ? '' : 's'}`);\n \n const resolvedPlugins = await resolvePluginContentRoots(\n context.source.contentRoot!,\n marketplace,\n pluginNames,\n context.source.gitUrl!,\n context.source.gitRef,\n commitSha,\n options,\n execContext\n );\n \n if (resolvedPlugins.length === 0) {\n s.stop('No plugins resolved');\n out.warn('Could not resolve any plugins for resource discovery');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n // Discover resources in each plugin and merge\n const allResources: DiscoveredResource[] = [];\n \n for (const plugin of resolvedPlugins) {\n const discovery = await discoverResources(plugin.basePath, plugin.repoRoot);\n \n // Prefix display names with plugin name when multiple plugins\n if (resolvedPlugins.length > 1) {\n for (const resource of discovery.all) {\n resource.displayName = `${plugin.pluginEntry.name}/${resource.displayName}`;\n }\n }\n \n allResources.push(...discovery.all);\n }\n \n // Build merged discovery result\n const byType = new Map<ResourceType, DiscoveredResource[]>();\n for (const resource of allResources) {\n const existing = byType.get(resource.resourceType) || [];\n existing.push(resource);\n byType.set(resource.resourceType, existing);\n }\n \n const mergedDiscovery: ResourceDiscoveryResult = {\n all: allResources,\n byType,\n total: allResources.length,\n basePath: resolvedPlugins[0].basePath,\n repoRoot: resolvedPlugins[0].repoRoot\n };\n \n if (mergedDiscovery.total === 0) {\n s.stop('No resources found');\n out.warn('No installable resources found across the specified plugins');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n s.stop(`Found ${mergedDiscovery.total} resource${mergedDiscovery.total === 1 ? '' : 's'}`);\n \n // Interactive selection\n const selected = await promptResourceSelection(\n mergedDiscovery,\n marketplace.name,\n undefined,\n resolveOutput(execContext),\n resolvePrompt(execContext)\n );\n\n if (selected.length === 0) {\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n displaySelectionSummary(selected);\n \n // Build resource contexts per plugin and install\n // Group selected resources by which plugin they came from (by filePath prefix)\n const allResourceContexts: InstallationContext[] = [];\n \n for (const plugin of resolvedPlugins) {\n const pluginSelected = selected.filter(s => \n s.filePath.startsWith(plugin.basePath)\n );\n \n if (pluginSelected.length === 0) continue;\n \n const resourceSpecs: ResourceInstallationSpec[] = pluginSelected.map(s => ({\n name: resolvedPlugins.length > 1 \n ? s.displayName.replace(`${plugin.pluginEntry.name}/`, '')\n : s.displayName,\n resourceType: s.resourceType as 'agent' | 'skill' | 'command' | 'rule',\n resourcePath: s.resourcePath,\n basePath: resolve(plugin.basePath),\n resourceKind: s.installKind,\n matchedBy: 'filename' as const,\n resourceVersion: s.version\n }));\n \n const resourceContexts = buildResourceInstallContexts(\n plugin.context,\n resourceSpecs,\n plugin.repoRoot\n ).map(rc => {\n if (rc.source.type === 'path') {\n rc.source.localPath = plugin.repoRoot;\n }\n return rc;\n });\n \n allResourceContexts.push(...resourceContexts);\n }\n \n if (allResourceContexts.length === 0) {\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n \n const pipelineResult = await runMultiContextPipeline(allResourceContexts);\n \n return {\n success: pipelineResult.success,\n error: pipelineResult.error,\n data: {\n installed: pipelineResult.data?.installed || 0,\n skipped: pipelineResult.data?.skipped || 0\n }\n };\n }\n \n /**\n * Handle ambiguous base resolution.\n * Prompts user or auto-selects, then continues to pipeline.\n */\n private async handleAmbiguous(\n result: PreprocessResult,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext,\n policy: InteractionPolicy\n ): Promise<CommandResult> {\n const { context, ambiguousMatches } = result;\n \n if (!ambiguousMatches || ambiguousMatches.length === 0) {\n if (context.platforms.length === 0) {\n context.platforms = await resolvePlatforms(context.targetDir, options.platforms, { interactive: policy.canPrompt(PromptTier.Required) });\n }\n return runUnifiedInstallPipeline(context);\n }\n \n const repoRoot = context.source.contentRoot || context.targetDir;\n \n // Format matches for prompts\n const matches: BaseMatch[] = ambiguousMatches.map(m => ({\n base: m.base,\n pattern: m.pattern,\n startIndex: m.startIndex,\n exampleTarget: `${m.pattern} \u2192 <platforms>/${m.pattern.replace('**/', '').replace('*', 'file')}`\n }));\n \n let selectedMatch: BaseMatch;\n \n if (options.force || !policy.canPrompt(PromptTier.Disambiguation)) {\n selectedMatch = handleAmbiguityNonInteractive(matches);\n } else {\n const resourcePath = context.source.resourcePath || context.source.gitPath || '';\n selectedMatch = await promptBaseSelection(resourcePath, matches, repoRoot);\n }\n \n // Update context with selection\n context.detectedBase = selectedMatch.base;\n context.matchedPattern = selectedMatch.pattern;\n context.baseSource = 'user-selection';\n context.baseRelative = relative(repoRoot, selectedMatch.base) || '.';\n \n logger.info('Ambiguous base resolved', {\n base: context.detectedBase,\n pattern: context.matchedPattern\n });\n\n if (context.platforms.length === 0) {\n context.platforms = await resolvePlatforms(context.targetDir, options.platforms, { interactive: policy.canPrompt(PromptTier.Required) });\n }\n return runUnifiedInstallPipeline(context);\n }\n \n /**\n * Handle interactive resource selection (--interactive option).\n * Discovers all resources, prompts for selection, and installs selected items.\n */\n private async handleList(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<CommandResult> {\n return handleListSelection(context, options, execContext);\n }\n \n /**\n * Handle multi-resource installation (bulk install or convenience filters).\n * For bulk install (opkg i), uses DependencyResolutionExecutor for recursive dependency resolution.\n */\n private async handleMultiResource(\n result: PreprocessResult,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext,\n policy: InteractionPolicy\n ): Promise<CommandResult> {\n const out = resolveOutput(execContext);\n const { context, resourceContexts, workspaceContext } = result;\n const dependencyContexts = resourceContexts ?? [];\n\n const needsPlatforms =\n dependencyContexts.some((ctx) => ctx.platforms.length === 0) ||\n (workspaceContext?.platforms.length === 0);\n\n if (needsPlatforms) {\n const resolvedPlatforms = await resolvePlatforms(context.targetDir, options.platforms, { interactive: policy.canPrompt(PromptTier.Required) });\n for (const ctx of dependencyContexts) {\n if (ctx.platforms.length === 0) ctx.platforms = resolvedPlatforms;\n }\n if (workspaceContext && workspaceContext.platforms.length === 0) {\n workspaceContext.platforms = resolvedPlatforms;\n }\n }\n\n if (dependencyContexts.length === 0 && !workspaceContext) {\n if (context.source.packageName === '__bulk__') {\n out.warn('No packages found in openpackage.yml');\n out.info('\\nTips:');\n out.info(' - Add packages to the \"dependencies\" array in openpackage.yml');\n out.info(' - Add development packages to the \"dev-dependencies\" array');\n out.info(' - Use \"opkg install <package-name>\" to install a specific package');\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n return {\n success: false,\n error: 'No resources matched the specified filters'\n };\n }\n\n if (context.source.packageName === '__bulk__') {\n return this.runRecursiveBulkInstall(options, execContext, workspaceContext ?? undefined);\n }\n\n // For non-bulk multi-resource installs (convenience filters), check subsumption\n // per resource context and filter out already-covered ones\n if (!options.force && dependencyContexts.length > 0) {\n const filteredContexts: InstallationContext[] = [];\n let skippedCount = 0;\n\n for (const ctx of dependencyContexts) {\n const subsumptionResult = await checkSubsumption(ctx.source, ctx.targetDir);\n if (subsumptionResult.type === 'already-covered') {\n const resourcePath = ctx.source.resourcePath ||\n ctx.source.packageName.replace(/^.*?\\/[^/]+\\/[^/]+\\//, '');\n out.info(`Skipped: ${resourcePath} is already installed via ${subsumptionResult.coveringPackage}`);\n skippedCount++;\n } else {\n filteredContexts.push(ctx);\n }\n }\n\n if (filteredContexts.length === 0) {\n return {\n success: true,\n data: {\n packageName: context.source.packageName,\n installed: 0,\n skipped: skippedCount,\n reason: 'All resources already installed via full package'\n }\n };\n }\n\n // Replace with filtered list\n if (skippedCount > 0) {\n dependencyContexts.length = 0;\n dependencyContexts.push(...filteredContexts);\n }\n }\n\n if (dependencyContexts.length > 0) {\n out.success(`Installing ${dependencyContexts.length} package${dependencyContexts.length === 1 ? '' : 's'} from openpackage.yml`);\n }\n\n if (workspaceContext) {\n try {\n await runUnifiedInstallPipeline(workspaceContext);\n } catch (error) {\n logger.warn('Workspace root install failed', { error });\n }\n }\n\n if (dependencyContexts.length === 0) {\n return { success: true, data: { installed: 0, skipped: 0 } };\n }\n\n return this.runBulkInstall(dependencyContexts);\n }\n\n /**\n * Run bulk install using recursive dependency resolution (graph + pipeline per package).\n */\n private async runRecursiveBulkInstall(\n options: NormalizedInstallOptions,\n execContext: ExecutionContext,\n workspaceContext?: InstallationContext | null\n ): Promise<CommandResult> {\n const out = resolveOutput(execContext);\n if (workspaceContext) {\n try {\n await runUnifiedInstallPipeline(workspaceContext);\n } catch (error) {\n logger.warn('Workspace root install failed', { error });\n }\n }\n\n // Reuse platforms from workspace context when available (avoid duplicate prompt)\n const policy = execContext.interactionPolicy;\n let platforms = workspaceContext?.platforms?.length\n ? workspaceContext.platforms\n : await resolvePlatforms(execContext.targetDir, options.platforms, { interactive: policy?.canPrompt(PromptTier.Required) ?? false });\n\n const skipCache = options.resolutionMode === 'remote-primary';\n \n const executor = new DependencyResolutionExecutor(execContext, {\n graphOptions: {\n workspaceRoot: execContext.targetDir,\n includeDev: true,\n maxDepth: 10,\n skipCache\n },\n loaderOptions: {\n parallel: true,\n cacheEnabled: !skipCache,\n // Recursive dependency installs should not modify workspace openpackage.yml\n installOptions: { ...options, skipManifestUpdate: true }\n },\n plannerOptions: {\n platforms,\n // Recursive dependency installs should not modify workspace openpackage.yml\n installOptions: { ...options, skipManifestUpdate: true },\n force: options.force ?? false\n },\n dryRun: options.dryRun ?? false,\n failFast: false\n });\n\n const execResult = await executor.execute();\n\n const summary = execResult.summary;\n if (summary) {\n out.success(`Installation complete: ${summary.installed} installed${summary.failed > 0 ? `, ${summary.failed} failed` : ''}${summary.skipped > 0 ? `, ${summary.skipped} skipped` : ''}`);\n }\n\n return {\n success: execResult.success,\n data: summary\n ? { installed: summary.installed, skipped: summary.failed + summary.skipped, results: execResult.results }\n : { installed: 0, skipped: 0 },\n error: execResult.error,\n warnings: execResult.warnings\n };\n }\n \n /**\n * Run bulk installation for multiple packages.\n */\n private async runBulkInstall(contexts: InstallationContext[]): Promise<CommandResult> {\n const out = resolveOutput(contexts[0]?.execution);\n let totalInstalled = 0;\n let totalSkipped = 0;\n const results: Array<{ name: string; success: boolean; error?: string }> = [];\n \n for (const ctx of contexts) {\n try {\n const result = await runUnifiedInstallPipeline(ctx);\n \n if (result.success) {\n totalInstalled++;\n results.push({ name: ctx.source.packageName, success: true });\n } else {\n totalSkipped++;\n results.push({ name: ctx.source.packageName, success: false, error: result.error });\n out.error(`${ctx.source.packageName}: ${result.error}`);\n }\n } catch (error) {\n totalSkipped++;\n results.push({ name: ctx.source.packageName, success: false, error: String(error) });\n out.error(`${ctx.source.packageName}: ${error}`);\n }\n }\n \n // Display summary\n out.success(`Installation complete: ${totalInstalled} installed${totalSkipped > 0 ? `, ${totalSkipped} failed` : ''}`);\n \n const allSuccessful = totalSkipped === 0;\n return {\n success: allSuccessful,\n data: { installed: totalInstalled, skipped: totalSkipped, results },\n error: allSuccessful ? undefined : `${totalSkipped} packages failed to install`\n };\n }\n}\n\n/**\n * Create a configured orchestrator with all strategies registered.\n */\nexport function createOrchestrator(): InstallOrchestrator {\n const orchestrator = new InstallOrchestrator();\n \n // Register all strategies\n for (const strategy of createAllStrategies()) {\n orchestrator.registerStrategy(strategy);\n }\n \n return orchestrator;\n}\n", "/**\n * Ambiguity prompts for resource installation.\n * \n * Handles user prompts when multiple patterns match at the same depth,\n * allowing users to select their preferred base directory.\n */\n\nimport { relative } from 'path';\nimport { logger } from '../../utils/logger.js';\nimport type { PromptPort } from '../ports/prompt.js';\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput, resolvePrompt } from '../ports/resolve.js';\n\n/**\n * Base match option for user selection\n */\nexport interface BaseMatch {\n /** Base directory path (absolute) */\n base: string;\n \n /** Pattern that matched */\n pattern: string;\n \n /** Start index of the match */\n startIndex: number;\n \n /** Example target path for display */\n exampleTarget?: string;\n}\n\n/**\n * Prompt user to select a base when multiple patterns match.\n * \n * @param resourcePath - The resource path that has ambiguous matches\n * @param matches - Array of possible base matches\n * @param repoRoot - Repository root for calculating relative paths\n * @returns Selected base match\n */\nexport async function promptBaseSelection(\n resourcePath: string,\n matches: BaseMatch[],\n repoRoot: string,\n output?: OutputPort,\n prompt?: PromptPort\n): Promise<BaseMatch> {\n const out = output ?? resolveOutput();\n const p = prompt ?? resolvePrompt();\n\n out.info(`\\n\u2753 Multiple installation bases detected for '${resourcePath}':\\n`);\n\n // Create choices for the prompt\n const choices = matches.map((match, i) => {\n const baseDisplay = match.base === repoRoot \n ? '/ (repo root)' \n : '/' + relative(repoRoot, match.base);\n \n return {\n title: `${i + 1}. Base: ${baseDisplay}`,\n description: ` Pattern: ${match.pattern}\\n ${match.exampleTarget ? 'Would install: ' + match.exampleTarget : ''}`,\n value: match\n };\n });\n\n // Add auto option (deepest match)\n choices.push({\n title: 'a. Auto (deepest match)',\n description: ' Select the most specific base automatically',\n value: null as any // Signal for auto-select\n });\n\n try {\n const selection = await p.select<BaseMatch | null>(\n 'Select base:',\n choices\n );\n\n if (selection === null) {\n // Auto-select deepest match\n const deepest = selectDeepestMatch(matches);\n logger.info('User selected auto (deepest match)', { base: deepest.base, pattern: deepest.pattern });\n return deepest;\n }\n\n logger.info('User selected base', { \n base: selection.base, \n pattern: selection.pattern \n });\n return selection;\n } catch (error) {\n // On cancellation or error, fall back to deepest match\n logger.warn('Base selection cancelled or failed, using deepest match', { error });\n return selectDeepestMatch(matches);\n }\n}\n\n/**\n * Select the deepest match from an array of base matches.\n * The deepest match is the one with the highest startIndex.\n * \n * @param matches - Array of base matches\n * @returns The deepest match\n */\nfunction selectDeepestMatch(matches: BaseMatch[]): BaseMatch {\n if (matches.length === 0) {\n throw new Error('Cannot select deepest match from empty array');\n }\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n // Find maximum start index\n const maxStartIndex = Math.max(...matches.map(m => m.startIndex));\n \n // Get first match at that depth (in case of ties)\n return matches.find(m => m.startIndex === maxStartIndex)!;\n}\n\n/**\n * Check if the current environment supports interactive prompts.\n *\n * @returns True if interactive prompts are supported\n * @deprecated Use ExecutionContext.interactive instead when possible.\n */\nexport function canPrompt(): boolean {\n // Check if stdin is a TTY (terminal)\n return process.stdin.isTTY === true;\n}\n\n/**\n * Handle ambiguity in non-interactive mode (--force or CI/CD).\n * Returns the deepest match without prompting.\n * \n * @param matches - Array of ambiguous matches\n * @returns Selected base (deepest match)\n */\nexport function handleAmbiguityNonInteractive(matches: BaseMatch[], output?: OutputPort): BaseMatch {\n const selected = selectDeepestMatch(matches);\n const out = output ?? resolveOutput();\n \n logger.info('Non-interactive mode: using deepest match', {\n base: selected.base,\n pattern: selected.pattern,\n startIndex: selected.startIndex\n });\n\n // Log for debugging in CI/CD\n out.info(`\u2139\uFE0F Multiple bases detected. Using deepest match: ${selected.base}`);\n out.info(` Pattern: ${selected.pattern}`);\n \n return selected;\n}\n", "import { join, basename, relative, resolve } from 'path';\nimport { readTextFile, exists } from '../../utils/fs.js';\nimport { logger } from '../../utils/logger.js';\nimport { ValidationError, UserCancellationError } from '../../utils/errors.js';\nimport { buildGitInstallContext, buildPathInstallContext, buildResourceInstallContexts } from './unified/context-builders.js';\nimport type { InstallationContext } from './unified/context.js';\nimport { runUnifiedInstallPipeline } from './unified/pipeline.js';\nimport { detectPluginType, detectPluginWithMarketplace, validatePluginManifest } from './plugin-detector.js';\nimport type { CommandResult, InstallOptions, ExecutionContext } from '../../types/index.js';\nimport type { OutputPort } from '../ports/output.js';\nimport type { PromptPort } from '../ports/prompt.js';\nimport { resolveOutput, resolvePrompt } from '../ports/resolve.js';\nimport { runMultiContextPipeline } from './unified/multi-context-pipeline.js';\nimport { getLoaderForSource } from './sources/loader-factory.js';\nimport { applyBaseDetection } from './preprocessing/base-resolver.js';\nimport { resolveConvenienceResources } from './preprocessing/convenience-preprocessor.js';\nimport { discoverResources } from './resource-discoverer.js';\nimport { promptResourceSelection, displaySelectionSummary } from './resource-selection-menu.js';\nimport type { ResourceInstallationSpec } from './convenience-matchers.js';\nimport type { SelectedResource } from './resource-types.js';\nimport {\n normalizePluginSource,\n isRelativePathSource,\n isGitSource,\n type PluginSourceSpec,\n type NormalizedPluginSource\n} from './plugin-sources.js';\n\n/**\n * Claude Code marketplace manifest schema.\n * See: https://code.claude.com/docs/en/plugin-marketplaces\n */\nexport interface MarketplaceManifest {\n name: string;\n description?: string;\n homepage?: string;\n plugins: MarketplacePluginEntry[];\n}\n\n/**\n * Marketplace plugin entry.\n * Each entry defines a plugin and where to find it.\n * When strict is false, all plugin metadata can be defined here instead of in plugin.json.\n */\nexport interface MarketplacePluginEntry {\n // Required fields\n name: string;\n source: PluginSourceSpec;\n \n // Standard metadata fields\n description?: string;\n version?: string;\n author?: {\n name?: string;\n email?: string;\n url?: string;\n };\n homepage?: string;\n repository?: string | {\n type?: string;\n url?: string;\n };\n license?: string;\n keywords?: string[];\n category?: string;\n tags?: string[];\n \n // Component configuration fields\n commands?: string | string[];\n agents?: string | string[];\n hooks?: string | object;\n mcpServers?: string | object;\n lspServers?: string | object;\n \n // Strictness control\n strict?: boolean;\n}\n\n/**\n * Parse and validate a marketplace manifest.\n * \n * @param manifestPath - Path to marketplace.json file\n * @param context - Context for fallback naming\n * @returns Parsed marketplace manifest\n */\nexport async function parseMarketplace(\n manifestPath: string,\n context?: { gitUrl?: string; repoPath?: string }\n): Promise<MarketplaceManifest> {\n logger.debug('Parsing marketplace manifest', { manifestPath, context });\n \n try {\n const content = await readTextFile(manifestPath);\n const manifest = JSON.parse(content) as MarketplaceManifest;\n \n // If name is missing, use fallback from repo name\n if (!manifest.name && context?.repoPath) {\n manifest.name = basename(context.repoPath);\n logger.debug('Marketplace name missing, using repo name as fallback', { name: manifest.name });\n }\n \n // Validate required fields\n if (!manifest.name) {\n throw new ValidationError('Marketplace manifest missing required field: name');\n }\n \n if (!manifest.plugins || !Array.isArray(manifest.plugins)) {\n throw new ValidationError('Marketplace manifest missing or invalid plugins array');\n }\n \n if (manifest.plugins.length === 0) {\n throw new ValidationError('Marketplace contains no plugins');\n }\n \n // Validate each plugin entry\n for (const plugin of manifest.plugins) {\n if (!plugin.name) {\n throw new ValidationError('Marketplace plugin entry missing required field: name');\n }\n if (!plugin.source) {\n throw new ValidationError(`Plugin '${plugin.name}' missing required field: source`);\n }\n \n // Validate source can be normalized (will throw if invalid)\n try {\n normalizePluginSource(plugin.source, plugin.name);\n } catch (error) {\n throw new ValidationError(\n `Plugin '${plugin.name}' has invalid source: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n \n logger.info('Parsed marketplace manifest', {\n name: manifest.name,\n pluginCount: manifest.plugins.length\n });\n \n return manifest;\n \n } catch (error) {\n if (error instanceof ValidationError) {\n throw error;\n }\n throw new ValidationError(`Failed to parse marketplace manifest at ${manifestPath}: ${error}`);\n }\n}\n\n/**\n * Display interactive plugin selection prompt using single selection.\n * \n * @param marketplace - Parsed marketplace manifest\n * @returns Selected plugin name (empty string if user cancelled)\n */\nexport async function promptPluginSelection(\n marketplace: MarketplaceManifest,\n execContext?: ExecutionContext\n): Promise<string> {\n const out = resolveOutput(execContext);\n const prompt = resolvePrompt(execContext);\n // Display marketplace description (header is shown by the spinner stop in orchestrator)\n if (marketplace.description) {\n out.message(marketplace.description);\n }\n\n const choices = marketplace.plugins\n .sort((a, b) => a.name.localeCompare(b.name))\n .map(plugin => ({\n title: plugin.name,\n value: plugin.name,\n description: plugin.description || ''\n }));\n \n try {\n const selectedPlugin = await prompt.select(\n 'Select a plugin to install:',\n choices\n );\n \n logger.info('User selected plugin', { selected: selectedPlugin });\n return selectedPlugin as string;\n } catch (error) {\n if (error instanceof UserCancellationError) {\n logger.info('User cancelled plugin selection');\n return '';\n }\n throw error;\n }\n}\n\n/**\n * Install mode type\n */\nexport type InstallMode = 'full' | 'partial';\n\n/**\n * Prompt user to choose between full plugin install or partial (individual resources).\n * \n * @param pluginName - Name of the plugin being installed\n * @returns Install mode ('full' or 'partial'), or empty string if cancelled\n */\nexport async function promptInstallMode(pluginName: string, execContext?: ExecutionContext): Promise<InstallMode | ''> {\n const prompt = resolvePrompt(execContext);\n try {\n const mode = await prompt.select(\n `How would you like to install ${pluginName}?`,\n [\n { \n title: 'Install full plugin', \n value: 'full' as const,\n description: 'Install all resources from this plugin' \n },\n { \n title: 'Select individual resources', \n value: 'partial' as const,\n description: 'Choose specific agents, skills, commands, etc.' \n }\n ]\n );\n \n logger.info('User selected install mode', { mode });\n return mode as InstallMode;\n } catch (error) {\n if (error instanceof UserCancellationError) {\n logger.info('User cancelled install mode selection');\n return '';\n }\n throw error;\n }\n}\n\n/**\n * Install individual resources from a plugin (partial install mode).\n * Discovers resources and prompts user to select which ones to install.\n * \n * @param pluginDir - Absolute path to plugin directory\n * @param pluginEntry - Marketplace plugin entry\n * @param context - Installation context with source metadata\n * @param repoRoot - Repository root path\n * @returns Command result\n */\nasync function installPluginPartial(\n pluginDir: string,\n pluginEntry: MarketplacePluginEntry,\n context: any,\n repoRoot: string\n): Promise<CommandResult> {\n const out = resolveOutput(context.execution);\n logger.info('Starting partial plugin installation', {\n plugin: pluginEntry.name,\n path: pluginDir\n });\n \n // Discover all resources with spinner\n const s = out.spinner();\n s.start('Discovering resources');\n \n const discovery = await discoverResources(pluginDir, repoRoot);\n \n // Stop spinner with completion message\n if (discovery.total === 0) {\n s.stop('No resources found');\n } else {\n s.stop(`${discovery.total} resource${discovery.total === 1 ? '' : 's'} discovered`);\n }\n \n // Check if any resources found\n if (discovery.total === 0) {\n out.warn('No installable resources found in this plugin');\n return {\n success: true,\n data: { installed: 0, skipped: 0 }\n };\n }\n \n // Prompt for resource selection\n const selected: SelectedResource[] = await promptResourceSelection(\n discovery,\n context.source.packageName || pluginEntry.name,\n context.source.version,\n resolveOutput(context.execution),\n resolvePrompt(context.execution)\n );\n \n if (selected.length === 0) {\n return {\n success: true,\n data: { installed: 0, skipped: 0 }\n };\n }\n \n // Display selection summary\n displaySelectionSummary(selected);\n \n // Convert selected resources to ResourceInstallationSpec format\n const resourceSpecs: ResourceInstallationSpec[] = selected.map(s => ({\n name: s.displayName,\n resourceType: s.resourceType as 'agent' | 'skill' | 'command' | 'rule',\n resourcePath: s.resourcePath,\n basePath: resolve(pluginDir),\n resourceKind: s.installKind,\n matchedBy: 'filename' as const,\n resourceVersion: s.version\n }));\n \n // Build resource contexts for installation\n const resourceContexts = buildResourceInstallContexts(\n context,\n resourceSpecs,\n repoRoot\n ).map(rc => {\n // Ensure path-based loader can resolve repo-relative resourcePath\n if (rc.source.type === 'path') {\n rc.source.localPath = repoRoot;\n }\n return rc;\n });\n \n // Run multi-context pipeline\n const result = await runMultiContextPipeline(resourceContexts);\n \n return {\n success: result.success,\n error: result.error,\n data: {\n installed: result.data?.installed || 0,\n skipped: result.data?.skipped || 0\n }\n };\n}\n\n/**\n * Install selected plugins from a marketplace.\n * \n * @param marketplaceDir - Absolute path to cloned marketplace repository root\n * @param marketplace - Parsed marketplace manifest\n * @param selectedName - Name of plugin to install\n * @param installMode - Install mode ('full' or 'partial')\n * @param marketplaceGitUrl - Git URL of the marketplace repository\n * @param marketplaceGitRef - Git ref (branch/tag/sha) if specified\n * @param marketplaceCommitSha - Commit SHA of cached marketplace\n * @param options - Install options\n * @param cwd - Current working directory for installation\n */\nexport async function installMarketplacePlugins(\n marketplaceDir: string,\n marketplace: MarketplaceManifest,\n selectedName: string,\n installMode: InstallMode,\n marketplaceGitUrl: string,\n marketplaceGitRef: string | undefined,\n marketplaceCommitSha: string,\n options: InstallOptions,\n execContext: ExecutionContext,\n convenienceOptions?: { agents?: string[]; skills?: string[]; rules?: string[]; commands?: string[] }\n): Promise<CommandResult> {\n logger.info('Installing marketplace plugin', { \n marketplace: marketplace.name,\n plugin: selectedName,\n mode: installMode\n });\n \n const out = resolveOutput(execContext);\n \n const pluginEntry = marketplace.plugins.find(p => p.name === selectedName);\n if (!pluginEntry) {\n const error = `Plugin '${selectedName}' not found in marketplace`;\n logger.error(error, { marketplace: marketplace.name });\n out.error(`${selectedName}: ${error}`);\n return { success: false, error };\n }\n \n // Normalize the plugin source\n let normalizedSource: NormalizedPluginSource;\n try {\n normalizedSource = normalizePluginSource(pluginEntry.source, selectedName);\n } catch (error) {\n logger.error('Failed to normalize plugin source', { plugin: selectedName, error });\n const errorMsg = error instanceof Error ? error.message : 'Invalid source configuration';\n out.error(`${selectedName}: ${errorMsg}`);\n return { success: false, error: errorMsg };\n }\n \n // Install based on source type\n try {\n let installResult: CommandResult;\n \n if (isRelativePathSource(normalizedSource)) {\n installResult = await installRelativePathPlugin(\n marketplaceDir,\n marketplace,\n pluginEntry,\n normalizedSource,\n installMode,\n marketplaceGitUrl,\n marketplaceGitRef,\n marketplaceCommitSha,\n options,\n execContext,\n convenienceOptions\n );\n } else if (isGitSource(normalizedSource)) {\n installResult = await installGitPlugin(\n marketplace,\n pluginEntry,\n normalizedSource,\n installMode,\n options,\n execContext,\n convenienceOptions\n );\n } else {\n throw new Error(`Unsupported source type: ${normalizedSource.type}`);\n }\n \n return installResult;\n \n } catch (error) {\n logger.error('Failed to install plugin', { plugin: selectedName, error });\n const errorMsg = error instanceof Error ? error.message : String(error);\n out.error(`${selectedName}: ${errorMsg}`);\n return { success: false, error: errorMsg };\n }\n}\n\n/**\n * Install a plugin from a relative path within the marketplace repository.\n */\nasync function installRelativePathPlugin(\n marketplaceDir: string,\n marketplace: MarketplaceManifest,\n pluginEntry: MarketplacePluginEntry,\n normalizedSource: NormalizedPluginSource,\n installMode: InstallMode,\n marketplaceGitUrl: string,\n marketplaceGitRef: string | undefined,\n marketplaceCommitSha: string,\n options: InstallOptions,\n execContext: ExecutionContext,\n convenienceOptions?: { agents?: string[]; skills?: string[]; rules?: string[]; commands?: string[] }\n): Promise<CommandResult> {\n const out = resolveOutput(execContext);\n const pluginSubdir = normalizedSource.relativePath!;\n const pluginDir = join(marketplaceDir, pluginSubdir);\n \n // Validate plugin subdirectory exists (silent for partial mode)\n if (!(await exists(pluginDir))) {\n const error = `Path '${pluginSubdir}' does not exist in marketplace repository`;\n logger.error('Plugin path not found', { \n plugin: pluginEntry.name, \n path: pluginSubdir,\n fullPath: pluginDir\n });\n out.error(`${pluginEntry.name}: ${error}`);\n return { success: false, error };\n }\n \n const hasConvenienceOptions = Boolean(convenienceOptions?.agents?.length || convenienceOptions?.skills?.length || convenienceOptions?.rules?.length || convenienceOptions?.commands?.length);\n\n if (hasConvenienceOptions) {\n logger.info('Convenience filters active, bypassing full plugin validation', {\n plugin: pluginEntry.name,\n path: pluginSubdir\n });\n\n const ctx = await buildPathInstallContext(\n execContext,\n pluginDir,\n {\n ...options,\n sourceType: 'directory' as const\n }\n );\n\n ctx.source.gitSourceOverride = {\n gitUrl: marketplaceGitUrl,\n gitRef: marketplaceGitRef,\n gitPath: pluginSubdir\n };\n\n ctx.source.pluginMetadata = {\n isPlugin: true,\n marketplaceEntry: pluginEntry,\n marketplaceSource: {\n url: marketplaceGitUrl,\n commitSha: marketplaceCommitSha,\n pluginName: pluginEntry.name\n }\n };\n\n ctx.detectedBase = pluginDir;\n ctx.baseRelative = relative(marketplaceDir, pluginDir) || '.';\n\n const resources = await resolveConvenienceResources(pluginDir, marketplaceDir, convenienceOptions ?? {});\n\n const resourceContexts = buildResourceInstallContexts(ctx, resources, marketplaceDir).map(rc => {\n if (rc.source.type === 'path') {\n rc.source.localPath = marketplaceDir;\n }\n return rc;\n });\n const multiResult = await runMultiContextPipeline(resourceContexts);\n return {\n success: multiResult.success,\n error: multiResult.error\n };\n }\n\n // Build path context for the already-cloned plugin directory\n const ctx = await buildPathInstallContext(\n execContext,\n pluginDir,\n {\n ...options,\n sourceType: 'directory' as const\n }\n );\n \n // Add git source override for manifest recording\n ctx.source.gitSourceOverride = {\n gitUrl: marketplaceGitUrl,\n gitRef: marketplaceGitRef,\n gitPath: pluginSubdir\n };\n \n // Add marketplace metadata to context\n ctx.source.pluginMetadata = {\n isPlugin: true,\n marketplaceEntry: pluginEntry,\n marketplaceSource: {\n url: marketplaceGitUrl,\n commitSha: marketplaceCommitSha,\n pluginName: pluginEntry.name\n }\n };\n\n // Branch based on install mode\n if (installMode === 'partial') {\n // Partial install: prompt for resource selection\n logger.info('Using partial install mode for relative path plugin', {\n plugin: pluginEntry.name,\n path: pluginSubdir\n });\n \n ctx.detectedBase = pluginDir;\n ctx.baseRelative = relative(marketplaceDir, pluginDir) || '.';\n \n const repoRoot = marketplaceDir;\n return await installPluginPartial(pluginDir, pluginEntry, ctx, repoRoot);\n }\n\n // Full install: validate and install entire plugin\n logger.info('Using full install mode for relative path plugin', {\n plugin: pluginEntry.name,\n path: pluginSubdir\n });\n\n // Validate plugin structure with marketplace context\n const detection = await detectPluginWithMarketplace(pluginDir, pluginEntry);\n \n if (!detection.isPlugin) {\n const strictInfo = pluginEntry.strict === false \n ? ' Set \"strict\": false in marketplace entry if this plugin is defined entirely in marketplace.json.'\n : '';\n const error = `Path '${pluginSubdir}' does not contain a valid plugin.${strictInfo}`;\n logger.error('Invalid plugin structure', { \n plugin: pluginEntry.name, \n path: pluginSubdir,\n strict: pluginEntry.strict\n });\n out.error(`${pluginEntry.name}: ${error}`);\n return { success: false, error };\n }\n \n // For plugins with plugin.json, validate it's parseable\n if (detection.manifestPath) {\n if (!(await validatePluginManifest(detection.manifestPath))) {\n const error = `Invalid plugin manifest in '${pluginSubdir}' (cannot parse JSON)`;\n logger.error('Invalid plugin manifest', { plugin: pluginEntry.name });\n out.error(`${pluginEntry.name}: ${error}`);\n return { success: false, error };\n }\n }\n \n // Update context with detection results\n ctx.source.pluginMetadata = {\n ...ctx.source.pluginMetadata,\n pluginType: detection.type as any,\n manifestPath: detection.manifestPath\n };\n \n // Run the unified pipeline \u2014 it handles its own spinner and reports results\n const pipelineResult = await runUnifiedInstallPipeline(ctx);\n \n if (!pipelineResult.success) {\n const installedName = ctx.source.packageName || pluginEntry.name;\n out.error(`${installedName}: ${pipelineResult.error || 'Unknown error'}`);\n }\n \n return {\n success: pipelineResult.success,\n error: pipelineResult.error\n };\n}\n\n/**\n * Install a plugin from an external git repository.\n */\nasync function installGitPlugin(\n marketplace: MarketplaceManifest,\n pluginEntry: MarketplacePluginEntry,\n normalizedSource: NormalizedPluginSource,\n installMode: InstallMode,\n options: InstallOptions,\n execContext: ExecutionContext,\n convenienceOptions?: { agents?: string[]; skills?: string[]; rules?: string[]; commands?: string[] }\n): Promise<CommandResult> {\n const out = resolveOutput(execContext);\n const gitUrl = normalizedSource.gitUrl!;\n const gitRef = normalizedSource.gitRef;\n const gitPath = normalizedSource.gitPath;\n \n logger.info('Installing git plugin', {\n plugin: pluginEntry.name,\n gitUrl,\n gitRef,\n gitPath\n });\n \n // Build git context\n const ctx = await buildGitInstallContext(\n execContext,\n gitUrl,\n {\n ...options,\n gitRef,\n gitPath\n }\n );\n \n // Add marketplace metadata for proper scoping\n ctx.source.pluginMetadata = {\n isPlugin: true,\n marketplaceEntry: pluginEntry\n };\n\n const hasConvenienceOptions = Boolean(convenienceOptions?.agents?.length || convenienceOptions?.skills?.length || convenienceOptions?.rules?.length || convenienceOptions?.commands?.length);\n if (hasConvenienceOptions) {\n const loader = getLoaderForSource(ctx.source);\n const loaded = await loader.load(ctx.source, options, execContext);\n\n ctx.source.packageName = loaded.packageName;\n ctx.source.version = loaded.version;\n ctx.source.contentRoot = loaded.contentRoot;\n ctx.source.pluginMetadata = {\n ...loaded.pluginMetadata,\n ...(ctx.source.pluginMetadata ?? {}),\n marketplaceEntry: pluginEntry\n };\n\n if (loaded.sourceMetadata?.commitSha) {\n (ctx.source as any)._commitSha = loaded.sourceMetadata.commitSha;\n }\n\n if (loaded.sourceMetadata?.baseDetection) {\n applyBaseDetection(ctx, loaded);\n }\n\n const basePath = ctx.detectedBase || loaded.contentRoot || execContext.targetDir;\n const repoRoot = loaded.sourceMetadata?.repoPath || loaded.contentRoot || basePath;\n const resources = await resolveConvenienceResources(basePath, repoRoot, convenienceOptions ?? {});\n\n const resourceContexts = buildResourceInstallContexts(ctx, resources, repoRoot);\n const multiResult = await runMultiContextPipeline(resourceContexts);\n return {\n success: multiResult.success,\n error: multiResult.error\n };\n }\n\n // Branch based on install mode\n if (installMode === 'partial') {\n // Partial install: load plugin, discover resources, prompt for selection\n logger.info('Using partial install mode for git plugin', {\n plugin: pluginEntry.name\n });\n\n const loader = getLoaderForSource(ctx.source);\n const loaded = await loader.load(ctx.source, options, execContext);\n\n ctx.source.packageName = loaded.packageName;\n ctx.source.version = loaded.version;\n ctx.source.contentRoot = loaded.contentRoot;\n ctx.source.pluginMetadata = {\n ...loaded.pluginMetadata,\n ...(ctx.source.pluginMetadata ?? {}),\n marketplaceEntry: pluginEntry\n };\n\n if (loaded.sourceMetadata?.commitSha) {\n (ctx.source as any)._commitSha = loaded.sourceMetadata.commitSha;\n }\n\n if (loaded.sourceMetadata?.baseDetection) {\n applyBaseDetection(ctx, loaded);\n }\n\n const basePath = ctx.detectedBase || loaded.contentRoot || execContext.targetDir;\n const repoRoot = loaded.sourceMetadata?.repoPath || loaded.contentRoot || basePath;\n \n return await installPluginPartial(basePath, pluginEntry, ctx, repoRoot);\n }\n \n // Full install: run unified pipeline \u2014 it handles its own spinner and reports results\n logger.info('Using full install mode for git plugin', {\n plugin: pluginEntry.name\n });\n\n const pipelineResult = await runUnifiedInstallPipeline(ctx);\n \n if (!pipelineResult.success) {\n const installedName = ctx.source.packageName || pluginEntry.name;\n out.error(`${installedName}: ${pipelineResult.error || 'Unknown error'}`);\n }\n \n return {\n success: pipelineResult.success,\n error: pipelineResult.error\n };\n}\n\n/**\n * Validate that requested plugin names exist in marketplace.\n *\n * @param marketplace - Parsed marketplace manifest\n * @param requestedPlugins - Array of plugin names to validate\n * @returns Object with valid and invalid plugin name arrays\n */\nexport function validatePluginNames(\n marketplace: MarketplaceManifest,\n requestedPlugins: string[]\n): { valid: string[]; invalid: string[] } {\n const availableNames = new Set(marketplace.plugins.map(p => p.name));\n\n const valid: string[] = [];\n const invalid: string[] = [];\n\n for (const name of requestedPlugins) {\n if (availableNames.has(name)) {\n valid.push(name);\n } else {\n invalid.push(name);\n }\n }\n\n return { valid, invalid };\n}\n\n/**\n * Resolved plugin info for resource discovery (used by --interactive).\n */\nexport interface ResolvedPluginInfo {\n pluginEntry: MarketplacePluginEntry;\n context: InstallationContext;\n basePath: string;\n repoRoot: string;\n}\n\n/**\n * Resolve plugin content roots for resource discovery.\n * Loads each plugin's source and returns resolved paths and contexts\n * without installing anything.\n *\n * @param marketplaceDir - Absolute path to cloned marketplace repository root\n * @param marketplace - Parsed marketplace manifest\n * @param pluginNames - Plugin names to resolve\n * @param marketplaceGitUrl - Git URL of the marketplace repository\n * @param marketplaceGitRef - Git ref (branch/tag/sha) if specified\n * @param marketplaceCommitSha - Commit SHA of cached marketplace\n * @param options - Install options\n * @param execContext - Execution context\n * @returns Array of resolved plugin info objects\n */\nexport async function resolvePluginContentRoots(\n marketplaceDir: string,\n marketplace: MarketplaceManifest,\n pluginNames: string[],\n marketplaceGitUrl: string,\n marketplaceGitRef: string | undefined,\n marketplaceCommitSha: string,\n options: InstallOptions,\n execContext: ExecutionContext\n): Promise<ResolvedPluginInfo[]> {\n const results: ResolvedPluginInfo[] = [];\n\n for (const name of pluginNames) {\n const pluginEntry = marketplace.plugins.find(p => p.name === name);\n if (!pluginEntry) continue;\n\n let normalizedSource: NormalizedPluginSource;\n try {\n normalizedSource = normalizePluginSource(pluginEntry.source, name);\n } catch (error) {\n logger.warn('Failed to normalize plugin source for list', { plugin: name, error });\n continue;\n }\n\n try {\n if (isRelativePathSource(normalizedSource)) {\n const pluginSubdir = normalizedSource.relativePath!;\n const pluginDir = join(marketplaceDir, pluginSubdir);\n\n if (!(await exists(pluginDir))) {\n logger.warn('Plugin path not found for list', { plugin: name, path: pluginSubdir });\n continue;\n }\n\n const ctx = await buildPathInstallContext(execContext, pluginDir, {\n ...options,\n sourceType: 'directory' as const\n });\n\n ctx.source.gitSourceOverride = {\n gitUrl: marketplaceGitUrl,\n gitRef: marketplaceGitRef,\n gitPath: pluginSubdir\n };\n\n ctx.source.pluginMetadata = {\n isPlugin: true,\n marketplaceEntry: pluginEntry,\n marketplaceSource: {\n url: marketplaceGitUrl,\n commitSha: marketplaceCommitSha,\n pluginName: pluginEntry.name\n }\n };\n\n ctx.detectedBase = pluginDir;\n ctx.baseRelative = relative(marketplaceDir, pluginDir) || '.';\n\n results.push({\n pluginEntry,\n context: ctx,\n basePath: pluginDir,\n repoRoot: marketplaceDir\n });\n } else if (isGitSource(normalizedSource)) {\n const ctx = await buildGitInstallContext(execContext, normalizedSource.gitUrl!, {\n ...options,\n gitRef: normalizedSource.gitRef,\n gitPath: normalizedSource.gitPath\n });\n\n ctx.source.pluginMetadata = {\n isPlugin: true,\n marketplaceEntry: pluginEntry\n };\n\n const loader = getLoaderForSource(ctx.source);\n const loaded = await loader.load(ctx.source, options, execContext);\n\n ctx.source.packageName = loaded.packageName;\n ctx.source.version = loaded.version;\n ctx.source.contentRoot = loaded.contentRoot;\n ctx.source.pluginMetadata = {\n ...loaded.pluginMetadata,\n ...(ctx.source.pluginMetadata ?? {}),\n marketplaceEntry: pluginEntry\n };\n\n if (loaded.sourceMetadata?.baseDetection) {\n applyBaseDetection(ctx, loaded);\n }\n\n const basePath = ctx.detectedBase || loaded.contentRoot || execContext.targetDir;\n const repoRoot = loaded.sourceMetadata?.repoPath || loaded.contentRoot || basePath;\n\n results.push({\n pluginEntry,\n context: ctx,\n basePath,\n repoRoot\n });\n }\n } catch (error) {\n logger.warn('Failed to resolve plugin for list', { plugin: name, error });\n continue;\n }\n }\n\n return results;\n}\n", "import { basename, join, relative } from 'path';\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport type { InstallationContext, PackageSource } from './context.js';\nimport { classifyPackageInput } from '../package-input.js';\nimport { normalizePlatforms } from '../../platform/platform-mapper.js';\nimport { parsePackageYml } from '../../../utils/package-yml.js';\nimport { getLocalPackageYmlPath, getLocalOpenPackageDir } from '../../../utils/paths.js';\nimport { exists } from '../../../utils/fs.js';\nimport { createWorkspacePackageYml, ensureLocalOpenPackageStructure } from '../../package-management.js';\nimport { logger } from '../../../utils/logger.js';\nimport { resolveDeclaredPath } from '../../../utils/path-resolution.js';\nimport type { ResourceInstallationSpec } from '../convenience-matchers.js';\n\n/**\n * Result of building contexts for bulk install.\n * Workspace root is separate from dependency contexts so the orchestrator can run it as a distinct stage.\n */\nexport interface BulkInstallContextsResult {\n workspaceContext: InstallationContext | null;\n dependencyContexts: InstallationContext[];\n}\n\n/**\n * Build context for registry-based installation\n */\nexport async function buildRegistryInstallContext(\n execContext: ExecutionContext,\n packageName: string,\n options: InstallOptions & { version?: string; registryPath?: string }\n): Promise<InstallationContext> {\n const source: PackageSource = {\n type: 'registry',\n packageName,\n version: options.version,\n registryPath: options.registryPath\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n}\n\n/**\n * Build context for path-based installation\n */\nexport async function buildPathInstallContext(\n execContext: ExecutionContext,\n sourcePath: string,\n options: InstallOptions & { sourceType: 'directory' | 'tarball' }\n): Promise<InstallationContext> {\n // Will need to load package to get name\n // For now, we'll populate after loading\n const source: PackageSource = {\n type: 'path',\n packageName: '', // Populated after loading\n localPath: sourcePath,\n sourceType: options.sourceType\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n}\n\n/**\n * Build context for git-based installation\n */\nexport async function buildGitInstallContext(\n execContext: ExecutionContext,\n gitUrl: string,\n options: InstallOptions & { gitRef?: string; gitPath?: string }\n): Promise<InstallationContext> {\n const source: PackageSource = {\n type: 'git',\n packageName: '', // Populated after loading\n gitUrl,\n gitRef: options.gitRef,\n gitPath: options.gitPath\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n}\n\n/**\n * Build context for workspace root installation\n * Used when installing/applying workspace-level files from .openpackage/\n */\nexport async function buildWorkspaceRootInstallContext(\n execContext: ExecutionContext,\n options: InstallOptions,\n mode: 'install' | 'apply' = 'install'\n): Promise<InstallationContext | null> {\n const cwd = execContext.targetDir;\n \n // Ensure .openpackage/ structure exists\n await ensureLocalOpenPackageStructure(cwd);\n \n // Create workspace manifest if it doesn't exist\n await createWorkspacePackageYml(cwd);\n \n const openpackageDir = getLocalOpenPackageDir(cwd);\n const packageYmlPath = getLocalPackageYmlPath(cwd);\n \n // Check if workspace manifest exists\n if (!(await exists(packageYmlPath))) {\n return null;\n }\n \n // Load workspace manifest\n let config;\n try {\n config = await parsePackageYml(packageYmlPath);\n } catch (error) {\n logger.warn(`Failed to read workspace manifest: ${error}`);\n return null;\n }\n \n // Use workspace directory name as package name if not specified in manifest\n const packageName = config.name || basename(cwd);\n \n const source: PackageSource = {\n type: 'workspace',\n packageName,\n version: config.version,\n contentRoot: openpackageDir\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode,\n options: mode === 'apply' ? { ...options, force: true } : options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n}\n\n\n\n/**\n * Build context from package input (auto-detect type)\n */\nexport async function buildInstallContext(\n execContext: ExecutionContext,\n packageInput: string | undefined,\n options: InstallOptions\n): Promise<InstallationContext | InstallationContext[] | BulkInstallContextsResult> {\n // No input = bulk install (returns workspace + dependency contexts separately)\n if (!packageInput) {\n return buildBulkInstallContexts(execContext, options);\n }\n \n // Classify input to determine source type (use sourceCwd for input resolution)\n const classification = await classifyPackageInput(packageInput, execContext.sourceCwd);\n \n switch (classification.type) {\n case 'registry':\n return buildRegistryInstallContext(execContext, classification.name!, options);\n \n case 'directory':\n case 'tarball':\n return buildPathInstallContext(execContext, classification.resolvedPath!, {\n ...options,\n sourceType: classification.type\n });\n \n case 'git':\n return buildGitInstallContext(execContext, classification.gitUrl!, {\n ...options,\n gitRef: classification.gitRef,\n gitPath: classification.gitPath\n });\n \n default:\n throw new Error(`Unknown package input type: ${classification.type}`);\n }\n}\n\n/**\n * Build contexts for bulk installation.\n * Returns workspace root and dependency contexts separately so the orchestrator can run workspace as a distinct stage.\n */\nasync function buildBulkInstallContexts(\n execContext: ExecutionContext,\n options: InstallOptions\n): Promise<BulkInstallContextsResult> {\n const cwd = execContext.targetDir;\n const dependencyContexts: InstallationContext[] = [];\n\n // First, try to build workspace root context (run as distinct stage, not in dependency loop)\n const workspaceContext = await buildWorkspaceRootInstallContext(execContext, options, 'install');\n\n // Ensure workspace manifest exists before reading\n await createWorkspacePackageYml(cwd);\n\n // Read openpackage.yml and create context for each package\n const opkgYmlPath = getLocalPackageYmlPath(cwd);\n const opkgYml = await parsePackageYml(opkgYmlPath);\n\n // Get workspace package name to exclude it from bulk install\n const workspacePackageName = workspaceContext?.source.packageName;\n\n // Support both legacy `packages:` and current `dependencies:` + `dev-dependencies:` keys.\n const deps = ((opkgYml as any).packages ??\n (opkgYml as any).dependencies ??\n []) as any[];\n const devDeps = (((opkgYml as any).devDependencies ??\n (opkgYml as any)['dev-dependencies'] ??\n []) as any[]);\n\n // Merge + dedupe to avoid double-install from duplicate manifest entries\n const allDeps: any[] = [...deps, ...devDeps].filter(Boolean);\n const seen = new Set<string>();\n\n if (allDeps.length > 0) {\n for (const dep of allDeps) {\n const dedupeKey = JSON.stringify({\n name: dep?.name ?? null,\n url: dep?.url ?? dep?.git ?? null,\n ref: dep?.ref ?? null,\n path: dep?.path ?? null,\n version: dep?.version ?? null,\n base: dep?.base ?? null\n });\n if (seen.has(dedupeKey)) {\n continue;\n }\n seen.add(dedupeKey);\n\n // Skip if this package matches the workspace package name\n if (workspacePackageName && dep.name === workspacePackageName) {\n continue;\n }\n \n let source: PackageSource;\n \n if (dep.git || dep.url) {\n // Git source - handle both old (git) and new (url) formats\n const gitUrlRaw = dep.url || dep.git!;\n \n // Parse url field to extract ref if embedded\n const [gitUrl, embeddedRef] = gitUrlRaw.includes('#') \n ? gitUrlRaw.split('#', 2)\n : [gitUrlRaw, undefined];\n \n // Use embedded ref if present, otherwise fall back to separate ref field\n const gitRef = embeddedRef || dep.ref;\n\n // Bulk installs should match the resource-model behavior used by individual installs.\n // Many manifests use `name: gh@owner/repo/<resourcePath>` and/or `path:` to indicate a resource\n // (directory or file) within the repo. Passing that as `gitPath` breaks because gitPath implies\n // \"package lives in subdirectory\", and can be a file path (invalid).\n let resourcePathFromName: string | undefined;\n const depName = String(dep.name ?? '');\n if (depName.startsWith('gh@')) {\n const tail = depName.slice(3);\n const parts = tail.split('/').filter(Boolean);\n if (parts.length > 2) {\n resourcePathFromName = parts.slice(2).join('/');\n }\n }\n const effectiveResourcePath: string | undefined = dep.path || resourcePathFromName;\n const shouldTreatPathAsResource = depName.startsWith('gh@');\n \n source = {\n type: 'git',\n packageName: dep.name,\n gitUrl,\n gitRef,\n gitPath: shouldTreatPathAsResource ? undefined : dep.path,\n resourcePath: shouldTreatPathAsResource ? effectiveResourcePath : undefined,\n manifestBase: dep.base // Phase 5: Pass manifest base to source\n };\n } else if (dep.path) {\n // Path source - resolve tilde paths before creating source\n const resolved = resolveDeclaredPath(dep.path, cwd);\n const isTarball = dep.path.endsWith('.tgz') || dep.path.endsWith('.tar.gz');\n \n source = {\n type: 'path',\n packageName: dep.name,\n localPath: resolved.absolute,\n sourceType: isTarball ? 'tarball' : 'directory',\n manifestBase: dep.base // Phase 5: Pass manifest base to source\n };\n } else {\n // Registry source\n source = {\n type: 'registry',\n packageName: dep.name,\n version: dep.version,\n manifestBase: dep.base // Phase 5: Pass manifest base to source\n };\n }\n \n // Phase 5: Create context with base field from manifest if present\n const context: InstallationContext = {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n \n // Phase 5: Store base from manifest for reproducibility\n // When base is present, skip base detection and use manifest value\n if (dep.base) {\n context.baseRelative = dep.base;\n context.baseSource = 'manifest';\n }\n \n dependencyContexts.push(context);\n }\n }\n\n return { workspaceContext: workspaceContext ?? null, dependencyContexts };\n}\n\n/**\n * Build context from a ResourceSpec (Phase 3: Resource Model)\n */\nexport async function buildResourceInstallContext(\n execContext: ExecutionContext,\n resourceSpec: any, // ResourceSpec from resource-arg-parser\n options: InstallOptions\n): Promise<InstallationContext> {\n let source: PackageSource;\n \n switch (resourceSpec.type) {\n case 'github-url':\n case 'github-shorthand':\n // Git source with resource path\n source = {\n type: 'git',\n packageName: '', // Populated after loading\n gitUrl: resourceSpec.gitUrl!,\n gitRef: resourceSpec.ref,\n // IMPORTANT: In resource-mode, `resourceSpec.path` represents a resource filter\n // (file or directory) within the repo, NOT a git subdirectory to clone into.\n // `gitPath` is reserved for \"package lives in subdirectory\" semantics (legacy/manifest).\n resourcePath: resourceSpec.path // Store resource path for base detection + scoping\n };\n break;\n \n case 'registry':\n // Registry source with optional path\n source = {\n type: 'registry',\n packageName: resourceSpec.name!,\n version: resourceSpec.version,\n resourcePath: resourceSpec.path\n };\n break;\n \n case 'filepath':\n // Local path source\n const absolutePath = resourceSpec.absolutePath!;\n const relativePath = relative(execContext.sourceCwd, absolutePath).replace(/\\\\/g, '/');\n const resourcePath = relativePath.startsWith('..') ? basename(absolutePath) : relativePath;\n source = {\n type: 'path',\n packageName: '', // Populated after loading\n localPath: absolutePath,\n sourceType: resourceSpec.isDirectory ? 'directory' : 'tarball',\n resourcePath\n };\n break;\n \n default:\n throw new Error(`Unknown resource type: ${resourceSpec.type}`);\n }\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n}\n\nfunction buildResourceMatchedPattern(\n resourceSpec: ResourceInstallationSpec,\n repoRoot: string,\n basePath: string\n): string | undefined {\n const absoluteResourcePath = join(repoRoot, resourceSpec.resourcePath);\n const relativeToBase = relative(basePath, absoluteResourcePath)\n .replace(/\\\\/g, '/')\n .replace(/^\\.\\/?/, '');\n\n if (!relativeToBase) {\n return undefined;\n }\n\n if (resourceSpec.resourceKind === 'directory') {\n const normalized = relativeToBase.replace(/\\/$/, '');\n return `${normalized}/**`;\n }\n\n return relativeToBase;\n}\n\n/**\n * Build multiple contexts for resource-centric installations.\n */\nexport function buildResourceInstallContexts(\n baseContext: InstallationContext,\n resourceSpecs: ResourceInstallationSpec[],\n repoRoot: string\n): InstallationContext[] {\n const detectedBase = baseContext.detectedBase ?? baseContext.source.contentRoot ?? baseContext.targetDir;\n const baseRelative = baseContext.baseRelative ?? (relative(repoRoot, detectedBase) || '.');\n\n return resourceSpecs.map(spec => {\n const source: PackageSource = {\n ...baseContext.source,\n resourcePath: spec.resourcePath,\n resourceVersion: spec.resourceVersion\n };\n\n const effectiveBase = baseContext.detectedBase ?? spec.basePath;\n\n return {\n ...baseContext,\n source,\n resolvedPackages: baseContext.resolvedPackages.length > 0\n ? baseContext.resolvedPackages\n : [],\n warnings: [],\n errors: [],\n detectedBase: effectiveBase,\n baseRelative: baseRelative === '' ? '.' : baseRelative,\n baseSource: baseContext.baseSource,\n matchedPattern: buildResourceMatchedPattern(spec, repoRoot, effectiveBase) ?? baseContext.matchedPattern\n };\n });\n}\n\n\n", "import type { PackageYml, ExecutionContext } from '../../../types/index.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type { InstallOptions } from '../../../types/index.js';\nimport type { EnhancedPackageFormat } from '../detection-types.js';\nimport type { ConversionContext } from '../conversion-context.js';\n\n/**\n * Result of loading a package from a source\n */\nexport interface LoadedPackage {\n /** Package metadata */\n metadata: PackageYml;\n \n /** Package name (from package.yml or derived) */\n packageName: string;\n \n /** Package version */\n version: string;\n \n /** Absolute path to package content root */\n contentRoot: string;\n \n /** Source type for tracking */\n source: 'registry' | 'path' | 'git' | 'workspace';\n \n /** Plugin-specific metadata (will be stored in context.source.pluginMetadata) */\n pluginMetadata?: {\n isPlugin: boolean;\n pluginType?: 'individual' | 'marketplace';\n format?: any;\n manifestPath?: string;\n };\n \n /** Additional source metadata */\n sourceMetadata?: {\n /** For git sources: repository path */\n repoPath?: string;\n \n /** For git sources: commit SHA of cached version */\n commitSha?: string;\n \n /** Base detection result (for resource model) */\n baseDetection?: any;\n };\n \n /**\n * Format detection metadata (Phase 4)\n * Set by conversion coordinator after format detection\n */\n formatDetection?: EnhancedPackageFormat;\n \n /**\n * Whether package was pre-converted (Phase 4)\n * True if package was converted from platform format to universal\n */\n preConverted?: boolean;\n \n /**\n * Conversion context (Phase 4)\n * Contains conversion metadata and statistics\n */\n conversionContext?: ConversionContext;\n}\n\n/**\n * Interface for package source loaders\n */\nexport interface PackageSourceLoader {\n /**\n * Check if this loader can handle the given source\n */\n canHandle(source: PackageSource): boolean;\n \n /**\n * Load package from the source\n * \n * @param source - Package source information\n * @param options - Install options\n * @param execContext - Execution context (uses sourceCwd for resolving inputs)\n */\n load(\n source: PackageSource,\n options: InstallOptions,\n execContext: ExecutionContext\n ): Promise<LoadedPackage>;\n}\n\n/**\n * Base error for source loading failures\n */\nexport class SourceLoadError extends Error {\n constructor(\n public source: PackageSource,\n message: string,\n public cause?: Error\n ) {\n super(message);\n this.name = 'SourceLoadError';\n }\n}\n", "import os from 'os';\nimport path from 'path';\n\nimport { DIR_PATTERNS, OPENPACKAGE_DIRS, UNVERSIONED } from '../../constants/index.js';\nimport { listPackageVersions, getPackageVersionPath } from '../directory.js';\nimport { exists } from '../../utils/fs.js';\nimport { parsePackageYml } from '../../utils/package-yml.js';\nimport { getLocalPackageDir } from '../../utils/paths.js';\nimport { SCOPED_PACKAGE_REGEX, normalizePackageName } from '../../utils/package-name.js';\nimport semver from 'semver';\nimport type { InstallResolutionMode } from './types.js';\n\ntype MutableSourceKind = 'workspaceMutable' | 'globalMutable';\n\nexport interface MutableSourceInfo {\n kind: MutableSourceKind;\n packageRootDir: string;\n version: string;\n}\n\nexport interface CandidateVersionsResult {\n localVersions: string[];\n sourceKind?: MutableSourceKind | 'registry';\n contentRoot?: string;\n}\n\nfunction getGlobalMutablePackageDir(packageName: string): string {\n const normalizedName = normalizePackageName(packageName);\n const scopedMatch = normalizedName.match(SCOPED_PACKAGE_REGEX);\n const baseDir = path.join(os.homedir(), DIR_PATTERNS.OPENPACKAGE, OPENPACKAGE_DIRS.PACKAGES);\n\n if (scopedMatch) {\n const [, scope, localName] = scopedMatch;\n return path.join(baseDir, `@${scope}`, localName);\n }\n\n return path.join(baseDir, normalizedName);\n}\n\nasync function loadMutableSourceVersion(packageRootDir: string): Promise<string | null> {\n const manifestPath = path.join(packageRootDir, 'openpackage.yml');\n if (!(await exists(manifestPath))) {\n return null;\n }\n\n try {\n const manifest = await parsePackageYml(manifestPath);\n return manifest.version ?? UNVERSIONED;\n } catch {\n return null;\n }\n}\n\nexport async function detectWorkspaceMutableSource(\n cwd: string,\n packageName: string\n): Promise<MutableSourceInfo | null> {\n const packageRootDir = getLocalPackageDir(cwd, packageName);\n const version = await loadMutableSourceVersion(packageRootDir);\n if (!version) {\n return null;\n }\n\n return { kind: 'workspaceMutable', packageRootDir, version };\n}\n\nexport async function detectGlobalMutableSource(\n packageName: string\n): Promise<MutableSourceInfo | null> {\n const packageRootDir = getGlobalMutablePackageDir(packageName);\n const version = await loadMutableSourceVersion(packageRootDir);\n if (!version) {\n return null;\n }\n\n return { kind: 'globalMutable', packageRootDir, version };\n}\n\nexport async function resolveCandidateVersionsForInstall(args: {\n cwd: string;\n packageName: string;\n mode: InstallResolutionMode;\n}): Promise<CandidateVersionsResult> {\n const { cwd, packageName, mode } = args;\n\n if (mode === 'remote-primary') {\n return { localVersions: [] };\n }\n\n const workspaceSource = await detectWorkspaceMutableSource(cwd, packageName);\n if (workspaceSource) {\n return {\n localVersions: [workspaceSource.version],\n sourceKind: workspaceSource.kind,\n contentRoot: workspaceSource.packageRootDir\n };\n }\n\n const globalMutable = await detectGlobalMutableSource(packageName);\n if (globalMutable) {\n return {\n localVersions: [globalMutable.version],\n sourceKind: globalMutable.kind,\n contentRoot: globalMutable.packageRootDir\n };\n }\n\n const registryVersions = await listPackageVersions(packageName);\n return {\n localVersions: registryVersions,\n sourceKind: 'registry'\n };\n}\n\nexport async function resolvePackageContentRoot(args: {\n cwd: string;\n packageName: string;\n version: string;\n}): Promise<string> {\n const { cwd, packageName, version } = args;\n\n const workspaceSource = await detectWorkspaceMutableSource(cwd, packageName);\n if (workspaceSource) {\n return path.join(workspaceSource.packageRootDir, path.sep);\n }\n\n const globalMutable = await detectGlobalMutableSource(packageName);\n if (globalMutable) {\n return path.join(globalMutable.packageRootDir, path.sep);\n }\n\n const versionPath = getPackageVersionPath(packageName, version);\n return path.join(versionPath, path.sep);\n}\n\nexport async function maybeWarnHigherRegistryVersion(args: {\n packageName: string;\n selectedVersion: string;\n}): Promise<string | undefined> {\n if (!semver.valid(args.selectedVersion)) {\n return undefined;\n }\n\n const registryVersions = await listPackageVersions(args.packageName);\n if (registryVersions.length === 0) {\n return undefined;\n }\n\n const highest = registryVersions[0];\n if (semver.valid(highest) && semver.gt(highest, args.selectedVersion)) {\n return `Newer version available in local registry: ${args.packageName}@${args.selectedVersion} (selected) < ${args.packageName}@${highest} (registry)`;\n }\n\n return undefined;\n}\n", "import path from 'path';\n\nimport { getRegistryDirectories } from '../directory.js';\nimport { normalizePackageName } from '../../utils/package-name.js';\nimport { selectInstallVersionUnified } from '../install/version-selection.js';\nimport { DEFAULT_VERSION_CONSTRAINT, REGISTRY_PATH_PREFIXES } from '../../constants/index.js';\nimport type { InstallResolutionMode } from '../install/types.js';\n\nexport interface ResolveRegistryVersionOptions {\n /**\n * Semver constraint; defaults to '*'.\n */\n constraint?: string;\n /**\n * Resolution strategy (defaults to install's \"default\" mode: local-first with remote fallback).\n */\n mode?: InstallResolutionMode;\n profile?: string;\n apiKey?: string;\n explicitPrereleaseIntent?: boolean;\n}\n\nimport type { ResolutionSource } from '../../constants/index.js';\n\nexport interface ResolveRegistryVersionResult {\n version: string;\n declaredPath: string;\n absolutePath: string;\n resolutionSource?: ResolutionSource;\n}\n\n/**\n * Resolve a registry version and construct both declared (tilde) and absolute paths.\n */\nexport async function resolveRegistryVersion(\n packageName: string,\n options: ResolveRegistryVersionOptions = {}\n): Promise<ResolveRegistryVersionResult> {\n const normalizedName = normalizePackageName(packageName);\n const mode: InstallResolutionMode = options.mode ?? 'default';\n const constraint = options.constraint ?? DEFAULT_VERSION_CONSTRAINT;\n\n const selection = await selectInstallVersionUnified({\n packageName: normalizedName,\n constraint,\n mode,\n explicitPrereleaseIntent: options.explicitPrereleaseIntent,\n profile: options.profile,\n apiKey: options.apiKey\n });\n\n if (!selection.selectedVersion) {\n throw new Error(\n `Unable to resolve a version for '${normalizedName}' with constraint '${constraint}'.`\n );\n }\n\n const version = selection.selectedVersion;\n const { packages: registryRoot } = getRegistryDirectories();\n\n const absolutePath = path.join(registryRoot, normalizedName, version, path.sep);\n const declaredPath = `${REGISTRY_PATH_PREFIXES.BASE}${normalizedName}/${version}/`;\n\n return {\n version,\n declaredPath,\n absolutePath,\n resolutionSource: selection.resolutionSource\n };\n}\n", "import * as semver from 'semver';\nimport { listPackageVersions } from '../directory.js';\nimport {\n fetchRemotePackageMetadata,\n type RemotePullFailure\n} from '../remote-pull.js';\nimport type { PullPackageResponse } from '../../types/api.js';\nimport { describeRemoteFailure } from './remote-reporting.js';\nimport { InstallResolutionMode } from './types.js';\nimport {\n selectVersionWithWipPolicy,\n type VersionSelectionOptions,\n type VersionSelectionResult\n} from '../../utils/version-ranges.js';\nimport { isScopedName } from '../scoping/package-scoping.js';\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput } from '../ports/resolve.js';\nimport { extractRemoteErrorReason } from '../../utils/error-reasons.js';\nimport { UNVERSIONED } from '../../constants/index.js';\nimport { createCacheManager } from '../cache-manager.js';\n\nexport interface VersionSourceSummary {\n localVersions: string[];\n remoteVersions: string[];\n availableVersions: string[];\n remoteStatus: 'skipped' | 'success' | 'failed';\n warnings: string[];\n remoteError?: string;\n fallbackToLocalOnly?: boolean;\n remoteFailure?: RemotePullFailure;\n}\n\nexport interface GatherVersionSourcesArgs {\n packageName: string;\n mode: InstallResolutionMode;\n localVersions?: string[];\n remoteVersions?: string[];\n profile?: string;\n apiKey?: string;\n}\n\nexport interface InstallVersionSelectionArgs extends GatherVersionSourcesArgs {\n constraint: string;\n explicitPrereleaseIntent?: boolean;\n selectionOptions?: VersionSelectionOptions;\n}\n\nexport interface InstallVersionSelectionResult {\n selectedVersion: string | null;\n selection: VersionSelectionResult;\n sources: VersionSourceSummary;\n constraint: string;\n mode: InstallResolutionMode;\n}\n\nexport interface UnifiedInstallVersionSelectionArgs {\n packageName: string;\n constraint: string;\n mode: InstallResolutionMode;\n selectionOptions?: VersionSelectionOptions;\n explicitPrereleaseIntent?: boolean;\n profile?: string;\n apiKey?: string;\n localVersions?: string[];\n remoteVersions?: string[];\n filterAvailableVersions?: (versions: string[]) => string[];\n}\n\nexport interface UnifiedInstallVersionSelectionResult extends InstallVersionSelectionResult {\n resolutionSource?: 'local' | 'remote';\n}\n\ninterface RemoteVersionLookupOptions {\n profile?: string;\n apiKey?: string;\n skipCache?: boolean; // For --remote flag, bypass metadata cache\n}\n\ninterface RemoteVersionLookupSuccess {\n success: true;\n versions: string[];\n}\n\ninterface RemoteVersionLookupFailure {\n success: false;\n failure: RemotePullFailure;\n}\n\ntype RemoteVersionLookupResult = RemoteVersionLookupSuccess | RemoteVersionLookupFailure;\n\nexport async function gatherVersionSourcesForInstall(args: GatherVersionSourcesArgs): Promise<VersionSourceSummary> {\n const normalizedLocal = normalizeAndSortVersions(\n args.localVersions ?? await listPackageVersions(args.packageName)\n );\n let remoteVersions: string[] = [];\n let remoteStatus: VersionSourceSummary['remoteStatus'] = 'skipped';\n let remoteError: string | undefined;\n let remoteFailure: RemotePullFailure | undefined;\n const warnings: string[] = [];\n\n if (args.mode !== 'local-only') {\n if (args.remoteVersions) {\n remoteVersions = normalizeAndSortVersions(args.remoteVersions);\n remoteStatus = 'success';\n } else {\n const remoteLookup = await fetchRemoteVersions(args.packageName, {\n profile: args.profile,\n apiKey: args.apiKey,\n skipCache: args.mode === 'remote-primary'\n });\n\n if (remoteLookup.success) {\n remoteVersions = normalizeAndSortVersions(remoteLookup.versions);\n remoteStatus = 'success';\n } else {\n remoteStatus = 'failed';\n remoteError = describeRemoteFailure(args.packageName, remoteLookup.failure);\n remoteFailure = remoteLookup.failure;\n }\n }\n }\n\n if (args.mode === 'local-only') {\n return {\n localVersions: normalizedLocal,\n remoteVersions: [],\n availableVersions: normalizedLocal,\n remoteStatus: 'skipped',\n warnings\n };\n }\n\n if (args.mode === 'remote-primary') {\n if (remoteStatus !== 'success') {\n throw new Error(\n remoteError ?? `Remote registry data required to resolve ${args.packageName}`\n );\n }\n\n return {\n localVersions: normalizedLocal,\n remoteVersions,\n availableVersions: remoteVersions,\n remoteStatus,\n warnings,\n remoteFailure\n };\n }\n\n const fallbackToLocalOnly = remoteStatus !== 'success';\n\n if (fallbackToLocalOnly && remoteError && isScopedName(args.packageName)) {\n const reason = extractRemoteErrorReason(remoteError);\n warnings.push(`Remote pull failed for \\`${args.packageName}\\` (reason: ${reason})`);\n }\n\n return {\n localVersions: normalizedLocal,\n remoteVersions,\n availableVersions: fallbackToLocalOnly ? normalizedLocal : mergeAndSortVersions(normalizedLocal, remoteVersions),\n remoteStatus,\n warnings,\n remoteError,\n fallbackToLocalOnly,\n remoteFailure\n };\n}\n\nexport async function selectInstallVersionUnified(\n args: UnifiedInstallVersionSelectionArgs\n): Promise<UnifiedInstallVersionSelectionResult> {\n const mergedSelectionOptions: VersionSelectionOptions = {\n ...(args.selectionOptions ?? {}),\n ...(args.explicitPrereleaseIntent ? { explicitPrereleaseIntent: true } : {})\n };\n\n const applyFilter = (versions: string[]): string[] =>\n args.filterAvailableVersions ? args.filterAvailableVersions(versions) : versions;\n\n const attemptWithSources = (sources: VersionSourceSummary, modeContext: InstallResolutionMode) => {\n const filteredVersions = applyFilter(sources.availableVersions);\n\n const selection = selectVersionWithWipPolicy(\n filteredVersions,\n args.constraint,\n mergedSelectionOptions\n );\n\n const selectedVersion = selection.version;\n let resolutionSource: 'local' | 'remote' | undefined;\n if (selectedVersion) {\n const inLocal = sources.localVersions.includes(selectedVersion);\n const inRemote = sources.remoteVersions.includes(selectedVersion);\n if (inLocal && !inRemote) {\n resolutionSource = 'local';\n } else if (!inLocal && inRemote) {\n resolutionSource = 'remote';\n } else if (inLocal && inRemote) {\n resolutionSource = modeContext === 'remote-primary' ? 'remote' : 'local';\n }\n }\n\n return {\n selectedVersion,\n selection,\n sources,\n resolutionSource\n };\n };\n\n const gatherBase = {\n packageName: args.packageName,\n localVersions: args.localVersions,\n remoteVersions: args.remoteVersions,\n profile: args.profile,\n apiKey: args.apiKey\n };\n\n if (args.mode === 'local-only') {\n const sources = await gatherVersionSourcesForInstall({\n ...gatherBase,\n mode: 'local-only'\n });\n const result = attemptWithSources(sources, 'local-only');\n return {\n ...result,\n constraint: args.constraint,\n mode: args.mode\n };\n }\n\n if (args.mode === 'remote-primary') {\n const sources = await gatherVersionSourcesForInstall({\n ...gatherBase,\n mode: 'remote-primary'\n });\n const result = attemptWithSources(sources, 'remote-primary');\n return {\n ...result,\n constraint: args.constraint,\n mode: args.mode\n };\n }\n\n // Default mode: local-first with remote fallback.\n const localSources = await gatherVersionSourcesForInstall({\n ...gatherBase,\n mode: 'local-only'\n });\n const localAttempt = attemptWithSources(localSources, 'local-only');\n\n if (localAttempt.selectedVersion) {\n return {\n ...localAttempt,\n constraint: args.constraint,\n mode: args.mode\n };\n }\n\n const fallbackSources = await gatherVersionSourcesForInstall({\n ...gatherBase,\n mode: 'default'\n });\n\n if (fallbackSources.remoteStatus === 'failed') {\n const reason =\n fallbackSources.remoteError ??\n `Remote metadata lookup failed while resolving ${args.packageName}`;\n throw new Error(reason);\n }\n\n const fallbackAttempt = attemptWithSources(fallbackSources, args.mode);\n\n return {\n ...fallbackAttempt,\n constraint: args.constraint,\n mode: args.mode\n };\n}\n\nasync function fetchRemoteVersions(\n packageName: string,\n options: RemoteVersionLookupOptions,\n output?: OutputPort\n): Promise<RemoteVersionLookupResult> {\n const out = output ?? resolveOutput();\n const cacheManager = createCacheManager();\n \n // Check cached metadata first (skip if --remote flag is set)\n if (!options.skipCache) {\n const cachedMeta = await cacheManager.getCachedMetadata(packageName);\n if (cachedMeta && cachedMeta.versions.length > 0) {\n return { success: true, versions: cachedMeta.versions };\n }\n }\n \n const spinner = out.spinner();\n spinner.start(`Checking remote versions for ${packageName}...`);\n\n try {\n const metadataResult = await fetchRemotePackageMetadata(packageName, undefined, {\n profile: options.profile,\n apiKey: options.apiKey,\n recursive: false\n });\n\n if (!metadataResult.success) {\n return { success: false, failure: metadataResult };\n }\n\n const versions = extractVersionsFromRemoteResponse(metadataResult.response);\n \n // Cache the fetched versions\n if (versions.length > 0) {\n await cacheManager.cacheMetadata(packageName, versions);\n }\n \n return { success: true, versions };\n } finally {\n spinner.stop();\n }\n}\n\nfunction extractVersionsFromRemoteResponse(response: PullPackageResponse): string[] {\n const collected = new Set<string>();\n\n const candidates: Array<unknown> = [];\n const packageAny = response.package as any;\n if (Array.isArray(packageAny?.versions)) {\n candidates.push(...packageAny.versions);\n }\n\n const responseAny = response as any;\n if (Array.isArray(responseAny?.versions)) {\n candidates.push(...responseAny.versions);\n }\n if (Array.isArray(responseAny?.availableVersions)) {\n candidates.push(...responseAny.availableVersions);\n }\n\n for (const candidate of candidates) {\n const normalized = extractVersionString(candidate);\n if (normalized) {\n collected.add(normalized);\n }\n }\n\n if (response.version) {\n const normalizedVersion = response.version.version ?? UNVERSIONED;\n collected.add(normalizedVersion);\n }\n\n return Array.from(collected);\n}\n\nfunction extractVersionString(candidate: unknown): string | null {\n if (typeof candidate === 'string') {\n return semver.valid(candidate) ? candidate : null;\n }\n\n if (candidate && typeof candidate === 'object') {\n const value = (candidate as any).version;\n if (value === undefined || value === null) {\n return UNVERSIONED;\n }\n if (typeof value === 'string') {\n if (semver.valid(value)) {\n return value;\n }\n }\n }\n\n return null;\n}\n\nfunction normalizeAndSortVersions(versions: string[]): string[] {\n const normalized = new Set<string>();\n for (const version of versions) {\n if (typeof version !== 'string') {\n continue;\n }\n const trimmed = version.trim();\n if (!trimmed) {\n continue;\n }\n if (!semver.valid(trimmed)) {\n continue;\n }\n normalized.add(trimmed);\n }\n const sorted = Array.from(normalized).sort(semver.rcompare);\n return sorted;\n}\n\nfunction mergeAndSortVersions(left: string[], right: string[]): string[] {\n const merged = new Set<string>();\n\n for (const version of [...left, ...right]) {\n if (semver.valid(version)) {\n merged.add(version);\n }\n }\n\n const sorted = Array.from(merged).sort(semver.rcompare);\n return sorted;\n}\n\n", "import type { PullPackageDownload } from '../../types/api.js';\nimport { hasPackageVersion } from '../directory.js';\nimport { parseDownloadIdentifier } from '../remote-pull.js';\n\n/**\n * Create a unique key for a download based on name and version\n */\nexport function createDownloadKey(name: string, version: string): string {\n return `${name}@${version}`;\n}\n\n/**\n * Compute which download keys are missing locally\n */\nexport async function computeMissingDownloadKeys(downloads: PullPackageDownload[]): Promise<Set<string>> {\n const missingKeys = new Set<string>();\n\n for (const download of downloads) {\n if (!download?.name) {\n continue;\n }\n\n try {\n const { packageName: name, version } = parseDownloadIdentifier(download.name);\n if (!version) {\n continue;\n }\n\n const existsLocally = await hasPackageVersion(name, version);\n if (!existsLocally) {\n missingKeys.add(createDownloadKey(name, version));\n }\n } catch (error) {\n // Skip download due to invalid name\n }\n }\n\n return missingKeys;\n}\n", "/**\n * Extract a concise, user-friendly reason string from a raw error message.\n *\n * This is used to normalize low-level network / registry / fetch errors into\n * short labels that can be embedded in messages like:\n * \"Remote pull failed for `<pkg>` (reason: <reason>)\"\n */\nexport function extractRemoteErrorReason(message: string): string {\n const normalized = (message || '').trim();\n\n if (!normalized) {\n return 'unknown error';\n }\n\n // Specific phrases we already emit elsewhere\n if (normalized.includes('not found in remote registry')) {\n return 'not found in remote registry';\n }\n if (/Access denied/i.test(normalized)) {\n return 'access denied';\n }\n if (/Network error/i.test(normalized)) {\n return 'network error';\n }\n if (/Integrity check failed/i.test(normalized)) {\n return 'integrity check failed';\n }\n\n // Common network / fetch failures\n if (/fetch failed/i.test(normalized)) {\n return 'network error';\n }\n if (/network|ENOTFOUND|ECONNREFUSED|ETIMEDOUT/i.test(normalized)) {\n return 'network error';\n }\n\n // Not found / HTTP 404 style errors\n if (/not found|404/i.test(normalized)) {\n return 'not found in remote registry';\n }\n\n // Access / auth errors\n if (/access denied|unauthorized|403|401/i.test(normalized)) {\n return 'access denied';\n }\n\n // Integrity / checksum issues\n if (/integrity|checksum/i.test(normalized)) {\n return 'integrity check failed';\n }\n\n // Fallback: return message if short enough, otherwise truncate\n if (normalized.length <= 50) {\n return normalized;\n }\n\n return `${normalized.slice(0, 47)}...`;\n}\n\n\n", "import type { RemoteBatchPullResult, RemotePullFailure } from '../remote-pull.js';\nimport { createDownloadKey } from './download-keys.js';\nimport { extractRemoteErrorReason } from '../../utils/error-reasons.js';\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput } from '../ports/resolve.js';\n\n/**\n * Record the outcome of a batch pull operation\n */\nexport function recordBatchOutcome(\n label: string,\n result: RemoteBatchPullResult,\n warnings: string[],\n dryRun: boolean,\n output?: OutputPort\n): void {\n const out = output ?? resolveOutput();\n if (result.warnings) {\n warnings.push(...result.warnings);\n }\n\n const successful = result.pulled.map(item => createDownloadKey(item.name, item.version));\n const failed = result.failed.map(item => ({\n key: createDownloadKey(item.name, item.version),\n error: item.error ?? 'Unknown error'\n }));\n\n if (dryRun) {\n if (successful.length > 0) {\n out.info(`Would ${label}: ${successful.join(', ')}`);\n }\n\n if (failed.length > 0) {\n for (const failure of failed) {\n const reason = extractRemoteErrorReason(failure.error);\n const message = `Dry run: remote pull would fail for \\`${failure.key}\\` (reason: ${reason})`;\n out.warn(message);\n warnings.push(message);\n }\n }\n\n return;\n }\n\n if (successful.length > 0) {\n out.success(`${label}: ${successful.length}`);\n for (const key of successful) {\n out.info(` \u251C\u2500\u2500 ${key}`);\n }\n }\n\n if (failed.length > 0) {\n for (const failure of failed) {\n const reason = extractRemoteErrorReason(failure.error);\n const message = `Remote pull failed for \\`${failure.key}\\` (reason: ${reason})`;\n out.warn(message);\n warnings.push(message);\n }\n }\n}\n\n/**\n * Describe a remote failure in a user-friendly way\n */\nexport function describeRemoteFailure(label: string, failure: RemotePullFailure): string {\n switch (failure.reason) {\n case 'not-found':\n return `Package '${label}' not found in remote registry`;\n case 'access-denied':\n return failure.message || `Access denied pulling ${label}`;\n case 'network':\n return failure.message || `Network error pulling ${label}`;\n case 'integrity':\n return failure.message || `Integrity check failed pulling ${label}`;\n default:\n return failure.message || `Failed to pull ${label}`;\n }\n}\n", "import type { PackageSourceLoader, LoadedPackage } from './base.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport { SourceLoadError } from './base.js';\nimport { parsePackageYml } from '../../../utils/package-yml.js';\nimport {\n resolvePackageContentRoot,\n detectWorkspaceMutableSource,\n detectGlobalMutableSource\n} from '../local-source-resolution.js';\nimport { resolveRegistryVersion } from '../../source-resolution/resolve-registry-version.js';\nimport { hasPackageVersion } from '../../directory.js';\nimport { pullPackageFromRemote } from '../../remote-pull.js';\nimport { join } from 'path';\n\n/**\n * Loads packages from the local registry\n */\nexport class RegistrySourceLoader implements PackageSourceLoader {\n canHandle(source: PackageSource): boolean {\n return source.type === 'registry';\n }\n \n async load(\n source: PackageSource,\n options: InstallOptions,\n execContext: ExecutionContext\n ): Promise<LoadedPackage> {\n if (!source.packageName) {\n throw new SourceLoadError(source, 'Package name is required for registry sources');\n }\n \n // Resolve version to latest when not specified (regression fix for regular registry installs)\n if (!source.version) {\n const resolved = await resolveRegistryVersion(source.packageName, {\n mode: options.resolutionMode ?? 'default',\n profile: options.profile,\n apiKey: options.apiKey\n });\n source.version = resolved.version;\n }\n \n // If package is not available (workspace, global, or registry) and mode allows remote, pull first\n const mode = options.resolutionMode ?? 'default';\n const inWorkspace = await detectWorkspaceMutableSource(execContext.targetDir, source.packageName);\n const inGlobal = await detectGlobalMutableSource(source.packageName);\n const inRegistry = await hasPackageVersion(source.packageName, source.version);\n const availableLocally = !!(inWorkspace || inGlobal || inRegistry);\n\n if (!availableLocally && mode !== 'local-only') {\n const pullResult = await pullPackageFromRemote(source.packageName, source.version, {\n profile: options.profile,\n apiKey: options.apiKey,\n skipLocalCheck: mode === 'remote-primary'\n });\n if (!pullResult.success) {\n const reason = pullResult.reason ?? 'unknown';\n const message = pullResult.message ?? 'Remote pull failed';\n throw new SourceLoadError(\n source,\n `Package ${source.packageName}@${source.version} not in local registry and remote pull failed: ${message} (reason: ${reason})`\n );\n }\n } else if (availableLocally && mode === 'remote-primary') {\n const pullResult = await pullPackageFromRemote(source.packageName, source.version, {\n profile: options.profile,\n apiKey: options.apiKey,\n skipLocalCheck: true\n });\n if (!pullResult.success) {\n const reason = pullResult.reason ?? 'unknown';\n const message = pullResult.message ?? 'Remote pull failed';\n throw new SourceLoadError(\n source,\n `--remote: Package ${source.packageName}@${source.version} remote pull failed: ${message} (reason: ${reason})`\n );\n }\n }\n if (!availableLocally && mode === 'local-only') {\n throw new SourceLoadError(\n source,\n `Package ${source.packageName}@${source.version} not found in local registry. Use default resolution (remove --local) to pull from remote.`\n );\n }\n \n try {\n // Resolve content root (use targetDir for registry location)\n const contentRoot = await resolvePackageContentRoot({\n cwd: execContext.targetDir,\n packageName: source.packageName,\n version: source.version\n });\n \n // Load package metadata\n const manifestPath = join(contentRoot, 'openpackage.yml');\n const metadata = await parsePackageYml(manifestPath);\n \n return {\n metadata,\n packageName: source.packageName,\n version: source.version,\n contentRoot,\n source: 'registry'\n };\n } catch (error) {\n throw new SourceLoadError(\n source,\n `Failed to load package ${source.packageName}@${source.version} from registry`,\n error as Error\n );\n }\n }\n \n}\n", "import { resolve, basename } from 'path';\nimport type { PackageSourceLoader, LoadedPackage } from './base.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport { SourceLoadError } from './base.js';\nimport { loadPackageFromPath } from '../path-package-loader.js';\nimport { detectPluginType } from '../plugin-detector.js';\nimport { detectBaseForFilepath } from '../base-detector.js';\nimport { getPlatformsState } from '../../../core/platforms.js';\nimport { logger } from '../../../utils/logger.js';\nimport { exists } from '../../../utils/fs.js';\nimport { formatNoPatternMatchError } from '../../../utils/install-error-messages.js';\n\n/**\n * Loads packages from local file paths (directories or tarballs)\n */\nexport class PathSourceLoader implements PackageSourceLoader {\n canHandle(source: PackageSource): boolean {\n return source.type === 'path';\n }\n \n async load(\n source: PackageSource,\n options: InstallOptions,\n execContext: ExecutionContext\n ): Promise<LoadedPackage> {\n if (!source.localPath) {\n throw new SourceLoadError(source, 'Local path is required for path sources');\n }\n \n try {\n // Resolve paths using sourceCwd for input resolution\n const resolvedPath = resolve(execContext.sourceCwd, source.localPath);\n \n // Phase 5: If manifest base is present, skip detection (reproducibility)\n let detectedBaseInfo: any = null;\n if (source.manifestBase) {\n // Use base from manifest instead of detecting\n // For path sources, manifestBase is relative to the path source itself\n const absoluteBase = resolve(resolvedPath, source.manifestBase);\n detectedBaseInfo = {\n matchType: 'manifest',\n base: absoluteBase,\n baseRelative: source.manifestBase,\n matchedPattern: null\n };\n \n source.detectedBase = absoluteBase;\n \n logger.info('Using base from manifest for path source', {\n base: source.manifestBase,\n absoluteBase\n });\n } else if (source.resourcePath) {\n // NEW: If a resource path was specified, detect base\n const platformsState = getPlatformsState(execContext.targetDir);\n const platformsConfig = platformsState.config;\n\n // For resource-centric installs, prefer detecting base from the actual resource path\n // when the resource exists under the provided localPath.\n const candidateAbsoluteResourcePath = resolve(resolvedPath, source.resourcePath);\n detectedBaseInfo = await detectBaseForFilepath(\n (await exists(candidateAbsoluteResourcePath)) ? candidateAbsoluteResourcePath : resolvedPath,\n platformsConfig\n );\n \n logger.info('Base detection result for path source', {\n matchType: detectedBaseInfo.matchType,\n base: detectedBaseInfo.base,\n matchedPattern: detectedBaseInfo.matchedPattern\n });\n \n // Phase 6: Enhanced error message with pattern suggestions\n if (detectedBaseInfo.matchType === 'none') {\n const resourcePath = source.resourcePath || source.localPath || '';\n const errorMessage = formatNoPatternMatchError(resourcePath, platformsConfig);\n throw new SourceLoadError(source, errorMessage);\n }\n \n // Store detected base in source\n if (detectedBaseInfo.base) {\n source.detectedBase = detectedBaseInfo.base;\n }\n }\n \n // Use detected base as content root if available\n const contentRoot = detectedBaseInfo?.base || resolvedPath;\n \n // Detect if this is a Claude Code plugin\n const pluginDetection = await detectPluginType(contentRoot);\n \n // Check if marketplace\n if (detectedBaseInfo?.matchType === 'marketplace') {\n return {\n metadata: null as any,\n packageName: '',\n version: '0.0.0',\n contentRoot,\n source: 'path',\n pluginMetadata: {\n isPlugin: true,\n pluginType: 'marketplace',\n manifestPath: pluginDetection.manifestPath || detectedBaseInfo?.manifestPath\n },\n sourceMetadata: {\n baseDetection: detectedBaseInfo\n }\n };\n }\n \n // Build context for package loading\n // If gitSourceOverride exists, use it for proper git-based naming\n const loadContext: any = {\n repoPath: contentRoot,\n marketplaceEntry: source.pluginMetadata?.marketplaceEntry,\n resourcePath: source.resourcePath\n };\n \n if (source.gitSourceOverride) {\n loadContext.gitUrl = source.gitSourceOverride.gitUrl;\n loadContext.path = source.gitSourceOverride.gitPath;\n }\n \n // Load package from path, passing git context for proper scoping\n let sourcePackage = await loadPackageFromPath(contentRoot, loadContext);\n \n const packageName = sourcePackage.metadata.name;\n const version = sourcePackage.metadata.version || '0.0.0';\n \n // Note: Plugin transformation is handled by the main flow, not here\n return {\n metadata: sourcePackage.metadata,\n packageName,\n version,\n contentRoot,\n source: 'path',\n pluginMetadata: pluginDetection.isPlugin ? {\n isPlugin: true,\n pluginType: pluginDetection.type as any // Can be 'individual', 'marketplace', or 'marketplace-defined'\n } : undefined,\n sourceMetadata: {\n baseDetection: detectedBaseInfo\n }\n };\n } catch (error) {\n throw new SourceLoadError(\n source,\n `Failed to load package from path: ${source.localPath}`,\n error as Error\n );\n }\n }\n \n}\n", "/**\n * Base detection algorithm for resource-based installation.\n * \n * Detects the \"base\" directory of a resource - the parent directory\n * that serves as the package root for installation flows.\n * \n * Detection priority:\n * 1. openpackage.yml at resource root\n * 2. .claude-plugin/marketplace.json at resource root (triggers selection flow)\n * 3. .claude-plugin/plugin.json at resource root\n * 4. Pattern matching against platforms.jsonc (deepest match)\n */\n\nimport { join, resolve, dirname, relative, isAbsolute, sep } from 'path';\nimport { exists, readTextFile } from '../../utils/fs.js';\nimport { extractAllFromPatterns, findDeepestMatch, type PatternMatch } from '../../utils/pattern-matcher.js';\nimport { logger } from '../../utils/logger.js';\nimport { FILE_PATTERNS, CLAUDE_PLUGIN_PATHS } from '../../constants/index.js';\nimport { stat } from 'fs/promises';\n\n/**\n * Result of base detection\n */\nexport interface BaseDetectionResult {\n /** Absolute path to detected base (undefined if no match) */\n base: string | undefined;\n \n /** The from pattern that matched (for pattern-based detection) */\n matchedPattern?: string;\n \n /** How the base was determined */\n matchType: \n | 'openpackage' // Found openpackage.yml\n | 'marketplace' // Found marketplace.json (needs selection)\n | 'plugin' // Found plugin.json\n | 'pattern' // Matched from pattern\n | 'ambiguous' // Multiple patterns at same depth\n | 'none'; // No match found\n \n /** For ambiguous cases, all possible matches */\n ambiguousMatches?: Array<{\n pattern: string;\n base: string;\n startIndex: number;\n }>;\n \n /** Path to marketplace manifest (for marketplace detection) */\n manifestPath?: string;\n}\n\n/**\n * Detect the base directory for a resource.\n * \n * @param resourcePath - Path to the resource (relative to repoRoot, or absolute if filepath)\n * @param repoRoot - Root directory of the repository/package\n * @param platformsConfig - Platforms configuration object for pattern matching\n * @returns Base detection result\n */\nexport async function detectBase(\n resourcePath: string,\n repoRoot: string,\n platformsConfig: any\n): Promise<BaseDetectionResult> {\n // Resolve absolute path to resource\n const absoluteResourcePath = isAbsolute(resourcePath) \n ? resourcePath \n : resolve(repoRoot, resourcePath);\n const repoRootResolved = resolve(repoRoot);\n\n // Determine whether resourcePath points to a file or directory.\n // If it's a file, manifests must be discovered by walking up from the file's directory.\n let probeStart = absoluteResourcePath;\n let statIsDir: boolean | null = null;\n let statIsFile: boolean | null = null;\n try {\n const s = await stat(absoluteResourcePath);\n statIsDir = s.isDirectory();\n statIsFile = s.isFile();\n if (!s.isDirectory()) {\n probeStart = dirname(absoluteResourcePath);\n }\n } catch {\n // If stat fails, keep probeStart as-is and fall back to patterns.\n }\n\n const isWithinRepo = (absPath: string): boolean => {\n if (absPath === repoRootResolved) return true;\n return absPath.startsWith(`${repoRootResolved}${sep}`);\n };\n\n // Track marketplace root (do not immediately return it for file-scoped resource installs)\n // so we can attempt resolving an individual plugin base first.\n let marketplaceRoot: { base: string; manifestPath: string } | null = null;\n\n // Priority 1-3: Walk up directories from probeStart to repoRoot, preferring the deepest match.\n // This allows file resources inside a marketplace repo to resolve to the specific plugin base\n // (plugin.json) before hitting the marketplace root.\n let currentDir = probeStart;\n let previousDir = '';\n while (currentDir !== previousDir && isWithinRepo(currentDir)) {\n // Priority 1: openpackage.yml\n const openpackageYmlPath = join(currentDir, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(openpackageYmlPath)) {\n logger.info('Base detected via openpackage.yml', { base: currentDir });\n return {\n base: currentDir,\n matchType: 'openpackage'\n };\n }\n\n // Priority 2: marketplace.json\n const marketplacePath = join(currentDir, CLAUDE_PLUGIN_PATHS.MARKETPLACE_MANIFEST);\n if (await exists(marketplacePath)) {\n logger.info('Base detected via marketplace.json', { base: currentDir });\n marketplaceRoot = { base: currentDir, manifestPath: marketplacePath };\n }\n\n // Priority 3: plugin.json\n const pluginPath = join(currentDir, CLAUDE_PLUGIN_PATHS.PLUGIN_MANIFEST);\n if (await exists(pluginPath)) {\n logger.info('Base detected via plugin.json', { base: currentDir });\n return {\n base: currentDir,\n matchType: 'plugin'\n };\n }\n\n previousDir = currentDir;\n currentDir = dirname(currentDir);\n }\n\n // Marketplace-aware plugin base inference:\n // If this repo is a Claude marketplace AND the user provided a file/dir resource path within it,\n // try to resolve the plugin base from marketplace.json plugin entries (e.g. \"./plugins/unit-testing\").\n if (marketplaceRoot && resourcePath && !isAbsolute(resourcePath)) {\n try {\n const raw = await readTextFile(marketplaceRoot.manifestPath);\n const parsed = JSON.parse(raw) as { plugins?: Array<{ name?: string; source?: any; strict?: boolean }> };\n const plugins = Array.isArray(parsed.plugins) ? parsed.plugins : [];\n\n const normalizeRel = (value: string): string => value.replace(/\\\\/g, '/').replace(/^\\.\\/?/, '').replace(/^\\/+/, '');\n const normalizedResource = normalizeRel(resourcePath);\n\n let bestMatch: { rel: string; pluginName?: string } | null = null;\n for (const p of plugins) {\n const source = (p as any)?.source;\n const relRaw = typeof source === 'string' ? source : undefined;\n if (!relRaw) continue;\n const rel = normalizeRel(relRaw);\n if (!rel) continue;\n if (normalizedResource === rel || normalizedResource.startsWith(`${rel}/`)) {\n if (!bestMatch || rel.length > bestMatch.rel.length) {\n bestMatch = { rel, pluginName: p?.name };\n }\n }\n }\n\n if (bestMatch) {\n const inferredBase = resolve(repoRootResolved, bestMatch.rel);\n logger.info('Base inferred from marketplace plugin entry', { base: inferredBase, plugin: bestMatch.pluginName, rel: bestMatch.rel });\n return {\n base: inferredBase,\n matchType: 'plugin'\n };\n }\n } catch (error) {\n // Ignore marketplace parsing issues; fall back to patterns/marketplace mode.\n }\n }\n\n // Priority 4: Pattern matching\n const patternResult = await detectBaseFromPatterns(resourcePath, repoRoot, platformsConfig);\n if (patternResult.matchType !== 'none') {\n return patternResult;\n }\n\n // Fallback: if we discovered a marketplace root and nothing else matched, return marketplace.\n if (marketplaceRoot) {\n return {\n base: marketplaceRoot.base,\n matchType: 'marketplace',\n manifestPath: marketplaceRoot.manifestPath\n };\n }\n\n return patternResult;\n}\n\n/**\n * Detect base using pattern matching against platforms.jsonc.\n * \n * @param resourcePath - Path to the resource (relative to repoRoot)\n * @param repoRoot - Root directory of the repository\n * @param platformsConfig - Platforms configuration object\n * @returns Base detection result\n */\nasync function detectBaseFromPatterns(\n resourcePath: string,\n repoRoot: string,\n platformsConfig: any\n): Promise<BaseDetectionResult> {\n // Extract all patterns from platforms config\n const patterns = extractAllFromPatterns(platformsConfig);\n\n // Match resource path against patterns\n const result = findDeepestMatch(resourcePath, patterns);\n\n if (!result) {\n logger.warn('No pattern matched for resource', { resourcePath });\n return {\n base: undefined,\n matchType: 'none'\n };\n }\n\n // Calculate absolute base path\n const basePath = result.match.basePath \n ? resolve(repoRoot, result.match.basePath)\n : repoRoot;\n\n if (result.isAmbiguous && result.ambiguousMatches) {\n logger.info('Ambiguous base detected', {\n resourcePath,\n matchCount: result.ambiguousMatches.length,\n patterns: result.ambiguousMatches.map(m => m.pattern)\n });\n\n return {\n base: basePath,\n matchType: 'ambiguous',\n matchedPattern: result.match.pattern,\n ambiguousMatches: result.ambiguousMatches.map(m => ({\n pattern: m.pattern,\n base: m.basePath ? resolve(repoRoot, m.basePath) : repoRoot,\n startIndex: m.startIndex\n }))\n };\n }\n\n logger.info('Base detected via pattern matching', {\n resourcePath,\n base: basePath,\n pattern: result.match.pattern,\n startIndex: result.match.startIndex\n });\n\n return {\n base: basePath,\n matchedPattern: result.match.pattern,\n matchType: 'pattern'\n };\n}\n\n/**\n * Detect base for a file path source (local filesystem).\n * Similar to detectBase but handles local paths specially.\n * \n * @param absolutePath - Absolute path to the resource\n * @param platformsConfig - Platforms configuration object\n * @returns Base detection result\n */\nexport async function detectBaseForFilepath(\n absolutePath: string,\n platformsConfig: any\n): Promise<BaseDetectionResult> {\n // For file paths, we need to find the base by traversing up the directory tree\n // and checking each parent directory for manifest files or pattern matches\n\n let currentPath = absolutePath;\n const s = await stat(absolutePath);\n \n // If it's a file, start from its directory\n if (!s.isDirectory()) {\n currentPath = dirname(absolutePath);\n }\n\n // Check current directory for manifests\n const manifestResult = await checkForManifests(currentPath);\n if (manifestResult) {\n return manifestResult;\n }\n\n // Try pattern matching\n // For file paths, we need to extract a relative path structure to match against patterns\n // We'll traverse up the tree looking for a point where the remaining path matches a pattern\n \n return await detectBaseForFilepathViaPatterns(absolutePath, platformsConfig);\n}\n\n/**\n * Check a directory for manifest files.\n */\nasync function checkForManifests(dirPath: string): Promise<BaseDetectionResult | null> {\n // Check for openpackage.yml\n const openpackageYml = join(dirPath, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(openpackageYml)) {\n return {\n base: dirPath,\n matchType: 'openpackage'\n };\n }\n\n // Check for marketplace.json\n const marketplace = join(dirPath, CLAUDE_PLUGIN_PATHS.MARKETPLACE_MANIFEST);\n if (await exists(marketplace)) {\n return {\n base: dirPath,\n matchType: 'marketplace',\n manifestPath: marketplace\n };\n }\n\n // Check for plugin.json\n const plugin = join(dirPath, CLAUDE_PLUGIN_PATHS.PLUGIN_MANIFEST);\n if (await exists(plugin)) {\n return {\n base: dirPath,\n matchType: 'plugin'\n };\n }\n\n return null;\n}\n\n/**\n * Detect base for a file path using pattern matching.\n * Traverses up the directory tree to find a matching pattern.\n */\nasync function detectBaseForFilepathViaPatterns(\n absolutePath: string,\n platformsConfig: any\n): Promise<BaseDetectionResult> {\n const patterns = extractAllFromPatterns(platformsConfig);\n \n let currentPath = absolutePath;\n const s = await stat(absolutePath);\n \n // If it's a file, start from its directory\n if (!s.isDirectory()) {\n currentPath = dirname(absolutePath);\n }\n\n // Traverse up the directory tree\n let previousPath = '';\n while (currentPath !== previousPath) {\n // Build relative path from current directory to the resource\n const relativePath = relative(currentPath, absolutePath);\n \n if (!relativePath || relativePath === '.') {\n // Reached the resource itself\n previousPath = currentPath;\n currentPath = dirname(currentPath);\n continue;\n }\n\n // Try matching this relative path against patterns\n const result = findDeepestMatch(relativePath, patterns);\n \n if (result) {\n // Found a match!\n const basePath = result.match.basePath\n ? resolve(currentPath, result.match.basePath)\n : currentPath;\n\n if (result.isAmbiguous && result.ambiguousMatches) {\n return {\n base: basePath,\n matchType: 'ambiguous',\n matchedPattern: result.match.pattern,\n ambiguousMatches: result.ambiguousMatches.map(m => ({\n pattern: m.pattern,\n base: m.basePath ? resolve(currentPath, m.basePath) : currentPath,\n startIndex: m.startIndex\n }))\n };\n }\n\n return {\n base: basePath,\n matchedPattern: result.match.pattern,\n matchType: 'pattern'\n };\n }\n\n // Move up one directory\n previousPath = currentPath;\n currentPath = dirname(currentPath);\n }\n\n // No match found\n return {\n base: undefined,\n matchType: 'none'\n };\n}\n", "/**\n * Pattern matching utilities for base detection.\n * \n * Extracts patterns from platforms.jsonc and matches resource paths\n * against them using segment-indexed matching with deepest match resolution.\n */\n\nimport { minimatch } from 'minimatch';\nimport { logger } from './logger.js';\n\n/**\n * A pattern match result\n */\nexport interface PatternMatch {\n /** The pattern that matched */\n pattern: string;\n \n /** Segment index where the match begins (0-based) */\n startIndex: number;\n \n /** The matched portion of the path */\n matchedPath: string;\n \n /** The base portion (everything before the match) */\n basePath: string;\n}\n\n/**\n * Extract all \"from\" patterns from a platforms configuration object.\n * \n * @param platformsConfig - The platforms.jsonc configuration object\n * @returns Array of unique patterns\n */\nexport function extractAllFromPatterns(platformsConfig: any): string[] {\n const patterns = new Set<string>();\n\n // Global flows\n if (platformsConfig.global?.export) {\n for (const flow of platformsConfig.global.export) {\n addFlowPatterns(flow.from, patterns);\n }\n }\n\n // Platform-specific flows\n for (const [key, value] of Object.entries(platformsConfig)) {\n if (key === 'global' || key === '$schema') continue;\n \n const platformDef = value as any;\n if (platformDef.export) {\n for (const flow of platformDef.export) {\n addFlowPatterns(flow.from, patterns);\n }\n }\n }\n\n return Array.from(patterns);\n}\n\n/**\n * Add patterns from a flow's \"from\" field.\n * Handles string, array, and $switch expressions.\n */\nfunction addFlowPatterns(from: any, patterns: Set<string>): void {\n if (typeof from === 'string') {\n patterns.add(from);\n } else if (typeof from === 'object' && from !== null && 'pattern' in from && typeof from.pattern === 'string') {\n // Pattern object (e.g. { pattern: \"agents/**/*.md\", schema?: \"...\" })\n patterns.add(from.pattern);\n } else if (Array.isArray(from)) {\n for (const p of from) {\n if (typeof p === 'string') {\n patterns.add(p);\n } else if (typeof p === 'object' && p !== null && 'pattern' in p && typeof (p as any).pattern === 'string') {\n patterns.add((p as any).pattern);\n }\n }\n } else if (typeof from === 'object' && from.$switch) {\n // Handle $switch expressions - extract patterns from cases\n if (from.$switch.cases) {\n for (const c of from.$switch.cases) {\n if (typeof c.value === 'string') {\n patterns.add(c.value);\n } else if (Array.isArray(c.value)) {\n for (const v of c.value) {\n if (typeof v === 'string') {\n patterns.add(v);\n } else if (typeof v === 'object' && v !== null && 'pattern' in v && typeof (v as any).pattern === 'string') {\n patterns.add((v as any).pattern);\n }\n }\n } else if (typeof c.value === 'object' && c.value !== null && 'pattern' in c.value && typeof (c.value as any).pattern === 'string') {\n patterns.add((c.value as any).pattern);\n }\n }\n }\n if (from.$switch.default) {\n if (typeof from.$switch.default === 'string') {\n patterns.add(from.$switch.default);\n } else if (typeof from.$switch.default === 'object' && from.$switch.default !== null && 'pattern' in from.$switch.default && typeof (from.$switch.default as any).pattern === 'string') {\n patterns.add((from.$switch.default as any).pattern);\n }\n }\n }\n}\n\n/**\n * Match a resource path against an array of patterns.\n * Returns all matches with their segment indices.\n * \n * @param resourcePath - The path to match (e.g., \"plugins/ui/agents/designer.md\")\n * @param patterns - Array of glob patterns to match against\n * @returns Array of pattern matches\n */\nexport function matchPatterns(resourcePath: string, patterns: string[]): PatternMatch[] {\n const matches: PatternMatch[] = [];\n \n // Normalize path: remove leading/trailing slashes, split into segments\n const normalizedPath = resourcePath.replace(/^\\/+|\\/+$/g, '');\n const segments = normalizedPath.split('/').filter(s => s.length > 0);\n \n if (segments.length === 0) {\n return matches;\n }\n\n // Try matching each pattern\n for (const pattern of patterns) {\n // Normalize pattern\n const normalizedPattern = pattern.replace(/^\\/+|\\/+$/g, '');\n const patternSegments = normalizedPattern.split('/').filter(s => s.length > 0);\n \n if (patternSegments.length === 0) continue;\n\n // Try matching the pattern starting at each segment index\n for (let startIndex = 0; startIndex < segments.length; startIndex++) {\n const candidatePath = segments.slice(startIndex).join('/');\n \n // Use minimatch to test if the candidate path matches the pattern\n if (minimatch(candidatePath, normalizedPattern, { dot: true })) {\n const basePath = startIndex > 0 ? segments.slice(0, startIndex).join('/') : '';\n \n matches.push({\n pattern: normalizedPattern,\n startIndex,\n matchedPath: candidatePath,\n basePath\n });\n \n // Only record the first (earliest) match for this pattern\n break;\n }\n }\n }\n\n logger.debug('Pattern matching results', {\n resourcePath: normalizedPath,\n matchCount: matches.length,\n matches: matches.map(m => ({\n pattern: m.pattern,\n startIndex: m.startIndex,\n basePath: m.basePath\n }))\n });\n\n return matches;\n}\n\n/**\n * Select the deepest match from an array of pattern matches.\n * \n * The deepest match is the one with the highest startIndex\n * (i.e., the pattern that matches furthest from the root).\n * \n * If multiple patterns match at the same depth, returns all of them\n * as ambiguous matches.\n * \n * @param matches - Array of pattern matches\n * @returns Object with deepest match(es) and whether it's ambiguous\n */\nexport function selectDeepestMatch(matches: PatternMatch[]): {\n match: PatternMatch;\n isAmbiguous: boolean;\n ambiguousMatches?: PatternMatch[];\n} {\n if (matches.length === 0) {\n throw new Error('Cannot select deepest match from empty array');\n }\n\n if (matches.length === 1) {\n return {\n match: matches[0],\n isAmbiguous: false\n };\n }\n\n // Find the maximum start index\n const maxStartIndex = Math.max(...matches.map(m => m.startIndex));\n \n // Get all matches at that depth\n const deepestMatches = matches.filter(m => m.startIndex === maxStartIndex);\n \n if (deepestMatches.length === 1) {\n return {\n match: deepestMatches[0],\n isAmbiguous: false\n };\n }\n\n // Multiple matches at the same depth - ambiguous\n return {\n match: deepestMatches[0], // Return first as default\n isAmbiguous: true,\n ambiguousMatches: deepestMatches\n };\n}\n\n/**\n * Match a resource path and return the deepest match.\n * This is a convenience function that combines matchPatterns and selectDeepestMatch.\n * \n * @param resourcePath - The path to match\n * @param patterns - Array of glob patterns\n * @returns Deepest match result, or null if no matches\n */\nexport function findDeepestMatch(\n resourcePath: string,\n patterns: string[]\n): {\n match: PatternMatch;\n isAmbiguous: boolean;\n ambiguousMatches?: PatternMatch[];\n} | null {\n const matches = matchPatterns(resourcePath, patterns);\n \n if (matches.length === 0) {\n return null;\n }\n\n return selectDeepestMatch(matches);\n}\n", "/**\n * Phase 6: Enhanced error messages for resource installation.\n * \n * Provides helpful, actionable error messages with suggestions\n * for common failure scenarios.\n */\n\nimport { extractAllFromPatterns } from './pattern-matcher.js';\n\n/**\n * Format an error message for when no pattern matches a resource path.\n * Provides helpful suggestions based on the path structure.\n * \n * @param resourcePath - The path that didn't match\n * @param platformsConfig - Platforms configuration for pattern extraction\n * @returns Formatted error message with suggestions\n */\nexport function formatNoPatternMatchError(\n resourcePath: string,\n platformsConfig: any\n): string {\n // Extract patterns from platforms config\n const patterns = extractAllFromPatterns(platformsConfig);\n const uniquePatterns = Array.from(new Set(patterns));\n \n // Analyze the path to provide specific suggestions\n const pathSegments = resourcePath.split('/').filter(s => s.length > 0);\n const suggestions: string[] = [];\n \n // Check if path contains common directory names\n if (pathSegments.some(s => s === 'agents' || s.includes('agent'))) {\n suggestions.push('\u2022 Did you mean to install an agent? Ensure your path follows the agents/**/*.md pattern');\n }\n \n if (pathSegments.some(s => s === 'skills' || s.includes('skill'))) {\n suggestions.push('\u2022 Did you mean to install a skill? Ensure your path follows the skills/**/* pattern');\n }\n \n if (pathSegments.some(s => s === 'rules' || s.includes('rule'))) {\n suggestions.push('\u2022 Did you mean to install a rule? Ensure your path follows the rules/**/*.md pattern');\n }\n \n if (pathSegments.some(s => s === 'commands' || s.includes('command'))) {\n suggestions.push('\u2022 Did you mean to install a command? Ensure your path follows the commands/**/*.md pattern');\n }\n \n // Build the error message\n let message = `Path '${resourcePath}' does not match any installable pattern.\\n\\n`;\n message += `Installable patterns include:\\n`;\n \n // Show most common patterns first\n const commonPatterns = [\n 'agents/**/*.md',\n 'skills/**/*',\n 'rules/**/*.md',\n 'commands/**/*.md'\n ];\n \n for (const pattern of commonPatterns) {\n if (uniquePatterns.includes(pattern)) {\n message += ` \u2022 ${pattern}\\n`;\n }\n }\n \n // Show other patterns if they exist\n const otherPatterns = uniquePatterns.filter(p => !commonPatterns.includes(p));\n if (otherPatterns.length > 0 && otherPatterns.length <= 5) {\n for (const pattern of otherPatterns) {\n message += ` \u2022 ${pattern}\\n`;\n }\n } else if (otherPatterns.length > 5) {\n message += ` \u2022 ... and ${otherPatterns.length} more patterns\\n`;\n }\n \n if (suggestions.length > 0) {\n message += `\\n\uD83D\uDCA1 Suggestions:\\n`;\n message += suggestions.join('\\n');\n }\n \n return message;\n}\n\n/**\n * Format an error message for when a resource is not found.\n * \n * @param resourceName - Name of the resource\n * @param resourceType - Type of resource (agent, skill, etc.)\n * @param availableResources - List of available resources (if any)\n * @returns Formatted error message\n */\nexport function formatResourceNotFoundError(\n resourceName: string,\n resourceType: 'agent' | 'skill' | 'plugin',\n availableResources?: string[]\n): string {\n let message = `${resourceType.charAt(0).toUpperCase() + resourceType.slice(1)} '${resourceName}' not found.\\n`;\n \n if (availableResources && availableResources.length > 0) {\n message += `\\nAvailable ${resourceType}s:\\n`;\n const sortedResources = [...availableResources].sort();\n for (const resource of sortedResources.slice(0, 10)) {\n message += ` \u2022 ${resource}\\n`;\n }\n if (sortedResources.length > 10) {\n message += ` \u2022 ... and ${sortedResources.length - 10} more\\n`;\n }\n \n // Try to find similar names\n const similar = findSimilarNames(resourceName, availableResources);\n if (similar.length > 0) {\n message += `\\n\uD83D\uDCA1 Did you mean:\\n`;\n for (const name of similar.slice(0, 3)) {\n message += ` \u2022 ${name}\\n`;\n }\n }\n }\n \n return message;\n}\n\n/**\n * Find names similar to the target name using simple string distance.\n * \n * @param target - The target name to match\n * @param candidates - List of candidate names\n * @returns Array of similar names (up to 3)\n */\nfunction findSimilarNames(target: string, candidates: string[]): string[] {\n const targetLower = target.toLowerCase();\n \n // Score each candidate\n const scored = candidates.map(candidate => ({\n name: candidate,\n score: calculateSimilarity(targetLower, candidate.toLowerCase())\n }));\n \n // Sort by score (higher is better)\n scored.sort((a, b) => b.score - a.score);\n \n // Return top matches with score > 0.5\n return scored\n .filter(s => s.score > 0.5)\n .slice(0, 3)\n .map(s => s.name);\n}\n\n/**\n * Calculate similarity between two strings.\n * Uses a simple character-based similarity metric.\n * \n * @param a - First string\n * @param b - Second string\n * @returns Similarity score (0-1, higher is more similar)\n */\nfunction calculateSimilarity(a: string, b: string): number {\n if (a === b) return 1.0;\n if (a.length === 0 || b.length === 0) return 0.0;\n \n // Check for substring match\n if (a.includes(b) || b.includes(a)) {\n return 0.8;\n }\n \n // Simple character overlap metric\n const aChars = new Set(a.split(''));\n const bChars = new Set(b.split(''));\n const overlap = [...aChars].filter(c => bChars.has(c)).length;\n const total = Math.max(aChars.size, bChars.size);\n \n return overlap / total;\n}\n\n/**\n * Format an error message for version specification on sub-paths.\n * \n * @param input - The invalid input string\n * @returns Formatted error message with correct syntax\n */\nexport function formatVersionOnSubPathError(input: string): string {\n // Try to extract the parts to provide a corrected example\n const parts = input.split('@');\n let suggestion = '';\n \n if (parts.length >= 2) {\n // Assume format like: gh@owner/repo/path@version\n const beforeVersion = parts.slice(0, -1).join('@');\n const version = parts[parts.length - 1];\n const versionPart = version.split('/')[0];\n \n // Try to reconstruct: gh@owner/repo@version/path\n const segments = beforeVersion.split('/');\n if (segments.length >= 3) {\n suggestion = `\\n\\nDid you mean: ${segments.slice(0, 3).join('/')}@${versionPart}/${segments.slice(3).join('/')}`;\n }\n }\n \n let message = `Version cannot be specified on sub-paths.\\n\\n`;\n message += `Got: ${input}\\n`;\n message += `Valid format: <package>[@version][/path]\\n`;\n message += `Examples:\\n`;\n message += ` \u2022 gh@owner/repo@v1.0.0/agents/designer.md\\n`;\n message += ` \u2022 my-package@1.0.0/skills/git\\n`;\n message += ` \u2022 @scope/package@2.0.0/agents/architect\\n`;\n \n if (suggestion) {\n message += suggestion;\n }\n \n return message;\n}\n\n\n", "import type { PackageSourceLoader, LoadedPackage } from './base.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport { SourceLoadError } from './base.js';\nimport { loadPackageFromGit } from '../git-package-loader.js';\nimport { loadPackageFromPath } from '../path-package-loader.js';\nimport { detectPluginType } from '../plugin-detector.js';\nimport { detectBase } from '../base-detector.js';\nimport { getPlatformsState } from '../../../core/platforms.js';\nimport { logger } from '../../../utils/logger.js';\nimport { resolve, relative } from 'path';\n\n/**\n * Loads packages from git repositories\n */\nexport class GitSourceLoader implements PackageSourceLoader {\n canHandle(source: PackageSource): boolean {\n return source.type === 'git';\n }\n \n async load(\n source: PackageSource,\n options: InstallOptions,\n execContext: ExecutionContext\n ): Promise<LoadedPackage> {\n if (!source.gitUrl) {\n throw new SourceLoadError(source, 'Git URL is required for git sources');\n }\n \n try {\n // Load package from git\n // Use skipCache when resolutionMode is 'remote-primary' (--remote flag)\n const skipCache = options.resolutionMode === 'remote-primary';\n const result = await loadPackageFromGit({\n url: source.gitUrl,\n ref: source.gitRef,\n path: source.gitPath,\n resourcePath: source.resourcePath,\n skipCache\n });\n \n // Phase 5: If manifest base is present, skip detection (reproducibility)\n let detectedBaseInfo: any = null;\n if (source.manifestBase) {\n // Use base from manifest instead of detecting\n const absoluteBase = resolve(result.repoPath, source.manifestBase);\n detectedBaseInfo = {\n matchType: 'manifest',\n base: absoluteBase,\n baseRelative: source.manifestBase,\n matchedPattern: null\n };\n \n source.detectedBase = absoluteBase;\n \n logger.info('Using base from manifest for git source', {\n base: source.manifestBase,\n absoluteBase\n });\n } else if (source.resourcePath || source.gitPath) {\n // NEW: If a resource path was specified, detect base\n const platformsState = getPlatformsState(execContext.targetDir);\n const platformsConfig = platformsState.config;\n const pathToDetect = source.resourcePath || source.gitPath || '';\n \n detectedBaseInfo = await detectBase(\n pathToDetect,\n result.repoPath,\n platformsConfig\n );\n \n logger.info('Base detection result for git source', {\n matchType: detectedBaseInfo.matchType,\n base: detectedBaseInfo.base,\n matchedPattern: detectedBaseInfo.matchedPattern\n });\n \n // Store detected base in source\n if (detectedBaseInfo.base) {\n source.detectedBase = detectedBaseInfo.base;\n }\n }\n \n // When resourcePath is set, treat as concrete resource install (no marketplace selection).\n // Otherwise, if repo is a marketplace, return placeholder for selection flow.\n if (\n !source.resourcePath &&\n (result.isMarketplace || detectedBaseInfo?.matchType === 'marketplace')\n ) {\n const pluginDetection = await detectPluginType(result.sourcePath);\n \n return {\n metadata: null as any, // Marketplace doesn't have single package\n packageName: '', // Unknown until plugin selection\n version: '0.0.0',\n contentRoot: result.sourcePath,\n source: 'git',\n pluginMetadata: {\n isPlugin: true,\n pluginType: 'marketplace',\n manifestPath: pluginDetection.manifestPath || detectedBaseInfo?.manifestPath\n },\n sourceMetadata: {\n repoPath: result.repoPath,\n commitSha: result.commitSha,\n baseDetection: detectedBaseInfo\n }\n };\n }\n \n // Use detected base as content root if available\n const contentRoot = detectedBaseInfo?.base || result.sourcePath;\n \n // Load individual package/plugin\n let sourcePackage = await loadPackageFromPath(contentRoot, {\n gitUrl: source.gitUrl,\n path: source.gitPath,\n resourcePath: source.resourcePath,\n repoPath: result.repoPath,\n marketplaceEntry: source.pluginMetadata?.marketplaceEntry\n });\n \n // Detect plugin type at content root\n const pluginDetection = await detectPluginType(contentRoot);\n \n const packageName = sourcePackage.metadata.name;\n const version = sourcePackage.metadata.version || '0.0.0';\n \n // Note: Plugin transformation is handled by the main flow, not here\n return {\n metadata: sourcePackage.metadata,\n packageName,\n version,\n contentRoot,\n source: 'git',\n pluginMetadata: pluginDetection.isPlugin ? {\n isPlugin: true,\n pluginType: pluginDetection.type as any, // Can be 'individual', 'marketplace', or 'marketplace-defined'\n manifestPath: pluginDetection.manifestPath\n } : undefined,\n sourceMetadata: {\n repoPath: result.repoPath,\n commitSha: result.commitSha,\n baseDetection: detectedBaseInfo\n }\n };\n } catch (error) {\n if (error instanceof SourceLoadError) {\n throw error;\n }\n const err = error as Error;\n const ref = source.gitRef ? `#${source.gitRef}` : '';\n const subdir = source.gitPath ? ` (path: ${source.gitPath})` : '';\n const causeMsg = err?.message ? ` - ${err.message}` : '';\n throw new SourceLoadError(\n source,\n `Failed to load package from git: ${source.gitUrl}${ref}${subdir}${causeMsg}`,\n err\n );\n }\n }\n \n}\n", "import { join } from 'path';\nimport type { PackageSourceLoader, LoadedPackage } from './base.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport { SourceLoadError } from './base.js';\nimport { readWorkspaceIndex } from '../../../utils/workspace-index-yml.js';\nimport { resolveDeclaredPath } from '../../../utils/path-resolution.js';\nimport { loadPackageFromPath } from '../path-package-loader.js';\n\n/**\n * Loads packages from workspace index (for apply command)\n */\nexport class WorkspaceSourceLoader implements PackageSourceLoader {\n canHandle(source: PackageSource): boolean {\n return source.type === 'workspace';\n }\n \n async load(\n source: PackageSource,\n options: InstallOptions,\n execContext: ExecutionContext\n ): Promise<LoadedPackage> {\n if (!source.packageName) {\n throw new SourceLoadError(source, 'Package name is required for workspace sources');\n }\n \n try {\n // Check if contentRoot is already set (workspace root install case)\n if (source.contentRoot) {\n const pkg = await loadPackageFromPath(source.contentRoot, {\n packageName: source.packageName\n });\n const metadata = pkg.metadata;\n const version = source.version || metadata.version || '0.0.0';\n \n return {\n metadata,\n packageName: source.packageName,\n version,\n contentRoot: join(source.contentRoot, '/'),\n source: 'workspace',\n pluginMetadata: (pkg as any)._format ? {\n isPlugin: true,\n pluginType: 'individual',\n format: (pkg as any)._format\n } : undefined\n };\n }\n \n // Standard workspace source loading (from index)\n // Read workspace index (use targetDir for workspace location)\n const { index } = await readWorkspaceIndex(execContext.targetDir);\n const entry = index.packages?.[source.packageName];\n \n if (!entry?.path) {\n throw new SourceLoadError(\n source,\n `Package '${source.packageName}' is not installed in this workspace. ` +\n `Run 'opkg install ${source.packageName}' to install it first.`\n );\n }\n \n // Resolve package path (relative to targetDir)\n const resolved = resolveDeclaredPath(entry.path, execContext.targetDir);\n const contentRoot = join(resolved.absolute, '/');\n \n // Load package metadata (handles regular packages and plugins)\n const pkg = await loadPackageFromPath(contentRoot, {\n packageName: source.packageName,\n gitUrl: source.gitUrl,\n path: source.gitPath\n });\n const metadata = pkg.metadata;\n \n const version = entry.version || metadata.version || '0.0.0';\n \n return {\n metadata,\n packageName: source.packageName,\n version,\n contentRoot,\n source: 'workspace',\n pluginMetadata: (pkg as any)._format ? {\n isPlugin: true,\n pluginType: 'individual',\n format: (pkg as any)._format\n } : undefined\n };\n } catch (error) {\n if (error instanceof SourceLoadError) {\n throw error;\n }\n \n throw new SourceLoadError(\n source,\n `Failed to load package '${source.packageName}' from workspace`,\n error as Error\n );\n }\n }\n \n}\n", "import type { PackageSourceLoader } from './base.js';\nimport type { PackageSource } from '../unified/context.js';\nimport { RegistrySourceLoader } from './registry-source.js';\nimport { PathSourceLoader } from './path-source.js';\nimport { GitSourceLoader } from './git-source.js';\nimport { WorkspaceSourceLoader } from './workspace-source.js';\n\n/**\n * Registry of all available source loaders\n */\nconst loaders: PackageSourceLoader[] = [\n new RegistrySourceLoader(),\n new PathSourceLoader(),\n new GitSourceLoader(),\n new WorkspaceSourceLoader()\n];\n\n/**\n * Get appropriate loader for a source\n */\nexport function getLoaderForSource(source: PackageSource): PackageSourceLoader {\n const loader = loaders.find(l => l.canHandle(source));\n \n if (!loader) {\n throw new Error(`No loader available for source type: ${source.type}`);\n }\n \n return loader;\n}\n", "import type { InstallationContext } from './context.js';\nimport { resolveOutput } from '../../ports/resolve.js';\n\n/**\n * Check if context should resolve dependencies\n */\nexport function shouldResolveDependencies(ctx: InstallationContext): boolean {\n // Skip dependency resolution for apply mode\n if (ctx.mode === 'apply') {\n return false;\n }\n // Git/path installs are already fully specified by their source content.\n // The registry dependency resolver expects the root package to exist in a registry;\n // for git/path sources this can incorrectly mark the root as \"missing\" and trigger\n // remote pulls (e.g. Claude marketplace plugins).\n if (ctx.source.type === 'git' || ctx.source.type === 'path') {\n return false;\n }\n // Workspace sources with contentRoot already set (workspace root install) are also\n // fully specified and should not be resolved through the registry. These install\n // workspace-level files from .openpackage/ and the package name in the manifest\n // is just metadata, not a reference to a registry package.\n if (ctx.source.type === 'workspace' && ctx.source.contentRoot) {\n return false;\n }\n return true;\n}\n\n/**\n * Check if context should update manifest\n */\nexport function shouldUpdateManifest(ctx: InstallationContext): boolean {\n return (\n ctx.mode !== 'apply' &&\n ctx.source.type !== 'workspace' &&\n ctx.options.skipManifestUpdate !== true\n );\n}\n\n/**\n * Add warning to context\n */\nexport function addWarning(ctx: InstallationContext, message: string): void {\n if (!ctx.warnings.includes(message)) {\n ctx.warnings.push(message);\n const out = resolveOutput(ctx.execution);\n out.warn(message);\n }\n}\n\n/**\n * Add error to context\n */\nexport function addError(ctx: InstallationContext, message: string): void {\n if (!ctx.errors.includes(message)) {\n ctx.errors.push(message);\n }\n}\n\n/**\n * Get display name for source\n */\nexport function getSourceDisplayName(ctx: InstallationContext): string {\n const { source } = ctx;\n \n switch (source.type) {\n case 'registry':\n return source.version\n ? `${source.packageName}@${source.version}`\n : source.packageName;\n \n case 'path':\n // For marketplace plugins loaded from cache, show the plugin name\n // instead of exposing the internal cache path\n if (source.pluginMetadata?.marketplaceSource || source.pluginMetadata?.marketplaceEntry) {\n const entryName = source.pluginMetadata.marketplaceEntry?.name;\n return source.packageName || entryName || 'plugin';\n }\n return `${source.packageName} (from ${source.localPath})`;\n \n case 'git':\n const ref = source.gitRef ? `#${source.gitRef}` : '';\n const subdir = source.gitPath ? `&path=${source.gitPath}` : '';\n return `${source.packageName} (git:${source.gitUrl}${ref}${subdir})`;\n \n case 'workspace':\n return `${source.packageName} (workspace)`;\n \n default:\n return source.packageName;\n }\n}\n", "/**\n * Load Package Phase\n * Loads package from source using appropriate loader\n */\n\nimport type { InstallationContext } from '../context.js';\nimport { getLoaderForSource } from '../../sources/loader-factory.js';\nimport { addError, getSourceDisplayName } from '../context-helpers.js';\nimport { logger } from '../../../../utils/logger.js';\nimport type { OutputPort } from '../../../ports/output.js';\nimport { resolveOutput } from '../../../ports/resolve.js';\nimport { applyBaseDetection, computePathScoping } from '../../preprocessing/base-resolver.js';\n\n/**\n * Load package from source\n */\nexport async function loadPackagePhase(ctx: InstallationContext, output?: OutputPort): Promise<void> {\n // Skip if context already has loaded data (preprocessed by strategy)\n // NOTE: We require resolvedPackages to be populated too; otherwise later phases break.\n if (ctx.source.contentRoot && ctx.source.packageName && ctx.resolvedPackages.length > 0) {\n return;\n }\n \n const out = output ?? resolveOutput(ctx.execution);\n const spinner = out.spinner();\n \n try {\n // Get appropriate loader\n const loader = getLoaderForSource(ctx.source);\n \n // Display loading message with spinner\n const displayName = getSourceDisplayName(ctx);\n const spinnerMsg = `Loading ${displayName}`;\n spinner.start(spinnerMsg);\n \n // Load package\n const loaded = await loader.load(ctx.source, ctx.options, ctx.execution);\n \n // Stop spinner with the resolved package identity\n const version = loaded.version ? `@${loaded.version}` : '';\n spinner.stop(`Installed ${loaded.packageName}${version}`);\n\n // Update context\n ctx.source.packageName = loaded.packageName;\n ctx.source.version = loaded.version;\n \n // Apply version fallback chain for resource installations (agents/skills)\n // Priority: resourceVersion (from frontmatter) > metadata.version > parent version > undefined\n if (ctx.source.resourceVersion !== undefined) {\n // Resource has explicit version from frontmatter, use it as final version\n ctx.source.version = ctx.source.resourceVersion;\n } else if (loaded.metadata?.version && loaded.metadata.version !== loaded.version) {\n // Metadata has different version than loader provided (e.g., openpackage.yml in resource dir)\n ctx.source.version = loaded.metadata.version;\n }\n // Otherwise, keep loaded.version (parent package/plugin version)\n \n // Apply base detection results from loader (resource model).\n // Bulk installs previously missed this, causing unscoped installs and incorrect workspace-index paths.\n applyBaseDetection(ctx, loaded);\n\n // Ensure contentRoot is always set after load phase\n // This is required by the pipeline validation and may not be set if base detection was skipped\n if (!ctx.source.contentRoot) {\n ctx.source.contentRoot = loaded.contentRoot;\n }\n\n // If this install targets a concrete resource (file or dir), scope matchedPattern to that resource.\n // This matches the behavior of individual resource installs.\n const resourcePath = (ctx.source as any).resourcePath as string | undefined;\n if (resourcePath) {\n await computePathScoping(ctx, loaded, resourcePath);\n }\n \n ctx.source.pluginMetadata = loaded.pluginMetadata;\n \n // Store commit SHA for git sources (needed for workspace index marketplace metadata)\n if (loaded.sourceMetadata?.commitSha) {\n if (!ctx.source.pluginMetadata) {\n ctx.source.pluginMetadata = { isPlugin: false };\n }\n if (!ctx.source.pluginMetadata.marketplaceSource && loaded.sourceMetadata.commitSha) {\n // Store commit SHA for potential marketplace source tracking\n (ctx.source as any)._commitSha = loaded.sourceMetadata.commitSha;\n }\n }\n \n // Map source type to ResolvedPackage source format\n let resolvedSource: 'local' | 'remote' | 'path' | 'git' | undefined;\n switch (ctx.source.type) {\n case 'registry':\n resolvedSource = 'local'; // Registry packages are local\n break;\n case 'path':\n resolvedSource = 'path';\n break;\n case 'git':\n resolvedSource = 'git';\n break;\n case 'workspace':\n resolvedSource = 'local'; // Workspace packages are local\n break;\n }\n \n // Create root resolved package (simplified - full dependency resolution in next phase)\n // Use the effective version from context (which has fallback chain applied)\n const effectiveVersion = ctx.source.version || loaded.version;\n \n const rootPackage: any = {\n name: loaded.packageName,\n version: effectiveVersion,\n pkg: { \n metadata: loaded.metadata, \n files: [], \n _format: (loaded.metadata as any)?._format || ctx.source.pluginMetadata?.format \n },\n isRoot: true,\n source: resolvedSource,\n contentRoot: ctx.source.contentRoot || loaded.contentRoot // Use detected base as content root\n };\n \n // Add marketplace metadata if present\n if (ctx.source.pluginMetadata?.marketplaceSource) {\n rootPackage.marketplaceMetadata = ctx.source.pluginMetadata.marketplaceSource;\n }\n \n // Add resource version if present (for agents/skills with individual versions)\n if (ctx.source.resourceVersion !== undefined) {\n rootPackage.resourceVersion = ctx.source.resourceVersion;\n }\n \n ctx.resolvedPackages = [rootPackage];\n \n logger.info(`Loaded ${loaded.packageName}@${effectiveVersion} from ${loaded.source}`);\n \n } catch (error) {\n spinner.stop();\n const errorMsg = `Failed to load package: ${error}`;\n addError(ctx, errorMsg);\n throw new Error(errorMsg);\n }\n}\n", "/**\n * Import Flow Converter Module\n * \n * Converts files using import flows from platforms.jsonc.\n * Applies platform-specific \u2192 universal format transformations.\n * \n * Phase 3: Per-File Import Flow Application\n */\n\nimport { minimatch } from 'minimatch';\nimport { logger } from '../../utils/logger.js';\nimport { getPlatformDefinition } from '../platforms.js';\nimport { getPatternFromFlow, schemaRegistry } from './schema-registry.js';\nimport { applyMapPipeline, createMapContext } from '../flows/map-pipeline/index.js';\nimport { defaultTransformRegistry } from '../flows/flow-transforms.js';\nimport { splitFrontmatter, dumpYaml } from '../markdown-frontmatter.js';\nimport { basename, dirname, extname } from 'path';\nimport { stripPlatformSuffixFromFilename } from '../flows/platform-suffix-handler.js';\nimport { scoreAgainstSchema } from './file-format-detector.js';\nimport type { Flow } from '../../types/flows.js';\nimport type { \n PackageFile,\n PlatformId,\n FileFormat,\n FormatGroup\n} from './detection-types.js';\n\n/**\n * Conversion result for a single file\n */\nexport interface FileConversionResult {\n /** Original file */\n original: PackageFile;\n \n /** Converted file (in universal format) */\n converted?: PackageFile;\n \n /** Whether conversion succeeded */\n success: boolean;\n \n /** Error if conversion failed */\n error?: Error;\n \n /** Flow that was applied */\n appliedFlow?: Flow;\n \n /** Whether file needed transformation */\n transformed: boolean;\n}\n\n/**\n * Conversion result for a format group\n */\nexport interface FormatGroupConversionResult {\n /** Platform ID of this group */\n platformId: PlatformId;\n \n /** Converted files (in universal format) */\n convertedFiles: PackageFile[];\n \n /** Per-file conversion results */\n fileResults: FileConversionResult[];\n \n /** Overall success (all files converted) */\n success: boolean;\n \n /** Number of files processed */\n filesProcessed: number;\n \n /** Number of files successfully converted */\n filesConverted: number;\n \n /** Number of files that failed */\n filesFailed: number;\n}\n\n/**\n * Convert a format group using import flows\n * \n * Loads import flows for the platform and applies them to each file in the group.\n * Returns converted files in universal format.\n * \n * @param group - Format group to convert\n * @param targetDir - Optional target directory for local platform config\n * @returns Conversion result with converted files\n */\nexport function convertFormatGroup(\n group: FormatGroup,\n targetDir?: string\n): FormatGroupConversionResult {\n // Skip conversion for universal format (already in target format)\n if (group.platformId === 'universal') {\n return {\n platformId: group.platformId,\n convertedFiles: group.files,\n fileResults: group.files.map(file => ({\n original: file,\n converted: file,\n success: true,\n transformed: false\n })),\n success: true,\n filesProcessed: group.files.length,\n filesConverted: group.files.length,\n filesFailed: 0\n };\n }\n \n // Skip conversion for unknown format (no flows available)\n if (group.platformId === 'unknown') {\n logger.warn('Group has unknown format, cannot convert');\n return {\n platformId: group.platformId,\n convertedFiles: [],\n fileResults: group.files.map(file => ({\n original: file,\n success: false,\n error: new Error('Unknown format - no conversion flows available'),\n transformed: false\n })),\n success: false,\n filesProcessed: group.files.length,\n filesConverted: 0,\n filesFailed: group.files.length\n };\n }\n \n // Load import flows for platform\n const platform = getPlatformDefinition(group.platformId, targetDir);\n if (!platform) {\n logger.error(`Platform definition not found: ${group.platformId}`);\n return {\n platformId: group.platformId,\n convertedFiles: [],\n fileResults: group.files.map(file => ({\n original: file,\n success: false,\n error: new Error(`Platform definition not found: ${group.platformId}`),\n transformed: false\n })),\n success: false,\n filesProcessed: group.files.length,\n filesConverted: 0,\n filesFailed: group.files.length\n };\n }\n \n const importFlows = platform.import || [];\n if (importFlows.length === 0) {\n logger.warn(`No import flows defined for platform: ${group.platformId}`);\n // Return files unchanged if no flows (treat as already universal)\n return {\n platformId: group.platformId,\n convertedFiles: group.files,\n fileResults: group.files.map(file => ({\n original: file,\n converted: file,\n success: true,\n transformed: false\n })),\n success: true,\n filesProcessed: group.files.length,\n filesConverted: group.files.length,\n filesFailed: 0\n };\n }\n \n // Apply import flows to each file\n const fileResults: FileConversionResult[] = [];\n const convertedFiles: PackageFile[] = [];\n \n for (const file of group.files) {\n const result = convertSingleFile(file, importFlows, group.platformId);\n fileResults.push(result);\n \n if (result.success && result.converted) {\n convertedFiles.push(result.converted);\n }\n }\n \n const filesConverted = fileResults.filter(r => r.success).length;\n const filesFailed = fileResults.filter(r => !r.success).length;\n \n return {\n platformId: group.platformId,\n convertedFiles,\n fileResults,\n success: filesFailed === 0,\n filesProcessed: group.files.length,\n filesConverted,\n filesFailed\n };\n}\n\n/**\n * Convert a single file using import flows\n * \n * Matches file against flows, applies transformations, converts to universal format.\n * \n * @param file - File to convert\n * @param flows - Import flows to apply\n * @param platformId - Source platform ID\n * @returns Conversion result\n */\nexport function convertSingleFile(\n file: PackageFile,\n flows: Flow[],\n platformId: PlatformId\n): FileConversionResult {\n // Find matching flow for this file\n const matchedFlow = findMatchingFlow(file.path, flows);\n \n if (!matchedFlow) {\n // Fallback: schema-based flow match\n // This handles cases where platform-formatted content exists at a universal path\n // (e.g. Claude-formatted agent in `agents/` rather than `.claude/agents/`).\n const schemaFlow = findBestSchemaMatchingFlow(file, flows, platformId);\n if (schemaFlow) {\n try {\n const converted = applyFlowToFile(file, schemaFlow, platformId);\n return {\n original: file,\n converted,\n success: true,\n appliedFlow: schemaFlow,\n transformed: true\n };\n } catch (error) {\n logger.error(`Failed to convert file (schema fallback): ${file.path}`, error);\n return {\n original: file,\n success: false,\n error: error instanceof Error ? error : new Error(String(error)),\n appliedFlow: schemaFlow,\n transformed: false\n };\n }\n }\n\n // No flow matched - return file unchanged (assume already universal)\n return {\n original: file,\n converted: file,\n success: true,\n transformed: false\n };\n }\n \n try {\n // Apply flow transformation\n const converted = applyFlowToFile(file, matchedFlow, platformId);\n \n return {\n original: file,\n converted,\n success: true,\n appliedFlow: matchedFlow,\n transformed: true\n };\n } catch (error) {\n logger.error(`Failed to convert file: ${file.path}`, error);\n return {\n original: file,\n success: false,\n error: error instanceof Error ? error : new Error(String(error)),\n appliedFlow: matchedFlow,\n transformed: false\n };\n }\n}\n\n/**\n * Find matching flow for a file path\n * \n * Matches file path against flow 'from' patterns using glob matching.\n * Returns first matching flow.\n * \n * @param filePath - File path to match\n * @param flows - Array of flows to check\n * @returns Matching flow or null\n */\nfunction findMatchingFlow(filePath: string, flows: Flow[]): Flow | null {\n for (const flow of flows) {\n const pattern = getPatternFromFlow(flow, 'from');\n \n if (!pattern) {\n continue;\n }\n \n // Check if file path matches flow pattern\n if (matchGlob(filePath, pattern)) {\n return flow;\n }\n }\n \n return null;\n}\n\n/**\n * Fallback: Find the best schema-matching flow for a file.\n *\n * Uses the flow's `from` schema (if present) to score against frontmatter.\n * Only considered when glob/path matching fails.\n */\nfunction findBestSchemaMatchingFlow(\n file: PackageFile,\n flows: Flow[],\n platformId: PlatformId\n): Flow | null {\n // Parse frontmatter (if needed)\n let frontmatter = file.frontmatter;\n if (!frontmatter && file.content) {\n const parsed = splitFrontmatter(file.content);\n frontmatter = parsed.frontmatter || {};\n }\n\n if (!frontmatter || Object.keys(frontmatter).length === 0) {\n return null;\n }\n\n let best: { flow: Flow; score: number } | null = null;\n\n for (const flow of flows) {\n const schema = schemaRegistry.getSchemaForFlow(flow, 'from');\n if (!schema) continue;\n\n const match = scoreAgainstSchema(frontmatter, schema, flow, file.path, platformId);\n\n // Ignore extremely weak matches to reduce accidental conversions\n if (match.score <= 0.2) continue;\n\n if (!best || match.score > best.score) {\n best = { flow, score: match.score };\n }\n }\n\n return best?.flow ?? null;\n}\n\n/**\n * Match file path against glob pattern\n */\nfunction matchGlob(filePath: string, pattern: string): boolean {\n try {\n return minimatch(filePath, pattern);\n } catch (error) {\n logger.warn(`Invalid glob pattern: ${pattern}`, error);\n return false;\n }\n}\n\n/**\n * Apply flow transformation to a file\n * \n * Transforms file content using flow's map operations.\n * Handles frontmatter transformation and path transformation.\n * \n * @param file - File to transform\n * @param flow - Flow to apply\n * @param platformId - Source platform ID\n * @returns Transformed file\n */\nfunction applyFlowToFile(\n file: PackageFile,\n flow: Flow,\n platformId: PlatformId\n): PackageFile {\n // Parse frontmatter if not already parsed\n let frontmatter = file.frontmatter;\n let body = '';\n \n if (!frontmatter && file.content) {\n const parsed = splitFrontmatter(file.content);\n frontmatter = parsed.frontmatter;\n body = parsed.body;\n }\n \n // Transform frontmatter using map operations\n let transformedFrontmatter = frontmatter;\n \n if (flow.map && flow.map.length > 0 && frontmatter) {\n // Create map context\n const mapContext = createMapContext({\n filename: basename(file.path),\n dirname: dirname(file.path),\n path: file.path,\n ext: extname(file.path)\n });\n \n // Apply map pipeline\n transformedFrontmatter = applyMapPipeline(\n frontmatter,\n flow.map,\n mapContext,\n defaultTransformRegistry\n );\n }\n \n // Transform path using flow patterns\n let transformedPath = transformPath(file.path, flow);\n // Strip platform suffix from output path (e.g. agents/foo.opencode.md -> agents/foo.md)\n const stripped = stripPlatformSuffixFromFilename(transformedPath);\n if (stripped !== transformedPath) {\n transformedPath = stripped;\n }\n \n // Serialize frontmatter back to content\n let transformedContent = file.content;\n if (transformedFrontmatter && body !== undefined) {\n const serialized = dumpYaml(transformedFrontmatter);\n const yamlBlock = serialized.endsWith('\\n') ? serialized : `${serialized}\\n`;\n transformedContent = `---\\n${yamlBlock}---\\n${body}`;\n }\n \n return {\n path: transformedPath,\n content: transformedContent,\n frontmatter: transformedFrontmatter\n };\n}\n\n/**\n * Transform file path using flow patterns\n * \n * Converts platform-specific path to universal path.\n * Example: .claude/agents/agent.md \u2192 agents/agent.md\n * \n * @param filePath - Original file path\n * @param flow - Flow with from/to patterns\n * @returns Transformed path\n */\nfunction transformPath(filePath: string, flow: Flow): string {\n const fromPattern = getPatternFromFlow(flow, 'from');\n const toPattern = getPatternFromFlow(flow, 'to');\n \n if (!fromPattern || !toPattern) {\n return filePath;\n }\n \n // Simple pattern transformation: replace glob prefix\n // Example: \".claude/agents/**/*.md\" \u2192 \"agents/**/*.md\"\n // \".claude/agents/foo.md\" \u2192 \"agents/foo.md\"\n \n // Extract non-glob prefix from patterns\n const fromPrefix = extractGlobPrefix(fromPattern);\n const toPrefix = extractGlobPrefix(toPattern);\n \n // If file path starts with from prefix, replace with to prefix\n if (filePath.startsWith(fromPrefix)) {\n const relativePath = filePath.substring(fromPrefix.length);\n return toPrefix + relativePath;\n }\n \n return filePath;\n}\n\n/**\n * Extract non-glob prefix from a glob pattern\n * \n * Example: \"agents/**\\/*.md\" \u2192 \"agents/\"\n * \".claude/agents/**\\/*.md\" \u2192 \".claude/agents/\"\n */\nfunction extractGlobPrefix(pattern: string): string {\n const parts = pattern.split('/');\n const prefix: string[] = [];\n \n for (const part of parts) {\n if (part.includes('*') || part.includes('?') || part.includes('[')) {\n break;\n }\n prefix.push(part);\n }\n \n return prefix.length > 0 ? prefix.join('/') + '/' : '';\n}\n\n/**\n * Validate that converted file is in universal format\n * \n * Checks that file has been transformed correctly.\n * \n * @param file - Converted file to validate\n * @returns Whether file is valid universal format\n */\nexport function validateUniversalFormat(file: PackageFile): boolean {\n // Parse frontmatter\n let frontmatter = file.frontmatter;\n \n if (!frontmatter && file.content) {\n const parsed = splitFrontmatter(file.content);\n frontmatter = parsed.frontmatter;\n }\n \n if (!frontmatter) {\n // No frontmatter - technically valid (e.g., skills)\n return true;\n }\n \n // Check for universal format indicators\n // Universal format uses:\n // - tools: array format (not string or object)\n // - model: prefixed format (e.g., \"anthropic/claude-3-5-sonnet-20241022\")\n // - permissions: object format (not permissionMode string)\n \n // Check tools field if present\n if ('tools' in frontmatter) {\n const tools = frontmatter.tools;\n \n // Universal format uses array\n if (!Array.isArray(tools)) {\n return false;\n }\n }\n \n // Check for platform-specific exclusive fields\n // These should not be present in universal format\n const platformExclusiveFields = [\n 'permissionMode', // Claude exclusive\n 'hooks', // Claude exclusive\n 'skills', // Claude exclusive\n 'temperature', // OpenCode exclusive\n 'maxSteps', // OpenCode exclusive\n 'disabled' // OpenCode exclusive\n ];\n \n for (const field of platformExclusiveFields) {\n if (field in frontmatter) {\n return false;\n }\n }\n \n return true;\n}\n\n/**\n * Apply import flows to array of files\n * \n * Convenience function that applies flows to multiple files.\n * \n * @param files - Files to convert\n * @param flows - Import flows to apply\n * @param platformId - Source platform ID\n * @returns Array of converted files\n */\nexport function applyImportFlows(\n files: PackageFile[],\n flows: Flow[],\n platformId: PlatformId\n): PackageFile[] {\n const convertedFiles: PackageFile[] = [];\n \n for (const file of files) {\n const result = convertSingleFile(file, flows, platformId);\n \n if (result.success && result.converted) {\n convertedFiles.push(result.converted);\n } else {\n logger.warn(`Failed to convert file: ${file.path}`, {\n error: result.error?.message\n });\n // Include original file if conversion failed\n convertedFiles.push(file);\n }\n }\n \n return convertedFiles;\n}\n", "/**\n * Format Group Merger Module\n * \n * Merges converted format groups into a unified package structure.\n * Handles path conflicts and deduplication.\n * \n * Phase 3: Per-File Import Flow Application\n */\n\nimport { logger } from '../../utils/logger.js';\nimport type { PackageFile, PlatformId, SpecialFormat } from './detection-types.js';\n\n/**\n * Validation result for merged package\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n \n /** Validation errors (if any) */\n errors: string[];\n \n /** Validation warnings (if any) */\n warnings: string[];\n}\n\n/**\n * Merge format groups into unified package\n * \n * Combines all converted format groups into a single array of files in universal format.\n * Handles path conflicts using priority-based deduplication.\n * \n * @param groups - Map of platform ID -> converted files\n * @returns Unified array of files in universal format\n */\nexport function mergeFormatGroups(\n groups: Map<PlatformId | SpecialFormat, PackageFile[]>\n): PackageFile[] {\n // Collect all files from all groups\n const allFiles: PackageFile[] = [];\n \n for (const [platformId, files] of groups) {\n allFiles.push(...files);\n }\n \n // Deduplicate paths with priority-based resolution\n const deduplicated = deduplicatePaths(allFiles);\n \n return deduplicated;\n}\n\n/**\n * Deduplicate files by path using priority ordering\n * \n * Priority (highest to lowest):\n * 1. Universal format (most canonical)\n * 2. Non-universal formats (first occurrence wins)\n * \n * @param files - Array of files (potentially with duplicate paths)\n * @returns Deduplicated array\n */\nexport function deduplicatePaths(files: PackageFile[]): PackageFile[] {\n const pathMap = new Map<string, PackageFile>();\n \n for (const file of files) {\n const existing = pathMap.get(file.path);\n \n if (!existing) {\n // First occurrence - add to map\n pathMap.set(file.path, file);\n continue;\n }\n \n // Duplicate path - apply priority rules\n const priority = determinePriority(file, existing);\n \n if (priority === 'new') {\n pathMap.set(file.path, file);\n }\n }\n \n return Array.from(pathMap.values());\n}\n\n/**\n * Determine which file has priority for the same path\n * \n * @param newFile - New file being considered\n * @param existingFile - Existing file in the map\n * @returns Which file to keep ('new' or 'existing')\n */\nfunction determinePriority(\n newFile: PackageFile,\n existingFile: PackageFile\n): 'new' | 'existing' {\n // Priority 1: Universal format content\n // Check if files have universal format indicators\n \n const newIsUniversal = isLikelyUniversalFormat(newFile);\n const existingIsUniversal = isLikelyUniversalFormat(existingFile);\n \n if (newIsUniversal && !existingIsUniversal) {\n return 'new';\n }\n \n if (existingIsUniversal && !newIsUniversal) {\n return 'existing';\n }\n \n // Priority 2: First occurrence wins (existing)\n return 'existing';\n}\n\n/**\n * Check if file is likely in universal format\n * \n * Heuristic check based on frontmatter structure.\n * Universal format uses:\n * - tools: array\n * - permissions: object\n * - model: prefixed (anthropic/...)\n * \n * @param file - File to check\n * @returns Whether file is likely universal format\n */\nfunction isLikelyUniversalFormat(file: PackageFile): boolean {\n if (!file.frontmatter) {\n // No frontmatter - could be universal (e.g., skills)\n return true;\n }\n \n const fm = file.frontmatter;\n \n // Check tools field\n if ('tools' in fm) {\n // Universal uses array\n if (Array.isArray(fm.tools)) {\n return true;\n }\n // Platform-specific uses string or object\n return false;\n }\n \n // Check permissions field\n if ('permissions' in fm) {\n // Universal uses object\n if (typeof fm.permissions === 'object' && fm.permissions !== null) {\n return true;\n }\n }\n \n // Check for platform-specific exclusive fields\n const platformExclusiveFields = [\n 'permissionMode', // Claude\n 'hooks', // Claude\n 'skills', // Claude\n 'temperature', // OpenCode\n 'maxSteps', // OpenCode\n 'disabled' // OpenCode\n ];\n \n for (const field of platformExclusiveFields) {\n if (field in fm) {\n // Has platform-specific field - not universal\n return false;\n }\n }\n \n // No clear indicators - assume universal\n return true;\n}\n\n/**\n * Validate merged package structure\n * \n * Checks for:\n * - No duplicate paths remaining\n * - All files have content or frontmatter\n * - Paths are valid\n * \n * @param files - Merged file array\n * @returns Validation result\n */\nexport function validateMergedPackage(files: PackageFile[]): ValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n \n // Check for duplicates\n const paths = new Set<string>();\n for (const file of files) {\n if (paths.has(file.path)) {\n errors.push(`Duplicate path after merge: ${file.path}`);\n }\n paths.add(file.path);\n }\n \n // Check file validity\n for (const file of files) {\n // Check path is non-empty\n if (!file.path || file.path.trim() === '') {\n errors.push('File with empty path found');\n continue;\n }\n \n // Check file has either content or frontmatter\n if (!file.content && !file.frontmatter) {\n warnings.push(`File ${file.path} has no content or frontmatter`);\n }\n \n // Check for absolute paths (should be relative)\n if (file.path.startsWith('/')) {\n warnings.push(`File has absolute path: ${file.path}`);\n }\n }\n \n const valid = errors.length === 0;\n \n if (!valid) {\n logger.error('Merged package validation failed', { errors, warnings });\n } else if (warnings.length > 0) {\n logger.warn('Merged package validation warnings', { warnings });\n }\n \n return {\n valid,\n errors,\n warnings\n };\n}\n\n/**\n * Get statistics about merged package\n * \n * @param files - Merged file array\n * @returns Package statistics\n */\nexport function getMergedPackageStats(files: PackageFile[]): {\n totalFiles: number;\n filesWithFrontmatter: number;\n filesWithContent: number;\n uniquePaths: number;\n} {\n const paths = new Set<string>();\n let filesWithFrontmatter = 0;\n let filesWithContent = 0;\n \n for (const file of files) {\n paths.add(file.path);\n \n if (file.frontmatter && Object.keys(file.frontmatter).length > 0) {\n filesWithFrontmatter++;\n }\n \n if (file.content && file.content.trim().length > 0) {\n filesWithContent++;\n }\n }\n \n return {\n totalFiles: files.length,\n filesWithFrontmatter,\n filesWithContent,\n uniquePaths: paths.size\n };\n}\n", "/**\n * Conversion Context Module\n * \n * Tracks conversion state and metadata during per-file/per-group conversion.\n * Provides context for conversion operations and error tracking.\n * \n * Phase 3: Per-File Import Flow Application\n */\n\nimport { logger } from '../../utils/logger.js';\nimport type { Flow } from '../../types/flows.js';\nimport type { \n PackageFile,\n PlatformId,\n SpecialFormat,\n FormatGroup\n} from './detection-types.js';\n\n/**\n * Conversion context for tracking state during conversion\n * \n * Maintains:\n * - Original format groups from detection\n * - Conversion results per group\n * - Errors per file\n * - Cached import flows per platform\n * - Overall statistics\n */\nexport interface ConversionContext {\n /**\n * Original format groups (keyed by dynamic platform ID)\n * Input to conversion process\n */\n formatGroups: Map<PlatformId | SpecialFormat, PackageFile[]>;\n \n /**\n * Conversion results per group (keyed by dynamic platform ID)\n * Output from conversion process\n */\n convertedGroups: Map<PlatformId | SpecialFormat, PackageFile[]>;\n \n /**\n * Conversion errors per file path\n * Tracks which files failed and why\n */\n errors: Map<string, Error>;\n \n /**\n * Conversion metadata and statistics\n */\n metadata: ConversionMetadata;\n \n /**\n * Platform import flows cache (keyed by dynamic platform ID)\n * Loaded flows cached for reuse across files\n */\n importFlowsCache: Map<PlatformId, Flow[]>;\n}\n\n/**\n * Conversion metadata and statistics\n */\nexport interface ConversionMetadata {\n /** Total files in package */\n totalFiles: number;\n \n /** Files successfully converted */\n convertedFiles: number;\n \n /** Files skipped (already universal or no flows) */\n skippedFiles: number;\n \n /** Files that failed conversion */\n failedFiles: number;\n \n /** Start time of conversion */\n startTime: number;\n \n /** End time of conversion (if complete) */\n endTime?: number;\n \n /** Duration in milliseconds (if complete) */\n durationMs?: number;\n}\n\n/**\n * Create a new conversion context from format groups\n * \n * @param formatGroups - Format groups from detection phase\n * @returns Initialized conversion context\n */\nexport function createConversionContext(\n formatGroups: Map<PlatformId | SpecialFormat, PackageFile[]>\n): ConversionContext {\n // Count total files\n const totalFiles = Array.from(formatGroups.values())\n .reduce((sum, files) => sum + files.length, 0);\n \n return {\n formatGroups,\n convertedGroups: new Map(),\n errors: new Map(),\n metadata: {\n totalFiles,\n convertedFiles: 0,\n skippedFiles: 0,\n failedFiles: 0,\n startTime: Date.now()\n },\n importFlowsCache: new Map()\n };\n}\n\n/**\n * Record successful conversion for a group\n * \n * @param context - Conversion context to update\n * @param platformId - Platform ID of converted group\n * @param convertedFiles - Converted files\n * @param filesConverted - Number of files successfully converted\n * @param filesSkipped - Number of files skipped\n */\nexport function recordGroupConversion(\n context: ConversionContext,\n platformId: PlatformId | SpecialFormat,\n convertedFiles: PackageFile[],\n filesConverted: number,\n filesSkipped: number\n): void {\n context.convertedGroups.set(platformId, convertedFiles);\n context.metadata.convertedFiles += filesConverted;\n context.metadata.skippedFiles += filesSkipped;\n}\n\n/**\n * Record conversion error for a file\n * \n * @param context - Conversion context to update\n * @param filePath - Path of file that failed\n * @param error - Error that occurred\n */\nexport function recordConversionError(\n context: ConversionContext,\n filePath: string,\n error: Error\n): void {\n context.errors.set(filePath, error);\n context.metadata.failedFiles++;\n \n logger.debug(`Recorded conversion error for ${filePath}`, error);\n}\n\n/**\n * Mark conversion as complete\n * \n * Updates metadata with end time and duration.\n * \n * @param context - Conversion context to finalize\n */\nexport function finalizeConversion(context: ConversionContext): void {\n context.metadata.endTime = Date.now();\n context.metadata.durationMs = context.metadata.endTime - context.metadata.startTime;\n}\n\n/**\n * Get conversion summary\n * \n * @param context - Conversion context\n * @returns Human-readable summary\n */\nexport function getConversionSummary(context: ConversionContext): string {\n const { totalFiles, convertedFiles, skippedFiles, failedFiles, durationMs } = context.metadata;\n \n const parts: string[] = [];\n parts.push(`Total: ${totalFiles} files`);\n parts.push(`Converted: ${convertedFiles}`);\n parts.push(`Skipped: ${skippedFiles}`);\n \n if (failedFiles > 0) {\n parts.push(`Failed: ${failedFiles}`);\n }\n \n if (durationMs !== undefined) {\n parts.push(`Duration: ${durationMs}ms`);\n }\n \n return parts.join(', ');\n}\n\n/**\n * Check if conversion was successful\n * \n * @param context - Conversion context\n * @returns Whether all files were converted successfully\n */\nexport function isConversionSuccessful(context: ConversionContext): boolean {\n return context.metadata.failedFiles === 0;\n}\n\n/**\n * Get all conversion errors\n * \n * @param context - Conversion context\n * @returns Array of [filePath, error] tuples\n */\nexport function getConversionErrors(\n context: ConversionContext\n): Array<[string, Error]> {\n return Array.from(context.errors.entries());\n}\n\n/**\n * Cache import flows for a platform\n * \n * @param context - Conversion context\n * @param platformId - Platform ID\n * @param flows - Import flows to cache\n */\nexport function cacheImportFlows(\n context: ConversionContext,\n platformId: PlatformId,\n flows: Flow[]\n): void {\n context.importFlowsCache.set(platformId, flows);\n}\n\n/**\n * Get cached import flows for a platform\n * \n * @param context - Conversion context\n * @param platformId - Platform ID\n * @returns Cached flows or null if not cached\n */\nexport function getCachedImportFlows(\n context: ConversionContext,\n platformId: PlatformId\n): Flow[] | null {\n return context.importFlowsCache.get(platformId) || null;\n}\n\n/**\n * Create format groups from enhanced package format\n * \n * Helper to convert from detection result to format groups structure.\n * \n * @param files - All package files\n * @param formatGroups - Map of platform -> file paths from detection\n * @returns Map of platform -> files\n */\nexport function createFormatGroupsFromPaths(\n files: PackageFile[],\n formatGroups: Map<PlatformId | SpecialFormat, string[]>\n): Map<PlatformId | SpecialFormat, PackageFile[]> {\n const result = new Map<PlatformId | SpecialFormat, PackageFile[]>();\n \n // Create file lookup map\n const fileMap = new Map<string, PackageFile>();\n for (const file of files) {\n fileMap.set(file.path, file);\n }\n \n // Build format groups with actual file objects\n for (const [platformId, filePaths] of formatGroups) {\n const groupFiles: PackageFile[] = [];\n \n for (const filePath of filePaths) {\n const file = fileMap.get(filePath);\n if (file) {\n groupFiles.push(file);\n } else {\n logger.warn(`File not found in package: ${filePath}`);\n }\n }\n \n if (groupFiles.length > 0) {\n result.set(platformId, groupFiles);\n }\n }\n \n return result;\n}\n", "/**\n * Conversion Coordinator Module\n * \n * Orchestrates format detection and pre-conversion for packages.\n * Integrates Phase 2 detection and Phase 3 conversion into the installation pipeline.\n * \n * Phase 4: Integration with Existing Pipeline\n */\n\nimport { logger } from '../../utils/logger.js';\nimport { detectEnhancedPackageFormat } from './format-detector.js';\nimport { convertFormatGroup } from './import-flow-converter.js';\nimport { mergeFormatGroups } from './format-group-merger.js';\nimport { \n createConversionContext, \n recordGroupConversion, \n recordConversionError,\n finalizeConversion,\n type ConversionContext \n} from './conversion-context.js';\nimport type { \n PackageFile as DetectionPackageFile,\n EnhancedPackageFormat,\n FormatGroup,\n PlatformId,\n SpecialFormat\n} from './detection-types.js';\nimport type { InstallOptions, PackageFile } from '../../types/index.js';\n\n/**\n * Result of package conversion coordination\n */\nexport interface PackageConversionResult {\n /**\n * Whether package was converted\n * False if package was already universal or no conversion needed\n */\n wasConverted: boolean;\n \n /**\n * Enhanced format detection result\n */\n formatDetection: EnhancedPackageFormat;\n \n /**\n * Converted files (universal format)\n * If not converted, contains original files\n */\n files: PackageFile[];\n \n /**\n * Conversion context (if conversion occurred)\n */\n conversionContext?: ConversionContext;\n \n /**\n * Conversion errors (if any)\n */\n errors: Error[];\n \n /**\n * Warnings (non-fatal issues)\n */\n warnings: string[];\n}\n\n/**\n * Options for conversion coordination\n */\nexport interface ConversionOptions {\n /**\n * Target directory for platform config loading\n */\n targetDir?: string;\n \n /**\n * Force conversion even if already universal\n */\n forceConversion?: boolean;\n \n /**\n * Skip conversion entirely (passthrough)\n */\n skipConversion?: boolean;\n}\n\n/**\n * Coordinate format detection and pre-conversion for a package\n * \n * This is the main entry point for Phase 4 integration.\n * \n * Flow:\n * 1. Detect package format (Tier 1: markers, Tier 2: per-file)\n * 2. Determine if conversion is needed\n * 3. If needed, apply per-group conversion\n * 4. Merge converted groups\n * 5. Return unified result\n * \n * @param files - Package files to process\n * @param contentRoot - Package content root path\n * @param options - Conversion options\n * @returns Conversion result with converted files\n */\nexport async function coordinateConversion(\n files: DetectionPackageFile[],\n contentRoot: string,\n options: ConversionOptions = {}\n): Promise<PackageConversionResult> {\n const errors: Error[] = [];\n const warnings: string[] = [];\n \n try {\n // Skip conversion if requested\n if (options.skipConversion) {\n return {\n wasConverted: false,\n formatDetection: createSkipDetectionResult(files),\n files: convertToMainPackageFiles(files),\n errors: [],\n warnings: []\n };\n }\n \n // Step 1: Enhanced format detection (Phase 2)\n // Cast to main PackageFile type since detection uses its own PackageFile interface\n const formatDetection = await detectEnhancedPackageFormat(files as any);\n \n logger.info('Format detection complete', {\n packageFormat: formatDetection.packageFormat,\n detectionMethod: formatDetection.detectionMethod,\n confidence: formatDetection.confidence,\n totalFiles: formatDetection.analysis.totalFiles\n });\n \n // Step 2: Determine if conversion is needed\n const needsConversion = shouldPreConvert(formatDetection, options);\n \n if (!needsConversion) {\n // Still convert platform-specific groups when package is mostly universal\n // (e.g. agents/foo.opencode.md in otherwise-universal package)\n const hasPlatformSpecificGroups = (formatDetection.formatGroups?.size ?? 0) > 0 &&\n Array.from(formatDetection.formatGroups?.keys() ?? []).some(\n k => k !== 'universal' && k !== 'unknown'\n );\n if (!hasPlatformSpecificGroups) {\n return {\n wasConverted: false,\n formatDetection,\n files: convertToMainPackageFiles(files),\n errors: [],\n warnings: []\n };\n }\n }\n \n // Step 3: Perform pre-conversion (Phase 3)\n logger.info('Pre-converting package to universal format', {\n packageFormat: formatDetection.packageFormat,\n groupCount: formatDetection.formatGroups?.size || 0\n });\n \n const conversionResult = await preConvertPackage(\n files,\n formatDetection,\n options.targetDir\n );\n \n return {\n wasConverted: true,\n formatDetection,\n files: convertToMainPackageFiles(conversionResult.files),\n conversionContext: conversionResult.context,\n errors: conversionResult.errors,\n warnings: conversionResult.warnings\n };\n \n } catch (error) {\n logger.error('Conversion coordination failed', { error });\n errors.push(error instanceof Error ? error : new Error(String(error)));\n \n // Return original files on error (graceful degradation)\n return {\n wasConverted: false,\n formatDetection: createErrorDetectionResult(files, error),\n files: convertToMainPackageFiles(files),\n errors,\n warnings\n };\n }\n}\n\n\n\n/**\n * Determine if package needs pre-conversion\n * \n * Conversion needed if:\n * - Package format is platform-specific (not universal)\n * - Package format is mixed (multiple platforms)\n * - Force conversion is enabled\n * \n * @param format - Enhanced format detection result\n * @param options - Conversion options\n * @returns Whether conversion is needed\n */\nexport function shouldPreConvert(\n format: EnhancedPackageFormat,\n options: ConversionOptions = {}\n): boolean {\n // Force conversion if requested\n if (options.forceConversion) {\n return true;\n }\n \n // Skip if already universal\n if (format.packageFormat === 'universal') {\n return false;\n }\n \n // Convert if platform-specific or mixed\n if (format.packageFormat !== 'unknown') {\n return true;\n }\n \n // Unknown format - don't convert (let existing flow handle it)\n return false;\n}\n\n/**\n * Pre-convert package to universal format (Phase 3)\n * \n * Applies import flows per format group and merges results.\n */\nasync function preConvertPackage(\n files: DetectionPackageFile[],\n formatDetection: EnhancedPackageFormat,\n targetDir?: string\n): Promise<{\n files: DetectionPackageFile[];\n context: ConversionContext;\n errors: Error[];\n warnings: string[];\n}> {\n const errors: Error[] = [];\n const warnings: string[] = [];\n \n // Get format groups from detection (paths only)\n const formatGroupPaths = formatDetection.formatGroups;\n \n if (!formatGroupPaths || formatGroupPaths.size === 0) {\n logger.warn('No format groups found for conversion');\n return {\n files,\n context: createConversionContext(new Map()),\n errors: [],\n warnings: ['No format groups found for conversion']\n };\n }\n \n // Create file lookup map for efficient access\n const fileMap = new Map<string, DetectionPackageFile>();\n for (const file of files) {\n fileMap.set(file.path, file);\n }\n \n // Convert path groups to PackageFile groups\n const formatGroups = new Map<PlatformId | SpecialFormat, DetectionPackageFile[]>();\n for (const [platformId, paths] of formatGroupPaths.entries()) {\n const groupFiles: DetectionPackageFile[] = [];\n for (const path of paths) {\n const file = fileMap.get(path);\n if (file) {\n groupFiles.push(file);\n } else {\n logger.warn(`File not found in file map: ${path}`);\n }\n }\n if (groupFiles.length > 0) {\n formatGroups.set(platformId, groupFiles);\n }\n }\n \n // Create conversion context\n const conversionContext = createConversionContext(formatGroups);\n \n // Convert each format group\n const convertedGroups = new Map<PlatformId | SpecialFormat, PackageFile[]>();\n\n for (const [platformId, groupFiles] of formatGroups.entries()) {\n try {\n // Create format group object\n const formatGroup: FormatGroup = {\n platformId,\n files: groupFiles,\n confidence: 1.0 // Use detection confidence if available\n };\n \n // Convert group using Phase 3 converter\n const groupResult = convertFormatGroup(formatGroup, targetDir);\n \n // Record conversion in context\n // Type cast needed since detection-types and main types are structurally compatible but nominally different\n recordGroupConversion(\n conversionContext,\n platformId,\n groupResult.convertedFiles as any,\n groupResult.filesConverted,\n groupResult.filesProcessed - groupResult.filesConverted\n );\n \n // Collect errors\n for (const fileResult of groupResult.fileResults) {\n if (!fileResult.success && fileResult.error) {\n recordConversionError(\n conversionContext,\n fileResult.original.path,\n fileResult.error\n );\n errors.push(fileResult.error);\n }\n }\n \n // Add to converted groups\n // Type cast needed since detection-types and main types are structurally compatible but nominally different\n convertedGroups.set(platformId, groupResult.convertedFiles as any);\n \n } catch (error) {\n logger.error(`Failed to convert format group: ${platformId}`, { error });\n const err = error instanceof Error ? error : new Error(String(error));\n errors.push(err);\n warnings.push(`Failed to convert ${platformId} format group: ${err.message}`);\n \n // Record error for all files in group\n for (const file of groupFiles) {\n recordConversionError(conversionContext, file.path, err);\n }\n }\n }\n \n // Merge converted groups (Phase 3)\n const mergedFiles = mergeFormatGroups(convertedGroups);\n \n // Finalize conversion context\n finalizeConversion(conversionContext);\n \n logger.info('Pre-conversion complete', {\n totalFiles: mergedFiles.length,\n convertedFiles: conversionContext.metadata.convertedFiles,\n failedFiles: conversionContext.metadata.failedFiles,\n durationMs: conversionContext.metadata.durationMs\n });\n \n // Convert detection PackageFile to main PackageFile (ensure content is present)\n const convertedFiles: PackageFile[] = mergedFiles.map(f => ({\n path: f.path,\n content: f.content || '', // Should always be present, but fallback to empty string\n ...(f.frontmatter && { frontmatter: f.frontmatter })\n })) as PackageFile[];\n \n return {\n files: convertedFiles,\n context: conversionContext,\n errors,\n warnings\n };\n}\n\n/**\n * Convert detection PackageFile array to main PackageFile array\n * Ensures all files have content property\n */\nfunction convertToMainPackageFiles(files: DetectionPackageFile[]): PackageFile[] {\n return files.map(f => ({\n path: f.path,\n content: f.content || ''\n }));\n}\n\n/**\n * Create a detection result for skipped conversion\n */\nfunction createSkipDetectionResult(files: DetectionPackageFile[]): EnhancedPackageFormat {\n return {\n packageFormat: 'universal',\n detectionMethod: 'package-marker',\n confidence: 1.0,\n analysis: {\n totalFiles: files.length,\n analyzedFiles: 0,\n skippedFiles: files.length,\n formatDistribution: new Map([['universal', files.length]])\n }\n };\n}\n\n/**\n * Create a detection result for error case\n */\nfunction createErrorDetectionResult(\n files: DetectionPackageFile[],\n error: unknown\n): EnhancedPackageFormat {\n logger.error('Detection failed, returning unknown format', { error });\n \n return {\n packageFormat: 'unknown',\n detectionMethod: 'package-marker',\n confidence: 0,\n analysis: {\n totalFiles: files.length,\n analyzedFiles: 0,\n skippedFiles: files.length,\n formatDistribution: new Map([['unknown', files.length]])\n }\n };\n}\n", "/**\n * Convert Phase\n * \n * Performs format detection and pre-conversion of packages.\n * Integrates Phase 2 detection and Phase 3 conversion into the pipeline.\n * \n * Phase 4: Integration with Existing Pipeline\n */\n\nimport type { InstallationContext } from '../context.js';\nimport { coordinateConversion } from '../../conversion-coordinator.js';\nimport { addWarning } from '../context-helpers.js';\nimport { logger } from '../../../../utils/logger.js';\nimport { readdir } from 'fs/promises';\nimport { join } from 'path';\nimport { readFile } from 'fs/promises';\nimport type { PackageFile as DetectionPackageFile } from '../../detection-types.js';\nimport { minimatch } from 'minimatch';\nimport { getPlatformDefinitions, matchesUniversalPattern } from '../../../platforms.js';\nimport { getPatternFromFlow } from '../../schema-registry.js';\nimport { \n createTempPackageDirectory, \n writeTempPackageFiles,\n createConversionCacheDirectory,\n cleanupTempDirectory\n} from '../../strategies/helpers/temp-directory.js';\n\n/**\n * Convert phase - detect format and pre-convert if needed\n * \n * This phase:\n * 1. Loads all files from content root\n * 2. Runs format detection (Tier 1 + Tier 2)\n * 3. Pre-converts if platform-specific format detected\n * 4. Updates context with conversion metadata\n * \n * @param ctx - Installation context\n */\nexport async function convertPhase(ctx: InstallationContext): Promise<void> {\n // Skip if no content root (shouldn't happen after load phase)\n if (!ctx.source.contentRoot) {\n logger.warn('No content root, skipping convert phase');\n return;\n }\n \n // Skip if package is a marketplace (will be handled by marketplace flow)\n if (ctx.source.pluginMetadata?.pluginType === 'marketplace') {\n return;\n }\n \n try {\n // Load package files\n const files = await loadPackageFiles(ctx.source.contentRoot, {\n targetDir: ctx.targetDir,\n matchedPattern: ctx.matchedPattern\n });\n \n if (files.length === 0) {\n logger.warn('No files found in package, skipping conversion');\n return;\n }\n\n // Coordinate conversion (detection + conversion if needed)\n const conversionResult = await coordinateConversion(\n files,\n ctx.source.contentRoot,\n {\n targetDir: ctx.targetDir,\n skipConversion: false\n }\n );\n \n // Update context with conversion metadata\n ctx.formatDetection = conversionResult.formatDetection;\n ctx.wasPreConverted = conversionResult.wasConverted;\n \n if (conversionResult.errors.length > 0) {\n ctx.conversionErrors = conversionResult.errors;\n logger.warn('Conversion had errors', {\n errorCount: conversionResult.errors.length\n });\n }\n \n // Add warnings to context\n for (const warning of conversionResult.warnings) {\n addWarning(ctx, warning);\n }\n \n // Log conversion results\n if (conversionResult.wasConverted) {\n logger.info('Package pre-converted to universal format', {\n packageName: ctx.source.packageName,\n originalFormat: conversionResult.formatDetection.packageFormat,\n fileCount: conversionResult.files.length,\n detectionMethod: conversionResult.formatDetection.detectionMethod\n });\n\n // Store original contentRoot before any modifications\n const originalContentRoot = ctx.source.contentRoot;\n \n // Determine conversion strategy based on source location\n const isGitCache = originalContentRoot.includes('/.openpackage/cache/git/') || \n originalContentRoot.includes('.openpackage/cache/git/');\n \n let conversionRoot: string;\n let shouldCleanup = false;\n \n if (isGitCache) {\n // Git cache: Store converted files in .opkg-converted subdirectory\n // Extract the git cache root (without any subdirectory)\n const gitCacheMatch = originalContentRoot.match(/(.+\\.openpackage\\/cache\\/git\\/[^\\/]+\\/[^\\/]+)/);\n const gitCacheRoot = gitCacheMatch ? gitCacheMatch[1] : originalContentRoot;\n \n const isResourceScoped = Boolean(ctx.matchedPattern);\n \n if (!isResourceScoped) {\n // Full install: wipe any existing conversion cache first.\n // A prior resource-scoped install (e.g. --agents code-reviewer) may have\n // populated the cache with only a subset of files. Stale files that no\n // longer exist in the source would survive a write-over and get installed.\n const existingCache = join(gitCacheRoot, '.opkg-converted');\n await cleanupTempDirectory(existingCache);\n }\n\n conversionRoot = await createConversionCacheDirectory(gitCacheRoot);\n await writeTempPackageFiles(conversionResult.files, conversionRoot);\n shouldCleanup = false;\n logger.info(isResourceScoped\n ? 'Patched conversion cache with resource-scoped files'\n : 'Created fresh conversion cache for full install', {\n conversionRoot,\n fileCount: conversionResult.files.length\n });\n } else {\n // Local path or other source: Use temporary directory\n conversionRoot = await createTempPackageDirectory('opkg-preconverted-');\n await writeTempPackageFiles(conversionResult.files, conversionRoot);\n shouldCleanup = true; // Cleanup temp directory after install\n logger.info('Created temporary conversion directory', { conversionRoot });\n }\n\n // Track temp dir for cleanup in the pipeline (only for non-git-cache)\n if (shouldCleanup) {\n (ctx as any)._tempConversionRoot = conversionRoot;\n }\n \n // Store original content root for index writing\n (ctx as any)._originalContentRoot = originalContentRoot;\n\n // Update content roots so installation uses converted files\n ctx.source.contentRoot = conversionRoot;\n const rootPkg = ctx.resolvedPackages.find((p: any) => p.isRoot);\n if (rootPkg) {\n rootPkg.contentRoot = conversionRoot;\n // Store original for index writing\n (rootPkg as any).originalContentRoot = originalContentRoot;\n }\n \n // Store converted files in package metadata for downstream use\n if (ctx.resolvedPackages.length > 0) {\n const rootPackage = ctx.resolvedPackages[0];\n if (rootPackage.pkg) {\n // Store converted files in package\n rootPackage.pkg.files = conversionResult.files;\n \n // Mark as converted in metadata\n if (!rootPackage.pkg.metadata) {\n rootPackage.pkg.metadata = {} as any;\n }\n (rootPackage.pkg.metadata as any)._wasConverted = true;\n (rootPackage.pkg.metadata as any)._originalFormat = conversionResult.formatDetection.packageFormat;\n }\n }\n }\n \n } catch (error) {\n // Conversion errors are non-fatal - log and continue\n logger.error('Convert phase failed', { error });\n addWarning(\n ctx,\n `Format conversion failed: ${error instanceof Error ? error.message : String(error)}`\n );\n \n // Store error in context\n if (!ctx.conversionErrors) {\n ctx.conversionErrors = [];\n }\n ctx.conversionErrors.push(\n error instanceof Error ? error : new Error(String(error))\n );\n }\n}\n\n/**\n * Load all package files from content root\n * \n * Recursively walks directory tree and loads all files.\n * \n * @param contentRoot - Package content root path\n * @returns Array of package files with paths and content\n */\nasync function loadPackageFiles(\n contentRoot: string,\n opts: { targetDir: string; matchedPattern?: string }\n): Promise<DetectionPackageFile[]> {\n const files: DetectionPackageFile[] = [];\n \n function isRelevantPath(relPath: string, targetDir: string, matchedPattern?: string): boolean {\n const normalized = relPath.replace(/\\\\/g, '/').replace(/^\\.\\/?/, '');\n const matchesMatchedPattern = matchedPattern ? minimatch(normalized, matchedPattern) : true;\n if (!matchesMatchedPattern) {\n return false;\n }\n\n const isUniversal = matchesUniversalPattern(normalized, targetDir);\n let importMatch: { platformId: string; pattern: string } | null = null;\n\n if (!isUniversal) {\n // Platform-specific paths (declared by import flow \"from\" patterns in platforms.jsonc)\n const platforms = getPlatformDefinitions(targetDir);\n for (const [platformId, def] of Object.entries(platforms)) {\n const importFlows = def.import || [];\n for (const flow of importFlows) {\n const pattern = getPatternFromFlow(flow as any, 'from');\n if (pattern && minimatch(normalized, pattern)) {\n importMatch = { platformId, pattern };\n break;\n }\n }\n if (importMatch) break;\n }\n }\n\n const relevant = isUniversal || importMatch !== null;\n\n return relevant;\n }\n\n async function walk(dir: string, baseDir: string, opts: { targetDir: string; matchedPattern?: string }): Promise<void> {\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n \n // Skip hidden directories and node_modules\n if (entry.isDirectory()) {\n if (entry.name.startsWith('.') && entry.name !== '.claude-plugin') {\n continue;\n }\n if (entry.name === 'node_modules') {\n continue;\n }\n \n await walk(fullPath, baseDir, opts);\n } else {\n const relativePath = fullPath.substring(baseDir.length + 1).replace(/\\\\/g, '/');\n if (!isRelevantPath(relativePath, opts.targetDir, opts.matchedPattern)) {\n continue;\n }\n // Load file content\n try {\n const content = await readFile(fullPath, 'utf-8');\n \n files.push({\n path: relativePath,\n content\n });\n } catch (error) {\n logger.warn(`Failed to read file: ${fullPath}`, { error });\n }\n }\n }\n }\n \n await walk(contentRoot, contentRoot, opts);\n\n return files;\n}\n", "/**\n * Temp Directory Helpers Module\n * \n * Utilities for managing temporary directories during package conversion.\n */\n\nimport { join, dirname } from 'path';\nimport { mkdtemp, rm } from 'fs/promises';\nimport { tmpdir } from 'os';\nimport { ensureDir, writeTextFile } from '../../../../utils/fs.js';\nimport { logger } from '../../../../utils/logger.js';\nimport type { PackageConversionContext } from '../../../../types/conversion-context.js';\nimport { contextToJSON } from '../../../conversion-context/index.js';\n\n/**\n * Create a temporary directory for package conversion\n * \n * @param prefix - Prefix for temp directory name\n * @returns Absolute path to created temp directory\n */\nexport async function createTempPackageDirectory(prefix: string = 'opkg-converted-'): Promise<string> {\n const tempDir = await mkdtemp(join(tmpdir(), prefix));\n return tempDir;\n}\n\n/**\n * Create a conversion cache directory within git cache location.\n * This stores converted files alongside the original git cache for reuse.\n * \n * @param gitCachePath - Path to git cache directory\n * @returns Absolute path to conversion cache directory\n */\nexport async function createConversionCacheDirectory(\n gitCachePath: string\n): Promise<string> {\n const conversionDir = join(gitCachePath, '.opkg-converted');\n await ensureDir(conversionDir);\n return conversionDir;\n}\n\n/**\n * Write package files to temporary directory\n * \n * @param files - Array of files to write\n * @param tempDir - Temporary directory path\n */\nexport async function writeTempPackageFiles(\n files: Array<{ path: string; content: string }>,\n tempDir: string\n): Promise<void> {\n for (const file of files) {\n const filePath = join(tempDir, file.path);\n await ensureDir(dirname(filePath));\n await writeTextFile(filePath, file.content);\n }\n}\n\n/**\n * Write conversion context to temporary directory\n * \n * @param context - Conversion context to write\n * @param tempDir - Temporary directory path\n */\nexport async function writeConversionContext(\n context: PackageConversionContext,\n tempDir: string\n): Promise<void> {\n const contextPath = join(tempDir, '.opkg-conversion-context.json');\n const contextJson = contextToJSON(context);\n await writeTextFile(contextPath, contextJson);\n}\n\n/**\n * Cleanup temporary directory with error handling\n * \n * @param tempDir - Directory to cleanup\n */\nexport async function cleanupTempDirectory(tempDir: string | null): Promise<void> {\n if (!tempDir) {\n return;\n }\n \n try {\n await rm(tempDir, { recursive: true, force: true });\n } catch (error) {\n logger.warn('Failed to cleanup temp directory', {\n tempDir,\n error\n });\n }\n}\n", "import * as semver from 'semver';\nimport type { InstallationContext } from '../context.js';\nimport { pullMissingDependenciesIfNeeded } from '../../remote-flow.js';\nimport { addWarning, addError } from '../context-helpers.js';\nimport { logger } from '../../../../utils/logger.js';\nimport { resolveDependencies } from '../../../dependency-resolver/resolver.js';\nimport { gatherGlobalVersionConstraints, gatherRootVersionConstraints } from '../../../openpackage.js';\nimport { VersionConflictError } from '../../../../utils/errors.js';\nimport type { PromptPort } from '../../../ports/prompt.js';\nimport { resolvePrompt } from '../../../ports/resolve.js';\nimport type { InteractionPolicy } from '../../../../core/interaction-policy.js';\nimport { PromptTier } from '../../../../core/interaction-policy.js';\nimport type { PackageRemoteResolutionOutcome } from '../../types.js';\n\ninterface DependencyResolutionResult {\n resolvedPackages: Awaited<ReturnType<typeof resolveDependencies>>['resolvedPackages'];\n missingPackages: string[];\n warnings?: string[];\n remoteOutcomes?: Record<string, PackageRemoteResolutionOutcome>;\n}\n\nclass VersionResolutionAbortError extends Error {\n constructor(public packageName: string) {\n super(`Unable to resolve version for ${packageName}`);\n this.name = 'VersionResolutionAbortError';\n }\n}\n\nasync function resolveDependenciesForInstall(\n packageName: string,\n cwd: string,\n version: string | undefined,\n options: InstallationContext['options'],\n policy?: InteractionPolicy,\n prompt?: PromptPort\n): Promise<DependencyResolutionResult> {\n const globalConstraints = await gatherGlobalVersionConstraints(cwd);\n const rootConstraints = await gatherRootVersionConstraints(cwd);\n const rootOverrides = new Map(rootConstraints);\n const resolverWarnings = new Set<string>();\n\n const resolverOptions = {\n mode: options.resolutionMode ?? 'default',\n profile: options.profile,\n apiKey: options.apiKey,\n skipCache: options.resolutionMode === 'remote-primary',\n onWarning: (message: string) => {\n if (!resolverWarnings.has(message)) {\n resolverWarnings.add(message);\n }\n }\n };\n\n const runResolution = async () => {\n return await resolveDependencies(\n packageName,\n cwd,\n true,\n new Set(),\n new Map(),\n version,\n new Map(),\n globalConstraints,\n rootOverrides,\n resolverOptions\n );\n };\n\n try {\n const result = await runResolution();\n return {\n resolvedPackages: result.resolvedPackages,\n missingPackages: result.missingPackages,\n warnings: resolverWarnings.size > 0 ? Array.from(resolverWarnings) : undefined,\n remoteOutcomes: result.remoteOutcomes\n };\n } catch (error) {\n if (error instanceof VersionConflictError) {\n const conflictDetails: any = (error as any).details || {};\n const conflictName = conflictDetails.packageName || conflictDetails.pkg || packageName;\n const available: string[] = conflictDetails.availableVersions || [];\n\n let chosenVersion: string | null = null;\n if (options.force) {\n chosenVersion = [...available].sort((a, b) => semver.rcompare(a, b))[0] || null;\n } else if (policy && !policy.canPrompt(PromptTier.ConflictResolution)) {\n throw new Error(`Version conflict for '${conflictName}'. Available versions: ${available.join(', ')}. Use --force to auto-select latest, or run interactively to choose.`);\n } else {\n const p = prompt ?? resolvePrompt();\n const versionChoices = available.map(v => ({ title: v, value: v }));\n chosenVersion = await p.select<string>(\n `Select version of '${conflictName}' to install:`,\n versionChoices,\n 'Use arrow keys to navigate, Enter to select'\n );\n }\n\n if (!chosenVersion) {\n throw new VersionResolutionAbortError(conflictName);\n }\n\n rootOverrides.set(conflictName, [chosenVersion]);\n const retryResult = await runResolution();\n return {\n resolvedPackages: retryResult.resolvedPackages,\n missingPackages: retryResult.missingPackages,\n warnings: resolverWarnings.size > 0 ? Array.from(resolverWarnings) : undefined,\n remoteOutcomes: retryResult.remoteOutcomes\n };\n }\n\n throw error;\n }\n}\n\n/**\n * Resolve dependencies phase\n */\nexport async function resolveDependenciesPhase(ctx: InstallationContext): Promise<void> {\n try {\n // Initial dependency resolution\n const result = await resolveDependenciesForInstall(\n ctx.source.packageName,\n ctx.targetDir,\n ctx.source.version,\n ctx.options,\n ctx.execution?.interactionPolicy,\n ctx.execution?.prompt\n );\n \n // Add warnings\n result.warnings?.forEach(w => addWarning(ctx, w));\n \n // Update context\n ctx.resolvedPackages = result.resolvedPackages;\n let missingPackages = result.missingPackages;\n \n // Pull missing dependencies if needed\n if (missingPackages.length > 0 && ctx.options.resolutionMode !== 'local-only') {\n const pullResult = await pullMissingDependenciesIfNeeded({\n missingPackages,\n resolvedPackages: ctx.resolvedPackages,\n remoteOutcomes: result.remoteOutcomes || {},\n warnedPackages: new Set(),\n dryRun: ctx.options.dryRun || false,\n profile: ctx.options.profile,\n apiKey: ctx.options.apiKey\n });\n \n pullResult.warnings.forEach(w => addWarning(ctx, w));\n \n // Re-resolve if we pulled anything\n if (pullResult.pulledAny) {\n const refreshed = await resolveDependenciesForInstall(\n ctx.source.packageName,\n ctx.targetDir,\n ctx.source.version,\n ctx.options,\n ctx.execution?.interactionPolicy,\n ctx.execution?.prompt\n );\n \n ctx.resolvedPackages = refreshed.resolvedPackages;\n missingPackages = refreshed.missingPackages;\n }\n }\n \n // Warn about remaining missing packages\n if (missingPackages.length > 0) {\n const warning = `Missing packages: ${Array.from(new Set(missingPackages)).join(', ')}`;\n addWarning(ctx, warning);\n }\n \n logger.info(`Resolved ${ctx.resolvedPackages.length} packages`);\n \n } catch (error) {\n const errorMsg = `Failed to resolve dependencies: ${error}`;\n addError(ctx, errorMsg);\n throw new Error(errorMsg);\n }\n}\n", "import * as semver from 'semver';\nimport { PackageYml } from '../../types/index.js';\nimport type { ResolvedPackage } from '../dependency-resolver/types.js';\nimport { arePackageNamesEquivalent } from '../../utils/package-name.js';\nimport { getLocalPackageYmlPath } from '../../utils/paths.js';\nimport { parsePackageYml } from '../../utils/package-yml.js';\nimport { exists } from '../../utils/fs.js';\n\n/**\n * Extract packages from openpackage.yml configuration\n */\nexport function extractPackagesFromConfig(config: PackageYml): Array<{ name: string; version?: string; path?: string; git?: string; url?: string; ref?: string; subdirectory?: string; isDev: boolean }> {\n const packages: Array<{ name: string; version?: string; path?: string; git?: string; url?: string; ref?: string; subdirectory?: string; isDev: boolean }> = [];\n \n const processSection = (section: 'dependencies' | 'dev-dependencies', isDev: boolean) => {\n const deps = config[section];\n if (deps) {\n for (const pkg of deps) {\n packages.push({\n name: pkg.name,\n version: pkg.version,\n path: pkg.path,\n git: (pkg as any).git,\n url: (pkg as any).url,\n ref: (pkg as any).ref,\n subdirectory: (pkg as any).subdirectory,\n isDev\n });\n }\n }\n };\n\n processSection('dependencies', false);\n processSection('dev-dependencies', true);\n \n return packages;\n}\n\n\n\n/**\n * Get the highest version and required version of a package from the dependency tree\n */\nexport async function getVersionInfoFromDependencyTree(\n packageName: string,\n resolvedPackages: ResolvedPackage[]\n): Promise<{ highestVersion: string; requiredVersion?: string }> {\n let highestVersion = '0.0.0';\n let highestRequiredVersion: string | undefined;\n \n // Get the requiredVersions map from the first resolved package\n const requiredVersions = (resolvedPackages[0] as any)?.requiredVersions as Map<string, string[]> | undefined;\n \n for (const resolved of resolvedPackages) {\n if (arePackageNamesEquivalent(resolved.name, packageName)) {\n if (semver.gt(resolved.version, highestVersion)) {\n highestVersion = resolved.version;\n }\n }\n }\n \n // Get the highest required version from all specified versions for this package\n if (requiredVersions && requiredVersions.has(packageName)) {\n const versions = requiredVersions.get(packageName)!;\n for (const version of versions) {\n if (!highestRequiredVersion || semver.gt(version, highestRequiredVersion)) {\n highestRequiredVersion = version;\n }\n }\n }\n \n return { highestVersion, requiredVersion: highestRequiredVersion };\n}\n\n/**\n * Check if a package name refers to an existing path/git-based dependency in openpackage.yml\n * Returns the dependency source if found, null otherwise\n */\nexport async function findExistingPathOrGitSource(\n cwd: string,\n packageName: string\n): Promise<\n | { type: 'path'; path: string }\n | { type: 'git'; url: string; ref?: string; subdir?: string }\n | null\n> {\n const packageYmlPath = getLocalPackageYmlPath(cwd);\n if (!(await exists(packageYmlPath))) {\n return null;\n }\n\n const config = await parsePackageYml(packageYmlPath);\n const allDeps = [...(config.dependencies || []), ...(config['dev-dependencies'] || [])];\n \n const dep = allDeps.find(d => arePackageNamesEquivalent(d.name, packageName));\n if (!dep) {\n return null;\n }\n\n // Handle both new (url) and legacy (git) fields\n if (dep.url || dep.git) {\n const gitUrlRaw = dep.url || dep.git!;\n \n // Parse url field to extract ref if embedded\n const [gitUrl, embeddedRef] = gitUrlRaw.includes('#') \n ? gitUrlRaw.split('#', 2)\n : [gitUrlRaw, undefined];\n \n // Use embedded ref if present, otherwise fall back to separate ref field\n const ref = embeddedRef || dep.ref;\n \n return { type: 'git', url: gitUrl, ref, subdir: dep.path };\n }\n\n if (dep.path) {\n return { type: 'path', path: dep.path };\n }\n\n return null;\n}\n", "import type { InstallVersionSelectionResult } from './version-selection.js';\nimport type { PackageRemoteResolutionOutcome, InstallResolutionMode } from './types.js';\n\nexport function buildNoVersionFoundError(\n packageName: string,\n constraint: string,\n selection: InstallVersionSelectionResult['selection'],\n mode: InstallResolutionMode\n): Error {\n const stableList = formatVersionList(selection.availableStable);\n const prereleaseList = formatVersionList(selection.availablePrerelease);\n const suggestions = [\n 'Edit .openpackage/openpackage.yml or adjust the CLI range, then retry.',\n 'Create a new package version locally using opkg new.'\n ];\n\n if (mode === 'local-only') {\n suggestions.push('Re-run without --local to include remote versions in resolution.');\n }\n\n const message = [\n `No version of '${packageName}' satisfies '${constraint}'.`,\n `Available stable versions: ${stableList}`,\n `Available WIP/pre-release versions: ${prereleaseList}`,\n 'Suggested next steps:',\n ...suggestions.map(suggestion => ` \u2022 ${suggestion}`)\n ].join('\\n');\n\n return new Error(message);\n}\n\nexport function formatVersionList(versions: string[]): string {\n if (!versions || versions.length === 0) {\n return 'none';\n }\n return versions.join(', ');\n}\n\nexport function mapReasonLabelToOutcome(\n reasonLabel: string\n): PackageRemoteResolutionOutcome['reason'] {\n switch (reasonLabel) {\n case 'not found in remote registry':\n case 'not found in registry':\n return 'not-found';\n case 'access denied':\n return 'access-denied';\n case 'network error':\n return 'network';\n case 'integrity check failed':\n return 'integrity';\n default:\n return 'unknown';\n }\n}\n\n", "import type { RemotePackageMetadataSuccess, RemoteBatchPullResult, RemotePullFailure } from '../remote-pull.js';\nimport type { ResolvedPackage } from '../dependency-resolver/types.js';\nimport type { PackageRemoteResolutionOutcome } from './types.js';\nimport {\n fetchRemotePackageMetadata,\n pullDownloadsBatchFromRemote,\n aggregateRecursiveDownloads,\n parseDownloadIdentifier,\n isPartialDownload\n} from '../remote-pull.js';\nimport { packageManager } from '../package.js';\nimport { getVersionInfoFromDependencyTree } from './install-helpers.js';\n\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput } from '../ports/resolve.js';\nimport { computeMissingDownloadKeys, createDownloadKey } from './download-keys.js';\nimport { extractRemoteErrorReason } from '../../utils/error-reasons.js';\nimport { recordBatchOutcome } from './remote-reporting.js';\nimport { mapReasonLabelToOutcome } from './install-errors.js';\n\nfunction extractReasonFromFailure(failure: RemotePullFailure): string {\n switch (failure.reason) {\n case 'not-found':\n return 'not found in remote registry';\n case 'access-denied':\n return 'access denied';\n case 'network':\n return 'network error';\n case 'integrity':\n return 'integrity check failed';\n default:\n return failure.message ? extractRemoteErrorReason(failure.message) : 'unknown error';\n }\n}\n\n/**\n * Fetch metadata for missing dependencies\n */\nexport async function fetchMissingDependencyMetadata(\n missing: string[],\n resolvedPackages: ResolvedPackage[],\n opts: {\n dryRun: boolean;\n profile?: string;\n apiKey?: string;\n alreadyWarnedPackages?: Set<string>;\n onFailure?: (name: string, failure: RemotePullFailure) => void;\n },\n output?: OutputPort\n): Promise<RemotePackageMetadataSuccess[]> {\n const out = output ?? resolveOutput();\n const { dryRun, alreadyWarnedPackages } = opts;\n const uniqueMissing = Array.from(new Set(missing));\n const metadataResults: RemotePackageMetadataSuccess[] = [];\n\n const metadataSpinner = dryRun ? null : out.spinner();\n if (metadataSpinner) metadataSpinner.start(`Fetching metadata for ${uniqueMissing.length} missing package(s)...`);\n\n try {\n for (const missingName of uniqueMissing) {\n let requiredVersion: string | undefined;\n try {\n const versionInfo = await getVersionInfoFromDependencyTree(missingName, resolvedPackages);\n requiredVersion = versionInfo.requiredVersion;\n } catch (error) {\n // Failed to determine required version, continue without it\n }\n\n const metadataResult = await fetchRemotePackageMetadata(missingName, requiredVersion, { recursive: true, profile: opts.profile, apiKey: opts.apiKey });\n if (!metadataResult.success) {\n // Skip warning if we already warned about this package during resolution\n if (!alreadyWarnedPackages?.has(missingName)) {\n const packageLabel = requiredVersion ? `${missingName}@${requiredVersion}` : missingName;\n const reason = extractReasonFromFailure(metadataResult);\n // Avoid garbled output by stopping the spinner before printing\n // warning messages, since the spinner writes to the same stdout line.\n if (metadataSpinner) {\n metadataSpinner.stop();\n }\n out.warn(`Remote pull failed for \\`${packageLabel}\\` (reason: ${reason})`);\n }\n opts.onFailure?.(missingName, metadataResult);\n continue;\n }\n\n metadataResults.push(metadataResult);\n }\n } finally {\n if (metadataSpinner) metadataSpinner.stop();\n }\n\n return metadataResults;\n}\n\n/**\n * Pull missing dependencies from remote\n */\nexport async function pullMissingDependencies(\n metadata: RemotePackageMetadataSuccess[],\n keysToDownload: Set<string>,\n opts: { dryRun: boolean; profile?: string; apiKey?: string },\n output?: OutputPort\n): Promise<RemoteBatchPullResult[]> {\n const out = output ?? resolveOutput();\n const { dryRun } = opts;\n const batchResults: RemoteBatchPullResult[] = [];\n const warnings: string[] = [];\n\n if (keysToDownload.size > 0 || dryRun) {\n const spinner = dryRun ? null : out.spinner();\n if (spinner) spinner.start(`Pulling ${keysToDownload.size} missing dependency package(s) from remote...`);\n\n try {\n const remainingKeys = new Set(keysToDownload);\n\n for (const metadataResult of metadata) {\n if (!dryRun && remainingKeys.size === 0) {\n break;\n }\n\n const batchResult = await pullDownloadsBatchFromRemote(metadataResult.response, {\n httpClient: metadataResult.context.httpClient,\n profile: opts.profile || metadataResult.context.profile,\n apiKey: opts.apiKey,\n dryRun,\n filter: (dependencyName, dependencyVersion) => {\n const key = createDownloadKey(dependencyName, dependencyVersion);\n if (!keysToDownload.has(key)) {\n return false;\n }\n\n if (dryRun) {\n return true;\n }\n\n if (!remainingKeys.has(key)) {\n return false;\n }\n\n remainingKeys.delete(key);\n return true;\n }\n });\n\n batchResults.push(batchResult);\n }\n } finally {\n if (spinner) spinner.stop();\n }\n }\n\n return batchResults;\n}\n\nexport function updateRemoteOutcomesFromBatch(\n batchResult: RemoteBatchPullResult,\n remoteOutcomes: Record<string, PackageRemoteResolutionOutcome>\n): void {\n if (!batchResult.failed || batchResult.failed.length === 0) {\n return;\n }\n\n for (const failure of batchResult.failed) {\n const reasonLabel = extractRemoteErrorReason(failure.error ?? 'Unknown error');\n const reasonTag = mapReasonLabelToOutcome(reasonLabel);\n const packageName = failure.name;\n const message = `Remote pull failed for \\`${packageName}\\` (reason: ${reasonLabel})`;\n\n remoteOutcomes[packageName] = {\n name: packageName,\n reason: reasonTag,\n message\n };\n }\n}\n\nfunction computeRetryEligibleMissing(\n names: string[],\n remoteOutcomes: Record<string, PackageRemoteResolutionOutcome>\n): string[] {\n return names.filter(name => {\n const outcome = remoteOutcomes[name];\n if (!outcome) {\n return true;\n }\n return outcome.reason !== 'not-found' && outcome.reason !== 'access-denied';\n });\n}\n\nexport interface PullMissingDependenciesContext {\n missingPackages: string[];\n resolvedPackages: ResolvedPackage[];\n remoteOutcomes: Record<string, PackageRemoteResolutionOutcome>;\n warnedPackages: Set<string>;\n dryRun: boolean;\n profile?: string;\n apiKey?: string;\n}\n\nexport interface PullMissingDependenciesResult {\n pulledAny: boolean;\n warnings: string[];\n}\n\nexport async function pullMissingDependenciesIfNeeded(\n context: PullMissingDependenciesContext\n): Promise<PullMissingDependenciesResult> {\n const retryEligibleMissing = computeRetryEligibleMissing(context.missingPackages, context.remoteOutcomes);\n if (retryEligibleMissing.length === 0) {\n return { pulledAny: false, warnings: [] };\n }\n\n const metadataResults = await fetchMissingDependencyMetadata(retryEligibleMissing, context.resolvedPackages, {\n dryRun: context.dryRun,\n profile: context.profile,\n apiKey: context.apiKey,\n alreadyWarnedPackages: context.warnedPackages,\n onFailure: (name, failure) => {\n context.remoteOutcomes[name] = {\n name,\n reason: failure.reason,\n message: failure.message ?? `Remote pull failed for \\`${name}\\``\n };\n }\n });\n\n if (metadataResults.length === 0) {\n return { pulledAny: false, warnings: [] };\n }\n\n const keysToDownload = new Set<string>();\n for (const metadata of metadataResults) {\n const aggregated = aggregateRecursiveDownloads([metadata.response]);\n const missingKeys = await computeMissingDownloadKeys(aggregated);\n missingKeys.forEach(key => keysToDownload.add(key));\n }\n\n const batchResults = await pullMissingDependencies(metadataResults, keysToDownload, {\n dryRun: context.dryRun,\n profile: context.profile,\n apiKey: context.apiKey\n });\n\n const warnings: string[] = [];\n for (const batchResult of batchResults) {\n recordBatchOutcome('Pulled dependencies', batchResult, warnings, context.dryRun);\n updateRemoteOutcomesFromBatch(batchResult, context.remoteOutcomes);\n }\n\n return { pulledAny: metadataResults.length > 0, warnings };\n}\n\n\n", "/**\n * Legacy Recursive Dependency Resolver\n * \n * @deprecated This module is deprecated for new code. Use DependencyResolutionExecutor\n * from '../install/resolution/executor.js' for recursive dependency resolution.\n * \n * This function is still used by the unified pipeline for single-package installs\n * and will be migrated in a future release.\n */\n\nimport * as yaml from 'js-yaml';\nimport * as semver from 'semver';\nimport { resolve, dirname } from 'path';\nimport { PackageYml, Package } from '../../types/index.js';\nimport { packageManager } from '../package.js';\nimport { getInstalledPackageVersion } from '../openpackage.js';\nimport { logger } from '../../utils/logger.js';\nimport { PackageNotFoundError, VersionConflictError } from '../../utils/errors.js';\nimport { hasExplicitPrereleaseIntent } from '../../utils/version-ranges.js';\nimport { listPackageVersions, getLatestPackageVersion, findPackageByName, hasPackageVersion } from '../directory.js';\nimport { selectInstallVersionUnified } from '../install/version-selection.js';\nimport { InstallResolutionMode, type PackageRemoteResolutionOutcome } from '../install/types.js';\nimport { extractRemoteErrorReason } from '../../utils/error-reasons.js';\nimport { PACKAGE_PATHS } from '../../constants/index.js';\nimport { loadPackageFromPath } from '../install/path-package-loader.js';\nimport { loadPackageFromGit } from '../install/git-package-loader.js';\nimport {\n resolveCandidateVersionsForInstall,\n type CandidateVersionsResult,\n maybeWarnHigherRegistryVersion,\n resolvePackageContentRoot\n} from '../install/local-source-resolution.js';\nimport type { ResolvedPackage } from './types.js';\nimport { promptOverwrite } from './prompts.js';\n\ninterface DependencyResolverOptions {\n mode?: InstallResolutionMode;\n profile?: string;\n apiKey?: string;\n onWarning?: (message: string) => void;\n skipCache?: boolean; // Force fresh git clones (for --remote flag)\n}\n\nexport interface ResolveDependenciesResult {\n resolvedPackages: ResolvedPackage[];\n missingPackages: string[];\n remoteOutcomes?: Record<string, PackageRemoteResolutionOutcome>;\n}\n\n/**\n * Recursively resolve package dependencies for installation\n * \n * @deprecated This function is part of the legacy dependency resolver.\n * Consider using the modular dependency resolution utilities from\n * `./dependency-resolver/` for new code. This function will be refactored\n * in a future release.\n */\nexport async function resolveDependencies(\n packageName: string,\n targetDir: string,\n isRoot: boolean = true,\n visitedStack: Set<string> = new Set(),\n resolvedPackages: Map<string, ResolvedPackage> = new Map(),\n version?: string,\n requiredVersions: Map<string, string[]> = new Map(),\n globalConstraints?: Map<string, string[]>,\n rootOverrides?: Map<string, string[]>,\n resolverOptions: DependencyResolverOptions = {},\n remoteOutcomes: Map<string, PackageRemoteResolutionOutcome> = new Map(),\n currentPackageSourcePath?: string // Path to the package that declared this dependency (for resolving relative paths)\n): Promise<ResolveDependenciesResult> {\n // Track missing dependencies for this invocation subtree\n const missing = new Set<string>();\n const resolutionMode: InstallResolutionMode = resolverOptions.mode ?? 'local-only';\n\n // 1. Cycle detection\n if (visitedStack.has(packageName)) {\n const cycle = Array.from(visitedStack);\n const cycleStart = cycle.indexOf(packageName);\n const actualCycle = cycle.slice(cycleStart).concat([packageName]);\n const warning =\n `Circular dependency detected:\\n` +\n ` ${actualCycle.join(' \u2192 ')}\\n` +\n `\uD83D\uDCA1 Review your package dependencies to break the cycle.\\n` +\n ` (The cycle will be skipped for this install run.)`;\n // Surface as a warning via logger and resolver callback, but do NOT mark the\n // package as missing. This keeps the install flow running without falsely\n // reporting the root package as a missing dependency.\n logger.warn(warning);\n if (resolverOptions.onWarning) {\n resolverOptions.onWarning(warning);\n }\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n \n // 1.5. Check if already resolved (e.g., from path/git source)\n // This avoids expensive version resolution, remote lookups, and package loading\n // for packages that have already been resolved (e.g., path-based installs)\n const alreadyResolved = resolvedPackages.get(packageName);\n if (alreadyResolved) {\n logger.debug(`Package '${packageName}' already resolved to v${alreadyResolved.version} from ${alreadyResolved.source || 'unknown'}, validating constraints`);\n \n // Still need to validate version constraints even for pre-resolved packages\n // Gather all constraints for this package\n let allRanges: string[] = [];\n if (rootOverrides?.has(packageName)) {\n allRanges = [...(rootOverrides.get(packageName)!)];\n } else {\n if (version) allRanges.push(version);\n const globalRanges = globalConstraints?.get(packageName);\n if (globalRanges) allRanges.push(...globalRanges);\n const priorRanges = requiredVersions.get(packageName) || [];\n if (priorRanges.length > 0) allRanges.push(...priorRanges);\n }\n \n const dedupedRanges = Array.from(new Set(allRanges));\n const normalizedRanges = dedupedRanges.map(r => r.trim()).filter(Boolean);\n const isWildcardRange = (range: string) => {\n const normalized = range.toLowerCase();\n return normalized === '*' || normalized === 'latest';\n };\n const constraintRanges = normalizedRanges.filter(range => !isWildcardRange(range));\n \n // Validate existing version against constraints\n if (constraintRanges.length > 0) {\n const existingVersion = alreadyResolved.version;\n const allSatisfied = constraintRanges.every(range => {\n try {\n return semver.satisfies(existingVersion, range, { includePrerelease: true });\n } catch (error) {\n logger.debug(\n `Failed to evaluate semver for ${packageName}@${existingVersion} against range '${range}': ${error}`\n );\n return false;\n }\n });\n \n if (!allSatisfied) {\n // Version conflict with pre-resolved package\n const sourceDescription = alreadyResolved.source === 'path' ? 'local path' :\n alreadyResolved.source === 'git' ? 'git repository' :\n alreadyResolved.source || 'unknown source';\n const conflictMessage = `Package '${packageName}' was resolved to version ${existingVersion} (from ${sourceDescription}) but other dependencies require: ${constraintRanges.join(', ')}`;\n logger.error(conflictMessage);\n throw new VersionConflictError(packageName, {\n ranges: constraintRanges,\n availableVersions: [existingVersion]\n });\n }\n \n logger.debug(`Package '${packageName}' v${existingVersion} satisfies constraints: ${constraintRanges.join(', ')}`);\n }\n \n // Track required version if specified\n if (version) {\n if (!requiredVersions.has(packageName)) {\n requiredVersions.set(packageName, []);\n }\n requiredVersions.get(packageName)!.push(version);\n }\n \n // Constraints satisfied - process dependencies without re-loading package\n const pkg = alreadyResolved.pkg;\n const packageYmlFile =\n pkg.files.find(f => f.path === PACKAGE_PATHS.MANIFEST_RELATIVE) ||\n pkg.files.find(f => f.path === 'openpackage.yml');\n \n if (packageYmlFile) {\n const config = yaml.load(packageYmlFile.content) as PackageYml;\n \n // Recursively resolve dependencies\n visitedStack.add(packageName);\n \n // Only process 'dependencies' array (NOT 'dev-dependencies' for transitive dependencies)\n const dependencies = config.dependencies || [];\n \n // Determine the source directory for resolving relative paths\n const baseDir = currentPackageSourcePath ? dirname(currentPackageSourcePath) : targetDir;\n\n const resolveLocalPackage = async (\n pkg: Package,\n sourceType: 'git' | 'path',\n sourcePath: string,\n requiredRange?: string\n ) => {\n if (!resolvedPackages.has(pkg.metadata.name)) {\n resolvedPackages.set(pkg.metadata.name, {\n name: pkg.metadata.name,\n version: pkg.metadata.version || '0.0.0',\n pkg: pkg,\n isRoot: false,\n source: sourceType,\n contentRoot: sourcePath,\n requiredVersion: pkg.metadata.version,\n requiredRange\n });\n\n const child = await resolveDependencies(\n pkg.metadata.name,\n targetDir,\n false,\n visitedStack,\n resolvedPackages,\n pkg.metadata.version,\n requiredVersions,\n globalConstraints,\n rootOverrides,\n resolverOptions,\n remoteOutcomes,\n sourcePath\n );\n for (const m of child.missingPackages) missing.add(m);\n }\n };\n\n const processDependencyEntry = async (dep: any) => {\n // Git-based dependency - handle both new (url) and legacy (git) fields\n if (dep.url || dep.git) {\n const gitUrlRaw = dep.url || dep.git!;\n \n try {\n // Parse url field to extract ref if embedded\n const [gitUrl, embeddedRef] = gitUrlRaw.includes('#') \n ? gitUrlRaw.split('#', 2)\n : [gitUrlRaw, undefined];\n \n // Use embedded ref if present, otherwise fall back to separate ref field\n const ref = embeddedRef || dep.ref;\n \n const result = await loadPackageFromGit({\n url: gitUrl,\n ref,\n skipCache: resolverOptions.skipCache\n });\n if (result.isMarketplace) {\n logger.error(`Dependency '${dep.name}' points to a Claude Code plugin marketplace, which cannot be used as a dependency`);\n missing.add(dep.name);\n return;\n }\n await resolveLocalPackage(result.pkg!, 'git', result.sourcePath, dep.version);\n } catch (error) {\n logger.error(`Failed to load git-based dependency '${dep.name}' from '${gitUrlRaw}': ${error}`);\n missing.add(dep.name);\n }\n } else if (dep.path) {\n // Resolve path relative to the current package's location\n const resolvedPath = resolve(baseDir, dep.path);\n \n try {\n // Load package from path\n const pathPackage = await loadPackageFromPath(resolvedPath);\n await resolveLocalPackage(pathPackage, 'path', resolvedPath, dep.version);\n } catch (error) {\n logger.error(`Failed to load path-based dependency '${dep.name}' from '${dep.path}': ${error}`);\n missing.add(dep.name);\n }\n } else {\n // Standard registry-based dependency resolution\n const child = await resolveDependencies(\n dep.name,\n targetDir,\n false,\n visitedStack,\n resolvedPackages,\n dep.version,\n requiredVersions,\n globalConstraints,\n rootOverrides,\n resolverOptions,\n remoteOutcomes\n );\n for (const m of child.missingPackages) missing.add(m);\n }\n };\n \n // Process regular packages\n for (const dep of dependencies) {\n await processDependencyEntry(dep);\n }\n \n // For root package, also process dev-dependencies\n if (isRoot) {\n const devDependencies = config['dev-dependencies'] || [];\n for (const dep of devDependencies) {\n await processDependencyEntry(dep);\n }\n }\n \n visitedStack.delete(packageName);\n }\n \n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n \n // 2. Resolve version range(s) to specific version if needed\n let resolvedVersion: string | undefined;\n let versionRange: string | undefined;\n // Track where the final selected version came from for UX purposes\n let resolutionSource: 'local' | 'remote' | undefined;\n\n // Precedence: root overrides (from root openpackage.yml) > combined constraints\n let allRanges: string[] = [];\n\n if (rootOverrides?.has(packageName)) {\n // Root openpackage.yml versions act as authoritative overrides\n allRanges = [...(rootOverrides.get(packageName)!)];\n } else {\n // No root override - combine all constraints\n if (version) {\n allRanges.push(version);\n }\n const globalRanges = globalConstraints?.get(packageName);\n if (globalRanges) {\n allRanges.push(...globalRanges);\n }\n const priorRanges = requiredVersions.get(packageName) || [];\n if (priorRanges.length > 0) {\n allRanges.push(...priorRanges);\n }\n }\n\n const dedupedRanges = Array.from(new Set(allRanges));\n const normalizedRanges = dedupedRanges.map(r => r.trim()).filter(Boolean);\n const isWildcardRange = (range: string) => {\n const normalized = range.toLowerCase();\n return normalized === '*' || normalized === 'latest';\n };\n const constraintRanges = normalizedRanges.filter(range => !isWildcardRange(range));\n const hasConstraints = constraintRanges.length > 0;\n const combinedRangeLabel = hasConstraints ? constraintRanges.join(' & ') : undefined;\n\n const filterAvailableVersions = (versions: string[]): string[] => {\n if (!hasConstraints) {\n return versions;\n }\n\n return versions.filter(versionCandidate => {\n return constraintRanges.every(range => {\n try {\n return semver.satisfies(versionCandidate, range, { includePrerelease: true });\n } catch (error) {\n logger.debug(\n `Failed to evaluate semver for ${packageName}@${versionCandidate} against range '${range}': ${error}`\n );\n return false;\n }\n });\n });\n };\n\n const localSources: CandidateVersionsResult = await resolveCandidateVersionsForInstall({\n cwd: targetDir,\n packageName,\n mode: resolutionMode\n });\n\n const mutableSourceVersion =\n localSources.sourceKind === 'workspaceMutable' || localSources.sourceKind === 'globalMutable'\n ? localSources.localVersions[0]\n : null;\n if (mutableSourceVersion && constraintRanges.length > 0) {\n const satisfies = constraintRanges.every(range =>\n semver.satisfies(mutableSourceVersion, range, { includePrerelease: true })\n );\n if (!satisfies) {\n throw new VersionConflictError(packageName, {\n ranges: constraintRanges,\n availableVersions: [mutableSourceVersion]\n });\n }\n }\n\n const localVersions = localSources.localVersions;\n const explicitPrereleaseIntent = allRanges.some(range => hasExplicitPrereleaseIntent(range));\n\n let selectionResult;\n try {\n selectionResult = await selectInstallVersionUnified({\n packageName,\n constraint: '*',\n mode: resolutionMode,\n explicitPrereleaseIntent,\n profile: resolverOptions.profile,\n apiKey: resolverOptions.apiKey,\n localVersions,\n filterAvailableVersions\n });\n } catch (error) {\n // In default (local-first with remote fallback) mode, a failure here almost\n // always means that remote metadata lookup failed (e.g. network error,\n // unreachable registry) while trying to fall back to remote. For local-first\n // semantics we should treat this as \"remote unavailable\" and continue with a\n // best-effort local resolution by marking this package as missing instead of\n // aborting the entire install.\n if (resolutionMode === 'default') {\n const message = error instanceof Error ? error.message : String(error);\n const reason = extractRemoteErrorReason(message);\n const warning = `Remote pull failed for \\`${packageName}\\` (reason: ${reason})`;\n\n logger.warn(warning);\n if (resolverOptions.onWarning) {\n resolverOptions.onWarning(warning);\n }\n\n let outcomeReason: PackageRemoteResolutionOutcome['reason'] = 'unknown';\n if (error && typeof error === 'object' && 'failure' in error && error.failure) {\n outcomeReason = (error.failure as { reason: PackageRemoteResolutionOutcome['reason'] }).reason;\n }\n remoteOutcomes.set(packageName, {\n name: packageName,\n reason: outcomeReason,\n message: warning\n });\n\n missing.add(packageName);\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n\n // For non-default modes (e.g. remote-primary), remote metadata is required\n // and failures should still be treated as fatal.\n throw error;\n }\n\n if (selectionResult.sources.warnings.length > 0 && resolverOptions.onWarning) {\n selectionResult.sources.warnings.forEach(resolverOptions.onWarning);\n }\n\n const filteredAvailable = filterAvailableVersions(selectionResult.sources.availableVersions);\n\n if (!selectionResult.selectedVersion) {\n if (filteredAvailable.length > 0) {\n throw new VersionConflictError(packageName, {\n ranges: allRanges,\n availableVersions: selectionResult.sources.availableVersions\n });\n } else {\n missing.add(packageName);\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n } else {\n resolvedVersion = selectionResult.selectedVersion;\n }\n\n versionRange = combinedRangeLabel;\n resolutionSource =\n selectionResult.resolutionSource ?? (resolutionMode === 'remote-primary' ? 'remote' : 'local');\n logger.debug(\n `Resolved constraints [${allRanges.join(', ')}] to '${resolvedVersion}' for package '${packageName}'`\n );\n\n const higherLocalWarning = await maybeWarnHigherRegistryVersion({\n packageName,\n selectedVersion: resolvedVersion\n });\n if (higherLocalWarning) {\n logger.warn(`\u26A0\uFE0F ${higherLocalWarning}`);\n if (resolverOptions.onWarning) {\n resolverOptions.onWarning(`\u26A0\uFE0F ${higherLocalWarning}`);\n }\n }\n\n if (!hasConstraints) {\n versionRange = undefined;\n }\n\n // 3. Attempt to repair dependency from local registry\n let pkg: Package;\n const contentRoot =\n localSources.contentRoot ??\n (await resolvePackageContentRoot({\n cwd: targetDir,\n packageName,\n version: resolvedVersion\n }));\n try {\n // Load package with resolved version\n logger.debug(`Attempting to load package '${packageName}' from local registry`, {\n version: resolvedVersion,\n originalRange: versionRange\n });\n pkg = await packageManager.loadPackage(packageName, resolvedVersion, { packageRootDir: contentRoot });\n logger.debug(`Successfully loaded package '${packageName}' from local registry`, {\n version: pkg.metadata.version\n });\n } catch (error) {\n if (error instanceof PackageNotFoundError) {\n // Auto-repair attempt: Check if package exists in registry but needs to be loaded\n logger.debug(`Package '${packageName}' not found in local registry, attempting repair`);\n\n try {\n // Check if package exists in registry (but files might be missing)\n // First try direct lookup (works for normalized names)\n let hasPackage = await getLatestPackageVersion(packageName) !== null;\n if (!hasPackage) {\n // If not found, try case-insensitive lookup\n const foundPackage = await findPackageByName(packageName);\n hasPackage = foundPackage !== null;\n }\n logger.debug(`Registry check for '${packageName}': hasPackage=${hasPackage}, requiredVersion=${version}`);\n\n if (hasPackage) {\n // Check if the resolved version exists (use resolvedVersion if available, otherwise fall back to version)\n const versionToCheck = resolvedVersion || version;\n if (versionToCheck) {\n const hasSpecificVersion = await hasPackageVersion(packageName, versionToCheck);\n if (!hasSpecificVersion) {\n // Package exists but not in the required/resolved version - treat as a missing dependency\n const dependencyChain = Array.from(visitedStack);\n const versionDisplay = versionRange || version || resolvedVersion;\n let warningMessage = `Package '${packageName}' exists in registry but version '${versionDisplay}' is not available\\n\\n`;\n\n if (dependencyChain.length > 0) {\n warningMessage += `\u2713 Dependency chain:\\n`;\n for (let i = 0; i < dependencyChain.length; i++) {\n const indent = ' '.repeat(i);\n warningMessage += `${indent}\u2514\u2500 ${dependencyChain[i]}\\n`;\n }\n warningMessage += `${' '.repeat(dependencyChain.length)}\u2514\u2500 ${packageName}@${versionDisplay} \u274C (version not available)\\n\\n`;\n }\n\n warningMessage += `\uD83D\uDCA1 To resolve this issue:\\n`;\n warningMessage += ` \u2022 Install the available version: opkg install ${packageName}@latest\\n`;\n warningMessage += ` \u2022 Update the dependency in openpackage.yml to use an available version\\n`;\n\n // Surface as warning but do NOT abort the entire install \u2013 mark as missing instead.\n logger.warn(warningMessage);\n if (resolverOptions.onWarning) {\n resolverOptions.onWarning(warningMessage);\n }\n\n missing.add(packageName);\n return {\n resolvedPackages: Array.from(resolvedPackages.values()),\n missingPackages: Array.from(missing)\n };\n }\n }\n\n logger.info(`Found package '${packageName}' in registry, attempting repair`);\n // Attempt to load again with the resolved version - this might succeed if it was a temporary issue\n pkg = await packageManager.loadPackage(packageName, resolvedVersion || version, {\n packageRootDir: contentRoot\n });\n logger.info(`Successfully repaired and loaded package '${packageName}'`);\n } else {\n // Package truly doesn't exist - treat as missing dependency\n missing.add(packageName);\n return {\n resolvedPackages: Array.from(resolvedPackages.values()),\n missingPackages: Array.from(missing)\n };\n }\n } catch (repairError) {\n // Repair failed - treat as missing dependency instead of aborting the whole install flow\n const remoteOutcome = remoteOutcomes.get(packageName);\n const derivedReason = remoteOutcome ? formatRemoteOutcomeReason(remoteOutcome) : null;\n const fallbackReason = extractRemoteErrorReason(String(repairError));\n const reason = derivedReason ?? fallbackReason;\n if (remoteOutcome) {\n const warning = `Remote pull failed for \\`${packageName}\\` (reason: ${reason})`;\n logger.warn(warning);\n if (resolverOptions.onWarning) {\n resolverOptions.onWarning(warning);\n }\n } else {\n // Warning suppressed until remote outcome available\n }\n\n missing.add(packageName);\n return {\n resolvedPackages: Array.from(resolvedPackages.values()),\n missingPackages: Array.from(missing)\n };\n }\n } else {\n // Re-throw other errors\n throw error;\n }\n }\n\n // Use the resolved version (from directory name) rather than metadata version\n // This ensures WIP packages use their full version string (e.g., 1.0.0-000fz8.a3k)\n // instead of the base version from openpackage.yml (e.g., 1.0.0)\n const currentVersion = resolvedVersion;\n if (!currentVersion) {\n throw new Error(`Resolved version is undefined for package ${packageName}`);\n }\n \n // 3. Check for existing resolution\n const existing = resolvedPackages.get(packageName);\n if (existing) {\n const comparison = semver.compare(currentVersion, existing.version);\n \n if (comparison > 0) {\n // Current version is newer - prompt to overwrite\n const shouldOverwrite = await promptOverwrite(packageName, existing.version, currentVersion);\n if (shouldOverwrite) {\n existing.version = currentVersion;\n existing.pkg = pkg;\n existing.conflictResolution = 'overwritten';\n } else {\n existing.conflictResolution = 'skipped';\n }\n } else {\n // Existing version is same or newer - keep existing\n existing.conflictResolution = 'kept';\n }\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n \n // 3.1. Check for already installed version in openpackage\n const installedVersion = await getInstalledPackageVersion(packageName, targetDir);\n if (installedVersion) {\n const comparison = semver.compare(currentVersion, installedVersion);\n \n if (comparison > 0) {\n // New version is greater than installed - allow installation but will prompt later\n logger.debug(`Package '${packageName}' will be upgraded from v${installedVersion} to v${currentVersion}`);\n } else if (comparison === 0) {\n // Same version - skip installation\n logger.debug(`Package '${packageName}' v${currentVersion} already installed, skipping`);\n resolvedPackages.set(packageName, {\n name: packageName,\n version: installedVersion,\n pkg,\n isRoot,\n contentRoot, // Track content root for consistent access\n conflictResolution: 'kept'\n });\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n } else {\n // New version is older than installed - skip installation\n logger.debug(`Package '${packageName}' has newer version installed (v${installedVersion} > v${currentVersion}), skipping`);\n resolvedPackages.set(packageName, {\n name: packageName,\n version: installedVersion,\n pkg,\n isRoot,\n contentRoot, // Track content root for consistent access\n conflictResolution: 'kept'\n });\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n }\n }\n \n // 4. Track required version if specified\n if (version) {\n if (!requiredVersions.has(packageName)) {\n requiredVersions.set(packageName, []);\n }\n requiredVersions.get(packageName)!.push(version);\n }\n\n // 5. Add to resolved map\n resolvedPackages.set(packageName, {\n name: packageName,\n version: currentVersion,\n pkg,\n isRoot,\n source: resolutionSource ?? 'local',\n contentRoot, // Track content root for workspace/global mutable sources\n requiredVersion: resolvedVersion, // Track the resolved version\n requiredRange: versionRange // Track the original range\n });\n \n // 5. Parse dependencies from package's openpackage.yml\n const packageYmlFile =\n pkg.files.find(f => f.path === PACKAGE_PATHS.MANIFEST_RELATIVE) ||\n pkg.files.find(f => f.path === 'openpackage.yml');\n if (packageYmlFile) {\n const config = yaml.load(packageYmlFile.content) as PackageYml;\n \n // 6. Recursively resolve dependencies\n visitedStack.add(packageName);\n \n // Only process 'dependencies' array (NOT 'dev-dependencies' for transitive dependencies)\n const dependencies = config.dependencies || [];\n \n // Determine the source directory for resolving relative paths\n // If currentPackageSourcePath is provided, use its directory; otherwise use targetDir\n const baseDir = currentPackageSourcePath ? dirname(currentPackageSourcePath) : targetDir;\n\n const resolveLocalPackage = async (\n pkg: Package,\n sourceType: 'git' | 'path',\n sourcePath: string,\n requiredRange?: string\n ) => {\n if (!resolvedPackages.has(pkg.metadata.name)) {\n resolvedPackages.set(pkg.metadata.name, {\n name: pkg.metadata.name,\n version: pkg.metadata.version || '0.0.0',\n pkg: pkg,\n isRoot: false,\n source: sourceType,\n contentRoot: sourcePath,\n requiredVersion: pkg.metadata.version,\n requiredRange\n });\n\n const child = await resolveDependencies(\n pkg.metadata.name,\n targetDir,\n false,\n visitedStack,\n resolvedPackages,\n pkg.metadata.version,\n requiredVersions,\n globalConstraints,\n rootOverrides,\n resolverOptions,\n remoteOutcomes,\n sourcePath\n );\n for (const m of child.missingPackages) missing.add(m);\n }\n };\n\n const processDependencyEntry = async (dep: any) => {\n // Git-based dependency - handle both new (url) and legacy (git) fields\n if (dep.url || dep.git) {\n const gitUrlRaw = dep.url || dep.git!;\n \n try {\n // Parse url field to extract ref if embedded\n const [gitUrl, embeddedRef] = gitUrlRaw.includes('#') \n ? gitUrlRaw.split('#', 2)\n : [gitUrlRaw, undefined];\n \n // Use embedded ref if present, otherwise fall back to separate ref field\n const ref = embeddedRef || dep.ref;\n \n const result = await loadPackageFromGit({\n url: gitUrl,\n ref,\n skipCache: resolverOptions.skipCache\n });\n if (result.isMarketplace) {\n logger.error(`Dependency '${dep.name}' points to a Claude Code plugin marketplace, which cannot be used as a dependency`);\n missing.add(dep.name);\n return;\n }\n await resolveLocalPackage(result.pkg!, 'git', result.sourcePath, dep.version);\n } catch (error) {\n logger.error(`Failed to load git-based dependency '${dep.name}' from '${gitUrlRaw}': ${error}`);\n missing.add(dep.name);\n }\n } else if (dep.path) {\n // Resolve path relative to the current package's location\n const resolvedPath = resolve(baseDir, dep.path);\n \n try {\n // Load package from path\n const pathPackage = await loadPackageFromPath(resolvedPath);\n await resolveLocalPackage(pathPackage, 'path', resolvedPath, dep.version);\n } catch (error) {\n logger.error(`Failed to load path-based dependency '${dep.name}' from '${dep.path}': ${error}`);\n missing.add(dep.name);\n }\n } else {\n // Standard registry-based dependency resolution\n const child = await resolveDependencies(\n dep.name,\n targetDir,\n false,\n visitedStack,\n resolvedPackages,\n dep.version,\n requiredVersions,\n globalConstraints,\n rootOverrides,\n resolverOptions,\n remoteOutcomes\n );\n for (const m of child.missingPackages) missing.add(m);\n }\n };\n \n // Process regular packages\n for (const dep of dependencies) {\n await processDependencyEntry(dep);\n }\n \n // For root package, also process dev-dependencies\n if (isRoot) {\n const devDependencies = config['dev-dependencies'] || [];\n for (const dep of devDependencies) {\n await processDependencyEntry(dep);\n }\n }\n \n visitedStack.delete(packageName);\n\n }\n \n // Attach the requiredVersions map to each resolved package for later use\n const resolvedArray = Array.from(resolvedPackages.values());\n for (const resolved of resolvedArray) {\n (resolved as any).requiredVersions = requiredVersions;\n }\n return buildResolveResult(resolvedPackages, missing, remoteOutcomes);\n}\n\nfunction buildResolveResult(\n resolvedPackages: Map<string, ResolvedPackage>,\n missing: Set<string>,\n remoteOutcomes: Map<string, PackageRemoteResolutionOutcome>\n): ResolveDependenciesResult {\n const resolvedArray = Array.from(resolvedPackages.values());\n const outcomesRecord =\n remoteOutcomes.size > 0 ? Object.fromEntries(remoteOutcomes) : undefined;\n\n return {\n resolvedPackages: resolvedArray,\n missingPackages: Array.from(missing),\n remoteOutcomes: outcomesRecord\n };\n}\n\nfunction formatRemoteOutcomeReason(outcome: PackageRemoteResolutionOutcome): string {\n switch (outcome.reason) {\n case 'not-found':\n return 'not found in remote registry';\n case 'access-denied':\n return 'access denied';\n case 'network':\n return 'network error';\n case 'integrity':\n return 'integrity check failed';\n default:\n return extractRemoteErrorReason(outcome.message || 'unknown error');\n }\n}\n", "import { join } from 'path';\nimport { PackageYml, PackageDependency } from '../types/index.js';\nimport { parsePackageYml } from '../utils/package-yml.js';\nimport { exists, isDirectory, listDirectories } from '../utils/fs.js';\nimport { logger } from '../utils/logger.js';\nimport { FILE_PATTERNS } from '../constants/index.js';\nimport { DEFAULT_INSTALL_ROOT } from '../constants/workspace.js';\nimport { getLocalPackageYmlPath, getLocalPackagesDir } from '../utils/paths.js';\nimport { findFilesByExtension, findDirectoriesContainingFile } from '../utils/file-processing.js';\nimport { getDetectedPlatforms, getPlatformDefinition, type Platform } from './platforms.js';\nimport { arePackageNamesEquivalent } from '../utils/package-name.js';\n\n/**\n * Package metadata from openpackage directory\n */\nexport interface OpenPackagePackage {\n name: string;\n version?: string;\n description?: string;\n dependencies?: PackageDependency[];\n 'dev-dependencies'?: PackageDependency[];\n path: string;\n}\n\n/**\n * Find package config file in a directory.\n * Prefers v2 layout: <dir>/openpackage.yml, then <dir>/.openpackage/openpackage.yml (workspace-style).\n */\nasync function findPackageConfigFile(directoryPath: string): Promise<string | null> {\n const rootManifest = join(directoryPath, FILE_PATTERNS.OPENPACKAGE_YML);\n const workspaceManifest = getLocalPackageYmlPath(directoryPath);\n \n if (await exists(rootManifest)) {\n return rootManifest;\n } else if (await exists(workspaceManifest)) {\n return workspaceManifest;\n }\n \n return null;\n}\n\n/**\n * Get the version of an installed package by package name\n */\nexport async function getInstalledPackageVersion(packageName: string, targetDir: string): Promise<string | null> {\n const openpackagePath = join(targetDir, DEFAULT_INSTALL_ROOT);\n const packageOpenPackagePath = join(openpackagePath, packageName);\n \n if (!(await exists(packageOpenPackagePath))) {\n return null;\n }\n \n const configPath = await findPackageConfigFile(packageOpenPackagePath);\n if (!configPath) {\n return null;\n }\n \n try {\n const config = await parsePackageYml(configPath);\n return config.version ?? null;\n } catch (error) {\n logger.warn(`Failed to parse package config for ${packageName}: ${error}`);\n return null;\n }\n}\n\n/**\n * Find package directory in ai by matching package name\n */\nexport async function findPackageDirectory(openpackagePath: string, packageName: string): Promise<string | null> {\n if (!(await exists(openpackagePath)) || !(await isDirectory(openpackagePath))) {\n return null;\n }\n\n try {\n const subdirectories = await listDirectories(openpackagePath);\n \n for (const subdir of subdirectories) {\n const subdirPath = join(openpackagePath, subdir);\n const configPath = await findPackageConfigFile(subdirPath);\n \n if (configPath) {\n try {\n const packageConfig = await parsePackageYml(configPath);\n if (arePackageNamesEquivalent(packageConfig.name, packageName)) {\n return subdirPath;\n }\n } catch (error) {\n logger.warn(`Failed to parse package file ${configPath}: ${error}`);\n }\n }\n }\n \n return null;\n } catch (error) {\n logger.error(`Failed to search ai directory: ${error}`);\n return null;\n }\n}\n\n/**\n * Scan openpackage directory for all available packages\n */\nexport async function scanOpenPackagePackages(openpackagePath: string): Promise<Map<string, OpenPackagePackage>> {\n const packages = new Map<string, OpenPackagePackage>();\n\n if (!(await exists(openpackagePath)) || !(await isDirectory(openpackagePath))) {\n logger.debug('Install root directory not found or not a directory', { openpackagePath });\n return packages;\n }\n\n try {\n // Find all openpackage.yml files recursively under the packages directory\n const packagesDir = getLocalPackagesDir(openpackagePath);\n if (!(await exists(packagesDir))) {\n return packages;\n }\n\n const packageDirs = await findDirectoriesContainingFile(\n packagesDir,\n FILE_PATTERNS.OPENPACKAGE_YML,\n async (filePath) => {\n try {\n return await parsePackageYml(filePath);\n } catch (error) {\n logger.warn(`Failed to parse package file ${filePath}: ${error}`);\n return null;\n }\n }\n );\n\n for (const { dirPath, parsedContent } of packageDirs) {\n if (parsedContent) {\n const packageConfig = parsedContent;\n packages.set(packageConfig.name, {\n name: packageConfig.name,\n version: packageConfig.version,\n description: packageConfig.description,\n dependencies: packageConfig.dependencies || [],\n 'dev-dependencies': packageConfig['dev-dependencies'] || [],\n path: dirPath\n });\n }\n }\n } catch (error) {\n logger.error(`Failed to scan ai directory: ${error}`);\n }\n\n return packages;\n}\n\n/**\n * Gather version constraints from the main and cached package openpackage.yml files\n */\nexport async function gatherGlobalVersionConstraints(cwd: string, includeResolutions: boolean = true): Promise<Map<string, string[]>> {\n const constraints = new Map<string, Set<string>>();\n\n const addConstraint = (name?: string, range?: string) => {\n if (!name || !range) {\n return;\n }\n\n const trimmedName = name.trim();\n const trimmedRange = range.trim();\n\n if (!trimmedName || !trimmedRange) {\n return;\n }\n\n if (!constraints.has(trimmedName)) {\n constraints.set(trimmedName, new Set());\n }\n\n constraints.get(trimmedName)!.add(trimmedRange);\n };\n\n const collectFromConfig = (config: PackageYml | null | undefined) => {\n if (!config) {\n return;\n }\n\n config.dependencies?.forEach(dep => addConstraint(dep.name, dep.version));\n config['dev-dependencies']?.forEach(dep => addConstraint(dep.name, dep.version));\n };\n\n // Collect from main .openpackage/openpackage.yml if present\n const mainPackagePath = getLocalPackageYmlPath(cwd);\n if (await exists(mainPackagePath)) {\n try {\n const mainConfig = await parsePackageYml(mainPackagePath);\n collectFromConfig(mainConfig);\n } catch (error) {\n logger.debug(`Failed to parse main openpackage.yml for constraints: ${error}`);\n }\n }\n\n // Collect from each package under .openpackage/packages\n const packagesDir = getLocalPackagesDir(cwd);\n if (await exists(packagesDir) && await isDirectory(packagesDir)) {\n try {\n const packageDirs = await findDirectoriesContainingFile(\n packagesDir,\n FILE_PATTERNS.OPENPACKAGE_YML,\n async (filePath) => {\n try {\n return await parsePackageYml(filePath);\n } catch (error) {\n logger.debug(`Failed to parse openpackage.yml at ${filePath}: ${error}`);\n return null;\n }\n }\n );\n\n for (const { parsedContent } of packageDirs) {\n collectFromConfig(parsedContent);\n }\n } catch (error) {\n logger.debug(`Failed to enumerate packages directory for constraints: ${error}`);\n }\n }\n\n const result = new Map<string, string[]>();\n for (const [name, ranges] of constraints) {\n result.set(name, Array.from(ranges));\n }\n\n return result;\n}\n\n/**\n * Gather version constraints only from the main .openpackage/openpackage.yml\n * Used to treat root-declared versions as authoritative overrides\n */\nexport async function gatherRootVersionConstraints(cwd: string): Promise<Map<string, string[]>> {\n const result = new Map<string, string[]>();\n\n const addConstraint = (name?: string, range?: string) => {\n if (!name || !range) return;\n const trimmedName = name.trim();\n const trimmedRange = range.trim();\n if (!trimmedName || !trimmedRange) return;\n if (!result.has(trimmedName)) result.set(trimmedName, []);\n const arr = result.get(trimmedName)!;\n if (!arr.includes(trimmedRange)) arr.push(trimmedRange);\n };\n\n const mainPackagePath = getLocalPackageYmlPath(cwd);\n if (await exists(mainPackagePath)) {\n try {\n const mainConfig = await parsePackageYml(mainPackagePath);\n mainConfig.dependencies?.forEach(dep => addConstraint(dep.name, dep.version));\n mainConfig['dev-dependencies']?.forEach(dep => addConstraint(dep.name, dep.version));\n } catch (error) {\n logger.debug(`Failed to parse main openpackage.yml for root constraints: ${error}`);\n }\n }\n\n return result;\n}\n\n/**\n * Get package configuration\n */\nexport async function getOpenPackagePackageConfig(openpackagePath: string, packageName: string): Promise<PackageYml | null> {\n const packagePath = await findPackageDirectory(openpackagePath, packageName);\n if (!packagePath) {\n return null;\n }\n \n const configPath = await findPackageConfigFile(packagePath);\n if (!configPath) {\n return null;\n }\n \n try {\n return await parsePackageYml(configPath);\n } catch (error) {\n logger.warn(`Failed to parse package config for ${packageName}: ${error}`);\n return null;\n }\n}\n\n/**\n * Check for existing installed package by searching markdown files in ai, .claude, and .cursor directories\n */\nexport async function checkExistingPackageInMarkdownFiles(\n cwd: string, \n packageName: string\n): Promise<{ found: boolean; version?: string; location?: string }> {\n // Build search targets: ai directory + all detected platform subdirectories\n const targets: Array<{ dir: string; exts?: string[]; label: string }> = [];\n\n // Always include workspace install root\n targets.push({\n dir: join(cwd, DEFAULT_INSTALL_ROOT),\n exts: [FILE_PATTERNS.MD_FILES],\n label: DEFAULT_INSTALL_ROOT\n });\n\n // Add detected platforms' directories from flows\n try {\n const platforms = await getDetectedPlatforms(cwd);\n for (const platform of platforms) {\n const def = getPlatformDefinition(platform as Platform);\n \n // Extract directories from export flows (package \u2192 workspace)\n if (def.export && def.export.length > 0) {\n const platformDirs = new Set<string>();\n \n for (const flow of def.export) {\n const toPattern = typeof flow.to === 'string' ? flow.to : Object.keys(flow.to)[0];\n if (toPattern) {\n // Extract directory from pattern\n const parts = toPattern.split('/');\n if (parts.length > 1) {\n const fullPath = parts.slice(0, -1).join('/');\n platformDirs.add(fullPath);\n }\n }\n }\n \n // Add each unique directory as a target\n for (const dirPath of platformDirs) {\n const fullDirPath = join(cwd, dirPath);\n targets.push({ \n dir: fullDirPath, \n exts: undefined, // Allow all extensions (flows handle this)\n label: def.id \n });\n }\n }\n }\n } catch (error) {\n logger.debug(`Failed to build platform search targets: ${error}`);\n }\n\n logger.debug(`Checking for existing package '${packageName}' across ${targets.length} locations`);\n\n // Search each target directory for files with supported extensions\n for (const target of targets) {\n const extensions = target.exts;\n if (extensions && extensions.length === 0) {\n continue;\n }\n\n try {\n const files = await findFilesByExtension(target.dir, extensions ?? []);\n for (const file of files) {\n // Frontmatter support removed - cannot determine package ownership\n }\n } catch (dirErr) {\n logger.debug(`Failed to search directory ${target.dir}: ${dirErr}`);\n }\n }\n\n return { found: false };\n}\n", "/**\n * Prompt utilities for dependency resolution.\n */\n\nimport type { PromptPort } from '../ports/prompt.js';\nimport { resolvePrompt } from '../ports/resolve.js';\n\n/**\n * Prompt user for overwrite confirmation\n */\nexport async function promptOverwrite(\n packageName: string, \n existingVersion: string, \n newVersion: string,\n prompt?: PromptPort\n): Promise<boolean> {\n const p = prompt ?? resolvePrompt();\n return p.confirm(\n `Package '${packageName}' conflict: existing v${existingVersion} vs required v${newVersion}. Overwrite with v${newVersion}?`,\n true\n );\n}\n", "import { join } from 'path';\nimport { InstallOptions } from '../../../types/index.js';\nimport type { InteractionPolicy } from '../../../core/interaction-policy.js';\nimport { PromptTier } from '../../../core/interaction-policy.js';\nimport type { ResolvedPackage } from '../../dependency-resolver/types.js';\nimport { checkExistingPackageInMarkdownFiles } from '../../openpackage.js';\nimport { parsePackageYml } from '../../../utils/package-yml.js';\nimport { exists } from '../../../utils/fs.js';\nimport { logger } from '../../../utils/logger.js';\nimport { getLocalPackageDir } from '../../../utils/paths.js';\nimport { FILE_PATTERNS } from '../../../constants/index.js';\nimport { getVersionInfoFromDependencyTree } from '../install-helpers.js';\nimport type { PromptPort } from '../../ports/prompt.js';\nimport { resolvePrompt, resolveOutput } from '../../ports/resolve.js';\n\n/**\n * Get currently installed version from .openpackage/packages/<package>/openpackage.yml\n */\nasync function getInstalledPackageVersion(cwd: string, packageName: string): Promise<string | undefined> {\n try {\n const packageDir = getLocalPackageDir(cwd, packageName);\n const packageYmlPath = join(packageDir, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(packageYmlPath)) {\n const config = await parsePackageYml(packageYmlPath);\n return config.version;\n }\n } catch {\n // ignore parse errors; treat as unknown\n }\n return undefined;\n}\n\n/**\n * Check for conflicts with all packages in the dependency tree\n */\nexport async function checkAndHandleAllPackageConflicts(\n resolvedPackages: ResolvedPackage[],\n options: InstallOptions,\n policy?: InteractionPolicy,\n prompt?: PromptPort\n): Promise<{ shouldProceed: boolean; skippedPackages: string[]; forceOverwritePackages: Set<string> }> {\n const cwd = process.cwd();\n const skippedPackages: string[] = [];\n const forceOverwritePackages = new Set<string>();\n const p = prompt ?? resolvePrompt();\n \n // Check each package in the dependency tree for conflicts\n for (const resolved of resolvedPackages) {\n const existingCheck = await checkExistingPackageInMarkdownFiles(cwd, resolved.name);\n \n if (existingCheck.found) {\n const versionInfo = await getVersionInfoFromDependencyTree(resolved.name, resolvedPackages);\n const existingVersion = existingCheck.version || await getInstalledPackageVersion(cwd, resolved.name);\n \n\n \n if (options.dryRun) {\n // In dry run mode, proceed; per-file logic will report decisions\n continue;\n }\n \n if (options.force) {\n // When --force is used, automatically overwrite all conflicts\n logger.info(`Force flag set - automatically overwriting package '${resolved.name}' v${existingVersion}`);\n forceOverwritePackages.add(resolved.name);\n continue;\n }\n \n // Prompt per package overwrite confirmation when existing detected\n if (policy && !policy.canPrompt(PromptTier.Confirmation)) {\n resolveOutput().warn(`Skipping '${resolved.name}' (already exists). Use --force to overwrite.`);\n skippedPackages.push(resolved.name);\n } else {\n const versionSuffix = existingVersion ? ` (${existingVersion})` : '';\n const confirmed = await p.confirm(\n `Package '${resolved.name}' already exists${versionSuffix}. Overwrite all files?`\n );\n if (confirmed) {\n forceOverwritePackages.add(resolved.name);\n } else {\n skippedPackages.push(resolved.name);\n }\n }\n continue;\n }\n }\n \n return { shouldProceed: true, skippedPackages, forceOverwritePackages };\n}\n", "import type { InstallationContext } from '../context.js';\nimport { checkAndHandleAllPackageConflicts } from '../../operations/conflict-handler.js';\nimport { logger } from '../../../../utils/logger.js';\n\n/**\n * Process conflicts phase\n * @returns true if should proceed, false if cancelled\n */\nexport async function processConflictsPhase(ctx: InstallationContext): Promise<boolean> {\n const conflictResult = await checkAndHandleAllPackageConflicts(ctx.resolvedPackages as any, ctx.options, ctx.execution?.interactionPolicy);\n \n if (!conflictResult.shouldProceed) {\n return false;\n }\n \n // Update resolved packages based on conflict resolution\n ctx.resolvedPackages = ctx.resolvedPackages.filter(pkg => !conflictResult.skippedPackages.includes(pkg.name));\n \n // Store conflict result in context for use in the execute phase\n ctx.conflictResult = conflictResult;\n \n return true;\n}\n", "import { packageManager } from '../../package.js';\nimport { FILE_PATTERNS, PACKAGE_PATHS } from '../../../constants/index.js';\nimport type { PackageFile } from '../../../types/index.js';\nimport type { Platform } from '../../platforms.js';\nimport { isManifestPath, normalizePackagePath } from '../../../utils/manifest-paths.js';\nimport { getPlatformRootFileNames, stripRootCopyPrefix } from '../../platform/platform-root-files.js';\nimport { minimatch } from 'minimatch';\nimport { join } from 'path';\nimport { exists } from '../../../utils/fs.js';\nimport { hasPluginContent } from '../plugin-detector.js';\n\nexport interface CategorizedInstallFiles {\n pathBasedFiles: PackageFile[];\n rootFiles: Map<string, string>;\n rootCopyFiles: PackageFile[];\n}\n\nexport async function discoverAndCategorizeFiles(\n packageName: string,\n version: string,\n platforms: Platform[],\n contentRoot?: string,\n matchedPattern?: string // Phase 4: Pattern for filtering\n): Promise<CategorizedInstallFiles> {\n // Root file discovery only works for OpenPackage dirs or Claude plugins.\n // Also treat directories with plugin content (commands/agents/skills/hooks or .mcp.json/.lsp.json)\n // as loadable so marketplace-defined plugins without plugin.json can install.\n if (contentRoot) {\n const hasOpenPackageYml = await exists(join(contentRoot, 'openpackage.yml'));\n const hasClaudePluginJson = await exists(join(contentRoot, '.claude-plugin', 'plugin.json'));\n const hasClaudeMarketplaceJson = await exists(join(contentRoot, '.claude-plugin', 'marketplace.json'));\n const hasPluginContentDirs = await hasPluginContent(contentRoot);\n const isLoadableRoot =\n hasOpenPackageYml || hasClaudePluginJson || hasClaudeMarketplaceJson || hasPluginContentDirs;\n\n if (!isLoadableRoot) {\n return { pathBasedFiles: [], rootFiles: new Map(), rootCopyFiles: [] };\n }\n }\n\n // Load once\n const pkg = await packageManager.loadPackage(packageName, version, {\n packageRootDir: contentRoot\n });\n\n // Phase 4: Build include filter that considers matchedPattern\n const shouldInclude = (path: string): boolean => {\n // Check matched pattern (from base detection or resource scoping)\n if (matchedPattern && !minimatch(path, matchedPattern)) {\n return false;\n }\n \n return true;\n };\n\n // Precompute platform root filenames\n const platformRootNames = getPlatformRootFileNames(platforms);\n\n // Single pass classification\n const pathBasedFiles: PackageFile[] = [];\n const rootFiles = new Map<string, string>();\n const rootCopyFiles: PackageFile[] = [];\n for (const file of pkg.files) {\n const p = file.path;\n const normalized = normalizePackagePath(p);\n // Never install registry package metadata files\n if (isManifestPath(p) || normalized === PACKAGE_PATHS.INDEX_RELATIVE) continue;\n if (!shouldInclude(p)) continue;\n\n // root/** copy-to-root handling\n const stripped = stripRootCopyPrefix(normalized);\n if (stripped !== null) {\n rootCopyFiles.push({ ...file, path: stripped });\n continue;\n }\n\n pathBasedFiles.push(file);\n\n if (normalized === FILE_PATTERNS.AGENTS_MD || platformRootNames.has(normalized)) {\n rootFiles.set(normalized, file.content);\n }\n }\n\n return { pathBasedFiles, rootFiles, rootCopyFiles };\n}\n\n\n", "/**\n * Unified Root File Operations\n * Handles root file installation and synchronization for both install and apply commands\n */\n\nimport { join } from 'path';\nimport { exists, readTextFile, writeTextFile } from '../../../utils/fs.js';\nimport { mergePackageContentIntoRootFile } from '../../../utils/root-file-merger.js';\nimport { extractPackageContentFromRootFile } from '../../../utils/root-file-extractor.js';\nimport { getPlatformDefinition, getAllPlatforms, type Platform } from '../../platforms.js';\nimport { FILE_PATTERNS } from '../../../constants/index.js';\nimport { logger } from '../../../utils/logger.js';\nimport { getPathLeaf } from '../../../utils/path-normalization.js';\nimport type { PackageFile } from '../../../types/index.js';\n\n/**\n * Input for root file operations - supports both formats\n */\nexport type RootFileInput = \n | Map<string, string> // From install flow\n | PackageFile[] // From apply flow\n | Record<string, string>; // Alternative map format\n\n/**\n * Result of root file operations\n */\nexport interface RootFileOperationResult {\n /** Files that were newly created */\n created: string[];\n \n /** Files that were updated (already existed) */\n updated: string[];\n \n /** Files that were skipped (no changes needed) */\n skipped: string[];\n \n /** Legacy alias for created (for backward compatibility) */\n installed?: string[];\n}\n\n/**\n * Universal root file installer/syncer\n * \n * Handles root file installation and synchronization for both install and apply commands.\n * Supports multiple input formats for maximum flexibility.\n * \n * @param cwd - Current working directory\n * @param packageName - Name of the package\n * @param rootFiles - Root files to install (Map, PackageFile[], or Record)\n * @param platforms - Target platforms\n * @returns Operation result with created/updated/skipped files\n */\nexport async function installOrSyncRootFiles(\n cwd: string,\n packageName: string,\n rootFiles: RootFileInput,\n platforms: Platform[]\n): Promise<RootFileOperationResult> {\n const result: RootFileOperationResult = {\n created: [],\n updated: [],\n skipped: []\n };\n \n // Normalize input to a common format\n const rootFilesMap = normalizeRootFileInput(rootFiles);\n \n if (rootFilesMap.size === 0) {\n return result;\n }\n \n // Always install/sync universal AGENTS.md regardless of platform detection\n await installUniversalAgentsFile(cwd, packageName, rootFilesMap, result);\n \n // Install platform-specific root files\n if (platforms.length > 0) {\n await installPlatformRootFiles(cwd, packageName, rootFilesMap, platforms, result);\n }\n \n // Deduplicate results\n result.created = Array.from(new Set(result.created));\n result.updated = Array.from(new Set(result.updated));\n result.skipped = Array.from(new Set(result.skipped));\n \n // Add legacy alias for backward compatibility\n result.installed = result.created;\n \n return result;\n}\n\n/**\n * Normalize different input formats to a common Map structure\n */\nfunction normalizeRootFileInput(input: RootFileInput): Map<string, string> {\n // Already a Map\n if (input instanceof Map) {\n return input;\n }\n \n // PackageFile array\n if (Array.isArray(input)) {\n const map = new Map<string, string>();\n for (const file of input) {\n const fileName = getPathLeaf(file.path);\n if (fileName && isRootFile(fileName)) {\n map.set(fileName, file.content);\n }\n }\n return map;\n }\n \n // Plain object/Record\n return new Map(Object.entries(input));\n}\n\n/**\n * Check if a file name is a root file\n */\nfunction isRootFile(fileName: string): boolean {\n const rootFileNames = new Set<string>([FILE_PATTERNS.AGENTS_MD]);\n \n // Add all platform root files\n for (const platform of getAllPlatforms()) {\n const def = getPlatformDefinition(platform);\n if (def.rootFile) {\n rootFileNames.add(def.rootFile);\n }\n }\n \n return rootFileNames.has(fileName);\n}\n\n/**\n * Install universal AGENTS.md file\n */\nasync function installUniversalAgentsFile(\n cwd: string,\n packageName: string,\n rootFilesMap: Map<string, string>,\n result: RootFileOperationResult\n): Promise<void> {\n const agentsContent = rootFilesMap.get(FILE_PATTERNS.AGENTS_MD);\n \n if (!agentsContent || !agentsContent.trim()) {\n return;\n }\n \n try {\n const targetPath = join(cwd, FILE_PATTERNS.AGENTS_MD);\n const wasUpdated = await installSingleRootFile(\n targetPath,\n packageName,\n agentsContent.trim()\n );\n \n if (wasUpdated) {\n result.updated.push(FILE_PATTERNS.AGENTS_MD);\n } else {\n result.created.push(FILE_PATTERNS.AGENTS_MD);\n }\n } catch (error) {\n logger.error(`Failed to install universal root file ${FILE_PATTERNS.AGENTS_MD}: ${error}`);\n result.skipped.push(FILE_PATTERNS.AGENTS_MD);\n }\n}\n\n/**\n * Install platform-specific root files\n */\nasync function installPlatformRootFiles(\n cwd: string,\n packageName: string,\n rootFilesMap: Map<string, string>,\n platforms: Platform[],\n result: RootFileOperationResult\n): Promise<void> {\n for (const platform of platforms) {\n const platformDef = getPlatformDefinition(platform);\n \n if (!platformDef.rootFile) {\n continue; // Platform doesn't use root files\n }\n \n // Skip if already handled by universal AGENTS.md\n if (platformDef.rootFile === FILE_PATTERNS.AGENTS_MD) {\n continue;\n }\n \n // Prefer platform-specific file, fallback to AGENTS.md\n let content = rootFilesMap.get(platformDef.rootFile);\n let sourceFileName = platformDef.rootFile;\n \n if (!content && rootFilesMap.has(FILE_PATTERNS.AGENTS_MD)) {\n content = rootFilesMap.get(FILE_PATTERNS.AGENTS_MD)!;\n sourceFileName = FILE_PATTERNS.AGENTS_MD;\n }\n \n if (!content || !content.trim()) {\n continue;\n }\n \n try {\n const targetPath = join(cwd, platformDef.rootFile);\n const wasUpdated = await installSingleRootFile(\n targetPath,\n packageName,\n content.trim()\n );\n \n if (wasUpdated) {\n result.updated.push(platformDef.rootFile);\n } else {\n result.created.push(platformDef.rootFile);\n }\n } catch (error) {\n logger.error(`Failed to install root file ${platformDef.rootFile}: ${error}`);\n result.skipped.push(platformDef.rootFile);\n }\n }\n}\n\n/**\n * Install or update a single root file\n * @returns true if file was updated (existed before), false if newly created\n */\nasync function installSingleRootFile(\n targetPath: string,\n packageName: string,\n sectionBody: string\n): Promise<boolean> {\n // Read existing content if file exists\n let existingContent = '';\n let fileExists = false;\n \n if (await exists(targetPath)) {\n existingContent = await readTextFile(targetPath);\n fileExists = true;\n }\n \n // Check if section content is unchanged (optimization)\n if (fileExists) {\n const existingSectionContent = extractPackageContentFromRootFile(\n existingContent,\n packageName\n )?.trim();\n \n if (existingSectionContent === sectionBody) {\n return true; // Still counts as \"updated\" (touched but unchanged)\n }\n }\n \n // Merge package content into the file\n const mergedContent = mergePackageContentIntoRootFile(\n existingContent,\n packageName,\n sectionBody\n );\n \n // Write the merged content\n await writeTextFile(targetPath, mergedContent);\n \n return fileExists;\n}\n", "/**\n * Flow-Based Index Installer\n * \n * INFRASTRUCTURE LAYER: Workspace index integration\n * \n * Wraps flow-based-installer.ts with workspace index management.\n * This is the primary entry point for production installations.\n * \n * Delegates to flow-based-installer.ts for core flow execution,\n * then updates workspace index with file mappings.\n * \n * Hierarchy:\n * Command Layer -> install-flow.ts -> THIS FILE -> flow-based-installer.ts\n */\n\nimport { join } from 'path';\nimport { promises as fs } from 'fs';\nimport {\n installPackageWithFlows,\n type FlowInstallContext\n} from './flow-based-installer.js';\nimport { resolvePackageContentRoot } from './local-source-resolution.js';\nimport { logger } from '../../utils/logger.js';\nimport { formatPathForYaml } from '../../utils/path-resolution.js';\nimport { sortMapping } from '../../utils/package-index-yml.js';\nimport {\n readWorkspaceIndex,\n writeWorkspaceIndex\n} from '../../utils/workspace-index-yml.js';\nimport { exists } from '../../utils/fs.js';\nimport type { Platform } from '../platforms.js';\nimport type { InstallOptions } from '../../types/index.js';\nimport type { WorkspaceIndexFileMapping } from '../../types/workspace-index.js';\nimport type { RelocatedFile } from './conflicts/file-conflict-resolver.js';\nimport { createContextFromFormat } from '../conversion-context/creation.js';\nimport { detectFormatWithContextFromDirectory } from './helpers/format-detection.js';\nimport {\n logConflictMessages,\n logErrorMessages\n} from './helpers/result-logging.js';\nimport {\n collectConflictMessages,\n collectErrorMessages\n} from './helpers/result-aggregation.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface IndexInstallResult {\n installed: number;\n updated: number;\n deleted: number;\n skipped: number;\n files: string[];\n installedFiles: string[];\n updatedFiles: string[];\n deletedFiles: string[];\n /** True when namespace conflict resolution was triggered for this package */\n namespaced?: boolean;\n /** Files that were physically relocated on disk during namespace resolution */\n relocatedFiles?: RelocatedFile[];\n}\n\ninterface PackageIndexRecord {\n path: string;\n packageName: string;\n workspace: {\n version: string;\n hash?: string;\n };\n files: Record<string, (string | WorkspaceIndexFileMapping)[]>;\n}\n\n// ============================================================================\n// Main Installation Function\n// ============================================================================\n\n/**\n * Install a package using flow-based installation\n * This is the new entry point that replaces installPackageByIndex\n */\nexport async function installPackageByIndexWithFlows(\n cwd: string,\n packageName: string,\n version: string,\n platforms: Platform[],\n options: InstallOptions,\n contentRoot?: string,\n packageFormat?: any, // Optional format metadata from plugin transformer\n marketplaceMetadata?: { // Optional marketplace source metadata\n url: string;\n commitSha: string;\n pluginName: string;\n },\n matchedPattern?: string, // Phase 4: Pattern from base detection\n resourceVersion?: string, // Resource-specific version (for agents/skills)\n originalContentRoot?: string, // Original source path before conversion (for index)\n forceOverwrite?: boolean // Phase 5: Package was confirmed for overwrite at package-level conflict phase\n): Promise<IndexInstallResult> {\n logger.debug(`Installing ${packageName}@${version} with flows for platforms: ${platforms.join(', ')}`);\n\n // Resolve package root\n const resolvedContentRoot = contentRoot ?? await resolvePackageContentRoot({\n cwd,\n packageName,\n version\n });\n\n // Aggregate results across all platforms\n const aggregatedResult: IndexInstallResult = {\n installed: 0,\n updated: 0,\n deleted: 0,\n skipped: 0,\n files: [],\n installedFiles: [],\n updatedFiles: [],\n deletedFiles: []\n };\n\n const allTargetPaths = new Set<string>();\n const allConflicts: string[] = [];\n const allErrors: string[] = [];\n const fileMapping: Record<string, (string | WorkspaceIndexFileMapping)[]> = {};\n \n // Helper to normalize source keys: merge variants that refer to the same file\n // This handles cases where .mcp.json and mcp.jsonc are discovered separately but refer to the same file\n const sourceKeyCache = new Map<string, string>(); // Maps discovered source -> canonical key\n const normalizeSourceKey = async (source: string): Promise<string> => {\n // Check cache first\n if (sourceKeyCache.has(source)) {\n return sourceKeyCache.get(source)!;\n }\n \n const sourceAbs = join(resolvedContentRoot, source);\n if (!await exists(sourceAbs)) {\n sourceKeyCache.set(source, source);\n return source;\n }\n \n // Check if any already-seen source key refers to the same file\n // When both .mcp.json and mcp.jsonc exist and refer to the same file, prefer .mcp.json\n // (since apply command uses .mcp.json, it's the canonical form)\n let canonicalKey = source;\n for (const [cachedSource, cachedCanonical] of sourceKeyCache.entries()) {\n if (cachedSource === source) continue;\n const cachedAbs = join(resolvedContentRoot, cachedSource);\n if (await exists(cachedAbs)) {\n try {\n const sourceStat = await fs.stat(sourceAbs);\n const cachedStat = await fs.stat(cachedAbs);\n // Same file if same inode (Unix) or same size+mtime\n if (sourceStat.ino === cachedStat.ino || \n (sourceStat.size === cachedStat.size && \n Math.abs(sourceStat.mtimeMs - cachedStat.mtimeMs) < 1000)) {\n // Prefer dot-prefixed variant (.mcp.json) as canonical key when both exist\n // This matches apply command behavior\n if (source.startsWith('.') && !cachedCanonical.startsWith('.')) {\n canonicalKey = source;\n // Update cached entry to use dot-prefixed variant\n sourceKeyCache.set(cachedSource, source);\n } else if (!source.startsWith('.') && cachedCanonical.startsWith('.')) {\n canonicalKey = cachedCanonical;\n } else {\n canonicalKey = cachedCanonical;\n }\n sourceKeyCache.set(source, canonicalKey);\n return canonicalKey;\n }\n } catch {\n // If stat fails, treat as different files\n }\n }\n }\n \n // No match found, use source as canonical key\n sourceKeyCache.set(source, source);\n return source;\n };\n\n // Execute flows for each platform\n for (const platform of platforms) {\n // Create conversion context from format or detect it using shared utility\n let conversionContext;\n let format = packageFormat;\n \n if (!packageFormat) {\n // Detect format and context from directory\n const result = await detectFormatWithContextFromDirectory(resolvedContentRoot);\n format = result.format;\n conversionContext = result.context;\n } else {\n // Create context from existing format\n conversionContext = createContextFromFormat(packageFormat);\n }\n \n const installContext: FlowInstallContext = {\n packageName,\n packageRoot: resolvedContentRoot,\n workspaceRoot: cwd,\n platform,\n packageVersion: version,\n priority: 0, // Priority is calculated from dependency graph during multi-package installs\n dryRun: options.dryRun ?? false,\n packageFormat: format,\n conversionContext,\n // Phase 4: Pass resource filtering info\n matchedPattern\n };\n\n try {\n const result = await installPackageWithFlows(installContext, options, forceOverwrite ?? false);\n\n // Aggregate target paths + per-source mapping for workspace index\n for (const absTarget of result.targetPaths ?? []) {\n allTargetPaths.add(absTarget);\n }\n // Merge file mappings with normalization\n for (const [source, targets] of Object.entries(result.fileMapping ?? {})) {\n const normalizedSource = await normalizeSourceKey(source);\n \n if (!fileMapping[normalizedSource]) {\n fileMapping[normalizedSource] = [];\n }\n \n // Note: mergeWorkspaceFileMappings expects nested objects, so we wrap in object\n const tempTarget = { [normalizedSource]: fileMapping[normalizedSource] };\n const tempSource = { [normalizedSource]: targets };\n \n // Merge while deduping by target path; prefer complex mapping over string\n const byTarget = new Map<string, string | WorkspaceIndexFileMapping>();\n for (const m of fileMapping[normalizedSource]) {\n const targetPath = typeof m === 'string' ? m : m.target;\n byTarget.set(targetPath, m);\n }\n for (const m of targets) {\n const targetPath = typeof m === 'string' ? m : m.target;\n const prior = byTarget.get(targetPath);\n if (!prior) {\n byTarget.set(targetPath, m);\n } else if (typeof prior === 'string' && typeof m !== 'string') {\n byTarget.set(targetPath, m);\n }\n }\n fileMapping[normalizedSource] = Array.from(byTarget.values());\n }\n\n // Aggregate statistics\n aggregatedResult.installed += result.filesProcessed;\n aggregatedResult.updated += 0; // Flow executor doesn't distinguish new vs updated yet\n aggregatedResult.skipped += result.filesProcessed - result.filesWritten;\n\n // Collect conflicts and errors using shared utilities\n collectConflictMessages(allConflicts, result.conflicts);\n collectErrorMessages(allErrors, result.errors);\n\n // Propagate namespace metadata from the strategy result\n if (result.namespaced) {\n aggregatedResult.namespaced = true;\n }\n if (result.relocatedFiles && result.relocatedFiles.length > 0) {\n if (!aggregatedResult.relocatedFiles) {\n aggregatedResult.relocatedFiles = [];\n }\n aggregatedResult.relocatedFiles.push(...result.relocatedFiles);\n }\n\n // Log results per platform\n if (result.filesProcessed > 0) {\n logger.info(\n `${platform}: processed ${result.filesProcessed} files` +\n (options.dryRun ? ' (dry run)' : `, wrote ${result.filesWritten} files`)\n );\n }\n\n } catch (error) {\n logger.error(`Failed to install ${packageName} for platform ${platform}: ${error}`);\n allErrors.push(`${platform}: ${error}`);\n }\n }\n\n // Log aggregated results using shared utilities\n logConflictMessages(allConflicts);\n logErrorMessages(allErrors);\n\n // Update workspace index if not dry-run\n if (!options.dryRun) {\n // For resource-scoped installs, store the most specific source path possible:\n // - file match: <root>/<file>\n // - directory match: <root>/<dir> (matchedPattern like \"dir/**\")\n // This keeps index paths and names aligned for resource installs.\n const isGlob = Boolean(matchedPattern && (matchedPattern.includes('*') || matchedPattern.includes('?') || matchedPattern.includes('[')));\n const isDirGlob = Boolean(matchedPattern && matchedPattern.replace(/\\\\/g, '/').endsWith('/**'));\n const dirGlobPrefix = isDirGlob\n ? matchedPattern!.replace(/\\\\/g, '/').replace(/\\/\\*\\*$/, '')\n : undefined;\n \n // Use originalContentRoot if provided (for converted packages), otherwise use resolvedContentRoot\n const basePathForIndex = originalContentRoot || resolvedContentRoot;\n \n const indexSourcePath = (matchedPattern && !isGlob)\n ? join(basePathForIndex, matchedPattern)\n : (dirGlobPrefix && dirGlobPrefix.length > 0)\n ? join(basePathForIndex, dirGlobPrefix)\n : basePathForIndex;\n\n await updateWorkspaceIndexForFlows(\n cwd,\n packageName,\n version,\n indexSourcePath,\n fileMapping,\n marketplaceMetadata,\n resourceVersion\n );\n }\n\n // Set result files\n aggregatedResult.files = Array.from(allTargetPaths);\n aggregatedResult.installedFiles = Array.from(allTargetPaths);\n\n return aggregatedResult;\n}\n\n// ============================================================================\n// Workspace Index Management\n// ============================================================================\n\n/**\n * Update workspace index with flow-based installation results\n */\nasync function updateWorkspaceIndexForFlows(\n cwd: string,\n packageName: string,\n version: string,\n packagePath: string,\n fileMapping: Record<string, (string | WorkspaceIndexFileMapping)[]>,\n marketplaceMetadata?: {\n url: string;\n commitSha: string;\n pluginName: string;\n },\n resourceVersion?: string\n): Promise<void> {\n try {\n const wsRecord = await readWorkspaceIndex(cwd);\n \n // Initialize packages map if needed\n wsRecord.index.packages = wsRecord.index.packages ?? {};\n \n // Convert file mapping to workspace index format\n const files: Record<string, (string | WorkspaceIndexFileMapping)[]> = {};\n for (const [source, targets] of Object.entries(fileMapping)) {\n files[source] = targets;\n }\n \n // Convert to workspace-relative path if under workspace, then apply tilde notation for global paths\n const formattedPath = formatPathForYaml(packagePath, cwd);\n \n // Apply version fallback chain: resourceVersion > version > undefined\n // This ensures agents/skills can have individual versions\n const effectiveVersion = resourceVersion ?? version;\n \n // Update package entry\n const packageEntry: any = {\n ...wsRecord.index.packages[packageName],\n path: formattedPath,\n version: effectiveVersion,\n files: sortMapping(files)\n };\n \n // Add marketplace metadata if present\n if (marketplaceMetadata) {\n packageEntry.marketplace = marketplaceMetadata;\n }\n \n wsRecord.index.packages[packageName] = packageEntry;\n \n await writeWorkspaceIndex(wsRecord);\n logger.debug(`Updated workspace index for ${packageName}@${version}`);\n } catch (error) {\n logger.warn(`Failed to update workspace index for ${packageName}: ${error}`);\n }\n}\n\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Read package index from workspace\n */\nasync function readPackageIndex(\n cwd: string,\n packageName: string\n): Promise<PackageIndexRecord | null> {\n const record = await readWorkspaceIndex(cwd);\n const entry = record.index.packages?.[packageName];\n if (!entry) return null;\n \n return {\n path: entry.path ?? '',\n packageName,\n workspace: {\n version: entry.version ?? '',\n hash: undefined\n },\n files: entry.files ?? {}\n };\n}\n\n/**\n * Write package index to workspace\n */\nasync function writePackageIndex(\n record: PackageIndexRecord,\n cwd: string\n): Promise<void> {\n const wsRecord = await readWorkspaceIndex(cwd);\n wsRecord.index.packages = wsRecord.index.packages ?? {};\n \n const entry = wsRecord.index.packages[record.packageName];\n const rawPath = entry?.path ?? record.path ?? '';\n \n if (!rawPath) {\n logger.warn(\n `Skipping workspace index write for ${record.packageName}: source path is unknown`\n );\n return;\n }\n \n // Convert to workspace-relative path if under workspace, then apply tilde notation for global paths\n const pathToUse = formatPathForYaml(rawPath, cwd);\n \n wsRecord.index.packages[record.packageName] = {\n ...entry,\n path: pathToUse,\n version: entry?.version ?? record.workspace?.version,\n files: sortMapping(record.files ?? {})\n };\n \n await writeWorkspaceIndex(wsRecord);\n}\n", "/**\n * Format Conversion Installation Strategy\n * \n * Converts package from source format \u2192 universal \u2192 target platform format.\n * \n * This strategy performs per-platform conversion to handle conditional flows\n * that depend on the target platform (e.g., `when: { \"$eq\": [\"$$platform\", \"claude\"] }`).\n * \n * Each target platform gets its own conversion pass with proper context variables:\n * - $$platform = target platform (for conditional evaluation)\n * - $$source = original source format (preserved through conversion)\n * \n * Used when source platform \u2260 target platform.\n */\n\nimport { join, relative } from 'path';\nimport type { Platform } from '../../platforms.js';\nimport type { Package } from '../../../types/index.js';\nimport type { PackageConversionContext } from '../../../types/conversion-context.js';\nimport type { PackageFormat } from '../format-detector.js';\nimport type { InstallOptions } from '../../../types/index.js';\nimport type { FlowInstallContext, FlowInstallResult } from './types.js';\nimport { BaseStrategy } from './base-strategy.js';\nimport { needsConversion, detectPackageFormat } from '../format-detector.js';\nimport { createPlatformConverter } from '../../flows/platform-converter.js';\nimport { walkFiles } from '../../../utils/file-walker.js';\nimport { readTextFile } from '../../../utils/fs.js';\nimport { logger } from '../../../utils/logger.js';\nimport {\n createTempPackageDirectory,\n writeTempPackageFiles,\n writeConversionContext,\n cleanupTempDirectory\n} from './helpers/temp-directory.js';\nimport { createContextFromFormat } from '../../conversion-context/index.js';\nimport { FlowBasedInstallStrategy } from './flow-based-strategy.js';\n\n/**\n * Format Conversion Installation Strategy\n * \n * Performs per-platform conversion to ensure conditional flows have\n * correct context variables during transformation.\n */\nexport class ConversionInstallStrategy extends BaseStrategy {\n readonly name = 'conversion';\n \n canHandle(format: PackageFormat, platform: Platform): boolean {\n return needsConversion(format, platform);\n }\n \n async install(\n context: FlowInstallContext,\n options?: InstallOptions,\n forceOverwrite: boolean = false\n ): Promise<FlowInstallResult> {\n const { packageName, packageRoot, workspaceRoot, platform, dryRun } = context;\n \n this.logStrategySelection(context);\n \n logger.info(`Converting ${packageName} from ${context.packageFormat?.platform || 'unknown'} to ${platform} format`);\n \n try {\n // Phase 1: Load package files\n const packageFiles = await this.loadPackageFiles(packageRoot);\n \n // Phase 2: Create package object with original format metadata\n const pkg: Package = {\n metadata: {\n name: packageName,\n version: context.packageVersion\n },\n files: packageFiles,\n _format: context.packageFormat || await this.detectFormat(packageRoot)\n };\n \n // Phase 3: Create conversion context and convert FOR the specific target platform\n // This ensures conditional flows like `when: { \"$eq\": [\"$$platform\", \"claude\"] }`\n // have the correct context during conversion\n const conversionContext = createContextFromFormat(pkg._format!);\n \n const converter = createPlatformConverter(workspaceRoot);\n const conversionResult = await converter.convert(\n pkg,\n conversionContext, // Pass conversion context\n platform, // Target platform\n { dryRun }\n );\n \n if (!conversionResult.success || !conversionResult.convertedPackage) {\n logger.error('Package conversion failed', {\n package: packageName,\n stages: conversionResult.stages\n });\n \n return this.createErrorResult(\n context,\n new Error('Conversion failed'),\n 'Failed to convert package format'\n );\n }\n \n logger.info(\n `Conversion to universal format complete (${conversionResult.stages.length} stages), ` +\n `now applying ${platform} platform flows`\n );\n \n // Phase 4: Write converted files to temp directory and install\n return await this.installConvertedPackage(\n conversionResult.convertedPackage,\n conversionResult.updatedContext || conversionContext,\n context,\n options,\n forceOverwrite\n );\n \n } catch (error) {\n logger.error('Conversion installation failed', { packageName, error });\n return this.createErrorResult(\n context,\n error as Error,\n `Failed to install with conversion: ${(error as Error).message}`\n );\n }\n }\n \n /**\n * Load all package files from directory\n */\n private async loadPackageFiles(packageRoot: string): Promise<Array<{ path: string; content: string }>> {\n const packageFiles: Array<{ path: string; content: string }> = [];\n \n for await (const sourcePath of walkFiles(packageRoot)) {\n const relativePath = relative(packageRoot, sourcePath);\n \n if (relativePath.startsWith('.openpackage/') || relativePath === 'openpackage.yml') {\n continue;\n }\n \n const content = await readTextFile(sourcePath);\n packageFiles.push({ path: relativePath, content, encoding: 'utf8' } as any);\n }\n \n return packageFiles;\n }\n \n /**\n * Detect package format from directory\n */\n private async detectFormat(packageRoot: string): Promise<PackageFormat> {\n const files: Array<{ path: string; content: string }> = [];\n \n for await (const fullPath of walkFiles(packageRoot)) {\n const relativePath = relative(packageRoot, fullPath);\n \n if (relativePath.startsWith('.git/') || relativePath === '.git') {\n continue;\n }\n \n files.push({ path: relativePath, content: '' });\n }\n \n return detectPackageFormat(files);\n }\n \n /**\n * Install converted package from temp directory with context\n */\n private async installConvertedPackage(\n convertedPackage: Package,\n conversionContext: PackageConversionContext,\n context: FlowInstallContext,\n options?: InstallOptions,\n forceOverwrite: boolean = false\n ): Promise<FlowInstallResult> {\n let tempPackageRoot: string | null = null;\n \n try {\n // Create temp directory\n tempPackageRoot = await createTempPackageDirectory();\n \n // Write converted files\n await writeTempPackageFiles(convertedPackage.files, tempPackageRoot);\n \n // Write conversion context (persists through temp directory)\n await writeConversionContext(conversionContext, tempPackageRoot);\n \n // Install from temp directory using flow-based installation\n const flowStrategy = new FlowBasedInstallStrategy();\n \n const convertedContext: FlowInstallContext = {\n ...context,\n packageRoot: tempPackageRoot,\n // Updated package format after conversion\n packageFormat: convertedPackage._format,\n // Pass updated conversion context\n conversionContext\n };\n \n const installResult = await flowStrategy.install(convertedContext, options, forceOverwrite);\n \n // Cleanup temp directory\n await cleanupTempDirectory(tempPackageRoot);\n \n return installResult;\n \n } catch (error) {\n await cleanupTempDirectory(tempPackageRoot);\n \n logger.error('Failed to install converted package', { \n packageName: context.packageName, \n error \n });\n \n return this.createErrorResult(\n context,\n error as Error,\n `Failed to install converted package: ${(error as Error).message}`\n );\n }\n }\n}\n", "/**\n * Result Converter Module\n * \n * Utilities for converting execution results to installation results.\n */\n\nimport type { Platform } from '../../../platforms.js';\nimport type { FlowInstallResult } from '../types.js';\nimport { logger } from '../../../../utils/logger.js';\n\n/**\n * Convert execution result from flow coordinator to installation result format\n * \n * @param executionResult - Result from flow execution coordinator\n * @param packageName - Name of package being installed\n * @param platform - Target platform\n * @param dryRun - Whether this is a dry run\n * @returns Formatted installation result\n */\nexport function convertToInstallResult(\n executionResult: any,\n packageName: string,\n platform: Platform,\n dryRun: boolean\n): FlowInstallResult {\n const result: FlowInstallResult = {\n success: executionResult.success,\n filesProcessed: executionResult.filesProcessed,\n filesWritten: executionResult.filesWritten,\n conflicts: executionResult.conflicts.map((c: any) => ({\n targetPath: c.path,\n packages: [\n { packageName: c.winner, priority: 0, chosen: true },\n ...c.losers.map((loser: string) => ({\n packageName: loser,\n priority: 0,\n chosen: false\n }))\n ],\n message: `Conflict in ${c.path}: ${c.winner} overwrites ${c.losers.join(', ')}`\n })),\n errors: executionResult.errors,\n targetPaths: executionResult.targetPaths,\n fileMapping: executionResult.fileMapping\n };\n \n // Log results\n if (result.filesProcessed > 0) {\n logger.info(\n `Processed ${result.filesProcessed} files for ${packageName} on platform ${platform}` +\n (dryRun ? ' (dry run)' : `, wrote ${result.filesWritten} files`)\n );\n }\n \n return result;\n}\n\n/**\n * Create an empty install result (for early returns)\n */\nexport function createEmptyResult(): FlowInstallResult {\n return {\n success: true,\n filesProcessed: 0,\n filesWritten: 0,\n conflicts: [],\n errors: [],\n targetPaths: [],\n fileMapping: {},\n namespaced: false,\n relocatedFiles: []\n };\n}\n", "/**\n * Flow Helpers Module\n * \n * Utilities for retrieving and manipulating flows for installation strategies.\n */\n\nimport type { Flow } from '../../../../types/flows.js';\nimport type { Platform } from '../../../platforms.js';\nimport { getPlatformDefinition, getGlobalExportFlows } from '../../../platforms.js';\n\n/**\n * Get applicable flows for a platform, including global flows\n */\nexport function getApplicableFlows(platform: Platform, cwd: string): Flow[] {\n const flows: Flow[] = [];\n \n const globalExportFlows = getGlobalExportFlows(cwd);\n if (globalExportFlows && globalExportFlows.length > 0) {\n flows.push(...globalExportFlows);\n }\n \n const definition = getPlatformDefinition(platform, cwd);\n if (definition.export && definition.export.length > 0) {\n flows.push(...definition.export);\n }\n \n return flows;\n}\n", "/**\n * Result Logging Helpers\n * \n * Shared utilities for logging installation results, conflicts, and errors.\n * Provides consistent logging behavior across installation modules.\n */\n\nimport { logger } from '../../../utils/logger.js';\nimport { toTildePath } from '../../../utils/path-resolution.js';\nimport type { FlowInstallResult, FlowConflictReport, FlowInstallError } from '../strategies/types.js';\n\n/**\n * Log conflicts from FlowInstallResult\n * \n * @param conflicts - Array of conflict reports\n */\nexport function logConflicts(conflicts: FlowConflictReport[]): void {\n if (conflicts.length === 0) return;\n \n logger.warn(`Detected ${conflicts.length} conflicts during installation`);\n for (const conflict of conflicts) {\n const winner = conflict.packages.find(p => p.chosen);\n const loser = conflict.packages.find(p => !p.chosen);\n logger.warn(\n ` ${toTildePath(conflict.targetPath)}: ${winner?.packageName} (priority ${winner?.priority}) overwrites ${loser?.packageName}`\n );\n }\n}\n\n/**\n * Log errors from FlowInstallResult\n * \n * @param errors - Array of installation errors\n */\nexport function logErrors(errors: FlowInstallError[]): void {\n if (errors.length === 0) return;\n \n logger.error(`Encountered ${errors.length} errors during installation`);\n for (const error of errors) {\n logger.error(` ${error.sourcePath}: ${error.message}`);\n }\n}\n\n/**\n * Log conflict messages (string array format)\n * \n * Used by flow-index-installer which aggregates conflicts across platforms.\n * \n * @param conflicts - Array of conflict message strings\n */\nexport function logConflictMessages(conflicts: string[]): void {\n if (conflicts.length === 0) return;\n \n logger.warn(`Detected ${conflicts.length} conflicts during installation:`);\n for (const conflict of conflicts) {\n logger.warn(` ${conflict}`);\n }\n}\n\n/**\n * Log error messages (string array format)\n * \n * Used by flow-index-installer which aggregates errors across platforms.\n * \n * @param errors - Array of error message strings\n */\nexport function logErrorMessages(errors: string[]): void {\n if (errors.length === 0) return;\n \n logger.error(`Encountered ${errors.length} errors during installation:`);\n for (const error of errors) {\n logger.error(` ${error}`);\n }\n}\n\n/**\n * Log complete installation result with processing summary\n * \n * Logs files processed/written and then delegates to conflict/error logging.\n * \n * @param result - Flow installation result\n * @param packageName - Package being installed\n * @param platform - Target platform\n * @param dryRun - Whether this is a dry run\n */\nexport function logInstallationResult(\n result: FlowInstallResult,\n packageName: string,\n platform: string,\n dryRun: boolean\n): void {\n if (result.filesProcessed > 0) {\n logger.info(\n `Processed ${result.filesProcessed} files for ${packageName} on platform ${platform}` +\n (dryRun ? ' (dry run)' : `, wrote ${result.filesWritten} files`)\n );\n }\n \n logConflicts(result.conflicts);\n logErrors(result.errors);\n}\n", "/**\n * Base Strategy Module\n * \n * Abstract base class providing shared functionality for installation strategies.\n */\n\nimport type { Platform } from '../../platforms.js';\nimport type { FlowContext } from '../../../types/flows.js';\nimport type { PackageFormat } from '../format-detector.js';\nimport type { InstallationStrategy, FlowInstallContext, FlowInstallResult } from './types.js';\nimport type { InstallOptions } from '../../../types/index.js';\nimport { getPlatformDefinition, deriveRootDirFromFlows } from '../../platforms.js';\nimport { logger } from '../../../utils/logger.js';\nimport { createEmptyResult } from './helpers/result-converter.js';\nimport { getApplicableFlows } from './helpers/flow-helpers.js';\nimport { logInstallationResult } from '../helpers/result-logging.js';\nimport { minimatch } from 'minimatch';\nimport { relative } from 'path';\n\n/**\n * Abstract base class for installation strategies\n */\nexport abstract class BaseStrategy implements InstallationStrategy {\n abstract readonly name: string;\n \n abstract canHandle(format: PackageFormat, platform: Platform): boolean;\n \n abstract install(\n context: FlowInstallContext,\n options?: InstallOptions,\n forceOverwrite?: boolean\n ): Promise<FlowInstallResult>;\n \n /**\n * Create an empty result object\n */\n protected createEmptyResult(): FlowInstallResult {\n return createEmptyResult();\n }\n \n /**\n * Get applicable flows for a platform (global + platform-specific)\n */\n protected getApplicableFlows(platform: Platform, cwd: string) {\n return getApplicableFlows(platform, cwd);\n }\n \n /**\n * Build flow context with standard variables\n * \n * Uses conversion context as the single source of truth for format identity.\n */\n protected buildFlowContext(\n context: FlowInstallContext,\n direction: 'install' | 'save' = 'install'\n ): FlowContext {\n const platformDef = getPlatformDefinition(context.platform, context.workspaceRoot);\n \n // Use conversion context as single source of truth for original format\n const originalSource = context.conversionContext.originalFormat.platform || 'openpackage';\n \n return {\n workspaceRoot: context.workspaceRoot,\n packageRoot: context.packageRoot,\n platform: context.platform,\n packageName: context.packageName,\n direction,\n variables: {\n name: context.packageName,\n version: context.packageVersion,\n priority: context.priority,\n rootFile: platformDef.rootFile,\n rootDir: deriveRootDirFromFlows(platformDef),\n // Context variables for conditional flows\n platform: context.platform, // Target platform\n targetPlatform: context.platform, // Explicit target platform\n source: originalSource, // Original source format (from conversion context)\n sourcePlatform: originalSource, // Explicit source platform\n // Path variable for conditional installation behavior\n targetRoot: context.workspaceRoot\n },\n dryRun: context.dryRun\n };\n }\n \n /**\n * Log strategy selection for debugging\n */\n protected logStrategySelection(context: FlowInstallContext): void {\n // Strategy selection logging removed for cleaner output\n }\n \n /**\n * Log installation results using shared utility\n */\n protected logResults(result: FlowInstallResult, context: FlowInstallContext): void {\n logInstallationResult(\n result,\n context.packageName,\n context.platform,\n context.dryRun ?? false\n );\n }\n \n /**\n * Create an error result\n */\n protected createErrorResult(\n context: FlowInstallContext,\n error: Error,\n message: string\n ): FlowInstallResult {\n return {\n success: false,\n filesProcessed: 0,\n filesWritten: 0,\n conflicts: [],\n errors: [{\n flow: { from: context.packageRoot, to: context.workspaceRoot },\n sourcePath: context.packageRoot,\n error,\n message\n }],\n targetPaths: [],\n fileMapping: {}\n };\n }\n \n /**\n * Apply resource filtering to flow sources (Phase 4: Resource model)\n * \n * Filters sources based on matched pattern (from base detection or resource scoping).\n * \n * @param flowSources - Map of flows to source paths\n * @param matchedPattern - Pattern that matched for base detection\n * @param packageRoot - Package root directory\n * @returns Filtered flow sources\n */\n protected applyResourceFiltering(\n flowSources: Map<any, string[]>,\n matchedPattern: string | undefined,\n packageRoot: string\n ): Map<any, string[]> {\n // If no filtering specified, return original sources\n if (!matchedPattern) {\n return flowSources;\n }\n \n const normalizedPattern = matchedPattern.replace(/\\\\/g, '/');\n \n const filteredSources = new Map<any, string[]>();\n \n for (const [flow, sources] of flowSources.entries()) {\n const filtered = sources.filter(sourcePath => {\n // discoverFlowSources returns paths relative to packageRoot already.\n // However, some callers may provide absolute paths. Support both robustly.\n const isAbs = sourcePath.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(sourcePath);\n const normalizedSource = sourcePath.replace(/\\\\/g, '/');\n const relativePath = (isAbs ? relative(packageRoot, sourcePath) : normalizedSource).replace(/\\\\/g, '/');\n \n // Check matched pattern if specified\n if (!minimatch(relativePath, normalizedPattern)) {\n return false;\n }\n \n return true;\n });\n \n if (filtered.length > 0) {\n filteredSources.set(flow, filtered);\n }\n }\n\n return filteredSources;\n }\n}\n", "/**\n * Platform Converter Module\n * \n * High-level orchestration for converting packages between formats:\n * - Platform-specific \u2192 Universal \u2192 Platform-specific\n * - Direct installation when source = target platform\n */\n\nimport { join, relative } from 'path';\nimport { promises as fs } from 'fs';\nimport type { Package, PackageFile } from '../../types/index.js';\nimport type { PackageConversionContext } from '../../types/conversion-context.js';\nimport type { Platform } from '../platforms.js';\nimport type { Flow, FlowContext, FlowResult } from '../../types/flows.js';\nimport type { PackageFormat } from '../install/format-detector.js';\nimport { \n detectPackageFormat, \n isPlatformSpecific,\n needsConversion \n} from '../install/format-detector.js';\nimport { getPlatformDefinition, getGlobalImportFlows } from '../platforms.js';\nimport { createFlowExecutor } from './flow-executor.js';\nimport { logger } from '../../utils/logger.js';\nimport { ensureDir, writeTextFile, readTextFile } from '../../utils/fs.js';\nimport { tmpdir } from 'os';\nimport { mkdtemp, rm } from 'fs/promises';\nimport { minimatch } from 'minimatch';\nimport { \n createContextFromPackage,\n updateContextAfterConversion,\n withTargetPlatform \n} from '../conversion-context/index.js';\n\n/**\n * Conversion pipeline stage\n */\nexport interface ConversionStage {\n name: string;\n description: string;\n flows: Flow[];\n inverted: boolean;\n}\n\n/**\n * Conversion pipeline definition\n */\nexport interface ConversionPipeline {\n source: PackageFormat;\n target: Platform;\n stages: ConversionStage[];\n needsConversion: boolean;\n}\n\n/**\n * Conversion options\n */\nexport interface ConversionOptions {\n dryRun?: boolean;\n}\n\n/**\n * Conversion result with updated context\n */\nexport interface ConversionResult {\n success: boolean;\n convertedPackage?: Package;\n updatedContext?: PackageConversionContext;\n stages: Array<{\n stage: string;\n filesProcessed: number;\n success: boolean;\n error?: string;\n }>;\n}\n\n/**\n * Platform Converter\n * \n * Orchestrates multi-stage conversions between package formats\n */\nexport class PlatformConverter {\n private workspaceRoot: string;\n \n constructor(workspaceRoot: string) {\n this.workspaceRoot = workspaceRoot;\n }\n \n /**\n * Convert a package to target platform format with conversion context\n * \n * @param pkg - Package to convert\n * @param context - Conversion context (optional, will be created if not provided)\n * @param targetPlatform - Target platform\n * @param options - Conversion options\n * @returns Conversion result with updated context\n */\n async convert(\n pkg: Package,\n context: PackageConversionContext | undefined,\n targetPlatform: Platform,\n options?: ConversionOptions\n ): Promise<ConversionResult> {\n logger.info('Starting platform conversion', {\n package: pkg.metadata.name,\n targetPlatform,\n hasContext: !!context\n });\n \n // Create or use provided context\n const conversionContext = context || createContextFromPackage(pkg);\n \n // Set target platform\n const contextWithTarget = withTargetPlatform(conversionContext, targetPlatform);\n \n // Use provided format if available, otherwise detect from files\n const sourceFormat = pkg._format || detectPackageFormat(pkg.files);\n \n logger.debug('Source format', {\n type: sourceFormat.type,\n platform: sourceFormat.platform,\n confidence: sourceFormat.confidence,\n source: pkg._format ? 'provided' : 'detected',\n contextOriginal: conversionContext.originalFormat.platform\n });\n \n // Build conversion pipeline\n const pipeline = this.buildPipeline(sourceFormat, targetPlatform);\n \n if (!pipeline.needsConversion) {\n logger.info('No conversion needed - formats match');\n return {\n success: true,\n convertedPackage: pkg,\n updatedContext: contextWithTarget,\n stages: []\n };\n }\n \n // Execute pipeline with context\n return await this.executePipeline(pkg, contextWithTarget, pipeline, options);\n }\n \n /**\n * Build conversion pipeline based on source and target formats\n */\n buildPipeline(\n sourceFormat: PackageFormat,\n targetPlatform: Platform\n ): ConversionPipeline {\n const stages: ConversionStage[] = [];\n const needsConv = needsConversion(sourceFormat, targetPlatform);\n \n logger.info('Checking if conversion needed', {\n sourceType: sourceFormat.type,\n sourcePlatform: sourceFormat.platform,\n targetPlatform,\n needsConversion: needsConv\n });\n \n if (!needsConv) {\n return {\n source: sourceFormat,\n target: targetPlatform,\n stages: [],\n needsConversion: false\n };\n }\n \n // Platform-specific \u2192 Universal\n if (isPlatformSpecific(sourceFormat) && sourceFormat.platform) {\n const sourcePlatform = sourceFormat.platform;\n \n // Get source platform import flows (these transform workspace \u2192 package)\n const platformDef = getPlatformDefinition(sourcePlatform, this.workspaceRoot);\n const platformImportFlows = platformDef.import || [];\n const globalImportFlows = getGlobalImportFlows(this.workspaceRoot) || [];\n \n const allImportFlows = [...globalImportFlows, ...platformImportFlows];\n \n logger.info(`Building conversion stage with ${allImportFlows.length} import flows`, {\n sourcePlatform,\n flowCount: allImportFlows.length\n });\n\n // IMPORTANT:\n // These \"import\" flows are defined to read platform-specific paths (e.g. \".claude-plugin/plugin.json\")\n // from the source package and write universal outputs (e.g. \"openpackage.yml\").\n //\n // We should NOT strip the platform prefix here. Doing so turns \".claude-plugin/plugin.json\" into\n // \"plugin.json\", which will not exist in a real Claude plugin repository and makes the\n // platform-to-universal stage a no-op (causing infinite re-detection/re-conversion loops).\n const adjustedFlows = allImportFlows;\n \n stages.push({\n name: 'platform-to-universal',\n description: `Convert from ${sourcePlatform} format to universal format`,\n flows: adjustedFlows,\n inverted: false // Not inverted - using import flows directly\n });\n }\n \n // Universal \u2192 Target Platform\n // Note: This stage will be handled by the normal flow-based installer\n // We only need to convert TO universal here; the installer handles universal \u2192 platform\n \n return {\n source: sourceFormat,\n target: targetPlatform,\n stages,\n needsConversion: true\n };\n }\n \n /**\n * Execute conversion pipeline with context\n */\n async executePipeline(\n pkg: Package,\n context: PackageConversionContext,\n pipeline: ConversionPipeline,\n options?: ConversionOptions\n ): Promise<ConversionResult> {\n const result: ConversionResult = {\n success: true,\n stages: []\n };\n \n let currentPackage = pkg;\n let currentContext = context;\n const dryRun = options?.dryRun ?? false;\n \n // Create temporary directory for intermediate files\n let tempDir: string | null = null;\n \n try {\n tempDir = await mkdtemp(join(tmpdir(), 'opkg-convert-'));\n \n for (const stage of pipeline.stages) {\n logger.info(`Executing conversion stage: ${stage.name}`);\n \n const stageResult = await this.executeStage(\n currentPackage,\n currentContext,\n stage,\n tempDir,\n dryRun,\n pipeline.target\n );\n \n result.stages.push({\n stage: stage.name,\n filesProcessed: stageResult.filesProcessed,\n success: stageResult.success,\n error: stageResult.error\n });\n \n if (!stageResult.success) {\n result.success = false;\n result.updatedContext = currentContext;\n return result;\n }\n \n // Update package with converted files\n if (stageResult.convertedFiles) {\n currentPackage = {\n ...currentPackage,\n files: stageResult.convertedFiles,\n // Update format to universal (source platform tracked in context)\n _format: {\n type: 'universal',\n platform: undefined,\n confidence: 1.0,\n analysis: {\n universalFiles: stageResult.convertedFiles.length,\n platformSpecificFiles: 0,\n detectedPlatforms: new Map(),\n totalFiles: stageResult.convertedFiles.length,\n samplePaths: {\n universal: stageResult.convertedFiles.slice(0, 3).map(f => f.path),\n platformSpecific: []\n }\n }\n }\n };\n \n // Update context after conversion\n currentContext = updateContextAfterConversion(\n currentContext,\n { type: 'universal', platform: undefined },\n pipeline.target\n );\n }\n }\n \n result.convertedPackage = currentPackage;\n result.updatedContext = currentContext;\n return result;\n \n } catch (error) {\n logger.error('Conversion pipeline failed', { error });\n result.success = false;\n result.updatedContext = currentContext;\n result.stages.push({\n stage: 'pipeline',\n filesProcessed: 0,\n success: false,\n error: (error as Error).message\n });\n return result;\n \n } finally {\n // Cleanup temp directory\n if (tempDir) {\n try {\n await rm(tempDir, { recursive: true, force: true });\n } catch (error) {\n logger.warn('Failed to cleanup temp directory', { tempDir, error });\n }\n }\n }\n }\n \n /**\n * Discover files matching a glob pattern\n */\n private async discoverMatchingFiles(\n pattern: string | string[] | import('../../types/flows.js').SwitchExpression,\n baseDir: string\n ): Promise<string[]> {\n // Handle switch expressions\n if (typeof pattern === 'object' && '$switch' in pattern) {\n throw new Error('Cannot discover files from SwitchExpression - expression must be resolved first');\n }\n const patterns = Array.isArray(pattern) ? pattern : [pattern];\n const matches: string[] = [];\n \n // Walk all files in baseDir\n async function* walkFiles(dir: string): AsyncGenerator<string> {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n \n if (entry.isDirectory()) {\n yield* walkFiles(fullPath);\n } else if (entry.isFile()) {\n yield fullPath;\n }\n }\n }\n \n // Check each file against the patterns\n for await (const filePath of walkFiles(baseDir)) {\n const relativePath = relative(baseDir, filePath);\n \n // Check if file matches any pattern (with priority - first match wins for arrays)\n for (const p of patterns) {\n // IMPORTANT: conversion must match dotfiles like \".claude-plugin/plugin.json\".\n // If dotfiles don't match, platform-to-universal stages can become no-ops and loop forever.\n if (minimatch(relativePath, p, { dot: true })) {\n matches.push(filePath);\n break; // Only match once per file\n }\n }\n }\n \n return matches;\n }\n \n /**\n * Execute a single conversion stage with context\n */\n private async executeStage(\n pkg: Package,\n context: PackageConversionContext,\n stage: ConversionStage,\n tempDir: string,\n dryRun: boolean,\n targetPlatform: Platform\n ): Promise<{\n success: boolean;\n filesProcessed: number;\n convertedFiles?: PackageFile[];\n error?: string;\n }> {\n try {\n const executor = createFlowExecutor();\n const convertedFiles: PackageFile[] = [];\n let filesProcessed = 0;\n const matchedSources = new Set<string>();\n \n // Create isolated input/output roots for this stage\n const stageRoot = join(tempDir, stage.name);\n const packageRoot = join(stageRoot, 'in');\n const outputRoot = join(stageRoot, 'out');\n await ensureDir(packageRoot);\n await ensureDir(outputRoot);\n \n // Write package files to temp directory\n for (const file of pkg.files) {\n const filePath = join(packageRoot, file.path);\n await ensureDir(join(filePath, '..'));\n await writeTextFile(filePath, file.content);\n }\n \n // Build flow context with proper platform variables for conditional evaluation\n // During conversion, we set:\n // - $$platform = target platform (for conditionals like \"$eq\": [\"$$platform\", \"claude\"])\n // - $$source = original source format (for conditionals like \"$eq\": [\"$$source\", \"claude-plugin\"])\n const flowContext: FlowContext = {\n workspaceRoot: outputRoot, // Write outputs away from inputs\n packageRoot,\n platform: targetPlatform, // Use target platform for conditional evaluation\n packageName: pkg.metadata.name,\n direction: 'install', // Always use 'install' direction for conversion\n variables: {\n name: pkg.metadata.name,\n version: pkg.metadata.version || '0.0.0',\n platform: targetPlatform, // For conditional: \"$eq\": [\"$$platform\", \"claude\"]\n source: context.originalFormat.platform || 'openpackage', // Use context for $$source\n sourcePlatform: context.originalFormat.platform || 'openpackage', // Use context for sourcePlatform\n targetPlatform: targetPlatform\n },\n dryRun\n };\n \n // Execute flows for each matching file\n for (const flow of stage.flows) {\n // Discover files that match the flow's 'from' pattern\n const matchingFiles = await this.discoverMatchingFiles(\n flow.from,\n packageRoot\n );\n \n logger.info(`Flow pattern matching`, {\n pattern: flow.from,\n matchCount: matchingFiles.length,\n matches: matchingFiles.map(f => relative(packageRoot, f))\n });\n \n if (matchingFiles.length === 0) {\n logger.debug('No files match flow pattern', { \n pattern: flow.from,\n packageRoot \n });\n continue;\n }\n \n // Execute flow for each matching file\n for (const sourceFile of matchingFiles) {\n const sourceRelative = relative(packageRoot, sourceFile);\n matchedSources.add(sourceRelative);\n \n // Create concrete flow with specific file path\n const concreteFlow: Flow = {\n ...flow,\n from: sourceRelative\n };\n \n const flowResult = await executor.executeFlow(concreteFlow, flowContext);\n \n if (!flowResult.success) {\n return {\n success: false,\n filesProcessed,\n error: `Flow execution failed for ${sourceRelative}: ${flowResult.error?.message}`\n };\n }\n \n filesProcessed++;\n \n // Collect transformed files\n if (typeof flowResult.target === 'string') {\n const targetPath = relative(outputRoot, flowResult.target);\n \n // Read transformed file content\n try {\n const content = await readTextFile(flowResult.target);\n \n convertedFiles.push({\n path: targetPath,\n content,\n encoding: 'utf8'\n });\n } catch (error) {\n logger.warn('Failed to read converted file', { \n target: flowResult.target, \n error \n });\n }\n }\n }\n }\n\n return {\n success: true,\n filesProcessed,\n convertedFiles: convertedFiles.length > 0 ? convertedFiles : undefined\n };\n \n } catch (error) {\n logger.error('Stage execution failed', { stage: stage.name, error });\n return {\n success: false,\n filesProcessed: 0,\n error: (error as Error).message\n };\n }\n }\n}\n\n/**\n * Create a platform converter instance\n */\nexport function createPlatformConverter(workspaceRoot: string): PlatformConverter {\n return new PlatformConverter(workspaceRoot);\n}\n", "/**\n * Standard Flow-Based Installation Strategy\n * \n * Applies platform flows with full transformations.\n * Used for universal format packages.\n */\n\nimport { join, relative, dirname, basename } from 'path';\nimport type { Platform } from '../../platforms.js';\nimport type { PackageFormat } from '../format-detector.js';\nimport type { InstallOptions } from '../../../types/index.js';\nimport type { FlowInstallContext, FlowInstallResult } from './types.js';\nimport type { Flow, FlowContext, SwitchExpression } from '../../../types/flows.js';\nimport { BaseStrategy } from './base-strategy.js';\nimport { platformUsesFlows } from '../../platforms.js';\nimport { filterSourcesByPlatform } from './helpers/platform-filtering.js';\nimport { convertToInstallResult } from './helpers/result-converter.js';\nimport { discoverFlowSources } from '../../flows/flow-source-discovery.js';\nimport { executeFlowsForSources } from '../../flows/flow-execution-coordinator.js';\nimport {\n resolveTargetFromGlob,\n} from '../../flows/flow-execution-coordinator.js';\nimport {\n resolvePattern,\n extractCapturedName,\n getFirstFromPattern,\n} from '../../flows/flow-source-discovery.js';\nimport { resolveSwitchExpression } from '../../flows/switch-resolver.js';\nimport {\n buildOwnershipContext,\n resolveConflictsForTargets,\n namespaceFlowToPattern,\n type TargetEntry,\n} from '../conflicts/file-conflict-resolver.js';\nimport { normalizePathForProcessing } from '../../../utils/path-normalization.js';\nimport { logger } from '../../../utils/logger.js';\nimport { readWorkspaceIndex } from '../../../utils/workspace-index-yml.js';\n\n/**\n * Standard Flow-Based Installation Strategy\n * \n * Applies platform flows with full transformations.\n * Used for universal format packages.\n */\nexport class FlowBasedInstallStrategy extends BaseStrategy {\n readonly name = 'flow-based';\n \n canHandle(format: PackageFormat, platform: Platform): boolean {\n // Default strategy - handles all remaining cases\n return true;\n }\n \n async install(\n context: FlowInstallContext,\n options?: InstallOptions,\n forceOverwrite: boolean = false\n ): Promise<FlowInstallResult> {\n const { packageName, packageRoot, workspaceRoot, platform, dryRun } = context;\n \n this.logStrategySelection(context);\n \n // Check if platform uses flows\n if (!platformUsesFlows(platform, workspaceRoot)) {\n return this.createEmptyResult();\n }\n \n // Get applicable flows\n const flows = this.getApplicableFlows(platform, workspaceRoot);\n if (flows.length === 0) {\n return this.createEmptyResult();\n }\n \n // Build context\n const flowContext = this.buildFlowContext(context, 'install');\n \n // Discover sources\n const flowSources = await discoverFlowSources(flows, packageRoot, flowContext);\n\n // Apply resource filtering if specified\n const resourceFilteredSources = this.applyResourceFiltering(\n flowSources,\n context.matchedPattern,\n packageRoot\n );\n \n // Filter by platform\n const filteredSources = filterSourcesByPlatform(resourceFilteredSources, platform);\n\n // -----------------------------------------------------------------------\n // File-level conflict resolution (Phase 3)\n // -----------------------------------------------------------------------\n const effectiveOptions = options ?? {};\n const conflictWarnings: string[] = [];\n let wasNamespaced = false;\n let conflictRelocatedFiles: Array<{ from: string; to: string }> = [];\n\n try {\n // Pre-compute the target paths that will be written by the flows\n const targets = this.computeTargetEntries(filteredSources, flowContext);\n\n if (targets.length > 0) {\n // Load the package's previous workspace-index record to determine previously-owned paths\n const previousRecord = await this.readPreviousIndexRecord(workspaceRoot, packageName);\n\n // Build ownership context (other-package indexes + previous-owned paths)\n const ownershipContext = await buildOwnershipContext(\n workspaceRoot,\n packageName,\n previousRecord\n );\n\n // Resolve conflicts \u2014 get back the filtered set of allowed targets\n const { allowedTargets, warnings, packageWasNamespaced, namespaceDir, relocatedFiles } = await resolveConflictsForTargets(\n workspaceRoot,\n targets,\n ownershipContext,\n effectiveOptions,\n packageName,\n forceOverwrite\n );\n conflictWarnings.push(...warnings);\n wasNamespaced = packageWasNamespaced;\n conflictRelocatedFiles = relocatedFiles;\n\n // When bulk namespacing was triggered, rewrite every non-merge flow's\n // `to` pattern so the executor writes files to namespaced locations.\n const sourcesToExecute = packageWasNamespaced && namespaceDir\n ? this.rewriteFlowsForNamespace(filteredSources, namespaceDir)\n : filteredSources;\n\n // Rebuild filteredSources keeping only flows whose targets were allowed.\n // Normalize paths to ensure consistent comparison (conflict resolver uses normalizePathForProcessing).\n const allowedRelPaths = new Set(\n allowedTargets.map(t => normalizePathForProcessing(t.relPath))\n );\n const prunedSources = this.pruneSourcesByAllowedTargets(\n sourcesToExecute,\n flowContext,\n allowedRelPaths\n );\n\n // Execute flows on the pruned source set\n const executionResult = await executeFlowsForSources(prunedSources, flowContext);\n const result = convertToInstallResult(executionResult, packageName, platform, dryRun);\n\n // Surface conflict warnings as additional FlowConflictReport entries\n for (const msg of conflictWarnings) {\n logger.warn(msg);\n result.conflicts.push({\n targetPath: '',\n packages: [{ packageName, priority: 0, chosen: true }],\n message: msg\n });\n }\n\n // Attach namespace metadata to the result\n result.namespaced = wasNamespaced;\n result.relocatedFiles = conflictRelocatedFiles;\n\n this.logResults(result, context);\n return result;\n }\n } catch (error) {\n // Conflict resolution is best-effort: on unexpected failure log and continue\n logger.warn(`File conflict resolution failed for ${packageName}: ${error}. Proceeding without conflict checks.`);\n }\n\n // Execute flows (no targets to conflict-check, or conflict resolution errored)\n const executionResult = await executeFlowsForSources(filteredSources, flowContext);\n \n // Convert to result\n const result = convertToInstallResult(executionResult, packageName, platform, dryRun);\n \n this.logResults(result, context);\n \n return result;\n }\n\n // -------------------------------------------------------------------------\n // Helpers\n // -------------------------------------------------------------------------\n\n /**\n * Pre-compute the workspace-relative target path for each (flow, source) pair\n * using the same resolution logic as the flow execution coordinator.\n * Each entry is annotated with the resolved `to` pattern and merge-flow flag\n * so that the conflict resolver can derive namespace insertion points and\n * correctly exclude merge flows from namespacing.\n */\n private computeTargetEntries(\n flowSources: Map<Flow, string[]>,\n flowContext: FlowContext\n ): TargetEntry[] {\n const entries: TargetEntry[] = [];\n\n for (const [flow, sources] of flowSources) {\n const firstPattern = getFirstFromPattern(flow.from);\n // A flow is a merge flow when its merge strategy is not plain 'replace'\n // (deep, shallow, and composite all produce merged/combined output)\n const isMergeFlow = Boolean(\n flow.merge && flow.merge !== 'replace'\n );\n\n for (const sourceRel of sources) {\n try {\n const sourceAbs = join(flowContext.packageRoot, sourceRel);\n const capturedName = extractCapturedName(sourceRel, firstPattern);\n\n const sourceContext: FlowContext = {\n ...flowContext,\n variables: {\n ...flowContext.variables,\n sourcePath: sourceRel,\n sourceDir: dirname(sourceRel),\n sourceFile: basename(sourceRel),\n ...(capturedName ? { capturedName } : {})\n }\n };\n\n let rawToPattern: string;\n if (typeof flow.to === 'string') {\n rawToPattern = flow.to;\n } else if (isSwitchExpression(flow.to)) {\n rawToPattern = resolveSwitchExpression(flow.to as SwitchExpression, sourceContext);\n } else if (typeof flow.to === 'object' && flow.to !== null && 'pattern' in flow.to) {\n rawToPattern = (flow.to as { pattern: string }).pattern;\n } else {\n rawToPattern = Object.keys(flow.to as object)[0] ?? '';\n }\n\n const resolvedToPattern = resolvePattern(rawToPattern, sourceContext, capturedName);\n const targetAbs = resolveTargetFromGlob(\n sourceAbs,\n firstPattern,\n resolvedToPattern,\n sourceContext\n );\n\n const targetRelRaw = relative(flowContext.workspaceRoot, targetAbs);\n const targetRel = targetRelRaw.replace(/\\\\/g, '/');\n\n entries.push({\n relPath: targetRel,\n absPath: targetAbs,\n flowToPattern: resolvedToPattern,\n isMergeFlow\n });\n } catch {\n // If target resolution fails for a source, skip it \u2014 the executor\n // will handle the error properly during execution.\n }\n }\n }\n\n return entries;\n }\n\n /**\n * Rewrite the `to` pattern of every non-merge flow to include the namespace\n * subdirectory. Returns a new Map \u2014 the original is not mutated.\n *\n * Merge flows (deep / shallow / composite) are left untouched because they\n * produce a single combined output file that is intentionally shared across\n * packages.\n */\n private rewriteFlowsForNamespace(\n flowSources: Map<Flow, string[]>,\n namespaceDir: string\n ): Map<Flow, string[]> {\n const rewritten = new Map<Flow, string[]>();\n\n for (const [flow, sources] of flowSources) {\n const isMerge = Boolean(flow.merge && flow.merge !== 'replace');\n if (isMerge) {\n // Keep merge flows exactly as-is\n rewritten.set(flow, sources);\n continue;\n }\n\n // Rewrite the `to` field to include the namespace\n let newTo: Flow['to'];\n if (typeof flow.to === 'string') {\n newTo = namespaceFlowToPattern(flow.to, namespaceDir);\n } else if (\n typeof flow.to === 'object' &&\n flow.to !== null &&\n '$switch' in flow.to\n ) {\n // SwitchExpression \u2014 rewrite each case value and the default\n const sw = flow.to as any;\n const rewriteSwitchValue = (v: any): any => {\n if (typeof v === 'string') return namespaceFlowToPattern(v, namespaceDir);\n if (typeof v === 'object' && v !== null && 'pattern' in v) {\n return { ...v, pattern: namespaceFlowToPattern(v.pattern, namespaceDir) };\n }\n return v;\n };\n newTo = {\n $switch: {\n ...sw.$switch,\n cases: sw.$switch.cases.map((c: any) => ({\n ...c,\n value: rewriteSwitchValue(c.value)\n })),\n ...(sw.$switch.default !== undefined\n ? { default: rewriteSwitchValue(sw.$switch.default) }\n : {})\n }\n } as unknown as Flow['to'];\n } else if (\n typeof flow.to === 'object' &&\n flow.to !== null &&\n 'pattern' in flow.to\n ) {\n newTo = { pattern: namespaceFlowToPattern((flow.to as any).pattern, namespaceDir) } as Flow['to'];\n } else if (typeof flow.to === 'object' && flow.to !== null) {\n // MultiTargetFlows \u2014 rewrite each key\n const multi: Record<string, any> = {};\n for (const [key, val] of Object.entries(flow.to as object)) {\n multi[namespaceFlowToPattern(key, namespaceDir)] = val;\n }\n newTo = multi as Flow['to'];\n } else {\n newTo = flow.to;\n }\n\n rewritten.set({ ...flow, to: newTo }, sources);\n }\n\n return rewritten;\n }\n\n /**\n * Remove from filteredSources any (flow, source) pair whose resolved target\n * was not in the allowedRelPaths set.\n */\n private pruneSourcesByAllowedTargets(\n flowSources: Map<Flow, string[]>,\n flowContext: FlowContext,\n allowedRelPaths: Set<string>\n ): Map<Flow, string[]> {\n const pruned = new Map<Flow, string[]>();\n\n for (const [flow, sources] of flowSources) {\n const firstPattern = getFirstFromPattern(flow.from);\n const keptSources: string[] = [];\n\n for (const sourceRel of sources) {\n try {\n const sourceAbs = join(flowContext.packageRoot, sourceRel);\n const capturedName = extractCapturedName(sourceRel, firstPattern);\n\n const sourceContext: FlowContext = {\n ...flowContext,\n variables: {\n ...flowContext.variables,\n sourcePath: sourceRel,\n sourceDir: dirname(sourceRel),\n sourceFile: basename(sourceRel),\n ...(capturedName ? { capturedName } : {})\n }\n };\n\n let rawToPattern: string;\n if (typeof flow.to === 'string') {\n rawToPattern = flow.to;\n } else if (isSwitchExpression(flow.to)) {\n rawToPattern = resolveSwitchExpression(flow.to as SwitchExpression, sourceContext);\n } else if (typeof flow.to === 'object' && flow.to !== null && 'pattern' in flow.to) {\n rawToPattern = (flow.to as { pattern: string }).pattern;\n } else {\n rawToPattern = Object.keys(flow.to as object)[0] ?? '';\n }\n\n const resolvedToPattern = resolvePattern(rawToPattern, sourceContext, capturedName);\n const targetAbs = resolveTargetFromGlob(\n sourceAbs,\n firstPattern,\n resolvedToPattern,\n sourceContext\n );\n const targetRelRaw = relative(flowContext.workspaceRoot, targetAbs);\n const targetRel = normalizePathForProcessing(targetRelRaw);\n\n if (allowedRelPaths.has(targetRel)) {\n keptSources.push(sourceRel);\n }\n } catch {\n // On resolution failure, keep the source so the executor handles it\n keptSources.push(sourceRel);\n }\n }\n\n if (keptSources.length > 0) {\n pruned.set(flow, keptSources);\n }\n }\n\n return pruned;\n }\n\n /**\n * Read the package's existing workspace-index entry (its files mapping),\n * used to determine which paths were previously owned by this package.\n */\n private async readPreviousIndexRecord(\n cwd: string,\n packageName: string\n ): Promise<{ files: Record<string, any[]> } | null> {\n try {\n const wsRecord = await readWorkspaceIndex(cwd);\n const entry = wsRecord.index.packages?.[packageName];\n if (!entry) return null;\n return { files: entry.files ?? {} };\n } catch {\n return null;\n }\n }\n}\n\n// -------------------------------------------------------------------------\n// Module-private helper (mirrors isSwitchExpression in flow-execution-coordinator)\n// -------------------------------------------------------------------------\nfunction isSwitchExpression(value: unknown): value is SwitchExpression {\n return (\n typeof value === 'object' &&\n value !== null &&\n '$switch' in (value as object)\n );\n}\n", "/**\n * Platform Filtering Helpers Module\n * \n * Utilities for filtering source files based on platform specificity.\n */\n\nimport { basename } from 'path';\nimport type { Flow } from '../../../../types/flows.js';\nimport type { Platform } from '../../../platforms.js';\nimport {\n buildOverrideMap,\n shouldSkipUniversalFile,\n isPlatformSpecificFileForTarget\n} from '../../../flows/platform-suffix-handler.js';\nimport { isPlatformId } from '../../../platforms.js';\n\n/**\n * Filter flow sources by platform, removing files not applicable to target platform\n * \n * @param flowSources - Map of flows to source file paths\n * @param platform - Target platform\n * @returns Filtered map with only applicable sources\n */\nexport function filterSourcesByPlatform(\n flowSources: Map<Flow, string[]>,\n platform: Platform\n): Map<Flow, string[]> {\n const filtered = new Map<Flow, string[]>();\n \n // Build override map once for all sources\n const allSources: string[] = [];\n for (const sources of flowSources.values()) {\n allSources.push(...sources);\n }\n const overrideMap = buildOverrideMap(allSources);\n \n for (const [flow, sources] of flowSources) {\n const filteredSourcesForFlow: string[] = [];\n \n for (const sourceRel of sources) {\n // Skip platform-specific files not for this platform\n if (!isPlatformSpecificFileForTarget(sourceRel, platform) && \n sourceRel.includes('.') && \n sourceRel.split('.').length >= 3) {\n const parts = basename(sourceRel).split('.');\n const possiblePlatform = parts[parts.length - 2];\n if (possiblePlatform !== platform && isPlatformId(possiblePlatform)) {\n continue;\n }\n }\n \n // Skip universal files with platform overrides\n if (shouldSkipUniversalFile(sourceRel, platform, allSources, overrideMap)) {\n continue;\n }\n \n filteredSourcesForFlow.push(sourceRel);\n }\n \n if (filteredSourcesForFlow.length > 0) {\n filtered.set(flow, filteredSourcesForFlow);\n }\n }\n \n return filtered;\n}\n\n/**\n * Re-export utilities for convenience\n */\nexport { buildOverrideMap, shouldSkipUniversalFile, isPlatformSpecificFileForTarget };\n", "/**\n * Flow Source Discovery\n * \n * Discovers source files that match flow patterns.\n * Handles glob patterns, {name} placeholders, and priority-based pattern matching.\n */\n\nimport { promises as fs } from 'fs';\nimport { join, dirname, basename, relative } from 'path';\nimport { minimatch } from 'minimatch';\nimport type { Flow, FlowContext, SwitchExpression } from '../../types/flows.js';\nimport { exists } from '../../utils/fs.js';\nimport { getAllPlatforms } from '../platforms.js';\nimport type { Platform } from '../platforms.js';\nimport { logger } from '../../utils/logger.js';\n\nfunction isFlowPatternValue(value: any): value is { pattern: string; schema?: string } {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'pattern' in value &&\n typeof (value as any).pattern === 'string'\n );\n}\n\nfunction unwrapPatternValue(value: any): any {\n return isFlowPatternValue(value) ? value.pattern : value;\n}\n\n/**\n * Discovery result for a single flow\n */\nexport interface FlowSourceDiscovery {\n flow: Flow;\n sources: string[];\n}\n\n/**\n * Discovery options\n */\nexport interface DiscoveryOptions {\n /**\n * Enable caching of pattern matches (default: false)\n */\n enableCache?: boolean;\n \n /**\n * Prefer dot-prefixed files for root-level patterns (default: true)\n * When true, checks .mcp.json before mcp.jsonc\n */\n preferDotPrefixed?: boolean;\n \n /**\n * Include platform-specific file variants (default: true)\n */\n includePlatformVariants?: boolean;\n}\n\n/**\n * Discover source files that match flow patterns\n * \n * @param flows - Flows to discover sources for\n * @param packageRoot - Package root directory\n * @param context - Flow execution context\n * @param options - Discovery options\n * @returns Map of flow to discovered source paths\n */\nexport async function discoverFlowSources(\n flows: Flow[],\n packageRoot: string,\n context: FlowContext,\n options: DiscoveryOptions = {}\n): Promise<Map<Flow, string[]>> {\n const flowSources = new Map<Flow, string[]>();\n const {\n preferDotPrefixed = true,\n includePlatformVariants = true\n } = options;\n \n for (const flow of flows) {\n // Handle array patterns: check all patterns, not just the first\n const patterns = Array.isArray(flow.from) ? flow.from : [flow.from];\n const allSourcePaths = new Set<string>();\n \n // Track dot-prefixed files found to avoid duplicates\n const dotPrefixedPathsFound = new Set<string>();\n const dotPrefixedBaseNames = new Set<string>();\n \n // First pass: check for dot-prefixed variants (if enabled)\n if (preferDotPrefixed) {\n for (const pattern of patterns) {\n const sourcePattern = resolvePattern(pattern, context);\n \n // Check for dot-prefixed variants for root-level files only\n if (!sourcePattern.includes('/') && !sourcePattern.startsWith('.')) {\n const dotPrefixedPattern = `.${sourcePattern}`;\n const dotPrefixedPaths = await matchPattern(dotPrefixedPattern, packageRoot);\n \n for (const path of dotPrefixedPaths) {\n dotPrefixedPathsFound.add(path);\n \n // Extract base name for similarity matching\n const baseName = path.replace(/^\\./, '').split('.')[0];\n dotPrefixedBaseNames.add(baseName);\n allSourcePaths.add(path);\n }\n }\n }\n }\n \n // Second pass: check non-dot patterns\n for (const pattern of patterns) {\n const sourcePattern = resolvePattern(pattern, context);\n \n // Skip non-dot pattern if dot-prefixed variant with same base was found\n if (!sourcePattern.includes('/') && !sourcePattern.startsWith('.')) {\n const patternBaseName = sourcePattern.split('.')[0];\n if (dotPrefixedBaseNames.has(patternBaseName)) {\n continue;\n }\n }\n \n const sourcePaths = await matchPattern(sourcePattern, packageRoot);\n for (const path of sourcePaths) {\n allSourcePaths.add(path);\n }\n }\n \n flowSources.set(flow, Array.from(allSourcePaths));\n }\n \n return flowSources;\n}\n\n/**\n * Resolve pattern placeholders like {name}\n * \n * Note: {name} is reserved for pattern matching and is NOT replaced\n * unless explicitly provided in the context variables via capturedName\n * \n * @param pattern - Pattern with placeholders\n * @param context - Flow context with variables\n * @param capturedName - Captured {name} value (optional)\n * @returns Resolved pattern\n */\nexport function resolvePattern(\n pattern: any,\n context: FlowContext,\n capturedName?: string\n): string {\n pattern = unwrapPatternValue(pattern);\n\n // Handle switch expressions\n if (typeof pattern === 'object' && '$switch' in pattern) {\n throw new Error('Cannot resolve SwitchExpression in resolvePattern - expression must be resolved first');\n }\n\n if (typeof pattern !== 'string') {\n throw new Error(`Invalid flow pattern type: expected string, got ${typeof pattern}`);\n }\n\n return pattern.replace(/{(\\w+)}/g, (match, key) => {\n // If capturedName is provided and this is {name}, use the captured value\n if (key === 'name' && capturedName !== undefined) {\n return capturedName;\n }\n \n // Otherwise, reserve {name} for pattern matching - don't substitute it\n if (key === 'name') {\n return match;\n }\n \n if (key in context.variables) {\n return String(context.variables[key]);\n }\n \n return match;\n });\n}\n\n/**\n * Extract the captured {name} value from a source path that matched a pattern\n * \n * @param sourcePath - Source path that matched\n * @param pattern - Pattern with {name} placeholder\n * @returns Captured name value, or undefined if no match\n * \n * @example\n * extractCapturedName('rules/typescript.md', 'rules/{name}.md') // => 'typescript'\n */\nexport function extractCapturedName(sourcePath: string, pattern: string): string | undefined {\n // Convert pattern to regex with capture group for {name}\n const regexPattern = pattern\n .replace(/\\{name\\}/g, '([^/]+)')\n .replace(/\\*/g, '.*')\n .replace(/\\./g, '\\\\.');\n \n const regex = new RegExp('^' + regexPattern + '$');\n const match = sourcePath.match(regex);\n \n if (match && match[1]) {\n return match[1];\n }\n \n return undefined;\n}\n\n/**\n * Get the first pattern from a flow's from field\n * \n * @param from - Flow from field (string, array, or switch expression)\n * @returns First pattern\n */\nexport function getFirstFromPattern(from: string | string[] | SwitchExpression): string {\n const value = unwrapPatternValue(Array.isArray(from) ? from[0] : from);\n if (typeof value === 'object' && value !== null && '$switch' in value) {\n throw new Error('Cannot get first pattern from SwitchExpression - expression must be resolved first');\n }\n if (typeof value !== 'string') {\n throw new Error(`Invalid flow.from pattern type: expected string, got ${typeof value}`);\n }\n return value;\n}\n\n/**\n * Match files against a pattern\n * \n * Supports:\n * - Simple exact paths\n * - {name} placeholders\n * - * wildcards\n * - ** recursive globs\n * - Platform-specific variant discovery\n * \n * @param pattern - Pattern to match\n * @param baseDir - Base directory to search in\n * @returns Array of matched file paths (relative to baseDir)\n */\nexport async function matchPattern(pattern: string, baseDir: string): Promise<string[]> {\n const matches: string[] = [];\n \n // Fast path: no wildcards/placeholders, check exact file and platform variants\n if (!pattern.includes('*') && !pattern.includes('{')) {\n const exactPath = join(baseDir, pattern);\n \n // Check for exact match\n if (await exists(exactPath)) {\n matches.push(relative(baseDir, exactPath));\n }\n \n // Also check for platform-specific variants\n const variants = await findPlatformVariants(exactPath, baseDir);\n matches.push(...variants);\n \n return matches;\n }\n \n // Globs: recursive walk with pattern matching\n const parts = pattern.split('/');\n const globPart = parts.findIndex(p => p.includes('*'));\n \n // No glob segment (e.g., {name}.md): scan the parent dir and filter\n if (globPart === -1) {\n const dirRel = dirname(pattern);\n const filePattern = basename(pattern);\n const searchDir = join(baseDir, dirRel);\n \n if (!(await exists(searchDir))) {\n return [];\n }\n \n const entries = await fs.readdir(searchDir, { withFileTypes: true });\n const regex = new RegExp(\n '^' +\n filePattern\n .replace(/\\{name\\}/g, '([^/]+)')\n .replace(/\\./g, '\\\\.')\n .replace(/\\*/g, '.*') +\n '$'\n );\n \n for (const entry of entries) {\n if (!entry.isFile()) continue;\n if (!regex.test(entry.name)) continue;\n matches.push(relative(baseDir, join(searchDir, entry.name)));\n }\n \n return matches;\n }\n \n // Pattern has glob segments\n const dirPath = join(baseDir, ...parts.slice(0, globPart));\n const filePattern = parts.slice(globPart).join('/');\n \n if (!(await exists(dirPath))) {\n return [];\n }\n \n await findMatchingFiles(dirPath, filePattern, baseDir, matches);\n return matches;\n}\n\n/**\n * Find platform-specific variants of a file\n * \n * @param exactPath - Exact file path (absolute)\n * @param baseDir - Base directory for relative path calculation\n * @returns Array of platform-specific variant paths (relative to baseDir)\n */\nasync function findPlatformVariants(\n exactPath: string,\n baseDir: string\n): Promise<string[]> {\n const matches: string[] = [];\n const dirPath = dirname(exactPath);\n const fileName = basename(exactPath);\n const nameParts = fileName.split('.');\n \n if (nameParts.length < 2 || !(await exists(dirPath))) {\n return matches;\n }\n \n // Get all known platforms\n const knownPlatforms = getAllPlatforms({ includeDisabled: true }) as readonly Platform[];\n \n // For each platform, check if a platform-specific variant exists\n const ext = nameParts[nameParts.length - 1];\n const baseName = nameParts.slice(0, -1).join('.');\n \n for (const platform of knownPlatforms) {\n const platformFileName = `${baseName}.${platform}.${ext}`;\n const platformPath = join(dirPath, platformFileName);\n \n if (await exists(platformPath)) {\n matches.push(relative(baseDir, platformPath));\n }\n }\n \n return matches;\n}\n\n/**\n * Recursively find files matching a pattern\n * \n * @param dir - Directory to search in\n * @param pattern - Pattern to match (may contain globs)\n * @param baseDir - Base directory for relative path calculation\n * @param matches - Array to accumulate matches\n */\nasync function findMatchingFiles(\n dir: string,\n pattern: string,\n baseDir: string,\n matches: string[]\n): Promise<void> {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n const rel = relative(baseDir, fullPath);\n \n if (entry.isDirectory()) {\n await findMatchingFiles(fullPath, pattern, baseDir, matches);\n } else if (entry.isFile()) {\n const matched = minimatch(rel, pattern, { dot: false });\n if (matched) {\n matches.push(rel);\n }\n }\n }\n } catch (error) {\n // Ignore permission errors\n if ((error as NodeJS.ErrnoException).code !== 'EACCES' && \n (error as NodeJS.ErrnoException).code !== 'EPERM') {\n logger.debug('Error reading directory during pattern matching', { dir, error });\n }\n }\n}\n\n/**\n * Batch discover sources for multiple flows\n * Returns flat array of all discoveries\n * \n * @param flows - Flows to discover sources for\n * @param packageRoot - Package root directory\n * @param context - Flow execution context\n * @param options - Discovery options\n * @returns Array of flow source discoveries\n */\nexport async function batchDiscoverFlowSources(\n flows: Flow[],\n packageRoot: string,\n context: FlowContext,\n options: DiscoveryOptions = {}\n): Promise<FlowSourceDiscovery[]> {\n const discoveries: FlowSourceDiscovery[] = [];\n const flowSourcesMap = await discoverFlowSources(flows, packageRoot, context, options);\n \n for (const [flow, sources] of flowSourcesMap) {\n discoveries.push({ flow, sources });\n }\n \n return discoveries;\n}\n\n/**\n * Count total discovered sources across all flows\n * \n * @param flowSources - Map of flows to sources\n * @returns Total number of unique source files\n */\nexport function countDiscoveredSources(flowSources: Map<Flow, string[]>): number {\n const allSources = new Set<string>();\n \n for (const sources of flowSources.values()) {\n for (const source of sources) {\n allSources.add(source);\n }\n }\n \n return allSources.size;\n}\n", "/**\n * Flow Execution Coordinator\n * \n * Coordinates flow execution for discovered source files.\n * Handles target path resolution, context building, and result aggregation.\n */\n\nimport { join, dirname, basename, relative, extname } from 'path';\nimport type { Flow, FlowContext, FlowResult, SwitchExpression } from '../../types/flows.js';\nimport type { FlowExecutor } from '../../types/flows.js';\nimport type { Platform } from '../platforms.js';\nimport type { WorkspaceIndexFileMapping } from '../../types/workspace-index.js';\nimport { createFlowExecutor } from './flow-executor.js';\nimport { \n resolvePattern, \n extractCapturedName, \n getFirstFromPattern \n} from './flow-source-discovery.js';\nimport { resolveRecursiveGlobTargetRelativePath } from '../glob-target-mapping.js';\nimport { logger } from '../../utils/logger.js';\nimport { stripPlatformSuffixFromFilename } from './platform-suffix-handler.js';\nimport { resolveSwitchExpression } from './switch-resolver.js';\n\n/**\n * Execution result with enhanced metadata\n */\nexport interface ExecutionResult {\n success: boolean;\n filesProcessed: number;\n filesWritten: number;\n targetPaths: string[];\n fileMapping: Record<string, (string | WorkspaceIndexFileMapping)[]>;\n conflicts: Array<{\n path: string;\n winner: string;\n losers: string[];\n }>;\n errors: Array<{\n flow: Flow;\n sourcePath: string;\n error: Error;\n message: string;\n }>;\n}\n\n/**\n * Execution context for coordinating flow execution\n */\nexport interface CoordinatorContext extends FlowContext {\n /**\n * Flow executor instance to use\n */\n executor?: FlowExecutor;\n}\n\n/**\n * Execute flows for discovered source files\n * \n * @param flowSources - Map of flows to source files\n * @param context - Execution context\n * @returns Execution result with aggregated metrics\n */\nexport async function executeFlowsForSources(\n flowSources: Map<Flow, string[]>,\n context: CoordinatorContext\n): Promise<ExecutionResult> {\n const result: ExecutionResult = {\n success: true,\n filesProcessed: 0,\n filesWritten: 0,\n targetPaths: [],\n fileMapping: {},\n conflicts: [],\n errors: []\n };\n \n const executor = context.executor || createFlowExecutor();\n \n for (const [flow, sources] of flowSources) {\n for (const sourceRel of sources) {\n try {\n const sourceResult = await processSourceFile(\n flow,\n sourceRel,\n context,\n executor\n );\n \n // Aggregate results\n if (sourceResult.processed) {\n result.filesProcessed++;\n }\n \n if (sourceResult.written && !context.dryRun) {\n result.filesWritten++;\n }\n \n if (sourceResult.targetPath) {\n result.targetPaths.push(sourceResult.targetPath);\n }\n \n if (sourceResult.fileMapping) {\n const key = sourceResult.mappingKey || sourceRel;\n if (!result.fileMapping[key]) {\n result.fileMapping[key] = [];\n }\n result.fileMapping[key].push(...sourceResult.fileMapping);\n }\n \n if (sourceResult.conflicts) {\n result.conflicts.push(...sourceResult.conflicts);\n }\n \n if (!sourceResult.success) {\n result.success = false;\n if (sourceResult.error) {\n result.errors.push({\n flow,\n sourcePath: sourceRel,\n error: sourceResult.error,\n message: sourceResult.error.message\n });\n }\n }\n \n } catch (error) {\n result.success = false;\n result.errors.push({\n flow,\n sourcePath: sourceRel,\n error: error as Error,\n message: `Error processing ${sourceRel}: ${(error as Error).message}`\n });\n }\n }\n }\n \n return result;\n}\n\n/**\n * Result from processing a single source file\n */\ninterface SourceProcessingResult {\n success: boolean;\n processed: boolean;\n written: boolean;\n targetPath?: string;\n fileMapping?: (string | WorkspaceIndexFileMapping)[];\n mappingKey?: string;\n conflicts?: Array<{\n path: string;\n winner: string;\n losers: string[];\n }>;\n error?: Error;\n}\n\n/**\n * Check if a value is a switch expression\n */\nfunction isSwitchExpression(value: any): value is SwitchExpression {\n return (\n typeof value === 'object' &&\n value !== null &&\n '$switch' in value\n );\n}\n\n/**\n * Process a single source file through a flow\n * \n * @param flow - Flow to execute\n * @param sourceRel - Source file path (relative to package root)\n * @param context - Execution context\n * @param executor - Flow executor instance\n * @returns Processing result\n */\nasync function processSourceFile(\n flow: Flow,\n sourceRel: string,\n context: CoordinatorContext,\n executor: FlowExecutor\n): Promise<SourceProcessingResult> {\n const sourceAbs = join(context.packageRoot, sourceRel);\n \n // Extract captured name from pattern\n const firstPattern = getFirstFromPattern(flow.from);\n const capturedName = extractCapturedName(sourceRel, firstPattern);\n \n // Build source-specific context\n const sourceContext: FlowContext = {\n ...context,\n variables: {\n ...context.variables,\n sourcePath: sourceRel,\n sourceDir: dirname(sourceRel),\n sourceFile: basename(sourceRel),\n ...(capturedName ? { capturedName } : {})\n }\n };\n \n // Resolve target path - handle switch expressions and FlowPattern\n let rawToPattern: string;\n if (typeof flow.to === 'string') {\n rawToPattern = flow.to;\n } else if (isSwitchExpression(flow.to)) {\n // Resolve switch expression to concrete target path\n rawToPattern = resolveSwitchExpression(flow.to, sourceContext);\n } else if (typeof flow.to === 'object' && flow.to !== null && 'pattern' in flow.to) {\n // FlowPattern { pattern: \"...\", schema?: \"...\" } - use pattern, not Object.keys\n rawToPattern = (flow.to as { pattern: string }).pattern;\n } else {\n // Multi-target flows - use first target path key\n rawToPattern = Object.keys(flow.to as object)[0] ?? '';\n }\n const resolvedToPattern = resolvePattern(rawToPattern, sourceContext, capturedName);\n const targetAbs = resolveTargetFromGlob(\n sourceAbs,\n firstPattern,\n resolvedToPattern,\n sourceContext\n );\n const targetRel = relative(context.workspaceRoot, targetAbs);\n \n // Create concrete flow with resolved paths\n const concreteFlow: Flow = {\n ...flow,\n from: sourceRel,\n to: targetRel\n };\n \n // Execute flow\n const flowResult = await executor.executeFlow(concreteFlow, sourceContext);\n \n // Check if flow was skipped\n const wasSkipped = flowResult.warnings?.includes('Flow skipped due to condition');\n \n if (wasSkipped) {\n return {\n success: true,\n processed: false,\n written: false\n };\n }\n \n if (!flowResult.success) {\n return {\n success: false,\n processed: true,\n written: false,\n error: flowResult.error || new Error('Flow execution failed')\n };\n }\n \n // Process successful result\n const target = typeof flowResult.target === 'string' \n ? flowResult.target \n : (flowResult.target as any);\n \n if (typeof target !== 'string') {\n return {\n success: true,\n processed: true,\n written: false\n };\n }\n \n const targetRelFromWorkspace = relative(context.workspaceRoot, target);\n const normalizedTargetRel = targetRelFromWorkspace.replace(/\\\\/g, '/');\n \n // Build file mapping\n const isKeyTrackedMerge =\n (flowResult.merge === 'deep' || flowResult.merge === 'shallow') &&\n Array.isArray(flowResult.keys);\n \n const fileMapping: (string | WorkspaceIndexFileMapping)[] = [];\n \n if (isKeyTrackedMerge) {\n fileMapping.push({\n target: normalizedTargetRel,\n merge: flowResult.merge,\n keys: flowResult.keys\n });\n } else {\n fileMapping.push(normalizedTargetRel);\n }\n \n // Extract conflicts\n const conflicts = flowResult.conflicts?.map(conflict => ({\n path: conflict.path,\n winner: conflict.winner,\n losers: conflict.losers\n })) || [];\n \n return {\n success: true,\n processed: true,\n written: true,\n targetPath: target,\n fileMapping,\n mappingKey: sourceRel,\n conflicts\n };\n}\n\n/**\n * Resolve target path from glob patterns\n * Strips platform suffixes from filenames (e.g. read-specs.claude.md -> read-specs.md)\n * \n * @param sourceAbsPath - Absolute source path\n * @param fromPattern - Source pattern from flow\n * @param toPattern - Target pattern from flow\n * @param context - Flow context\n * @returns Resolved absolute target path\n */\nexport function resolveTargetFromGlob(\n sourceAbsPath: string,\n fromPattern: string,\n toPattern: string,\n context: FlowContext\n): string {\n const sourceRelFromPackage = relative(context.packageRoot, sourceAbsPath);\n \n // If 'to' pattern has glob, map the structure\n if (toPattern.includes('*')) {\n // Handle ** recursive patterns\n if (toPattern.includes('**')) {\n const targetRel = resolveRecursiveGlobTargetRelativePath(\n sourceRelFromPackage,\n fromPattern,\n toPattern\n );\n return join(context.workspaceRoot, targetRel);\n }\n \n // Single-level * patterns\n const sourceExt = extname(sourceAbsPath);\n const sourceBase = basename(sourceAbsPath, sourceExt);\n \n const toParts = toPattern.split('*');\n const toPrefix = toParts[0];\n const toSuffix = toParts[1] || '';\n \n const targetExt = toSuffix.startsWith('.') ? toSuffix : (sourceExt + toSuffix);\n const targetFileName = sourceBase + targetExt;\n \n // Strip platform suffix from the final target filename\n const strippedTargetFileName = stripPlatformSuffixFromFilename(targetFileName);\n \n return join(context.workspaceRoot, toPrefix + strippedTargetFileName);\n }\n \n // No glob in target - use as-is\n return join(context.workspaceRoot, toPattern);\n}\n\n/**\n * Build flow context with standard variables\n * \n * @param baseContext - Base context properties\n * @param platformDef - Platform definition (for rootFile, rootDir)\n * @returns Complete flow context\n */\nexport function buildFlowContext(\n baseContext: {\n workspaceRoot: string;\n packageRoot: string;\n platform: Platform;\n packageName: string;\n packageVersion: string;\n priority: number;\n dryRun: boolean;\n direction: 'install' | 'save';\n },\n platformDef: {\n rootFile?: string;\n rootDir?: string;\n }\n): FlowContext {\n return {\n workspaceRoot: baseContext.workspaceRoot,\n packageRoot: baseContext.packageRoot,\n platform: baseContext.platform,\n packageName: baseContext.packageName,\n direction: baseContext.direction,\n variables: {\n name: baseContext.packageName,\n version: baseContext.packageVersion,\n priority: baseContext.priority,\n rootFile: platformDef.rootFile,\n rootDir: platformDef.rootDir\n },\n dryRun: baseContext.dryRun\n };\n}\n\n/**\n * Aggregate results from multiple executions\n * \n * @param results - Array of execution results\n * @returns Combined result\n */\nexport function aggregateExecutionResults(results: ExecutionResult[]): ExecutionResult {\n const aggregated: ExecutionResult = {\n success: true,\n filesProcessed: 0,\n filesWritten: 0,\n targetPaths: [],\n fileMapping: {},\n conflicts: [],\n errors: []\n };\n \n for (const result of results) {\n aggregated.filesProcessed += result.filesProcessed;\n aggregated.filesWritten += result.filesWritten;\n aggregated.targetPaths.push(...result.targetPaths);\n aggregated.conflicts.push(...result.conflicts);\n aggregated.errors.push(...result.errors);\n \n // Merge file mappings\n for (const [source, targets] of Object.entries(result.fileMapping)) {\n if (!aggregated.fileMapping[source]) {\n aggregated.fileMapping[source] = [];\n }\n aggregated.fileMapping[source].push(...targets);\n }\n \n if (!result.success) {\n aggregated.success = false;\n }\n }\n \n return aggregated;\n}\n", "/**\n * File-Level Conflict Resolver\n *\n * Detects and resolves file-level conflicts for flow-based installs.\n * Uses package-name namespacing to organise conflicting files into\n * per-package subdirectories, preserving all versions on disk.\n */\n\nimport { dirname, join } from 'path';\nimport { promises as fs } from 'fs';\n\nimport { exists, ensureDir, readTextFile, walkFiles } from '../../../utils/fs.js';\nimport { normalizePathForProcessing } from '../../../utils/path-normalization.js';\nimport { formatPathForYaml } from '../../../utils/path-resolution.js';\nimport { calculateFileHash } from '../../../utils/hash-utils.js';\nimport { getTargetPath } from '../../../utils/workspace-index-helpers.js';\nimport { sortMapping, isDirKey, ensureTrailingSlash } from '../../../utils/package-index-yml.js';\nimport { readWorkspaceIndex, writeWorkspaceIndex } from '../../../utils/workspace-index-yml.js';\nimport { getRegistryDirectories } from '../../directory.js';\nimport { sep } from 'path';\nimport type { PromptPort } from '../../ports/prompt.js';\nimport { resolvePrompt } from '../../ports/resolve.js';\nimport { logger } from '../../../utils/logger.js';\nimport { deriveNamespaceSlug } from '../../../utils/plugin-naming.js';\nimport type { InstallOptions } from '../../../types/index.js';\nimport type { WorkspaceConflictOwner } from '../../../utils/workspace-index-ownership.js';\nimport type { WorkspaceIndexFileMapping } from '../../../types/workspace-index.js';\nimport {\n loadOtherPackageIndexes,\n buildExpandedIndexesContext,\n type ExpandedIndexesContext,\n} from '../index-based-installer.js';\n\n// ============================================================================\n// Internal Types\n// ============================================================================\n\ntype ConflictResolution = 'namespace' | 'skip' | 'overwrite';\n\ninterface PackageIndexRecord {\n path: string;\n packageName: string;\n workspace: {\n version: string;\n hash?: string;\n };\n files: Record<string, (string | WorkspaceIndexFileMapping)[]>;\n}\n\n// ============================================================================\n// Public Types\n// ============================================================================\n\nexport type FileConflictType = 'none' | 'owned-by-other' | 'exists-unowned';\n\nexport interface FileConflictInfo {\n type: FileConflictType;\n /** Set when type === 'owned-by-other' */\n owner?: WorkspaceConflictOwner;\n}\n\nexport interface OwnershipContext {\n expandedIndexes: ExpandedIndexesContext;\n /** Paths the current package already owned (so re-installs skip the conflict check) */\n previousOwnedPaths: Set<string>;\n /** Raw index records keyed by package name (needed for namespace index updates) */\n indexByPackage: Map<string, PackageIndexRecord>;\n}\n\n/** A resolved target path together with the content that will be written there */\nexport interface TargetEntry {\n /** Workspace-relative path (forward-slash, normalised) */\n relPath: string;\n /** Absolute path */\n absPath: string;\n /**\n * Content of the source file. Used only for the 'exists-unowned' branch\n * where we compare content before deciding whether a conflict exists.\n * Leave undefined if you want to skip the content-diff check for that branch.\n */\n content?: string;\n /**\n * The resolved `flow.to` pattern that produced this target path.\n * Used to derive the namespace insertion point (the base directory of the\n * pattern, i.e. everything before the first glob character).\n * e.g. \"rules/**\\/*.md\" \u2192 base = \"rules\"\n */\n flowToPattern?: string;\n /**\n * True when the flow that produced this entry uses a merge strategy\n * (deep, shallow, or composite). Merge-flow targets are excluded from\n * namespacing because they intentionally combine content from multiple\n * packages into a single file (e.g. mcp.json, settings.json).\n */\n isMergeFlow?: boolean;\n}\n\n/** A file that was physically moved from one location to another during namespace resolution */\nexport interface RelocatedFile {\n /** Original workspace-relative path before relocation */\n from: string;\n /** New workspace-relative path after relocation */\n to: string;\n}\n\nexport interface ConflictResolutionResult {\n /** Targets that should proceed to flow execution (paths may be rewritten to namespaced form) */\n allowedTargets: TargetEntry[];\n /** Human-readable warnings/notes accumulated during resolution */\n warnings: string[];\n /**\n * True when at least one conflict triggered bulk namespacing for the\n * installing package. The flow-based strategy uses this to rewrite the\n * flow `to` patterns before executing flows so that the executor writes\n * files to the correct namespaced locations.\n */\n packageWasNamespaced: boolean;\n /**\n * The package name used as the namespace directory segment.\n * Only set when packageWasNamespaced is true.\n */\n namespaceDir?: string;\n /**\n * Files that were physically relocated on disk during namespace resolution.\n * These are files owned by *other* packages that were moved into their\n * own namespace subdirectories to make room for the incoming package.\n */\n relocatedFiles: RelocatedFile[];\n}\n\n// ============================================================================\n// Private: expand a package's index to its owned file paths\n// (moved from index-based-installer.ts)\n// ============================================================================\n\nasync function collectFilesUnderDirectory(cwd: string, dirRelPath: string): Promise<string[]> {\n const directoryRel = ensureTrailingSlash(normalizePathForProcessing(dirRelPath));\n const absDir = join(cwd, directoryRel);\n if (!(await exists(absDir))) {\n return [];\n }\n\n const collected: string[] = [];\n try {\n for await (const absFile of walkFiles(absDir)) {\n // normalizeRelativePath inline\n const { relative: relFn } = await import('path');\n const rel = relFn(cwd, absFile);\n collected.push(normalizePathForProcessing(rel).replace(/\\\\/g, '/'));\n }\n } catch (error) {\n logger.warn(`Failed to enumerate directory ${absDir}: ${error}`);\n }\n return collected;\n}\n\nasync function expandIndexToFilePaths(\n cwd: string,\n index: PackageIndexRecord | null\n): Promise<Set<string>> {\n const owned = new Set<string>();\n if (!index) return owned;\n\n for (const [key, values] of Object.entries(index.files)) {\n if (isDirKey(key)) {\n for (const mapping of values) {\n const dirRel = getTargetPath(mapping);\n const files = await collectFilesUnderDirectory(cwd, dirRel);\n for (const rel of files) {\n owned.add(normalizePathForProcessing(rel));\n }\n }\n } else {\n for (const mapping of values) {\n const value = getTargetPath(mapping);\n owned.add(normalizePathForProcessing(value));\n }\n }\n }\n\n return owned;\n}\n\n// ============================================================================\n// Private: prompt helpers\n// ============================================================================\n\nasync function promptConflictResolution(message: string, prompt: PromptPort): Promise<ConflictResolution> {\n return prompt.select<ConflictResolution>(\n message,\n [\n { title: 'Namespace (organise by package name)', value: 'namespace' },\n { title: 'Skip (keeps existing)', value: 'skip' },\n { title: 'Overwrite (replaces existing)', value: 'overwrite' }\n ]\n );\n}\n\nasync function promptContentDifferenceResolution(\n workspacePath: string,\n prompt: PromptPort,\n sourcePath?: string\n): Promise<'overwrite' | 'skip'> {\n const formattedSource = sourcePath\n ? (sourcePath.startsWith('/') ? sourcePath : `/${sourcePath}`)\n : undefined;\n const message = formattedSource\n ? `Package file ${formattedSource} differs from workspace file ${workspacePath}`\n : `File ${workspacePath} differs from package version`;\n\n return prompt.select<'overwrite' | 'skip'>(\n message,\n [\n { title: 'Overwrite (use package version)', value: 'overwrite' },\n { title: 'Skip (keep workspace version)', value: 'skip' }\n ]\n );\n}\n\n// ============================================================================\n// Private: content-difference check\n// ============================================================================\n\nasync function hasContentDifference(absPath: string, newContent: string): Promise<boolean> {\n try {\n if (!(await exists(absPath))) return false;\n const existing = await readTextFile(absPath, 'utf8');\n if (existing === newContent) return false;\n const [existingHash, newHash] = await Promise.all([\n calculateFileHash(existing),\n calculateFileHash(newContent)\n ]);\n return existingHash !== newHash;\n } catch (error) {\n logger.warn(`Failed to check content difference for ${absPath}: ${error}`);\n return true; // assume differs on error \u2014 safer to prompt than to silently skip\n }\n}\n\n// ============================================================================\n// Private: derive a namespaced path for a target\n// ============================================================================\n\n/**\n * Insert `packageName` as a subdirectory immediately after the base directory\n * of the flow's `to` pattern.\n *\n * The insertion point is the longest non-glob prefix of `flowToPattern`.\n * For example:\n * relPath=\"rules/git/commits.md\", packageName=\"acme\", flowToPattern=\"rules/**\\/*.md\"\n * \u2192 base=\"rules\" \u2192 \"rules/acme/git/commits.md\"\n *\n * relPath=\".cursor/rules/my-rule.mdc\", packageName=\"corp\", flowToPattern=\".cursor/rules/**\"\n * \u2192 base=\".cursor/rules\" \u2192 \".cursor/rules/corp/my-rule.mdc\"\n *\n * relPath=\"agents/helper.md\", packageName=\"my-pkg\", flowToPattern=\"agents/*\"\n * \u2192 base=\"agents\" \u2192 \"agents/my-pkg/helper.md\"\n *\n * When `flowToPattern` is undefined (no metadata available), falls back to\n * inserting the namespace after the first path segment.\n */\nexport function generateNamespacedPath(\n relPath: string,\n packageName: string,\n flowToPattern: string | undefined\n): string {\n const normalized = relPath.replace(/\\\\/g, '/');\n\n // Derive the base directory from the flow pattern (everything before the first glob)\n let baseDir = '';\n if (flowToPattern) {\n const patternNorm = flowToPattern.replace(/\\\\/g, '/');\n const firstGlob = patternNorm.search(/[*?{]/);\n if (firstGlob > 0) {\n // Strip trailing slash from the prefix before the glob\n const prefix = patternNorm.slice(0, firstGlob).replace(/\\/$/, '');\n // The base is the directory portion of the prefix\n const lastSlash = prefix.lastIndexOf('/');\n baseDir = lastSlash >= 0 ? prefix.slice(0, lastSlash) : '';\n // If prefix itself ends with a complete segment (no trailing slash was present),\n // the full prefix is the base dir\n if (!patternNorm[firstGlob - 1]?.match(/\\//)) {\n baseDir = prefix.includes('/') ? prefix.slice(0, prefix.lastIndexOf('/')) : '';\n } else {\n baseDir = prefix;\n }\n } else if (firstGlob === -1) {\n // Literal pattern \u2014 base is the directory of the literal target\n const lastSlash = patternNorm.lastIndexOf('/');\n baseDir = lastSlash >= 0 ? patternNorm.slice(0, lastSlash) : '';\n }\n }\n\n if (!baseDir) {\n // Fallback: insert namespace after the first path segment\n const parts = normalized.split('/');\n if (parts.length <= 1) {\n return `${packageName}/${normalized}`;\n }\n return `${parts[0]}/${packageName}/${parts.slice(1).join('/')}`;\n }\n\n // Verify the target actually starts with the base dir\n const baseDirSlash = baseDir.endsWith('/') ? baseDir : `${baseDir}/`;\n if (normalized.startsWith(baseDirSlash) || normalized === baseDir) {\n const rest = normalized.slice(baseDirSlash.length);\n return rest ? `${baseDir}/${packageName}/${rest}` : `${baseDir}/${packageName}`;\n }\n\n // Fallback if base doesn't match (shouldn't happen in normal usage)\n const parts = normalized.split('/');\n if (parts.length <= 1) {\n return `${packageName}/${normalized}`;\n }\n return `${parts[0]}/${packageName}/${parts.slice(1).join('/')}`;\n}\n\n/**\n * Rewrite a flow's `to` pattern to insert `packageName` after the pattern's\n * base directory. This is used to redirect an entire flow's output into a\n * namespaced subdirectory without changing individual source files.\n *\n * Examples:\n * \"rules/**\\/*.md\" + \"acme\" \u2192 \"rules/acme/**\\/*.md\"\n * \".cursor/rules/**\" + \"corp\" \u2192 \".cursor/rules/corp/**\"\n * \"agents/*\" + \"my-pkg\" \u2192 \"agents/my-pkg/*\"\n * \".cursor/mcp.json\" + \"pkg\" \u2192 \".cursor/pkg/mcp.json\" (literal)\n */\nexport function namespaceFlowToPattern(pattern: string, packageName: string): string {\n const normalized = pattern.replace(/\\\\/g, '/');\n const firstGlob = normalized.search(/[*?{]/);\n\n if (firstGlob === -1) {\n // Literal path \u2014 insert namespace before the filename\n const lastSlash = normalized.lastIndexOf('/');\n if (lastSlash < 0) return `${packageName}/${normalized}`;\n return `${normalized.slice(0, lastSlash)}/${packageName}/${normalized.slice(lastSlash + 1)}`;\n }\n\n // Find the last '/' before the first glob \u2014 that's the insertion point\n const prefix = normalized.slice(0, firstGlob);\n const lastSlash = prefix.lastIndexOf('/');\n if (lastSlash < 0) {\n // Pattern starts directly with a glob (e.g. \"*.md\") \u2014 prefix with namespace\n return `${packageName}/${normalized}`;\n }\n\n const baseDir = prefix.slice(0, lastSlash); // e.g. \"rules\"\n const rest = normalized.slice(lastSlash + 1); // e.g. \"**/*.md\"\n return `${baseDir}/${packageName}/${rest}`;\n}\n\n// ============================================================================\n// Private: update owner's workspace index after a namespace move\n// ============================================================================\n\nasync function updateOwnerIndexAfterRename(\n cwd: string,\n owner: WorkspaceConflictOwner,\n oldRelPath: string,\n newRelPath: string,\n indexByPackage: Map<string, PackageIndexRecord>\n): Promise<void> {\n const normalizedOld = normalizePathForProcessing(oldRelPath);\n const normalizedNew = normalizePathForProcessing(newRelPath);\n const record = indexByPackage.get(owner.packageName);\n if (!record) return;\n\n if (owner.type === 'file') {\n const values = record.files[owner.key];\n if (!values) return;\n const idx = values.findIndex(mapping => {\n const target = getTargetPath(mapping);\n return normalizePathForProcessing(target) === normalizedOld;\n });\n if (idx === -1) return;\n const oldMapping = values[idx];\n values[idx] = typeof oldMapping === 'string'\n ? normalizedNew\n : { ...oldMapping, target: normalizedNew };\n }\n // dir-key owners: directory key is still valid after rename, nothing to change.\n\n // Persist to workspace index\n const wsRecord = await readWorkspaceIndex(cwd);\n wsRecord.index.packages = wsRecord.index.packages ?? {};\n const entry = wsRecord.index.packages[record.packageName];\n\n const rawPath =\n entry?.path ??\n record.path ??\n (record.workspace?.version\n ? join(getRegistryDirectories().packages, record.packageName, record.workspace.version, sep)\n : '');\n if (!rawPath) {\n logger.warn(`Skipping workspace index write for ${record.packageName}: source path unknown`);\n return;\n }\n\n const pathToUse = formatPathForYaml(rawPath, cwd);\n wsRecord.index.packages[record.packageName] = {\n ...entry,\n path: pathToUse,\n version: entry?.version ?? record.workspace?.version,\n files: sortMapping(record.files ?? {})\n };\n\n await writeWorkspaceIndex(wsRecord);\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Build the ownership context needed for conflict checks on a single install run.\n *\n * @param cwd - Workspace root\n * @param packageName - Package being installed (excluded from \"other owners\")\n * @param previousRecord - Workspace-index record for this package from the previous install,\n * or null if this is a fresh install.\n */\nexport async function buildOwnershipContext(\n cwd: string,\n packageName: string,\n previousRecord: { files: Record<string, (string | WorkspaceIndexFileMapping)[]> } | null\n): Promise<OwnershipContext> {\n const otherIndexes = await loadOtherPackageIndexes(cwd, packageName);\n const expandedIndexes = await buildExpandedIndexesContext(cwd, otherIndexes);\n\n // Build previousOwnedPaths from the caller-supplied record (avoids reading the index again)\n const previousIndex: PackageIndexRecord | null = previousRecord\n ? {\n path: '',\n packageName,\n workspace: { version: '' },\n files: previousRecord.files\n }\n : null;\n const previousOwnedPaths = await expandIndexToFilePaths(cwd, previousIndex);\n\n const indexByPackage = new Map<string, PackageIndexRecord>();\n for (const rec of otherIndexes) {\n indexByPackage.set(rec.packageName, rec);\n }\n\n return { expandedIndexes, previousOwnedPaths, indexByPackage };\n}\n\n/**\n * Classify a single target path as conflict-free, owned-by-another-package, or\n * existing-on-disk-but-unowned.\n */\nexport function classifyFileConflict(\n targetRelPath: string,\n ownershipContext: OwnershipContext\n): FileConflictInfo {\n const normalized = normalizePathForProcessing(targetRelPath);\n const owner = ownershipContext.expandedIndexes.installedPathOwners.get(normalized);\n\n if (owner) {\n return { type: 'owned-by-other', owner };\n }\n\n // For the 'exists-unowned' classification we only report the type here;\n // the caller must also check disk existence (and optionally content).\n if (!ownershipContext.previousOwnedPaths.has(normalized)) {\n return { type: 'exists-unowned' };\n }\n\n return { type: 'none' };\n}\n\n/**\n * Decide what to do for a single classified conflict.\n *\n * The decision cascade is:\n * 1. Per-path override (`options.conflictDecisions`)\n * 2. `--force` flag\n * 3. Configured strategy (`options.conflictStrategy`, when not 'ask')\n * 4. Default: 'namespace' for owned-by-other, TTY prompt for exists-unowned\n * 5. Non-interactive fallback: namespace (owned-by-other) / skip (exists-unowned)\n *\n * @param conflictType - 'owned-by-other' or 'exists-unowned'\n * @param relPath - Workspace-relative path (for display / per-path key lookup)\n * @param ownerName - Package name of the owner (only relevant for 'owned-by-other')\n * @param sourcePath - Package-relative source path (shown in prompts)\n * @param options - Install options carrying force / conflictStrategy / conflictDecisions\n * @param interactive - Whether the session is running in TTY interactive mode\n * @param forceOverwrite - True when the package-level phase confirmed an overwrite for this pkg\n */\nexport async function resolveFileConflict(\n conflictType: 'owned-by-other' | 'exists-unowned',\n relPath: string,\n ownerName: string | undefined,\n sourcePath: string | undefined,\n options: InstallOptions,\n interactive: boolean,\n forceOverwrite: boolean,\n prompt?: PromptPort\n): Promise<{ decision: ConflictResolution; warning?: string }> {\n const perPathDecisions = options.conflictDecisions ?? {};\n const normalized = normalizePathForProcessing(relPath);\n\n // 1. Per-path override\n const perPath = perPathDecisions[normalized] ?? perPathDecisions[relPath];\n if (perPath) {\n return { decision: perPath as ConflictResolution };\n }\n\n // 2. Force flag or package-level force-overwrite confirmation\n if (options.force || forceOverwrite) {\n // --force still namespaces owned-by-other (both packages keep their file);\n // for unowned files --force overwrites since there's no package to namespace to.\n const resolution: ConflictResolution =\n conflictType === 'owned-by-other' ? 'namespace' : 'overwrite';\n const warning = conflictType === 'owned-by-other'\n ? `Namespacing ${normalized} (owned by ${ownerName}) due to --force.`\n : `Overwriting ${normalized} (content differs, --force active).`;\n return { decision: resolution, warning };\n }\n\n const strategy = options.conflictStrategy;\n\n // 3. Explicit non-'ask' strategy\n if (strategy && strategy !== 'ask') {\n const decision = strategy as ConflictResolution;\n let warning: string | undefined;\n if (decision === 'skip') {\n warning = conflictType === 'owned-by-other'\n ? `Skipping ${normalized} (owned by ${ownerName}) due to conflict strategy '${strategy}'.`\n : `Skipping ${normalized} (content differs) due to conflict strategy '${strategy}'.`;\n } else if (decision === 'overwrite' && conflictType === 'exists-unowned') {\n warning = `Overwriting ${normalized} (content differs) due to conflict strategy '${strategy}'.`;\n }\n return { decision, warning };\n }\n\n // 4a. Default for owned-by-other: always namespace (no prompt needed)\n if (conflictType === 'owned-by-other') {\n return { decision: 'namespace' };\n }\n\n // 4b. exists-unowned: prompt in interactive mode\n if (interactive) {\n const p = prompt ?? resolvePrompt();\n const decision = await promptContentDifferenceResolution(normalized, p, sourcePath);\n return { decision };\n }\n\n // 5. Non-interactive fallback for exists-unowned: skip\n const warning = `Skipping ${normalized} (content differs) \u2014 non-interactive mode.`;\n return { decision: 'skip', warning };\n}\n\n/**\n * Execute the namespace strategy for an `owned-by-other` conflict:\n * moves the existing file (owned by another package) into its own namespace\n * subdirectory and updates that package's workspace index entry.\n *\n * The incoming file's namespaced path is computed separately via\n * `generateNamespacedPath()` and is NOT written here \u2014 that is handled\n * by the flow executor after the target entries are rewritten.\n *\n * @param ownerNamespaceSlug The derived short slug for the owner package\n * (computed via deriveNamespaceSlug).\n */\nexport async function executeNamespace(\n cwd: string,\n targetRelPath: string,\n owner: WorkspaceConflictOwner,\n ownershipContext: OwnershipContext,\n flowToPattern: string | undefined,\n dryRun: boolean,\n ownerNamespaceSlug: string\n): Promise<{ ownerNamespacedPath: string; warning: string }> {\n const normalized = normalizePathForProcessing(targetRelPath);\n const ownerNamespacedPath = generateNamespacedPath(normalized, ownerNamespaceSlug, flowToPattern);\n\n if (dryRun) {\n return {\n ownerNamespacedPath,\n warning: `Would move ${normalized} (owned by ${owner.packageName}) \u2192 ${ownerNamespacedPath} to make room for incoming namespaced file.`\n };\n }\n\n const absTarget = join(cwd, normalized);\n const absNamespaced = join(cwd, ownerNamespacedPath);\n await ensureDir(dirname(absNamespaced));\n await fs.rename(absTarget, absNamespaced);\n\n await updateOwnerIndexAfterRename(\n cwd,\n owner,\n normalized,\n ownerNamespacedPath,\n ownershipContext.indexByPackage\n );\n\n // Update in-memory ownership map so subsequent targets in this run see the move\n ownershipContext.expandedIndexes.installedPathOwners.delete(normalized);\n ownershipContext.expandedIndexes.installedPathOwners.set(\n normalizePathForProcessing(ownerNamespacedPath),\n owner\n );\n\n return {\n ownerNamespacedPath,\n warning: `Moved ${normalized} (owned by ${owner.packageName}) \u2192 ${ownerNamespacedPath} (namespaced).`\n };\n}\n\n/**\n * Resolve conflicts for a batch of target paths.\n *\n * ### Namespacing strategy (default)\n *\n * This function uses a **two-pass** approach for the `namespace` strategy:\n *\n * **Pass 1 \u2014 detection:**\n * Iterate all targets and classify each. If ANY non-merge-flow target has a\n * conflict (`owned-by-other` OR `exists-unowned`), mark the entire package\n * for bulk namespacing.\n *\n * **Pass 2 \u2014 application:**\n * - Rewrite ALL non-merge-flow target paths to their namespaced form so that\n * the executor writes every file for this package under\n * `<base>/<packageName>/<rest>`.\n * - For `owned-by-other` conflicts: also physically move the existing owner's\n * file into its own namespace and update the owner's workspace index.\n * - For `exists-unowned` conflicts: leave the existing unowned file in place\n * (it is the \"original\"); only the incoming file is namespaced (which is\n * already the case from the bulk rewrite).\n *\n * ### Non-namespace strategies\n * When the resolved strategy is `skip` or `overwrite` (set via\n * `--conflicts skip|overwrite` or per-path overrides), the original\n * per-file behaviour is preserved and no bulk namespacing occurs.\n *\n * @param cwd - Workspace root\n * @param targets - Pre-computed target entries (from computeTargetEntries)\n * @param ownershipContext - Ownership context built by buildOwnershipContext\n * @param options - Install options\n * @param installingPackageName - Name of the package being installed (used as namespace dir)\n * @param forceOverwrite - True when the package-level phase confirmed an overwrite\n */\nexport async function resolveConflictsForTargets(\n cwd: string,\n targets: TargetEntry[],\n ownershipContext: OwnershipContext,\n options: InstallOptions,\n installingPackageName: string,\n forceOverwrite: boolean = false,\n prompt?: PromptPort\n): Promise<ConflictResolutionResult> {\n const warnings: string[] = [];\n const interactive = options.interactive ?? false;\n const isDryRun = Boolean(options.dryRun);\n\n // -------------------------------------------------------------------------\n // Compute namespace slugs for all known packages\n // -------------------------------------------------------------------------\n\n // Build the set of slugs already claimed by other installed packages\n const otherPackageNames = Array.from(ownershipContext.indexByPackage.keys());\n const slugByPackageName = new Map<string, string>();\n const existingSlugs = new Set<string>();\n\n for (const name of otherPackageNames) {\n const slug = deriveNamespaceSlug(name, existingSlugs);\n slugByPackageName.set(name, slug);\n existingSlugs.add(slug);\n }\n\n // Derive the installing package's slug (avoiding collisions with other packages)\n const installingSlug = deriveNamespaceSlug(installingPackageName, existingSlugs);\n\n // -------------------------------------------------------------------------\n // Pass 1: Classify all targets to determine whether bulk namespacing applies\n // -------------------------------------------------------------------------\n\n type Classification =\n | { type: 'none' }\n | { type: 'owned-by-other'; owner: WorkspaceConflictOwner }\n | { type: 'exists-unowned' };\n\n const classifications: Classification[] = [];\n let shouldNamespacePackage = false;\n\n for (const target of targets) {\n // Merge-flow targets are never namespaced\n if (target.isMergeFlow) {\n classifications.push({ type: 'none' });\n continue;\n }\n\n const classification = classifyFileConflict(target.relPath, ownershipContext);\n\n if (classification.type === 'none') {\n classifications.push({ type: 'none' });\n continue;\n }\n\n if (classification.type === 'owned-by-other') {\n classifications.push({ type: 'owned-by-other', owner: classification.owner! });\n\n // Determine the resolution for this file to see if namespacing will apply\n const { decision } = await resolveFileConflict(\n 'owned-by-other',\n target.relPath,\n classification.owner!.packageName,\n undefined,\n options,\n interactive,\n forceOverwrite,\n prompt\n );\n\n if (decision === 'namespace') {\n shouldNamespacePackage = true;\n }\n continue;\n }\n\n // exists-unowned\n const absTarget = join(cwd, normalizePathForProcessing(target.relPath));\n const fileExists = await exists(absTarget);\n if (!fileExists) {\n classifications.push({ type: 'none' });\n continue;\n }\n\n // Check content difference if we have content\n if (target.content !== undefined) {\n const contentDiffers = await hasContentDifference(absTarget, target.content);\n if (!contentDiffers) {\n classifications.push({ type: 'none' });\n continue;\n }\n }\n\n classifications.push({ type: 'exists-unowned' });\n\n // For exists-unowned the incoming file gets namespaced (no owner to move)\n const { decision } = await resolveFileConflict(\n 'exists-unowned',\n target.relPath,\n undefined,\n undefined,\n options,\n interactive,\n forceOverwrite,\n prompt\n );\n\n if (decision === 'namespace') {\n shouldNamespacePackage = true;\n }\n }\n\n // -------------------------------------------------------------------------\n // Pass 2: Apply resolutions\n // -------------------------------------------------------------------------\n\n const allowedTargets: TargetEntry[] = [];\n const relocatedFiles: RelocatedFile[] = [];\n\n for (let i = 0; i < targets.length; i++) {\n const target = targets[i];\n const cls = classifications[i];\n\n // \u2500\u2500 No conflict (or merge-flow) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (cls.type === 'none') {\n if (shouldNamespacePackage && !target.isMergeFlow) {\n // Bulk namespacing: rewrite this non-conflicting file's path too\n const namespacedRel = generateNamespacedPath(\n target.relPath,\n installingSlug,\n target.flowToPattern\n );\n const namespacedAbs = join(cwd, namespacedRel);\n allowedTargets.push({ ...target, relPath: namespacedRel, absPath: namespacedAbs });\n } else {\n allowedTargets.push(target);\n }\n continue;\n }\n\n // \u2500\u2500 owned-by-other \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (cls.type === 'owned-by-other') {\n const { decision, warning } = await resolveFileConflict(\n 'owned-by-other',\n target.relPath,\n cls.owner.packageName,\n undefined,\n options,\n interactive,\n forceOverwrite,\n prompt\n );\n if (warning) warnings.push(warning);\n\n if (decision === 'skip') continue;\n\n if (decision === 'namespace') {\n try {\n // Move the existing owner's file into its namespace\n const ownerSlug = slugByPackageName.get(cls.owner.packageName)\n ?? deriveNamespaceSlug(cls.owner.packageName, existingSlugs);\n const { ownerNamespacedPath, warning: nsWarn } = await executeNamespace(\n cwd,\n target.relPath,\n cls.owner,\n ownershipContext,\n target.flowToPattern,\n isDryRun,\n ownerSlug\n );\n warnings.push(nsWarn);\n relocatedFiles.push({ from: normalizePathForProcessing(target.relPath), to: ownerNamespacedPath });\n\n // Rewrite this incoming target to its namespaced path\n const namespacedRel = generateNamespacedPath(\n target.relPath,\n installingSlug,\n target.flowToPattern\n );\n const namespacedAbs = join(cwd, namespacedRel);\n allowedTargets.push({ ...target, relPath: namespacedRel, absPath: namespacedAbs });\n } catch (error) {\n warnings.push(`Failed to namespace ${target.relPath}: ${error}`);\n // Do not add to allowedTargets on failure\n }\n continue;\n }\n\n // overwrite: allow flow to write the file; clear in-memory owner to avoid re-prompting\n if (!isDryRun) {\n ownershipContext.expandedIndexes.installedPathOwners.delete(\n normalizePathForProcessing(target.relPath)\n );\n }\n if (isDryRun) {\n warnings.push(`Would overwrite ${target.relPath} (currently owned by ${cls.owner.packageName}).`);\n }\n allowedTargets.push(target);\n continue;\n }\n\n // \u2500\u2500 exists-unowned \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (cls.type === 'exists-unowned') {\n const { decision, warning } = await resolveFileConflict(\n 'exists-unowned',\n target.relPath,\n undefined,\n undefined,\n options,\n interactive,\n forceOverwrite,\n prompt\n );\n if (warning) warnings.push(warning);\n\n if (decision === 'skip') continue;\n\n if (decision === 'namespace') {\n // Leave the existing unowned file in place; only namespace the incoming file\n const namespacedRel = generateNamespacedPath(\n target.relPath,\n installingSlug,\n target.flowToPattern\n );\n const namespacedAbs = join(cwd, namespacedRel);\n if (isDryRun) {\n warnings.push(\n `Would install ${target.relPath} as ${namespacedRel} ` +\n `(existing unowned file kept at original path).`\n );\n } else {\n warnings.push(\n `Installed as ${namespacedRel} ` +\n `(existing unowned file kept at ${target.relPath}).`\n );\n }\n allowedTargets.push({ ...target, relPath: namespacedRel, absPath: namespacedAbs });\n continue;\n }\n\n // overwrite or dry-run\n if (isDryRun) {\n warnings.push(`Would overwrite existing local file ${target.relPath} (content differs).`);\n }\n allowedTargets.push(target);\n continue;\n }\n }\n\n return {\n allowedTargets,\n warnings,\n packageWasNamespaced: shouldNamespacePackage,\n namespaceDir: shouldNamespacePackage ? installingSlug : undefined,\n relocatedFiles\n };\n}\n", "import { dirname, join, relative, sep } from 'path';\n\nimport {\n exists,\n ensureDir,\n listDirectories,\n listFiles,\n remove,\n removeEmptyDirectories,\n walkFiles,\n} from '../../utils/fs.js';\nimport { packageManager } from '../package.js';\nimport { getRegistryDirectories } from '../directory.js';\nimport { logger } from '../../utils/logger.js';\nimport {\n FILE_PATTERNS,\n} from '../../constants/index.js';\nimport { getPlatformRootFileNames, stripRootCopyPrefix } from '../platform/platform-root-files.js';\nimport type { Platform } from '../platforms.js';\nimport { getPlatformsState } from '../platforms.js';\nimport { normalizePathForProcessing } from '../../utils/path-normalization.js';\nimport { formatPathForYaml } from '../../utils/path-resolution.js';\nimport {\n isAllowedRegistryPath,\n isRootRegistryPath,\n isSkippableRegistryPath,\n normalizeRegistryPath,\n extractUniversalSubdirInfo\n} from '../platform/registry-entry-filter.js';\nimport { mapUniversalToPlatform } from '../platform/platform-mapper.js';\nimport type { PackageFile } from '../../types/index.js';\nimport { mergeInlinePlatformOverride } from '../platform-yaml-merge.js';\nimport { parseUniversalPath } from '../platform/platform-file.js';\nimport { getPlatformDefinition, deriveRootDirFromFlows } from '../platforms.js';\nimport {\n sortMapping,\n ensureTrailingSlash,\n isDirKey,\n pruneNestedDirectories\n} from '../../utils/package-index-yml.js';\nimport {\n getWorkspaceIndexPath,\n readWorkspaceIndex,\n} from '../../utils/workspace-index-yml.js';\nimport {\n type WorkspaceConflictOwner\n} from '../../utils/workspace-index-ownership.js';\nimport { getTargetPath } from '../../utils/workspace-index-helpers.js';\nimport type { WorkspaceIndexFileMapping } from '../../types/workspace-index.js';\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\ntype PackageIndexLocation = 'root' | 'nested';\n\ninterface PackageIndexRecord {\n path: string;\n packageName: string;\n workspace: {\n version: string;\n hash?: string;\n };\n files: Record<string, (string | WorkspaceIndexFileMapping)[]>;\n}\n\ninterface RegistryFileEntry {\n registryPath: string;\n content: string;\n encoding?: string;\n}\n\ninterface PlannedTarget {\n absPath: string;\n relPath: string;\n platform?: Platform | 'other';\n}\n\ninterface PlannedFile {\n registryPath: string;\n content: string;\n encoding?: string;\n targets: PlannedTarget[];\n}\n\ninterface GroupPlan {\n key: string;\n plannedFiles: PlannedFile[];\n decision: 'dir' | 'file';\n platformDecisions: Map<Platform | 'other', 'dir' | 'file'>;\n targetDirs: Set<string>;\n}\n\ntype ConflictOwner = WorkspaceConflictOwner;\n\nexport interface ExpandedIndexesContext {\n dirKeyOwners: Map<string, ConflictOwner[]>;\n installedPathOwners: Map<string, ConflictOwner>;\n}\n\ninterface PlannedTargetDetail {\n absPath: string;\n relPath: string;\n content: string;\n encoding?: string;\n sourcePath?: string;\n}\n\n// ============================================================================\n// Path and File Utilities\n// ============================================================================\n\nfunction normalizeRelativePath(cwd: string, absPath: string): string {\n const rel = relative(cwd, absPath);\n const normalized = normalizePathForProcessing(rel);\n return normalized.replace(/\\\\/g, '/');\n}\n\nexport async function loadOtherPackageIndexes(\n cwd: string,\n excludePackage: string\n): Promise<PackageIndexRecord[]> {\n const record = await readWorkspaceIndex(cwd);\n const wsPath = getWorkspaceIndexPath(cwd);\n const packages = record.index.packages ?? {};\n const results: PackageIndexRecord[] = [];\n\n for (const [name, entry] of Object.entries(packages)) {\n if (name === excludePackage) continue;\n results.push({\n path: entry?.path ?? wsPath,\n packageName: name,\n workspace: { version: entry?.version ?? '' },\n files: entry?.files ?? {}\n });\n }\n\n return results;\n}\n\nasync function collectFilesUnderDirectory(cwd: string, dirRelPath: string): Promise<string[]> {\n const directoryRel = ensureTrailingSlash(normalizePathForProcessing(dirRelPath));\n const absDir = join(cwd, directoryRel);\n if (!(await exists(absDir))) {\n return [];\n }\n\n const collected: string[] = [];\n try {\n for await (const absFile of walkFiles(absDir)) {\n const relPath = normalizeRelativePath(cwd, absFile);\n collected.push(relPath);\n }\n } catch (error) {\n logger.warn(`Failed to enumerate directory ${absDir}: ${error}`);\n }\n return collected;\n}\n\nexport async function buildExpandedIndexesContext(\n cwd: string,\n indexes: PackageIndexRecord[]\n): Promise<ExpandedIndexesContext> {\n const dirKeyOwners = new Map<string, ConflictOwner[]>();\n const installedPathOwners = new Map<string, ConflictOwner>();\n\n for (const record of indexes) {\n for (const [rawKey, values] of Object.entries(record.files)) {\n const key = normalizePathForProcessing(rawKey);\n const owner: ConflictOwner = {\n packageName: record.packageName,\n key,\n type: key.endsWith('/') ? 'dir' : 'file'\n };\n\n if (owner.type === 'dir') {\n if (!dirKeyOwners.has(key)) {\n dirKeyOwners.set(key, []);\n }\n dirKeyOwners.get(key)!.push(owner);\n\n for (const mapping of values) {\n const dirRel = getTargetPath(mapping);\n const files = await collectFilesUnderDirectory(cwd, dirRel);\n for (const filePath of files) {\n if (!installedPathOwners.has(filePath)) {\n installedPathOwners.set(filePath, owner);\n }\n }\n }\n } else {\n for (const mapping of values) {\n const fileRel = getTargetPath(mapping);\n const normalizedValue = normalizePathForProcessing(fileRel);\n if (!installedPathOwners.has(normalizedValue)) {\n installedPathOwners.set(normalizedValue, owner);\n }\n }\n }\n }\n }\n\n return { dirKeyOwners, installedPathOwners };\n}\n\n// ============================================================================\n// Group Planning Functions\n// ============================================================================\n\nfunction deriveGroupKey(registryPath: string, cwd?: string): string {\n const normalized = normalizeRegistryPath(registryPath);\n const segments = normalized.split('/');\n if (segments.length <= 1) {\n return '';\n }\n\n const first = segments[0];\n const state = getPlatformsState(cwd ?? null);\n const universalSubdirs = state.universalSubdirs;\n\n if (universalSubdirs.has(first)) {\n if (segments.length >= 2) {\n return ensureTrailingSlash(`${segments[0]}/${segments[1]}`);\n }\n return ensureTrailingSlash(`${segments[0]}`);\n }\n\n const lastSlash = normalized.lastIndexOf('/');\n if (lastSlash === -1) return '';\n return ensureTrailingSlash(normalized.substring(0, lastSlash));\n}\n\nfunction createPlannedFiles(entries: RegistryFileEntry[]): PlannedFile[] {\n return entries.map(entry => ({\n registryPath: entry.registryPath,\n content: entry.content,\n encoding: entry.encoding,\n targets: []\n }));\n}\n\nfunction groupPlannedFiles(plannedFiles: PlannedFile[], cwd?: string): Map<string, PlannedFile[]> {\n const groups = new Map<string, PlannedFile[]>();\n for (const planned of plannedFiles) {\n const key = deriveGroupKey(planned.registryPath, cwd);\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(planned);\n }\n return groups;\n}\n\n// ============================================================================\n// Index Mapping Building Functions\n// ============================================================================\n\nfunction refreshGroupTargetDirs(plan: GroupPlan): void {\n plan.targetDirs = collectTargetDirectories(plan.plannedFiles);\n}\n\nfunction buildFallbackFileMappings(plan: GroupPlan): Record<string, string[]> {\n const mapping: Record<string, string[]> = {};\n\n for (const file of plan.plannedFiles) {\n if (file.targets.length === 0) continue;\n const values = Array.from(\n new Set(\n file.targets.map(target => normalizePathForProcessing(target.relPath))\n )\n ).sort();\n mapping[normalizeRegistryPath(file.registryPath)] = values;\n }\n\n return mapping;\n}\n\nfunction buildIndexMappingFromPlans(plans: GroupPlan[]): Record<string, string[]> {\n const mapping: Record<string, string[]> = {};\n\n for (const plan of plans) {\n refreshGroupTargetDirs(plan);\n const fileMappings = buildFallbackFileMappings(plan);\n for (const [registryPath, values] of Object.entries(fileMappings)) {\n const existing = mapping[registryPath] ?? [];\n mapping[registryPath] = Array.from(new Set([...existing, ...values]));\n }\n }\n\n return sortMapping(mapping);\n}\n\n// ============================================================================\n// Target Mapping Functions\n// ============================================================================\n\nfunction mapRegistryPathToTargets(\n cwd: string,\n registryPath: string,\n platforms: Platform[]\n): PlannedTarget[] {\n const normalized = normalizeRegistryPath(registryPath);\n const targets: PlannedTarget[] = [];\n\n const universalInfo = extractUniversalSubdirInfo(normalized, cwd);\n\n if (universalInfo) {\n const parsed = parseUniversalPath(normalized);\n\n if (parsed?.platformSuffix) {\n const targetPlatform = parsed.platformSuffix as Platform;\n if (platforms.includes(targetPlatform)) {\n try {\n const mapped = mapUniversalToPlatform(\n targetPlatform,\n parsed.universalSubdir,\n parsed.relPath,\n cwd\n );\n const targetAbs = join(cwd, mapped.relFile);\n targets.push({\n absPath: targetAbs,\n relPath: normalizeRelativePath(cwd, targetAbs),\n platform: targetPlatform\n });\n } catch (error) {\n logger.debug(`Platform ${targetPlatform} does not support ${normalized}: ${error}`);\n }\n }\n return targets;\n }\n\n const rel = parsed ? parsed.relPath : universalInfo.relPath;\n for (const platform of platforms) {\n try {\n const mapped = mapUniversalToPlatform(platform, universalInfo.universalSubdir, rel, cwd);\n const targetAbs = join(cwd, mapped.relFile);\n targets.push({\n absPath: targetAbs,\n relPath: normalizeRelativePath(cwd, targetAbs),\n platform\n });\n } catch (error) {\n logger.debug(`Platform ${platform} does not support ${normalized}: ${error}`);\n }\n }\n return targets;\n }\n\n const fallbackAbs = join(cwd, normalized);\n targets.push({\n absPath: fallbackAbs,\n relPath: normalizeRelativePath(cwd, fallbackAbs),\n platform: 'other'\n });\n return targets;\n}\n\nfunction attachTargetsToPlannedFiles(\n cwd: string,\n plannedFiles: PlannedFile[],\n platforms: Platform[]\n): void {\n const overriddenByBase = new Map<string, Set<Platform>>();\n for (const pf of plannedFiles) {\n const parsed = parseUniversalPath(pf.registryPath);\n if (parsed?.platformSuffix) {\n const baseKey = `${parsed.universalSubdir}/${parsed.relPath}`;\n if (!overriddenByBase.has(baseKey)) {\n overriddenByBase.set(baseKey, new Set());\n }\n overriddenByBase.get(baseKey)!.add(parsed.platformSuffix as Platform);\n }\n }\n\n for (const planned of plannedFiles) {\n const targets = mapRegistryPathToTargets(cwd, planned.registryPath, platforms);\n\n const parsed = parseUniversalPath(planned.registryPath);\n if (parsed && !parsed.platformSuffix) {\n const baseKey = `${parsed.universalSubdir}/${parsed.relPath}`;\n const excludedPlatforms = overriddenByBase.get(baseKey);\n if (excludedPlatforms && excludedPlatforms.size > 0) {\n planned.targets = targets.filter(t =>\n !(t.platform && t.platform !== 'other' && excludedPlatforms.has(t.platform as Platform))\n );\n } else {\n planned.targets = targets;\n }\n } else {\n planned.targets = targets;\n }\n }\n}\n\n// ============================================================================\n// Directory Collection Functions\n// ============================================================================\n\nfunction collectTargetDirectories(plannedFiles: PlannedFile[]): Set<string> {\n const dirs = new Set<string>();\n for (const planned of plannedFiles) {\n for (const target of planned.targets) {\n const dirName = dirname(target.relPath);\n if (!dirName || dirName === '.') continue;\n dirs.add(ensureTrailingSlash(normalizePathForProcessing(dirName)));\n }\n }\n return dirs;\n}\n\nfunction collectTargetDirectoriesByPlatform(\n plannedFiles: PlannedFile[]\n): Map<Platform | 'other', Set<string>> {\n const dirsByPlatform = new Map<Platform | 'other', Set<string>>();\n \n for (const planned of plannedFiles) {\n for (const target of planned.targets) {\n const platform = target.platform ?? 'other';\n if (!dirsByPlatform.has(platform)) {\n dirsByPlatform.set(platform, new Set());\n }\n const dirName = dirname(target.relPath);\n if (!dirName || dirName === '.') continue;\n dirsByPlatform.get(platform)!.add(ensureTrailingSlash(normalizePathForProcessing(dirName)));\n }\n }\n \n return dirsByPlatform;\n}\n\nasync function directoryHasEntries(absDir: string): Promise<boolean> {\n if (!(await exists(absDir))) return false;\n const files = await listFiles(absDir).catch(() => [] as string[]);\n if (files.length > 0) return true;\n const subdirs = await listDirectories(absDir).catch(() => [] as string[]);\n return subdirs.length > 0;\n}\n\n// ============================================================================\n// Platform Decision Functions\n// ============================================================================\n\nasync function checkPlatformDirectoryOccupancy(\n cwd: string,\n platformDirs: Set<string>\n): Promise<boolean> {\n for (const dirRel of platformDirs) {\n const absDir = join(cwd, dirRel);\n if (await directoryHasEntries(absDir)) {\n return true;\n }\n }\n return false;\n}\n\nfunction hadPreviousDirForPlatform(\n previousIndex: PackageIndexRecord | null,\n groupKey: string,\n platform: Platform | 'other'\n): boolean {\n if (!previousIndex || platform === 'other') {\n return false;\n }\n\n const prevValues = previousIndex.files[groupKey] ?? [];\n if (prevValues.length === 0) {\n return false;\n }\n\n const platformDef = getPlatformDefinition(platform);\n const rootDir = normalizePathForProcessing(deriveRootDirFromFlows(platformDef));\n\n for (const mapping of prevValues) {\n const value = getTargetPath(mapping);\n const normalizedValue = normalizePathForProcessing(value);\n if (\n normalizedValue === rootDir ||\n normalizedValue.startsWith(`${rootDir}/`)\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nasync function determinePlatformDecisions(\n cwd: string,\n targetDirsByPlatform: Map<Platform | 'other', Set<string>>,\n wasDirKey: boolean,\n previousIndex: PackageIndexRecord | null,\n groupKey: string\n): Promise<Map<Platform | 'other', 'dir' | 'file'>> {\n const platformDecisions = new Map<Platform | 'other', 'dir' | 'file'>();\n\n for (const [platform, platformDirs] of targetDirsByPlatform.entries()) {\n if (wasDirKey && hadPreviousDirForPlatform(previousIndex, groupKey, platform)) {\n platformDecisions.set(platform, 'dir');\n continue;\n }\n\n const directoryOccupied = await checkPlatformDirectoryOccupancy(cwd, platformDirs);\n platformDecisions.set(platform, directoryOccupied ? 'file' : 'dir');\n }\n\n return platformDecisions;\n}\n\nfunction computeOverallDecision(\n platformDecisions: Map<Platform | 'other', 'dir' | 'file'>\n): 'dir' | 'file' {\n const hasAnyDirDecision = Array.from(platformDecisions.values()).some(d => d === 'dir');\n return hasAnyDirDecision ? 'dir' : 'file';\n}\n\nasync function decideGroupPlans(\n cwd: string,\n groups: Map<string, PlannedFile[]>,\n previousIndex: PackageIndexRecord | null,\n context: ExpandedIndexesContext\n): Promise<GroupPlan[]> {\n const plans: GroupPlan[] = [];\n const previousDirKeys = new Set(\n previousIndex\n ? Object.keys(previousIndex.files).filter(key => isDirKey(key))\n : []\n );\n\n for (const [groupKey, plannedFiles] of groups.entries()) {\n const targetDirs = collectTargetDirectories(plannedFiles);\n const targetDirsByPlatform = collectTargetDirectoriesByPlatform(plannedFiles);\n let decision: 'dir' | 'file' = 'file';\n const platformDecisions = new Map<Platform | 'other', 'dir' | 'file'>();\n\n const otherDirOwners = context.dirKeyOwners.get(groupKey) ?? [];\n const hasTargets = plannedFiles.some(file => file.targets.length > 0);\n\n if (groupKey !== '' && hasTargets && otherDirOwners.length === 0) {\n const wasDirKey = previousDirKeys.has(groupKey);\n const computedDecisions = await determinePlatformDecisions(\n cwd,\n targetDirsByPlatform,\n wasDirKey,\n previousIndex,\n groupKey\n );\n platformDecisions.clear();\n computedDecisions.forEach((value, key) => platformDecisions.set(key, value));\n decision = computeOverallDecision(platformDecisions);\n }\n\n plans.push({\n key: groupKey,\n plannedFiles,\n decision,\n platformDecisions,\n targetDirs\n });\n }\n\n return plans;\n}\n\n// ============================================================================\n// Shared Helper for Building Index Mappings\n// ============================================================================\n\nfunction addMappingValue(mapping: Record<string, string[]>, key: string, value: string): void {\n if (!mapping[key]) {\n mapping[key] = [];\n }\n if (!mapping[key]!.includes(value)) {\n mapping[key]!.push(value);\n }\n}\n\nasync function augmentIndexMappingWithRootAndCopyToRoot(\n cwd: string,\n mapping: Record<string, string[]>,\n packageFiles: PackageFile[],\n platforms: Platform[]\n): Promise<Record<string, string[]>> {\n const augmented: Record<string, string[]> = { ...mapping };\n\n const rootFileNames = getPlatformRootFileNames(platforms);\n const explicitRootKeys = new Set<string>();\n const hasAgents = packageFiles.some(file => normalizeRegistryPath(file.path) === FILE_PATTERNS.AGENTS_MD);\n\n for (const file of packageFiles) {\n const normalized = normalizeRegistryPath(file.path);\n\n const stripped = stripRootCopyPrefix(normalized);\n if (stripped !== null) {\n if (await exists(join(cwd, stripped))) {\n addMappingValue(augmented, normalized, stripped);\n }\n continue;\n }\n\n if (rootFileNames.has(normalized) || isRootRegistryPath(normalized)) {\n explicitRootKeys.add(normalized);\n if (await exists(join(cwd, normalized))) {\n addMappingValue(augmented, normalized, normalized);\n }\n }\n }\n\n for (const file of packageFiles) {\n const normalized = normalizeRegistryPath(file.path);\n if (!isAllowedRegistryPath(normalized, cwd)) continue;\n if (isSkippableRegistryPath(normalized, cwd)) continue;\n if (await exists(join(cwd, normalized))) {\n addMappingValue(augmented, normalized, normalized);\n }\n }\n\n if (hasAgents) {\n for (const rootFile of rootFileNames) {\n if (rootFile === FILE_PATTERNS.AGENTS_MD) continue;\n if (explicitRootKeys.has(rootFile)) continue;\n if (await exists(join(cwd, rootFile))) {\n addMappingValue(augmented, FILE_PATTERNS.AGENTS_MD, rootFile);\n }\n }\n }\n\n return sortMapping(augmented);\n}\n\n/**\n * Build index mapping for package files using the same logic flow as installPackageByIndex\n * This function reuses the planning, grouping, and decision logic to ensure consistency\n * between installation and sync operations.\n * \n * @param cwd - Current working directory\n * @param packageFiles - Array of package files to build mapping for\n * @param platforms - Platforms to map files to\n * @param previousIndex - Previous index record (if any)\n * @param otherIndexes - Other package indexes for conflict detection\n * @returns Record mapping registry paths to installed paths\n */\nexport async function buildIndexMappingForPackageFiles(\n cwd: string,\n packageFiles: PackageFile[],\n platforms: Platform[],\n previousIndex: PackageIndexRecord | null,\n otherIndexes: PackageIndexRecord[]\n): Promise<Record<string, string[]>> {\n const registryEntries: RegistryFileEntry[] = packageFiles\n .filter(file => {\n const normalized = normalizeRegistryPath(file.path);\n if (isRootRegistryPath(normalized)) return false;\n if (isSkippableRegistryPath(normalized, cwd)) return false;\n return isAllowedRegistryPath(normalized, cwd);\n })\n .map(file => ({\n registryPath: normalizeRegistryPath(file.path),\n content: file.content,\n encoding: file.encoding as string | undefined\n }));\n\n if (registryEntries.length === 0) {\n return await augmentIndexMappingWithRootAndCopyToRoot(cwd, {}, packageFiles, platforms);\n }\n\n const plannedFiles = createPlannedFiles(registryEntries);\n attachTargetsToPlannedFiles(cwd, plannedFiles, platforms);\n \n const groups = groupPlannedFiles(plannedFiles, cwd);\n const context = await buildExpandedIndexesContext(cwd, otherIndexes);\n const groupPlans = await decideGroupPlans(cwd, groups, previousIndex, context);\n \n const mapping = buildIndexMappingFromPlans(groupPlans);\n return await augmentIndexMappingWithRootAndCopyToRoot(cwd, mapping, packageFiles, platforms);\n}\n", "/**\n * Strategy Selector Module\n * \n * Selects the appropriate installation strategy based on package format and target platform.\n */\n\nimport type { InstallOptions } from '../../../types/index.js';\nimport type { FlowInstallContext, InstallationStrategy } from './types.js';\nimport { ConversionInstallStrategy } from './conversion-strategy.js';\nimport { FlowBasedInstallStrategy } from './flow-based-strategy.js';\nimport { needsConversion } from '../format-detector.js';\n\n/**\n * Select the appropriate installation strategy based on package format and platform\n * \n * Strategy selection:\n * 1. ConversionInstallStrategy - Cross-platform conversion required (source \u2260 target)\n * 2. FlowBasedInstallStrategy - Default for all other cases (universal or same-platform)\n * \n * @param context - Installation context with package metadata\n * @param options - Installation options\n * @returns Selected installation strategy\n */\nexport function selectInstallStrategy(\n context: FlowInstallContext,\n options?: InstallOptions\n): InstallationStrategy {\n const format = context.packageFormat;\n const platform = context.platform;\n \n // If no format provided, default to flow-based strategy\n if (!format) {\n return new FlowBasedInstallStrategy();\n }\n \n // Check if conversion is needed\n if (needsConversion(format, platform)) {\n return new ConversionInstallStrategy();\n }\n \n // Default: flow-based strategy\n return new FlowBasedInstallStrategy();\n}\n", "/**\n * Format Detection Helpers\n * \n * Shared utilities for detecting package formats from directories.\n * Extracts common logic used by both flow-based-installer and flow-index-installer.\n */\n\nimport { relative } from 'path';\nimport { walkFiles } from '../../../utils/file-walker.js';\nimport { \n detectPackageFormat, \n detectPackageFormatWithContext,\n type PackageFormat\n} from '../format-detector.js';\nimport type { PackageConversionContext } from '../../../types/conversion-context.js';\nimport { logger } from '../../../utils/logger.js';\n\n/**\n * Load file list from package directory for format detection\n * Excludes .git directories\n * \n * @param packageRoot - Root directory of the package\n * @returns Array of file paths with empty content strings\n */\nexport async function loadPackageFileList(\n packageRoot: string\n): Promise<Array<{ path: string; content: string }>> {\n const files: Array<{ path: string; content: string }> = [];\n \n try {\n for await (const fullPath of walkFiles(packageRoot)) {\n const relativePath = relative(packageRoot, fullPath);\n \n // Skip git metadata\n if (relativePath.startsWith('.git/') || relativePath === '.git') {\n continue;\n }\n \n files.push({\n path: relativePath,\n content: ''\n });\n }\n } catch (error) {\n logger.error('Failed to read package directory for format detection', { \n packageRoot, \n error \n });\n }\n \n return files;\n}\n\n/**\n * Detect package format from directory\n * \n * Convenience wrapper that loads file list and detects format.\n * \n * @param packageRoot - Root directory of the package\n * @returns Detected package format\n */\nexport async function detectFormatFromDirectory(\n packageRoot: string\n): Promise<PackageFormat> {\n const files = await loadPackageFileList(packageRoot);\n return detectPackageFormat(files);\n}\n\n/**\n * Detect package format with conversion context from directory\n * \n * Convenience wrapper that loads file list and detects format with context.\n * Use this when you need both format and conversion context for the installation pipeline.\n * \n * @param packageRoot - Root directory of the package\n * @returns Detected format and conversion context\n */\nexport async function detectFormatWithContextFromDirectory(\n packageRoot: string\n): Promise<{ format: PackageFormat; context: PackageConversionContext }> {\n const files = await loadPackageFileList(packageRoot);\n return detectPackageFormatWithContext(files);\n}\n", "/**\n * Flow-Based Installer Module\n * \n * Handles installation of package files using the declarative flow system.\n * Integrates with the existing install pipeline to execute flow transformations\n * for each package file, with multi-package composition and priority-based merging.\n * \n * This module now serves as a thin orchestration layer, delegating to specialized\n * strategy implementations for different installation scenarios.\n * \n * CORE LAYER: Pure flow execution logic\n * For workspace-integrated installation with index updates, see flow-index-installer.ts\n */\n\nimport type { InstallOptions } from '../../types/index.js';\nimport { platformUsesFlows } from '../platforms.js';\nimport { logger } from '../../utils/logger.js';\nimport {\n selectInstallStrategy,\n type FlowInstallContext,\n type FlowInstallResult,\n type FlowConflictReport,\n type FlowInstallError\n} from './strategies/index.js';\nimport { detectFormatFromDirectory } from './helpers/format-detection.js';\nimport { logInstallationResult } from './helpers/result-logging.js';\n// Re-export types for backward compatibility\nexport type {\n FlowInstallContext,\n FlowInstallResult,\n FlowConflictReport,\n FlowInstallError\n};\n\n// ============================================================================\n// Main Installation API\n// ============================================================================\n\n/**\n * Execute flows for a single package installation with format detection and conversion\n * \n * This is the main entry point for flow-based installation. It:\n * 1. Detects the package format (universal vs platform-specific)\n * 2. Selects the appropriate installation strategy\n * 3. Delegates to the strategy for execution\n * \n * @param installContext - Installation context with package metadata\n * @param options - Installation options (e.g., dryRun)\n * @returns Installation result with file mappings and metrics\n */\nexport async function installPackageWithFlows(\n installContext: FlowInstallContext,\n options?: InstallOptions,\n forceOverwrite: boolean = false\n): Promise<FlowInstallResult> {\n const {\n packageName,\n packageRoot,\n workspaceRoot,\n platform,\n packageVersion,\n priority,\n dryRun\n } = installContext;\n \n const result: FlowInstallResult = {\n success: true,\n filesProcessed: 0,\n filesWritten: 0,\n conflicts: [],\n errors: [],\n targetPaths: [],\n fileMapping: {}\n };\n \n try {\n // Check if platform uses flows\n if (!platformUsesFlows(platform, workspaceRoot)) {\n logger.debug(`Platform ${platform} does not use flows, skipping flow-based installation`);\n return result;\n }\n \n // Phase 1: Get or detect package format\n const packageFormat = installContext.packageFormat || \n await detectFormatFromDirectory(packageRoot);\n \n logger.debug('Package format', {\n package: packageName,\n type: packageFormat.type,\n platform: packageFormat.platform,\n confidence: packageFormat.confidence,\n targetPlatform: platform,\n source: installContext.packageFormat ? 'provided' : 'detected'\n });\n \n // Phase 2: Select and execute installation strategy\n const enrichedContext: FlowInstallContext = {\n ...installContext,\n packageFormat\n };\n \n const strategy = selectInstallStrategy(enrichedContext, options);\n const strategyResult = await strategy.install(enrichedContext, options, forceOverwrite);\n \n // Log results using shared utility\n logInstallationResult(strategyResult, packageName, platform, dryRun ?? false);\n \n return strategyResult;\n \n } catch (error) {\n result.success = false;\n logger.error(`Failed to install package ${packageName} with flows: ${(error as Error).message}`);\n result.errors.push({\n flow: { from: packageRoot, to: workspaceRoot },\n sourcePath: packageRoot,\n error: error as Error,\n message: `Installation failed: ${(error as Error).message}`\n });\n return result;\n }\n}\n", "/**\n * Result Aggregation Helpers\n * \n * Shared utilities for aggregating installation results across multiple packages or platforms.\n * Handles merging of file mappings, conflicts, errors, and statistics.\n */\n\nimport type { FlowInstallResult } from '../strategies/types.js';\nimport type { WorkspaceIndexFileMapping } from '../../../types/workspace-index.js';\n\n/**\n * Merge file mappings from multiple results\n * Simple deduplication by concatenating unique targets\n * \n * @param target - Target mapping to merge into (mutated)\n * @param source - Source mapping to merge from\n */\nexport function mergeFileMappings(\n target: Record<string, (string | WorkspaceIndexFileMapping)[]>,\n source: Record<string, (string | WorkspaceIndexFileMapping)[]>\n): void {\n for (const [sourceKey, targets] of Object.entries(source)) {\n const existing = target[sourceKey] ?? [];\n target[sourceKey] = Array.from(new Set([...existing, ...targets])).sort();\n }\n}\n\n/**\n * Merge file mappings with workspace index format\n * Prefers complex mappings over simple strings, deduplicates by target path\n * \n * This is used by flow-index-installer which needs to handle both string and\n * WorkspaceIndexFileMapping formats.\n * \n * @param target - Target mapping to merge into (mutated)\n * @param source - Source mapping to merge from\n */\nexport function mergeWorkspaceFileMappings(\n target: Record<string, (string | WorkspaceIndexFileMapping)[]>,\n source: Record<string, (string | WorkspaceIndexFileMapping)[]>\n): void {\n for (const [sourceKey, targets] of Object.entries(source)) {\n const existing = target[sourceKey] ?? [];\n \n // Deduplicate by target path, prefer complex mapping over string\n const byTarget = new Map<string, string | WorkspaceIndexFileMapping>();\n \n for (const m of existing) {\n const targetPath = typeof m === 'string' ? m : m.target;\n byTarget.set(targetPath, m);\n }\n \n for (const m of targets) {\n const targetPath = typeof m === 'string' ? m : m.target;\n const prior = byTarget.get(targetPath);\n \n if (!prior) {\n byTarget.set(targetPath, m);\n } else if (typeof prior === 'string' && typeof m !== 'string') {\n // Prefer complex mapping over string\n byTarget.set(targetPath, m);\n }\n }\n \n target[sourceKey] = Array.from(byTarget.values());\n }\n}\n\n/**\n * Aggregate flow install results\n * \n * Merges statistics, errors, conflicts, target paths, and file mappings from\n * source into target. Target is mutated.\n * \n * @param target - Target result to aggregate into (mutated)\n * @param source - Source result to aggregate from\n */\nexport function aggregateFlowResults(\n target: FlowInstallResult,\n source: FlowInstallResult\n): void {\n target.filesProcessed += source.filesProcessed;\n target.filesWritten += source.filesWritten;\n target.errors.push(...source.errors);\n target.conflicts.push(...source.conflicts);\n target.targetPaths.push(...(source.targetPaths ?? []));\n \n mergeFileMappings(target.fileMapping, source.fileMapping ?? {});\n \n if (!source.success) {\n target.success = false;\n }\n}\n\n/**\n * Collect unique conflict messages\n * \n * Converts FlowConflictReport objects to strings and adds unique messages to target array.\n * Used by flow-index-installer to aggregate conflicts across platforms.\n * \n * @param target - Target array to add messages to (mutated)\n * @param conflicts - Source conflicts to convert and add\n */\nexport function collectConflictMessages(\n target: string[],\n conflicts: FlowInstallResult['conflicts']\n): void {\n for (const conflict of conflicts) {\n const msg = `${conflict.targetPath}: ${conflict.message}`;\n if (!target.includes(msg)) {\n target.push(msg);\n }\n }\n}\n\n/**\n * Collect unique error messages\n * \n * Converts FlowInstallError objects to strings and adds unique messages to target array.\n * Used by flow-index-installer to aggregate errors across platforms.\n * \n * @param target - Target array to add messages to (mutated)\n * @param errors - Source errors to convert and add\n */\nexport function collectErrorMessages(\n target: string[],\n errors: FlowInstallResult['errors']\n): void {\n for (const error of errors) {\n const msg = `${error.sourcePath}: ${error.message}`;\n if (!target.includes(msg)) {\n target.push(msg);\n }\n }\n}\n", "/**\n * Installation Executor\n *\n * Contains the index-based installation logic for executing package installations.\n * Migrated from install-flow.ts to support the unified pipeline.\n */\n\nimport { InstallOptions } from '../../../types/index.js';\nimport type { ResolvedPackage } from '../../dependency-resolver/types.js';\nimport { type Platform } from '../../platforms.js';\nimport { logger } from '../../../utils/logger.js';\nimport { UserCancellationError } from '../../../utils/errors.js';\nimport { discoverAndCategorizeFiles } from '../helpers/file-discovery.js';\nimport { installOrSyncRootFiles } from './root-files.js';\nimport { installPackageByIndexWithFlows as installPackageByIndex, type IndexInstallResult } from '../flow-index-installer.js';\nimport type { RelocatedFile } from '../conflicts/file-conflict-resolver.js';\nimport { ensureDir, exists, writeTextFile } from '../../../utils/fs.js';\nimport { dirname, join } from 'path';\nimport { checkAndHandleAllPackageConflicts } from './conflict-handler.js';\nimport { readWorkspaceIndex, writeWorkspaceIndex } from '../../../utils/workspace-index-yml.js';\nimport { PACKAGE_ROOT_DIRS } from '../../../constants/index.js';\n\nexport type ConflictSummary = Awaited<ReturnType<typeof checkAndHandleAllPackageConflicts>>;\n\nexport interface InstallationPhasesParams {\n cwd: string;\n packages: ResolvedPackage[];\n platforms: Platform[];\n conflictResult?: ConflictSummary;\n options: InstallOptions;\n targetDir: string;\n matchedPattern?: string;\n}\n\nexport interface InstallationPhasesResult {\n installedCount: number;\n skippedCount: number;\n errorCount: number;\n allAddedFiles: string[];\n allUpdatedFiles: string[];\n rootFileResults: { installed: string[]; updated: string[]; skipped: string[] };\n totalOpenPackageFiles: number;\n errors?: string[];\n /** True when namespace conflict resolution was triggered for any package */\n namespaced?: boolean;\n /** Files that were physically relocated on disk during namespace resolution */\n relocatedFiles?: RelocatedFile[];\n}\n\n/**\n * Perform the index-based installation process\n *\n * Installs each package using the index-based installer and handles root files.\n */\nexport async function performIndexBasedInstallationPhases(params: InstallationPhasesParams): Promise<InstallationPhasesResult> {\n const { cwd, packages, platforms, conflictResult, options, targetDir, matchedPattern } = params;\n\n let totalInstalled = 0;\n let totalUpdated = 0;\n let totalDeleted = 0;\n let totalSkipped = 0;\n let totalErrors = 0;\n const allAddedFiles: string[] = [];\n const allUpdatedFiles: string[] = [];\n const allDeletedFiles: string[] = [];\n const errors: string[] = [];\n let anyNamespaced = false;\n const allRelocatedFiles: RelocatedFile[] = [];\n\n for (const resolved of packages) {\n try {\n // Extract originalContentRoot if it was stored during conversion\n const originalContentRoot = (resolved as any).originalContentRoot;\n\n // Check if the package-level conflict phase confirmed an overwrite for this package\n const forceOverwrite = conflictResult?.forceOverwritePackages?.has(resolved.name) ?? false;\n \n const installResult: IndexInstallResult = await installPackageByIndex(\n cwd,\n resolved.name,\n resolved.version,\n platforms,\n options,\n resolved.contentRoot,\n resolved.pkg._format,\n resolved.marketplaceMetadata,\n matchedPattern,\n resolved.resourceVersion,\n originalContentRoot, // Pass original path for index writing\n forceOverwrite // Phase 5: propagate package-level overwrite decision\n );\n\n totalInstalled += installResult.installed;\n totalUpdated += installResult.updated;\n totalDeleted += installResult.deleted;\n totalSkipped += installResult.skipped;\n\n allAddedFiles.push(...installResult.installedFiles);\n allUpdatedFiles.push(...installResult.updatedFiles);\n allDeletedFiles.push(...installResult.deletedFiles);\n\n // Aggregate namespace metadata\n if (installResult.namespaced) {\n anyNamespaced = true;\n }\n if (installResult.relocatedFiles && installResult.relocatedFiles.length > 0) {\n allRelocatedFiles.push(...installResult.relocatedFiles);\n }\n\n if (installResult.installed > 0 || installResult.updated > 0 || installResult.deleted > 0) {\n logger.info(`Index-based install for ${resolved.name}: ${installResult.installed} installed, ${installResult.updated} updated, ${installResult.deleted} deleted`);\n }\n } catch (error) {\n if (error instanceof UserCancellationError) {\n throw error;\n }\n const errorMsg = `Failed index-based install for ${resolved.name}: ${error}`;\n logger.error(errorMsg);\n errors.push(errorMsg);\n totalErrors++;\n }\n }\n\n // Handle root files separately\n const rootFileResults = {\n installed: new Set<string>(),\n updated: new Set<string>(),\n skipped: new Set<string>()\n };\n\n /** Per-package root files + root copy paths to augment workspace index */\n const rootFileAugmentations = new Map<string, { rootFilePaths: string[]; rootCopyPaths: string[] }>();\n\n for (const resolved of packages) {\n try {\n const categorized = await discoverAndCategorizeFiles(\n resolved.name,\n resolved.version,\n platforms,\n resolved.contentRoot,\n matchedPattern\n );\n const installResult = await installOrSyncRootFiles(\n cwd,\n resolved.name,\n categorized.rootFiles,\n platforms\n );\n\n installResult.created.forEach(file => rootFileResults.installed.add(file));\n installResult.updated.forEach(file => rootFileResults.updated.add(file));\n installResult.skipped.forEach(file => rootFileResults.skipped.add(file));\n\n // Copy root/** files directly to workspace root (strip prefix)\n for (const file of categorized.rootCopyFiles) {\n const targetPath = join(cwd, file.path);\n const parent = dirname(targetPath);\n await ensureDir(parent);\n const existed = await exists(targetPath);\n await writeTextFile(targetPath, file.content, (file.encoding as BufferEncoding) ?? 'utf8');\n if (existed) {\n rootFileResults.updated.add(file.path);\n } else {\n rootFileResults.installed.add(file.path);\n }\n }\n\n // Collect root files + root copy for index augmentation\n if (!options.dryRun) {\n const rootFilePaths = [...installResult.created, ...installResult.updated];\n const rootCopyPaths = categorized.rootCopyFiles.map(f => f.path);\n if (rootFilePaths.length > 0 || rootCopyPaths.length > 0) {\n rootFileAugmentations.set(resolved.name, { rootFilePaths, rootCopyPaths });\n }\n }\n } catch (error) {\n if (error instanceof UserCancellationError) {\n throw error;\n }\n const errorMsg = `Failed root file install for ${resolved.name}: ${error}`;\n logger.error(errorMsg);\n errors.push(errorMsg);\n totalErrors++;\n }\n }\n\n // Augment workspace index with root files and root copy files (flow-installer writes index before root phase)\n if (!options.dryRun && rootFileAugmentations.size > 0) {\n try {\n const wsRecord = await readWorkspaceIndex(cwd);\n wsRecord.index.packages = wsRecord.index.packages ?? {};\n for (const [packageName, { rootFilePaths, rootCopyPaths }] of rootFileAugmentations) {\n const entry = wsRecord.index.packages[packageName];\n if (!entry) continue;\n const files = { ...(entry.files ?? {}) };\n for (const path of rootFilePaths) {\n const existing = files[path] ?? [];\n if (!existing.includes(path)) {\n files[path] = [...existing, path];\n }\n }\n const rootPrefix = `${PACKAGE_ROOT_DIRS.ROOT_COPY}/`;\n for (const path of rootCopyPaths) {\n const registryKey = `${rootPrefix}${path}`;\n const existing = files[registryKey] ?? [];\n if (!existing.includes(path)) {\n files[registryKey] = [...existing, path];\n }\n }\n wsRecord.index.packages[packageName] = { ...entry, files };\n }\n await writeWorkspaceIndex(wsRecord);\n logger.debug(`Augmented workspace index with root files for ${rootFileAugmentations.size} package(s)`);\n } catch (error) {\n logger.warn(`Failed to augment workspace index with root files: ${error}`);\n }\n }\n\n // Deduplicate: remove any root files that also appear in allAddedFiles/allUpdatedFiles\n const addedSet = new Set(allAddedFiles);\n const updatedSet = new Set(allUpdatedFiles);\n const dedupedRootInstalled = Array.from(rootFileResults.installed).filter(\n f => !addedSet.has(f)\n );\n const dedupedRootUpdated = Array.from(rootFileResults.updated).filter(\n f => !updatedSet.has(f)\n );\n\n return {\n installedCount: totalInstalled,\n skippedCount: totalSkipped,\n errorCount: totalErrors,\n allAddedFiles,\n errors: errors.length > 0 ? errors : undefined,\n allUpdatedFiles,\n rootFileResults: {\n installed: dedupedRootInstalled,\n updated: dedupedRootUpdated,\n skipped: Array.from(rootFileResults.skipped)\n },\n totalOpenPackageFiles: totalInstalled + totalUpdated,\n namespaced: anyNamespaced || undefined,\n relocatedFiles: allRelocatedFiles.length > 0 ? allRelocatedFiles : undefined\n };\n}\n", "/**\n * Display utilities for dependency resolution results.\n */\n\nimport type { ResolvedPackage } from './types.js';\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput } from '../ports/resolve.js';\n\n/**\n * Display dependency tree to user\n */\nexport function displayDependencyTree(resolvedPackages: ResolvedPackage[], silent: boolean = false, output?: OutputPort): void {\n if (silent) return;\n const out = output ?? resolveOutput();\n const root = resolvedPackages.find(f => f.isRoot);\n if (!root) return;\n \n out.info(`\\nInstalling ${root.name}@${root.version} with dependencies:\\n`);\n \n // Show root\n out.info(`${root.name}@${root.version} (root)`);\n \n // Show transitive dependencies\n const transitive = resolvedPackages.filter(f => !f.isRoot);\n for (const dep of transitive) {\n const status = dep.conflictResolution \n ? ` (${dep.conflictResolution})`\n : '';\n \n // Show version range information if available\n const rangeInfo = dep.requiredRange && dep.requiredRange !== dep.version\n ? ` [from ${dep.requiredRange}]`\n : '';\n \n out.info(`\u251C\u2500\u2500 ${dep.name}@${dep.version}${rangeInfo}${status}`);\n }\n \n out.info(`\\nTotal: ${resolvedPackages.length} packages\\n`);\n}\n", "import { logger } from '../../utils/logger.js';\nimport type { OutputPort } from '../ports/output.js';\nimport type { PromptPort } from '../ports/prompt.js';\nimport { resolveOutput, resolvePrompt } from '../ports/resolve.js';\nimport type { Platform } from '../../types/platform.js';\nimport { getDetectedPlatforms, getPlatformDefinitions } from '../platforms.js';\nimport type { PlatformDefinition } from '../../types/platform.js';\n\n/**\n * Detect existing platforms in the project\n * Wrapper around getDetectedPlatforms that adds debug logging\n */\nexport async function detectPlatforms(targetDir: string): Promise<Platform[]> {\n const detectedPlatforms = await getDetectedPlatforms(targetDir);\n\n if (detectedPlatforms.length > 0) {\n logger.debug(`Auto-detected platforms: ${detectedPlatforms.join(', ')}`);\n }\n\n return detectedPlatforms;\n}\n\n/**\n * Prompt user for platform selection when no platforms are detected\n */\nexport async function promptForPlatformSelection(\n output?: OutputPort,\n prompt?: PromptPort\n): Promise<Platform[]> {\n const out = output ?? resolveOutput();\n const prm = prompt ?? resolvePrompt();\n \n out.step('Platform Detection');\n out.info('No AI development platform detected in this project.');\n\n const choices = Object.values(getPlatformDefinitions()).map((platform: PlatformDefinition) => ({\n title: platform.name,\n value: platform.id\n }));\n\n const selected = await prm.select<string>(\n 'Which platform are you using for AI-assisted development?',\n choices,\n 'Use arrow keys to navigate, Enter to select'\n );\n\n return selected ? [selected as Platform] : [];\n}\n", "import { resolvePlatformName, type Platform } from '../platforms.js';\nimport { normalizePlatforms } from '../platform/platform-mapper.js';\nimport { detectPlatforms, promptForPlatformSelection } from './package-installation.js';\n\n/**\n * Resolve platforms for an operation.\n * - Uses specified platforms if provided (validated against known platforms)\n * - Otherwise auto-detects\n * - If none detected and interactive=true, prompts user to select\n */\nexport async function resolvePlatforms(\n cwd: string,\n specified: string[] | undefined,\n options: { interactive?: boolean } = {}\n): Promise<Platform[]> {\n const interactive = options.interactive === true;\n\n const normalized = normalizePlatforms(specified);\n if (normalized && normalized.length > 0) {\n const resolved = normalized.map(name => resolvePlatformName(name));\n const invalidIndex = resolved.findIndex(platform => !platform);\n if (invalidIndex !== -1) {\n throw new Error(`platform ${normalized[invalidIndex]} not found`);\n }\n return resolved as Platform[];\n }\n\n const auto = await detectPlatforms(cwd);\n if (auto.length > 0) return auto;\n\n if (interactive) {\n const selected = await promptForPlatformSelection();\n return selected;\n }\n\n // Non-interactive with no detected platforms: default to cursor so installs are not silently no-ops.\n return ['cursor'] as Platform[];\n}\n\n\n", "import type { InstallationContext } from '../context.js';\nimport { performIndexBasedInstallationPhases } from '../../operations/installation-executor.js';\nimport { displayDependencyTree } from '../../../dependency-resolver/display.js';\nimport { resolvePlatforms } from '../../platform-resolution.js';\nimport { logger } from '../../../../utils/logger.js';\nimport { splitPackageNameForTelemetry } from '../../../../utils/plugin-naming.js';\n\nimport type { RelocatedFile } from '../../conflicts/file-conflict-resolver.js';\n\nexport interface ExecutionResult {\n installedCount: number;\n skippedCount: number;\n errorCount: number;\n allAddedFiles: string[];\n allUpdatedFiles: string[];\n rootFileResults: { installed: string[]; updated: string[]; skipped: string[] };\n hadErrors: boolean;\n installedAnyFiles: boolean;\n errors?: string[];\n /** True when namespace conflict resolution was triggered for any package */\n namespaced?: boolean;\n /** Files that were physically relocated on disk during namespace resolution */\n relocatedFiles?: RelocatedFile[];\n}\n\n/**\n * Execute installation phase\n */\nexport async function executeInstallationPhase(\n ctx: InstallationContext\n): Promise<ExecutionResult> {\n // Display dependency tree\n displayDependencyTree(ctx.resolvedPackages, true);\n \n // Resolve platforms if not already set (orchestrator preflight sets for bulk/single)\n if (ctx.platforms.length === 0) {\n const canPrompt = ctx.execution.interactive ?? false;\n ctx.platforms = await resolvePlatforms(\n ctx.targetDir,\n ctx.options.platforms,\n { interactive: canPrompt }\n );\n }\n\n // Get conflict result from context\n const conflictResult = ctx.conflictResult;\n\n // Execute installation\n const outcome = await performIndexBasedInstallationPhases({\n cwd: ctx.targetDir,\n packages: ctx.resolvedPackages,\n platforms: ctx.platforms,\n conflictResult,\n options: ctx.options,\n targetDir: ctx.targetDir,\n matchedPattern: ctx.matchedPattern // Phase 4: Pass matched pattern\n });\n \n // Track errors in context\n outcome.errors?.forEach(e => ctx.errors.push(e));\n \n const hadErrors = outcome.errorCount > 0;\n const installedAnyFiles =\n outcome.allAddedFiles.length > 0 ||\n outcome.allUpdatedFiles.length > 0 ||\n outcome.rootFileResults.installed.length > 0 ||\n outcome.rootFileResults.updated.length > 0;\n \n // Record telemetry for successful installations\n if (installedAnyFiles && ctx.execution.telemetryCollector) {\n for (const pkg of ctx.resolvedPackages) {\n // Split package name into base name and resource path\n // This handles cases like \"gh@user/repo/agents/designer\" -> base: \"gh@user/repo\", path: \"agents/designer\"\n const { baseName, resourcePath: nameResourcePath } = splitPackageNameForTelemetry(pkg.name);\n \n // Determine the actual resource path to send\n // Priority: ctx.matchedPattern > nameResourcePath (extracted from package name)\n const resourcePath = ctx.matchedPattern || nameResourcePath;\n \n // Determine resource type\n let resourceType: string | undefined;\n if (pkg.marketplaceMetadata) {\n resourceType = 'plugin';\n } else if (resourcePath) {\n // Check if this was an agent or skill based on resource path\n if (resourcePath.includes('agent')) {\n resourceType = 'agent';\n } else if (resourcePath.includes('skill')) {\n resourceType = 'skill';\n }\n }\n \n // Extract resource name from resource path or package name\n const resourceName = resourcePath \n ? resourcePath.split('/').pop()?.replace(/\\.(md|json)$/, '') || pkg.name.split('/').pop() || pkg.name\n : pkg.name.split('/').pop() || pkg.name;\n \n ctx.execution.telemetryCollector.recordInstall({\n packageName: baseName, // Send base package name (e.g., \"gh@user/repo\")\n version: pkg.version,\n resourcePath, // Send resource path separately (e.g., \"agents/designer\")\n resourceType,\n resourceName,\n marketplaceName: pkg.marketplaceMetadata?.pluginName,\n pluginName: pkg.marketplaceMetadata?.pluginName\n });\n }\n }\n \n return {\n ...outcome,\n hadErrors,\n installedAnyFiles,\n errors: outcome.errors\n };\n}\n\n", "import type { InstallationContext } from '../context.js';\nimport { addPackageToYml } from '../../../package-management.js';\nimport { formatPathForYaml } from '../../../../utils/path-resolution.js';\nimport { logger } from '../../../../utils/logger.js';\n\n/**\n * Update manifest phase (openpackage.yml)\n */\nexport async function updateManifestPhase(ctx: InstallationContext): Promise<void> {\n const mainPackage = ctx.resolvedPackages.find(pkg => pkg.isRoot);\n \n if (!mainPackage) {\n logger.warn(`No root package found in resolved packages, skipping manifest update`);\n return;\n }\n \n try {\n // Determine fields based on source type\n const fields = buildManifestFields(ctx, mainPackage);\n \n await addPackageToYml(\n ctx.targetDir,\n ctx.source.packageName,\n mainPackage.version,\n ctx.options.dev ?? false,\n fields.range,\n fields.force,\n fields.path,\n fields.gitUrl,\n fields.gitRef,\n fields.gitPath,\n fields.base // Phase 4: Pass base field for resource model\n );\n \n logger.info(`Updated manifest for ${ctx.source.packageName}`);\n \n } catch (error) {\n logger.warn(`Failed to update manifest: ${error}`);\n // Non-fatal - installation succeeded even if manifest update failed\n }\n}\n\nfunction buildManifestFields(ctx: InstallationContext, mainPackage: any) {\n const fields: any = {\n range: undefined,\n force: true,\n path: undefined,\n gitUrl: undefined,\n gitRef: undefined,\n gitPath: undefined,\n base: undefined // Phase 4: Base field for resource model\n };\n \n // Check for git source override first (for marketplace plugins)\n // This allows path-based loading with git-based manifest recording\n if (ctx.source.gitSourceOverride) {\n fields.gitUrl = ctx.source.gitSourceOverride.gitUrl;\n fields.gitRef = ctx.source.gitSourceOverride.gitRef;\n // If this install was scoped to a specific resource, record the full repo-relative resource path.\n // This keeps manifest entries logically consistent with ctx.source.packageName (which includes the resource path).\n fields.gitPath = ctx.source.resourcePath ?? ctx.source.gitSourceOverride.gitPath;\n return fields;\n }\n \n // Phase 4: Record base field if user-selected or non-default\n // This ensures reproducible installs when ambiguity was resolved\n if (ctx.baseRelative && ctx.baseSource === 'user-selection') {\n fields.base = ctx.baseRelative;\n }\n \n switch (ctx.source.type) {\n case 'registry':\n // Registry packages get version range\n fields.range = ctx.source.version;\n break;\n \n case 'path':\n // Path packages get path field\n // Use centralized path formatting for consistency with workspace index\n fields.path = formatPathForYaml(ctx.source.localPath || '', ctx.targetDir);\n break;\n \n case 'git':\n // Git packages get git fields\n fields.gitUrl = ctx.source.gitUrl;\n fields.gitRef = ctx.source.gitRef;\n // For resource-scoped installs, prefer recording the concrete resource path (file or dir).\n fields.gitPath = ctx.source.resourcePath ?? ctx.source.gitPath;\n break;\n \n case 'workspace':\n // Workspace (apply) doesn't update manifest\n break;\n }\n \n return fields;\n}\n", "import type { PackageRemoteResolutionOutcome } from './types.js';\nimport type { RelocatedFile } from './conflicts/file-conflict-resolver.js';\nimport type { OutputPort } from '../ports/output.js';\nimport { resolveOutput } from '../ports/resolve.js';\nimport { extractRemoteErrorReason } from '../../utils/error-reasons.js';\nimport { formatPathForDisplay, getTreeConnector } from '../../utils/formatters.js';\n\n/**\n * Data required to render the install report.\n *\n * Replaces the previous 13-positional-parameter signature with a single\n * options object for clarity and extensibility.\n */\nexport interface InstallReportData {\n packageName: string;\n resolvedPackages: any[];\n platformResult: { platforms: string[]; created: string[] };\n options: any;\n mainPackage?: any;\n installedFiles?: string[];\n updatedFiles?: string[];\n rootFileResults?: { installed: string[]; updated: string[]; skipped: string[] };\n missingPackages?: string[];\n missingPackageOutcomes?: Record<string, PackageRemoteResolutionOutcome>;\n errorCount?: number;\n errors?: string[];\n /** When true, show \"dependency recorded in your manifest\" for 0-install success. Defaults to true. */\n isDependencyInstall?: boolean;\n /** True when namespace conflict resolution was triggered */\n namespaced?: boolean;\n /** Files that were physically relocated on disk during namespace resolution */\n relocatedFiles?: RelocatedFile[];\n /** When true, use compact note-based display for file lists (interactive mode) */\n interactive?: boolean;\n}\n\n// ============================================================================\n// Helper: render a list of items with correct tree connectors\n// ============================================================================\n\nfunction renderTreeList(items: string[], output: OutputPort, indent: string = ' '): void {\n for (let i = 0; i < items.length; i++) {\n const connector = getTreeConnector(i === items.length - 1);\n output.info(`${indent}${connector}${items[i]}`);\n }\n}\n\n/**\n * Render a file list as a note box (interactive) or tree list (non-interactive).\n * Matches the pattern used in add.ts and remove.ts.\n */\nfunction renderFileList(\n items: string[],\n title: string,\n output: OutputPort,\n interactive: boolean\n): void {\n if (interactive) {\n const maxDisplay = 10;\n const displayItems = items.slice(0, maxDisplay);\n const more = items.length > maxDisplay ? `\\n... and ${items.length - maxDisplay} more` : '';\n output.note(displayItems.join('\\n') + more, title);\n } else {\n output.success(title);\n renderTreeList(items, output);\n }\n}\n\n// ============================================================================\n// Main display function\n// ============================================================================\n\nexport function displayInstallationResults(data: InstallReportData, output: OutputPort = resolveOutput()): void {\n const {\n packageName,\n resolvedPackages,\n platformResult,\n mainPackage,\n installedFiles,\n updatedFiles,\n rootFileResults,\n missingPackages,\n missingPackageOutcomes,\n errorCount,\n errors,\n isDependencyInstall = true,\n namespaced,\n relocatedFiles,\n interactive = false,\n } = data;\n\n // Check if installation actually succeeded\n const hadErrors = (errorCount && errorCount > 0) || false;\n const installedAnyFiles = (installedFiles && installedFiles.length > 0) ||\n (updatedFiles && updatedFiles.length > 0) ||\n (rootFileResults && (rootFileResults.installed.length > 0 || rootFileResults.updated.length > 0));\n\n if (hadErrors && !installedAnyFiles) {\n // Complete failure - nothing was installed\n output.error(`Failed to install ${packageName}${mainPackage ? `@${mainPackage.version}` : ''}`);\n if (errors && errors.length > 0) {\n output.error(`Installation errors:`);\n for (const error of errors) {\n output.info(` \u2022 ${error}`);\n }\n }\n return;\n }\n\n // Handle empty directory/filtered installs (0 files but still success)\n if (!installedAnyFiles && !hadErrors) {\n let summaryText = `Succeeded ${packageName}`;\n if (mainPackage) {\n summaryText += `@${mainPackage.version}`;\n }\n summaryText += ' with 0 installs';\n output.success(`${summaryText}`);\n output.info(`\uD83D\uDCA1 No files matched. The package directory may be empty or filters excluded all content.`);\n if (isDependencyInstall) {\n output.info(` The dependency has been recorded in your manifest.`);\n }\n return;\n }\n\n // \u2500\u2500 Main success header \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // In interactive mode, the load-package spinner already displays \"Installed <name>@<version>\"\n // so skip the duplicate header.\n if (!interactive) {\n let summaryText = `Installed ${packageName}`;\n if (mainPackage) {\n summaryText += `@${mainPackage.version}`;\n }\n output.success(`${summaryText}`);\n }\n\n // \u2500\u2500 Dependency packages \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n const dependencyPackages = resolvedPackages.filter(f => !f.isRoot);\n if (dependencyPackages.length > 0) {\n output.success(`Installed dependencies: ${dependencyPackages.length}`);\n const depLines = dependencyPackages.map(dep => {\n const packageSpecifier =\n typeof dep.name === 'string' && (dep.name.startsWith('@') || dep.name.startsWith('gh@'))\n ? dep.name\n : `@${dep.name}`;\n return `${packageSpecifier}@${dep.version}`;\n });\n renderTreeList(depLines, output);\n }\n output.success(`Total packages processed: ${resolvedPackages.length}`);\n\n // \u2500\u2500 Installed files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (installedFiles && installedFiles.length > 0) {\n const header = namespaced\n ? `Installed files: ${installedFiles.length} (namespaced)`\n : `Installed files: ${installedFiles.length}`;\n const sortedFiles = [...installedFiles].sort((a, b) => a.localeCompare(b));\n renderFileList(sortedFiles.map(f => formatPathForDisplay(f)), header, output, interactive);\n }\n\n // \u2500\u2500 Updated files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (updatedFiles && updatedFiles.length > 0) {\n const header = namespaced\n ? `Updated files: ${updatedFiles.length} (namespaced)`\n : `Updated files: ${updatedFiles.length}`;\n const sortedFiles = [...updatedFiles].sort((a, b) => a.localeCompare(b));\n renderFileList(sortedFiles.map(f => formatPathForDisplay(f)), header, output, interactive);\n }\n\n // \u2500\u2500 Relocated files (namespace-triggered moves) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (relocatedFiles && relocatedFiles.length > 0) {\n const lines = relocatedFiles.map(\n r => `${formatPathForDisplay(r.from)} \u2192 ${formatPathForDisplay(r.to)}`\n );\n renderFileList(lines, `Relocated files: ${relocatedFiles.length}`, output, interactive);\n }\n\n // \u2500\u2500 Root files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (rootFileResults) {\n const totalRootFiles = rootFileResults.installed.length + rootFileResults.updated.length;\n if (totalRootFiles > 0) {\n const rootLines: string[] = [];\n if (rootFileResults.installed.length > 0) {\n const sortedInstalled = [...rootFileResults.installed].sort((a, b) => a.localeCompare(b));\n for (const file of sortedInstalled) {\n rootLines.push(`${formatPathForDisplay(file)} (created)`);\n }\n }\n if (rootFileResults.updated.length > 0) {\n const sortedUpdated = [...rootFileResults.updated].sort((a, b) => a.localeCompare(b));\n for (const file of sortedUpdated) {\n rootLines.push(`${formatPathForDisplay(file)} (updated)`);\n }\n }\n renderFileList(rootLines, `Root files: ${totalRootFiles} file(s)`, output, interactive);\n }\n }\n\n // \u2500\u2500 Platform directories \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (platformResult.created.length > 0) {\n output.success(`Created platform directories: ${platformResult.created.join(', ')}`);\n }\n\n // \u2500\u2500 Partial failure: errors during an otherwise-successful install \u2500\u2500\u2500\u2500\n if (hadErrors && errors && errors.length > 0) {\n output.warn(`Errors during installation: ${errors.length}`);\n renderTreeList(errors, output);\n }\n\n // \u2500\u2500 Missing dependencies \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n if (missingPackages && missingPackages.length > 0) {\n output.warn(`Missing dependencies detected:`);\n for (const missing of missingPackages) {\n const reasonLabel = formatMissingDependencyReason(missingPackageOutcomes?.[missing]);\n output.info(` \u2022 ${missing} (${reasonLabel})`);\n }\n output.info(`\uD83D\uDCA1 To resolve missing dependencies:`);\n output.info(` \u2022 Create locally: opkg new <package-name>`);\n output.info(` \u2022 Install from registry/git: opkg install ${missingPackages.join(' ')}`);\n output.info(` \u2022 Remove from openpackage.yml`);\n output.info('');\n }\n}\n\nfunction formatMissingDependencyReason(outcome?: PackageRemoteResolutionOutcome): string {\n if (!outcome) {\n return 'not found in registry';\n }\n\n switch (outcome.reason) {\n case 'not-found':\n return 'not found in remote registry';\n case 'access-denied':\n return 'access denied';\n case 'network':\n return 'network error';\n case 'integrity':\n return 'integrity check failed';\n default:\n return extractRemoteErrorReason(outcome.message || 'unknown error');\n }\n}\n", "import type { CommandResult } from '../../../../types/index.js';\nimport type { InstallationContext } from '../context.js';\nimport type { ExecutionResult } from './execute.js';\nimport { displayInstallationResults } from '../../install-reporting.js';\nimport { getInstallRootDir } from '../../../../utils/paths.js';\nimport { resolveOutput } from '../../../ports/resolve.js';\n\n/**\n * Report results phase\n */\nexport async function reportResultsPhase(\n ctx: InstallationContext,\n installResult: ExecutionResult\n): Promise<CommandResult> {\n const mainPackage = ctx.resolvedPackages.find(pkg => pkg.isRoot);\n \n // Display results (only show \"dependency recorded\" for dependency installs, not workspace-root)\n const isDependencyInstall = ctx.source.type !== 'workspace';\n displayInstallationResults({\n packageName: ctx.source.packageName,\n resolvedPackages: ctx.resolvedPackages,\n platformResult: { platforms: ctx.platforms, created: [] },\n options: ctx.options,\n mainPackage,\n installedFiles: installResult.allAddedFiles,\n updatedFiles: installResult.allUpdatedFiles,\n rootFileResults: installResult.rootFileResults,\n missingPackages: [],\n missingPackageOutcomes: {},\n errorCount: installResult.errorCount,\n errors: installResult.errors,\n isDependencyInstall,\n namespaced: installResult.namespaced,\n relocatedFiles: installResult.relocatedFiles,\n interactive: ctx.execution.interactionPolicy?.isTTY ?? false,\n }, resolveOutput(ctx.execution));\n \n // Build result data\n return {\n success: true,\n data: {\n packageName: ctx.source.packageName,\n targetDir: getInstallRootDir(ctx.targetDir),\n resolvedPackages: ctx.resolvedPackages,\n totalPackages: ctx.resolvedPackages.length,\n installed: installResult.installedCount,\n skipped: installResult.skippedCount,\n totalOpenPackageFiles: installResult.installedCount + installResult.allUpdatedFiles.length\n },\n warnings: ctx.warnings.length > 0 ? Array.from(new Set(ctx.warnings)) : undefined\n };\n}\n", "import type { CommandResult } from '../../../types/index.js';\nimport type { InstallationContext } from './context.js';\nimport { loadPackagePhase } from './phases/load-package.js';\nimport { convertPhase } from './phases/convert.js';\nimport { resolveDependenciesPhase } from './phases/resolve-dependencies.js';\nimport { processConflictsPhase } from './phases/conflicts.js';\nimport { executeInstallationPhase } from './phases/execute.js';\nimport { updateManifestPhase } from './phases/manifest.js';\nimport { reportResultsPhase } from './phases/report.js';\nimport { shouldResolveDependencies, shouldUpdateManifest } from './context-helpers.js';\nimport { logger } from '../../../utils/logger.js';\nimport { createWorkspacePackageYml } from '../../package-management.js';\nimport { cleanupTempDirectory } from '../strategies/helpers/temp-directory.js';\nimport { resolveOutput } from '../../ports/resolve.js';\n\nfunction assertPipelineContextComplete(ctx: InstallationContext): void {\n if (!ctx.source.type) {\n throw new Error('Pipeline context invalid: ctx.source.type is required');\n }\n if (!ctx.source.packageName) {\n throw new Error('Pipeline context invalid: ctx.source.packageName must be set after load phase');\n }\n if (!ctx.source.contentRoot) {\n throw new Error('Pipeline context invalid: ctx.source.contentRoot must be set after load phase');\n }\n if (!Array.isArray(ctx.resolvedPackages) || ctx.resolvedPackages.length === 0) {\n throw new Error('Pipeline context invalid: ctx.resolvedPackages must contain a root package after load phase');\n }\n if (!ctx.resolvedPackages.some(p => (p as any).isRoot)) {\n throw new Error('Pipeline context invalid: ctx.resolvedPackages must contain an isRoot package');\n }\n}\n\n/**\n * Unified installation pipeline\n * \n * Handles all installation scenarios (install, apply, bulk) with conditional phase execution\n * based on the context mode.\n * \n * @param ctx - Installation context\n * @returns Command result\n */\nexport async function runUnifiedInstallPipeline(\n ctx: InstallationContext\n): Promise<CommandResult> {\n logger.info(`Starting unified installation pipeline`, {\n mode: ctx.mode,\n sourceType: ctx.source.type,\n packageName: ctx.source.packageName\n });\n \n let tempConversionRoot: string | null = null;\n try {\n // Phase 0: Ensure workspace manifest exists (auto-create if needed)\n // Only for install mode, not apply mode (apply requires existing installation)\n if (ctx.mode === 'install') {\n await createWorkspacePackageYml(ctx.targetDir);\n }\n \n // Phase 1: Load package from source (always)\n await loadPackagePhase(ctx);\n \n // Assert context is complete after load phase\n assertPipelineContextComplete(ctx);\n\n // Phase 2: Resolve dependencies (skip for apply mode)\n if (shouldResolveDependencies(ctx)) {\n await resolveDependenciesPhase(ctx);\n }\n\n // Phase 3: Convert package format if needed (Phase 4 integration)\n // Run AFTER dependency resolution so the final root package contentRoot is updated.\n await convertPhase(ctx);\n\n tempConversionRoot = (ctx as any)._tempConversionRoot ?? null;\n \n // Phase 4: Process conflicts (always)\n const shouldProceed = await processConflictsPhase(ctx);\n if (!shouldProceed) {\n return createCancellationResult(ctx);\n }\n \n // Phase 5: Execute installation (always)\n const installResult = await executeInstallationPhase(ctx);\n \n // Check for complete failure\n if (installResult.hadErrors && !installResult.installedAnyFiles) {\n return {\n success: false,\n error: `Failed to install ${ctx.source.packageName}: ${ctx.errors.join('; ')}`\n };\n }\n \n // Phase 6: Update manifest (skip for apply)\n if (shouldUpdateManifest(ctx)) {\n await updateManifestPhase(ctx);\n }\n \n // Phase 7: Report results (always)\n return await reportResultsPhase(ctx, installResult);\n \n } catch (error) {\n logger.error(`Pipeline failed for ${ctx.source.packageName}:`, error);\n \n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n warnings: ctx.warnings.length > 0 ? ctx.warnings : undefined\n };\n } finally {\n // Cleanup any temp conversion directory created during convert phase\n await cleanupTempDirectory(tempConversionRoot);\n }\n}\n\n/**\n * Create result for user cancellation\n */\nfunction createCancellationResult(ctx: InstallationContext): CommandResult {\n const out = resolveOutput(ctx.execution);\n out.info('Installation cancelled by user');\n \n return {\n success: true,\n data: {\n packageName: ctx.source.packageName,\n installed: 0,\n skipped: 1,\n totalPackages: 0\n }\n };\n}\n", "import type { CommandResult } from '../../../types/index.js';\nimport type { InstallationContext } from './context.js';\nimport { runUnifiedInstallPipeline } from './pipeline.js';\nimport { logger } from '../../../utils/logger.js';\n\nexport async function runMultiContextPipeline(\n contexts: InstallationContext[]\n): Promise<CommandResult> {\n if (contexts.length === 0) {\n return { success: true, data: { installed: 0, skipped: 0, results: [] } };\n }\n\n let installed = 0;\n let skipped = 0;\n let failed = 0;\n const results: Array<{ name: string; success: boolean; error?: string }> = [];\n\n for (const ctx of contexts) {\n const result = await runUnifiedInstallPipeline(ctx);\n const name = (result.data as any)?.packageName || ctx.source.packageName || 'unknown';\n\n if (result.success) {\n installed += (result.data as any)?.installed ?? 0;\n skipped += (result.data as any)?.skipped ?? 0;\n } else {\n failed += 1;\n logger.error(`Failed to install ${name}: ${result.error}`);\n }\n\n results.push({\n name,\n success: result.success,\n error: result.success ? undefined : result.error\n });\n }\n\n const success = failed === 0;\n return {\n success,\n data: {\n installed,\n skipped,\n results\n },\n error: success ? undefined : `${failed} resource${failed === 1 ? '' : 's'} failed to install`\n };\n}\n", "/**\n * Resource Selection Menu\n * \n * Interactive menu for selecting specific resources to install\n */\n\nimport type { OutputPort } from '../ports/output.js';\nimport type { PromptPort } from '../ports/prompt.js';\nimport { resolveOutput, resolvePrompt } from '../ports/resolve.js';\nimport { logger } from '../../utils/logger.js';\nimport { UserCancellationError } from '../../utils/errors.js';\nimport { getInstallableTypes, toLabelPlural, RESOURCE_TYPE_ORDER } from '../resources/resource-registry.js';\nimport type { ResourceCatalog, ResourceEntry } from '../resources/resource-catalog.js';\nimport type { \n ResourceDiscoveryResult, \n DiscoveredResource,\n SelectedResource,\n ResourceType \n} from './resource-types.js';\n\n/**\n * Display interactive resource selection menu\n * \n * @param discovery - Resource discovery result\n * @param packageName - Package name for display\n * @param packageVersion - Package version for display\n * @returns Array of selected resources (empty if cancelled)\n */\nexport async function promptResourceSelection(\n discovery: ResourceDiscoveryResult,\n packageName: string,\n packageVersion?: string,\n output?: OutputPort,\n prompt?: PromptPort\n): Promise<SelectedResource[]> {\n const out = output ?? resolveOutput();\n const prm = prompt ?? resolvePrompt();\n \n logger.debug('Prompting resource selection', {\n package: packageName,\n version: packageVersion,\n total: discovery.total\n });\n \n // No resources found\n if (discovery.total === 0) {\n out.warn('No resources found in this package');\n return [];\n }\n \n // Build grouped options by resource type\n const groupedOptions = buildGroupedOptions(discovery);\n \n if (Object.keys(groupedOptions).length === 0) {\n out.warn('No installable resources found');\n return [];\n }\n \n try {\n // Original: clackGroupMultiselect(message, groupedOptions, { selectableGroups, groupSpacing })\n // PromptPort.groupMultiselect does not support selectableGroups/groupSpacing options;\n // adapters should implement selectable groups and spacing as appropriate for their backend.\n const groups: Record<string, Array<{ label: string; value: DiscoveredResource }>> = {};\n for (const [groupName, options] of Object.entries(groupedOptions)) {\n groups[groupName] = options.map(opt => ({\n label: opt.label,\n value: opt.value\n }));\n }\n \n const selectedResources = await prm.groupMultiselect<DiscoveredResource>(\n 'Select resources to install:',\n groups\n );\n \n if (!selectedResources || selectedResources.length === 0) {\n logger.info('User cancelled resource selection or selected nothing');\n return [];\n }\n \n // Map selected DiscoveredResource objects to SelectedResource objects\n const selected: SelectedResource[] = selectedResources.map(resource => ({\n resourceType: resource.resourceType,\n resourcePath: resource.resourcePath,\n displayName: resource.displayName,\n filePath: resource.filePath,\n installKind: resource.installKind,\n version: resource.version\n }));\n \n logger.info('User selected resources', {\n count: selected.length,\n types: Array.from(new Set(selected.map(r => r.resourceType)))\n });\n \n return selected;\n } catch (error) {\n if (error instanceof UserCancellationError) {\n logger.info('User cancelled resource selection');\n return [];\n }\n throw error;\n }\n}\n\n/**\n * Build grouped options for resource selection\n */\nfunction buildGroupedOptions(\n discovery: ResourceDiscoveryResult\n): Record<string, Array<{ value: DiscoveredResource; label: string; hint: string }>> {\n const groupedOptions: Record<string, Array<{ value: DiscoveredResource; label: string; hint: string }>> = {};\n \n // Resource type display order and labels\n const typeOrder = getInstallableTypes().map(def => ({\n type: def.id as ResourceType,\n label: def.labelPlural,\n }));\n \n for (const { type, label } of typeOrder) {\n const resources = discovery.byType.get(type);\n \n if (!resources || resources.length === 0) {\n continue;\n }\n \n // Create group name with count\n const groupName = `${label} (${resources.length})`;\n const groupOptions: Array<{ value: DiscoveredResource; label: string; hint: string }> = [];\n \n // Add resources to this group\n for (const resource of resources) {\n const versionSuffix = resource.version ? ` (v${resource.version})` : '';\n const pathHint = getPathHint(resource);\n \n // Build hint: description + path\n const fullDescription = resource.description \n ? `${resource.description} - ${pathHint}`\n : pathHint;\n const truncatedDescription = truncateToLines(fullDescription, 2);\n \n groupOptions.push({\n value: resource,\n label: `${resource.displayName}${versionSuffix}`,\n hint: truncatedDescription\n });\n }\n \n groupedOptions[groupName] = groupOptions;\n }\n \n return groupedOptions;\n}\n\n/**\n * Get path hint for display\n */\nfunction getPathHint(resource: DiscoveredResource): string {\n const path = resource.resourcePath;\n \n if (resource.installKind === 'directory') {\n return `${path}/`;\n }\n \n return path;\n}\n\n/**\n * Truncate text to a maximum number of lines\n * Approximates line breaks based on typical terminal width (~80 chars per line)\n */\nfunction truncateToLines(text: string, maxLines: number): string {\n const charsPerLine = 80;\n const maxChars = charsPerLine * maxLines;\n \n if (text.length <= maxChars) {\n return text;\n }\n \n // Truncate and add ellipsis\n return text.substring(0, maxChars - 3) + '...';\n}\n\n/**\n * Display summary of selected resources\n */\nexport function displaySelectionSummary(selected: SelectedResource[], output?: OutputPort): void {\n if (selected.length === 0) {\n return;\n }\n \n const out = output ?? resolveOutput();\n \n // Group by type\n const byType = new Map<ResourceType, number>();\n for (const resource of selected) {\n const count = byType.get(resource.resourceType) || 0;\n byType.set(resource.resourceType, count + 1);\n }\n \n const summary = [`Selected ${selected.length} resource${selected.length === 1 ? '' : 's'}:`];\n \n for (const [type, count] of byType.entries()) {\n const label = getTypeLabel(type);\n summary.push(` \u2022 ${count} ${label.toLowerCase()}`);\n }\n \n out.info(summary.join('\\n'));\n}\n\n/**\n * Get display label for resource type\n */\nfunction getTypeLabel(type: ResourceType): string {\n return toLabelPlural(type);\n}\n\nexport async function promptCatalogSelection(\n catalog: ResourceCatalog,\n header: { name: string; version?: string; action: string },\n output?: OutputPort,\n prompt?: PromptPort\n): Promise<ResourceEntry[]> {\n const out = output ?? resolveOutput();\n const prm = prompt ?? resolvePrompt();\n \n logger.debug('Prompting catalog selection', {\n action: header.action,\n total: catalog.total\n });\n \n if (catalog.total === 0) {\n out.warn('No resources found');\n return [];\n }\n \n const { choices, indexToEntry } = buildCatalogMenuChoices(catalog);\n \n if (choices.length === 0) {\n out.warn('No selectable resources found');\n return [];\n }\n \n try {\n // Original: smartMultiselect(message, choices, categoryMap, { hint, min })\n // smartMultiselect used a categoryMap to expand category selections into child indices.\n // PromptPort.multiselect returns selected values directly; category expansion\n // is the responsibility of the adapter implementation.\n const selectedIndices = await prm.multiselect<number>(\n `Select resources to ${header.action}:`,\n choices,\n {\n hint: '- Space: select/deselect \u2022 Enter: confirm \u2022 Categories expand to all items',\n min: 1\n }\n );\n \n if (!selectedIndices || selectedIndices.length === 0) {\n logger.info('User cancelled resource selection or selected nothing');\n return [];\n }\n \n const resourceIndices = selectedIndices.filter(idx => idx >= 0);\n const selected = resourceIndices\n .filter(idx => indexToEntry.has(idx))\n .map(idx => indexToEntry.get(idx)!);\n \n logger.info('User selected resources', {\n count: selected.length,\n types: Array.from(new Set(selected.map(r => r.resourceType)))\n });\n \n return selected;\n } catch (error) {\n if (error instanceof UserCancellationError) {\n logger.info('User cancelled resource selection');\n return [];\n }\n throw error;\n }\n}\n\nfunction buildCatalogMenuChoices(\n catalog: ResourceCatalog\n): { choices: Array<{ title: string; value: number; description?: string }>; indexToEntry: Map<number, ResourceEntry> } {\n const choices: Array<{ title: string; value: number; description?: string }> = [];\n const indexToEntry = new Map<number, ResourceEntry>();\n \n const typeOrder = RESOURCE_TYPE_ORDER;\n \n let globalIndex = 0;\n let categoryIndex = -1;\n \n for (const typeId of typeOrder) {\n const entries = catalog.byType.get(typeId);\n if (!entries || entries.length === 0) continue;\n \n const label = toLabelPlural(typeId);\n const currentCategoryIndex = categoryIndex;\n \n const boldLabel = `\\x1b[1m${label} (${entries.length}):\\x1b[0m`;\n choices.push({\n title: boldLabel,\n value: currentCategoryIndex,\n description: 'Select/deselect all items in this category'\n });\n \n for (const entry of entries) {\n const versionSuffix = entry.version ? ` (v${entry.version})` : '';\n const pathHint = getCatalogPathHint(entry);\n \n const fullDescription = entry.description\n ? `${entry.description} - ${pathHint}`\n : pathHint;\n const truncatedDescription = fullDescription.length > 160\n ? fullDescription.substring(0, 157) + '...'\n : fullDescription;\n \n indexToEntry.set(globalIndex, entry);\n \n choices.push({\n title: ` ${entry.name}${versionSuffix}`,\n value: globalIndex++,\n description: truncatedDescription\n });\n }\n \n categoryIndex--;\n }\n \n return { choices, indexToEntry };\n}\n\nfunction getCatalogPathHint(entry: ResourceEntry): string {\n if (entry.origin === 'installed') {\n if (entry.files.length === 1 && entry.files[0].target) {\n return entry.files[0].target;\n }\n return `(${entry.files.length} file${entry.files.length === 1 ? '' : 's'})`;\n }\n \n if (entry.resourcePath) {\n return entry.installKind === 'directory' ? `${entry.resourcePath}/` : entry.resourcePath;\n }\n \n return '';\n}\n\nexport function displayCatalogSelectionSummary(selected: ResourceEntry[], action: string, output?: OutputPort): void {\n if (selected.length === 0) return;\n \n const out = output ?? resolveOutput();\n \n const byType = new Map<string, number>();\n for (const entry of selected) {\n byType.set(entry.resourceType, (byType.get(entry.resourceType) || 0) + 1);\n }\n \n const lines: string[] = [];\n lines.push(`\\n\u2713 Selected ${selected.length} resource${selected.length === 1 ? '' : 's'} to ${action}:`);\n \n for (const [type, count] of byType.entries()) {\n const label = toLabelPlural(type as any);\n lines.push(` \u2022 ${count} ${label.toLowerCase()}`);\n }\n \n lines.push('');\n out.info(lines.join('\\n'));\n}\n", "/**\n * Plugin source type definitions and normalization.\n * Implements Claude Code marketplace plugin source specification.\n * \n * See: https://code.claude.com/docs/en/plugin-marketplaces#plugin-sources\n */\n\nimport { parseGitUrl } from '../../utils/git-url-parser.js';\nimport { logger } from '../../utils/logger.js';\nimport { ValidationError } from '../../utils/errors.js';\n\n/**\n * Structured source object types from Claude Code spec.\n * \n * Supported source types:\n * - Relative paths: string like \"./plugins/my-plugin\"\n * - GitHub: { source: 'github', repo: 'owner/repo', ref?, path? }\n * - Git URL: { source: 'url', url: 'https://...', ref?, path? }\n */\nexport type PluginSourceSpec = string | PluginSourceObject;\n\nexport type PluginSourceObject = GitHubSource | GitUrlSource;\n\nexport interface GitHubSource {\n source: 'github';\n repo: string; // \"owner/repo\" format\n ref?: string; // Optional branch/tag/sha\n path?: string; // Optional subdirectory within repo\n}\n\nexport interface GitUrlSource {\n source: 'url';\n url: string; // Full git URL\n ref?: string; // Optional branch/tag/sha\n path?: string; // Optional subdirectory\n}\n\n/**\n * Normalized plugin source for internal use.\n * All source types are converted to this common format.\n */\nexport interface NormalizedPluginSource {\n type: 'relative-path' | 'git';\n \n // For relative-path type\n relativePath?: string;\n \n // For git type (both GitHub and Git URL)\n gitUrl?: string;\n gitRef?: string;\n gitPath?: string;\n \n // Original spec for reference\n rawSource: PluginSourceSpec;\n}\n\n/**\n * Normalize a plugin source spec into a consistent internal format.\n * Handles all source types from the Claude Code marketplace spec.\n * \n * @param source - Plugin source from marketplace manifest\n * @param pluginName - Plugin name for error messages\n * @returns Normalized source\n * @throws ValidationError if source is invalid\n */\nexport function normalizePluginSource(\n source: PluginSourceSpec,\n pluginName: string\n): NormalizedPluginSource {\n if (!source) {\n throw new ValidationError(\n `Plugin '${pluginName}' missing required 'source' field`\n );\n }\n \n // Case 1: String source (relative path)\n if (typeof source === 'string') {\n return normalizeRelativePathSource(source, pluginName);\n }\n \n // Case 2: Structured source object\n const sourceObj = source as PluginSourceObject;\n \n if (!sourceObj.source) {\n throw new ValidationError(\n `Plugin '${pluginName}' has invalid source object: missing 'source' field`\n );\n }\n \n switch (sourceObj.source) {\n case 'github':\n return normalizeGitHubSource(sourceObj as GitHubSource, pluginName);\n \n case 'url':\n return normalizeGitUrlSource(sourceObj as GitUrlSource, pluginName);\n \n default:\n throw new ValidationError(\n `Plugin '${pluginName}' has unsupported source type: '${(sourceObj as any).source}'. ` +\n `Supported types: 'github', 'url', or relative path string`\n );\n }\n}\n\n/**\n * Normalize a relative path source.\n */\nfunction normalizeRelativePathSource(\n path: string,\n pluginName: string\n): NormalizedPluginSource {\n // Validate path doesn't traverse upward beyond marketplace root\n if (path.includes('..')) {\n throw new ValidationError(\n `Plugin '${pluginName}' source path contains '..' which is not allowed for security reasons`\n );\n }\n \n // Validate path is not absolute\n if (path.startsWith('/')) {\n throw new ValidationError(\n `Plugin '${pluginName}' source path must be relative to marketplace root, not absolute`\n );\n }\n \n // Normalize path: strip leading ./ if present\n const normalizedPath = path.startsWith('./') ? path.substring(2) : path;\n \n return {\n type: 'relative-path',\n relativePath: normalizedPath,\n rawSource: path\n };\n}\n\n/**\n * Normalize a GitHub source.\n */\nfunction normalizeGitHubSource(\n source: GitHubSource,\n pluginName: string\n): NormalizedPluginSource {\n // Validate repo format\n if (!source.repo) {\n throw new ValidationError(\n `Plugin '${pluginName}' GitHub source missing 'repo' field`\n );\n }\n \n if (!source.repo.includes('/')) {\n throw new ValidationError(\n `Plugin '${pluginName}' GitHub source 'repo' must be in 'owner/repo' format, got: '${source.repo}'`\n );\n }\n \n const parts = source.repo.split('/');\n if (parts.length !== 2 || !parts[0] || !parts[1]) {\n throw new ValidationError(\n `Plugin '${pluginName}' GitHub source 'repo' must be in 'owner/repo' format, got: '${source.repo}'`\n );\n }\n \n // Convert to full git URL\n const gitUrl = `https://github.com/${source.repo}.git`;\n \n return {\n type: 'git',\n gitUrl,\n gitRef: source.ref,\n gitPath: source.path,\n rawSource: source\n };\n}\n\n/**\n * Normalize a Git URL source.\n */\nfunction normalizeGitUrlSource(\n source: GitUrlSource,\n pluginName: string\n): NormalizedPluginSource {\n // Validate URL field exists\n if (!source.url) {\n throw new ValidationError(\n `Plugin '${pluginName}' Git URL source missing 'url' field`\n );\n }\n \n // Validate URL format by attempting to parse it\n try {\n parseGitUrl(source.url);\n } catch (error) {\n throw new ValidationError(\n `Plugin '${pluginName}' has invalid Git URL: ${source.url}. ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n \n return {\n type: 'git',\n gitUrl: source.url,\n gitRef: source.ref,\n gitPath: source.path,\n rawSource: source\n };\n}\n\n/**\n * Check if a normalized source is a relative path.\n */\nexport function isRelativePathSource(source: NormalizedPluginSource): boolean {\n return source.type === 'relative-path';\n}\n\n/**\n * Check if a normalized source is a git source (GitHub or Git URL).\n */\nexport function isGitSource(source: NormalizedPluginSource): boolean {\n return source.type === 'git';\n}\n", "import { normalizePathForProcessing } from '../../../utils/path-normalization.js';\nimport { DIR_PATTERNS, PACKAGE_PATHS } from '../../../constants/index.js';\n\n/**\n * Validate that target directory is not inside .openpackage metadata.\n * @throws Error if target is inside metadata directory\n */\nexport function assertTargetDirOutsideMetadata(targetDir: string): void {\n const normalized = normalizePathForProcessing(targetDir ?? '.');\n if (!normalized || normalized === '.') {\n return; // default install root\n }\n\n if (\n normalized === DIR_PATTERNS.OPENPACKAGE ||\n normalized.startsWith(`${DIR_PATTERNS.OPENPACKAGE}/`)\n ) {\n throw new Error(\n `Installation target '${targetDir}' cannot point inside ${DIR_PATTERNS.OPENPACKAGE} ` +\n `(reserved for metadata like ${PACKAGE_PATHS.INDEX_RELATIVE}). ` +\n `Choose a workspace path outside metadata.`\n );\n }\n}\n", "import type { InstallationContext } from '../../unified/context.js';\nimport type { ExecutionContext } from '../../../../types/index.js';\nimport type { \n NormalizedInstallOptions, \n InputClassification, \n PreprocessResult,\n InstallStrategy \n} from '../types.js';\n\n/**\n * Abstract base class for install strategies.\n * Provides common functionality.\n */\nexport abstract class BaseInstallStrategy implements InstallStrategy {\n abstract readonly name: string;\n \n abstract canHandle(classification: InputClassification): boolean;\n \n abstract buildContext(\n classification: InputClassification,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<InstallationContext>;\n \n abstract preprocess(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult>;\n \n /**\n * Create a simple preprocess result with no special handling.\n */\n protected createNormalResult(context: InstallationContext): PreprocessResult {\n return { context };\n }\n \n /**\n * Create a marketplace preprocess result.\n */\n protected createMarketplaceResult(\n context: InstallationContext,\n manifest?: any\n ): PreprocessResult {\n return {\n context,\n specialHandling: 'marketplace',\n marketplaceManifest: manifest\n };\n }\n \n /**\n * Create an ambiguous preprocess result.\n */\n protected createAmbiguousResult(\n context: InstallationContext,\n matches: Array<{ pattern: string; base: string; startIndex: number }>\n ): PreprocessResult {\n return {\n context,\n specialHandling: 'ambiguous',\n ambiguousMatches: matches\n };\n }\n \n /**\n * Create a multi-resource preprocess result.\n */\n protected createMultiResourceResult(\n context: InstallationContext,\n resourceContexts: InstallationContext[]\n ): PreprocessResult {\n return {\n context,\n specialHandling: 'multi-resource',\n resourceContexts\n };\n }\n}\n", "import type { InstallationContext, PackageSource } from '../../unified/context.js';\nimport type { ExecutionContext } from '../../../../types/index.js';\nimport type { \n NormalizedInstallOptions, \n InputClassification, \n PreprocessResult \n} from '../types.js';\nimport { BaseInstallStrategy } from './base.js';\nimport { getLoaderForSource } from '../../sources/loader-factory.js';\nimport { buildResourceInstallContexts } from '../../unified/context-builders.js';\nimport { normalizePlatforms } from '../../../platform/platform-mapper.js';\nimport { logger } from '../../../../utils/logger.js';\nimport { applyBaseDetection, computePathScoping } from '../../preprocessing/base-resolver.js';\nimport { resolveConvenienceResources } from '../../preprocessing/convenience-preprocessor.js';\nimport { resolveOutput } from '../../../ports/resolve.js';\n\nexport class GitInstallStrategy extends BaseInstallStrategy {\n readonly name = 'git';\n \n canHandle(classification: InputClassification): boolean {\n return classification.type === 'git';\n }\n \n async buildContext(\n classification: InputClassification,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<InstallationContext> {\n if (classification.type !== 'git') {\n throw new Error('GitStrategy cannot handle non-git classification');\n }\n \n const source: PackageSource = {\n type: 'git',\n packageName: '', // Populated after loading\n gitUrl: classification.gitUrl,\n gitRef: classification.gitRef,\n resourcePath: classification.resourcePath\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n }\n \n async preprocess(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult> {\n // Load the source\n const loader = getLoaderForSource(context.source);\n const loaded = await loader.load(context.source, options, execContext);\n \n // Update context with loaded info\n context.source.packageName = loaded.packageName;\n context.source.version = loaded.version;\n context.source.contentRoot = loaded.contentRoot;\n context.source.pluginMetadata = loaded.pluginMetadata;\n \n // Store commitSha for marketplace\n if (loaded.sourceMetadata?.commitSha) {\n (context.source as any)._commitSha = loaded.sourceMetadata.commitSha;\n }\n \n // Check for marketplace (early exit)\n if (loaded.pluginMetadata?.pluginType === 'marketplace') {\n return this.createMarketplaceResult(context);\n }\n \n // Process base detection (centralized)\n const baseResult = applyBaseDetection(context, loaded);\n if (baseResult.specialHandling === 'marketplace') {\n return this.createMarketplaceResult(context);\n }\n if (baseResult.specialHandling === 'ambiguous') {\n return this.createAmbiguousResult(context, baseResult.ambiguousMatches ?? []);\n }\n \n // Apply resource path scoping\n const resourcePath = context.source.resourcePath;\n if (resourcePath) {\n await computePathScoping(context, loaded, resourcePath);\n }\n\n // Populate root resolved package so the pipeline can skip re-loading.\n // (The unified load phase is the only other place that populates ctx.resolvedPackages.)\n context.resolvedPackages = [\n {\n name: context.source.packageName,\n version: context.source.version || loaded.version,\n pkg: {\n metadata: loaded.metadata,\n files: [],\n _format: (loaded.metadata as any)?._format || context.source.pluginMetadata?.format\n },\n isRoot: true,\n source: 'git',\n contentRoot: context.source.contentRoot || loaded.contentRoot\n } as any\n ];\n \n // Apply convenience filters (--agents, --skills)\n if (options.agents?.length || options.skills?.length || options.rules?.length || options.commands?.length) {\n return this.handleConvenienceFilters(context, loaded, options, execContext);\n }\n \n // Warn about unused --plugins flag\n if (options.plugins?.length && !options.agents && !options.skills) {\n const out = resolveOutput(execContext);\n out.warn('--plugins flag is only used with marketplace sources. Ignoring.');\n }\n \n return this.createNormalResult(context);\n }\n \n /**\n * Handle convenience filter options.\n */\n private async handleConvenienceFilters(\n context: InstallationContext,\n loaded: any,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult> {\n const basePath = context.detectedBase || loaded.contentRoot || execContext.targetDir;\n const repoRoot = loaded.sourceMetadata?.repoPath || loaded.contentRoot || basePath;\n\n const resources = await resolveConvenienceResources(basePath, repoRoot, {\n agents: options.agents,\n skills: options.skills,\n rules: options.rules,\n commands: options.commands\n });\n\n const resourceContexts = buildResourceInstallContexts(context, resources, repoRoot);\n return this.createMultiResourceResult(context, resourceContexts);\n }\n}\n", "/**\n * PathInstallStrategy handles installs from local directories/tarballs.\n *\n * It preloads the source once and populates the root resolved package so the unified\n * pipeline can skip re-loading.\n */\nimport type { InstallationContext, PackageSource } from '../../unified/context.js';\nimport type { ExecutionContext } from '../../../../types/index.js';\nimport type { NormalizedInstallOptions, InputClassification, PreprocessResult } from '../types.js';\nimport { BaseInstallStrategy } from './base.js';\nimport { getLoaderForSource } from '../../sources/loader-factory.js';\nimport { normalizePlatforms } from '../../../platform/platform-mapper.js';\n\nexport class PathInstallStrategy extends BaseInstallStrategy {\n readonly name = 'path';\n \n canHandle(classification: InputClassification): boolean {\n return classification.type === 'path';\n }\n \n async buildContext(\n classification: InputClassification,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<InstallationContext> {\n if (classification.type !== 'path') {\n throw new Error('PathStrategy cannot handle non-path classification');\n }\n \n const source: PackageSource = {\n type: 'path',\n packageName: '',\n localPath: classification.localPath,\n sourceType: 'directory' // Could detect tarball here\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n }\n \n async preprocess(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult> {\n const loader = getLoaderForSource(context.source);\n const loaded = await loader.load(context.source, options, execContext);\n \n context.source.packageName = loaded.packageName;\n context.source.version = loaded.version;\n context.source.contentRoot = loaded.contentRoot;\n context.source.pluginMetadata = loaded.pluginMetadata;\n\n context.resolvedPackages = [\n {\n name: context.source.packageName,\n version: context.source.version || loaded.version,\n pkg: {\n metadata: loaded.metadata,\n files: [],\n _format: (loaded.metadata as any)?._format || context.source.pluginMetadata?.format\n },\n isRoot: true,\n source: 'path',\n contentRoot: context.source.contentRoot || loaded.contentRoot\n } as any\n ];\n \n if (loaded.pluginMetadata?.pluginType === 'marketplace') {\n return this.createMarketplaceResult(context);\n }\n \n return this.createNormalResult(context);\n }\n}\n", "/**\n * RegistryInstallStrategy handles installs from the OpenPackage registry.\n *\n * Registry sources are loaded by the unified pipeline (load phase), since their metadata\n * and resolution behavior is centralized there.\n */\nimport type { InstallationContext, PackageSource } from '../../unified/context.js';\nimport type { ExecutionContext } from '../../../../types/index.js';\nimport type { NormalizedInstallOptions, InputClassification, PreprocessResult } from '../types.js';\nimport { BaseInstallStrategy } from './base.js';\nimport { normalizePlatforms } from '../../../platform/platform-mapper.js';\n\nexport class RegistryInstallStrategy extends BaseInstallStrategy {\n readonly name = 'registry';\n \n canHandle(classification: InputClassification): boolean {\n return classification.type === 'registry';\n }\n \n async buildContext(\n classification: InputClassification,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<InstallationContext> {\n if (classification.type !== 'registry') {\n throw new Error('RegistryStrategy cannot handle non-registry classification');\n }\n \n const source: PackageSource = {\n type: 'registry',\n packageName: classification.packageName,\n version: classification.version,\n resourcePath: classification.resourcePath\n };\n \n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source,\n mode: 'install',\n options,\n platforms: normalizePlatforms(options.platforms) || [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n }\n \n async preprocess(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult> {\n // Registry sources are handled by the pipeline's load phase\n return this.createNormalResult(context);\n }\n}\n", "/**\n * BulkInstallStrategy handles `opkg install` with no package argument.\n *\n * It expands the workspace manifest into multiple `InstallationContext`s and hands them\n * off to the multi-context pipeline via the orchestrator.\n */\nimport type { InstallationContext } from '../../unified/context.js';\nimport type { ExecutionContext } from '../../../../types/index.js';\nimport type { NormalizedInstallOptions, InputClassification, PreprocessResult } from '../types.js';\nimport { BaseInstallStrategy } from './base.js';\nimport { buildInstallContext, type BulkInstallContextsResult } from '../../unified/context-builders.js';\n\nexport class BulkInstallStrategy extends BaseInstallStrategy {\n readonly name = 'bulk';\n \n canHandle(classification: InputClassification): boolean {\n return classification.type === 'bulk';\n }\n \n async buildContext(\n classification: InputClassification,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<InstallationContext> {\n // Bulk install returns multiple contexts, but we need to return one\n // The actual multi-context handling is done in preprocess\n // Return a placeholder context\n return {\n execution: execContext,\n targetDir: execContext.targetDir,\n source: { type: 'workspace', packageName: '__bulk__' },\n mode: 'install',\n options,\n platforms: [],\n resolvedPackages: [],\n warnings: [],\n errors: []\n };\n }\n \n async preprocess(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n ): Promise<PreprocessResult> {\n // Build workspace + dependency contexts from openpackage.yml\n const raw = await buildInstallContext(execContext, undefined, options);\n\n const bulk = raw as BulkInstallContextsResult;\n if (bulk?.dependencyContexts && 'workspaceContext' in bulk) {\n const { workspaceContext: wsCtx, dependencyContexts: depCtxs } = bulk;\n if (depCtxs.length === 0 && !wsCtx) {\n return this.createNormalResult(context);\n }\n return {\n context,\n specialHandling: 'multi-resource',\n resourceContexts: depCtxs,\n workspaceContext: wsCtx ?? null\n };\n }\n\n // Legacy array shape (shouldn't happen for bulk)\n if (Array.isArray(raw)) {\n if (raw.length === 0) return this.createNormalResult(context);\n return this.createMultiResourceResult(raw[0], raw);\n }\n\n return this.createNormalResult(raw as InstallationContext);\n }\n}\n", "import type { InstallStrategy } from '../types.js';\nimport { GitInstallStrategy } from './git-strategy.js';\nimport { PathInstallStrategy } from './path-strategy.js';\nimport { RegistryInstallStrategy } from './registry-strategy.js';\nimport { BulkInstallStrategy } from './bulk-strategy.js';\n\nexport { BaseInstallStrategy } from './base.js';\nexport { GitInstallStrategy } from './git-strategy.js';\nexport { PathInstallStrategy } from './path-strategy.js';\nexport { RegistryInstallStrategy } from './registry-strategy.js';\nexport { BulkInstallStrategy } from './bulk-strategy.js';\n\n/**\n * Create all install strategies.\n */\nexport function createAllStrategies(): InstallStrategy[] {\n return [\n new BulkInstallStrategy(),\n new GitInstallStrategy(),\n new PathInstallStrategy(),\n new RegistryInstallStrategy(),\n ];\n}\n", "/**\n * Dependency graph builder.\n * Phase 1: Recursively discovers all dependencies and builds the graph without installing.\n */\n\nimport { dirname } from 'path';\nimport type {\n DependencyDeclaration,\n DependencyGraph,\n DependencyCycle,\n GraphMetadata,\n ResolvedSource,\n ResolutionDependencyNode,\n GraphBuilderOptions\n} from './types.js';\nimport { computeDependencyId } from './id-generator.js';\nimport { readManifestAtPath, extractDependencies, getDeclaredInDir } from './manifest-reader.js';\nimport { resolveDeclaredPath } from '../../../utils/path-resolution.js';\nimport { getLocalPackageYmlPath } from '../../../utils/paths.js';\nimport { parsePackageYml } from '../../../utils/package-yml.js';\nimport { ensureContentRoot } from './content-root-cache.js';\nimport { resolvePackageByName } from '../../package-name-resolution.js';\nimport { logger } from '../../../utils/logger.js';\n\nconst MAX_DEPTH_DEFAULT = 10;\n\n/**\n * Build ResolvedSource from a declaration (path and registry without loading).\n * For git, contentRoot is set later after load.\n * pathResolutionDir: directory to resolve path against (workspace root for root deps, manifest dir for nested).\n */\nfunction resolveSourceFromDeclaration(\n declaration: DependencyDeclaration,\n pathResolutionDir: string\n): ResolvedSource {\n if (declaration.url) {\n const [gitUrl, embeddedRef] = declaration.url.includes('#')\n ? declaration.url.split('#', 2)\n : [declaration.url, undefined];\n // IMPORTANT: Do not default to 'HEAD'. Passing 'HEAD' to `git clone --branch HEAD`\n // fails on many repos and differs from single-install behavior (which uses the default branch).\n const ref = embeddedRef || declaration.ref;\n const depName = String(declaration.name ?? '');\n let resourcePath = declaration.path ?? '';\n if (depName.startsWith('gh@')) {\n const tail = depName.slice(3);\n const parts = tail.split('/').filter(Boolean);\n if (parts.length > 2 && !resourcePath) {\n resourcePath = parts.slice(2).join('/');\n }\n }\n return {\n type: 'git',\n gitUrl,\n gitRef: ref,\n resourcePath: resourcePath || undefined,\n contentRoot: undefined\n };\n }\n if (declaration.path) {\n const { absolute } = resolveDeclaredPath(declaration.path, pathResolutionDir);\n return {\n type: 'path',\n absolutePath: absolute,\n contentRoot: absolute\n };\n }\n return {\n type: 'registry',\n packageName: declaration.name,\n resolvedVersion: declaration.version,\n contentRoot: undefined\n };\n}\n\nexport class DependencyGraphBuilder {\n private nodes: Map<string, ResolutionDependencyNode> = new Map();\n private visiting: Set<string> = new Set();\n private cycles: DependencyCycle[] = [];\n private warnings: string[] = [];\n private maxDepth: number;\n /** Directory used to resolve relative path deps at root level (depth 0). Set in build(). */\n private rootPathResolutionDir: string = '';\n\n constructor(\n private readonly workspaceRoot: string,\n private readonly options: GraphBuilderOptions\n ) {\n this.maxDepth = options.maxDepth ?? MAX_DEPTH_DEFAULT;\n }\n\n /**\n * Build complete dependency graph from root manifest.\n * Uses workspace .openpackage/openpackage.yml unless options.rootManifestPath is set.\n * When options.includeRoot is true, the root manifest package itself is included as\n * the first node in the graph (installed before its dependencies).\n */\n async build(): Promise<DependencyGraph> {\n const manifestPath = this.options.rootManifestPath ?? getLocalPackageYmlPath(this.workspaceRoot);\n this.rootPathResolutionDir = this.options.rootManifestPath\n ? dirname(manifestPath)\n : this.workspaceRoot;\n\n let manifest;\n try {\n manifest = await parsePackageYml(manifestPath);\n } catch (error) {\n logger.warn(`Could not read manifest at ${manifestPath}: ${error}`);\n return this.emptyGraph();\n }\n\n const roots: import('./types.js').DependencyId[] = [];\n let rootPackageNode: ResolutionDependencyNode | null = null;\n\n if (this.options.includeRoot && this.options.rootManifestPath) {\n rootPackageNode = await this.createRootPackageNode(manifest, manifestPath);\n if (rootPackageNode) {\n roots.push(rootPackageNode.id);\n }\n }\n\n const rootDeclarations = extractDependencies(\n manifest,\n manifestPath,\n 0,\n this.options.includeDev ?? true\n );\n\n for (const decl of rootDeclarations) {\n if (decl.depth >= this.maxDepth) {\n this.warnings.push(`Skipping dependency ${decl.name}: max depth ${this.maxDepth} reached`);\n continue;\n }\n const node = await this.discoverNode(decl);\n if (node) {\n if (rootPackageNode) {\n rootPackageNode.children.push(node.id);\n node.parents.push(rootPackageNode.id);\n } else {\n roots.push(node.id);\n }\n }\n }\n\n const installationOrder = this.computeInstallationOrder(roots);\n const maxDepth = this.computeMaxDepth();\n\n return {\n nodes: this.nodes,\n roots,\n installationOrder,\n cycles: this.cycles,\n metadata: {\n builtAt: new Date(),\n workspaceRoot: this.workspaceRoot,\n nodeCount: this.nodes.size,\n maxDepth,\n warnings: this.warnings\n }\n };\n }\n\n private async createRootPackageNode(\n manifest: import('../../../types/index.js').PackageYml,\n manifestPath: string\n ): Promise<ResolutionDependencyNode | null> {\n const contentRoot = dirname(manifestPath);\n const packageName = manifest.name || 'root';\n\n const id: import('./types.js').DependencyId = {\n key: `root:${contentRoot}`,\n displayName: packageName,\n sourceType: 'path'\n };\n\n const source: ResolvedSource = {\n type: 'path',\n absolutePath: contentRoot,\n contentRoot,\n manifestPath\n };\n\n const node: ResolutionDependencyNode = {\n id,\n declarations: [],\n source,\n children: [],\n parents: [],\n state: 'discovered'\n };\n\n this.nodes.set(id.key, node);\n return node;\n }\n\n private emptyGraph(): DependencyGraph {\n return {\n nodes: new Map(),\n roots: [],\n installationOrder: [],\n cycles: [],\n metadata: {\n builtAt: new Date(),\n workspaceRoot: this.workspaceRoot,\n nodeCount: 0,\n maxDepth: 0,\n warnings: this.warnings\n }\n };\n }\n\n private async discoverNode(\n declaration: DependencyDeclaration\n ): Promise<ResolutionDependencyNode | null> {\n const declaredInDir = getDeclaredInDir(declaration.declaredIn);\n const pathResolutionDir = declaration.depth === 0 ? this.rootPathResolutionDir : declaredInDir;\n\n // Resolve registry-only declarations to project/global path when package exists locally\n let effectiveDeclaration = declaration;\n if (!declaration.path && !declaration.url) {\n const resolved = await resolvePackageByName({\n cwd: this.workspaceRoot,\n packageName: declaration.name,\n checkCwd: false,\n searchWorkspace: true,\n searchGlobal: true,\n searchRegistry: false\n });\n if (resolved.found && resolved.path && (resolved.sourceType === 'workspace' || resolved.sourceType === 'global')) {\n effectiveDeclaration = { ...declaration, path: resolved.path };\n }\n }\n\n const id = computeDependencyId(effectiveDeclaration, pathResolutionDir);\n\n if (this.visiting.has(id.key)) {\n this.recordCycle(id);\n return null;\n }\n\n const existing = this.nodes.get(id.key);\n if (existing) {\n existing.declarations.push(declaration);\n return existing;\n }\n\n this.visiting.add(id.key);\n\n const source = resolveSourceFromDeclaration(effectiveDeclaration, pathResolutionDir);\n\n const node: ResolutionDependencyNode = {\n id,\n declarations: [declaration],\n source,\n children: [],\n parents: [],\n state: 'discovering'\n };\n this.nodes.set(id.key, node);\n\n let contentRoot: string | undefined = source.contentRoot ?? source.absolutePath;\n\n if (source.type === 'git' && !contentRoot) {\n const result = await ensureContentRoot(source, { skipCache: this.options.skipCache });\n if (result.isMarketplace) {\n this.warnings.push(`Dependency '${declaration.name}' is a marketplace; skipping nested deps`);\n } else if (result.contentRoot) {\n contentRoot = result.contentRoot;\n node.source.contentRoot = contentRoot;\n } else {\n logger.warn(`Failed to load git dependency '${declaration.name}'`);\n this.warnings.push(`Failed to load ${declaration.name}`);\n }\n }\n\n if (contentRoot && declaration.depth < this.maxDepth) {\n const manifest = await readManifestAtPath(contentRoot);\n if (manifest) {\n const childDeclarations = extractDependencies(\n manifest,\n contentRoot + '/openpackage.yml',\n declaration.depth + 1,\n false\n );\n for (const childDecl of childDeclarations) {\n if (childDecl.depth >= this.maxDepth) continue;\n const childNode = await this.discoverNode(childDecl);\n if (childNode) {\n node.children.push(childNode.id);\n childNode.parents.push(id);\n }\n }\n }\n }\n\n this.visiting.delete(id.key);\n node.state = 'discovered';\n return node;\n }\n\n private recordCycle(id: import('./types.js').DependencyId): void {\n const cycleNodes = Array.from(this.visiting).map((key) => {\n const n = this.nodes.get(key);\n return n?.id;\n }).filter(Boolean) as import('./types.js').DependencyId[];\n const startIdx = cycleNodes.findIndex((x) => x.key === id.key);\n const cycle = startIdx >= 0 ? cycleNodes.slice(startIdx).concat([id]) : [id];\n this.cycles.push({ nodes: cycle, resolution: 'skipped' });\n const cycleNames = cycle.map((c) => c.displayName).join(' \u2192 ');\n this.warnings.push(`Circular dependency detected: ${cycleNames}`);\n }\n\n private computeInstallationOrder(\n roots: import('./types.js').DependencyId[]\n ): import('./types.js').DependencyId[] {\n const order: import('./types.js').DependencyId[] = [];\n const visited = new Set<string>();\n\n const visit = (nodeId: import('./types.js').DependencyId) => {\n if (visited.has(nodeId.key)) return;\n visited.add(nodeId.key);\n const node = this.nodes.get(nodeId.key);\n if (!node) return;\n for (const childId of node.children) {\n visit(childId);\n }\n order.push(nodeId);\n };\n\n for (const root of roots) {\n visit(root);\n }\n return order;\n }\n\n private computeMaxDepth(): number {\n let max = 0;\n const depthMap = new Map<string, number>();\n\n const getDepth = (key: string): number => {\n const cached = depthMap.get(key);\n if (cached !== undefined) return cached;\n const node = this.nodes.get(key);\n if (!node) return 0;\n let d = 0;\n for (const childId of node.children) {\n d = Math.max(d, getDepth(childId.key) + 1);\n }\n depthMap.set(key, d);\n return d;\n };\n\n for (const key of this.nodes.keys()) {\n max = Math.max(max, getDepth(key));\n }\n return max;\n }\n}\n", "/**\n * Canonical ID computation for dependency graph nodes.\n * Used for deduplication and cycle detection.\n */\n\nimport { resolve, dirname } from 'path';\nimport type { DependencyId, DependencyDeclaration } from './types.js';\nimport { resolveDeclaredPath } from '../../../utils/path-resolution.js';\n\n/**\n * Normalize a git URL for stable canonical keys.\n * - Lowercase host and path\n * - Remove .git suffix\n * - Convert SSH to HTTPS form\n */\nexport function normalizeGitUrl(url: string): string {\n let normalized = url.trim();\n // SSH: git@github.com:user/repo.git -> https://github.com/user/repo\n if (normalized.startsWith('git@')) {\n const match = normalized.match(/^git@([^:]+):(.+)$/);\n if (match) {\n const [, host, pathPart] = match;\n normalized = `https://${host}/${pathPart}`;\n }\n }\n normalized = normalized.toLowerCase();\n if (normalized.endsWith('.git')) {\n normalized = normalized.slice(0, -4);\n }\n return normalized;\n}\n\n/**\n * Compute canonical dependency ID from a declaration.\n * declaredInDir should be the directory containing the manifest that declared this dependency\n * (e.g. dirname(declaration.declaredIn)).\n */\nexport function computeDependencyId(\n declaration: DependencyDeclaration,\n declaredInDir: string\n): DependencyId {\n const depName = String(declaration.name ?? '').trim();\n\n if (declaration.url) {\n // Git source: normalize URL + ref + path\n const [gitUrlRaw, embeddedRef] = declaration.url.includes('#')\n ? declaration.url.split('#', 2)\n : [declaration.url, undefined];\n // Keep a stable key for \"default branch\" installs without forcing an invalid ref.\n // Using 'HEAD' here is problematic because some code paths would attempt\n // `git clone --branch HEAD`, which is not a real branch on many repos.\n const ref = embeddedRef || declaration.ref || 'default';\n const normalizedUrl = normalizeGitUrl(gitUrlRaw);\n // Resource path from name (gh@owner/repo/path) or from path field\n let resourcePath = declaration.path ?? '';\n if (depName.startsWith('gh@')) {\n const tail = depName.slice(3);\n const parts = tail.split('/').filter(Boolean);\n if (parts.length > 2) {\n resourcePath = resourcePath || parts.slice(2).join('/');\n }\n }\n const key = `git:${normalizedUrl}#${ref}:${resourcePath}`;\n const displayName = depName || (resourcePath ? `git@${normalizedUrl}/${resourcePath}` : `git@${normalizedUrl}`);\n return { key, displayName, sourceType: 'git' };\n }\n\n if (declaration.path) {\n // Path source: resolve to absolute path\n const { absolute } = resolveDeclaredPath(declaration.path, declaredInDir);\n const key = `path:${absolute}`;\n const displayName = depName || declaration.path;\n return { key, displayName, sourceType: 'path' };\n }\n\n // Registry source: name + version constraint\n const version = (declaration.version ?? '*').trim();\n const key = `registry:${depName}:${version}`;\n return { key, displayName: depName, sourceType: 'registry' };\n}\n", "/**\n * Cross-source manifest reading for dependency discovery.\n * Reads openpackage.yml from path, and extracts dependency declarations.\n */\n\nimport { join, dirname } from 'path';\nimport type { PackageYml, PackageDependency } from '../../../types/index.js';\nimport { loadPackageConfig } from '../../package-context.js';\nimport { exists } from '../../../utils/fs.js';\nimport { parsePackageYml } from '../../../utils/package-yml.js';\nimport { DIR_PATTERNS, FILE_PATTERNS } from '../../../constants/index.js';\nimport type { DependencyDeclaration, ParsedManifest, ResolvedSource } from './types.js';\n\n/**\n * Resolve the path to the manifest file at a content root, if it exists.\n * Tries openpackage.yml at root, then .openpackage/openpackage.yml (workspace style).\n * Returns null if neither exists.\n */\nexport async function getManifestPathAtContentRoot(contentRoot: string): Promise<string | null> {\n const atRoot = join(contentRoot, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(atRoot)) return atRoot;\n const inOpenPackage = join(contentRoot, DIR_PATTERNS.OPENPACKAGE, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(inOpenPackage)) return inOpenPackage;\n return null;\n}\n\n/**\n * Read manifest from a content root directory.\n * Tries openpackage.yml at root, then .openpackage/openpackage.yml (workspace style).\n */\nexport async function readManifestAtPath(contentRoot: string): Promise<ParsedManifest | null> {\n const atRoot = join(contentRoot, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(atRoot)) {\n try {\n return await parsePackageYml(atRoot);\n } catch {\n return null;\n }\n }\n const inOpenPackage = join(contentRoot, DIR_PATTERNS.OPENPACKAGE, FILE_PATTERNS.OPENPACKAGE_YML);\n if (await exists(inOpenPackage)) {\n try {\n return await parsePackageYml(inOpenPackage);\n } catch {\n return null;\n }\n }\n return loadPackageConfig(contentRoot);\n}\n\n/**\n * Read manifest from a resolved source.\n * For path: reads from absolutePath. For git/registry: requires contentRoot (populated after load).\n */\nexport async function readManifestFromSource(\n source: ResolvedSource\n): Promise<ParsedManifest | null> {\n const contentRoot = source.contentRoot ?? source.absolutePath;\n if (!contentRoot) {\n return null;\n }\n return readManifestAtPath(contentRoot);\n}\n\n/**\n * Convert PackageDependency from manifest to DependencyDeclaration.\n */\nfunction toDependencyDeclaration(\n dep: PackageDependency & { base?: string },\n declaredIn: string,\n depth: number,\n isDev: boolean\n): DependencyDeclaration {\n const urlRaw = dep.url ?? (dep as { git?: string }).git;\n const [url, embeddedRef] =\n typeof urlRaw === 'string' && urlRaw.includes('#') ? urlRaw.split('#', 2) : [urlRaw, undefined];\n const ref = embeddedRef ?? (dep as { ref?: string }).ref;\n\n return {\n name: dep.name,\n version: dep.version,\n path: dep.path,\n url: typeof url === 'string' ? url : undefined,\n ref,\n base: dep.base,\n isDev,\n declaredIn,\n depth\n };\n}\n\n/**\n * Extract dependency declarations from a parsed manifest.\n * declaredIn: path to the manifest file that contains these dependencies.\n * depth: depth in the dependency tree (used when recursing).\n * includeDev: if true, include dev-dependencies (only at root level).\n */\nexport function extractDependencies(\n manifest: ParsedManifest,\n declaredIn: string,\n depth: number,\n includeDev: boolean\n): DependencyDeclaration[] {\n const out: DependencyDeclaration[] = [];\n\n const deps = manifest.dependencies ?? (manifest as { packages?: PackageDependency[] }).packages ?? [];\n for (const dep of deps) {\n if (!dep?.name) continue;\n out.push(toDependencyDeclaration(dep, declaredIn, depth, false));\n }\n\n if (includeDev && depth === 0) {\n const devDeps =\n manifest['dev-dependencies'] ??\n (manifest as { 'dev-packages'?: PackageDependency[] })['dev-packages'] ??\n [];\n for (const dep of devDeps) {\n if (!dep?.name) continue;\n out.push(toDependencyDeclaration(dep, declaredIn, depth, true));\n }\n }\n\n return out;\n}\n\n/**\n * Get the directory containing the manifest file.\n * Used as base for resolving relative path dependencies.\n */\nexport function getDeclaredInDir(manifestPath: string): string {\n return dirname(manifestPath);\n}\n", "/**\n * Shared cache for content roots during resolution.\n * Ensures graph-builder and package-loader don't duplicate git loads.\n */\n\nimport { join } from 'path';\nimport { loadPackageFromGit, type GitPackageLoadResult } from '../git-package-loader.js';\nimport type { ResolvedSource } from './types.js';\n\nexport interface ContentRootResult {\n contentRoot: string | undefined;\n isMarketplace: boolean;\n repoPath?: string;\n commitSha?: string;\n}\n\nconst contentRootCache = new Map<string, ContentRootResult>();\n\n/**\n * Generate a cache key for a git source.\n */\nfunction getCacheKey(source: ResolvedSource): string {\n if (source.type !== 'git') {\n throw new Error('getCacheKey only supports git sources');\n }\n return `${source.gitUrl}#${source.gitRef ?? 'default'}#${source.resourcePath ?? ''}`;\n}\n\nexport interface EnsureContentRootOptions {\n skipCache?: boolean;\n}\n\n/**\n * Ensure content root is loaded for a git source, using cache.\n * Returns undefined contentRoot if load fails.\n */\nexport async function ensureContentRoot(\n source: ResolvedSource,\n options: EnsureContentRootOptions = {}\n): Promise<ContentRootResult> {\n if (source.type !== 'git') {\n return {\n contentRoot: source.contentRoot ?? source.absolutePath,\n isMarketplace: false\n };\n }\n\n const key = getCacheKey(source);\n \n // Skip in-memory cache if skipCache is set (forces fresh git fetch)\n if (!options.skipCache) {\n const cached = contentRootCache.get(key);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const result = await loadPackageFromGit({\n url: source.gitUrl!,\n ref: source.gitRef,\n path: undefined,\n resourcePath: source.resourcePath,\n skipCache: options.skipCache\n });\n\n const contentRoot = source.resourcePath\n ? join(result.sourcePath, source.resourcePath)\n : result.sourcePath;\n\n const cacheResult: ContentRootResult = {\n contentRoot: result.isMarketplace ? undefined : contentRoot,\n isMarketplace: result.isMarketplace,\n repoPath: result.repoPath,\n commitSha: result.commitSha\n };\n\n contentRootCache.set(key, cacheResult);\n return cacheResult;\n } catch {\n const failResult: ContentRootResult = {\n contentRoot: undefined,\n isMarketplace: false\n };\n contentRootCache.set(key, failResult);\n return failResult;\n }\n}\n\n/**\n * Check if a git source has a cached content root.\n */\nexport function hasCachedContentRoot(source: ResolvedSource): boolean {\n if (source.type !== 'git') return false;\n return contentRootCache.has(getCacheKey(source));\n}\n\n/**\n * Get cached content root without loading.\n */\nexport function getCachedContentRoot(source: ResolvedSource): ContentRootResult | undefined {\n if (source.type !== 'git') return undefined;\n return contentRootCache.get(getCacheKey(source));\n}\n\n/**\n * Clear the content root cache (for tests).\n */\nexport function clearContentRootCache(): void {\n contentRootCache.clear();\n}\n", "/**\n * Package loader for dependency graph nodes.\n * Phase 2: Loads package content using existing source loaders.\n */\n\nimport type { InstallOptions, ExecutionContext } from '../../../types/index.js';\nimport type { PackageSource } from '../unified/context.js';\nimport type {\n DependencyGraph,\n ResolutionDependencyNode,\n ResolvedSource,\n LoadedPackageData,\n PackageLoaderOptions\n} from './types.js';\nimport { getLoaderForSource } from '../sources/loader-factory.js';\nimport type { LoadedPackage } from '../sources/base.js';\nimport { logger } from '../../../utils/logger.js';\nimport { getCachedContentRoot } from './content-root-cache.js';\n\nconst loadCache = new Map<string, LoadedPackageData>();\n\n/**\n * Convert ResolvedSource + declaration manifestBase to PackageSource for loaders.\n */\nfunction toPackageSource(\n node: ResolutionDependencyNode,\n cwd: string\n): PackageSource {\n const decl = node.declarations[0];\n const s = node.source;\n\n if (s.type === 'git') {\n return {\n type: 'git',\n packageName: decl?.name ?? node.id.displayName,\n gitUrl: s.gitUrl,\n gitRef: s.gitRef,\n gitPath: s.resourcePath ? undefined : decl?.path,\n resourcePath: s.resourcePath,\n manifestBase: decl?.base,\n contentRoot: s.contentRoot\n };\n }\n\n if (s.type === 'path') {\n return {\n type: 'path',\n packageName: decl?.name ?? node.id.displayName,\n localPath: s.absolutePath ?? s.contentRoot ?? '',\n sourceType: 'directory',\n manifestBase: decl?.base,\n contentRoot: s.contentRoot\n };\n }\n\n return {\n type: 'registry',\n packageName: s.packageName ?? decl?.name ?? node.id.displayName,\n version: s.resolvedVersion ?? decl?.version,\n manifestBase: decl?.base\n };\n}\n\n/**\n * Map loader result to LoadedPackageData.\n */\nfunction toLoadedPackageData(loaded: LoadedPackage): LoadedPackageData {\n const baseDetection = loaded.sourceMetadata?.baseDetection;\n return {\n name: loaded.packageName,\n version: loaded.version,\n contentRoot: loaded.contentRoot,\n repoRoot: loaded.sourceMetadata?.repoPath,\n metadata: loaded.metadata ?? { name: loaded.packageName, version: loaded.version },\n manifest: loaded.metadata ?? { name: loaded.packageName, version: loaded.version },\n baseDetection: baseDetection\n ? {\n base: baseDetection.base,\n relative: baseDetection.baseRelative,\n source: baseDetection.matchType,\n pattern: baseDetection.matchedPattern,\n matchType: baseDetection.matchType\n }\n : undefined,\n formatDetection: loaded.pluginMetadata?.format\n ? { format: loaded.pluginMetadata.format }\n : undefined\n };\n}\n\n/**\n * Compute depth of a node (distance from roots).\n */\nfunction getNodeDepth(node: ResolutionDependencyNode, graph: DependencyGraph): number {\n if (node.parents.length === 0) return 0;\n let depth = 0;\n for (const parentId of node.parents) {\n const parent = graph.nodes.get(parentId.key);\n if (parent) {\n depth = Math.max(depth, getNodeDepth(parent, graph) + 1);\n }\n }\n return depth;\n}\n\n/**\n * Group nodes by depth for parallel loading.\n */\nfunction groupByDepth(graph: DependencyGraph): Map<number, ResolutionDependencyNode[]> {\n const groups = new Map<number, ResolutionDependencyNode[]>();\n for (const node of graph.nodes.values()) {\n const depth = getNodeDepth(node, graph);\n if (!groups.has(depth)) {\n groups.set(depth, []);\n }\n groups.get(depth)!.push(node);\n }\n return new Map([...groups.entries()].sort((a, b) => a[0] - b[0]));\n}\n\nexport class PackageLoader {\n constructor(\n private readonly execContext: ExecutionContext,\n private readonly options: PackageLoaderOptions\n ) {}\n\n /**\n * Load all packages in the graph.\n * Path and git nodes are loaded via source loaders; registry nodes are left for the pipeline.\n */\n async loadAll(graph: DependencyGraph): Promise<void> {\n const cacheEnabled = this.options.cacheEnabled !== false;\n const parallel = this.options.parallel !== false;\n const installOptions: InstallOptions = this.options.installOptions ?? {};\n\n const byDepth = groupByDepth(graph);\n\n for (const [, nodes] of byDepth) {\n const loadables = nodes.filter(\n (n) => (n.source.type === 'path' || n.source.type === 'git') && !n.loaded\n );\n\n if (parallel && loadables.length > 1) {\n await Promise.all(\n loadables.map((node) => this.loadNode(node, graph, installOptions, cacheEnabled))\n );\n } else {\n for (const node of loadables) {\n await this.loadNode(node, graph, installOptions, cacheEnabled);\n }\n }\n }\n }\n\n private async loadNode(\n node: ResolutionDependencyNode,\n graph: DependencyGraph,\n installOptions: InstallOptions,\n cacheEnabled: boolean\n ): Promise<void> {\n if (node.loaded) return;\n\n if (cacheEnabled && loadCache.has(node.id.key)) {\n node.loaded = loadCache.get(node.id.key);\n node.state = 'loaded';\n return;\n }\n\n if (node.source.type === 'registry') {\n node.state = 'discovered';\n return;\n }\n\n // Use content root from graph-builder phase if available\n if (node.source.type === 'git' && !node.source.contentRoot) {\n const cached = getCachedContentRoot(node.source);\n if (cached?.contentRoot) {\n node.source.contentRoot = cached.contentRoot;\n }\n }\n\n node.state = 'loading';\n\n try {\n const packageSource = toPackageSource(node, this.execContext.targetDir);\n const loader = getLoaderForSource(packageSource);\n const loaded = await loader.load(packageSource, installOptions, this.execContext);\n\n if (!loaded.metadata && loaded.pluginMetadata?.pluginType === 'marketplace') {\n logger.warn(`Skipping marketplace node ${node.id.displayName} in resolution loader`);\n node.state = 'discovered';\n return;\n }\n\n const data = toLoadedPackageData(loaded);\n node.loaded = data;\n node.source.contentRoot = data.contentRoot;\n node.state = 'loaded';\n\n if (cacheEnabled) {\n loadCache.set(node.id.key, data);\n }\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n logger.warn(`Failed to load ${node.id.displayName}: ${errMsg}`);\n node.state = 'failed';\n // Do not rethrow: allow other packages to load; planner will skip failed nodes\n }\n }\n}\n\n/**\n * Clear the global load cache (e.g. for tests).\n */\nexport function clearLoadCache(): void {\n loadCache.clear();\n}\n", "/**\n * Installation planner: builds InstallationContexts from loaded graph nodes.\n * Phase 3: Creates installation plan in topological order.\n */\n\nimport type { PackageSource } from '../unified/context.js';\nimport type { ExecutionContext } from '../../../types/index.js';\nimport type { ResolvedPackage } from '../../dependency-resolver/types.js';\nimport type { InstallationContext } from '../unified/context.js';\nimport type {\n DependencyGraph,\n ResolutionDependencyNode,\n InstallationPlan,\n SkippedPackage,\n InstallationPlannerOptions\n} from './types.js';\nimport { getInstalledPackageVersion } from '../../openpackage.js';\nimport { resolveResourceScoping } from '../preprocessing/base-resolver.js';\n\n/**\n * Map resolution source type to ResolvedPackage source.\n */\nfunction mapSourceType(\n sourceType: 'registry' | 'path' | 'git'\n): 'local' | 'remote' | 'path' | 'git' {\n if (sourceType === 'registry') return 'local';\n return sourceType;\n}\n\n/**\n * Build PackageSource from a resolution node.\n */\nfunction buildPackageSource(node: ResolutionDependencyNode): PackageSource {\n const decl = node.declarations[0];\n const s = node.source;\n\n if (s.type === 'git') {\n return {\n type: 'git',\n packageName: node.loaded?.name ?? decl?.name ?? node.id.displayName,\n gitUrl: s.gitUrl,\n gitRef: s.gitRef,\n gitPath: s.resourcePath ? undefined : decl?.path,\n resourcePath: s.resourcePath,\n manifestBase: decl?.base,\n contentRoot: s.contentRoot ?? node.loaded?.contentRoot\n };\n }\n\n if (s.type === 'path') {\n return {\n type: 'path',\n packageName: node.loaded?.name ?? decl?.name ?? node.id.displayName,\n localPath: s.absolutePath ?? s.contentRoot ?? '',\n sourceType: 'directory',\n manifestBase: decl?.base,\n contentRoot: s.contentRoot ?? node.loaded?.contentRoot\n };\n }\n\n return {\n type: 'registry',\n packageName: s.packageName ?? decl?.name ?? node.id.displayName,\n version: s.resolvedVersion ?? decl?.version,\n manifestBase: decl?.base\n };\n}\n\n/**\n * Build ResolvedPackage (root entry) from loaded data.\n */\nfunction buildResolvedPackage(node: ResolutionDependencyNode): ResolvedPackage {\n const loaded = node.loaded!;\n return {\n name: loaded.name,\n version: loaded.version,\n pkg: {\n metadata: loaded.metadata,\n files: [],\n _format: loaded.formatDetection?.format\n },\n isRoot: true,\n source: mapSourceType(node.id.sourceType),\n contentRoot: loaded.contentRoot\n };\n}\n\nexport class InstallationPlanner {\n constructor(\n private readonly execContext: ExecutionContext,\n private readonly options: InstallationPlannerOptions\n ) {}\n\n /**\n * Create installation plan from loaded graph.\n * Nodes without .loaded (e.g. registry not pre-loaded) get a minimal context for the pipeline to load/resolve.\n */\n async createPlan(graph: DependencyGraph): Promise<InstallationPlan> {\n const contexts: InstallationContext[] = [];\n const skipped: SkippedPackage[] = [];\n const force = this.options.force ?? false;\n\n for (const id of graph.installationOrder) {\n const node = graph.nodes.get(id.key);\n if (!node) continue;\n\n if (node.state === 'failed') {\n skipped.push({ id: node.id, reason: 'failed' });\n continue;\n }\n\n if (!node.loaded) {\n skipped.push({ id: node.id, reason: 'not-loaded' });\n continue;\n }\n\n const alreadyInstalled = await getInstalledPackageVersion(node.loaded.name, this.execContext.targetDir);\n if (alreadyInstalled && !force) {\n skipped.push({ id: node.id, reason: 'already-installed' });\n continue;\n }\n\n const context = await this.buildContext(node);\n contexts.push(context);\n node.installContext = context;\n }\n\n return {\n contexts,\n skipped,\n graph,\n estimatedOperations: contexts.length\n };\n }\n\n /**\n * Build InstallationContext for the unified pipeline.\n * Caller must ensure node.loaded is set. Pre-populates source and resolvedPackages so pipeline skips load and resolve.\n */\n async buildContext(node: ResolutionDependencyNode): Promise<InstallationContext> {\n const source = buildPackageSource(node);\n const platforms = this.options.platforms ?? [];\n const installOptions = this.options.installOptions ?? {};\n const resolvedPackage = buildResolvedPackage(node);\n const ctx: InstallationContext = {\n execution: this.execContext,\n targetDir: this.execContext.targetDir,\n source,\n mode: 'install',\n options: installOptions as InstallationContext['options'],\n platforms,\n resolvedPackages: [resolvedPackage],\n warnings: [],\n errors: [],\n detectedBase: node.loaded!.baseDetection?.base,\n baseRelative: node.loaded!.baseDetection?.relative,\n baseSource: node.loaded!.baseDetection?.source as InstallationContext['baseSource'],\n matchedPattern: node.loaded!.baseDetection?.pattern\n };\n\n // Phase: resource scoping for recursive installs.\n // In recursive mode we pre-populate ctx.resolvedPackages/contentRoot, so loadPackagePhase is skipped,\n // and computePathScoping() would never run. If a concrete resourcePath is present, scope matchedPattern here.\n const resourcePath = (ctx.source as any).resourcePath as string | undefined;\n const repoRoot = node.loaded?.repoRoot;\n const baseAbs = ctx.detectedBase ?? ctx.source.contentRoot;\n if (resourcePath && repoRoot && baseAbs) {\n try {\n const result = await resolveResourceScoping(repoRoot, baseAbs, resourcePath);\n if (result) {\n // Phase 4: If we have a broad pattern from base detection (e.g. \"skills/**/*\"),\n // but we are installing a specific resource (e.g. \"skills/react-best-practices\"),\n // we must narrow the pattern to ensure only the requested resource is installed.\n if (!ctx.matchedPattern || (ctx.matchedPattern.includes('**') && result.pattern.length > ctx.matchedPattern.replace('/**', '').length)) {\n ctx.matchedPattern = result.pattern;\n }\n }\n } catch {\n // best-effort only\n }\n }\n\n return ctx;\n }\n}\n", "/**\n * Semver constraint resolution for registry packages in the dependency graph.\n * Finds compatible versions across multiple declarations with different constraints.\n */\n\nimport semver from 'semver';\nimport type { DependencyGraph, ResolutionDependencyNode } from './types.js';\n\nexport interface VersionSolution {\n resolved: Map<string, string>;\n conflicts: VersionConflict[];\n}\n\nexport interface VersionConflict {\n packageName: string;\n ranges: string[];\n requestedBy: string[];\n}\n\nexport interface SolverOptions {\n force?: boolean;\n allowPrerelease?: boolean;\n onConflict?: (conflict: VersionConflict, availableVersions: string[]) => Promise<string | null>;\n}\n\ninterface PackageConstraint {\n range: string;\n requestedBy: string;\n}\n\n/**\n * Solve version constraints for all registry packages in the dependency graph.\n * Groups nodes by package name, finds intersecting semver ranges, and picks\n * the highest satisfying version.\n */\nexport async function solveVersions(\n graph: DependencyGraph,\n options: SolverOptions = {}\n): Promise<VersionSolution> {\n const { force = false, allowPrerelease = false, onConflict } = options;\n const resolved = new Map<string, string>();\n const conflicts: VersionConflict[] = [];\n\n const registryPackages = groupRegistryNodesByPackage(graph);\n\n for (const [packageName, nodes] of registryPackages) {\n const constraints = extractConstraints(nodes);\n \n if (constraints.length === 0) {\n continue;\n }\n\n const ranges = constraints.map(c => c.range);\n const requestedBy = constraints.map(c => c.requestedBy);\n const availableVersions = extractAvailableVersions(nodes);\n\n const satisfyingVersion = findHighestSatisfyingVersion(\n ranges,\n availableVersions,\n allowPrerelease\n );\n\n if (satisfyingVersion) {\n resolved.set(packageName, satisfyingVersion);\n } else if (force && availableVersions.length > 0) {\n const highest = semver.maxSatisfying(availableVersions, '*', { includePrerelease: allowPrerelease });\n if (highest) {\n resolved.set(packageName, highest);\n }\n conflicts.push({ packageName, ranges, requestedBy });\n } else {\n const conflict: VersionConflict = { packageName, ranges, requestedBy };\n \n if (onConflict && availableVersions.length > 0) {\n const chosenVersion = await onConflict(conflict, availableVersions);\n if (chosenVersion) {\n resolved.set(packageName, chosenVersion);\n continue;\n }\n }\n \n conflicts.push(conflict);\n }\n }\n\n return { resolved, conflicts };\n}\n\nfunction groupRegistryNodesByPackage(\n graph: DependencyGraph\n): Map<string, ResolutionDependencyNode[]> {\n const grouped = new Map<string, ResolutionDependencyNode[]>();\n\n for (const node of graph.nodes.values()) {\n if (node.source.type !== 'registry' || !node.source.packageName) {\n continue;\n }\n\n const packageName = node.source.packageName;\n const existing = grouped.get(packageName) || [];\n existing.push(node);\n grouped.set(packageName, existing);\n }\n\n return grouped;\n}\n\nfunction extractConstraints(nodes: ResolutionDependencyNode[]): PackageConstraint[] {\n const constraints: PackageConstraint[] = [];\n\n for (const node of nodes) {\n for (const decl of node.declarations) {\n const range = normalizeVersionRange(decl.version);\n if (range) {\n constraints.push({\n range,\n requestedBy: decl.declaredIn\n });\n }\n }\n }\n\n return constraints;\n}\n\nfunction normalizeVersionRange(version?: string): string | null {\n if (!version) return null;\n \n const normalized = version.trim().toLowerCase();\n if (normalized === '*' || normalized === 'latest' || normalized === '') {\n return null;\n }\n \n return version.trim();\n}\n\nfunction extractAvailableVersions(nodes: ResolutionDependencyNode[]): string[] {\n const versions = new Set<string>();\n\n for (const node of nodes) {\n if (node.source.resolvedVersion) {\n versions.add(node.source.resolvedVersion);\n }\n if (node.loaded?.version) {\n versions.add(node.loaded.version);\n }\n }\n\n return Array.from(versions).filter(v => semver.valid(v));\n}\n\nfunction findHighestSatisfyingVersion(\n ranges: string[],\n availableVersions: string[],\n allowPrerelease: boolean\n): string | null {\n if (availableVersions.length === 0) {\n return null;\n }\n\n const satisfyingVersions = availableVersions.filter(version => {\n return ranges.every(range => {\n try {\n return semver.satisfies(version, range, { includePrerelease: allowPrerelease });\n } catch {\n return false;\n }\n });\n });\n\n if (satisfyingVersions.length === 0) {\n return null;\n }\n\n return semver.maxSatisfying(satisfyingVersions, '*', { includePrerelease: allowPrerelease });\n}\n\n/**\n * Check if a specific version satisfies all given constraints.\n */\nexport function versionSatisfiesAll(\n version: string,\n ranges: string[],\n allowPrerelease = false\n): boolean {\n return ranges.every(range => {\n try {\n return semver.satisfies(version, range, { includePrerelease: allowPrerelease });\n } catch {\n return false;\n }\n });\n}\n\n/**\n * Find the intersection range of multiple semver ranges (as a displayable string).\n * Returns null if ranges are incompatible.\n */\nexport function intersectRanges(ranges: string[]): string | null {\n if (ranges.length === 0) return null;\n if (ranges.length === 1) return ranges[0];\n\n const validRanges = ranges.filter(r => {\n try {\n return semver.validRange(r) !== null;\n } catch {\n return false;\n }\n });\n\n if (validRanges.length === 0) return null;\n\n return validRanges.join(' ');\n}\n\n/**\n * Create an interactive conflict handler that uses promptVersionSelection.\n * Returns a handler function suitable for the onConflict option.\n * \n * @param promptVersionSelection - The prompt function to use for version selection\n * @returns An onConflict handler function\n */\nexport function createInteractiveConflictHandler(\n promptVersionSelection: (packageName: string, versions: string[], action?: string) => Promise<string | null>\n): (conflict: VersionConflict, availableVersions: string[]) => Promise<string | null> {\n return async (conflict: VersionConflict, availableVersions: string[]): Promise<string | null> => {\n const sortedVersions = [...availableVersions].sort((a, b) => semver.rcompare(a, b));\n const rangesStr = conflict.ranges.join(', ');\n const action = `(requested ranges: ${rangesStr})`;\n \n return promptVersionSelection(conflict.packageName, sortedVersions, action);\n };\n}\n", "/**\n * Dependency resolution executor.\n * Orchestrates discovery, loading, planning, and execution.\n */\n\nimport type { CommandResult, ExecutionContext } from '../../../types/index.js';\nimport { runUnifiedInstallPipeline } from '../unified/pipeline.js';\nimport { DependencyGraphBuilder } from './graph-builder.js';\nimport { PackageLoader } from './package-loader.js';\nimport { InstallationPlanner } from './installation-planner.js';\nimport { solveVersions, createInteractiveConflictHandler, type VersionSolution, type SolverOptions } from './version-solver.js';\nimport type { PromptPort } from '../../ports/prompt.js';\nimport { resolvePrompt } from '../../ports/resolve.js';\nimport { PromptTier } from '../../../core/interaction-policy.js';\nimport type {\n DependencyGraph,\n ExecutorOptions,\n ExecutionResult,\n PackageResult,\n ExecutionSummary\n} from './types.js';\nimport { logger } from '../../../utils/logger.js';\n\nexport class DependencyResolutionExecutor {\n private graphBuilder: DependencyGraphBuilder;\n private packageLoader: PackageLoader;\n private planner: InstallationPlanner;\n\n constructor(\n private readonly execContext: ExecutionContext,\n private readonly options: ExecutorOptions\n ) {\n this.graphBuilder = new DependencyGraphBuilder(execContext.targetDir, options.graphOptions);\n this.packageLoader = new PackageLoader(execContext, options.loaderOptions);\n this.planner = new InstallationPlanner(execContext, options.plannerOptions);\n }\n\n /**\n * Execute full dependency resolution and installation.\n */\n async execute(): Promise<ExecutionResult> {\n const results: PackageResult[] = [];\n let graph: DependencyGraph | undefined;\n let versionSolution: VersionSolution | undefined;\n\n try {\n logger.info('Discovering dependencies');\n graph = await this.graphBuilder.build();\n\n if (graph.cycles.length > 0) {\n for (const cycle of graph.cycles) {\n const names = cycle.nodes.map((n) => n.displayName).join(' -> ');\n logger.warn(`Circular dependency: ${names}`);\n }\n }\n\n logger.info(`Found ${graph.metadata.nodeCount} packages (max depth: ${graph.metadata.maxDepth})`);\n\n const force = this.options.plannerOptions?.installOptions?.force ?? false;\n \n const solverOptions: SolverOptions = { force };\n if (!force && this.execContext.interactionPolicy?.canPrompt(PromptTier.ConflictResolution)) {\n const p = this.execContext.prompt ?? resolvePrompt();\n const versionSelector = async (packageName: string, versions: string[], action?: string): Promise<string | null> => {\n const choices = versions.map(v => ({ title: v, value: v }));\n return p.select<string>(\n `Select version of '${packageName}' ${action ?? ''}:`,\n choices,\n 'Use arrow keys to navigate, Enter to select'\n );\n };\n solverOptions.onConflict = createInteractiveConflictHandler(versionSelector);\n }\n \n versionSolution = await solveVersions(graph, solverOptions);\n\n if (versionSolution.conflicts.length > 0 && !force) {\n for (const conflict of versionSolution.conflicts) {\n const ranges = conflict.ranges.join(', ');\n const requesters = conflict.requestedBy.join(', ');\n logger.error(`Version conflict for ${conflict.packageName}: ranges [${ranges}] requested by [${requesters}]`);\n }\n return {\n success: false,\n error: `Version conflicts detected for: ${versionSolution.conflicts.map(c => c.packageName).join(', ')}`,\n results: [],\n graph,\n warnings: graph.metadata.warnings,\n versionSolution\n };\n }\n\n for (const [packageName, resolvedVersion] of versionSolution.resolved) {\n for (const node of graph.nodes.values()) {\n if (node.source.type === 'registry' && node.source.packageName === packageName) {\n node.source.resolvedVersion = resolvedVersion;\n }\n }\n }\n\n logger.info('Loading packages');\n await this.packageLoader.loadAll(graph);\n\n const loadedCount = this.countLoadedNodes(graph);\n logger.info(`Loaded ${loadedCount}/${graph.metadata.nodeCount} packages`);\n\n logger.info('Planning installation');\n const plan = await this.planner.createPlan(graph);\n\n logger.info(`${plan.contexts.length} packages to install, ${plan.skipped.length} skipped`);\n\n if (this.options.dryRun) {\n return this.createDryRunResult(plan, graph, versionSolution);\n }\n\n logger.info('Installing packages');\n for (const ctx of plan.contexts) {\n const node = this.findNodeForContext(ctx, graph);\n if (!node) continue;\n\n try {\n node.state = 'installing';\n const result: CommandResult = await runUnifiedInstallPipeline(ctx);\n\n if (result.success) {\n node.state = 'installed';\n results.push({\n id: node.id,\n success: true,\n data: result.data\n });\n } else {\n node.state = 'failed';\n results.push({\n id: node.id,\n success: false,\n error: result.error\n });\n if (this.options.failFast) {\n return this.createFinalResult(results, plan, graph, versionSolution);\n }\n }\n } catch (error) {\n node.state = 'failed';\n const errMsg = error instanceof Error ? error.message : String(error);\n results.push({ id: node.id, success: false, error: errMsg });\n if (this.options.failFast) {\n return this.createFinalResult(results, plan, graph, versionSolution);\n }\n }\n }\n\n return this.createFinalResult(results, plan, graph, versionSolution);\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: errMsg,\n results,\n graph,\n warnings: graph?.metadata.warnings,\n versionSolution\n };\n }\n }\n\n private countLoadedNodes(graph: DependencyGraph): number {\n let n = 0;\n for (const node of graph.nodes.values()) {\n if (node.loaded) n++;\n }\n return n;\n }\n\n private findNodeForContext(\n ctx: { source: { packageName: string; contentRoot?: string } },\n graph: DependencyGraph\n ): import('./types.js').ResolutionDependencyNode | undefined {\n for (const node of graph.nodes.values()) {\n if (node.installContext === ctx) return node;\n if (\n node.loaded &&\n node.loaded.name === ctx.source.packageName &&\n node.loaded.contentRoot === ctx.source.contentRoot\n ) {\n return node;\n }\n }\n return undefined;\n }\n\n private createDryRunResult(\n plan: import('./types.js').InstallationPlan,\n graph: DependencyGraph,\n versionSolution?: VersionSolution\n ): ExecutionResult {\n return {\n success: true,\n results: [],\n summary: {\n total: graph.metadata.nodeCount,\n installed: 0,\n failed: 0,\n skipped: plan.skipped.length\n },\n graph,\n warnings: graph.metadata.warnings,\n versionSolution\n };\n }\n\n private createFinalResult(\n results: PackageResult[],\n plan: import('./types.js').InstallationPlan,\n graph: DependencyGraph,\n versionSolution?: VersionSolution\n ): ExecutionResult {\n const installed = results.filter((r) => r.success).length;\n const failed = results.filter((r) => !r.success).length;\n const summary: ExecutionSummary = {\n total: graph.metadata.nodeCount,\n installed,\n failed,\n skipped: plan.skipped.length\n };\n return {\n success: failed === 0,\n results,\n summary,\n graph,\n error: failed > 0 ? `${failed} packages failed to install` : undefined,\n warnings: graph.metadata.warnings,\n versionSolution\n };\n }\n}\n", "/**\n * List Handler Module\n * \n * Handles --interactive option integration with install orchestrator\n */\n\nimport { resolve } from 'path';\nimport { logger } from '../../utils/logger.js';\nimport { resolveOutput, resolvePrompt } from '../ports/resolve.js';\nimport { PromptTier } from '../../core/interaction-policy.js';\nimport { discoverResources } from './resource-discoverer.js';\nimport { promptResourceSelection, displaySelectionSummary } from './resource-selection-menu.js';\nimport { buildResourceInstallContexts } from './unified/context-builders.js';\nimport { runMultiContextPipeline } from './unified/multi-context-pipeline.js';\nimport { getLoaderForSource } from './sources/loader-factory.js';\nimport { applyBaseDetection } from './preprocessing/base-resolver.js';\nimport type { InstallationContext } from './unified/context.js';\nimport type { NormalizedInstallOptions } from './orchestrator/types.js';\nimport type { ExecutionContext, CommandResult } from '../../types/index.js';\nimport type { ResourceInstallationSpec } from './convenience-matchers.js';\nimport type { SelectedResource } from './resource-types.js';\n\n/**\n * Handle interactive resource selection (--interactive option)\n * \n * @param context - Installation context\n * @param options - Normalized install options\n * @param execContext - Execution context\n * @returns Command result\n */\nexport async function handleListSelection(\n context: InstallationContext,\n options: NormalizedInstallOptions,\n execContext: ExecutionContext\n): Promise<CommandResult> {\n logger.info('Handling interactive resource selection', {\n packageName: context.source.packageName\n });\n \n const out = resolveOutput(execContext);\n \n // Load source to get content root and base detection\n const loader = getLoaderForSource(context.source);\n const loaded = await loader.load(context.source, options, execContext);\n \n // Update context with loaded data\n context.source.packageName = loaded.packageName;\n context.source.version = loaded.version;\n context.source.contentRoot = loaded.contentRoot;\n context.source.pluginMetadata = loaded.pluginMetadata;\n \n // Apply base detection\n if (loaded.sourceMetadata?.baseDetection) {\n applyBaseDetection(context, loaded);\n }\n \n // Determine base path and repo root\n const basePath = context.detectedBase || loaded.contentRoot || execContext.targetDir;\n const repoRoot = loaded.sourceMetadata?.repoPath || loaded.contentRoot || basePath;\n \n logger.debug('Resource discovery paths', {\n basePath,\n repoRoot,\n detectedBase: context.detectedBase\n });\n \n // Discover all resources with spinner\n const s = out.spinner();\n s.start('Discovering resources');\n \n const discovery = await discoverResources(basePath, repoRoot);\n \n if (discovery.total === 0) {\n s.stop('No resources found');\n } else {\n s.stop(`Found ${discovery.total} resource${discovery.total === 1 ? '' : 's'}`);\n }\n \n // Check if any resources found\n if (discovery.total === 0) {\n out.warn('No installable resources found in this package');\n return {\n success: true,\n data: { installed: 0, skipped: 0 }\n };\n }\n \n // Interactive or non-interactive selection\n let selected: SelectedResource[];\n \n const policy = execContext.interactionPolicy;\n if (!policy?.canPrompt(PromptTier.OptionalMenu)) {\n throw new Error('Interactive resource selection requires a TTY. Use --agents, --skills, --rules, or --commands to specify resources directly.');\n }\n\n selected = await promptResourceSelection(\n discovery,\n context.source.packageName,\n context.source.version,\n resolveOutput(execContext),\n resolvePrompt(execContext)\n );\n \n if (selected.length === 0) {\n return {\n success: true,\n data: { installed: 0, skipped: 0 }\n };\n }\n \n displaySelectionSummary(selected);\n \n // Convert selected resources to ResourceInstallationSpec format\n const resourceSpecs: ResourceInstallationSpec[] = selected.map(s => ({\n name: s.displayName,\n resourceType: s.resourceType as 'agent' | 'skill' | 'command' | 'rule',\n resourcePath: s.resourcePath,\n basePath: resolve(basePath),\n resourceKind: s.installKind,\n matchedBy: 'filename' as const,\n resourceVersion: s.version\n }));\n \n // Build resource contexts for installation\n const resourceContexts = buildResourceInstallContexts(\n context,\n resourceSpecs,\n repoRoot\n ).map(rc => {\n // Ensure path-based loader can resolve repo-relative resourcePath\n if (rc.source.type === 'path') {\n rc.source.localPath = repoRoot;\n }\n return rc;\n });\n \n // Run multi-context pipeline\n const result = await runMultiContextPipeline(resourceContexts);\n \n return {\n success: result.success,\n error: result.error,\n data: {\n installed: result.data?.installed || 0,\n skipped: result.data?.skipped || 0\n }\n };\n}\n", "/**\n * Subsumption Resolver\n * \n * Detects and resolves overlapping installations between resource-scoped\n * installs (e.g., gh@user/repo/agents/agent1) and full-package installs\n * (e.g., gh@user/repo) from the same source.\n * \n * Two scenarios:\n * 1. Resource installed first, then full package -> auto-replace resource entry\n * 2. Full package installed first, then resource -> skip (already covered)\n */\n\nimport type { PackageSource, InstallationContext } from '../unified/context.js';\nimport type { WorkspaceIndex, WorkspaceIndexPackage } from '../../../types/workspace-index.js';\nimport { readWorkspaceIndex, writeWorkspaceIndex } from '../../../utils/workspace-index-yml.js';\nimport { removePackageFromOpenpackageYml } from '../../package-management.js';\nimport { removeWorkspaceIndexEntry } from '../../../utils/workspace-index-ownership.js';\nimport { normalizePackageName } from '../../../utils/package-name.js';\nimport { normalizeGitUrl } from '../../../utils/git-url-parser.js';\nimport { logger } from '../../../utils/logger.js';\nimport type { OutputPort } from '../../ports/output.js';\nimport { resolveOutput } from '../../ports/resolve.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type SubsumptionResult =\n | SubsumptionNone\n | SubsumptionUpgrade\n | SubsumptionAlreadyCovered;\n\nexport interface SubsumptionNone {\n type: 'none';\n}\n\nexport interface SubsumptionUpgrade {\n type: 'upgrade';\n /** Resource-scoped entries that will be replaced by the full package */\n entriesToRemove: SubsumedEntry[];\n}\n\nexport interface SubsumptionAlreadyCovered {\n type: 'already-covered';\n /** The full-package name that already covers this resource */\n coveringPackage: string;\n}\n\nexport interface SubsumedEntry {\n /** Package name as recorded in the workspace index (e.g., gh@user/repo/agents/agent1) */\n packageName: string;\n}\n\n// ============================================================================\n// Detection\n// ============================================================================\n\n/**\n * Extract the source identity (normalized git URL or package name) and the\n * resource suffix from an installation context's source and package name.\n * \n * Returns null if the source type is not supported for subsumption.\n */\nexport function extractSourceIdentity(source: PackageSource): {\n /** Canonical source identifier (normalized git URL or registry name) */\n sourceKey: string;\n /** The gh@owner/repo prefix (for git) or package name (for registry/path) */\n basePackageName: string;\n /** Whether this install targets a specific resource within the package */\n isResourceScoped: boolean;\n} | null {\n const normalizedName = normalizePackageName(source.packageName);\n\n if (source.type === 'git' && source.gitUrl) {\n const normalizedUrl = normalizeGitUrl(source.gitUrl);\n // For git sources, the \"base\" package name is gh@owner/repo\n // A resource-scoped install has a longer name like gh@owner/repo/agents/agent1\n const ghMatch = normalizedName.match(/^gh@([^/]+\\/[^/]+)/);\n const basePackageName = ghMatch ? `gh@${ghMatch[1]}` : normalizedName;\n const isResourceScoped = Boolean(source.resourcePath) ||\n (normalizedName !== basePackageName);\n\n return {\n sourceKey: normalizedUrl,\n basePackageName,\n isResourceScoped\n };\n }\n\n if (source.type === 'path' && source.localPath) {\n // For path sources, the source key is the absolute path\n // Resource scoping is indicated by resourcePath\n const isResourceScoped = Boolean(source.resourcePath);\n return {\n sourceKey: `path:${source.localPath}`,\n basePackageName: normalizedName,\n isResourceScoped\n };\n }\n\n if (source.type === 'registry') {\n // Registry sources: the sourceKey is the normalized package name\n const isResourceScoped = Boolean(source.resourcePath || source.registryPath);\n return {\n sourceKey: `registry:${normalizedName}`,\n basePackageName: normalizedName,\n isResourceScoped\n };\n }\n\n return null;\n}\n\n/**\n * Determine if an existing workspace index entry belongs to the same source\n * as the incoming install. This matches based on:\n * - Git: normalized URL from the cached path pattern\n * - Path: absolute path prefix\n * - Registry: package name prefix\n * \n * For git sources, two entries share a source if the workspace index `path`\n * field points into the same git cache directory (same URL hash + commit hash).\n */\nfunction entrySameSource(\n existingName: string,\n existingEntry: WorkspaceIndexPackage,\n sourceKey: string,\n basePackageName: string,\n sourceType: PackageSource['type']\n): boolean {\n const normalizedExistingName = normalizePackageName(existingName);\n const normalizedBase = normalizePackageName(basePackageName);\n\n if (sourceType === 'git') {\n // For git sources, check if names share the same gh@owner/repo prefix\n // e.g., gh@user/repo and gh@user/repo/agents/agent1\n if (normalizedExistingName.startsWith(normalizedBase + '/') ||\n normalizedExistingName === normalizedBase) {\n return true;\n }\n // Also check if the base name is a prefix of the existing name\n if (normalizedBase.startsWith(normalizedExistingName + '/') ||\n normalizedBase === normalizedExistingName) {\n return true;\n }\n return false;\n }\n\n if (sourceType === 'path') {\n // For path sources, entries from the same local directory\n return normalizedExistingName === normalizedBase ||\n normalizedExistingName.startsWith(normalizedBase + '/') ||\n normalizedBase.startsWith(normalizedExistingName + '/');\n }\n\n if (sourceType === 'registry') {\n return normalizedExistingName === normalizedBase ||\n normalizedExistingName.startsWith(normalizedBase + '/') ||\n normalizedBase.startsWith(normalizedExistingName + '/');\n }\n\n return false;\n}\n\n/**\n * Check for subsumption between the incoming install and existing entries.\n * \n * @param source - The PackageSource for the incoming install\n * @param targetDir - The workspace target directory\n * @returns SubsumptionResult describing what action to take\n */\nexport async function checkSubsumption(\n source: PackageSource,\n targetDir: string\n): Promise<SubsumptionResult> {\n const identity = extractSourceIdentity(source);\n if (!identity) {\n return { type: 'none' };\n }\n\n const { sourceKey, basePackageName, isResourceScoped } = identity;\n\n // Read current workspace index\n const wsRecord = await readWorkspaceIndex(targetDir);\n const packages = wsRecord.index.packages ?? {};\n\n if (Object.keys(packages).length === 0) {\n return { type: 'none' };\n }\n\n const normalizedIncoming = normalizePackageName(source.packageName);\n\n if (!isResourceScoped) {\n // ---------------------------------------------------------------\n // Scenario 1: Installing a FULL PACKAGE\n // Check if any resource-scoped entries from the same source exist\n // ---------------------------------------------------------------\n const entriesToRemove: SubsumedEntry[] = [];\n\n for (const existingName of Object.keys(packages)) {\n if (normalizePackageName(existingName) === normalizedIncoming) {\n // Same package name -- not a subsumption, just a reinstall/update\n continue;\n }\n\n if (entrySameSource(existingName, packages[existingName], sourceKey, basePackageName, source.type)) {\n const normalizedExisting = normalizePackageName(existingName);\n // The existing entry is resource-scoped (its name is longer than the base)\n if (normalizedExisting.startsWith(normalizedIncoming + '/')) {\n entriesToRemove.push({ packageName: existingName });\n }\n }\n }\n\n if (entriesToRemove.length > 0) {\n return { type: 'upgrade', entriesToRemove };\n }\n } else {\n // ---------------------------------------------------------------\n // Scenario 2: Installing a RESOURCE from a package\n // Check if the full package from the same source is already installed\n // ---------------------------------------------------------------\n for (const existingName of Object.keys(packages)) {\n if (!entrySameSource(existingName, packages[existingName], sourceKey, basePackageName, source.type)) {\n continue;\n }\n\n const normalizedExisting = normalizePackageName(existingName);\n // The existing entry is the full package (its name equals the base)\n // and the incoming is more specific (resource-scoped)\n if (normalizedExisting === normalizePackageName(basePackageName) &&\n normalizedIncoming.startsWith(normalizedExisting + '/')) {\n return {\n type: 'already-covered',\n coveringPackage: existingName\n };\n }\n }\n }\n\n return { type: 'none' };\n}\n\n// ============================================================================\n// Resolution\n// ============================================================================\n\n/**\n * Resolve a subsumption upgrade by removing subsumed entries from both\n * the workspace manifest (openpackage.yml) and workspace index.\n * \n * @param result - The upgrade subsumption result\n * @param targetDir - The workspace target directory\n */\nexport async function resolveSubsumption(\n result: SubsumptionUpgrade,\n targetDir: string,\n output?: OutputPort\n): Promise<void> {\n const out = output ?? resolveOutput();\n const wsRecord = await readWorkspaceIndex(targetDir);\n\n for (const entry of result.entriesToRemove) {\n // Remove from workspace manifest (openpackage.yml)\n const removed = await removePackageFromOpenpackageYml(targetDir, entry.packageName);\n if (removed) {\n logger.info(`Removed subsumed manifest entry: ${entry.packageName}`);\n }\n\n // Remove from workspace index\n removeWorkspaceIndexEntry(wsRecord.index, entry.packageName);\n logger.info(`Removed subsumed index entry: ${entry.packageName}`);\n\n out.info(` Replacing ${entry.packageName} (subsumed by full package)`);\n }\n\n // Write updated workspace index\n await writeWorkspaceIndex(wsRecord);\n}\n", "import { HttpClient } from './http-client.js';\nimport { logger } from '../utils/logger.js';\nimport { getVersion } from '../utils/package.js';\nimport { configManager } from './config.js';\n\n/**\n * Single install event\n */\nexport interface InstallEvent {\n packageName: string;\n version: string;\n resourcePath?: string;\n resourceType?: string;\n resourceName?: string;\n marketplaceName?: string;\n pluginName?: string;\n}\n\n/**\n * Telemetry metadata\n */\ninterface TelemetryMetadata {\n cliVersion: string;\n timestamp: string;\n installCommand?: string;\n}\n\n/**\n * Batch telemetry request\n */\ninterface BatchTelemetryRequest {\n installs: InstallEvent[];\n metadata: TelemetryMetadata;\n}\n\n/**\n * Check if telemetry is enabled\n * Checks (in order of precedence):\n * 1. Environment variable OPKG_TELEMETRY_DISABLED\n * 2. Config file telemetry.disabled setting\n * 3. Default: enabled (true)\n */\nexport async function isTelemetryEnabled(): Promise<boolean> {\n // 1. Check environment variable first (highest priority)\n if (process.env.OPKG_TELEMETRY_DISABLED === 'true') {\n return false;\n }\n\n // 2. Check config file\n try {\n const configDisabled = await configManager.getTelemetryDisabled();\n if (configDisabled === true) {\n return false;\n }\n } catch (error) {\n // If config loading fails, continue with default\n logger.debug('Failed to load telemetry config, using default', { error });\n }\n\n // 3. Default: enabled\n return true;\n}\n\n/**\n * Check if telemetry debug mode is enabled\n */\nexport function isTelemetryDebugEnabled(): boolean {\n return process.env.OPKG_TELEMETRY_DEBUG === 'true';\n}\n\n/**\n * Collector for install telemetry events\n * Accumulates events during installation and sends in batch\n */\nexport class TelemetryCollector {\n private events: InstallEvent[] = [];\n private command?: string;\n\n constructor(command?: string) {\n this.command = command;\n }\n\n /**\n * Record an install event\n * Note: Does not check telemetry enabled here - check is done at collector creation\n */\n recordInstall(event: InstallEvent): void {\n // Basic validation\n if (!event.packageName || !event.version) {\n logger.debug('Skipping invalid telemetry event (missing package name or version)');\n return;\n }\n\n this.events.push(event);\n\n if (isTelemetryDebugEnabled()) {\n logger.debug(`[Telemetry] Recorded install: ${event.packageName}@${event.version}`, {\n resourcePath: event.resourcePath,\n resourceType: event.resourceType,\n resourceName: event.resourceName,\n });\n }\n }\n\n /**\n * Get the number of recorded events\n */\n getEventCount(): number {\n return this.events.length;\n }\n\n /**\n * Deduplicate events (same package + version + resource)\n */\n private deduplicateEvents(): InstallEvent[] {\n const seen = new Set<string>();\n const deduplicated: InstallEvent[] = [];\n\n for (const event of this.events) {\n const key = `${event.packageName}@${event.version}:${event.resourcePath || 'main'}`;\n if (!seen.has(key)) {\n seen.add(key);\n deduplicated.push(event);\n }\n }\n\n if (deduplicated.length < this.events.length) {\n logger.debug(\n `Deduplicated ${this.events.length - deduplicated.length} duplicate install events`\n );\n }\n\n return deduplicated;\n }\n\n /**\n * Flush all collected events to the backend\n * Fire-and-forget with timeout\n * Note: Does not check telemetry enabled here - check is done at collector creation\n */\n async flush(httpClient: HttpClient): Promise<void> {\n if (this.events.length === 0) {\n logger.debug('[Telemetry] No events to flush');\n return;\n }\n\n // Deduplicate events\n const uniqueEvents = this.deduplicateEvents();\n\n if (uniqueEvents.length === 0) {\n logger.debug('[Telemetry] All events were duplicates, nothing to send');\n return;\n }\n\n if (isTelemetryDebugEnabled()) {\n logger.debug(`[Telemetry] Flushing ${uniqueEvents.length} events`, {\n events: uniqueEvents,\n });\n // In debug mode, don't actually send\n return;\n }\n\n const payload: BatchTelemetryRequest = {\n installs: uniqueEvents,\n metadata: {\n cliVersion: getVersion(),\n timestamp: new Date().toISOString(),\n installCommand: this.command,\n },\n };\n\n try {\n logger.debug(`[Telemetry] Sending ${uniqueEvents.length} install events to backend`);\n\n // Fire-and-forget with 5 second timeout\n await reportBatchInstalls(httpClient, payload);\n\n logger.debug('[Telemetry] Successfully sent install events');\n } catch (error) {\n // Silent failure - log to debug only\n logger.debug('[Telemetry] Failed to send install events', { error });\n }\n }\n}\n\n/**\n * Send batch telemetry to backend\n * Fire-and-forget with timeout\n */\nasync function reportBatchInstalls(\n httpClient: HttpClient,\n payload: BatchTelemetryRequest\n): Promise<void> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout\n\n try {\n await httpClient.post('/telemetry/installs', payload, {\n signal: controller.signal,\n skipAuth: false, // Include auth if available\n });\n } catch (error) {\n // Check if it's a timeout\n if (error instanceof Error && error.name === 'AbortError') {\n logger.debug('[Telemetry] Request timed out after 5 seconds');\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n}\n\n/**\n * Create a new telemetry collector\n * Returns null if telemetry is disabled\n */\nexport async function createTelemetryCollector(command?: string): Promise<TelemetryCollector | null> {\n const enabled = await isTelemetryEnabled();\n if (!enabled) {\n return null;\n }\n\n return new TelemetryCollector(command);\n}\n", "/**\n * Install Command\n * \n * CLI definition only - all orchestration logic is in the orchestrator module.\n */\nimport { Command } from 'commander';\nimport type { InstallOptions } from '@opkg/core/types/index.js';\nimport { createOrchestrator } from '@opkg/core/core/install/orchestrator/index.js';\nimport { normalizeInstallOptions } from '@opkg/core/core/install/preprocessing/index.js';\nimport { createCliExecutionContext } from '../cli/context.js';\nimport { createTelemetryCollector } from '@opkg/core/core/telemetry.js';\nimport { createHttpClient } from '@opkg/core/core/http-client.js';\n\n/**\n * Setup install command\n */\nexport async function setupInstallCommand(args: any[]): Promise<void> {\n const [packageName, options, command] = args as [\n string | undefined,\n InstallOptions & { \n agents?: string[]; \n skills?: string[];\n rules?: string[];\n commands?: string[];\n conflicts?: string;\n interactive?: boolean;\n },\n Command\n ];\n\n // Validate mutually exclusive options\n if (options.interactive && (options.agents || options.skills || options.rules || options.commands)) {\n throw new Error('--interactive cannot be used with --agents, --skills, --rules, or --commands. Use --interactive for interactive selection or specify filters directly.');\n }\n \n // Get program-level options (for --cwd)\n const programOpts = command.parent?.opts() || {};\n \n // Create telemetry collector\n const telemetryCollector = await createTelemetryCollector('install');\n \n // Create execution context with CLI ports and telemetry\n const execContext = await createCliExecutionContext({\n global: options.global,\n cwd: programOpts.cwd\n });\n \n // Add telemetry collector to context\n if (telemetryCollector) {\n execContext.telemetryCollector = telemetryCollector;\n }\n \n // Normalize all options at CLI boundary\n const normalizedOptions = normalizeInstallOptions(options);\n \n // Create and execute orchestrator with execution context\n const orchestrator = createOrchestrator();\n const result = await orchestrator.execute(packageName, normalizedOptions, execContext);\n \n // Flush telemetry (truly fire-and-forget, non-blocking)\n if (telemetryCollector && result.success) {\n // Run in background without blocking command completion\n setImmediate(() => {\n createHttpClient({\n apiKey: options.apiKey,\n profile: options.profile\n })\n .then(httpClient => telemetryCollector.flush(httpClient))\n .catch(() => {\n // Silent failure - already logged in telemetry module\n });\n });\n }\n \n // Handle result\n if (!result.success) {\n if (result.error === 'Package not found') {\n return; // Already displayed message\n }\n throw new Error(result.error || 'Installation operation failed');\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;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cxC,MAAI,QAAQ,gBAAgB,QAAQ,UAAU,QAAQ,UAAU,QAAQ,SAAS,QAAQ;AACvF,UAAM,IAAI,MAAM,wJAAwJ;AAI1K,MAAM,cAAc,QAAQ,QAAQ,KAAK,KAAK,CAAC,GAGzC,qBAAqB,MAAM,yBAAyB,SAAS,GAG7D,cAAc,MAAM,0BAA0B;AAAA,IAClD,QAAQ,QAAQ;AAAA,IAChB,KAAK,YAAY;AAAA,EACnB,CAAC;AAGD,EAAI,uBACF,YAAY,qBAAqB;AAInC,MAAM,oBAAoB,wBAAwB,OAAO,GAInD,SAAS,MADM,mBAAmB,EACN,QAAQ,aAAa,mBAAmB,WAAW;AAkBrF,MAfI,sBAAsB,OAAO,WAE/B,aAAa,MAAM;AACjB,qBAAiB;AAAA,MACf,QAAQ,QAAQ;AAAA,MAChB,SAAS,QAAQ;AAAA,IACnB,CAAC,EACE,KAAK,gBAAc,mBAAmB,MAAM,UAAU,CAAC,EACvD,MAAM,MAAM;AAAA,IAEb,CAAC;AAAA,EACL,CAAC,GAIC,CAAC,OAAO,SAAS;AACnB,QAAI,OAAO,UAAU;AACnB;AAEF,UAAM,IAAI,MAAM,OAAO,SAAS,+BAA+B;AAAA,EACjE;AACF;",
6
+ "names": ["relative", "resolve", "join", "basename", "relative", "resolve", "relative", "relative", "path", "semver", "path", "join", "resolve", "join", "relative", "selectDeepestMatch", "join", "relative", "resolve", "resolve", "pluginDetection", "join", "pkg", "metadata", "version", "join", "minimatch", "basename", "dirname", "minimatch", "basename", "dirname", "path", "join", "minimatch", "join", "dirname", "join", "dirname", "join", "minimatch", "opts", "semver", "semver", "semver", "resolve", "dirname", "join", "join", "join", "allRanges", "normalizedRanges", "isWildcardRange", "constraintRanges", "pkg", "packageYmlFile", "dirname", "resolve", "join", "getInstalledPackageVersion", "join", "minimatch", "join", "join", "path", "minimatch", "join", "join", "join", "fs", "relative", "minimatch", "relative", "join", "relative", "tmpdir", "mkdtemp", "rm", "minimatch", "mkdtemp", "join", "tmpdir", "rm", "walkFiles", "relative", "minimatch", "join", "relative", "dirname", "basename", "basename", "basename", "fs", "join", "dirname", "basename", "relative", "minimatch", "path", "join", "relative", "dirname", "filePattern", "basename", "fs", "minimatch", "join", "dirname", "basename", "relative", "extname", "join", "dirname", "basename", "relative", "extname", "dirname", "join", "fs", "sep", "dirname", "join", "relative", "relative", "join", "collectFilesUnderDirectory", "join", "parts", "lastSlash", "join", "sep", "warning", "dirname", "fs", "decision", "executionResult", "result", "join", "dirname", "basename", "isSwitchExpression", "relative", "walkFiles", "relative", "relative", "walkFiles", "relative", "join", "fs", "dirname", "join", "join", "dirname", "path", "path", "path", "basename", "s", "resolve", "join", "ctx", "relative", "valid", "dirname", "normalizeGitUrl", "key", "join", "dirname", "join", "dirname", "join", "join", "dirname", "semver", "semver", "resolve", "s", "resolve", "valid", "commitSha", "result", "s", "resolve", "relative"]
7
+ }