@unbrained/pm-cli 2026.7.5 → 2026.7.7

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 (597) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/cli/commands/annotation-command.d.ts +1 -0
  3. package/dist/cli/commands/annotation-command.js +29 -2
  4. package/dist/cli/commands/annotation-command.js.map +1 -1
  5. package/dist/cli/commands/comments.js +3 -4
  6. package/dist/cli/commands/comments.js.map +1 -1
  7. package/dist/cli/commands/extension/bundled-catalog.d.ts +3 -0
  8. package/dist/cli/commands/extension/bundled-catalog.js +38 -28
  9. package/dist/cli/commands/extension/bundled-catalog.js.map +1 -1
  10. package/dist/cli/commands/extension/install-sources.js +81 -18
  11. package/dist/cli/commands/extension/install-sources.js.map +1 -1
  12. package/dist/cli/commands/health.js +9 -5
  13. package/dist/cli/commands/health.js.map +1 -1
  14. package/dist/cli/commands/learnings.js +5 -3
  15. package/dist/cli/commands/learnings.js.map +1 -1
  16. package/dist/cli/commands/notes.js +5 -3
  17. package/dist/cli/commands/notes.js.map +1 -1
  18. package/dist/cli/commands/reindex.js +4 -3
  19. package/dist/cli/commands/reindex.js.map +1 -1
  20. package/dist/cli/commands/search.js +3 -3
  21. package/dist/cli/commands/search.js.map +1 -1
  22. package/dist/cli/commands/test.d.ts +9 -0
  23. package/dist/cli/commands/test.js +144 -105
  24. package/dist/cli/commands/test.js.map +1 -1
  25. package/dist/cli/extension-command-help.js +10 -2
  26. package/dist/cli/extension-command-help.js.map +1 -1
  27. package/dist/cli/register-list-query.d.ts +1 -1
  28. package/dist/cli/register-list-query.js +18 -27
  29. package/dist/cli/register-list-query.js.map +1 -1
  30. package/dist/cli/register-operations.d.ts +0 -8
  31. package/dist/cli/register-operations.js +41 -46
  32. package/dist/cli/register-operations.js.map +1 -1
  33. package/dist/cli/register-setup.js +113 -13
  34. package/dist/cli/register-setup.js.map +1 -1
  35. package/dist/cli/registration-helpers.d.ts +5 -1
  36. package/dist/cli/registration-helpers.js +14 -2
  37. package/dist/cli/registration-helpers.js.map +1 -1
  38. package/dist/cli-bundle/chunks/append-F7WPGIQL.js +11 -0
  39. package/dist/cli-bundle/chunks/{contracts-OJEXMKVW.js → append-PVCTBVJG.js} +8 -9
  40. package/dist/cli-bundle/chunks/{chunk-PPE4YUQM.js → chunk-2APXX4TZ.js} +17 -28
  41. package/dist/cli-bundle/chunks/chunk-2APXX4TZ.js.map +1 -0
  42. package/dist/cli-bundle/chunks/{docs-S6UTOTO5.js → chunk-2LEJGRQ7.js} +3 -12
  43. package/dist/cli-bundle/chunks/{docs-S6UTOTO5.js.map → chunk-2LEJGRQ7.js.map} +1 -1
  44. package/dist/cli-bundle/chunks/{chunk-T3ABIMGW.js → chunk-2TILG6F2.js} +3 -3
  45. package/dist/cli-bundle/chunks/{chunk-S5AYOUT5.js → chunk-3G6UMXT3.js} +6 -8
  46. package/dist/cli-bundle/chunks/{chunk-S5AYOUT5.js.map → chunk-3G6UMXT3.js.map} +1 -1
  47. package/dist/cli-bundle/chunks/{chunk-RCT3YJOK.js → chunk-3TYOW6RR.js} +8 -8
  48. package/dist/cli-bundle/chunks/{chunk-3JZNEQBA.js → chunk-3X542TEY.js} +7 -7
  49. package/dist/cli-bundle/chunks/{history-repair-EVTO6LIH.js → chunk-42LXP4VO.js} +14 -21
  50. package/dist/cli-bundle/chunks/{history-repair-EVTO6LIH.js.map → chunk-42LXP4VO.js.map} +1 -1
  51. package/dist/cli-bundle/chunks/{chunk-5J2XPTAD.js → chunk-43SIHQND.js} +36 -15
  52. package/dist/cli-bundle/chunks/chunk-43SIHQND.js.map +7 -0
  53. package/dist/cli-bundle/chunks/{history-repair-4N6SDVHK.js → chunk-43UQN754.js} +12 -19
  54. package/dist/cli-bundle/chunks/{history-repair-4N6SDVHK.js.map → chunk-43UQN754.js.map} +1 -1
  55. package/dist/cli-bundle/chunks/{chunk-OWTIRHX4.js → chunk-43YSKY75.js} +4 -6
  56. package/dist/cli-bundle/chunks/{chunk-OWTIRHX4.js.map → chunk-43YSKY75.js.map} +1 -1
  57. package/dist/cli-bundle/chunks/{notes-72YXN5JX.js → chunk-4BKDAEDF.js} +6 -13
  58. package/dist/cli-bundle/chunks/{notes-72YXN5JX.js.map → chunk-4BKDAEDF.js.map} +2 -2
  59. package/dist/cli-bundle/chunks/{close-many-AP4MWU36.js → chunk-4IQKDKGE.js} +18 -32
  60. package/dist/cli-bundle/chunks/{close-many-AP4MWU36.js.map → chunk-4IQKDKGE.js.map} +1 -1
  61. package/dist/cli-bundle/chunks/{chunk-ZCJAA3JK.js → chunk-4MZOKTI2.js} +6 -8
  62. package/dist/cli-bundle/chunks/{chunk-ZCJAA3JK.js.map → chunk-4MZOKTI2.js.map} +1 -1
  63. package/dist/cli-bundle/chunks/{chunk-IJ6CO3JV.js → chunk-52NS7JDP.js} +14 -20
  64. package/dist/cli-bundle/chunks/{chunk-IJ6CO3JV.js.map → chunk-52NS7JDP.js.map} +1 -1
  65. package/dist/cli-bundle/chunks/{chunk-T3F4DF23.js → chunk-565WYS5W.js} +12 -16
  66. package/dist/cli-bundle/chunks/{chunk-T3F4DF23.js.map → chunk-565WYS5W.js.map} +1 -1
  67. package/dist/cli-bundle/chunks/{copy-OTJOWFL6.js → chunk-5FIQ4EX3.js} +13 -19
  68. package/dist/cli-bundle/chunks/{copy-OTJOWFL6.js.map → chunk-5FIQ4EX3.js.map} +1 -1
  69. package/dist/cli-bundle/chunks/{config-V57QD47V.js → chunk-6G6O3OPQ.js} +259 -41
  70. package/dist/cli-bundle/chunks/chunk-6G6O3OPQ.js.map +1 -0
  71. package/dist/cli-bundle/chunks/{chunk-K3AGVXSF.js → chunk-6LCJRGPD.js} +9 -13
  72. package/dist/cli-bundle/chunks/{chunk-K3AGVXSF.js.map → chunk-6LCJRGPD.js.map} +1 -1
  73. package/dist/cli-bundle/chunks/{chunk-7MDXZAZS.js → chunk-6UQCNWFV.js} +6 -8
  74. package/dist/cli-bundle/chunks/{chunk-7MDXZAZS.js.map → chunk-6UQCNWFV.js.map} +1 -1
  75. package/dist/cli-bundle/chunks/{chunk-LEKT4K7I.js → chunk-6XTSYPPO.js} +1216 -387
  76. package/dist/cli-bundle/chunks/chunk-6XTSYPPO.js.map +7 -0
  77. package/dist/cli-bundle/chunks/chunk-7ML7JONU.js +5434 -0
  78. package/dist/cli-bundle/chunks/chunk-7ML7JONU.js.map +1 -0
  79. package/dist/cli-bundle/chunks/{chunk-TSPKZRRW.js → chunk-7PNQA24K.js} +30 -36
  80. package/dist/cli-bundle/chunks/{chunk-TSPKZRRW.js.map → chunk-7PNQA24K.js.map} +1 -1
  81. package/dist/cli-bundle/chunks/{chunk-YOF5VPKM.js → chunk-7VQ3JJN5.js} +2 -2
  82. package/dist/cli-bundle/chunks/{chunk-BFVHCAOO.js → chunk-7Y5N34HX.js} +8 -12
  83. package/dist/cli-bundle/chunks/{chunk-BFVHCAOO.js.map → chunk-7Y5N34HX.js.map} +1 -1
  84. package/dist/cli-bundle/chunks/{chunk-P5TFTLWW.js → chunk-AGAVEDIE.js} +7 -7
  85. package/dist/cli-bundle/chunks/{chunk-YFIE7YK6.js → chunk-AJUON7E6.js} +3 -3
  86. package/dist/cli-bundle/chunks/{close-many-OMZIGZB4.js → chunk-ARKHKYYS.js} +16 -30
  87. package/dist/cli-bundle/chunks/{close-many-OMZIGZB4.js.map → chunk-ARKHKYYS.js.map} +1 -1
  88. package/dist/cli-bundle/chunks/{chunk-7EQNAZX2.js → chunk-C5ACVMOI.js} +99 -51
  89. package/dist/cli-bundle/chunks/chunk-C5ACVMOI.js.map +7 -0
  90. package/dist/cli-bundle/chunks/{chunk-PJ3A56YF.js → chunk-CJQM7O7R.js} +16 -20
  91. package/dist/cli-bundle/chunks/{chunk-PJ3A56YF.js.map → chunk-CJQM7O7R.js.map} +1 -1
  92. package/dist/cli-bundle/chunks/{chunk-WISPVC2E.js → chunk-D2DCTFTL.js} +7 -9
  93. package/dist/cli-bundle/chunks/{chunk-WISPVC2E.js.map → chunk-D2DCTFTL.js.map} +1 -1
  94. package/dist/cli-bundle/chunks/{append-CZGUZ45Q.js → chunk-DDDWVPID.js} +7 -11
  95. package/dist/cli-bundle/chunks/{append-CZGUZ45Q.js.map → chunk-DDDWVPID.js.map} +1 -1
  96. package/dist/cli-bundle/chunks/{learnings-2HTPZNGZ.js → chunk-DG6BSXZ7.js} +6 -13
  97. package/dist/cli-bundle/chunks/{learnings-2HTPZNGZ.js.map → chunk-DG6BSXZ7.js.map} +2 -2
  98. package/dist/cli-bundle/chunks/{chunk-7WYXBPYQ.js → chunk-DR2V5OIV.js} +3 -3
  99. package/dist/cli-bundle/chunks/{chunk-YQMMMONE.js → chunk-E3LWJUGF.js} +4 -6
  100. package/dist/cli-bundle/chunks/{chunk-YQMMMONE.js.map → chunk-E3LWJUGF.js.map} +1 -1
  101. package/dist/cli-bundle/chunks/{chunk-D3UCE7RW.js → chunk-E3YQFSFE.js} +6 -10
  102. package/dist/cli-bundle/chunks/{chunk-D3UCE7RW.js.map → chunk-E3YQFSFE.js.map} +1 -1
  103. package/dist/cli-bundle/chunks/{chunk-PDXT6Q55.js → chunk-EDO7VXSO.js} +2 -2
  104. package/dist/cli-bundle/chunks/{chunk-FDBARR33.js → chunk-EIUBK2LT.js} +12 -18
  105. package/dist/cli-bundle/chunks/{chunk-FDBARR33.js.map → chunk-EIUBK2LT.js.map} +1 -1
  106. package/dist/cli-bundle/chunks/{chunk-HBYZDSK5.js → chunk-EMXPI36L.js} +14 -20
  107. package/dist/cli-bundle/chunks/{chunk-HBYZDSK5.js.map → chunk-EMXPI36L.js.map} +1 -1
  108. package/dist/cli-bundle/chunks/{chunk-4OFLJHX6.js → chunk-EOUVR7JN.js} +13 -8
  109. package/dist/cli-bundle/chunks/chunk-EOUVR7JN.js.map +1 -0
  110. package/dist/cli-bundle/chunks/{chunk-FUM6UMY4.js → chunk-EVEPHNXJ.js} +4 -4
  111. package/dist/cli-bundle/chunks/{deps-L2FPIAD3.js → chunk-F6MT7KKE.js} +6 -10
  112. package/dist/cli-bundle/chunks/{deps-L2FPIAD3.js.map → chunk-F6MT7KKE.js.map} +1 -1
  113. package/dist/cli-bundle/chunks/{chunk-FGQKEDE4.js → chunk-F6YC2A6X.js} +7 -11
  114. package/dist/cli-bundle/chunks/{chunk-FGQKEDE4.js.map → chunk-F6YC2A6X.js.map} +1 -1
  115. package/dist/cli-bundle/chunks/chunk-FILL6BB2.js +5514 -0
  116. package/dist/cli-bundle/chunks/chunk-FILL6BB2.js.map +7 -0
  117. package/dist/cli-bundle/chunks/{chunk-RX3HQSYG.js → chunk-FN6SB4HU.js} +2 -2
  118. package/dist/cli-bundle/chunks/chunk-GH73UOSJ.js +5359 -0
  119. package/dist/cli-bundle/chunks/chunk-GH73UOSJ.js.map +1 -0
  120. package/dist/cli-bundle/chunks/{chunk-JLA7EVYV.js → chunk-GLS6VMWI.js} +37 -16
  121. package/dist/cli-bundle/chunks/chunk-GLS6VMWI.js.map +1 -0
  122. package/dist/cli-bundle/chunks/{files-JPU3FNJ7.js → chunk-GPIDUMMN.js} +10 -17
  123. package/dist/cli-bundle/chunks/{files-JPU3FNJ7.js.map → chunk-GPIDUMMN.js.map} +1 -1
  124. package/dist/cli-bundle/chunks/{history-compact-3F6VELO7.js → chunk-GTM5HQL4.js} +15 -21
  125. package/dist/cli-bundle/chunks/{history-compact-3F6VELO7.js.map → chunk-GTM5HQL4.js.map} +1 -1
  126. package/dist/cli-bundle/chunks/{chunk-DLQ4ZTCU.js → chunk-H2SMKL2N.js} +8 -8
  127. package/dist/cli-bundle/chunks/{chunk-S4APD35C.js → chunk-HHEWQXPD.js} +6 -6
  128. package/dist/cli-bundle/chunks/chunk-HHEWQXPD.js.map +7 -0
  129. package/dist/cli-bundle/chunks/{chunk-C3PMDWGX.js → chunk-HX6QXV5P.js} +2 -2
  130. package/dist/cli-bundle/chunks/{copy-LEE6P6EM.js → chunk-I74FMIWA.js} +11 -17
  131. package/dist/cli-bundle/chunks/{copy-LEE6P6EM.js.map → chunk-I74FMIWA.js.map} +1 -1
  132. package/dist/cli-bundle/chunks/chunk-IDIBF4E2.js +804 -0
  133. package/dist/cli-bundle/chunks/chunk-IDIBF4E2.js.map +7 -0
  134. package/dist/cli-bundle/chunks/{comments-SAG5LSKL.js → chunk-II7R6KD4.js} +9 -13
  135. package/dist/cli-bundle/chunks/{comments-SAG5LSKL.js.map → chunk-II7R6KD4.js.map} +1 -1
  136. package/dist/cli-bundle/chunks/chunk-J2VGADNG.js +10320 -0
  137. package/dist/cli-bundle/chunks/chunk-J2VGADNG.js.map +1 -0
  138. package/dist/cli-bundle/chunks/{chunk-Y76TWC45.js → chunk-J7BOLHAV.js} +5 -7
  139. package/dist/cli-bundle/chunks/{chunk-Y76TWC45.js.map → chunk-J7BOLHAV.js.map} +1 -1
  140. package/dist/cli-bundle/chunks/{chunk-QHZO65XW.js → chunk-KTGJ2CBU.js} +4 -6
  141. package/dist/cli-bundle/chunks/{chunk-QHZO65XW.js.map → chunk-KTGJ2CBU.js.map} +1 -1
  142. package/dist/cli-bundle/chunks/{chunk-5VVUKE3U.js → chunk-LCFJ7XAM.js} +32 -2
  143. package/dist/cli-bundle/chunks/{chunk-5VVUKE3U.js.map → chunk-LCFJ7XAM.js.map} +3 -3
  144. package/dist/cli-bundle/chunks/{chunk-YMABYTNG.js → chunk-LZQU6XJG.js} +28 -34
  145. package/dist/cli-bundle/chunks/{chunk-YMABYTNG.js.map → chunk-LZQU6XJG.js.map} +1 -1
  146. package/dist/cli-bundle/chunks/{chunk-3Y4OESPP.js → chunk-M62RO3XK.js} +10 -14
  147. package/dist/cli-bundle/chunks/{chunk-3Y4OESPP.js.map → chunk-M62RO3XK.js.map} +1 -1
  148. package/dist/cli-bundle/chunks/{chunk-YPPVU5GX.js → chunk-MCEUKJKW.js} +9 -11
  149. package/dist/cli-bundle/chunks/{chunk-YPPVU5GX.js.map → chunk-MCEUKJKW.js.map} +1 -1
  150. package/dist/cli-bundle/chunks/{chunk-T5Y3QSNF.js → chunk-MHNMCDWR.js} +1447 -86
  151. package/dist/cli-bundle/chunks/chunk-MHNMCDWR.js.map +1 -0
  152. package/dist/cli-bundle/chunks/{chunk-HJE4JTKQ.js → chunk-MRFWUSVA.js} +4 -6
  153. package/dist/cli-bundle/chunks/{chunk-HJE4JTKQ.js.map → chunk-MRFWUSVA.js.map} +1 -1
  154. package/dist/cli-bundle/chunks/{chunk-P3VRG72Q.js → chunk-N6ZHDLUY.js} +6 -8
  155. package/dist/cli-bundle/chunks/{chunk-P3VRG72Q.js.map → chunk-N6ZHDLUY.js.map} +1 -1
  156. package/dist/cli-bundle/chunks/{delete-HQKGRNRZ.js → chunk-NWWL22C7.js} +8 -12
  157. package/dist/cli-bundle/chunks/{delete-HQKGRNRZ.js.map → chunk-NWWL22C7.js.map} +1 -1
  158. package/dist/cli-bundle/chunks/{chunk-N6DNM2FA.js → chunk-P3MJJW7P.js} +2 -2
  159. package/dist/cli-bundle/chunks/{chunk-5JE6SMYS.js → chunk-PDXJXEZJ.js} +2 -2
  160. package/dist/cli-bundle/chunks/{append-NSQBCXZJ.js → chunk-Q64AYQYW.js} +9 -13
  161. package/dist/cli-bundle/chunks/{append-NSQBCXZJ.js.map → chunk-Q64AYQYW.js.map} +1 -1
  162. package/dist/cli-bundle/chunks/{update-many-SLLAMHT7.js → chunk-QDABF2RB.js} +26 -47
  163. package/dist/cli-bundle/chunks/{update-many-SLLAMHT7.js.map → chunk-QDABF2RB.js.map} +1 -1
  164. package/dist/cli-bundle/chunks/{chunk-NBFCNJ7Q.js → chunk-QFBSP3NI.js} +529 -46
  165. package/dist/cli-bundle/chunks/chunk-QFBSP3NI.js.map +1 -0
  166. package/dist/cli-bundle/chunks/{focus-LFZ6IDBR.js → chunk-RB3KLPAH.js} +11 -16
  167. package/dist/cli-bundle/chunks/{focus-LFZ6IDBR.js.map → chunk-RB3KLPAH.js.map} +1 -1
  168. package/dist/cli-bundle/chunks/{chunk-YSAH5FY5.js → chunk-RY7PTTUB.js} +94 -53
  169. package/dist/cli-bundle/chunks/chunk-RY7PTTUB.js.map +1 -0
  170. package/dist/cli-bundle/chunks/{chunk-WVSGSZ6J.js → chunk-S547WBYG.js} +1477 -86
  171. package/dist/cli-bundle/chunks/chunk-S547WBYG.js.map +7 -0
  172. package/dist/cli-bundle/chunks/{update-many-DC7X3EWM.js → chunk-S5BNGFN5.js} +24 -45
  173. package/dist/cli-bundle/chunks/{update-many-DC7X3EWM.js.map → chunk-S5BNGFN5.js.map} +1 -1
  174. package/dist/cli-bundle/chunks/{focus-WNMYCVYA.js → chunk-S6VC2A2K.js} +9 -14
  175. package/dist/cli-bundle/chunks/{focus-WNMYCVYA.js.map → chunk-S6VC2A2K.js.map} +1 -1
  176. package/dist/cli-bundle/chunks/{learnings-YBIHY3D6.js → chunk-SIM5JDON.js} +7 -14
  177. package/dist/cli-bundle/chunks/{learnings-YBIHY3D6.js.map → chunk-SIM5JDON.js.map} +1 -1
  178. package/dist/cli-bundle/chunks/{chunk-ZD34OFFQ.js → chunk-SY75LYXR.js} +12 -7
  179. package/dist/cli-bundle/chunks/chunk-SY75LYXR.js.map +7 -0
  180. package/dist/cli-bundle/chunks/{chunk-TT42JUMF.js → chunk-TEISGNSH.js} +7 -7
  181. package/dist/cli-bundle/chunks/chunk-TEISGNSH.js.map +1 -0
  182. package/dist/cli-bundle/chunks/{chunk-AAEQMOC6.js → chunk-TEKZOS7M.js} +2 -2
  183. package/dist/cli-bundle/chunks/{chunk-4QQ6PM7M.js → chunk-TGUK6XN6.js} +14 -18
  184. package/dist/cli-bundle/chunks/{chunk-4QQ6PM7M.js.map → chunk-TGUK6XN6.js.map} +1 -1
  185. package/dist/cli-bundle/chunks/{plan-R4NDQ27E.js → chunk-TNC6MZUD.js} +10 -21
  186. package/dist/cli-bundle/chunks/{plan-R4NDQ27E.js.map → chunk-TNC6MZUD.js.map} +1 -1
  187. package/dist/cli-bundle/chunks/chunk-TZLYO4PP.js +10498 -0
  188. package/dist/cli-bundle/chunks/chunk-TZLYO4PP.js.map +7 -0
  189. package/dist/cli-bundle/chunks/{chunk-YD5FML7K.js → chunk-UO7XAZK6.js} +27 -4
  190. package/dist/cli-bundle/chunks/chunk-UO7XAZK6.js.map +1 -0
  191. package/dist/cli-bundle/chunks/{docs-6CRCSVKK.js → chunk-V5ZWKJNY.js} +5 -14
  192. package/dist/cli-bundle/chunks/{docs-6CRCSVKK.js.map → chunk-V5ZWKJNY.js.map} +1 -1
  193. package/dist/cli-bundle/chunks/{notes-NJ7IQJX4.js → chunk-VGO73OCK.js} +7 -14
  194. package/dist/cli-bundle/chunks/{notes-NJ7IQJX4.js.map → chunk-VGO73OCK.js.map} +1 -1
  195. package/dist/cli-bundle/chunks/{chunk-NER3KUUS.js → chunk-VLEA2UTQ.js} +2 -2
  196. package/dist/cli-bundle/chunks/{files-6P57MRKL.js → chunk-W5HXHC7C.js} +8 -15
  197. package/dist/cli-bundle/chunks/{files-6P57MRKL.js.map → chunk-W5HXHC7C.js.map} +1 -1
  198. package/dist/cli-bundle/chunks/{chunk-ZMD35NYG.js → chunk-WCWVEXGA.js} +2 -2
  199. package/dist/cli-bundle/chunks/chunk-X47MKQXU.js +6690 -0
  200. package/dist/cli-bundle/chunks/chunk-X47MKQXU.js.map +7 -0
  201. package/dist/cli-bundle/chunks/{delete-62JQTYT4.js → chunk-XBX5CBRQ.js} +6 -10
  202. package/dist/cli-bundle/chunks/{delete-62JQTYT4.js.map → chunk-XBX5CBRQ.js.map} +1 -1
  203. package/dist/cli-bundle/chunks/{chunk-MTTXDAK4.js → chunk-XC3X7BQR.js} +541 -44
  204. package/dist/cli-bundle/chunks/chunk-XC3X7BQR.js.map +7 -0
  205. package/dist/cli-bundle/chunks/{history-compact-656Y2TN4.js → chunk-XHCVAZGM.js} +17 -23
  206. package/dist/cli-bundle/chunks/{history-compact-656Y2TN4.js.map → chunk-XHCVAZGM.js.map} +1 -1
  207. package/dist/cli-bundle/chunks/{chunk-ZAHXPXVY.js → chunk-XPMXPR7K.js} +7 -9
  208. package/dist/cli-bundle/chunks/{chunk-ZAHXPXVY.js.map → chunk-XPMXPR7K.js.map} +1 -1
  209. package/dist/cli-bundle/chunks/{deps-55FTG6Z5.js → chunk-XS2TMNXR.js} +8 -12
  210. package/dist/cli-bundle/chunks/{deps-55FTG6Z5.js.map → chunk-XS2TMNXR.js.map} +1 -1
  211. package/dist/cli-bundle/chunks/{plan-XWY5T67S.js → chunk-XXIYUTLK.js} +12 -23
  212. package/dist/cli-bundle/chunks/{plan-XWY5T67S.js.map → chunk-XXIYUTLK.js.map} +1 -1
  213. package/dist/cli-bundle/chunks/{chunk-7QH7DHUB.js → chunk-XZWL7VNE.js} +1220 -398
  214. package/dist/cli-bundle/chunks/chunk-XZWL7VNE.js.map +1 -0
  215. package/dist/cli-bundle/chunks/chunk-Y5IKRUEM.js +6624 -0
  216. package/dist/cli-bundle/chunks/chunk-Y5IKRUEM.js.map +1 -0
  217. package/dist/cli-bundle/chunks/{chunk-ABRA3BHY.js → chunk-Y7KYVCZM.js} +12 -18
  218. package/dist/cli-bundle/chunks/{chunk-ABRA3BHY.js.map → chunk-Y7KYVCZM.js.map} +1 -1
  219. package/dist/cli-bundle/chunks/{chunk-UI5BJ6DO.js → chunk-YCVWWIKY.js} +17 -28
  220. package/dist/cli-bundle/chunks/chunk-YCVWWIKY.js.map +7 -0
  221. package/dist/cli-bundle/chunks/chunk-YH5NBDFA.js +780 -0
  222. package/dist/cli-bundle/chunks/chunk-YH5NBDFA.js.map +1 -0
  223. package/dist/cli-bundle/chunks/chunk-YNCFP5AR.js +5509 -0
  224. package/dist/cli-bundle/chunks/chunk-YNCFP5AR.js.map +7 -0
  225. package/dist/cli-bundle/chunks/{comments-MIW5MZOX.js → chunk-YPD7SQ5P.js} +8 -12
  226. package/dist/cli-bundle/chunks/{comments-MIW5MZOX.js.map → chunk-YPD7SQ5P.js.map} +2 -2
  227. package/dist/cli-bundle/chunks/{chunk-T35XLYZF.js → chunk-YPMZMKN7.js} +2 -2
  228. package/dist/cli-bundle/chunks/{chunk-R3ZBLGTC.js → chunk-YTD5GICJ.js} +4 -4
  229. package/dist/cli-bundle/chunks/{config-DJJKZB5R.js → chunk-ZNEG2UDO.js} +264 -39
  230. package/dist/cli-bundle/chunks/{config-DJJKZB5R.js.map → chunk-ZNEG2UDO.js.map} +4 -4
  231. package/dist/cli-bundle/chunks/{chunk-EEY54JMF.js → chunk-ZO7CLOY2.js} +3 -3
  232. package/dist/cli-bundle/chunks/{close-3YRR3XY6.js → close-3YYQ5OG2.js} +5 -9
  233. package/dist/cli-bundle/chunks/close-Z3Q4U7TS.js +12 -0
  234. package/dist/cli-bundle/chunks/close-many-3L2RXH3M.js +22 -0
  235. package/dist/cli-bundle/chunks/close-many-D366FTIG.js +26 -0
  236. package/dist/cli-bundle/chunks/comments-54XDJNFE.js +17 -0
  237. package/dist/cli-bundle/chunks/comments-HGHC2PN6.js +13 -0
  238. package/dist/cli-bundle/chunks/copy-44RT5GDW.js +13 -0
  239. package/dist/cli-bundle/chunks/copy-UGMUGHZA.js +9 -0
  240. package/dist/cli-bundle/chunks/{create-XWWQFQ6S.js → create-4GWJWPXG.js} +9 -14
  241. package/dist/cli-bundle/chunks/create-AZXCUYKP.js +25 -0
  242. package/dist/cli-bundle/chunks/delete-Y6SXIQ4X.js +10 -0
  243. package/dist/cli-bundle/chunks/delete-YQ2VPXNF.js +14 -0
  244. package/dist/cli-bundle/chunks/deps-BU5EBJDU.js +17 -0
  245. package/dist/cli-bundle/chunks/deps-FMANWFRP.js +13 -0
  246. package/dist/cli-bundle/chunks/docs-OQBSJNIA.js +18 -0
  247. package/dist/cli-bundle/chunks/docs-VNPBZXEL.js +14 -0
  248. package/dist/cli-bundle/chunks/files-72HZEBOE.js +18 -0
  249. package/dist/cli-bundle/chunks/{activity-YKAKZTZ4.js → files-HTSB2KJG.js} +13 -13
  250. package/dist/cli-bundle/chunks/focus-FOG4ALC2.js +14 -0
  251. package/dist/cli-bundle/chunks/focus-SUTMKXGX.js +10 -0
  252. package/dist/cli-bundle/chunks/history-compact-M6IFAMBP.js +25 -0
  253. package/dist/cli-bundle/chunks/history-compact-NEXRPP2O.js +21 -0
  254. package/dist/cli-bundle/chunks/{history-redact-54ICFKXM.js → history-redact-NQX3OGZP.js} +7 -11
  255. package/dist/cli-bundle/chunks/history-redact-WQJBZ3PX.js +17 -0
  256. package/dist/cli-bundle/chunks/history-repair-CBHMHAJO.js +19 -0
  257. package/dist/cli-bundle/chunks/history-repair-NHOJG7WO.js +23 -0
  258. package/dist/cli-bundle/chunks/learnings-M64NTSOR.js +13 -0
  259. package/dist/cli-bundle/chunks/learnings-T63JGKKN.js +17 -0
  260. package/dist/cli-bundle/chunks/notes-73WE2UV2.js +13 -0
  261. package/dist/cli-bundle/chunks/notes-U7L6HQQ2.js +17 -0
  262. package/dist/cli-bundle/chunks/plan-OSCNYFGC.js +24 -0
  263. package/dist/cli-bundle/chunks/plan-OSCNYFGC.js.map +7 -0
  264. package/dist/cli-bundle/chunks/plan-TN537L24.js +28 -0
  265. package/dist/cli-bundle/chunks/plan-TN537L24.js.map +1 -0
  266. package/dist/cli-bundle/chunks/profile-MHAMXMHQ.js +37 -0
  267. package/dist/cli-bundle/chunks/profile-MHAMXMHQ.js.map +1 -0
  268. package/dist/cli-bundle/chunks/profile-TIGLAKJ7.js +33 -0
  269. package/dist/cli-bundle/chunks/profile-TIGLAKJ7.js.map +7 -0
  270. package/dist/cli-bundle/chunks/{register-list-query-5H66WFYF.js → register-list-query-OHXD7G5N.js} +41 -33
  271. package/dist/cli-bundle/chunks/register-list-query-OHXD7G5N.js.map +7 -0
  272. package/dist/cli-bundle/chunks/{register-list-query-FB3FNDLZ.js → register-list-query-ZCRABAPN.js} +42 -34
  273. package/dist/cli-bundle/chunks/register-list-query-ZCRABAPN.js.map +1 -0
  274. package/dist/cli-bundle/chunks/{register-mutation-UJO23C7R.js → register-mutation-P3G4XP6Q.js} +36 -41
  275. package/dist/cli-bundle/chunks/{register-mutation-UJO23C7R.js.map → register-mutation-P3G4XP6Q.js.map} +1 -1
  276. package/dist/cli-bundle/chunks/{register-mutation-Z2ETYHKS.js → register-mutation-XX4H56PE.js} +34 -39
  277. package/dist/cli-bundle/chunks/{register-mutation-Z2ETYHKS.js.map → register-mutation-XX4H56PE.js.map} +1 -1
  278. package/dist/cli-bundle/chunks/{register-operations-A3XAM5J7.js → register-operations-V6PIYEDU.js} +80 -52
  279. package/dist/cli-bundle/chunks/register-operations-V6PIYEDU.js.map +1 -0
  280. package/dist/cli-bundle/chunks/{register-operations-SG7HBSUP.js → register-operations-V6VKTG54.js} +79 -51
  281. package/dist/cli-bundle/chunks/register-operations-V6VKTG54.js.map +7 -0
  282. package/dist/cli-bundle/chunks/{register-setup-K6U3NVY5.js → register-setup-6RVAWT6W.js} +129 -31
  283. package/dist/cli-bundle/chunks/register-setup-6RVAWT6W.js.map +7 -0
  284. package/dist/cli-bundle/chunks/{register-setup-I45OGJUV.js → register-setup-6YVUSQYD.js} +130 -32
  285. package/dist/cli-bundle/chunks/register-setup-6YVUSQYD.js.map +1 -0
  286. package/dist/cli-bundle/chunks/{restore-YJ2ET6AT.js → restore-HC3YSWF7.js} +7 -11
  287. package/dist/cli-bundle/chunks/restore-HC3YSWF7.js.map +1 -0
  288. package/dist/cli-bundle/chunks/restore-LFAMMRYZ.js +15 -0
  289. package/dist/cli-bundle/chunks/restore-LFAMMRYZ.js.map +7 -0
  290. package/dist/cli-bundle/chunks/{schema-2PUXCZ25.js → schema-DAGSYO6E.js} +6 -10
  291. package/dist/cli-bundle/chunks/schema-DAGSYO6E.js.map +7 -0
  292. package/dist/cli-bundle/chunks/{schema-Y6DXXK2F.js → schema-UBXJCQAC.js} +6 -10
  293. package/dist/cli-bundle/chunks/schema-UBXJCQAC.js.map +1 -0
  294. package/dist/cli-bundle/chunks/update-CJGG5WMV.js +21 -0
  295. package/dist/cli-bundle/chunks/update-CJGG5WMV.js.map +7 -0
  296. package/dist/cli-bundle/chunks/update-LKD64AFP.js +25 -0
  297. package/dist/cli-bundle/chunks/update-LKD64AFP.js.map +1 -0
  298. package/dist/cli-bundle/chunks/update-many-G4SM7BHC.js +31 -0
  299. package/dist/cli-bundle/chunks/update-many-G4SM7BHC.js.map +7 -0
  300. package/dist/cli-bundle/chunks/update-many-VLIV3D7R.js +35 -0
  301. package/dist/cli-bundle/chunks/update-many-VLIV3D7R.js.map +1 -0
  302. package/dist/cli-bundle/main.js +29 -31
  303. package/dist/cli-bundle/main.js.map +2 -2
  304. package/dist/cli-bundle/sdk-runtime.js +136 -54
  305. package/dist/cli-bundle/sdk-testing.js +7 -8
  306. package/dist/cli-bundle/sdk.js +132 -84
  307. package/dist/cli-bundle/sdk.js.map +2 -2
  308. package/dist/core/history/drift-scan.js +3 -8
  309. package/dist/core/history/drift-scan.js.map +1 -1
  310. package/dist/core/output/mutation-projection.js +11 -5
  311. package/dist/core/output/mutation-projection.js.map +1 -1
  312. package/dist/core/search/cache.js +3 -3
  313. package/dist/core/search/cache.js.map +1 -1
  314. package/dist/core/search/semantic-defaults.d.ts +2 -0
  315. package/dist/core/search/semantic-defaults.js +11 -4
  316. package/dist/core/search/semantic-defaults.js.map +1 -1
  317. package/dist/core/search/vector-stores.d.ts +1 -1
  318. package/dist/core/search/vector-stores.js +33 -7
  319. package/dist/core/search/vector-stores.js.map +1 -1
  320. package/dist/mcp/server.d.ts +22 -50
  321. package/dist/mcp/server.js +62 -916
  322. package/dist/mcp/server.js.map +1 -1
  323. package/dist/sdk/cli-contracts/flag-contracts.js +7 -7
  324. package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
  325. package/dist/sdk/cli-contracts/tool-schema.js +9 -7
  326. package/dist/sdk/cli-contracts/tool-schema.js.map +1 -1
  327. package/dist/sdk/index.d.ts +4 -2
  328. package/dist/sdk/index.js +4 -4
  329. package/dist/sdk/index.js.map +1 -1
  330. package/dist/sdk/runtime.d.ts +312 -5
  331. package/dist/sdk/runtime.js +1391 -26
  332. package/dist/sdk/runtime.js.map +1 -1
  333. package/dist/sdk/start-task-status.d.ts +13 -0
  334. package/dist/sdk/start-task-status.js +19 -0
  335. package/dist/sdk/start-task-status.js.map +1 -0
  336. package/dist/sdk/workspace-contracts-cache.d.ts +17 -0
  337. package/dist/sdk/workspace-contracts-cache.js +36 -0
  338. package/dist/sdk/workspace-contracts-cache.js.map +1 -0
  339. package/docs/COMMANDS.md +10 -1
  340. package/docs/RELEASING.md +3 -1
  341. package/docs/SDK.md +81 -0
  342. package/docs/TESTING.md +3 -0
  343. package/docs/examples/sdk-app-embedding/run-embedded-pm.mjs +16 -2
  344. package/docs/examples/sdk-contract-consumer/inspect-contracts.mjs +16 -1
  345. package/package.json +1 -1
  346. package/dist/cli-bundle/chunks/activity-4XQIDNM5.js +0 -18
  347. package/dist/cli-bundle/chunks/aggregate-EQX2RGB7.js +0 -375
  348. package/dist/cli-bundle/chunks/aggregate-EQX2RGB7.js.map +0 -7
  349. package/dist/cli-bundle/chunks/aggregate-PEGZGJXD.js +0 -372
  350. package/dist/cli-bundle/chunks/aggregate-PEGZGJXD.js.map +0 -1
  351. package/dist/cli-bundle/chunks/chunk-37E72CNS.js +0 -217
  352. package/dist/cli-bundle/chunks/chunk-37E72CNS.js.map +0 -1
  353. package/dist/cli-bundle/chunks/chunk-3PL6LEKP.js +0 -1961
  354. package/dist/cli-bundle/chunks/chunk-3PL6LEKP.js.map +0 -1
  355. package/dist/cli-bundle/chunks/chunk-3U3VEWK6.js +0 -1749
  356. package/dist/cli-bundle/chunks/chunk-3U3VEWK6.js.map +0 -7
  357. package/dist/cli-bundle/chunks/chunk-4BU75MF4.js +0 -87
  358. package/dist/cli-bundle/chunks/chunk-4BU75MF4.js.map +0 -7
  359. package/dist/cli-bundle/chunks/chunk-4LRVSBO6.js +0 -822
  360. package/dist/cli-bundle/chunks/chunk-4LRVSBO6.js.map +0 -7
  361. package/dist/cli-bundle/chunks/chunk-4OFLJHX6.js.map +0 -1
  362. package/dist/cli-bundle/chunks/chunk-53BTLLAF.js +0 -2181
  363. package/dist/cli-bundle/chunks/chunk-53BTLLAF.js.map +0 -1
  364. package/dist/cli-bundle/chunks/chunk-57C2RLW5.js +0 -1704
  365. package/dist/cli-bundle/chunks/chunk-57C2RLW5.js.map +0 -1
  366. package/dist/cli-bundle/chunks/chunk-5B3X4Y22.js +0 -2330
  367. package/dist/cli-bundle/chunks/chunk-5B3X4Y22.js.map +0 -7
  368. package/dist/cli-bundle/chunks/chunk-5J2XPTAD.js.map +0 -7
  369. package/dist/cli-bundle/chunks/chunk-5JZ7APJU.js +0 -995
  370. package/dist/cli-bundle/chunks/chunk-5JZ7APJU.js.map +0 -1
  371. package/dist/cli-bundle/chunks/chunk-75U6M5ZD.js +0 -819
  372. package/dist/cli-bundle/chunks/chunk-75U6M5ZD.js.map +0 -1
  373. package/dist/cli-bundle/chunks/chunk-7C2O74AE.js +0 -23
  374. package/dist/cli-bundle/chunks/chunk-7C2O74AE.js.map +0 -7
  375. package/dist/cli-bundle/chunks/chunk-7EQNAZX2.js.map +0 -7
  376. package/dist/cli-bundle/chunks/chunk-7QH7DHUB.js.map +0 -1
  377. package/dist/cli-bundle/chunks/chunk-BVEUCSH2.js +0 -530
  378. package/dist/cli-bundle/chunks/chunk-BVEUCSH2.js.map +0 -7
  379. package/dist/cli-bundle/chunks/chunk-DC3QJQWI.js +0 -275
  380. package/dist/cli-bundle/chunks/chunk-DC3QJQWI.js.map +0 -7
  381. package/dist/cli-bundle/chunks/chunk-DRBV5UC2.js +0 -231
  382. package/dist/cli-bundle/chunks/chunk-DRBV5UC2.js.map +0 -7
  383. package/dist/cli-bundle/chunks/chunk-E2FUG6GD.js +0 -2184
  384. package/dist/cli-bundle/chunks/chunk-E2FUG6GD.js.map +0 -7
  385. package/dist/cli-bundle/chunks/chunk-EZFKWSC7.js +0 -1615
  386. package/dist/cli-bundle/chunks/chunk-EZFKWSC7.js.map +0 -7
  387. package/dist/cli-bundle/chunks/chunk-FJRKQREY.js +0 -228
  388. package/dist/cli-bundle/chunks/chunk-FJRKQREY.js.map +0 -1
  389. package/dist/cli-bundle/chunks/chunk-GIWXVMZ3.js +0 -3237
  390. package/dist/cli-bundle/chunks/chunk-GIWXVMZ3.js.map +0 -7
  391. package/dist/cli-bundle/chunks/chunk-HK72NWAD.js +0 -1570
  392. package/dist/cli-bundle/chunks/chunk-HK72NWAD.js.map +0 -1
  393. package/dist/cli-bundle/chunks/chunk-JFCVQXZX.js +0 -3206
  394. package/dist/cli-bundle/chunks/chunk-JFCVQXZX.js.map +0 -1
  395. package/dist/cli-bundle/chunks/chunk-JINYH2DB.js +0 -371
  396. package/dist/cli-bundle/chunks/chunk-JINYH2DB.js.map +0 -7
  397. package/dist/cli-bundle/chunks/chunk-JLA7EVYV.js.map +0 -1
  398. package/dist/cli-bundle/chunks/chunk-K32L7HZO.js +0 -76
  399. package/dist/cli-bundle/chunks/chunk-K32L7HZO.js.map +0 -1
  400. package/dist/cli-bundle/chunks/chunk-KDZ6K25I.js +0 -79
  401. package/dist/cli-bundle/chunks/chunk-KDZ6K25I.js.map +0 -7
  402. package/dist/cli-bundle/chunks/chunk-KL22PY6L.js +0 -915
  403. package/dist/cli-bundle/chunks/chunk-KL22PY6L.js.map +0 -1
  404. package/dist/cli-bundle/chunks/chunk-KLG4ZULO.js +0 -218
  405. package/dist/cli-bundle/chunks/chunk-KLG4ZULO.js.map +0 -7
  406. package/dist/cli-bundle/chunks/chunk-LEKT4K7I.js.map +0 -7
  407. package/dist/cli-bundle/chunks/chunk-MNZ7DRNC.js +0 -1858
  408. package/dist/cli-bundle/chunks/chunk-MNZ7DRNC.js.map +0 -1
  409. package/dist/cli-bundle/chunks/chunk-MTTXDAK4.js.map +0 -7
  410. package/dist/cli-bundle/chunks/chunk-MZ7VNEVY.js +0 -520
  411. package/dist/cli-bundle/chunks/chunk-MZ7VNEVY.js.map +0 -1
  412. package/dist/cli-bundle/chunks/chunk-N7X4WP6L.js +0 -1041
  413. package/dist/cli-bundle/chunks/chunk-N7X4WP6L.js.map +0 -7
  414. package/dist/cli-bundle/chunks/chunk-NBFCNJ7Q.js.map +0 -1
  415. package/dist/cli-bundle/chunks/chunk-NNHHXJB2.js +0 -20
  416. package/dist/cli-bundle/chunks/chunk-NNHHXJB2.js.map +0 -1
  417. package/dist/cli-bundle/chunks/chunk-OBA2WH65.js +0 -918
  418. package/dist/cli-bundle/chunks/chunk-OBA2WH65.js.map +0 -7
  419. package/dist/cli-bundle/chunks/chunk-OESSOFJ4.js +0 -1985
  420. package/dist/cli-bundle/chunks/chunk-OESSOFJ4.js.map +0 -7
  421. package/dist/cli-bundle/chunks/chunk-OK5NXCZB.js +0 -238
  422. package/dist/cli-bundle/chunks/chunk-OK5NXCZB.js.map +0 -1
  423. package/dist/cli-bundle/chunks/chunk-P5YORJRH.js +0 -1977
  424. package/dist/cli-bundle/chunks/chunk-P5YORJRH.js.map +0 -7
  425. package/dist/cli-bundle/chunks/chunk-PPAJG4GB.js +0 -1031
  426. package/dist/cli-bundle/chunks/chunk-PPAJG4GB.js.map +0 -1
  427. package/dist/cli-bundle/chunks/chunk-PPE4YUQM.js.map +0 -1
  428. package/dist/cli-bundle/chunks/chunk-QZ342C63.js +0 -220
  429. package/dist/cli-bundle/chunks/chunk-QZ342C63.js.map +0 -7
  430. package/dist/cli-bundle/chunks/chunk-R2EMWY7Q.js +0 -368
  431. package/dist/cli-bundle/chunks/chunk-R2EMWY7Q.js.map +0 -1
  432. package/dist/cli-bundle/chunks/chunk-S4APD35C.js.map +0 -7
  433. package/dist/cli-bundle/chunks/chunk-STPSZ2XY.js +0 -1149
  434. package/dist/cli-bundle/chunks/chunk-STPSZ2XY.js.map +0 -1
  435. package/dist/cli-bundle/chunks/chunk-T4MX77AK.js +0 -272
  436. package/dist/cli-bundle/chunks/chunk-T4MX77AK.js.map +0 -1
  437. package/dist/cli-bundle/chunks/chunk-T5Y3QSNF.js.map +0 -1
  438. package/dist/cli-bundle/chunks/chunk-TT42JUMF.js.map +0 -1
  439. package/dist/cli-bundle/chunks/chunk-UHKX7I75.js +0 -165
  440. package/dist/cli-bundle/chunks/chunk-UHKX7I75.js.map +0 -1
  441. package/dist/cli-bundle/chunks/chunk-UI5BJ6DO.js.map +0 -7
  442. package/dist/cli-bundle/chunks/chunk-US3T3W5J.js +0 -1932
  443. package/dist/cli-bundle/chunks/chunk-US3T3W5J.js.map +0 -1
  444. package/dist/cli-bundle/chunks/chunk-UZRDBL6W.js +0 -175
  445. package/dist/cli-bundle/chunks/chunk-UZRDBL6W.js.map +0 -7
  446. package/dist/cli-bundle/chunks/chunk-VY3VQ22F.js +0 -84
  447. package/dist/cli-bundle/chunks/chunk-VY3VQ22F.js.map +0 -1
  448. package/dist/cli-bundle/chunks/chunk-VZIYHZDX.js +0 -1868
  449. package/dist/cli-bundle/chunks/chunk-VZIYHZDX.js.map +0 -7
  450. package/dist/cli-bundle/chunks/chunk-WVSGSZ6J.js.map +0 -7
  451. package/dist/cli-bundle/chunks/chunk-XQCG2JGW.js +0 -1152
  452. package/dist/cli-bundle/chunks/chunk-XQCG2JGW.js.map +0 -7
  453. package/dist/cli-bundle/chunks/chunk-YD5FML7K.js.map +0 -1
  454. package/dist/cli-bundle/chunks/chunk-YSAH5FY5.js.map +0 -1
  455. package/dist/cli-bundle/chunks/chunk-YZIR4R3U.js +0 -1005
  456. package/dist/cli-bundle/chunks/chunk-YZIR4R3U.js.map +0 -7
  457. package/dist/cli-bundle/chunks/chunk-Z2CRRZYF.js +0 -215
  458. package/dist/cli-bundle/chunks/chunk-Z2CRRZYF.js.map +0 -1
  459. package/dist/cli-bundle/chunks/chunk-ZD34OFFQ.js.map +0 -7
  460. package/dist/cli-bundle/chunks/chunk-ZJB3UV5U.js +0 -2306
  461. package/dist/cli-bundle/chunks/chunk-ZJB3UV5U.js.map +0 -1
  462. package/dist/cli-bundle/chunks/chunk-ZVDL32GJ.js +0 -241
  463. package/dist/cli-bundle/chunks/chunk-ZVDL32GJ.js.map +0 -7
  464. package/dist/cli-bundle/chunks/claim-4DROPSIS.js +0 -144
  465. package/dist/cli-bundle/chunks/claim-4DROPSIS.js.map +0 -1
  466. package/dist/cli-bundle/chunks/claim-VX54TV5U.js +0 -147
  467. package/dist/cli-bundle/chunks/claim-VX54TV5U.js.map +0 -7
  468. package/dist/cli-bundle/chunks/close-OB2Y4QP5.js +0 -16
  469. package/dist/cli-bundle/chunks/config-V57QD47V.js.map +0 -1
  470. package/dist/cli-bundle/chunks/context-4OQGIPSO.js +0 -45
  471. package/dist/cli-bundle/chunks/context-WLA6IAWE.js +0 -49
  472. package/dist/cli-bundle/chunks/contracts-HXJLKCRI.js +0 -12
  473. package/dist/cli-bundle/chunks/create-WKOZKPQR.js +0 -30
  474. package/dist/cli-bundle/chunks/eval-N6UHFWVO.js +0 -288
  475. package/dist/cli-bundle/chunks/eval-N6UHFWVO.js.map +0 -7
  476. package/dist/cli-bundle/chunks/eval-PHOTWYHI.js +0 -278
  477. package/dist/cli-bundle/chunks/eval-PHOTWYHI.js.map +0 -1
  478. package/dist/cli-bundle/chunks/extension-NBAH62ML.js +0 -40
  479. package/dist/cli-bundle/chunks/extension-ZF6ZZPOU.js +0 -44
  480. package/dist/cli-bundle/chunks/gc-AETFKZ44.js +0 -398
  481. package/dist/cli-bundle/chunks/gc-AETFKZ44.js.map +0 -7
  482. package/dist/cli-bundle/chunks/gc-RLBP4QVN.js +0 -388
  483. package/dist/cli-bundle/chunks/gc-RLBP4QVN.js.map +0 -1
  484. package/dist/cli-bundle/chunks/get-NH2MPBCI.js +0 -283
  485. package/dist/cli-bundle/chunks/get-NH2MPBCI.js.map +0 -1
  486. package/dist/cli-bundle/chunks/get-P4ZQXCPZ.js +0 -286
  487. package/dist/cli-bundle/chunks/get-P4ZQXCPZ.js.map +0 -7
  488. package/dist/cli-bundle/chunks/health-3GVPMQBL.js +0 -1612
  489. package/dist/cli-bundle/chunks/health-3GVPMQBL.js.map +0 -1
  490. package/dist/cli-bundle/chunks/health-DNTM72GJ.js +0 -1615
  491. package/dist/cli-bundle/chunks/health-DNTM72GJ.js.map +0 -7
  492. package/dist/cli-bundle/chunks/history-RYKLC72X.js +0 -20
  493. package/dist/cli-bundle/chunks/history-SGPYRAFT.js +0 -24
  494. package/dist/cli-bundle/chunks/history-redact-4H3FCKF3.js +0 -21
  495. package/dist/cli-bundle/chunks/init-RPIPQUNV.js +0 -32
  496. package/dist/cli-bundle/chunks/init-SKQAESQS.js +0 -28
  497. package/dist/cli-bundle/chunks/list-64LHZ3HM.js +0 -32
  498. package/dist/cli-bundle/chunks/list-7LXBTEKI.js +0 -36
  499. package/dist/cli-bundle/chunks/next-7ODPAQ4U.js +0 -306
  500. package/dist/cli-bundle/chunks/next-7ODPAQ4U.js.map +0 -7
  501. package/dist/cli-bundle/chunks/next-ODJUM4ZM.js +0 -303
  502. package/dist/cli-bundle/chunks/next-ODJUM4ZM.js.map +0 -1
  503. package/dist/cli-bundle/chunks/profile-XQWEQKS3.js +0 -397
  504. package/dist/cli-bundle/chunks/profile-XQWEQKS3.js.map +0 -1
  505. package/dist/cli-bundle/chunks/profile-YRDHLMRO.js +0 -400
  506. package/dist/cli-bundle/chunks/profile-YRDHLMRO.js.map +0 -7
  507. package/dist/cli-bundle/chunks/register-list-query-5H66WFYF.js.map +0 -7
  508. package/dist/cli-bundle/chunks/register-list-query-FB3FNDLZ.js.map +0 -1
  509. package/dist/cli-bundle/chunks/register-operations-A3XAM5J7.js.map +0 -1
  510. package/dist/cli-bundle/chunks/register-operations-SG7HBSUP.js.map +0 -7
  511. package/dist/cli-bundle/chunks/register-setup-I45OGJUV.js.map +0 -1
  512. package/dist/cli-bundle/chunks/register-setup-K6U3NVY5.js.map +0 -7
  513. package/dist/cli-bundle/chunks/restore-PXOFL6AM.js +0 -19
  514. package/dist/cli-bundle/chunks/scheduling-shortcuts-SSC4MYWQ.js +0 -91
  515. package/dist/cli-bundle/chunks/scheduling-shortcuts-SSC4MYWQ.js.map +0 -7
  516. package/dist/cli-bundle/chunks/scheduling-shortcuts-ULRG7MNP.js +0 -88
  517. package/dist/cli-bundle/chunks/scheduling-shortcuts-ULRG7MNP.js.map +0 -1
  518. package/dist/cli-bundle/chunks/search-3S72CTD6.js +0 -38
  519. package/dist/cli-bundle/chunks/search-WNUNBQXO.js +0 -34
  520. package/dist/cli-bundle/chunks/stats-IJYTRQGV.js +0 -250
  521. package/dist/cli-bundle/chunks/stats-IJYTRQGV.js.map +0 -7
  522. package/dist/cli-bundle/chunks/stats-L2D5Y2O5.js +0 -240
  523. package/dist/cli-bundle/chunks/stats-L2D5Y2O5.js.map +0 -1
  524. package/dist/cli-bundle/chunks/telemetry-L2CVOKVN.js +0 -309
  525. package/dist/cli-bundle/chunks/telemetry-L2CVOKVN.js.map +0 -7
  526. package/dist/cli-bundle/chunks/telemetry-QBYWQA76.js +0 -306
  527. package/dist/cli-bundle/chunks/telemetry-QBYWQA76.js.map +0 -1
  528. package/dist/cli-bundle/chunks/test-DQ2QFJ7W.js +0 -45
  529. package/dist/cli-bundle/chunks/test-W7QBLVJS.js +0 -41
  530. package/dist/cli-bundle/chunks/test-all-636NTRTT.js +0 -434
  531. package/dist/cli-bundle/chunks/test-all-636NTRTT.js.map +0 -1
  532. package/dist/cli-bundle/chunks/test-all-DWYK3RG6.js +0 -437
  533. package/dist/cli-bundle/chunks/test-all-DWYK3RG6.js.map +0 -7
  534. package/dist/cli-bundle/chunks/test-runs-245OINZR.js +0 -28
  535. package/dist/cli-bundle/chunks/test-runs-ZRD4GCTT.js +0 -24
  536. package/dist/cli-bundle/chunks/update-SFLZPJXX.js +0 -30
  537. package/dist/cli-bundle/chunks/update-SJZ6S77U.js +0 -26
  538. package/dist/cli-bundle/chunks/upgrade-HFFXLZJA.js +0 -290
  539. package/dist/cli-bundle/chunks/upgrade-HFFXLZJA.js.map +0 -7
  540. package/dist/cli-bundle/chunks/upgrade-UYQKM7RF.js +0 -287
  541. package/dist/cli-bundle/chunks/upgrade-UYQKM7RF.js.map +0 -1
  542. package/dist/cli-bundle/chunks/validate-PA4FDTOV.js +0 -2143
  543. package/dist/cli-bundle/chunks/validate-PA4FDTOV.js.map +0 -7
  544. package/dist/cli-bundle/chunks/validate-Z7L75YEJ.js +0 -2105
  545. package/dist/cli-bundle/chunks/validate-Z7L75YEJ.js.map +0 -1
  546. /package/dist/cli-bundle/chunks/{activity-4XQIDNM5.js.map → append-F7WPGIQL.js.map} +0 -0
  547. /package/dist/cli-bundle/chunks/{activity-YKAKZTZ4.js.map → append-PVCTBVJG.js.map} +0 -0
  548. /package/dist/cli-bundle/chunks/{chunk-T3ABIMGW.js.map → chunk-2TILG6F2.js.map} +0 -0
  549. /package/dist/cli-bundle/chunks/{chunk-RCT3YJOK.js.map → chunk-3TYOW6RR.js.map} +0 -0
  550. /package/dist/cli-bundle/chunks/{chunk-3JZNEQBA.js.map → chunk-3X542TEY.js.map} +0 -0
  551. /package/dist/cli-bundle/chunks/{chunk-YOF5VPKM.js.map → chunk-7VQ3JJN5.js.map} +0 -0
  552. /package/dist/cli-bundle/chunks/{chunk-P5TFTLWW.js.map → chunk-AGAVEDIE.js.map} +0 -0
  553. /package/dist/cli-bundle/chunks/{chunk-YFIE7YK6.js.map → chunk-AJUON7E6.js.map} +0 -0
  554. /package/dist/cli-bundle/chunks/{chunk-7WYXBPYQ.js.map → chunk-DR2V5OIV.js.map} +0 -0
  555. /package/dist/cli-bundle/chunks/{chunk-PDXT6Q55.js.map → chunk-EDO7VXSO.js.map} +0 -0
  556. /package/dist/cli-bundle/chunks/{chunk-FUM6UMY4.js.map → chunk-EVEPHNXJ.js.map} +0 -0
  557. /package/dist/cli-bundle/chunks/{chunk-RX3HQSYG.js.map → chunk-FN6SB4HU.js.map} +0 -0
  558. /package/dist/cli-bundle/chunks/{chunk-DLQ4ZTCU.js.map → chunk-H2SMKL2N.js.map} +0 -0
  559. /package/dist/cli-bundle/chunks/{chunk-C3PMDWGX.js.map → chunk-HX6QXV5P.js.map} +0 -0
  560. /package/dist/cli-bundle/chunks/{chunk-N6DNM2FA.js.map → chunk-P3MJJW7P.js.map} +0 -0
  561. /package/dist/cli-bundle/chunks/{chunk-5JE6SMYS.js.map → chunk-PDXJXEZJ.js.map} +0 -0
  562. /package/dist/cli-bundle/chunks/{chunk-AAEQMOC6.js.map → chunk-TEKZOS7M.js.map} +0 -0
  563. /package/dist/cli-bundle/chunks/{chunk-NER3KUUS.js.map → chunk-VLEA2UTQ.js.map} +0 -0
  564. /package/dist/cli-bundle/chunks/{chunk-ZMD35NYG.js.map → chunk-WCWVEXGA.js.map} +0 -0
  565. /package/dist/cli-bundle/chunks/{chunk-T35XLYZF.js.map → chunk-YPMZMKN7.js.map} +0 -0
  566. /package/dist/cli-bundle/chunks/{chunk-R3ZBLGTC.js.map → chunk-YTD5GICJ.js.map} +0 -0
  567. /package/dist/cli-bundle/chunks/{chunk-EEY54JMF.js.map → chunk-ZO7CLOY2.js.map} +0 -0
  568. /package/dist/cli-bundle/chunks/{close-3YRR3XY6.js.map → close-3YYQ5OG2.js.map} +0 -0
  569. /package/dist/cli-bundle/chunks/{close-OB2Y4QP5.js.map → close-Z3Q4U7TS.js.map} +0 -0
  570. /package/dist/cli-bundle/chunks/{context-4OQGIPSO.js.map → close-many-3L2RXH3M.js.map} +0 -0
  571. /package/dist/cli-bundle/chunks/{context-WLA6IAWE.js.map → close-many-D366FTIG.js.map} +0 -0
  572. /package/dist/cli-bundle/chunks/{contracts-OJEXMKVW.js.map → comments-54XDJNFE.js.map} +0 -0
  573. /package/dist/cli-bundle/chunks/{contracts-HXJLKCRI.js.map → comments-HGHC2PN6.js.map} +0 -0
  574. /package/dist/cli-bundle/chunks/{create-XWWQFQ6S.js.map → copy-44RT5GDW.js.map} +0 -0
  575. /package/dist/cli-bundle/chunks/{create-WKOZKPQR.js.map → copy-UGMUGHZA.js.map} +0 -0
  576. /package/dist/cli-bundle/chunks/{extension-ZF6ZZPOU.js.map → create-4GWJWPXG.js.map} +0 -0
  577. /package/dist/cli-bundle/chunks/{extension-NBAH62ML.js.map → create-AZXCUYKP.js.map} +0 -0
  578. /package/dist/cli-bundle/chunks/{history-RYKLC72X.js.map → delete-Y6SXIQ4X.js.map} +0 -0
  579. /package/dist/cli-bundle/chunks/{history-SGPYRAFT.js.map → delete-YQ2VPXNF.js.map} +0 -0
  580. /package/dist/cli-bundle/chunks/{history-redact-54ICFKXM.js.map → deps-BU5EBJDU.js.map} +0 -0
  581. /package/dist/cli-bundle/chunks/{history-redact-4H3FCKF3.js.map → deps-FMANWFRP.js.map} +0 -0
  582. /package/dist/cli-bundle/chunks/{init-RPIPQUNV.js.map → docs-OQBSJNIA.js.map} +0 -0
  583. /package/dist/cli-bundle/chunks/{init-SKQAESQS.js.map → docs-VNPBZXEL.js.map} +0 -0
  584. /package/dist/cli-bundle/chunks/{list-64LHZ3HM.js.map → files-72HZEBOE.js.map} +0 -0
  585. /package/dist/cli-bundle/chunks/{list-7LXBTEKI.js.map → files-HTSB2KJG.js.map} +0 -0
  586. /package/dist/cli-bundle/chunks/{restore-YJ2ET6AT.js.map → focus-FOG4ALC2.js.map} +0 -0
  587. /package/dist/cli-bundle/chunks/{restore-PXOFL6AM.js.map → focus-SUTMKXGX.js.map} +0 -0
  588. /package/dist/cli-bundle/chunks/{schema-Y6DXXK2F.js.map → history-compact-M6IFAMBP.js.map} +0 -0
  589. /package/dist/cli-bundle/chunks/{schema-2PUXCZ25.js.map → history-compact-NEXRPP2O.js.map} +0 -0
  590. /package/dist/cli-bundle/chunks/{search-3S72CTD6.js.map → history-redact-NQX3OGZP.js.map} +0 -0
  591. /package/dist/cli-bundle/chunks/{search-WNUNBQXO.js.map → history-redact-WQJBZ3PX.js.map} +0 -0
  592. /package/dist/cli-bundle/chunks/{test-W7QBLVJS.js.map → history-repair-CBHMHAJO.js.map} +0 -0
  593. /package/dist/cli-bundle/chunks/{test-DQ2QFJ7W.js.map → history-repair-NHOJG7WO.js.map} +0 -0
  594. /package/dist/cli-bundle/chunks/{test-runs-ZRD4GCTT.js.map → learnings-M64NTSOR.js.map} +0 -0
  595. /package/dist/cli-bundle/chunks/{test-runs-245OINZR.js.map → learnings-T63JGKKN.js.map} +0 -0
  596. /package/dist/cli-bundle/chunks/{update-SJZ6S77U.js.map → notes-73WE2UV2.js.map} +0 -0
  597. /package/dist/cli-bundle/chunks/{update-SFLZPJXX.js.map → notes-U7L6HQQ2.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../../core/packages/manifest.ts", "../../../../../../../../cli/commands/extension/scaffold.ts", "../../../../../../../../cli/commands/extension/describe.ts", "../../../../../../../../cli/commands/extension.ts", "../../../../../../../../cli/commands/extension/managed-state.ts", "../../../../../../../../cli/commands/extension/install-sources.ts", "../../../../../../../../cli/commands/extension/bundled-catalog.ts", "../../../../../../../../cli/commands/extension/doctor.ts", "../../../../../../../../cli/commands/init.ts", "../../../../../../../../cli/commands/init-agent-guidance.ts"],
4
+ "sourcesContent": ["/**\n * @module core/packages/manifest\n *\n * Discovers and validates pm package manifests for Manifest.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathExists } from \"../fs/fs-utils.js\";\nimport { isPathWithinDirectory } from \"../fs/path-utils.js\";\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\n\nexport const PM_PACKAGE_RESOURCE_KINDS = [\n \"extensions\",\n \"docs\",\n \"examples\",\n \"assets\",\n \"prompts\",\n] as const;\n\n/**\n * Restricts pm package resource kind values accepted by command, SDK, and storage contracts.\n */\nexport type PmPackageResourceKind = (typeof PM_PACKAGE_RESOURCE_KINDS)[number];\n\n/**\n * Restricts pm package resource map values accepted by command, SDK, and storage contracts.\n */\nexport type PmPackageResourceMap = Partial<Record<PmPackageResourceKind, string[]>>;\n\n/**\n * Documents the pm package catalog link map payload exchanged by command, SDK, and package integrations.\n */\nexport interface PmPackageCatalogLinkMap {\n docs?: string;\n npm?: string;\n repository?: string;\n report?: string;\n}\n\n/**\n * Documents the pm package catalog media map payload exchanged by command, SDK, and package integrations.\n */\nexport interface PmPackageCatalogMediaMap {\n image?: string;\n video?: string;\n}\n\n/**\n * Documents the pm package catalog metadata payload exchanged by command, SDK, and package integrations.\n */\nexport interface PmPackageCatalogMetadata {\n display_name?: string;\n category?: string;\n summary?: string;\n links?: PmPackageCatalogLinkMap;\n media?: PmPackageCatalogMediaMap;\n tags?: string[];\n}\n\n/**\n * Documents the pm package manifest payload exchanged by command, SDK, and package integrations.\n */\nexport interface PmPackageManifest {\n source: \"pm\" | \"convention\";\n package_json_path?: string;\n package_name?: string;\n package_version?: string;\n package_private?: boolean;\n package_description?: string;\n package_keywords?: string[];\n package_homepage?: string;\n package_repository_url?: string;\n package_bugs_url?: string;\n aliases?: string[];\n resources: PmPackageResourceMap;\n catalog?: PmPackageCatalogMetadata;\n}\n\nexport const PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS: Readonly<Record<PmPackageResourceKind, readonly string[]>> =\n Object.freeze({\n extensions: Object.freeze([\n \".agents/pm/extensions\",\n \"extensions\",\n \".custom/pm-extensions\",\n \".custom/pm-extension\",\n ]),\n docs: Object.freeze([\n \"docs\",\n \"documentation\",\n ]),\n examples: Object.freeze([\n \"examples\",\n \"docs/examples\",\n ]),\n assets: Object.freeze([\n \"assets\",\n \".agents/pm/assets\",\n ]),\n prompts: Object.freeze([\n \"prompts\",\n \".agents/pm/prompts\",\n ]),\n });\n\nfunction isKnownPackageResourceKind(value: string): value is PmPackageResourceKind {\n return (PM_PACKAGE_RESOURCE_KINDS as readonly string[]).includes(value);\n}\n\nfunction normalizePackageResourceEntries(kind: PmPackageResourceKind, raw: unknown): string[] {\n if (raw === undefined || raw === null) {\n return [];\n }\n const entries = Array.isArray(raw) ? raw : [raw];\n const normalized: string[] = [];\n for (const entry of entries) {\n if (typeof entry !== \"string\" || entry.trim().length === 0) {\n throw new PmCliError(`Package manifest field pm.${kind} must contain string paths.`, EXIT_CODE.USAGE);\n }\n normalized.push(entry.trim());\n }\n return [...new Set(normalized)].sort((left, right) => left.localeCompare(right));\n}\n\nfunction normalizePackageResourceMap(raw: unknown): PmPackageResourceMap {\n if (raw === undefined || raw === null) {\n return {};\n }\n if (typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new PmCliError(\"Package manifest field pm must be an object.\", EXIT_CODE.USAGE);\n }\n const resources: PmPackageResourceMap = {};\n const candidate = raw as Record<string, unknown>;\n for (const [key, value] of Object.entries(candidate)) {\n if (!isKnownPackageResourceKind(key)) {\n continue;\n }\n const entries = normalizePackageResourceEntries(key, value);\n if (entries.length > 0) {\n resources[key] = entries;\n }\n }\n return resources;\n}\n\nfunction readStringField(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key];\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction normalizeStringArray(raw: unknown): string[] | undefined {\n if (!Array.isArray(raw)) {\n return undefined;\n }\n const values = raw\n .map((value) => typeof value === \"string\" ? value.trim() : \"\")\n .filter((value) => value.length > 0);\n return values.length > 0 ? [...new Set(values)].sort((left, right) => left.localeCompare(right)) : undefined;\n}\n\nfunction readUrlLikeField(raw: unknown): string | undefined {\n if (typeof raw === \"string\" && raw.trim().length > 0) {\n return raw.trim();\n }\n if (typeof raw === \"object\" && raw !== null && !Array.isArray(raw)) {\n const value = (raw as Record<string, unknown>).url;\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n }\n return undefined;\n}\n\nfunction normalizeCatalogLinks(raw: unknown): PmPackageCatalogLinkMap | undefined {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return undefined;\n }\n const source = raw as Record<string, unknown>;\n const links: PmPackageCatalogLinkMap = {\n docs: readStringField(source, \"docs\"),\n npm: readStringField(source, \"npm\"),\n repository: readStringField(source, \"repository\"),\n report: readStringField(source, \"report\"),\n };\n return Object.values(links).some((value) => typeof value === \"string\") ? links : undefined;\n}\n\nfunction normalizeCatalogMedia(raw: unknown): PmPackageCatalogMediaMap | undefined {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return undefined;\n }\n const source = raw as Record<string, unknown>;\n const media: PmPackageCatalogMediaMap = {\n image: readStringField(source, \"image\"),\n video: readStringField(source, \"video\"),\n };\n return Object.values(media).some((value) => typeof value === \"string\") ? media : undefined;\n}\n\nfunction normalizePackageCatalogMetadata(raw: unknown): PmPackageCatalogMetadata | undefined {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return undefined;\n }\n const source = raw as Record<string, unknown>;\n const catalog: PmPackageCatalogMetadata = {\n display_name: readStringField(source, \"display_name\") ?? readStringField(source, \"displayName\"),\n category: readStringField(source, \"category\"),\n summary: readStringField(source, \"summary\"),\n links: normalizeCatalogLinks(source.links),\n media: normalizeCatalogMedia(source.media),\n tags: normalizeStringArray(source.tags),\n };\n return Object.values(catalog).some((value) => value !== undefined) ? catalog : undefined;\n}\n\n/**\n * Implements read pm package manifest for the public runtime surface of this module.\n */\nexport async function readPmPackageManifest(packageRoot: string): Promise<PmPackageManifest> {\n const packageJsonPath = path.join(packageRoot, \"package.json\");\n if (!(await pathExists(packageJsonPath))) {\n return {\n source: \"convention\",\n resources: {},\n };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\")) as unknown;\n } catch (error: unknown) {\n throw new PmCliError(\n `Failed to parse package manifest at \"${packageJsonPath}\": ${String(error)}`,\n EXIT_CODE.USAGE,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new PmCliError(`Package manifest at \"${packageJsonPath}\" must be a JSON object.`, EXIT_CODE.USAGE);\n }\n\n const packageJson = parsed as Record<string, unknown>;\n const pmManifest = packageJson.pm;\n const hasPmManifest = pmManifest !== undefined && pmManifest !== null;\n const pmManifestRecord = typeof pmManifest === \"object\" && pmManifest !== null && !Array.isArray(pmManifest)\n ? pmManifest as Record<string, unknown>\n : {};\n return {\n source: hasPmManifest ? \"pm\" : \"convention\",\n package_json_path: packageJsonPath,\n package_name: typeof packageJson.name === \"string\" ? packageJson.name : undefined,\n package_version: typeof packageJson.version === \"string\" ? packageJson.version : undefined,\n package_private: packageJson.private === true,\n package_description: typeof packageJson.description === \"string\" ? packageJson.description : undefined,\n package_keywords: normalizeStringArray(packageJson.keywords),\n package_homepage: typeof packageJson.homepage === \"string\" ? packageJson.homepage : undefined,\n package_repository_url: readUrlLikeField(packageJson.repository),\n package_bugs_url: readUrlLikeField(packageJson.bugs),\n aliases: normalizeStringArray(pmManifestRecord.aliases),\n resources: normalizePackageResourceMap(pmManifest),\n catalog: normalizePackageCatalogMetadata(pmManifestRecord.catalog),\n };\n}\n\nasync function listExtensionManifestDirectories(parentDirectory: string): Promise<string[]> {\n if (!(await pathExists(parentDirectory))) {\n return [];\n }\n const entries = await fs.readdir(parentDirectory, { withFileTypes: true });\n const candidates: string[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) {\n continue;\n }\n const directory = path.join(parentDirectory, entry.name);\n if (await pathExists(path.join(directory, \"manifest.json\"))) {\n candidates.push(directory);\n }\n }\n return candidates.sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Implements collect package extension directories for the public runtime surface of this module.\n */\nexport async function collectPackageExtensionDirectories(packageRoot: string): Promise<string[]> {\n if (await pathExists(path.join(packageRoot, \"manifest.json\"))) {\n return [packageRoot];\n }\n\n const manifest = await readPmPackageManifest(packageRoot);\n const manifestEntries = manifest.resources.extensions ?? [];\n const discovered = new Set<string>();\n\n for (const entry of manifestEntries) {\n if (entry.includes(\"*\") || entry.startsWith(\"!\")) {\n throw new PmCliError(\n `Package extension entry \"${entry}\" uses a glob/exclusion pattern. pm package installs currently require concrete extension paths or directories.`,\n EXIT_CODE.USAGE,\n );\n }\n const absolute = path.resolve(packageRoot, entry);\n if (!isPathWithinDirectory(packageRoot, absolute)) {\n throw new PmCliError(`Package extension entry \"${entry}\" resolves outside package root.`, EXIT_CODE.USAGE);\n }\n if (await pathExists(path.join(absolute, \"manifest.json\"))) {\n discovered.add(absolute);\n continue;\n }\n for (const child of await listExtensionManifestDirectories(absolute)) {\n discovered.add(child);\n }\n }\n\n if (manifestEntries.length === 0) {\n for (const root of PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS.extensions) {\n for (const child of await listExtensionManifestDirectories(path.join(packageRoot, root))) {\n discovered.add(child);\n }\n }\n }\n\n return [...discovered].sort((left, right) => left.localeCompare(right));\n}\n", "/**\n * @module cli/commands/extension/scaffold\n *\n * Implements extension package-management support for Scaffold.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { EXECUTABLE_COMMAND_ALIASES } from \"../../bootstrap-args.js\";\nimport { pathExists } from \"../../../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../../../core/shared/constants.js\";\nimport { PmCliError } from \"../../../core/shared/errors.js\";\nimport { PM_CORE_COMMAND_NAMES } from \"../../../sdk/cli-contracts.js\";\nimport { normalizeManagedDirectoryName } from \"./shared.js\";\n\n// Safe compatibility floor emitted into scaffolded manifests. The current\n// starters are loaded as TypeScript and use the SDK define*/testing helpers; the\n// first released host that supports that full generated contract is v2026.6.24.\n// manifest_version tracks the manifest schema generation (currently 1).\nconst SCAFFOLD_MANIFEST_VERSION = 1;\nexport const SCAFFOLD_PM_MIN_VERSION = \"2026.6.24\";\nconst SCAFFOLD_NODE_ENGINE = \">=22.18.0\";\nconst SCAFFOLD_DECLARED_PERMISSIONS = {\n fs_read: false,\n fs_write: false,\n network: false,\n env_read: false,\n env_write: false,\n process_spawn: false,\n};\n\nconst RESERVED_SCAFFOLD_COMMAND_ROOTS = new Set([\n ...PM_CORE_COMMAND_NAMES.map((commandName) => commandName.split(\"-\")[0]!.toLowerCase()),\n ...Object.keys(EXECUTABLE_COMMAND_ALIASES).map((alias) => alias.toLowerCase()),\n // \"scaffold\" is a Commander command that currently lives outside both\n // PM_CORE_COMMAND_NAMES and EXECUTABLE_COMMAND_ALIASES.\n \"scaffold\",\n]);\n\n// TypeScript dev-dependency floor for scaffolded packages, matching the CLI's own\n// toolchain so generated packages compile against the same compiler generation.\nconst SCAFFOLD_TYPESCRIPT_VERSION = \"^6.0.0\";\n\n// `@types/node` floor for scaffolded packages: the colocated `index.test.ts`\n// imports `node:test`/`node:assert`, which need Node's ambient type definitions\n// to type-check. Pinned to the engines floor (Node >=22.18), matching the CLI\n// itself — the version where Node strips TypeScript types on load by default.\nconst SCAFFOLD_TYPES_NODE_VERSION = \"^22.0.0\";\n\nconst SAMPLE_HARNESS_CLEANUP_LINES = [\n \"type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;\",\n \"\",\n \"async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {\",\n \" if (!deactivated) {\",\n \" try {\",\n \" await ext.deactivate();\",\n \" } catch {\",\n \" // Preserve the original assertion error; cleanup is best effort.\",\n \" }\",\n \" }\",\n \"}\",\n \"\",\n] as const;\n\nconst SAMPLE_HARNESS_FINALLY_LINES = [\n \" } finally {\",\n \" await deactivateIfNeeded(ext, deactivated);\",\n \" }\",\n] as const;\n\nfunction indentGeneratedLines(lines: readonly string[], prefix: string): string[] {\n return lines.map((line) => (line === \"\" ? line : `${prefix}${line}`));\n}\n\nfunction buildSchemaCapabilityAssertionLines(options: {\n readonly extensionName: string;\n readonly itemTypeName: string;\n readonly itemTypeFolder: string;\n readonly fieldName: string;\n readonly migrationId: string;\n readonly includeMigrationReplacementHint?: boolean;\n}): string[] {\n const migrationHint = options.includeMigrationReplacementHint === true ? [\" // as your migration grows.\"] : [];\n return [\n \" // assertItemType/Field/Migration throw unless the registration is present, so\",\n \" // reaching each next line already proves the wiring; assert on the returned\",\n \" // definitions to demonstrate inspecting registered metadata.\",\n ` const itemType = ext.assertItemType({ itemType: ${JSON.stringify(options.itemTypeName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,\n ` assert.equal(itemType.itemType.folder, ${JSON.stringify(options.itemTypeFolder)});`,\n ` const itemField = ext.assertItemField({ field: ${JSON.stringify(options.fieldName)}, extensionName: ${JSON.stringify(options.extensionName)} });`,\n ' assert.equal(itemField.field.type, \"string\");',\n ` ext.assertMigration({ migration: ${JSON.stringify(options.migrationId)}, extensionName: ${JSON.stringify(options.extensionName)}, mandatory: false });`,\n \"\",\n \" // runMigration invokes the migration through pm's real runner with a synthetic\",\n \" // context and returns its result.\",\n ...migrationHint,\n ` const migrated = await ext.runMigration({ migration: ${JSON.stringify(options.migrationId)} });`,\n ` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(options.migrationId)} });`,\n ];\n}\n\nfunction buildProfileCapabilityAssertionLines(extensionName: string): string[] {\n return [\n \" // assertProfile throws unless the profile is registered, so reaching the next\",\n \" // line already proves the wiring; assert on the returned definition to inspect\",\n \" // the bundled archetype dimensions.\",\n ` const { profile } = ext.assertProfile({ profile: ${JSON.stringify(extensionName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n ` assert.equal(profile.title, ${JSON.stringify(`${extensionName} archetype`)});`,\n \" assert.equal(profile.types.length, 1);\",\n \" assert.equal(profile.workflows.length, 1);\",\n ];\n}\n\n// Strict NodeNext tsconfig emitted into every scaffold (ADR pm-2c28 / pm-m1uz:\n// extensions are authored AND loaded as TypeScript). It is a type-check-only\n// config (`noEmit`): there is no compile step — pm loads the `./index.ts`\n// manifest entry directly via Node's native type stripping (Node >=22.18), so\n// no `.js` is emitted or committed. `allowImportingTsExtensions` lets the\n// colocated `index.test.ts` import the sibling `./index.ts` entry with its real\n// extension, exactly as Node resolves it at load time. NodeNext resolution keeps\n// the module graph identical to the runtime loader.\nconst SCAFFOLD_TSCONFIG = {\n compilerOptions: {\n target: \"ES2022\",\n module: \"NodeNext\",\n moduleResolution: \"NodeNext\",\n strict: true,\n esModuleInterop: true,\n skipLibCheck: true,\n noEmit: true,\n allowImportingTsExtensions: true,\n // `node:test`/`node:assert` in the colocated test (and Node globals) resolve\n // from `@types/node`; name it explicitly so it is loaded regardless of how the\n // package manager lays out `node_modules/@types`.\n types: [\"node\"],\n },\n // Recursive so a package that grows into subdirectory `*.ts` modules still\n // type-checks; tsc excludes `node_modules` by default.\n include: [\"**/*.ts\"],\n};\n\n/**\n * Capability shapes the package/extension scaffolder can target via the\n * `--capability` selector — one per SDK extension capability, so every\n * registration surface has a runnable starter. `commands` emits the default\n * command-only starter; `hooks` additionally wires an `after_command` lifecycle\n * reactor; `search` wires an in-memory provider/adapter pair; `importers` wires\n * importer and exporter command primitives so authors can customize project\n * context movement; `schema` registers a custom item type, item field, and\n * migration so authors can model their own project domain; `profile` registers a\n * complete project-profile archetype (item types, statuses, fields, a workflow,\n * config, a template, and package recommendations) via `api.registerProfile` so\n * `pm profile apply` can tailor a tracker in one shot; `renderers` overrides how\n * a command's output is serialized for a format; `parser` rewrites a command's\n * parsed options before its handler runs; `preflight` adjusts pm's pre-run\n * migration/format gate decision; and `services` overrides a built-in pm service\n * (e.g. output formatting) — without starting from a blank extension.\n */\nexport const SCAFFOLD_CAPABILITIES = [\n \"commands\",\n \"hooks\",\n \"search\",\n \"importers\",\n \"schema\",\n \"profile\",\n \"renderers\",\n \"parser\",\n \"preflight\",\n \"services\",\n] as const;\n\n/**\n * Restricts the `--capability` selector to a {@link SCAFFOLD_CAPABILITIES} value.\n */\nexport type ExtensionScaffoldCapability = (typeof SCAFFOLD_CAPABILITIES)[number];\n\nconst SCAFFOLD_MANIFEST_CAPABILITIES: Record<ExtensionScaffoldCapability, readonly string[]> = {\n commands: [\"commands\"],\n hooks: [\"commands\", \"hooks\"],\n search: [\"commands\", \"search\"],\n importers: [\"commands\", \"schema\", \"importers\"],\n schema: [\"commands\", \"schema\"],\n // A profile registration IS a schema+config bundle, so the loader gate requires\n // the `schema` capability (no separate `profile` capability) — same grant as the\n // schema starter, mirroring the bundled pm-kanban exemplar.\n profile: [\"commands\", \"schema\"],\n renderers: [\"commands\", \"renderers\"],\n // The parser starter declares `--shout`/`--upper` command flags so the\n // override is runnable through `pm <command> --shout`; flag metadata is\n // schema-governed, so the manifest also declares `schema`.\n parser: [\"commands\", \"parser\", \"schema\"],\n preflight: [\"commands\", \"preflight\"],\n services: [\"commands\", \"services\"],\n};\n\nconst SAMPLE_TEST_CAPABILITIES_LITERAL: Record<ExtensionScaffoldCapability, string> = {\n commands: '[\"commands\"]',\n hooks: '[\"commands\", \"hooks\"]',\n search: '[\"commands\", \"search\"]',\n importers: '[\"commands\", \"schema\", \"importers\"]',\n schema: '[\"commands\", \"schema\"]',\n profile: '[\"commands\", \"schema\"]',\n renderers: '[\"commands\", \"renderers\"]',\n parser: '[\"commands\", \"parser\", \"schema\"]',\n preflight: '[\"commands\", \"preflight\"]',\n services: '[\"commands\", \"services\"]',\n};\n\nconst ENTRYPOINT_BULLETS: Record<ExtensionScaffoldCapability, string> = {\n commands: \"- `index.ts`: the TypeScript manifest entry — starter command registration plus a `deactivate` teardown stub.\",\n hooks:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.\",\n search:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.\",\n importers:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.\",\n schema:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.\",\n profile:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.\",\n renderers:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.\",\n parser:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.\",\n preflight:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.\",\n services:\n \"- `index.ts`: the TypeScript manifest entry — starter command registration, an `output_format` service override, and a `deactivate` teardown stub.\",\n};\n\nconst SAMPLE_TEST_BULLETS: Record<ExtensionScaffoldCapability, string> = {\n commands:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.\",\n hooks:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.\",\n search:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.\",\n importers:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.\",\n schema:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.\",\n profile:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.\",\n renderers:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.\",\n parser:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.\",\n preflight:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.\",\n services:\n \"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers.\",\n};\n\nconst TSCONFIG_BULLET = \"- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.\";\n\nconst PACKAGE_CAPABILITY_README_SECTIONS: Record<ExtensionScaffoldCapability, readonly string[]> = {\n commands: [],\n hooks: [\n \"\",\n \"## Lifecycle Hook\",\n \"`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.\",\n \"pm fires it once a command finishes, passing the command outcome and the\",\n \"items it mutated (`context.affected`). React there to keep external context\",\n \"in sync - sync records, emit telemetry, or refresh derived state. The\",\n \"`hooks` capability in `manifest.json` is what grants the hook registration;\",\n \"remove it (and the hook) if your package only needs commands.\",\n ],\n search: [\n \"\",\n \"## Search Provider\",\n \"`index.ts` registers a deterministic in-memory search provider and\",\n \"vector-store adapter through `api.registerSearchProvider` and\",\n \"`api.registerVectorStoreAdapter`. Replace the sample scoring,\",\n \"embedding, and storage behavior with your project-specific retrieval\",\n \"logic. The `search` capability in `manifest.json` grants both\",\n \"registrations.\",\n ],\n importers: [\n \"\",\n \"## Importer and Exporter\",\n \"`index.ts` registers paired project-context import/export commands through\",\n \"`api.registerImporter` and `api.registerExporter`. Replace the starter\",\n \"payloads with your domain adapter: GitHub issues, CSV rows, documents,\",\n \"tickets, or another project-management source of truth. The `importers`\",\n \"capability grants both registrations, and `schema` grants the example\",\n \"command flag metadata.\",\n ],\n schema: [\n \"\",\n \"## Custom Schema\",\n \"`index.ts` models a project domain by registering a custom item type, a\",\n \"custom item field, and a schema migration through `api.registerItemTypes`,\",\n \"`api.registerItemFields`, and `api.registerMigration`. This is how a package\",\n \"turns pm into a domain-specific tracker — `project management = context\",\n \"management`. Replace the sample type/field/migration with your own domain\",\n \"model; the `schema` capability in `manifest.json` grants all three\",\n \"registrations. Once installed, the custom type is usable everywhere, e.g.\",\n \"`pm create <type> \\\"<title>\\\"` and `pm list --type <type>`.\",\n ],\n profile: [\n \"\",\n \"## Project Profile\",\n \"`index.ts` registers a complete project-profile archetype through\",\n \"`api.registerProfile`. A profile is the broadest customization primitive pm\",\n \"has — one declarative bundle of item types, custom statuses, fields, a per-type\",\n \"workflow, config knobs, create templates, and package recommendations. Once the\",\n \"package is installed the profile resolves by name through `pm profile list`,\",\n \"`pm profile show <name>`, and `pm profile apply <name>`, which stages every\",\n \"dimension idempotently — exactly like a core archetype (agile/ops/research),\",\n \"with no consumer code required. Replace the sample archetype with your own\",\n \"domain; the `schema` capability in `manifest.json` grants the registration (a\",\n \"profile is a schema+config bundle, so it needs no separate capability).\",\n ],\n renderers: [\n \"\",\n \"## Output Renderer\",\n \"`index.ts` registers a `toon` output renderer override through\",\n \"`api.registerRenderer`. Renderer overrides run for every command's output in\",\n \"that format, so this starter scopes itself to THIS package's own command and\",\n \"returns `null` (pass-through to pm's default renderer) for everything else.\",\n \"Return a string to take over rendering. Replace the sample serialization with\",\n \"your own; the `renderers` capability in `manifest.json` grants the\",\n \"registration.\",\n ],\n parser: [\n \"\",\n \"## Parser Override\",\n \"`index.ts` registers a parser override for the starter command through\",\n \"`api.registerParser`. pm runs it on the command's parsed options BEFORE the\",\n \"handler, merging the delta you return. This starter rewrites a deprecated\",\n \"`--shout` alias to the canonical `--upper` flag; replace it with your\",\n \"command's real normalization. The `parser` capability in `manifest.json`\",\n \"grants the registration.\",\n ],\n preflight: [\n \"\",\n \"## Preflight Override\",\n \"`index.ts` registers a preflight override through `api.registerPreflight`. pm\",\n \"calls it before every command to compute the migration/format gate decision —\",\n \"the last registered override wins. Return only the decision keys you want to\",\n \"change; this starter echoes the current decision unchanged (a safe no-op) so\",\n \"installing the package does not alter gate behavior. The `preflight`\",\n \"capability in `manifest.json` grants the registration.\",\n ],\n services: [\n \"\",\n \"## Service Override\",\n \"`index.ts` overrides the built-in `output_format` service through\",\n \"`api.registerService`. The service renders a command's structured result;\",\n \"returning the payload unchanged passes through to pm's default formatting.\",\n \"This starter scopes itself to THIS package's own command and passes every\",\n \"other command through, so it never disrupts unrelated output. The `services`\",\n \"capability in `manifest.json` grants the registration.\",\n ],\n};\n\nconst EXTENSION_CAPABILITY_README_SECTIONS: Record<ExtensionScaffoldCapability, readonly string[]> = {\n commands: [],\n hooks: [\n \"\",\n \"## Lifecycle Hook\",\n \"`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.\",\n \"pm fires it once a command finishes, passing the command outcome and the\",\n \"items it mutated (`context.affected`). React there to keep external context\",\n \"in sync. The `hooks` capability in `manifest.json` grants the registration;\",\n \"remove it (and the hook) if your extension only needs commands.\",\n ],\n search: [\n \"\",\n \"## Search Provider\",\n \"`index.ts` registers a deterministic in-memory search provider and\",\n \"vector-store adapter through `api.registerSearchProvider` and\",\n \"`api.registerVectorStoreAdapter`. Replace the sample scoring, embedding,\",\n \"and storage behavior with your project-specific retrieval logic. The\",\n \"`search` capability in `manifest.json` grants both registrations.\",\n ],\n importers: [\n \"\",\n \"## Importer and Exporter\",\n \"`index.ts` registers paired project-context import/export commands through\",\n \"`api.registerImporter` and `api.registerExporter`. Replace the starter\",\n \"payloads with your domain adapter. The `importers` capability grants both\",\n \"registrations, and `schema` grants the example command flag metadata.\",\n ],\n schema: [\n \"\",\n \"## Custom Schema\",\n \"`index.ts` models a project domain by registering a custom item type, a\",\n \"custom item field, and a schema migration through `api.registerItemTypes`,\",\n \"`api.registerItemFields`, and `api.registerMigration`. Replace the sample\",\n \"type/field/migration with your own domain model; the `schema` capability in\",\n \"`manifest.json` grants all three registrations. Once installed, the custom\",\n 'type is usable everywhere, e.g. `pm create <type> \"<title>\"`.',\n ],\n profile: [\n \"\",\n \"## Project Profile\",\n \"`index.ts` registers a complete project-profile archetype through\",\n \"`api.registerProfile` — one declarative bundle of item types, custom statuses,\",\n \"fields, a per-type workflow, config knobs, create templates, and package\",\n \"recommendations. Once installed the profile resolves by name through\",\n \"`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`,\",\n \"which stages every dimension idempotently like a core archetype. Replace the\",\n \"sample archetype with your own domain; the `schema` capability in\",\n \"`manifest.json` grants the registration.\",\n ],\n renderers: [\n \"\",\n \"## Output Renderer\",\n \"`index.ts` registers a `toon` output renderer override through\",\n \"`api.registerRenderer`. Renderer overrides run for every command's output in\",\n \"that format, so this starter scopes itself to its own command and returns\",\n \"`null` (pass-through to pm's default renderer) for everything else. Replace\",\n \"the sample serialization with your own; the `renderers` capability in\",\n \"`manifest.json` grants the registration.\",\n ],\n parser: [\n \"\",\n \"## Parser Override\",\n \"`index.ts` registers a parser override for the starter command through\",\n \"`api.registerParser`. pm runs it on the command's parsed options BEFORE the\",\n \"handler, merging the delta you return. This starter rewrites a deprecated\",\n \"`--shout` alias to the canonical `--upper` flag; replace it with your own\",\n \"normalization. The `parser` capability in `manifest.json` grants the\",\n \"registration.\",\n ],\n preflight: [\n \"\",\n \"## Preflight Override\",\n \"`index.ts` registers a preflight override through `api.registerPreflight`. pm\",\n \"calls it before every command to compute the migration/format gate decision —\",\n \"the last registered override wins. This starter echoes the current decision\",\n \"unchanged (a safe no-op); return only the decision keys you want to change.\",\n \"The `preflight` capability in `manifest.json` grants the registration.\",\n ],\n services: [\n \"\",\n \"## Service Override\",\n \"`index.ts` overrides the built-in `output_format` service through\",\n \"`api.registerService`. Returning the payload unchanged passes through to pm's\",\n \"default formatting, so this starter scopes itself to its own command and\",\n \"passes every other command through. The `services` capability in\",\n \"`manifest.json` grants the registration.\",\n ],\n};\n\n// README activation explainer for command-bearing starters (commands/hooks/\n// search/importers): they declare `activation.commands` so pm loads them lazily.\nconst LAZY_ACTIVATION_README_SECTION: Record<\"package\" | \"extension\", readonly string[]> = {\n package: [\n \"\",\n \"## Lazy Activation\",\n \"`manifest.json` declares `activation.commands`: the exact command paths this\",\n \"package's `activate` registers. pm imports and activates the package lazily —\",\n \"only when an invoked command path matches one of these entries — so unrelated\",\n \"commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in\",\n \"sync with the registrations in `index.ts`: add an entry when you register a new\",\n \"command, importer, or exporter, and remove one you drop. An omitted or stale\",\n \"entry means the matching command will not dispatch from the CLI. Globally-scoped\",\n \"surfaces (hooks, parser/preflight/renderer overrides, and search providers for\",\n \"built-in search commands) still activate regardless of this list.\",\n ],\n extension: [\n \"\",\n \"## Lazy Activation\",\n \"`manifest.json` declares `activation.commands`: the exact command paths this\",\n \"extension's `activate` registers. pm imports and activates the extension lazily —\",\n \"only when an invoked command path matches one of these entries — so unrelated\",\n \"commands never pay to load it. Keep this list in sync with the registrations in\",\n \"`index.ts`: an omitted or stale entry means the matching command will not dispatch\",\n \"from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,\",\n \"and search providers for built-in search commands) still activate regardless.\",\n ],\n};\n\n// README activation explainer for the `schema` starter: it contributes a GLOBAL\n// custom item type/field, so it intentionally omits `activation.commands` and\n// relies on pm's conservative activation tier (see buildScaffoldActivationCommands).\nconst SCHEMA_ACTIVATION_README_SECTION: Record<\"package\" | \"extension\", readonly string[]> = {\n package: [\n \"\",\n \"## Activation\",\n \"This package contributes a GLOBAL custom item type and field, so `manifest.json`\",\n \"intentionally declares no `activation.commands`. pm activates the package\",\n \"conservatively — for every command — so the custom type is present wherever it is\",\n \"used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.\",\n \"Declaring narrow `activation.commands` here would gate activation to only those\",\n \"commands and silently leave the custom type unregistered for `pm create`. If you\",\n \"drop the schema registrations and keep only command/hook/search/importer surfaces,\",\n \"add `activation.commands` back so pm can load the package lazily.\",\n ],\n extension: [\n \"\",\n \"## Activation\",\n \"This extension contributes a GLOBAL custom item type and field, so `manifest.json`\",\n \"intentionally declares no `activation.commands`. pm activates the extension\",\n \"conservatively — for every command — so the custom type is present wherever it is\",\n \"used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.\",\n \"Declaring narrow `activation.commands` here would gate activation to only those\",\n \"commands and silently leave the custom type unregistered for `pm create`.\",\n ],\n};\n\n// README activation explainer for the `profile` starter: the contributed profile\n// is resolved by the built-in `pm profile list/show/apply` commands (which the\n// package does not own), so it intentionally omits `activation.commands` and relies\n// on pm's conservative activation tier (granted by the `schema` capability).\nconst PROFILE_ACTIVATION_README_SECTION: Record<\"package\" | \"extension\", readonly string[]> = {\n package: [\n \"\",\n \"## Activation\",\n \"This package contributes a project profile resolved by the built-in\",\n \"`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`\",\n \"commands — commands the package does not own — so `manifest.json` intentionally\",\n \"declares no `activation.commands`. pm activates the package conservatively (for\",\n \"every command, granted by the `schema` capability) so the profile is present\",\n \"whenever `pm profile` runs. Declaring narrow `activation.commands` here would\",\n \"gate activation to only the listed commands and silently leave the profile\",\n \"unregistered for `pm profile`.\",\n ],\n extension: [\n \"\",\n \"## Activation\",\n \"This extension contributes a project profile resolved by the built-in\",\n \"`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`\",\n \"commands, so `manifest.json` intentionally declares no `activation.commands`. pm\",\n \"activates the extension conservatively (for every command, granted by the\",\n \"`schema` capability) so the profile is present whenever `pm profile` runs.\",\n \"Declaring narrow `activation.commands` here would silently leave the profile\",\n \"unregistered for `pm profile`.\",\n ],\n};\n\n/**\n * Build the README \"Included Files\" bullet describing `manifest.json` for the\n * chosen capability and vocabulary. The `schema` and `profile` starters omit\n * `activation.commands` (see {@link buildScaffoldActivationCommands}), so their\n * bullet explains the global-contribution tradeoff instead of referencing a field\n * they deliberately lack.\n */\nfunction buildScaffoldManifestBullet(capability: ExtensionScaffoldCapability, vocabulary: \"extension\" | \"package\"): string {\n if (capability === \"schema\") {\n return `- \\`manifest.json\\`: ${vocabulary} metadata and capabilities (no \\`activation.commands\\` — the custom item type activates for every command).`;\n }\n if (capability === \"profile\") {\n return `- \\`manifest.json\\`: ${vocabulary} metadata and capabilities (no \\`activation.commands\\` — the contributed profile resolves through \\`pm profile\\` for every command).`;\n }\n return `- \\`manifest.json\\`: ${vocabulary} metadata, capabilities, and \\`activation.commands\\` (the command paths that lazily activate this ${vocabulary}).`;\n}\n\n/**\n * Select the README activation section for the chosen capability and vocabulary:\n * the `schema` and `profile` starters explain conservative activation (they omit\n * `activation.commands`); every other capability documents lazy activation.\n */\nfunction buildScaffoldActivationReadmeSection(\n capability: ExtensionScaffoldCapability,\n vocabulary: \"extension\" | \"package\",\n): readonly string[] {\n if (capability === \"schema\") {\n return SCHEMA_ACTIVATION_README_SECTION[vocabulary];\n }\n if (capability === \"profile\") {\n return PROFILE_ACTIVATION_README_SECTION[vocabulary];\n }\n return LAZY_ACTIVATION_README_SECTION[vocabulary];\n}\n\ninterface ExtensionScaffoldFileResult {\n path: string;\n status: \"created\" | \"unchanged\";\n}\n\ninterface ExtensionScaffoldResult {\n extension_name: string;\n command_name: string;\n capability: ExtensionScaffoldCapability;\n /**\n * Authoring style of the generated entrypoint: `\"imperative\"` (a hand-written\n * `activate` body, the default) or `\"declarative\"` (a `composeExtension`\n * blueprint). The declarative style is package-mode only (any capability).\n */\n style: ExtensionScaffoldStyle;\n target_path: string;\n created_directory: boolean;\n files: ExtensionScaffoldFileResult[];\n}\n\n/**\n * Authoring style the scaffolder targets for the generated entrypoint. The\n * default `\"imperative\"` emits a hand-written `activate` body; `\"declarative\"`\n * emits the SDK's `composeExtension` blueprint loop (package-mode only, for any\n * capability — see {@link buildDeclarativeEntrypoint}).\n */\nexport type ExtensionScaffoldStyle = \"imperative\" | \"declarative\";\n\n/**\n * Builds the starter command path from the normalized package/extension name.\n * Names that start with a built-in pm command or executable alias are prefixed\n * with `starter` so the generated command dispatches to the package instead of\n * being consumed by core command parsing.\n */\nexport function buildScaffoldCommandName(extensionName: string): string {\n const commandWords = extensionName\n .replace(/-/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((word) => word.length > 0);\n if (commandWords.length === 0) {\n return \"starter ping\";\n }\n const firstWordLower = commandWords[0]!.toLowerCase();\n let leadingStarterWords = 0;\n while (commandWords[leadingStarterWords]?.toLowerCase() === \"starter\") {\n leadingStarterWords += 1;\n }\n const nextStarterWord = commandWords[leadingStarterWords]?.toLowerCase();\n const starterRootCollision =\n leadingStarterWords > 0 &&\n (leadingStarterWords === commandWords.length || (nextStarterWord !== undefined && RESERVED_SCAFFOLD_COMMAND_ROOTS.has(nextStarterWord)));\n const reservedRoot = RESERVED_SCAFFOLD_COMMAND_ROOTS.has(firstWordLower) || starterRootCollision;\n const resolvedWords = reservedRoot ? [\"starter\", ...commandWords] : commandWords;\n return `${resolvedWords.join(\" \")} ping`;\n}\n\n/**\n * Build the project-profile archetype object literal the `profile` starter\n * registers — a complete {@link ProjectProfileDefinition} derived from the package\n * name: one custom item type, a custom status, a custom field, a per-type workflow,\n * offline search config, a create template, and an advisory package recommendation.\n *\n * Returned as the lines BETWEEN the object braces at a two-space base indent. Both\n * authoring styles read from this single source so they never drift: the imperative\n * {@link buildActivateBodyLines} wraps them in `api.registerProfile({ ... })`\n * (re-indenting by the `activate` body offset) and the declarative\n * {@link buildDeclarativeBlueprintSurface} wraps them in\n * `defineProjectProfile({ ... })`.\n */\nfunction buildProfileArchetypeFieldLines(extensionName: string): string[] {\n const typeName = extensionName;\n const typeFolder = `${extensionName}s`;\n // De-hyphenate for a short alias; omit a redundant self-alias for single-word names.\n const typeAlias = extensionName.replace(/-/g, \"\");\n const typeAliases = typeAlias === typeName ? [] : [typeAlias];\n const fieldKey = `${extensionName.replace(/-/g, \"_\")}_owner`;\n const statusId = \"reviewing\";\n return [\n ` name: ${JSON.stringify(extensionName)},`,\n ` title: ${JSON.stringify(`${extensionName} archetype`)},`,\n ' summary: \"Starter project profile. Replace these dimensions with your own archetype.\",',\n \" // Item types the profile upserts into the project schema when applied.\",\n \" types: [\",\n \" {\",\n ` name: ${JSON.stringify(typeName)},`,\n ` folder: ${JSON.stringify(typeFolder)},`,\n ` aliases: ${JSON.stringify(typeAliases)},`,\n ` description: ${JSON.stringify(`A ${extensionName} work item that flows to done.`)},`,\n \" },\",\n \" ],\",\n \" // Custom statuses upserted into the project status set.\",\n \" statuses: [\",\n \" {\",\n ` id: ${JSON.stringify(statusId)},`,\n ' roles: [\"active\"],',\n ' aliases: [\"in-review\"],',\n ' description: \"Work is implementation-complete and awaiting review.\",',\n \" },\",\n \" ],\",\n \" // Custom front-matter fields the archetype tracks.\",\n \" fields: [\",\n \" {\",\n ` key: ${JSON.stringify(fieldKey)},`,\n ' type: \"string\",',\n ' commands: [\"create\", \"update\", \"list\"],',\n ' description: \"Stakeholder accountable for the item.\",',\n \" },\",\n \" ],\",\n \" // Per-type workflow transition allow-list staged into settings.\",\n \" workflows: [\",\n \" {\",\n ` type: ${JSON.stringify(typeName)},`,\n \" allowed_transitions: [\",\n ' [\"open\", \"in_progress\"],',\n ` [\"in_progress\", ${JSON.stringify(statusId)}],`,\n ` [${JSON.stringify(statusId)}, \"in_progress\"],`,\n ` [${JSON.stringify(statusId)}, \"closed\"],`,\n ' [\"in_progress\", \"blocked\"],',\n ' [\"blocked\", \"in_progress\"],',\n \" ],\",\n \" },\",\n \" ],\",\n \" // Nested-settings knobs staged when the profile is applied.\",\n \" config: [\",\n ' { key: \"search_provider\", value: \"bm25\", summary: \"Offline BM25 lexical search needs no embedding service.\" },',\n ' { key: \"search_max_results\", value: \"20\", summary: \"Result cap tuned for quick triage.\" },',\n \" ],\",\n \" // Create templates staged into <pmRoot>/templates.\",\n \" templates: [\",\n \" {\",\n ` name: ${JSON.stringify(extensionName)},`,\n \" options: {\",\n ` type: ${JSON.stringify(typeName)},`,\n ' priority: \"2\",',\n ` tags: ${JSON.stringify(extensionName)},`,\n ' acceptanceCriteria: \"Item delivers the stated outcome with tests and docs updated.\",',\n ' body: \"## Context\\\\n\\\\n## Acceptance\\\\n- [ ] \\\\n\",',\n \" },\",\n \" },\",\n \" ],\",\n \" // Advisory package recommendations (never auto-installed).\",\n \" packages: [\",\n ' { spec: \"templates\", reason: \"Reusable create templates for recurring item shapes.\" },',\n \" ],\",\n ];\n}\n\n/**\n * Build the `activate` body lines for the starter entrypoint. The base body\n * always registers the starter command; capability-specific variants append\n * the matching SDK surface so generated packages demonstrate one runnable\n * customization primitive end to end.\n */\nfunction buildActivateBodyLines(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string[] {\n const searchProviderName = `${extensionName}-search`;\n const vectorAdapterName = `${extensionName}-vector`;\n const adapterName = `${extensionName.replace(/-/g, \" \")} items`;\n const commandLines = [\n \" api.registerCommand({\",\n ` name: ${JSON.stringify(commandName)},`,\n ' description: \"Starter scaffold command. Replace with your own behavior.\",',\n \" run: async (context) => ({\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n \" command: context.command,\",\n ' message: \"Starter extension scaffold is active.\",',\n \" }),\",\n \" });\",\n ];\n if (capability === \"commands\") {\n return commandLines;\n }\n if (capability === \"search\") {\n return [\n ...commandLines,\n \"\",\n \" // Search providers let packages customize how pm ranks and retrieves\",\n \" // project context. This starter is deterministic and dependency-free:\",\n \" // replace the scoring with your domain retrieval, embedding, or rerank\",\n \" // logic as the package grows.\",\n \" api.registerSearchProvider({\",\n ` name: ${JSON.stringify(searchProviderName)},`,\n \" query: async (context) => {\",\n \" const needle = context.query.toLowerCase();\",\n \" const hits = context.documents\",\n \" .filter((document) => {\",\n \" const title = String(document.metadata.title ?? \\\"\\\").toLowerCase();\",\n \" return title.includes(needle);\",\n \" })\",\n \" .map((document) => ({\",\n \" id: document.metadata.id,\",\n \" score: 1,\",\n ' matched_fields: [\"title\"],',\n \" }));\",\n \" return { hits };\",\n \" },\",\n \" embed: async (context) => [context.input.length],\",\n \" });\",\n \"\",\n \" // Vector-store adapters let packages own semantic index storage. This\",\n \" // starter returns a stable in-memory hit so generated tests can exercise\",\n \" // the adapter without external services.\",\n \" api.registerVectorStoreAdapter({\",\n ` name: ${JSON.stringify(vectorAdapterName)},`,\n \" query: async (context) => [{ id: \\\"starter-vector-hit\\\", score: context.limit }],\",\n \" upsert: async (context) => ({ upserted: context.points.length }),\",\n \" delete: async (context) => ({ deleted: context.ids.length }),\",\n \" });\",\n ];\n }\n if (capability === \"schema\") {\n const itemTypeName = extensionName;\n const itemTypeFolder = `${extensionName}s`;\n // De-hyphenate for a short alias (e.g. \"my-tracker\" -> \"mytracker\"). For a\n // single-word name the de-hyphenated form equals the type name, so omit the\n // alias rather than register a redundant self-alias in the starter.\n const itemTypeAlias = extensionName.replace(/-/g, \"\");\n const itemTypeAliases = itemTypeAlias === itemTypeName ? [] : [itemTypeAlias];\n const fieldName = `${extensionName.replace(/-/g, \"_\")}_note`;\n const migrationId = `${extensionName}-0001-init`;\n return [\n ...commandLines,\n \"\",\n \" // Schema registrations let a package model its own project domain — the\",\n \" // heart of \\\"project management = context management\\\". Item types and fields\",\n \" // are GLOBAL contributions: built-in commands like `pm create <type>` and\",\n \" // `pm list --type <type>` must see them, so this package declares no\",\n \" // `activation.commands` and pm activates it conservatively for every command.\",\n \" // The `schema` capability in manifest.json grants all three registrations.\",\n \" api.registerItemFields([\",\n \" {\",\n ` name: ${JSON.stringify(fieldName)},`,\n ' type: \"string\",',\n \" optional: true,\",\n \" },\",\n \" ]);\",\n \"\",\n \" api.registerItemTypes([\",\n \" {\",\n ` name: ${JSON.stringify(itemTypeName)},`,\n \" // Replace with your domain's canonical plural folder name.\",\n ` folder: ${JSON.stringify(itemTypeFolder)},`,\n ` aliases: ${JSON.stringify(itemTypeAliases)},`,\n \" // Add field names here to force them at `pm create` time.\",\n \" required_create_fields: [],\",\n \" },\",\n \" ]);\",\n \"\",\n \" // Migrations let a package evolve stored items as its schema changes. pm\",\n \" // runs each migration ONCE through the preflight gate (not once per item),\",\n \" // passing a context that identifies the migration itself: `context.id` is\",\n \" // the migration id (not an item id), alongside `context.pm_root` — iterate\",\n \" // the corpus yourself from there. This starter is a deterministic no-op so\",\n \" // package tests can invoke it without touching the corpus; replace the body\",\n \" // with your real rewrite.\",\n \" api.registerMigration({\",\n ` id: ${JSON.stringify(migrationId)},`,\n ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`,\n \" mandatory: false,\",\n \" run: async (context) => ({ migrated: true, id: context.id }),\",\n \" });\",\n ];\n }\n if (capability === \"profile\") {\n return [\n ...commandLines,\n \"\",\n \" // A project profile is the broadest customization primitive pm has: one\",\n \" // declarative bundle of item types, custom statuses, fields, a per-type\",\n \" // workflow, config knobs, create templates, and package recommendations. Once\",\n \" // this package is installed the profile resolves by name through `pm profile\",\n \" // list`, `pm profile show`, and `pm profile apply`, which stages every dimension\",\n \" // idempotently like a core archetype. A profile registration is a schema+config\",\n \" // bundle, so the `schema` capability in manifest.json grants it.\",\n \" api.registerProfile({\",\n // The archetype field lines are all non-empty, so re-indent each by the\n // `activate` body offset (object braces sit at two spaces, fields at four).\n ...buildProfileArchetypeFieldLines(extensionName).map((line) => ` ${line}`),\n \" });\",\n ];\n }\n if (capability === \"importers\") {\n return [\n ...commandLines,\n \"\",\n \" // Importers/exporters are the bridge between pm's context graph and\",\n \" // another project-management system. Keep the starter deterministic so\",\n \" // package tests can run without touching the network or filesystem; replace\",\n \" // these payloads with your adapter's real mapping as the package grows.\",\n \" api.registerImporter(\",\n ` ${JSON.stringify(adapterName)},`,\n \" async (context) => ({\",\n \" imported: 1,\",\n \" source: context.options.source ?? \\\"starter\\\",\",\n \" args: context.args,\",\n \" }),\",\n \" {\",\n ` action: ${JSON.stringify(`${adapterName} import`)},`,\n ' description: \"Import starter records into pm context.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--source\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Source name or path to import from.\",',\n \" },\",\n \" ],\",\n \" },\",\n \" );\",\n \"\",\n \" api.registerExporter(\",\n ` ${JSON.stringify(adapterName)},`,\n \" async (context) => ({\",\n \" exported: true,\",\n \" destination: context.options.destination ?? \\\"stdout\\\",\",\n \" args: context.args,\",\n \" }),\",\n \" {\",\n ` action: ${JSON.stringify(`${adapterName} export`)},`,\n ' description: \"Export pm context into starter records.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--destination\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Destination name or path to export to.\",',\n \" },\",\n \" ],\",\n \" },\",\n \" );\",\n ];\n }\n if (capability === \"renderers\") {\n return [\n ...commandLines,\n \"\",\n \" // Renderer overrides customize how pm serializes a command's structured\",\n \" // result for an output format (\\\"toon\\\" or \\\"json\\\"). pm runs this override for\",\n \" // EVERY command's output in that format, so it scopes itself to THIS\",\n \" // package's own command and returns null — pass-through to pm's default\",\n \" // renderer — for everything else. Return a string to take over rendering.\",\n \" // The `renderers` capability in manifest.json grants the registration.\",\n ' api.registerRenderer(\"toon\", (context) => {',\n ` if (context.command !== ${JSON.stringify(commandName)}) {`,\n \" return null;\",\n \" }\",\n ` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`,\n \" });\",\n ];\n }\n if (capability === \"parser\") {\n return [\n // The parser starter declares its own flags so the override is runnable end\n // to end through `pm <command> --shout`: the command defines the deprecated\n // `--shout` alias and canonical `--upper` flag, the parser rewrites one to\n // the other, and the handler surfaces the normalized value. Flag metadata\n // needs the `schema` capability (declared in manifest.json).\n \" api.registerCommand({\",\n ` name: ${JSON.stringify(commandName)},`,\n ' description: \"Starter scaffold command. Replace with your own behavior.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--shout\",',\n ' value_type: \"boolean\",',\n ' description: \"Deprecated alias for --upper; the parser override rewrites it.\",',\n \" },\",\n \" {\",\n ' long: \"--upper\",',\n ' value_type: \"boolean\",',\n ' description: \"Echo the canonical flag the parser override produces.\",',\n \" },\",\n \" ],\",\n \" run: async (context) => ({\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n \" command: context.command,\",\n \" // Surfaces the normalized option so `--shout`/`--upper` is observable.\",\n \" upper: context.options.upper === true,\",\n ' message: \"Starter extension scaffold is active.\",',\n \" }),\",\n \" });\",\n \"\",\n \" // Parser overrides preprocess a command's parsed options BEFORE its handler\",\n \" // runs, returning a delta — only the keys you set are merged over the parsed\",\n \" // input. This override is scoped to THIS package's own command. Here it\",\n \" // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`\",\n \" // flag; replace it with your command's real normalization. The `parser`\",\n \" // capability in manifest.json grants the registration.\",\n ` api.registerParser(${JSON.stringify(commandName)}, (context) => {`,\n \" const options = { ...context.options };\",\n \" if (options.shout === true) {\",\n \" options.upper = true;\",\n \" }\",\n \" delete options.shout;\",\n \" return { options };\",\n \" });\",\n ];\n }\n if (capability === \"preflight\") {\n return [\n ...commandLines,\n \"\",\n \" // Preflight overrides adjust pm's pre-run gate decision (extension\",\n \" // migrations + item-format checks) before EVERY command — the last\",\n \" // registered override wins. Return a delta of the keys you want to change\",\n \" // (enforce_item_format_gate, run_preflight_item_format_sync,\",\n \" // run_extension_migrations, enforce_mandatory_migration_gate); returning\",\n \" // context.decision unchanged is a safe no-op so installing the package does\",\n \" // not alter gate behavior — replace it with your policy, e.g.\",\n \" // `{ run_extension_migrations: false }`. The `preflight` capability in\",\n \" // manifest.json grants the registration.\",\n \" api.registerPreflight((context) => context.decision);\",\n ];\n }\n if (capability === \"services\") {\n return [\n ...commandLines,\n \"\",\n \" // Service overrides replace a built-in pm service. The `output_format`\",\n \" // service renders a command's structured result; returning the payload\",\n \" // unchanged passes through to pm's default formatting. This override scopes\",\n \" // itself to THIS package's own command and passes every other command\",\n \" // through, so it never disrupts unrelated output. The `services` capability\",\n \" // in manifest.json grants the registration.\",\n ' api.registerService(\"output_format\", (context) => {',\n ` if (context.command !== ${JSON.stringify(commandName)}) {`,\n \" return context.payload;\",\n \" }\",\n ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,\n \" });\",\n ];\n }\n return [\n ...commandLines,\n \"\",\n \" // after_command hooks fire once pm finishes a command, receiving the items\",\n \" // it mutated. This is the natural place to react to every change - sync to\",\n \" // an external system, emit telemetry, or refresh derived context\",\n ' // (\"project management = context management\"). This starter is a documented',\n \" // no-op on the success path; replace the body with your own reaction.\",\n \" api.hooks.afterCommand((context) => {\",\n \" if (!context.ok) {\",\n \" return;\",\n \" }\",\n \" // `context.affected` lists the items pm mutated (id, status,\",\n \" // changed_fields). React here, e.g.:\",\n \" // for (const item of context.affected ?? []) { /* ...item.id... */ }\",\n \" });\",\n ];\n}\n\n/**\n * Build the colocated `node:test` sample suite (`index.test.ts`) for the chosen\n * capability. Authored in TypeScript and run through the generated package's\n * `npm test` script (typecheck first, then `node --test`, which strips types on\n * Node >=22.18), it imports the `./index.ts` manifest entry directly under\n * NodeNext resolution.\n * Every variant covers activation, command invocation, and teardown via\n * `createExtensionTestHarness`; capability variants add tests that use the\n * harness-bound `assert*`/`run*` helpers and deactivate in `finally`.\n */\nfunction buildSampleTestSource(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string {\n const hooksEnabled = capability === \"hooks\";\n const searchEnabled = capability === \"search\";\n const importersEnabled = capability === \"importers\";\n const schemaEnabled = capability === \"schema\";\n const profileEnabled = capability === \"profile\";\n const renderersEnabled = capability === \"renderers\";\n const parserEnabled = capability === \"parser\";\n const preflightEnabled = capability === \"preflight\";\n const servicesEnabled = capability === \"services\";\n const capabilitiesLiteral = SAMPLE_TEST_CAPABILITIES_LITERAL[capability];\n const itemTypeName = extensionName;\n const itemTypeFolder = `${extensionName}s`;\n const fieldName = `${extensionName.replace(/-/g, \"_\")}_note`;\n const migrationId = `${extensionName}-0001-init`;\n const importNames = [\n \" assertExtensionDeactivated,\",\n \" createExtensionTestHarness,\",\n ];\n const hookTestLines = hooksEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertHook throws unless an after_command hook is registered, so\",\n \" // reaching the next line already proves the hook is wired.\",\n \" ext.assertHook({\",\n ' kind: \"after_command\",',\n ` extensionName: ${JSON.stringify(extensionName)},`,\n \" });\",\n \" // runHook fires the hook through pm's real runner with a synthetic\",\n \" // context and returns the warnings it produced; a clean hook returns none.\",\n \" // Replace the context/assertions as your hook grows.\",\n \" const warnings = await ext.runHook({\",\n ' kind: \"after_command\",',\n \" context: {\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n ' pm_root: \"\",',\n \" ok: true,\",\n \" affected: [],\",\n \" },\",\n \" });\",\n \" assert.deepEqual(warnings, []);\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const searchTestLines = searchEnabled\n ? buildDeclarativeCapabilityTestBlock(extensionName, commandName, \"search\", capabilitiesLiteral)\n : [];\n const importerTestLines = importersEnabled\n ? buildDeclarativeCapabilityTestBlock(extensionName, commandName, \"importers\", capabilitiesLiteral)\n : [];\n const schemaTestLines = schemaEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} registers and runs its custom schema`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n ...indentGeneratedLines(\n buildSchemaCapabilityAssertionLines({\n extensionName,\n itemTypeName,\n itemTypeFolder,\n fieldName,\n migrationId,\n includeMigrationReplacementHint: true,\n }),\n \" \",\n ),\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const profileTestLines = profileEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n ...indentGeneratedLines(buildProfileCapabilityAssertionLines(extensionName), \" \"),\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const rendererTestLines = renderersEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertRendererOverride throws unless a renderer is registered for the\",\n \" // format, so reaching the next line already proves the wiring.\",\n ` const override = ext.assertRendererOverride({ format: \"toon\", extensionName: ${JSON.stringify(extensionName)} });`,\n ' assert.equal(override.format, \"toon\");',\n \"\",\n \" // runRendererOverride renders through pm's real runner. The override\",\n \" // customizes only THIS package's command output and returns a string the\",\n \" // host uses verbatim. Replace the assertions as it grows.\",\n \" const rendered = await ext.runRendererOverride({\",\n ' format: \"toon\",',\n ` command: ${JSON.stringify(commandName)},`,\n \" result: { ok: true },\",\n \" });\",\n \" assert.equal(rendered.overridden, true);\",\n ` assert.equal(rendered.rendered, ${JSON.stringify(`${extensionName}: `)} + JSON.stringify({ ok: true }));`,\n \"\",\n \" // Output for any other command passes through to pm's default renderer.\",\n \" const passthrough = await ext.runRendererOverride({\",\n ' format: \"toon\",',\n ' command: \"list\",',\n \" result: { ok: true },\",\n \" });\",\n \" assert.equal(passthrough.overridden, false);\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const parserTestLines = parserEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} rewrites command options via its parser override`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertParserOverride throws unless a parser is registered for the\",\n \" // command, so reaching the next line already proves the wiring.\",\n ` ext.assertParserOverride({ command: ${JSON.stringify(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runParserOverride runs the override through pm's real parser runner and\",\n \" // returns the rewritten context. The starter rewrites the deprecated\",\n \" // `shout` alias to the canonical `upper` flag.\",\n \" const result = await ext.runParserOverride({\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n \" options: { shout: true },\",\n \" global: {},\",\n ' pm_root: \"\",',\n \" });\",\n \" assert.equal(result.overridden, true);\",\n \" assert.deepEqual(result.context.options, { upper: true });\",\n \"\",\n \" // End to end: feed the rewritten options into the command handler to\",\n \" // prove `pm <command> --shout` surfaces the normalized `upper` flag in\",\n \" // the result.\",\n ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)}, options: result.context.options });`,\n \" assert.equal(invocation.handled, true);\",\n \" assert.deepEqual(invocation.result, {\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n ` command: ${JSON.stringify(commandName)},`,\n \" upper: true,\",\n ' message: \"Starter extension scaffold is active.\",',\n \" });\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const preflightTestLines = preflightEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertPreflightOverride throws unless a preflight override is\",\n \" // registered, so reaching the next line already proves the wiring.\",\n ` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runPreflightOverride runs the override through pm's real runner with a\",\n \" // synthetic gate decision. The starter echoes the decision unchanged;\",\n \" // replace the values/assertions with your real policy.\",\n \" const decision = {\",\n \" enforce_item_format_gate: true,\",\n \" run_preflight_item_format_sync: false,\",\n \" run_extension_migrations: true,\",\n \" enforce_mandatory_migration_gate: false,\",\n \" };\",\n \" const result = await ext.runPreflightOverride({\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n \" options: {},\",\n \" global: {},\",\n ' pm_root: \"\",',\n \" decision,\",\n \" });\",\n \" assert.equal(result.overridden, true);\",\n \" assert.deepEqual(result.decision, decision);\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n const serviceTestLines = servicesEnabled\n ? [\n `test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`,\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertServiceOverride throws unless a service override is registered\",\n \" // for the service, so reaching the next line proves the wiring.\",\n ` ext.assertServiceOverride({ service: \"output_format\", extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runServiceOverride runs the override through pm's real service runner.\",\n \" // The override customizes only THIS package's command output (handled),\",\n \" // passing every other command through (not handled).\",\n \" const handled = await ext.runServiceOverride({\",\n ' service: \"output_format\",',\n ` command: ${JSON.stringify(commandName)},`,\n \" payload: { ok: true },\",\n \" });\",\n \" assert.equal(handled.handled, true);\",\n ` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, payload: { ok: true } });`,\n \"\",\n \" // Output for any other command passes through to pm's default formatter.\",\n \" const passthrough = await ext.runServiceOverride({\",\n ' service: \"output_format\",',\n ' command: \"list\",',\n \" payload: { ok: true },\",\n \" });\",\n \" assert.equal(passthrough.handled, false);\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ]\n : [];\n return [\n 'import assert from \"node:assert/strict\";',\n 'import { test } from \"node:test\";',\n \"import {\",\n ...importNames,\n '} from \"@unbrained/pm-cli/sdk/testing\";',\n // The search sample's synthetic query/vector contexts reference these SDK types\n // for their typed-stub fixtures; other capabilities need no extra type imports.\n ...(searchEnabled ? ['import type { ItemDocument, PmSettings } from \"@unbrained/pm-cli/sdk\";'] : []),\n 'import extension from \"./index.ts\";',\n \"\",\n ...SAMPLE_HARNESS_CLEANUP_LINES,\n `test(${JSON.stringify(`${extensionName} registers its starter command`)}, async () => {`,\n \" // `capabilities` mirrors manifest.json so the in-memory activation grants\",\n \" // the capabilities the entrypoint relies on.\",\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertCommandContract is bound to the right activation registry and throws\",\n \" // if the command is not registered, so reaching here already proves the\",\n \" // wiring; assert on the returned definition to inspect metadata.\",\n \" const registered = ext.assertCommandContract({\",\n ` command: ${JSON.stringify(commandName)},`,\n ` extensionName: ${JSON.stringify(extensionName)},`,\n \" });\",\n ' assert.equal(typeof registered.command.description, \"string\");',\n \"\",\n \" // runCommand invokes the handler through pm's real dispatch engine, so this\",\n \" // asserts behavior - not just that the command is wired. Replace these\",\n \" // assertions as you flesh out your command.\",\n \" const invocation = await ext.runCommand({\",\n ` command: ${JSON.stringify(commandName)},`,\n \" });\",\n \" assert.equal(invocation.handled, true);\",\n \" // The handler result is typed `unknown`, so deep-equality on the whole\",\n \" // structured payload keeps the assertion type-safe without a cast.\",\n \" assert.deepEqual(invocation.result, {\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n ` command: ${JSON.stringify(commandName)},`,\n // The parser starter's command surfaces the normalized `upper` flag, which\n // defaults to false when the command is invoked without `--shout`/`--upper`.\n ...(parserEnabled ? [\" upper: false,\"] : []),\n ' message: \"Starter extension scaffold is active.\",',\n \" });\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ...hookTestLines,\n ...searchTestLines,\n ...importerTestLines,\n ...schemaTestLines,\n ...profileTestLines,\n ...rendererTestLines,\n ...parserTestLines,\n ...preflightTestLines,\n ...serviceTestLines,\n `test(${JSON.stringify(`${extensionName} tears down cleanly via deactivate`)}, async () => {`,\n \" // createExtensionTestHarness binds teardown to the same name/layer used for\",\n \" // activation, so this proves your `deactivate` hook runs without throwing.\",\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" const teardown = await ext.deactivate();\",\n \" // assertExtensionDeactivated throws unless exactly one extension tore down\",\n \" // with no failures, so reaching the next line already proves teardown ran.\",\n \" assertExtensionDeactivated(teardown);\",\n \" assert.equal(teardown.deactivated, 1);\",\n \"});\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Build the manifest `activation.commands` list for the chosen capability: the\n * exact command paths the starter `activate` registers.\n *\n * pm uses this list for lazy activation — it imports and activates the package\n * only when an invoked command path matches one of these entries — so it must\n * stay in sync with the registrations in {@link buildActivateBodyLines}. Every\n * first-party bundled package declares the same field; emitting it keeps\n * generated packages on that convention so they get precise, lazy, correct\n * activation instead of falling back to capability heuristics (which cannot\n * enumerate the contributed commands). The `importers` variant additionally\n * registers paired import/export command handlers under the adapter name.\n *\n * The `schema` and `profile` variants are the deliberate exceptions: each returns\n * an empty list so the manifest omits `activation.commands`. Custom item types and\n * fields are GLOBAL schema contributions that built-in commands (`pm create\n * <type>`, `pm list --type <type>`, `pm validate`) must see, and a contributed\n * project profile is resolved by the built-in `pm profile list/show/apply` commands\n * — commands the package does not own and cannot enumerate. Declaring narrow\n * `activation.commands` there would gate activation to only the listed commands and\n * silently leave the custom type or profile unregistered for those built-ins;\n * omitting it lets pm's conservative activation tier (which covers `schema`) load\n * the package for every command.\n */\nfunction buildScaffoldActivationCommands(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string[] {\n if (capability === \"schema\" || capability === \"profile\") {\n return [];\n }\n if (capability === \"importers\") {\n const adapterName = `${extensionName.replace(/-/g, \" \")} items`;\n return [commandName, `${adapterName} import`, `${adapterName} export`];\n }\n return [commandName];\n}\n\n// One-line surface phrase per capability, listing the registration surfaces the\n// declarative blueprint populates beyond the always-present starter command. Used\n// to keep the generated README's entrypoint bullet accurate per capability.\nconst DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE: Record<ExtensionScaffoldCapability, string> = {\n commands: \"starter command\",\n hooks: \"starter command and after_command hook\",\n search: \"starter command, search provider, and vector-store adapter\",\n importers: \"starter command, importer, and exporter\",\n schema: \"starter command, custom item type, item field, and migration\",\n profile: \"starter command and project profile\",\n renderers: \"starter command and toon renderer override\",\n parser: \"starter command and parser override\",\n preflight: \"starter command and preflight override\",\n services: \"starter command and output_format service override\",\n};\n\n// The `ExtensionBlueprint` fields each capability populates, rendered as inline\n// code in the README's Declarative Authoring section so authors can see which\n// blueprint surface maps to the capability they scaffolded.\nconst DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS: Record<ExtensionScaffoldCapability, string> = {\n commands: \"`commands`\",\n hooks: \"`commands` and `hooks.afterCommand`\",\n search: \"`commands`, `searchProviders`, and `vectorStoreAdapters`\",\n importers: \"`commands`, `importers`, and `exporters`\",\n schema: \"`commands`, `itemTypes`, `itemFields`, and `migrations`\",\n profile: \"`commands` and `profiles`\",\n renderers: \"`commands` and `renderers`\",\n parser: \"`commands` and `parsers`\",\n preflight: \"`commands` and `preflights`\",\n services: \"`commands` and `services`\",\n};\n\n/**\n * The shared per-capability registration-definition builder for the declarative\n * starter: the `define*`-authored definitions, the `ExtensionBlueprint` fields that\n * collect them, and the extra `define*` builder names to import. It is the single\n * source the declarative {@link buildDeclarativeEntrypoint} and its colocated test\n * ({@link buildDeclarativeCapabilityTestBlock}) both read from, so the two never\n * drift on what the capability registers.\n */\ninterface DeclarativeBlueprintSurface {\n /** Extra `define*` builder names to import beyond the always-present trio. */\n builderImports: string[];\n /** The `export const <name> = define*({...})` definition blocks (blank-separated). */\n definitions: string[];\n /** The `ExtensionBlueprint` object field lines, e.g. ` searchProviders: [searchProvider],`. */\n blueprintFields: string[];\n}\n\n/**\n * Build the `defineCommand` starter-command definition for the declarative\n * entrypoint. Mirrors the imperative {@link buildActivateBodyLines} command body\n * (same name/description/run result), and for the `parser` capability declares the\n * `--shout`/`--upper` flags and surfaces the normalized `upper` option so the\n * override is runnable end to end through `pm <command> --shout`.\n */\nfunction buildDeclarativePingCommandLines(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string[] {\n const parserEnabled = capability === \"parser\";\n return [\n \"// The starter command, authored with the `defineCommand` builder so its literal\",\n \"// name is preserved and the handler `context` is inferred. Exporting it lets you\",\n \"// unit-test the definition in isolation, apart from the blueprint.\",\n \"export const pingCommand = defineCommand({\",\n ` name: ${JSON.stringify(commandName)},`,\n ' description: \"Starter scaffold command. Replace with your own behavior.\",',\n ...(parserEnabled\n ? [\n \" flags: [\",\n \" {\",\n ' long: \"--shout\",',\n ' value_type: \"boolean\",',\n ' description: \"Deprecated alias for --upper; the parser override rewrites it.\",',\n \" },\",\n \" {\",\n ' long: \"--upper\",',\n ' value_type: \"boolean\",',\n ' description: \"Echo the canonical flag the parser override produces.\",',\n \" },\",\n \" ],\",\n ]\n : []),\n \" run: async (context) => ({\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n \" command: context.command,\",\n ...(parserEnabled ? [\" upper: context.options.upper === true,\"] : []),\n ' message: \"Starter extension scaffold is active.\",',\n \" }),\",\n \"});\",\n ];\n}\n\n/**\n * Build the {@link DeclarativeBlueprintSurface} for a capability: the starter\n * command plus the capability's `define*`-authored registration definitions and\n * the `ExtensionBlueprint` fields that collect them.\n *\n * Blueprint fields are emitted in {@link composeExtension}'s registration order so\n * the generated `activate` wires them deterministically. Each surface mirrors the\n * imperative {@link buildActivateBodyLines} registration (same names, same handler\n * behavior) so a package scaffolded in either style installs and dispatches\n * identically — the manifest, derived capabilities, and registered surfaces match.\n */\nfunction buildDeclarativeBlueprintSurface(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): DeclarativeBlueprintSurface {\n const builderImports: string[] = [];\n const definitions: string[] = [...buildDeclarativePingCommandLines(extensionName, commandName, capability)];\n const blueprintFields: string[] = [\" commands: [pingCommand],\"];\n\n const searchProviderName = `${extensionName}-search`;\n const vectorAdapterName = `${extensionName}-vector`;\n const adapterName = `${extensionName.replace(/-/g, \" \")} items`;\n const itemTypeName = extensionName;\n const itemTypeFolder = `${extensionName}s`;\n // De-hyphenate for a short alias; omit a redundant self-alias for single-word names.\n const itemTypeAlias = extensionName.replace(/-/g, \"\");\n const itemTypeAliases = itemTypeAlias === itemTypeName ? [] : [itemTypeAlias];\n const fieldName = `${extensionName.replace(/-/g, \"_\")}_note`;\n const migrationId = `${extensionName}-0001-init`;\n\n switch (capability) {\n case \"commands\":\n break;\n case \"hooks\":\n builderImports.push(\"defineAfterCommandHook\");\n definitions.push(\n \"\",\n \"// after_command hooks fire once pm finishes a command, receiving the items it\",\n \"// mutated. React here - sync to an external system, emit telemetry, or refresh\",\n '// derived context (\"project management = context management\"). This starter is a',\n \"// documented no-op on the success path; replace the body with your own reaction.\",\n \"export const afterCommandHook = defineAfterCommandHook((context) => {\",\n \" if (!context.ok) {\",\n \" return;\",\n \" }\",\n \" // `context.affected` lists the items pm mutated (id, status, changed_fields):\",\n \" // for (const item of context.affected ?? []) { /* ...item.id... */ }\",\n \"});\",\n );\n blueprintFields.push(\" hooks: { afterCommand: [afterCommandHook] },\");\n break;\n case \"search\":\n builderImports.push(\"defineSearchProvider\", \"defineVectorStoreAdapter\");\n definitions.push(\n \"\",\n \"// Search providers let packages customize how pm ranks and retrieves project\",\n \"// context. This starter is deterministic and dependency-free: replace the scoring\",\n \"// with your domain retrieval, embedding, or rerank logic as the package grows.\",\n \"export const searchProvider = defineSearchProvider({\",\n ` name: ${JSON.stringify(searchProviderName)},`,\n \" query: async (context) => {\",\n \" const needle = context.query.toLowerCase();\",\n \" const hits = context.documents\",\n \" .filter((document) => {\",\n ' const title = String(document.metadata.title ?? \"\").toLowerCase();',\n \" return title.includes(needle);\",\n \" })\",\n \" .map((document) => ({\",\n \" id: document.metadata.id,\",\n \" score: 1,\",\n ' matched_fields: [\"title\"],',\n \" }));\",\n \" return { hits };\",\n \" },\",\n \" embed: async (context) => [context.input.length],\",\n \"});\",\n \"\",\n \"// Vector-store adapters let packages own semantic index storage. This starter\",\n \"// returns a stable in-memory hit so generated tests can exercise the adapter\",\n \"// without external services.\",\n \"export const vectorStoreAdapter = defineVectorStoreAdapter({\",\n ` name: ${JSON.stringify(vectorAdapterName)},`,\n ' query: async (context) => [{ id: \"starter-vector-hit\", score: context.limit }],',\n \" upsert: async (context) => ({ upserted: context.points.length }),\",\n \" delete: async (context) => ({ deleted: context.ids.length }),\",\n \"});\",\n );\n blueprintFields.push(\" searchProviders: [searchProvider],\", \" vectorStoreAdapters: [vectorStoreAdapter],\");\n break;\n case \"importers\":\n builderImports.push(\"defineExporter\", \"defineImporter\");\n definitions.push(\n \"\",\n \"// Importers/exporters are the bridge between pm's context graph and another\",\n \"// project-management system. Keep the starter deterministic so package tests can\",\n \"// run without touching the network or filesystem; replace these payloads with\",\n \"// your adapter's real mapping as the package grows.\",\n \"export const importer = defineImporter(async (context) => ({\",\n \" imported: 1,\",\n ' source: context.options.source ?? \"starter\",',\n \" args: context.args,\",\n \"}));\",\n \"\",\n \"export const exporter = defineExporter(async (context) => ({\",\n \" exported: true,\",\n ' destination: context.options.destination ?? \"stdout\",',\n \" args: context.args,\",\n \"}));\",\n );\n blueprintFields.push(\n \" importers: [\",\n \" {\",\n ` name: ${JSON.stringify(adapterName)},`,\n \" importer,\",\n \" options: {\",\n ` action: ${JSON.stringify(`${adapterName} import`)},`,\n ' description: \"Import starter records into pm context.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--source\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Source name or path to import from.\",',\n \" },\",\n \" ],\",\n \" },\",\n \" },\",\n \" ],\",\n \" exporters: [\",\n \" {\",\n ` name: ${JSON.stringify(adapterName)},`,\n \" exporter,\",\n \" options: {\",\n ` action: ${JSON.stringify(`${adapterName} export`)},`,\n ' description: \"Export pm context into starter records.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--destination\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Destination name or path to export to.\",',\n \" },\",\n \" ],\",\n \" },\",\n \" },\",\n \" ],\",\n );\n break;\n case \"schema\":\n builderImports.push(\"defineItemField\", \"defineItemType\", \"defineMigration\");\n definitions.push(\n \"\",\n \"// Schema registrations let a package model its own project domain - the heart of\",\n '// \"project management = context management\". Item types and fields are GLOBAL',\n \"// contributions, so this package declares no `activation.commands` and pm\",\n \"// activates it conservatively for every command.\",\n \"export const noteField = defineItemField({\",\n ` name: ${JSON.stringify(fieldName)},`,\n ' type: \"string\",',\n \" optional: true,\",\n \"});\",\n \"\",\n \"export const itemType = defineItemType({\",\n ` name: ${JSON.stringify(itemTypeName)},`,\n \" // Replace with your domain's canonical plural folder name.\",\n ` folder: ${JSON.stringify(itemTypeFolder)},`,\n ` aliases: ${JSON.stringify(itemTypeAliases)},`,\n \" // Add field names here to force them at `pm create` time.\",\n \" required_create_fields: [],\",\n \"});\",\n \"\",\n \"// Migrations let a package evolve stored items as its schema changes. pm runs each\",\n \"// migration ONCE through the preflight gate (not once per item), passing a context\",\n \"// that identifies the migration itself: `context.id` is the migration id (not an\",\n \"// item id), alongside `context.pm_root`. This starter is a deterministic no-op so\",\n \"// package tests can invoke it without touching the corpus; replace the body with\",\n \"// your real rewrite.\",\n \"export const initMigration = defineMigration({\",\n ` id: ${JSON.stringify(migrationId)},`,\n ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`,\n \" mandatory: false,\",\n \" run: async (context) => ({ migrated: true, id: context.id }),\",\n \"});\",\n );\n blueprintFields.push(\" itemTypes: [itemType],\", \" itemFields: [noteField],\", \" migrations: [initMigration],\");\n break;\n case \"profile\":\n builderImports.push(\"defineProjectProfile\");\n definitions.push(\n \"\",\n \"// A project profile is the broadest customization primitive pm has: one\",\n \"// declarative bundle of item types, custom statuses, fields, a per-type workflow,\",\n \"// config knobs, create templates, and package recommendations. Once installed it\",\n \"// resolves by name through `pm profile list/show/apply`, which stages every\",\n \"// dimension idempotently like a core archetype. A profile registration is a\",\n \"// schema+config bundle, so the `schema` capability grants it.\",\n \"export const starterProfile = defineProjectProfile({\",\n ...buildProfileArchetypeFieldLines(extensionName),\n \"});\",\n );\n blueprintFields.push(\" profiles: [starterProfile],\");\n break;\n case \"renderers\":\n builderImports.push(\"defineRendererOverride\");\n definitions.push(\n \"\",\n \"// Renderer overrides customize how pm serializes a command's structured result\",\n '// for an output format (\"toon\" or \"json\"). pm runs this override for EVERY',\n \"// command's output in that format, so it scopes itself to THIS package's own\",\n \"// command and returns null - pass-through to pm's default renderer - for\",\n \"// everything else. Return a string to take over rendering.\",\n \"export const toonRenderer = defineRendererOverride((context) => {\",\n ` if (context.command !== ${JSON.stringify(commandName)}) {`,\n \" return null;\",\n \" }\",\n ` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`,\n \"});\",\n );\n blueprintFields.push(\" renderers: { toon: toonRenderer },\");\n break;\n case \"parser\":\n builderImports.push(\"defineParserOverride\");\n definitions.push(\n \"\",\n \"// Parser overrides preprocess a command's parsed options BEFORE its handler runs,\",\n \"// returning a delta - only the keys you set are merged over the parsed input. This\",\n \"// override is scoped to THIS package's own command; here it rewrites the deprecated\",\n \"// `--shout` boolean alias to the canonical `--upper` flag.\",\n \"export const pingParser = defineParserOverride((context) => {\",\n \" const options = { ...context.options };\",\n \" if (options.shout === true) {\",\n \" options.upper = true;\",\n \" }\",\n \" delete options.shout;\",\n \" return { options };\",\n \"});\",\n );\n blueprintFields.push(` parsers: { ${JSON.stringify(commandName)}: pingParser },`);\n break;\n case \"preflight\":\n builderImports.push(\"definePreflightOverride\");\n definitions.push(\n \"\",\n \"// Preflight overrides adjust pm's pre-run gate decision (extension migrations +\",\n \"// item-format checks) before EVERY command - the last registered override wins.\",\n \"// Return a delta of the keys you want to change (enforce_item_format_gate,\",\n \"// run_preflight_item_format_sync, run_extension_migrations,\",\n \"// enforce_mandatory_migration_gate); returning context.decision unchanged is a\",\n \"// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.\",\n \"export const preflightOverride = definePreflightOverride((context) => context.decision);\",\n );\n blueprintFields.push(\" preflights: [preflightOverride],\");\n break;\n case \"services\":\n builderImports.push(\"defineServiceOverride\");\n definitions.push(\n \"\",\n \"// Service overrides replace a built-in pm service. The `output_format` service\",\n \"// renders a command's structured result; returning the payload unchanged passes\",\n \"// through to pm's default formatting. This override scopes itself to THIS\",\n \"// package's own command and passes every other command through.\",\n \"export const outputService = defineServiceOverride((context) => {\",\n ` if (context.command !== ${JSON.stringify(commandName)}) {`,\n \" return context.payload;\",\n \" }\",\n ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,\n \"});\",\n );\n blueprintFields.push(\" services: { output_format: outputService },\");\n break;\n }\n\n return { builderImports, definitions, blueprintFields };\n}\n\n/**\n * Build the declarative (`composeExtension`) variant of the starter `index.ts` for\n * the chosen capability.\n *\n * Where {@link buildActivateBodyLines} emits an imperative `activate` that calls\n * `api.register*` directly, this emits the SDK's flagship declarative loop: the\n * capability's surfaces are authored with the `define*` builders (via the shared\n * {@link buildDeclarativeBlueprintSurface}), collected into an `ExtensionBlueprint`\n * by `defineExtensionBlueprint`, and turned into the runtime module by\n * `composeExtension` (which generates the `activate` that registers every blueprint\n * surface in order). Every definition, the blueprint, and the module are exported\n * so the colocated test can preflight the blueprint and exercise the module — see\n * {@link buildDeclarativeSampleTestSource}.\n *\n * It is package-mode by construction: `composeExtension` is a runtime SDK *value*\n * import, so it belongs in package-mode authoring where the SDK is a linked\n * dependency, not in the import-free extension-only starters.\n * {@link scaffoldExtensionProject} enforces that constraint before this is reached.\n */\nfunction buildDeclarativeEntrypoint(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string {\n const surface = buildDeclarativeBlueprintSurface(extensionName, commandName, capability);\n // `composeExtension`/`defineCommand`/`defineExtensionBlueprint` are always needed;\n // sort the full set so the import line is stable and idiomatic per capability.\n const builderImports = [\n \"composeExtension\",\n \"defineCommand\",\n \"defineExtensionBlueprint\",\n ...surface.builderImports,\n ].sort((left, right) => left.localeCompare(right));\n return [\n `import { ${builderImports.join(\", \")} } from \"@unbrained/pm-cli/sdk\";`,\n \"\",\n ...surface.definitions,\n \"\",\n \"// Declarative authoring: describe WHAT the package registers as a blueprint and\",\n \"// let `composeExtension` generate the `activate` that wires every surface in order,\",\n \"// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`\",\n \"// contract-checks the blueprint where it is authored. Keep `manifest.json`'s\",\n \"// `capabilities` equal to the set this blueprint derives.\",\n \"export const blueprint = defineExtensionBlueprint({\",\n ...surface.blueprintFields,\n \" // `deactivate` is the teardown counterpart to the generated `activate`: pm runs\",\n \" // it on host shutdown/reload to release anything the package opened (timers,\",\n \" // connections, caches). This starter holds none, so it stays a no-op.\",\n \" deactivate: () => {},\",\n \"});\",\n \"\",\n \"// `composeExtension(blueprint)` is the package's default export — the runtime\",\n \"// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`\",\n \"// in index.test.ts before publishing.\",\n \"export default composeExtension(blueprint);\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Build the capability-specific `node:test` block for the declarative starter:\n * a dedicated test that activates the composed module through\n * {@link ExtensionTestHarness} and asserts + invokes the capability's surface\n * (hook, search provider/adapter, importer/exporter, schema, renderer, parser,\n * preflight, or service override). Returns `[]` for the `commands` capability,\n * whose only surface — the starter command — is already covered by the base test.\n *\n * Each block mirrors the imperative {@link buildSampleTestSource} capability test\n * but reaches it through the harness's bound `assert*`/`run*` helpers instead of\n * the standalone helpers, so the declarative starter never threads\n * `activation.registrations` / `activation.parsers` / ... by hand.\n */\nfunction buildDeclarativeCapabilityTestBlock(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n capabilitiesLiteral: string,\n): string[] {\n if (capability === \"commands\") {\n return [];\n }\n const searchProviderName = `${extensionName}-search`;\n const vectorAdapterName = `${extensionName}-vector`;\n const adapterName = `${extensionName.replace(/-/g, \" \")} items`;\n const itemTypeName = extensionName;\n const itemTypeFolder = `${extensionName}s`;\n const fieldName = `${extensionName.replace(/-/g, \"_\")}_note`;\n const migrationId = `${extensionName}-0001-init`;\n const harness = [\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n ];\n const withHarnessCleanup = (body: string[]): string[] => [\n ...harness,\n \" let deactivated = false;\",\n \" try {\",\n ...body.map((line) => (line === \"\" ? line : ` ${line}`)),\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n ];\n switch (capability) {\n case \"hooks\":\n return [\n `test(${JSON.stringify(`${extensionName} reacts to commands via its after_command hook`)}, async () => {`,\n ...withHarnessCleanup([\n \" // assertHook throws unless an after_command hook is registered, so reaching the\",\n \" // next line already proves the hook is wired.\",\n ` ext.assertHook({ kind: \"after_command\", extensionName: ${JSON.stringify(extensionName)} });`,\n \" // runHook fires the hook through pm's real runner with a synthetic context and\",\n \" // returns the warnings it produced; a clean hook returns none.\",\n \" const warnings = await ext.runHook({\",\n ' kind: \"after_command\",',\n \" context: {\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n ' pm_root: \"\",',\n \" ok: true,\",\n \" affected: [],\",\n \" },\",\n \" });\",\n \" assert.deepEqual(warnings, []);\",\n ]),\n \"});\",\n \"\",\n ];\n case \"search\":\n return [\n `test(${JSON.stringify(`${extensionName} registers and invokes search primitives`)}, async () => {`,\n ...withHarnessCleanup([\n ` ext.assertSearchProvider({ provider: ${JSON.stringify(searchProviderName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n ` ext.assertVectorStoreAdapter({ adapter: ${JSON.stringify(vectorAdapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // The starter provider reads only document title/id, so `settings` is a minimal\",\n \" // typed stub and `documents` carry just the fields it inspects.\",\n \" const query = await ext.runSearchProvider({\",\n ` provider: ${JSON.stringify(searchProviderName)},`,\n ' operation: \"query\",',\n \" context: {\",\n ' query: \"sync\",',\n ' mode: \"semantic\",',\n ' tokens: [\"sync\"],',\n \" options: {},\",\n \" settings: {} as PmSettings,\",\n \" documents: [\",\n ' { metadata: { id: \"pm-1\", title: \"Sync external context\" }, body: \"\" },',\n ' { metadata: { id: \"pm-2\", title: \"Unrelated task\" }, body: \"\" },',\n \" ] as ItemDocument[],\",\n \" },\",\n \" });\",\n ' assert.deepEqual(query, { hits: [{ id: \"pm-1\", score: 1, matched_fields: [\"title\"] }] });',\n \"\",\n \" const embedding = await ext.runSearchProvider({\",\n ` provider: ${JSON.stringify(searchProviderName)},`,\n ' operation: \"embed\",',\n ' context: { input: \"abc\", settings: {} as PmSettings, model: \"starter-model\" },',\n \" });\",\n \" assert.deepEqual(embedding, [3]);\",\n \"\",\n \" const vectorHits = await ext.runVectorStoreAdapter({\",\n ` adapter: ${JSON.stringify(vectorAdapterName)},`,\n ' operation: \"query\",',\n \" context: { vector: [0.1, 0.2], limit: 2, settings: {} as PmSettings },\",\n \" });\",\n ' assert.deepEqual(vectorHits, [{ id: \"starter-vector-hit\", score: 2 }]);',\n ]),\n \"});\",\n \"\",\n ];\n case \"importers\":\n return [\n `test(${JSON.stringify(`${extensionName} registers and invokes import/export primitives`)}, async () => {`,\n ...withHarnessCleanup([\n ` ext.assertImporter({ importer: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n ` ext.assertExporter({ exporter: ${JSON.stringify(adapterName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" const imported = await ext.runImporter({\",\n ` importer: ${JSON.stringify(adapterName)},`,\n ' options: { source: \"tickets\" },',\n ' args: [\"batch-1\"],',\n \" });\",\n \" assert.equal(imported.handled, true);\",\n ' assert.deepEqual(imported.result, { imported: 1, source: \"tickets\", args: [\"batch-1\"] });',\n \"\",\n \" const exported = await ext.runExporter({\",\n ` exporter: ${JSON.stringify(adapterName)},`,\n ' options: { destination: \"archive\" },',\n ' args: [\"done\"],',\n \" });\",\n \" assert.equal(exported.handled, true);\",\n ' assert.deepEqual(exported.result, { exported: true, destination: \"archive\", args: [\"done\"] });',\n ]),\n \"});\",\n \"\",\n ];\n case \"schema\":\n return [\n `test(${JSON.stringify(`${extensionName} registers and runs its custom schema`)}, async () => {`,\n ...withHarnessCleanup(\n buildSchemaCapabilityAssertionLines({\n extensionName,\n itemTypeName,\n itemTypeFolder,\n fieldName,\n migrationId,\n }),\n ),\n \"});\",\n \"\",\n ];\n case \"profile\":\n return [\n `test(${JSON.stringify(`${extensionName} registers its project profile`)}, async () => {`,\n ...withHarnessCleanup(buildProfileCapabilityAssertionLines(extensionName)),\n \"});\",\n \"\",\n ];\n case \"renderers\":\n return [\n `test(${JSON.stringify(`${extensionName} registers and invokes its renderer override`)}, async () => {`,\n ...withHarnessCleanup([\n \" // assertRendererOverride throws unless a renderer is registered for the format,\",\n \" // so reaching the next line already proves the wiring.\",\n ` const override = ext.assertRendererOverride({ format: \"toon\", extensionName: ${JSON.stringify(extensionName)} });`,\n ' assert.equal(override.format, \"toon\");',\n \"\",\n \" // runRendererOverride renders through pm's real runner. The override customizes\",\n \" // only THIS package's command output and returns a string the host uses verbatim.\",\n \" const rendered = await ext.runRendererOverride({\",\n ' format: \"toon\",',\n ` command: ${JSON.stringify(commandName)},`,\n \" result: { ok: true },\",\n \" });\",\n \" assert.equal(rendered.overridden, true);\",\n ` assert.equal(rendered.rendered, ${JSON.stringify(`${extensionName}: `)} + JSON.stringify({ ok: true }));`,\n \"\",\n \" // Output for any other command passes through to pm's default renderer.\",\n \" const passthrough = await ext.runRendererOverride({\",\n ' format: \"toon\",',\n ' command: \"list\",',\n \" result: { ok: true },\",\n \" });\",\n \" assert.equal(passthrough.overridden, false);\",\n ]),\n \"});\",\n \"\",\n ];\n case \"parser\":\n return [\n `test(${JSON.stringify(`${extensionName} rewrites command options via its parser override`)}, async () => {`,\n ...withHarnessCleanup([\n \" // assertParserOverride throws unless a parser is registered for the command, so\",\n \" // reaching the next line already proves the wiring.\",\n ` ext.assertParserOverride({ command: ${JSON.stringify(commandName)}, extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runParserOverride runs the override through pm's real parser runner and returns\",\n \" // the rewritten context. The starter rewrites the deprecated `shout` alias to the\",\n \" // canonical `upper` flag.\",\n \" const result = await ext.runParserOverride({\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n \" options: { shout: true },\",\n \" global: {},\",\n ' pm_root: \"\",',\n \" });\",\n \" assert.equal(result.overridden, true);\",\n \" assert.deepEqual(result.context.options, { upper: true });\",\n \"\",\n \" // End to end: feed the rewritten options into the command handler to prove\",\n \" // `pm <command> --shout` surfaces the normalized `upper` flag in the result.\",\n ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)}, options: result.context.options });`,\n \" assert.equal(invocation.handled, true);\",\n \" assert.deepEqual(invocation.result, {\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n ` command: ${JSON.stringify(commandName)},`,\n \" upper: true,\",\n ' message: \"Starter extension scaffold is active.\",',\n \" });\",\n ]),\n \"});\",\n \"\",\n ];\n case \"preflight\":\n return [\n `test(${JSON.stringify(`${extensionName} returns a preflight gate decision via its override`)}, async () => {`,\n ...withHarnessCleanup([\n \" // assertPreflightOverride throws unless a preflight override is registered, so\",\n \" // reaching the next line already proves the wiring.\",\n ` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runPreflightOverride runs the override through pm's real runner with a synthetic\",\n \" // gate decision. The starter echoes the decision unchanged; replace the\",\n \" // values/assertions with your real policy.\",\n \" const decision = {\",\n \" enforce_item_format_gate: true,\",\n \" run_preflight_item_format_sync: false,\",\n \" run_extension_migrations: true,\",\n \" enforce_mandatory_migration_gate: false,\",\n \" };\",\n \" const result = await ext.runPreflightOverride({\",\n ` command: ${JSON.stringify(commandName)},`,\n \" args: [],\",\n \" options: {},\",\n \" global: {},\",\n ' pm_root: \"\",',\n \" decision,\",\n \" });\",\n \" assert.equal(result.overridden, true);\",\n \" assert.deepEqual(result.decision, decision);\",\n ]),\n \"});\",\n \"\",\n ];\n case \"services\":\n return [\n `test(${JSON.stringify(`${extensionName} customizes command output via its service override`)}, async () => {`,\n ...withHarnessCleanup([\n \" // assertServiceOverride throws unless a service override is registered for the\",\n \" // service, so reaching the next line proves the wiring.\",\n ` ext.assertServiceOverride({ service: \"output_format\", extensionName: ${JSON.stringify(extensionName)} });`,\n \"\",\n \" // runServiceOverride runs the override through pm's real service runner. The\",\n \" // override customizes only THIS package's command output (handled), passing every\",\n \" // other command through (not handled).\",\n \" const handled = await ext.runServiceOverride({\",\n ' service: \"output_format\",',\n ` command: ${JSON.stringify(commandName)},`,\n \" payload: { ok: true },\",\n \" });\",\n \" assert.equal(handled.handled, true);\",\n ` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(extensionName)}, payload: { ok: true } });`,\n \"\",\n \" // Output for any other command passes through to pm's default formatter.\",\n \" const passthrough = await ext.runServiceOverride({\",\n ' service: \"output_format\",',\n ' command: \"list\",',\n \" payload: { ok: true },\",\n \" });\",\n \" assert.equal(passthrough.handled, false);\",\n ]),\n \"});\",\n \"\",\n ];\n }\n}\n\n/**\n * Build the declarative variant of the colocated `node:test` suite\n * (`index.test.ts`) for the chosen capability's `composeExtension` starter.\n *\n * Like {@link buildSampleTestSource}, this uses the harness-bound runtime\n * helpers; it also exercises the author-time capstone the declarative loop\n * unlocks:\n * `assertExtensionPreflight(blueprint, { identity, target })` (lint + manifest\n * synthesis + version-compat in one call) over the exported `blueprint`, and the\n * ergonomic runtime `createExtensionTestHarness(module)` whose `assert*`/`run*`/\n * `deactivate` methods are pre-bound to the right activation sub-registry. The base\n * suite covers preflight, the starter command, and teardown; for non-`commands`\n * capabilities {@link buildDeclarativeCapabilityTestBlock} adds a dedicated test for\n * the capability's surface. The `identity`/`target` versions are pinned to the\n * scaffolded `pm_min_version` so the synthesized manifest is trivially compatible\n * and the suite stays deterministic; an author edits them as the package matures.\n */\nfunction buildDeclarativeSampleTestSource(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string {\n const parserEnabled = capability === \"parser\";\n // The preflight report's capability set is DERIVED from the blueprint and SORTED,\n // so assert against the sorted manifest capabilities (a set match in canonical\n // order); the harness `capabilities` grant uses the same literal.\n const capabilitiesLiteral = JSON.stringify([...SCAFFOLD_MANIFEST_CAPABILITIES[capability]].sort());\n return [\n 'import assert from \"node:assert/strict\";',\n 'import { test } from \"node:test\";',\n 'import { assertExtensionDeactivated, assertExtensionPreflight, createExtensionTestHarness } from \"@unbrained/pm-cli/sdk/testing\";',\n // The search sample's synthetic query/vector contexts reference these SDK types\n // for their typed-stub fixtures; other capabilities need no extra type imports.\n ...(capability === \"search\" ? ['import type { ItemDocument, PmSettings } from \"@unbrained/pm-cli/sdk\";'] : []),\n 'import extension, { blueprint } from \"./index.ts\";',\n \"\",\n ...SAMPLE_HARNESS_CLEANUP_LINES,\n `test(${JSON.stringify(`${extensionName} passes author-time preflight`)}, () => {`,\n \" // assertExtensionPreflight is the author-time capstone: it lints the blueprint,\",\n \" // synthesizes the least-privilege manifest from `identity`, and checks the version\",\n \" // bounds against `target` in one call, throwing on any blocking finding. It returns\",\n \" // the full report so you can inspect the derived data.\",\n \" const report = assertExtensionPreflight(blueprint, {\",\n \" identity: {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ' version: \"0.1.0\",',\n ' entry: \"./index.ts\",',\n \" priority: 0,\",\n ` pm_min_version: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)},`,\n \" },\",\n ` target: { pmVersion: ${JSON.stringify(SCAFFOLD_PM_MIN_VERSION)} },`,\n \" });\",\n \" // The capability set is DERIVED from the blueprint, never hand-synced. Keep\",\n \" // manifest.json's `capabilities` equal to this list (set match, sorted).\",\n ` assert.deepEqual(report.capabilities, ${capabilitiesLiteral});`,\n ` assert.deepEqual(report.manifest?.capabilities, ${capabilitiesLiteral});`,\n \"});\",\n \"\",\n `test(${JSON.stringify(`${extensionName} registers and runs its starter command`)}, async () => {`,\n \" // createExtensionTestHarness activates the composed module once and binds the\",\n \" // assert*/run*/deactivate helpers to the right activation sub-registry, so you\",\n \" // never thread activation.registrations vs activation.commands by hand.\",\n \" // `capabilities` mirrors manifest.json so the in-memory activation grants what the\",\n \" // blueprint needs.\",\n \" const ext = await createExtensionTestHarness(extension, {\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` capabilities: ${capabilitiesLiteral},`,\n \" });\",\n \" let deactivated = false;\",\n \" try {\",\n \" // assertCommandContract throws unless the command is registered, so reaching\",\n \" // the next line already proves the wiring; assert on the returned definition\",\n \" // to demonstrate inspecting registered metadata.\",\n ` const registered = ext.assertCommandContract({ command: ${JSON.stringify(commandName)} });`,\n ' assert.equal(typeof registered.command.description, \"string\");',\n \"\",\n \" // runCommand invokes the handler through pm's real dispatch engine, so this\",\n \" // asserts behavior - not just that the command is wired. Replace these\",\n \" // assertions as you flesh out your command.\",\n ` const invocation = await ext.runCommand({ command: ${JSON.stringify(commandName)} });`,\n \" assert.equal(invocation.handled, true);\",\n \" assert.deepEqual(invocation.result, {\",\n \" ok: true,\",\n ` source: ${JSON.stringify(extensionName)},`,\n ` command: ${JSON.stringify(commandName)},`,\n // The parser starter's command surfaces the normalized `upper` flag, false when\n // the command is invoked without `--shout`/`--upper`.\n ...(parserEnabled ? [\" upper: false,\"] : []),\n ' message: \"Starter extension scaffold is active.\",',\n \" });\",\n \" // deactivate runs pm's real teardown engine over the module; exactly one\",\n \" // extension tears down with no failures.\",\n \" const teardown = await ext.deactivate();\",\n \" assertExtensionDeactivated(teardown);\",\n \" deactivated = true;\",\n ...SAMPLE_HARNESS_FINALLY_LINES,\n \"});\",\n \"\",\n ...buildDeclarativeCapabilityTestBlock(extensionName, commandName, capability, capabilitiesLiteral),\n ].join(\"\\n\");\n}\n\n/**\n * Build the README for the declarative (`composeExtension`) package starter for\n * the chosen capability.\n *\n * It documents the same metadata/validation sections as the imperative package\n * README but frames the entrypoint around the declarative loop and the author-time\n * preflight test, so the generated docs match the generated `index.ts`/\n * `index.test.ts`. The included-files bullets, the Declarative Authoring blueprint\n * fields, and the activation section are capability-aware: the `schema` starter\n * contributes a global item type (so it omits `activation.commands`), while every\n * other capability declares the command paths that lazily activate the package.\n */\nfunction buildDeclarativePackageReadme(\n packageName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n): string {\n // The schema/profile starters omit `activation.commands` (their surface is a\n // global contribution), so describe the manifest accurately and use the\n // conservative-activation section.\n const manifestBullet = buildScaffoldManifestBullet(capability, \"package\");\n const activationSection = buildScaffoldActivationReadmeSection(capability, \"package\");\n return [\n `# ${packageName}`,\n \"\",\n \"Generated by `pm package init --declarative`.\",\n \"\",\n \"## Included Files\",\n \"- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.\",\n manifestBullet,\n `- \\`index.ts\\`: the TypeScript manifest entry — a \\`defineExtensionBlueprint\\` blueprint (${DECLARATIVE_ENTRYPOINT_SURFACE_PHRASE[capability]}) composed into the runtime module by \\`composeExtension\\`, plus a \\`deactivate\\` teardown stub.`,\n \"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.\",\n TSCONFIG_BULLET,\n \"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.\",\n \"\",\n \"## Quick Start\",\n \"This package is authored AND loaded as TypeScript: the manifest `entry` is\",\n \"`./index.ts` and pm imports it directly via Node's native type stripping\",\n \"(Node >=22.18), so there is no build step — install and run:\",\n \"```bash\",\n \"npm install\",\n \"pm install --project <package-path>\",\n `pm ${commandName}`,\n \"pm package doctor --project --detail summary\",\n \"```\",\n \"\",\n \"## Declarative Authoring\",\n \"`index.ts` uses the SDK's declarative authoring loop instead of an imperative\",\n \"`activate` body. You describe WHAT the package registers as an\",\n \"`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires\",\n \"every surface in order:\",\n \"- The `define*` builders author each surface with literal-type preservation and\",\n \" contextual handler inference (`defineCommand`, `defineSearchProvider`,\",\n \" `defineItemType`, `defineParserOverride`, ...).\",\n `- \\`defineExtensionBlueprint({ ... })\\` collects the definitions into the blueprint;`,\n ` this starter populates ${DECLARATIVE_CAPABILITY_BLUEPRINT_FIELDS[capability]}. Add more`,\n \" fields as the package grows.\",\n \"- `composeExtension(blueprint)` is the default export — the runtime module pm\",\n \" loads. Its generated `activate` requires exactly the capabilities the blueprint\",\n \" derives, so `manifest.json`'s `capabilities` never drift.\",\n \"\",\n \"## Validate the Package\",\n \"`npm install` pulls the peer SDK and TypeScript. `npm test` is the default\",\n \"validation gate: it type-checks the package, then runs the colocated sample:\",\n \"```bash\",\n \"npm install\",\n \"npm test\",\n \"```\",\n \"`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`\",\n \"(the author-time lint + manifest synthesis + version-compatibility check over the\",\n \"exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose\",\n \"`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).\",\n \"`npm run typecheck` is available when you only want the SDK contract check.\",\n \"`npm run test:runtime` runs just `node --test`, which strips types on load and\",\n \"executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`\",\n \"helpers - no compile step and no extra test runner required.\",\n ...activationSection,\n \"\",\n \"## Compatibility Bounds\",\n \"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:\",\n `- \\`manifest_version\\` (integer): manifest schema generation. Leave at \\`${SCAFFOLD_MANIFEST_VERSION}\\` unless you adopt a newer manifest schema.`,\n `- \\`pm_min_version\\` (string): lowest pm CLI version that may load this package. Scaffolded as \\`${SCAFFOLD_PM_MIN_VERSION}\\`. The loader blocks the package on older CLIs.`,\n \"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.\",\n \"\",\n \"## Policy Metadata\",\n \"The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: \\\"strict\\\"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.\",\n \"\",\n \"## Notes\",\n \"- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload — there is no `.js` to regenerate.\",\n \"- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).\",\n \"- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.\",\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Derived, deterministic identifier set the package `define*` README snippets\n * reference: the search/vector adapter names, the importer/exporter adapter\n * label, the custom item type/folder/aliases, the note field, and the seed\n * migration id. All are projected from `extensionName` so the generated snippet\n * matches the generated `index.ts`.\n */\ninterface ScaffoldSnippetNames {\n searchProviderName: string;\n vectorAdapterName: string;\n adapterName: string;\n itemTypeName: string;\n itemTypeFolder: string;\n itemTypeAliases: string[];\n fieldName: string;\n migrationId: string;\n}\n\n/**\n * Project the {@link ScaffoldSnippetNames} for `extensionName`, omitting a\n * redundant self-alias when the de-hyphenated form already equals the type name.\n */\nfunction buildScaffoldSnippetNames(extensionName: string): ScaffoldSnippetNames {\n const itemTypeName = extensionName;\n const itemTypeAlias = extensionName.replace(/-/g, \"\");\n return {\n searchProviderName: `${extensionName}-search`,\n vectorAdapterName: `${extensionName}-vector`,\n adapterName: `${extensionName.replace(/-/g, \" \")} items`,\n itemTypeName,\n itemTypeFolder: `${extensionName}s`,\n itemTypeAliases: itemTypeAlias === itemTypeName ? [] : [itemTypeAlias],\n fieldName: `${extensionName.replace(/-/g, \"_\")}_note`,\n migrationId: `${extensionName}-0001-init`,\n };\n}\n\n/**\n * Build the comma-separated `define*` builder import list for the README\n * snippet, including only the builders the chosen capability demonstrates.\n */\nfunction buildDefineBuilderImports(capability: ExtensionScaffoldCapability): string {\n return [\n \"defineCommand\",\n ...(capability === \"hooks\" ? [\"defineAfterCommandHook\"] : []),\n ...(capability === \"search\" ? [\"defineSearchProvider\", \"defineVectorStoreAdapter\"] : []),\n ...(capability === \"importers\" ? [\"defineImporter\", \"defineExporter\"] : []),\n ...(capability === \"schema\" ? [\"defineItemType\", \"defineItemField\", \"defineMigration\"] : []),\n ...(capability === \"profile\" ? [\"defineProjectProfile\"] : []),\n ...(capability === \"renderers\" ? [\"defineRendererOverride\"] : []),\n ...(capability === \"parser\" ? [\"defineParserOverride\"] : []),\n ...(capability === \"preflight\" ? [\"definePreflightOverride\"] : []),\n ...(capability === \"services\" ? [\"defineServiceOverride\"] : []),\n ].join(\", \");\n}\n\n/**\n * Build the exported `define*` declarations for the README snippet: the base\n * `pingCommand` (with parser flags for the parser capability) plus the one\n * capability-specific export the chosen capability demonstrates.\n */\nfunction buildDefineBuilderExports(\n extensionName: string,\n commandName: string,\n capability: ExtensionScaffoldCapability,\n names: ScaffoldSnippetNames,\n): string[] {\n const lines = [\n \"export const pingCommand = defineCommand({\",\n ` name: ${JSON.stringify(commandName)},`,\n ' description: \"Starter scaffold command. Replace with your own behavior.\",',\n // The parser starter's command declares the flags its override normalizes so\n // the demo is runnable through `pm <command> --shout`, and surfaces the\n // canonical `upper` flag in the result.\n ...(capability === \"parser\"\n ? [\n \" flags: [\",\n ' { long: \"--shout\", value_type: \"boolean\", description: \"Deprecated alias for --upper.\" },',\n ' { long: \"--upper\", value_type: \"boolean\", description: \"Canonical flag the parser produces.\" },',\n \" ],\",\n \" run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),\",\n ]\n : [\" run: (context) => ({ ok: true, command: context.command }),\"]),\n \"});\",\n ];\n if (capability === \"hooks\") {\n lines.push(\n \"\",\n \"export const afterCommandHook = defineAfterCommandHook((context) => {\",\n \" if (!context.ok) return;\",\n \" // React to context.affected here as your package grows.\",\n \"});\",\n );\n }\n if (capability === \"search\") {\n lines.push(\n \"\",\n \"export const searchProvider = defineSearchProvider({\",\n ` name: ${JSON.stringify(names.searchProviderName)},`,\n \" query: async (context) => ({\",\n \" hits: context.documents\",\n \" .filter((document) => String(document.metadata.title ?? \\\"\\\").toLowerCase().includes(context.query.toLowerCase()))\",\n \" .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: [\\\"title\\\"] })),\",\n \" }),\",\n \" embed: async (context) => [context.input.length],\",\n \"});\",\n \"\",\n \"export const vectorStoreAdapter = defineVectorStoreAdapter({\",\n ` name: ${JSON.stringify(names.vectorAdapterName)},`,\n \" query: async (context) => [{ id: \\\"starter-vector-hit\\\", score: context.limit }],\",\n \" upsert: async (context) => ({ upserted: context.points.length }),\",\n \" delete: async (context) => ({ deleted: context.ids.length }),\",\n \"});\",\n );\n }\n if (capability === \"importers\") {\n lines.push(\n \"\",\n \"export const importer = defineImporter(async (context) => ({\",\n \" imported: 1,\",\n \" source: context.options.source ?? \\\"starter\\\",\",\n \" args: context.args,\",\n \"}));\",\n \"\",\n \"export const exporter = defineExporter(async (context) => ({\",\n \" exported: true,\",\n \" destination: context.options.destination ?? \\\"stdout\\\",\",\n \" args: context.args,\",\n \"}));\",\n );\n }\n if (capability === \"schema\") {\n lines.push(\n \"\",\n `export const noteField = defineItemField({ name: ${JSON.stringify(names.fieldName)}, type: \"string\", optional: true });`,\n \"\",\n \"export const itemType = defineItemType({\",\n ` name: ${JSON.stringify(names.itemTypeName)},`,\n ` folder: ${JSON.stringify(names.itemTypeFolder)},`,\n ` aliases: ${JSON.stringify(names.itemTypeAliases)},`,\n \" required_create_fields: [],\",\n \"});\",\n \"\",\n \"export const initMigration = defineMigration({\",\n ` id: ${JSON.stringify(names.migrationId)},`,\n ` description: ${JSON.stringify(`Initialize ${extensionName} schema state.`)},`,\n \" mandatory: false,\",\n \" run: async (context) => ({ migrated: true, id: context.id }),\",\n \"});\",\n );\n }\n if (capability === \"profile\") {\n // Abbreviated illustration; the generated index.ts populates every archetype\n // dimension (types, statuses, fields, workflow, config, template, packages).\n lines.push(\n \"\",\n \"export const starterProfile = defineProjectProfile({\",\n ` name: ${JSON.stringify(extensionName)},`,\n ` title: ${JSON.stringify(`${extensionName} archetype`)},`,\n ' summary: \"Starter project profile. Replace these dimensions with your own archetype.\",',\n \" types: [\",\n ` { name: ${JSON.stringify(names.itemTypeName)}, folder: ${JSON.stringify(names.itemTypeFolder)} },`,\n \" ],\",\n \" // ...plus statuses, fields, workflows, config, templates, and packages.\",\n \"});\",\n );\n }\n if (capability === \"renderers\") {\n lines.push(\n \"\",\n \"export const toonRenderer = defineRendererOverride((context) => {\",\n ` if (context.command !== ${JSON.stringify(commandName)}) return null;`,\n ` return ${JSON.stringify(`${extensionName}: `)} + JSON.stringify(context.result);`,\n \"});\",\n );\n }\n if (capability === \"parser\") {\n lines.push(\n \"\",\n \"export const pingParser = defineParserOverride((context) => {\",\n \" const options = { ...context.options };\",\n \" if (options.shout === true) options.upper = true;\",\n \" delete options.shout;\",\n \" return { options };\",\n \"});\",\n );\n }\n if (capability === \"preflight\") {\n lines.push(\n \"\",\n \"// Return a delta of the gate-decision keys you want to change; returning\",\n \"// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).\",\n \"export const preflightOverride = definePreflightOverride((context) => context.decision);\",\n );\n }\n if (capability === \"services\") {\n lines.push(\n \"\",\n \"export const outputService = defineServiceOverride((context) => {\",\n ` if (context.command !== ${JSON.stringify(commandName)}) return context.payload;`,\n ` return { rendered_by: ${JSON.stringify(extensionName)}, payload: context.payload };`,\n \"});\",\n );\n }\n return lines;\n}\n\n/**\n * Build the `activate` body registrations for the README snippet: one\n * `api.register*`/`api.hooks.*` call wiring the capability-specific exports\n * produced by {@link buildDefineBuilderExports}.\n */\nfunction buildDefineBuilderActivate(\n commandName: string,\n capability: ExtensionScaffoldCapability,\n names: ScaffoldSnippetNames,\n): string[] {\n const lines: string[] = [];\n if (capability === \"renderers\") {\n lines.push(' api.registerRenderer(\"toon\", toonRenderer);');\n }\n if (capability === \"parser\") {\n lines.push(` api.registerParser(${JSON.stringify(commandName)}, pingParser);`);\n }\n if (capability === \"preflight\") {\n lines.push(\" api.registerPreflight(preflightOverride);\");\n }\n if (capability === \"services\") {\n lines.push(' api.registerService(\"output_format\", outputService);');\n }\n if (capability === \"hooks\") {\n lines.push(\" api.hooks.afterCommand(afterCommandHook);\");\n }\n if (capability === \"search\") {\n lines.push(\" api.registerSearchProvider(searchProvider);\", \" api.registerVectorStoreAdapter(vectorStoreAdapter);\");\n }\n if (capability === \"schema\") {\n lines.push(\n \" api.registerItemFields([noteField]);\",\n \" api.registerItemTypes([itemType]);\",\n \" api.registerMigration(initMigration);\",\n );\n }\n if (capability === \"profile\") {\n lines.push(\" api.registerProfile(starterProfile);\");\n }\n if (capability === \"importers\") {\n lines.push(\n ` api.registerImporter(${JSON.stringify(names.adapterName)}, importer, {`,\n ` action: ${JSON.stringify(`${names.adapterName} import`)},`,\n ' description: \"Import starter records into pm context.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--source\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Source name or path to import from.\",',\n \" },\",\n \" ],\",\n \" });\",\n ` api.registerExporter(${JSON.stringify(names.adapterName)}, exporter, {`,\n ` action: ${JSON.stringify(`${names.adapterName} export`)},`,\n ' description: \"Export pm context into starter records.\",',\n \" flags: [\",\n \" {\",\n ' long: \"--destination\",',\n ' value_name: \"name\",',\n ' value_type: \"string\",',\n ' description: \"Destination name or path to export to.\",',\n \" },\",\n \" ],\",\n \" });\",\n );\n }\n return lines;\n}\n\n/**\n * Implements build starter extension scaffold files for the public runtime surface of this module.\n */\nexport function buildStarterExtensionScaffoldFiles(\n extensionName: string,\n commandName: string,\n vocabulary: \"extension\" | \"package\",\n capability: ExtensionScaffoldCapability = \"commands\",\n declarative: boolean = false,\n): Record<string, string> {\n const packageName = `pm-${extensionName}`;\n const capabilities = SCAFFOLD_MANIFEST_CAPABILITIES[capability];\n const activationCommands = buildScaffoldActivationCommands(extensionName, commandName, capability);\n const manifest = `${JSON.stringify(\n {\n name: extensionName,\n version: \"0.1.0\",\n entry: \"./index.ts\",\n manifest_version: SCAFFOLD_MANIFEST_VERSION,\n pm_min_version: SCAFFOLD_PM_MIN_VERSION,\n trusted: true,\n sandbox_profile: \"strict\",\n permissions: { ...SCAFFOLD_DECLARED_PERMISSIONS },\n capabilities,\n // Declares the exact command paths `activate` registers so pm activates\n // this package lazily — only when an invoked command matches — mirroring\n // every first-party bundled package. Keep it in sync with the entrypoint.\n // The schema and profile starters omit this field (empty list) so their\n // global contribution — a custom item type/field, or a project profile\n // resolved by `pm profile` — stays available to built-in commands (see\n // buildScaffoldActivationCommands).\n ...(activationCommands.length > 0 ? { activation: { commands: activationCommands } } : {}),\n },\n null,\n 2,\n )}\\n`;\n // The entrypoint is authored AND loaded as TypeScript (ADR pm-2c28 / pm-m1uz):\n // the manifest `entry` points at `./index.ts` and pm imports it directly via\n // Node's native type stripping (Node >=22.18) — there is no compile step and no\n // `.js` artifact. The typed `ExtensionApi` parameter is checked against the SDK\n // contract at author time (`npm run typecheck`).\n const entrypoint = [\n 'import type { ExtensionApi } from \"@unbrained/pm-cli/sdk\";',\n \"\",\n \"export function activate(api: ExtensionApi): void {\",\n ...buildActivateBodyLines(extensionName, commandName, capability),\n \"}\",\n \"\",\n \"// `deactivate` is the teardown counterpart to `activate`: pm runs it on host\",\n \"// shutdown/reload (e.g. the MCP server between requests) to release anything\",\n \"// `activate` opened - timers, connections, caches. This starter holds no such\",\n \"// resources, so it stays a documented no-op; add cleanup here as you grow.\",\n \"export function deactivate(): void {}\",\n \"\",\n \"export default {\",\n \" activate,\",\n \" deactivate,\",\n \"};\",\n \"\",\n ].join(\"\\n\");\n const tsconfig = `${JSON.stringify(SCAFFOLD_TSCONFIG, null, 2)}\\n`;\n // README bullet describing what index.ts wires, kept in sync with the chosen\n // capability so the generated docs match the generated code.\n const entrypointBullet = ENTRYPOINT_BULLETS[capability];\n // The schema/profile starters omit `activation.commands` (their surface is a\n // global contribution), so describe the manifest accurately instead of\n // referencing a field they deliberately lack.\n const manifestBullet = buildScaffoldManifestBullet(capability, vocabulary);\n if (vocabulary === \"package\") {\n const packageJson = `${JSON.stringify(\n {\n name: packageName,\n version: \"0.1.0\",\n private: true,\n type: \"module\",\n keywords: [\"pm-package\"],\n engines: {\n node: SCAFFOLD_NODE_ENGINE,\n },\n // There is no build step: pm loads the `./index.ts` manifest entry\n // directly via Node's native type stripping (Node >=22.18). `typecheck`\n // validates the source against the SDK contracts (`tsc --noEmit`), and\n // `test` is the self-validating author gate: typecheck first, then run\n // the colocated sample with Node's built-in runner (which strips types\n // on load) against the peer SDK testing helpers — no third-party test\n // runner or compile output required. `test:runtime` remains available\n // for tight loops after a separate `npm run typecheck`.\n scripts: {\n typecheck: \"tsc --noEmit\",\n \"test:runtime\": \"node --test\",\n test: \"npm run typecheck && npm run test:runtime\",\n },\n peerDependencies: {\n \"@unbrained/pm-cli\": `>=${SCAFFOLD_PM_MIN_VERSION}`,\n },\n devDependencies: {\n \"@types/node\": SCAFFOLD_TYPES_NODE_VERSION,\n typescript: SCAFFOLD_TYPESCRIPT_VERSION,\n },\n pm: {\n aliases: [extensionName],\n extensions: [\".\"],\n docs: [\"README.md\"],\n examples: [\"README.md\"],\n catalog: {\n display_name: extensionName,\n category: \"workflow\",\n summary: \"Starter pm package scaffold.\",\n tags: [\"starter\"],\n },\n },\n },\n null,\n 2,\n )}\\n`;\n // node:test sample: demonstrates validating the package with the SDK testing\n // helpers without adding a third-party test runner. The suite covers the\n // capability the scaffold targets (command invocation, and for the hooks\n // capability, the after_command lifecycle hook).\n const sampleTest = buildSampleTestSource(extensionName, commandName, capability);\n const sampleTestBullet = SAMPLE_TEST_BULLETS[capability];\n // The package commits only TypeScript source — pm loads the `.ts` entry\n // directly, so there is no compiled output to ignore. Keep dependencies and\n // the tsc incremental cache out of version control.\n const gitignore = [\n \"node_modules/\",\n \"*.log\",\n \"*.tsbuildinfo\",\n \"\",\n ].join(\"\\n\");\n const names = buildScaffoldSnippetNames(extensionName);\n const defineBuilderImports = buildDefineBuilderImports(capability);\n const defineBuilderSnippet = [\n \"```ts\",\n `import { ${defineBuilderImports} } from \"@unbrained/pm-cli/sdk\";`,\n 'import type { ExtensionApi } from \"@unbrained/pm-cli/sdk\";',\n \"\",\n ...buildDefineBuilderExports(extensionName, commandName, capability, names),\n \"\",\n \"export function activate(api: ExtensionApi): void {\",\n \" api.registerCommand(pingCommand);\",\n ...buildDefineBuilderActivate(commandName, capability, names),\n \"}\",\n \"\",\n \"export function deactivate(): void {}\",\n \"\",\n \"export default { activate, deactivate };\",\n \"```\",\n ];\n const packageReadme = [\n `# ${packageName}`,\n \"\",\n \"Generated by `pm package init`.\",\n \"\",\n \"## Included Files\",\n \"- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.\",\n manifestBullet,\n entrypointBullet,\n sampleTestBullet,\n TSCONFIG_BULLET,\n \"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.\",\n \"\",\n \"## Quick Start\",\n \"This package is authored AND loaded as TypeScript: the manifest `entry` is\",\n \"`./index.ts` and pm imports it directly via Node's native type stripping\",\n \"(Node >=22.18), so there is no build step — install and run:\",\n \"```bash\",\n \"npm install\",\n \"pm install --project <package-path>\",\n `pm ${commandName}`,\n \"pm package doctor --project --detail summary\",\n \"```\",\n \"\",\n \"## Validate the Package\",\n \"`npm install` pulls the peer SDK and TypeScript. `npm test` is the default\",\n \"validation gate: it type-checks the package, then runs the colocated sample:\",\n \"```bash\",\n \"npm install\",\n \"npm test\",\n \"```\",\n \"`npm run typecheck` is available when you only want the SDK contract check.\",\n \"`npm run test:runtime` runs just `node --test`, which strips types on load and\",\n \"executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`\",\n \"helpers - no compile step and no extra test runner required.\",\n \"\",\n \"## Authoring With define* Builders\",\n \"`index.ts` is authored fully in TypeScript so every registration is checked\",\n \"against the SDK contracts at author time. Use the public SDK authoring\",\n \"builders for exported definitions you want literal-type preservation,\",\n \"contextual handler inference, and direct unit tests for:\",\n ...defineBuilderSnippet,\n \"The builders return their argument unchanged; runtime validation still lives\",\n \"in `api.register*`, and behavior validation lives in `sdk/testing`.\",\n ...PACKAGE_CAPABILITY_README_SECTIONS[capability],\n ...buildScaffoldActivationReadmeSection(capability, \"package\"),\n \"\",\n \"## Compatibility Bounds\",\n \"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:\",\n `- \\`manifest_version\\` (integer): manifest schema generation. Leave at \\`${SCAFFOLD_MANIFEST_VERSION}\\` unless you adopt a newer manifest schema.`,\n `- \\`pm_min_version\\` (string): lowest pm CLI version that may load this package. Scaffolded as \\`${SCAFFOLD_PM_MIN_VERSION}\\`. The loader blocks the package on older CLIs.`,\n \"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.\",\n \"\",\n \"## Policy Metadata\",\n \"The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: \\\"strict\\\"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.\",\n \"\",\n \"## Notes\",\n \"- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload — there is no `.js` to regenerate.\",\n \"- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).\",\n \"- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.\",\n \"- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.\",\n \"\",\n ].join(\"\\n\");\n // The declarative starter swaps the imperative entrypoint/test/README for the\n // `composeExtension` blueprint form (package-mode, any capability, enforced by\n // scaffoldExtensionProject). package.json, manifest.json, tsconfig.json, and\n // .gitignore are identical to the imperative starter for the same capability.\n return {\n \"package.json\": packageJson,\n \"manifest.json\": manifest,\n \"index.ts\": declarative ? buildDeclarativeEntrypoint(extensionName, commandName, capability) : entrypoint,\n \"index.test.ts\": declarative ? buildDeclarativeSampleTestSource(extensionName, commandName, capability) : sampleTest,\n \"tsconfig.json\": tsconfig,\n \".gitignore\": gitignore,\n \"README.md\": declarative ? buildDeclarativePackageReadme(packageName, commandName, capability) : packageReadme,\n };\n }\n const readme = [\n `# ${extensionName}`,\n \"\",\n \"Generated by `pm extension init`.\",\n \"\",\n \"## Included Files\",\n manifestBullet,\n entrypointBullet,\n '- `package.json`: `{ \"type\": \"module\" }` marker so the ESM entrypoint loads even when the host project is CommonJS.',\n TSCONFIG_BULLET,\n \"\",\n \"## Quick Start\",\n \"This extension is authored AND loaded as TypeScript: the manifest `entry` is\",\n \"`./index.ts` and pm imports it directly via Node's native type stripping\",\n \"(Node >=22.18), so there is no compile step. Install the dev dependencies for\",\n \"type-checking, then install and run the extension:\",\n \"```bash\",\n \"npm install -D typescript @types/node @unbrained/pm-cli\",\n \"npx tsc --noEmit\",\n \"pm extension --install --project <scaffold-path>\",\n `pm ${commandName}`,\n \"pm extension --doctor --project --detail summary\",\n \"```\",\n ...EXTENSION_CAPABILITY_README_SECTIONS[capability],\n ...buildScaffoldActivationReadmeSection(capability, \"extension\"),\n \"\",\n \"## Compatibility Bounds\",\n \"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:\",\n `- \\`manifest_version\\` (integer): manifest schema generation. Leave at \\`${SCAFFOLD_MANIFEST_VERSION}\\` unless you adopt a newer manifest schema.`,\n `- \\`pm_min_version\\` (string): lowest pm CLI version that may load this extension. Scaffolded as \\`${SCAFFOLD_PM_MIN_VERSION}\\`. The loader blocks the extension on older CLIs.`,\n \"- `pm_max_version` (string, optional): highest pm CLI version that may load this extension. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the extension when the CLI exceeds this bound.\",\n \"\",\n \"## Policy Metadata\",\n \"The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: \\\"strict\\\"`, and all six permission keys as `false`. Keep that least-privilege shape for pure extensions; relax only the specific permission your extension actually needs and verify with `pm extension --doctor --project --detail deep --trace`.\",\n \"\",\n \"- This scaffold is TypeScript ESM source loaded directly by pm (no compile), so it works in package scopes with `type: module`.\",\n \"- Author in `index.ts` (the manifest entry); edits take effect on the next install/reload — there is no `.js` to regenerate.\",\n \"- Release any resources `activate` opens (timers, connections, caches) in the `deactivate` teardown hook.\",\n \"\",\n ].join(\"\\n\");\n return {\n \"manifest.json\": manifest,\n \"index.ts\": entrypoint,\n // Module-type marker: pm loads index.ts as ESM, and without a nearby\n // package.json Node inherits the host project's module type, breaking\n // installs into \"type\": \"commonjs\" projects (pm-r0m4).\n \"package.json\": `${JSON.stringify({ type: \"module\" }, null, 2)}\\n`,\n \"tsconfig.json\": tsconfig,\n \"README.md\": readme,\n };\n}\n\n/**\n * Implements scaffold extension project for the public runtime surface of this module.\n */\nexport async function scaffoldExtensionProject(\n target: string,\n vocabulary: \"extension\" | \"package\" = \"extension\",\n capability: string = \"commands\",\n declarative: boolean = false,\n): Promise<ExtensionScaffoldResult> {\n const normalizedCapability = capability.trim().toLowerCase();\n if (!(SCAFFOLD_CAPABILITIES as readonly string[]).includes(normalizedCapability)) {\n throw new PmCliError(\n `Unknown scaffold capability \"${capability}\". Supported capabilities: ${SCAFFOLD_CAPABILITIES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n }\n const resolvedCapability = normalizedCapability as ExtensionScaffoldCapability;\n // The declarative (`composeExtension` blueprint) starter is package-mode only.\n // `composeExtension` is a runtime SDK *value* import, so it belongs in\n // package-mode authoring where the SDK is a linked dependency — not in the\n // import-free extension-only starters that must load without it. Every capability\n // emits its blueprint form (see buildDeclarativeBlueprintSurface).\n if (declarative && vocabulary !== \"package\") {\n throw new PmCliError(\n \"--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.\",\n EXIT_CODE.USAGE,\n );\n }\n const style: ExtensionScaffoldStyle = declarative ? \"declarative\" : \"imperative\";\n const normalizedTarget = target.trim();\n const targetPath = path.resolve(process.cwd(), normalizedTarget);\n const extensionName = normalizeManagedDirectoryName(path.basename(targetPath));\n // Hyphenated names become space-separated command words; reserved roots get a\n // `starter` prefix so core commands and aliases cannot intercept dispatch.\n const commandName = buildScaffoldCommandName(extensionName);\n const scaffoldFiles = buildStarterExtensionScaffoldFiles(extensionName, commandName, vocabulary, resolvedCapability, declarative);\n\n let createdDirectory = false;\n if (await pathExists(targetPath)) {\n const existingTargetStats = await fs.stat(targetPath);\n if (!existingTargetStats.isDirectory()) {\n throw new PmCliError(\n `Scaffold target \"${targetPath}\" exists and is not a directory.`,\n EXIT_CODE.CONFLICT,\n );\n }\n } else {\n await fs.mkdir(targetPath, { recursive: true });\n createdDirectory = true;\n }\n\n for (const [relativePath, content] of Object.entries(scaffoldFiles)) {\n const absolutePath = path.join(targetPath, relativePath);\n if (!(await pathExists(absolutePath))) {\n continue;\n }\n const existingContent = await fs.readFile(absolutePath, \"utf8\");\n if (existingContent !== content) {\n throw new PmCliError(\n `Scaffold file \"${relativePath}\" already exists with different content in \"${targetPath}\". Choose a new target path or remove conflicting files.`,\n EXIT_CODE.CONFLICT,\n );\n }\n }\n\n const files: ExtensionScaffoldFileResult[] = [];\n for (const [relativePath, content] of Object.entries(scaffoldFiles)) {\n const absolutePath = path.join(targetPath, relativePath);\n if (await pathExists(absolutePath)) {\n files.push({\n path: relativePath,\n status: \"unchanged\",\n });\n continue;\n }\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, content, \"utf8\");\n files.push({\n path: relativePath,\n status: \"created\",\n });\n }\n\n return {\n extension_name: extensionName,\n command_name: commandName,\n capability: resolvedCapability,\n style,\n target_path: targetPath,\n created_directory: createdDirectory,\n files,\n };\n}\n", "/**\n * @module cli/commands/extension/describe\n *\n * Builds the `pm extension describe` / `pm package describe` payload: a flat,\n * by-name map of every surface each loaded extension registered.\n *\n * The SDK already ships {@link describeExtensionActivation} -- the `describe`\n * (enumerate-all) verb that complements the `assert*` (verify-one) and `run*`\n * (invoke-one) testing helpers -- but until now it was reachable only from a test\n * that hand-built an {@link ExtensionActivationResult}. This module is the thin\n * orchestration that lets an agent at the CLI (or over MCP) ask \"what does this\n * installed extension add to my context?\" in one call, instead of stitching\n * together `doctor` (errors), `manage` (update metadata), and a manifest read.\n *\n * It is intentionally pure: the caller performs the load+activate cycle (exactly\n * as `explore`/`doctor` already do) and hands the results here, so the same\n * builder is trivially unit-testable against synthetic activations.\n */\nimport { describeExtensionActivation, type ExtensionActivationSummary } from \"../../../core/extensions/activation-summary.js\";\nimport { renderExtensionSurfaceMarkdown } from \"../../../core/extensions/activation-summary-markdown.js\";\nimport type { ExtensionActivationResult, ExtensionLayer, ExtensionLoadResult } from \"../../../core/extensions/loader.js\";\nimport { normalizeExtensionNameForMatch } from \"./shared.js\";\n\n/**\n * Runtime state of a described extension. `ok` loaded and activated cleanly,\n * `failed` loaded but threw during `activate`, and `not_loaded` failed to import\n * at all -- the latter two register nothing, so their `surfaces` are empty and\n * the status explains why (rather than implying the extension contributes\n * nothing).\n */\nexport type ExtensionDescribeActivationStatus = \"ok\" | \"failed\" | \"not_loaded\";\n\n/**\n * One extension's contribution to the workspace: its identity plus the\n * {@link ExtensionActivationSummary} of every surface it registered.\n *\n * `surfaces` is matched by extension *name* (mirroring\n * {@link describeExtensionActivation}'s name filter), so when the same name is\n * loaded in both the project and global layers each entry reflects that name's\n * combined surfaces -- the `layer`/`version` fields still distinguish the\n * physical entries.\n */\nexport interface ExtensionSurfaceDescription {\n name: string;\n layer: ExtensionLayer;\n version: string;\n activation_status: ExtensionDescribeActivationStatus;\n surfaces: ExtensionActivationSummary;\n}\n\n/**\n * Result of {@link buildExtensionDescribeResult}: the per-extension surface maps\n * plus a deduplicated `union` across the described set. `target` echoes the\n * requested name filter (or `null` for the whole workspace) and `total` counts\n * the described entries so callers need not re-measure `extensions`.\n */\nexport interface ExtensionDescribeResult {\n target: string | null;\n total: number;\n extensions: ExtensionSurfaceDescription[];\n union: ExtensionActivationSummary;\n}\n\n/**\n * Compose a collision-free identity key for an extension from its layer and\n * normalized name. The two parts are joined with a colon; the layer prefix is\n * always a colon-free enum value, so distinct (layer, name) pairs never collide\n * even when a name itself contains a colon.\n */\nfunction layerNameKey(layer: ExtensionLayer, name: string): string {\n return `${layer}:${normalizeExtensionNameForMatch(name)}`;\n}\n\n/**\n * Summarize, by name, every registration surface the loaded extensions exercised.\n *\n * Walks `loadResult.loaded` (annotating each with `failed` when its layer+name is\n * in `activationResult.failed`) and `loadResult.failed` (as `not_loaded`), sorts\n * the entries by name then layer for deterministic output, and attaches each\n * extension's {@link describeExtensionActivation} summary. When `target` is\n * provided only the case-insensitively matching extensions are described and the\n * `union` is scoped to that resolved name set; otherwise every loaded extension contributes.\n * A target may name either the extension itself or its source npm package\n * (`source_package`), so agents can reuse the `package_name` values surfaced by\n * `pm extension list` / install discovery without a second lookup. An unmatched\n * `target` yields an empty `extensions` array -- the caller decides whether that\n * is a not-found error.\n */\nexport function buildExtensionDescribeResult(\n target: string | undefined,\n loadResult: ExtensionLoadResult,\n activationResult: ExtensionActivationResult,\n): ExtensionDescribeResult {\n const activationFailedKeys = new Set(activationResult.failed.map((entry) => layerNameKey(entry.layer, entry.name)));\n const candidates: ExtensionSurfaceDescription[] = [\n ...loadResult.loaded.map((entry) => ({\n name: entry.name,\n layer: entry.layer,\n version: entry.version,\n activation_status: activationFailedKeys.has(layerNameKey(entry.layer, entry.name))\n ? (\"failed\" as const)\n : (\"ok\" as const),\n surfaces: describeExtensionActivation(activationResult, { extensionName: entry.name }),\n })),\n ...loadResult.failed.map((entry) => ({\n name: entry.name,\n layer: entry.layer,\n version: \"unknown\",\n activation_status: \"not_loaded\" as const,\n surfaces: describeExtensionActivation(activationResult, { extensionName: entry.name }),\n })),\n ].sort((left, right) => left.name.localeCompare(right.name) || left.layer.localeCompare(right.layer));\n\n const normalizedTarget = typeof target === \"string\" ? normalizeExtensionNameForMatch(target) : null;\n const matchedNames =\n normalizedTarget === null\n ? null\n : new Set(\n loadResult.loaded\n .filter(\n (entry) =>\n normalizeExtensionNameForMatch(entry.name) === normalizedTarget ||\n (typeof entry.source_package === \"string\" &&\n normalizeExtensionNameForMatch(entry.source_package) === normalizedTarget),\n )\n .map((entry) => normalizeExtensionNameForMatch(entry.name))\n .concat(normalizedTarget),\n );\n const extensions =\n matchedNames === null ? candidates : candidates.filter((entry) => matchedNames.has(normalizeExtensionNameForMatch(entry.name)));\n const unionOptions =\n matchedNames === null\n ? {}\n : { extensionNames: [...matchedNames] };\n\n return {\n target: typeof target === \"string\" ? target.trim() : null,\n total: extensions.length,\n extensions,\n union: describeExtensionActivation(activationResult, unionOptions),\n };\n}\n\n/**\n * Human-readable label for each {@link ExtensionDescribeActivationStatus}, used\n * in the Markdown per-extension heading so a reader sees *why* an entry has no\n * surfaces (activation failed / never loaded) rather than assuming it\n * contributes nothing.\n */\nconst ACTIVATION_STATUS_LABELS: Record<ExtensionDescribeActivationStatus, string> = {\n ok: \"loaded\",\n failed: \"activation failed\",\n not_loaded: \"not loaded\",\n};\n\n/**\n * Render an {@link ExtensionDescribeResult} as a Markdown reference document: a\n * top-level title and scope line, one section per described extension (titled\n * with its identity and activation status), and — only when more than one\n * extension was described — a final union section spanning them all. Each\n * extension and the union are rendered with the shared\n * {@link renderExtensionSurfaceMarkdown} primitive at heading level 2, so the\n * document nests cleanly under the level-1 title.\n *\n * `noun` is the lifecycle vocabulary (`\"extension\"` or `\"package\"`) so the prose\n * matches the command the agent invoked. When no extensions match (an unmatched\n * target is already a not-found error upstream, so this is the \"nothing loaded\"\n * case) the document is the title plus a single explanatory note.\n */\nexport function renderExtensionDescribeMarkdown(result: ExtensionDescribeResult, noun: string): string {\n const titleNoun = `${noun[0]!.toUpperCase()}${noun.slice(1)}`;\n const lines = [`# ${titleNoun} surface reference`, \"\"];\n lines.push(result.target === null ? `Scope: all loaded ${noun}s` : `Scope: \\`${result.target}\\``);\n lines.push(`Described: ${result.total} ${noun}${result.total === 1 ? \"\" : \"s\"}`, \"\");\n\n if (result.extensions.length === 0) {\n lines.push(`_No ${noun}s are loaded._`, \"\");\n return `${lines.join(\"\\n\").trimEnd()}\\n`;\n }\n\n for (const entry of result.extensions) {\n const title = `${entry.name} (${entry.layer} v${entry.version}, ${ACTIVATION_STATUS_LABELS[entry.activation_status]})`;\n // renderExtensionSurfaceMarkdown already ends with a newline; the join adds a\n // single blank line between sections, so no extra \"\" separator is pushed.\n lines.push(renderExtensionSurfaceMarkdown(entry.surfaces, { title, headingLevel: 2 }));\n }\n\n if (result.extensions.length > 1) {\n lines.push(renderExtensionSurfaceMarkdown(result.union, { title: `Union across all described ${noun}s`, headingLevel: 2 }));\n }\n\n return `${lines.join(\"\\n\").trimEnd()}\\n`;\n}\n", "/**\n * @module cli/commands/extension\n *\n * Implements the pm extension command surface and its agent-facing runtime behavior.\n */\nimport { execFile } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { activateExtensions, loadExtensions, nextExtensionReloadToken } from \"../../core/extensions/index.js\";\nimport { resolveExtensionRoots } from \"../../core/extensions/loader.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { isPathWithinDirectory } from \"../../core/fs/path-utils.js\";\nimport { collectPackageExtensionDirectories } from \"../../core/packages/manifest.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { levenshteinDistanceWithinLimit } from \"../../core/shared/levenshtein.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { resolveGlobalPmRoot, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings, writeSettings } from \"../../core/store/settings.js\";\nimport { ensureTypeFolderScaffold } from \"./schema.js\";\nimport type { PmSettings } from \"../../types/index.js\";\n// Cohesive helper groups now live in ./extension/* sibling modules. They are\n// imported for the command wiring that stays here and re-exported below so\n// existing import sites (sdk barrels, upgrade.ts, tests) keep importing the\n// public surface (runExtension, managed-state read/write, install-source\n// parsing, …) from \"./extension.js\" unchanged.\nimport {\n normalizeStringList,\n normalizeExtensionNameForMatch,\n normalizeManagedDirectoryName,\n parseExtensionManifest,\n validateExtensionDirectory,\n} from \"./extension/shared.js\";\nimport {\n sortManagedEntries,\n managedExtensionSourcesEquivalent,\n readManagedExtensionState,\n writeManagedExtensionState,\n upsertManagedEntry,\n resolveManagedExtensionStatePath,\n type ManagedExtensionSource,\n type ManagedExtensionRecord,\n type ManagedExtensionState,\n} from \"./extension/managed-state.js\";\nimport {\n parseExtensionInstallSource,\n resolveInstallSource,\n areDirectoriesEquivalent,\n runGitCommand,\n} from \"./extension/install-sources.js\";\nimport {\n resolveBundledExtensionAliasSource,\n resolveBundledPackageNpmName,\n isBundledPackageInstallAllTarget,\n listBundledPackageAliases,\n resolveBundledAliasManifestName,\n buildBundledPackageCatalog,\n} from \"./extension/bundled-catalog.js\";\nimport { scaffoldExtensionProject } from \"./extension/scaffold.js\";\nimport { buildExtensionDescribeResult } from \"./extension/describe.js\";\nimport {\n applyDoctorRuntimeActivationState,\n classifyDoctorLoadFailureWarnings,\n classifyDoctorActivationFailureWarnings,\n classifyUnusedCapabilityWarnings,\n buildExtensionTriageSummary,\n parseDoctorDetailMode,\n collectUnknownCapabilityGuidance,\n buildCapabilityContractMetadata,\n buildDoctorConsistencySummary,\n} from \"./extension/doctor.js\";\n// Re-export the public surface that lives in sibling modules but was previously\n// exported from this file (used by sdk barrels, upgrade.ts, and tests).\nexport {\n parseExtensionManifest,\n validateExtensionDirectory,\n readManagedExtensionState,\n writeManagedExtensionState,\n resolveManagedExtensionStatePath,\n parseExtensionInstallSource,\n};\nexport type {\n ManagedExtensionSource,\n ManagedExtensionRecord,\n ManagedExtensionState,\n};\nexport type { ManagedExtensionStateReadResult } from \"./extension/managed-state.js\";\n\nconst execFileAsync = promisify(execFile);\nconst EXTENSION_INSTALL_COPY_ATTEMPTS = 3;\nconst EXTENSION_INSTALL_LOCK_ATTEMPTS = 120;\nconst EXTENSION_INSTALL_LOCK_DELAY_MS = 250;\nconst EXTENSION_INSTALL_LOCK_STALE_MS = 120_000;\n\n/**\n * Restricts extension command action values accepted by command, SDK, and storage contracts.\n */\nexport type ExtensionCommandAction =\n | \"install\"\n | \"uninstall\"\n | \"explore\"\n | \"manage\"\n | \"describe\"\n | \"reload\"\n | \"doctor\"\n | \"catalog\"\n | \"adopt\"\n | \"adopt-all\"\n | \"activate\"\n | \"deactivate\"\n | \"init\";\n\nconst LIFECYCLE_ACTION_TARGETS = [\n [\"install\", \"install\", \"--install\"],\n [\"uninstall\", \"uninstall\", \"--uninstall\"],\n [\"explore\", \"explore\", \"--explore\"],\n [\"list\", \"explore\", \"--explore\"],\n [\"manage\", \"manage\", \"--manage\"],\n [\"describe\", \"describe\", \"--describe\"],\n [\"reload\", \"reload\", \"--reload\"],\n [\"doctor\", \"doctor\", \"--doctor\"],\n [\"catalog\", \"catalog\", \"--catalog\"],\n [\"init\", \"init\", \"--init\"],\n [\"scaffold\", \"init\", \"--scaffold\"],\n [\"adopt\", \"adopt\", \"--adopt\"],\n [\"adopt-all\", \"adopt-all\", \"--adopt-all\"],\n [\"activate\", \"activate\", \"--activate\"],\n [\"deactivate\", \"deactivate\", \"--deactivate\"],\n] as const satisfies readonly (readonly [string, ExtensionCommandAction, `--${string}`])[];\n\nconst LIFECYCLE_ACTION_FLAG_HINT = LIFECYCLE_ACTION_TARGETS.map(([, , flag]) => flag)\n .filter((flag, index, flags) => flags.indexOf(flag) === index)\n .join(\", \");\nconst LIFECYCLE_ACTION_FLAGS: Record<ExtensionCommandAction, `--${string}`> = {\n install: \"--install\",\n uninstall: \"--uninstall\",\n explore: \"--explore\",\n manage: \"--manage\",\n describe: \"--describe\",\n reload: \"--reload\",\n doctor: \"--doctor\",\n catalog: \"--catalog\",\n adopt: \"--adopt\",\n \"adopt-all\": \"--adopt-all\",\n activate: \"--activate\",\n deactivate: \"--deactivate\",\n init: \"--init\",\n};\n/**\n * Restricts extension scope values accepted by command, SDK, and storage contracts.\n */\nexport type ExtensionScope = \"project\" | \"global\";\n/**\n * Restricts extension activation status values accepted by command, SDK, and storage contracts.\n */\nexport type ExtensionActivationStatus = \"ok\" | \"failed\" | \"not_loaded\" | \"unknown\";\n\n/**\n * Documents the extension command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ExtensionCommandOptions {\n install?: boolean;\n uninstall?: boolean;\n explore?: boolean;\n manage?: boolean;\n describe?: boolean;\n markdown?: boolean;\n output?: string;\n reload?: boolean;\n doctor?: boolean;\n catalog?: boolean;\n init?: boolean;\n scaffold?: boolean;\n strictExit?: boolean;\n failOnWarn?: boolean;\n adopt?: boolean;\n adoptAll?: boolean;\n activate?: boolean;\n deactivate?: boolean;\n project?: boolean;\n local?: boolean;\n global?: boolean;\n gh?: string;\n github?: string;\n ref?: string;\n detail?: string;\n trace?: boolean;\n watch?: boolean;\n runtimeProbe?: boolean;\n fixManagedState?: boolean;\n fields?: string;\n capability?: string;\n declarative?: boolean;\n vocabulary?: \"extension\" | \"package\";\n}\n\n/**\n * Documents the managed extension summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface ManagedExtensionSummary {\n name: string;\n directory: string;\n version: string;\n entry: string;\n scope: ExtensionScope;\n // Backward-compatible alias for configured enabled state. Prefer `enabled`.\n active: boolean;\n enabled: boolean;\n runtime_active: boolean | null;\n activation_status: ExtensionActivationStatus;\n command_paths?: string[];\n action_paths?: string[];\n managed: boolean;\n source?: ManagedExtensionSource;\n update_available?: boolean | null;\n last_update_check_at?: string;\n last_update_remote_commit?: string;\n update_error?: string;\n update_check_status: ExtensionUpdateCheckStatus;\n update_check_reason: string;\n}\n\n/**\n * Documents the extension command result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ExtensionCommandResult {\n ok: boolean;\n action: ExtensionCommandAction;\n scope: ExtensionScope;\n roots: {\n project: string;\n global: string;\n selected: string;\n settings_root: string;\n };\n warnings: string[];\n details: Record<string, unknown>;\n}\n\nconst NATIVE_OUTPUT_MARKER = \"__pm_native_output\";\n\n/**\n * Documents the extension triage summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface ExtensionTriageSummary {\n status: \"ok\" | \"warn\";\n warning_count: number;\n warning_codes: string[];\n warnings: string[];\n policy_warning_count: number;\n policy_violation_count: number;\n policy_blocked_count: number;\n total_extensions: number;\n managed_total: number;\n enabled_total: number;\n active_total: number;\n update_available_total: number;\n update_health_coverage: \"full\" | \"partial\";\n update_health_partial: boolean;\n unmanaged_loaded_extension_count: number;\n unmanaged_loaded_extensions: string[];\n unmanaged_expected_extension_count: number;\n unmanaged_expected_extensions: string[];\n unmanaged_action_required_extension_count: number;\n unmanaged_action_required_extensions: string[];\n update_check_status_totals: Record<ExtensionUpdateCheckStatus, number>;\n update_check_failed_total: number;\n top_warnings: string[];\n remediation: string[];\n collision_plan?: ExtensionCollisionPlan;\n}\n\n/**\n * Documents the extension collision plan payload exchanged by command, SDK, and package integrations.\n */\nexport interface ExtensionCollisionPlan {\n status: \"ok\" | \"conflicts_detected\";\n collision_count: number;\n extension_count: number;\n next_best_command: string;\n collisions: Array<{\n code: string;\n surface: string;\n winner: { layer: ExtensionScope; name: string };\n displaced: { layer: ExtensionScope; name: string };\n }>;\n remediation_candidates: Array<{\n action: \"deactivate\";\n extension: string;\n command: string;\n affected_collisions: number;\n feature_loss: {\n command_paths: string[];\n action_paths: string[];\n };\n }>;\n}\n\n/**\n * Restricts extension update check status values accepted by command, SDK, and storage contracts.\n */\nexport type ExtensionUpdateCheckStatus = \"checked\" | \"skipped_unmanaged\" | \"skipped_non_github\" | \"failed\" | \"not_checked\";\n\ninterface ExtensionUpdateCheckResolution {\n status: ExtensionUpdateCheckStatus;\n reason: string;\n}\n\n/**\n * Restricts extension doctor detail mode values accepted by command, SDK, and storage contracts.\n */\nexport type ExtensionDoctorDetailMode = \"summary\" | \"deep\";\nfunction buildExtensionPolicyDetails(policy: PmSettings[\"extensions\"][\"policy\"]): {\n mode: \"off\" | \"warn\" | \"enforce\";\n trust_mode: \"off\" | \"warn\" | \"enforce\";\n require_provenance: boolean;\n trusted_extensions: string[];\n default_sandbox_profile: \"none\" | \"restricted\" | \"strict\";\n allowed_extensions: string[];\n blocked_extensions: string[];\n allowed_capabilities: string[];\n blocked_capabilities: string[];\n allowed_surfaces: string[];\n blocked_surfaces: string[];\n allowed_commands: string[];\n blocked_commands: string[];\n allowed_actions: string[];\n blocked_actions: string[];\n allowed_services: string[];\n blocked_services: string[];\n extension_overrides: Array<{\n name: string;\n disabled?: boolean;\n require_trusted?: boolean;\n require_provenance?: boolean;\n sandbox_profile?: \"none\" | \"restricted\" | \"strict\";\n allowed_capabilities?: string[];\n blocked_capabilities?: string[];\n allowed_surfaces?: string[];\n blocked_surfaces?: string[];\n allowed_commands?: string[];\n blocked_commands?: string[];\n allowed_actions?: string[];\n blocked_actions?: string[];\n allowed_services?: string[];\n blocked_services?: string[];\n }>;\n} {\n const overrides = (policy.extension_overrides ?? [])\n .map((override) => ({\n name: override.name.trim(),\n disabled: override.disabled === true ? true : undefined,\n require_trusted: override.require_trusted === true ? true : undefined,\n require_provenance: override.require_provenance === true ? true : undefined,\n sandbox_profile: override.sandbox_profile,\n allowed_capabilities: normalizeStringList(override.allowed_capabilities ?? []),\n blocked_capabilities: normalizeStringList(override.blocked_capabilities ?? []),\n allowed_surfaces: normalizeStringList(override.allowed_surfaces ?? []),\n blocked_surfaces: normalizeStringList(override.blocked_surfaces ?? []),\n allowed_commands: normalizeStringList(override.allowed_commands ?? []),\n blocked_commands: normalizeStringList(override.blocked_commands ?? []),\n allowed_actions: normalizeStringList(override.allowed_actions ?? []),\n blocked_actions: normalizeStringList(override.blocked_actions ?? []),\n allowed_services: normalizeStringList(override.allowed_services ?? []),\n blocked_services: normalizeStringList(override.blocked_services ?? []),\n }))\n .filter((override) => override.name.length > 0)\n .sort((left, right) => left.name.localeCompare(right.name));\n return {\n mode: policy.mode,\n trust_mode: policy.trust_mode,\n require_provenance: policy.require_provenance === true,\n trusted_extensions: normalizeStringList(policy.trusted_extensions ?? []),\n default_sandbox_profile: policy.default_sandbox_profile ?? \"none\",\n allowed_extensions: normalizeStringList(policy.allowed_extensions ?? []),\n blocked_extensions: normalizeStringList(policy.blocked_extensions ?? []),\n allowed_capabilities: normalizeStringList(policy.allowed_capabilities ?? []),\n blocked_capabilities: normalizeStringList(policy.blocked_capabilities ?? []),\n allowed_surfaces: normalizeStringList(policy.allowed_surfaces ?? []),\n blocked_surfaces: normalizeStringList(policy.blocked_surfaces ?? []),\n allowed_commands: normalizeStringList(policy.allowed_commands ?? []),\n blocked_commands: normalizeStringList(policy.blocked_commands ?? []),\n allowed_actions: normalizeStringList(policy.allowed_actions ?? []),\n blocked_actions: normalizeStringList(policy.blocked_actions ?? []),\n allowed_services: normalizeStringList(policy.allowed_services ?? []),\n blocked_services: normalizeStringList(policy.blocked_services ?? []),\n extension_overrides: overrides.map((override) => ({\n name: override.name,\n ...(override.disabled === true ? { disabled: true } : {}),\n ...(override.require_trusted === true ? { require_trusted: true } : {}),\n ...(override.require_provenance === true ? { require_provenance: true } : {}),\n ...(override.sandbox_profile ? { sandbox_profile: override.sandbox_profile } : {}),\n ...(override.allowed_capabilities.length > 0 ? { allowed_capabilities: override.allowed_capabilities } : {}),\n ...(override.blocked_capabilities.length > 0 ? { blocked_capabilities: override.blocked_capabilities } : {}),\n ...(override.allowed_surfaces.length > 0 ? { allowed_surfaces: override.allowed_surfaces } : {}),\n ...(override.blocked_surfaces.length > 0 ? { blocked_surfaces: override.blocked_surfaces } : {}),\n ...(override.allowed_commands.length > 0 ? { allowed_commands: override.allowed_commands } : {}),\n ...(override.blocked_commands.length > 0 ? { blocked_commands: override.blocked_commands } : {}),\n ...(override.allowed_actions.length > 0 ? { allowed_actions: override.allowed_actions } : {}),\n ...(override.blocked_actions.length > 0 ? { blocked_actions: override.blocked_actions } : {}),\n ...(override.allowed_services.length > 0 ? { allowed_services: override.allowed_services } : {}),\n ...(override.blocked_services.length > 0 ? { blocked_services: override.blocked_services } : {}),\n })),\n };\n}\n\nfunction isRetriableExtensionInstallCopyError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)) {\n return false;\n }\n const code = (error as { code?: unknown }).code;\n return code === \"EEXIST\" || code === \"ENOTEMPTY\" || code === \"ENOENT\";\n}\n\nfunction isErrnoCode(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === code;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/**\n * Ensure the installed extension directory carries a `package.json` with\n * `\"type\": \"module\"`. Extension entrypoints are ESM TypeScript; without a\n * nearby package.json Node resolves the module type from the HOST project's\n * package.json, so installs into `\"type\": \"commonjs\"` projects fail activation\n * with `extension_load_failed` (pm-r0m4). Extensions that ship their own\n * package.json are left untouched.\n */\nasync function ensureExtensionModuleTypeMarker(destinationDirectory: string): Promise<void> {\n const markerPath = path.join(destinationDirectory, \"package.json\");\n if (await pathExists(markerPath)) {\n return;\n }\n await fs.writeFile(markerPath, `${JSON.stringify({ type: \"module\" }, null, 2)}\\n`, \"utf8\");\n}\n\n/**\n * Implements copy extension directory for install for the public runtime surface of this module.\n */\nexport async function copyExtensionDirectoryForInstall(\n sourceDirectory: string,\n destinationDirectory: string,\n copyDirectory: typeof fs.cp = fs.cp,\n): Promise<void> {\n for (let attempt = 1; attempt <= EXTENSION_INSTALL_COPY_ATTEMPTS; attempt += 1) {\n try {\n if (await pathExists(destinationDirectory)) {\n await fs.rm(destinationDirectory, { recursive: true, force: true });\n }\n await copyExtensionDirectoryWithoutSelfNesting(sourceDirectory, destinationDirectory, copyDirectory);\n return;\n } catch (error: unknown) {\n if (!isRetriableExtensionInstallCopyError(error) || attempt === EXTENSION_INSTALL_COPY_ATTEMPTS) {\n throw error;\n }\n await sleep(EXTENSION_INSTALL_LOCK_DELAY_MS);\n }\n }\n}\n\nasync function copyExtensionDirectoryWithoutSelfNesting(\n sourceDirectory: string,\n destinationDirectory: string,\n copyDirectory: typeof fs.cp,\n): Promise<void> {\n const resolvedSource = path.resolve(sourceDirectory);\n const resolvedDestination = path.resolve(destinationDirectory);\n if (resolvedSource === resolvedDestination) {\n return;\n }\n if (!isPathWithinDirectory(resolvedSource, resolvedDestination)) {\n await copyDirectory(sourceDirectory, destinationDirectory, { recursive: true, force: true });\n return;\n }\n\n const stagingRoot = await fs.mkdtemp(path.join(os.tmpdir(), \"pm-extension-copy-\"));\n const stagedDirectory = path.join(stagingRoot, \"extension\");\n try {\n await copyDirectory(sourceDirectory, stagedDirectory, { recursive: true, force: true });\n await copyDirectory(stagedDirectory, destinationDirectory, { recursive: true, force: true });\n } finally {\n await fs.rm(stagingRoot, { recursive: true, force: true });\n }\n}\n\nasync function withExtensionInstallLock<T>(\n settingsRoot: string,\n destinationDirectoryName: string,\n run: () => Promise<T>,\n options?: {\n attempts?: number;\n delay_ms?: number;\n stale_ms?: number;\n },\n): Promise<T> {\n const lockRoot = path.join(settingsRoot, \"runtime\", \"extension-install-locks\");\n const lockPath = path.join(lockRoot, `${destinationDirectoryName}.lock`);\n await fs.mkdir(lockRoot, { recursive: true });\n const attempts = Math.max(1, Math.floor(options?.attempts ?? EXTENSION_INSTALL_LOCK_ATTEMPTS));\n const delayMs = Math.max(0, Math.floor(options?.delay_ms ?? EXTENSION_INSTALL_LOCK_DELAY_MS));\n const staleMs = Math.max(0, Math.floor(options?.stale_ms ?? EXTENSION_INSTALL_LOCK_STALE_MS));\n\n let acquired = false;\n for (let attempt = 1; attempt <= attempts; attempt += 1) {\n try {\n await fs.mkdir(lockPath);\n acquired = true;\n await fs.writeFile(\n path.join(lockPath, \"owner.json\"),\n `${JSON.stringify({ pid: process.pid, created_at: nowIso(), destination: destinationDirectoryName }, null, 2)}\\n`,\n \"utf8\",\n );\n break;\n } catch (error: unknown) {\n if (!isErrnoCode(error, \"EEXIST\")) {\n throw error;\n }\n let stat: Awaited<ReturnType<typeof fs.stat>> | null = null;\n try {\n stat = await fs.stat(lockPath);\n } catch {\n stat = null;\n }\n if (stat && Date.now() - stat.mtimeMs > staleMs) {\n await fs.rm(lockPath, { recursive: true, force: true });\n continue;\n }\n await sleep(delayMs);\n }\n }\n\n if (!acquired) {\n throw new PmCliError(\n `Timed out waiting for extension install lock for \"${destinationDirectoryName}\".`,\n EXIT_CODE.CONFLICT,\n );\n }\n\n try {\n return await run();\n } finally {\n await fs.rm(lockPath, { recursive: true, force: true }).catch(() => undefined);\n }\n}\n\nasync function resolveInstalledExtensionCandidate(\n installed: ManagedExtensionSummary[],\n extensionTarget: string,\n): Promise<ManagedExtensionSummary | undefined> {\n const lookupValues = [extensionTarget];\n const bundledAliasManifestName = await resolveBundledAliasManifestName(extensionTarget);\n if (bundledAliasManifestName) {\n lookupValues.push(bundledAliasManifestName);\n }\n const normalizedLookups = [...new Set(lookupValues.map((value) => normalizeExtensionNameForMatch(value)).filter((value) => value.length > 0))];\n for (const lookup of normalizedLookups) {\n const byName = installed.find((entry) => normalizeExtensionNameForMatch(entry.name) === lookup);\n if (byName) {\n return byName;\n }\n const byDirectory = installed.find((entry) => normalizeExtensionNameForMatch(entry.directory) === lookup);\n if (byDirectory) {\n return byDirectory;\n }\n }\n return undefined;\n}\n\nfunction isExtensionEnabled(settings: PmSettings, name: string): boolean {\n const normalizedName = name.trim();\n const enabled = new Set(normalizeStringList(settings.extensions.enabled));\n const disabled = new Set(normalizeStringList(settings.extensions.disabled));\n if (disabled.has(normalizedName)) {\n return false;\n }\n if (enabled.size === 0) {\n return true;\n }\n return enabled.has(normalizedName);\n}\n\nfunction ensureActivated(settings: PmSettings, name: string): boolean {\n const normalizedName = name.trim();\n const enabled = new Set(normalizeStringList(settings.extensions.enabled));\n const disabled = new Set(normalizeStringList(settings.extensions.disabled));\n const previousEnabled = [...enabled];\n const previousDisabled = [...disabled];\n disabled.delete(normalizedName);\n if (enabled.size > 0) {\n enabled.add(normalizedName);\n }\n settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));\n settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));\n return (\n settings.extensions.enabled.join(\"\\u0000\") !== previousEnabled.join(\"\\u0000\") ||\n settings.extensions.disabled.join(\"\\u0000\") !== previousDisabled.join(\"\\u0000\")\n );\n}\n\nfunction ensureDeactivated(settings: PmSettings, name: string): boolean {\n const normalizedName = name.trim();\n const enabled = new Set(normalizeStringList(settings.extensions.enabled));\n const disabled = new Set(normalizeStringList(settings.extensions.disabled));\n const previousEnabled = [...enabled];\n const previousDisabled = [...disabled];\n enabled.delete(normalizedName);\n disabled.add(normalizedName);\n settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));\n settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));\n return (\n settings.extensions.enabled.join(\"\\u0000\") !== previousEnabled.join(\"\\u0000\") ||\n settings.extensions.disabled.join(\"\\u0000\") !== previousDisabled.join(\"\\u0000\")\n );\n}\n\nfunction clearExtensionState(settings: PmSettings, name: string): boolean {\n const normalizedName = name.trim();\n const enabled = new Set(normalizeStringList(settings.extensions.enabled));\n const disabled = new Set(normalizeStringList(settings.extensions.disabled));\n const previousEnabled = [...enabled];\n const previousDisabled = [...disabled];\n enabled.delete(normalizedName);\n disabled.delete(normalizedName);\n settings.extensions.enabled = [...enabled].sort((left, right) => left.localeCompare(right));\n settings.extensions.disabled = [...disabled].sort((left, right) => left.localeCompare(right));\n return (\n settings.extensions.enabled.join(\"\\u0000\") !== previousEnabled.join(\"\\u0000\") ||\n settings.extensions.disabled.join(\"\\u0000\") !== previousDisabled.join(\"\\u0000\")\n );\n}\n\nfunction suggestLifecycleActionTarget(target: string): { action: ExtensionCommandAction; flag: `--${string}` } | null {\n const normalizedTarget = target.trim().toLowerCase();\n const exactMatch = LIFECYCLE_ACTION_TARGETS.find(([candidate]) => candidate === normalizedTarget);\n if (exactMatch) {\n return { action: exactMatch[1], flag: exactMatch[2] };\n }\n const maxDistance = normalizedTarget.length <= 4 ? 1 : 2;\n let nearest: { action: ExtensionCommandAction; flag: `--${string}`; distance: number } | null = null;\n for (const [candidate, action, flag] of LIFECYCLE_ACTION_TARGETS) {\n const distance = levenshteinDistanceWithinLimit(normalizedTarget, candidate, maxDistance);\n if (distance === null) {\n continue;\n }\n if (nearest === null) {\n nearest = { action, flag, distance };\n continue;\n }\n if (distance < nearest.distance) {\n nearest = { action, flag, distance };\n }\n }\n return nearest === null ? null : { action: nearest.action, flag: nearest.flag };\n}\n\nfunction buildUnknownLifecycleActionError(target: string, options: ExtensionCommandOptions): PmCliError {\n const noun = options.vocabulary === \"package\" ? \"package\" : \"extension\";\n const suggestion = suggestLifecycleActionTarget(target);\n if (!suggestion) {\n return new PmCliError(\n `One action flag is required. Use one of: ${LIFECYCLE_ACTION_FLAG_HINT}. Bare \\`pm package\\` and \\`pm extension\\` default to --explore.`,\n EXIT_CODE.USAGE,\n );\n }\n const command = `pm ${noun} ${suggestion.flag}`;\n return new PmCliError(\n `Unknown ${noun} lifecycle action \"${target}\". Did you mean \"${suggestion.flag}\"?`,\n EXIT_CODE.USAGE,\n {\n code: \"unknown_lifecycle_action\",\n required: `Use one of: ${LIFECYCLE_ACTION_FLAG_HINT}.`,\n examples: [command, `pm ${noun} --help`],\n recovery: {\n attempted_command: `pm ${noun} ${target}`,\n suggested_retry: command,\n fallback_candidates: [\n {\n source: \"lifecycle_action\",\n command,\n reason: `nearest lifecycle action for \"${target}\"`,\n },\n ],\n },\n },\n );\n}\n\n// Maps each boolean action flag to the lifecycle action it selects. `scaffold`\n// aliases `init` and `adoptAll` selects `adopt-all`; every other flag maps to its\n// like-named action. Dispatching through the table keeps `resolveAction` flat.\nconst EXTENSION_ACTION_FLAG_SELECTORS = [\n [\"install\", \"install\"],\n [\"uninstall\", \"uninstall\"],\n [\"explore\", \"explore\"],\n [\"manage\", \"manage\"],\n [\"describe\", \"describe\"],\n [\"reload\", \"reload\"],\n [\"doctor\", \"doctor\"],\n [\"catalog\", \"catalog\"],\n [\"init\", \"init\"],\n [\"scaffold\", \"init\"],\n [\"adopt\", \"adopt\"],\n [\"adoptAll\", \"adopt-all\"],\n [\"activate\", \"activate\"],\n [\"deactivate\", \"deactivate\"],\n] as const satisfies readonly (readonly [keyof ExtensionCommandOptions, ExtensionCommandAction])[];\n\n/**\n * Map a bare positional token (already trimmed and lower-cased) to the lifecycle\n * action it implies for `pm extension <token>` / `pm package <token>`: the\n * `doctor`/`reload`/`catalog`/`init`/`scaffold`/`explore`/`manage` keywords, with\n * `list` and the empty string both meaning `explore`. Returns `null` for anything\n * else so the caller can raise a did-you-mean error.\n */\nfunction resolveImplicitActionFromTarget(normalizedTarget: string): ExtensionCommandAction | null {\n if (normalizedTarget === \"doctor\") {\n return \"doctor\";\n }\n if (normalizedTarget === \"reload\") {\n return \"reload\";\n }\n if (normalizedTarget === \"catalog\") {\n return \"catalog\";\n }\n if (normalizedTarget === \"init\" || normalizedTarget === \"scaffold\") {\n return \"init\";\n }\n if (normalizedTarget === \"explore\") {\n return \"explore\";\n }\n if (normalizedTarget === \"manage\") {\n return \"manage\";\n }\n if (normalizedTarget === \"list\" || normalizedTarget === \"\") {\n return \"explore\";\n }\n return null;\n}\n\nfunction resolveAction(target: string | undefined, options: ExtensionCommandOptions): ExtensionCommandAction {\n const selected = [\n ...new Set(\n EXTENSION_ACTION_FLAG_SELECTORS.filter(([flag]) => options[flag] === true).map(([, mappedAction]) => mappedAction),\n ),\n ];\n if (selected.length === 0) {\n if (target === undefined) {\n return \"explore\";\n }\n const implicitAction = resolveImplicitActionFromTarget(target.trim().toLowerCase());\n if (implicitAction) {\n return implicitAction;\n }\n throw buildUnknownLifecycleActionError(target, options);\n }\n if (selected.length > 1) {\n throw new PmCliError(\"Extension action flags are mutually exclusive.\", EXIT_CODE.USAGE);\n }\n return selected[0];\n}\n\nfunction resolveScope(options: ExtensionCommandOptions): ExtensionScope {\n const projectLike = options.project === true || options.local === true;\n const global = options.global === true;\n if (projectLike && global) {\n throw new PmCliError('Options \"--project/--local\" and \"--global\" are mutually exclusive.', EXIT_CODE.USAGE);\n }\n return global ? \"global\" : \"project\";\n}\nfunction resolveUpdateCheckResolution(managedEntry: ManagedExtensionRecord | undefined): ExtensionUpdateCheckResolution {\n if (!managedEntry) {\n return {\n status: \"skipped_unmanaged\",\n reason: \"extension_not_managed\",\n };\n }\n if (managedEntry.source.kind !== \"github\") {\n return {\n status: \"skipped_non_github\",\n reason: `managed_source_kind_${managedEntry.source.kind}`,\n };\n }\n const updateError = typeof managedEntry.update_error === \"string\" ? managedEntry.update_error.trim() : \"\";\n if (updateError.length > 0) {\n return {\n status: \"failed\",\n reason: updateError,\n };\n }\n if (typeof managedEntry.last_update_check_at === \"string\" && managedEntry.last_update_check_at.trim().length > 0) {\n if (managedEntry.update_available === true) {\n return {\n status: \"checked\",\n reason: \"update_available\",\n };\n }\n if (managedEntry.update_available === false) {\n return {\n status: \"checked\",\n reason: \"up_to_date\",\n };\n }\n return {\n status: \"checked\",\n reason: \"checked_without_commit_baseline\",\n };\n }\n return {\n status: \"not_checked\",\n reason: \"no_update_check_recorded\",\n };\n}\n\n/**\n * Assemble a {@link ManagedExtensionSummary} from a directory's resolved identity\n * (name/version/entry/enabled state) and its managed-state record, projecting the\n * managed-source provenance and the resolved update-check status. Runtime\n * activation fields default to \"not yet probed\" (`runtime_active: null`,\n * `activation_status: \"unknown\"`) so a later runtime probe can overlay live state.\n */\nfunction buildInstalledExtensionSummary(\n identity: { name: string; directory: string; version: string; entry: string; enabled: boolean },\n scope: ExtensionScope,\n managedEntry: ManagedExtensionRecord | undefined,\n updateCheck: ExtensionUpdateCheckResolution,\n): ManagedExtensionSummary {\n return {\n name: identity.name,\n directory: identity.directory,\n version: identity.version,\n entry: identity.entry,\n scope,\n active: identity.enabled,\n enabled: identity.enabled,\n runtime_active: null,\n activation_status: \"unknown\",\n managed: Boolean(managedEntry),\n source: managedEntry?.source,\n update_available: managedEntry?.update_available,\n last_update_check_at: managedEntry?.last_update_check_at,\n last_update_remote_commit: managedEntry?.last_update_remote_commit,\n update_error: managedEntry?.update_error,\n update_check_status: updateCheck.status,\n update_check_reason: updateCheck.reason,\n };\n}\n\nasync function listInstalledExtensions(\n extensionsRoot: string,\n scope: ExtensionScope,\n settings: PmSettings,\n state: ManagedExtensionState,\n): Promise<{ extensions: ManagedExtensionSummary[]; warnings: string[] }> {\n if (!(await pathExists(extensionsRoot))) {\n return {\n extensions: [],\n warnings: [],\n };\n }\n\n const entries = await fs.readdir(extensionsRoot, { withFileTypes: true });\n const directories = entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right));\n\n const managedByName = new Map<string, ManagedExtensionRecord>();\n const managedByDirectory = new Map<string, ManagedExtensionRecord>();\n for (const managedEntry of state.entries) {\n managedByName.set(normalizeExtensionNameForMatch(managedEntry.name), managedEntry);\n managedByDirectory.set(normalizeExtensionNameForMatch(managedEntry.directory), managedEntry);\n }\n\n const warnings: string[] = [];\n const summaries: ManagedExtensionSummary[] = [];\n for (const directoryName of directories) {\n const extensionDirectory = path.join(extensionsRoot, directoryName);\n const manifestPath = path.join(extensionDirectory, \"manifest.json\");\n if (!(await pathExists(manifestPath))) {\n warnings.push(`extension_manifest_missing:${scope}:${directoryName}`);\n const managedEntry = managedByDirectory.get(normalizeExtensionNameForMatch(directoryName));\n summaries.push(\n buildInstalledExtensionSummary(\n {\n name: managedEntry?.name ?? directoryName,\n directory: directoryName,\n version: managedEntry?.manifest_version ?? \"unknown\",\n entry: managedEntry?.manifest_entry ?? \"unknown\",\n enabled: managedEntry ? isExtensionEnabled(settings, managedEntry.name) : false,\n },\n scope,\n managedEntry,\n resolveUpdateCheckResolution(managedEntry),\n ),\n );\n continue;\n }\n\n let rawManifest: unknown;\n try {\n rawManifest = JSON.parse(await fs.readFile(manifestPath, \"utf8\")) as unknown;\n } catch {\n warnings.push(`extension_manifest_invalid_json:${scope}:${directoryName}`);\n continue;\n }\n const manifest = parseExtensionManifest(rawManifest);\n if (!manifest) {\n warnings.push(`extension_manifest_invalid:${scope}:${directoryName}`);\n continue;\n }\n const managedEntry =\n managedByName.get(normalizeExtensionNameForMatch(manifest.name)) ??\n managedByDirectory.get(normalizeExtensionNameForMatch(directoryName));\n summaries.push(\n buildInstalledExtensionSummary(\n {\n name: manifest.name,\n directory: directoryName,\n version: manifest.version,\n entry: manifest.entry,\n enabled: isExtensionEnabled(settings, manifest.name),\n },\n scope,\n managedEntry,\n resolveUpdateCheckResolution(managedEntry),\n ),\n );\n }\n return {\n extensions: summaries.sort((left, right) => left.name.localeCompare(right.name)),\n warnings: warnings.sort((left, right) => left.localeCompare(right)),\n };\n}\ninterface GithubUpdateStatus {\n checked_at: string;\n available: boolean | null;\n remote_commit?: string;\n error?: string;\n}\ntype ActivationFailureEntry = Awaited<ReturnType<typeof activateExtensions>>[\"failed\"][number];\n\ninterface ActivationFailureDiagnostic {\n layer: string;\n name: string;\n entry_path: string;\n error: string;\n missing_capability?: string;\n hint?: string;\n trace?: {\n method: string;\n registration_index: number;\n expected_schema: string;\n command?: string;\n capability?: string;\n missing_capability?: string;\n hint?: string;\n };\n}\n\nfunction summarizeRuntimeCommandPathsForExtension(\n extensionName: string,\n installed: ManagedExtensionSummary[],\n): { command_paths: string[]; action_paths: string[] } {\n const normalizedName = normalizeExtensionNameForMatch(extensionName);\n const entry = installed.find((candidate) => normalizeExtensionNameForMatch(candidate.name) === normalizedName);\n return {\n command_paths: [...(entry?.command_paths ?? [])].sort((left, right) => left.localeCompare(right)),\n action_paths: [...(entry?.action_paths ?? [])].sort((left, right) => left.localeCompare(right)),\n };\n}\n\nfunction resolveCommandDiscoveryPackageName(extensionName: string, source: ManagedExtensionSource): string {\n if (typeof source.package === \"string\" && source.package.trim().length > 0) {\n return source.package.trim();\n }\n if (source.kind === \"builtin\" && typeof source.name === \"string\" && source.name.trim().length > 0) {\n return source.name.trim();\n }\n return extensionName;\n}\n\nfunction buildInstallCommandDiscovery(\n extensionName: string,\n source: ManagedExtensionSource,\n commandSummary: { command_paths: string[]; action_paths: string[] },\n): Record<string, unknown> {\n const helpCommands = commandSummary.command_paths.map((commandPath) => `pm ${commandPath} --help`);\n return {\n package_name: resolveCommandDiscoveryPackageName(extensionName, source),\n extension_name: extensionName,\n command_paths: commandSummary.command_paths,\n action_paths: commandSummary.action_paths,\n help_commands: helpCommands,\n next_steps:\n commandSummary.command_paths.length > 0\n ? helpCommands\n : [\"Run pm package doctor --project --detail deep if expected package commands are missing.\"],\n };\n}\n\nfunction summarizeActivationFailureForDiagnostics(failure: ActivationFailureEntry): ActivationFailureDiagnostic {\n const trace = failure.trace\n ? {\n method: failure.trace.method,\n registration_index: failure.trace.registration_index,\n expected_schema: failure.trace.expected_schema,\n ...(failure.trace.command ? { command: failure.trace.command } : {}),\n ...(failure.trace.capability ? { capability: failure.trace.capability } : {}),\n ...(failure.trace.missing_capability ? { missing_capability: failure.trace.missing_capability } : {}),\n ...(failure.trace.hint ? { hint: failure.trace.hint } : {}),\n }\n : undefined;\n return {\n layer: failure.layer,\n name: failure.name,\n entry_path: failure.entry_path,\n error: failure.error,\n ...(failure.trace?.missing_capability ? { missing_capability: failure.trace.missing_capability } : {}),\n ...(failure.trace?.hint ? { hint: failure.trace.hint } : {}),\n ...(trace ? { trace } : {}),\n };\n}\n\nfunction collectActivationFailureDiagnostics(failures: ActivationFailureEntry[]): ActivationFailureDiagnostic[] {\n return failures\n .map((failure) => summarizeActivationFailureForDiagnostics(failure))\n .sort((left, right) => `${left.layer}:${left.name}`.localeCompare(`${right.layer}:${right.name}`));\n}\n\nfunction findActivationFailureByName(\n extensionName: string,\n failures: ActivationFailureDiagnostic[],\n layer?: ExtensionScope,\n): ActivationFailureDiagnostic | undefined {\n const normalizedName = normalizeExtensionNameForMatch(extensionName);\n return failures.find(\n (failure) =>\n (layer === undefined || failure.layer === layer) &&\n normalizeExtensionNameForMatch(failure.name) === normalizedName,\n );\n}\n\nfunction resolveInstallRuntimeActivationStatus(\n extensionName: string,\n scope: ExtensionScope,\n runtimeInstalled: ManagedExtensionSummary[],\n installActivationFailure: ActivationFailureDiagnostic | undefined,\n): ExtensionActivationStatus {\n const runtimeInstalledExtension = runtimeInstalled.find(\n (entry) =>\n entry.scope === scope && normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(extensionName),\n );\n return runtimeInstalledExtension?.activation_status ?? (installActivationFailure ? \"failed\" : \"unknown\");\n}\n\nasync function probeRuntimeCommandPathsForInstall(\n pmRoot: string,\n settings: PmSettings,\n refreshedInstalled: ManagedExtensionSummary[],\n global: GlobalOptions,\n): Promise<{\n installed: ManagedExtensionSummary[];\n warnings: string[];\n activation_failures: ActivationFailureDiagnostic[];\n item_type_registrations: Awaited<ReturnType<typeof activateExtensions>>[\"registrations\"][\"item_types\"];\n}> {\n const loadResult = await loadExtensions({\n pmRoot,\n settings,\n cwd: process.cwd(),\n noExtensions: global.noExtensions === true,\n reload_token: nextExtensionReloadToken(),\n cache_bust: true,\n });\n const activationResult = await activateExtensions({\n ...loadResult,\n loaded: loadResult.loaded,\n });\n return {\n installed: applyDoctorRuntimeActivationState(refreshedInstalled, loadResult, activationResult),\n warnings: [...loadResult.warnings, ...activationResult.warnings],\n activation_failures: collectActivationFailureDiagnostics(activationResult.failed),\n item_type_registrations: activationResult.registrations.item_types,\n };\n}\n\nasync function checkGithubUpdate(\n source: ManagedExtensionSource,\n gitCommandRunner: typeof runGitCommand = runGitCommand,\n): Promise<GithubUpdateStatus> {\n const checkedAt = nowIso();\n if (source.kind !== \"github\" || !source.repository) {\n return {\n checked_at: checkedAt,\n available: null,\n error: \"not_a_github_managed_source\",\n };\n }\n try {\n const ref = source.ref && source.ref.trim().length > 0 ? source.ref.trim() : \"HEAD\";\n const output = await gitCommandRunner([\"ls-remote\", source.repository, ref]);\n const firstLine = output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .find((line) => line.length > 0);\n if (!firstLine) {\n return {\n checked_at: checkedAt,\n available: null,\n error: \"no_remote_reference_found\",\n };\n }\n const [remoteCommit] = firstLine.split(/\\s+/);\n /* c8 ignore start -- firstLine is trimmed non-empty, so split always yields a non-empty first token */\n if (typeof remoteCommit !== \"string\" || remoteCommit.length === 0) {\n return {\n checked_at: checkedAt,\n available: null,\n error: \"invalid_remote_reference\",\n };\n }\n /* c8 ignore stop */\n if (typeof source.commit === \"string\" && source.commit.trim().length > 0) {\n return {\n checked_at: checkedAt,\n remote_commit: remoteCommit,\n available: remoteCommit !== source.commit.trim(),\n };\n }\n return {\n checked_at: checkedAt,\n remote_commit: remoteCommit,\n available: null,\n error: \"missing_installed_commit\",\n };\n } catch (error: unknown) {\n return {\n checked_at: checkedAt,\n available: null,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\ninterface AdoptedUnmanagedExtension {\n name: string;\n directory: string;\n version: string;\n entry: string;\n source: ManagedExtensionSource;\n}\n\ninterface AdoptUnmanagedExtensionsResult {\n state: ManagedExtensionState;\n adopted_entries: AdoptedUnmanagedExtension[];\n unmanaged_candidates: ManagedExtensionSummary[];\n already_managed_count: number;\n}\n\nasync function adoptUnmanagedExtensions(\n extensionsRoot: string,\n scope: ExtensionScope,\n installedExtensions: ManagedExtensionSummary[],\n state: ManagedExtensionState,\n): Promise<AdoptUnmanagedExtensionsResult> {\n const unmanagedCandidates = installedExtensions.filter((entry) => !entry.managed);\n const sortedCandidates = [...unmanagedCandidates].sort((left, right) => {\n const byName = left.name.localeCompare(right.name);\n if (byName !== 0) {\n return byName;\n }\n return left.directory.localeCompare(right.directory);\n });\n\n let nextState = state;\n const adoptedEntries: AdoptedUnmanagedExtension[] = [];\n for (const candidate of sortedCandidates) {\n const extensionDirectory = path.join(extensionsRoot, candidate.directory);\n const validated = await validateExtensionDirectory(extensionDirectory);\n const now = nowIso();\n const sourceRecord: ManagedExtensionSource = {\n kind: \"local\",\n input: candidate.name,\n location: extensionDirectory,\n };\n nextState = upsertManagedEntry(nextState, {\n name: validated.manifest.name,\n directory: candidate.directory,\n scope,\n manifest_version: validated.manifest.version,\n manifest_entry: validated.manifest.entry,\n capabilities: [...validated.manifest.capabilities],\n installed_at: now,\n updated_at: now,\n source: sourceRecord,\n });\n adoptedEntries.push({\n name: validated.manifest.name,\n directory: candidate.directory,\n version: validated.manifest.version,\n entry: validated.manifest.entry,\n source: sourceRecord,\n });\n }\n\n if (adoptedEntries.length > 0) {\n await writeManagedExtensionState(extensionsRoot, nextState);\n }\n\n return {\n state: nextState,\n adopted_entries: adoptedEntries,\n unmanaged_candidates: sortedCandidates,\n already_managed_count: installedExtensions.length - unmanagedCandidates.length,\n };\n}\n\nfunction resolveExtensionRootsForScope(scope: ExtensionScope, global: GlobalOptions): {\n pm_root: string;\n scope: ExtensionScope;\n settings_root: string;\n selected_root: string;\n roots: { global: string; project: string };\n} {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n const roots = resolveExtensionRoots(pmRoot, process.cwd());\n const settingsRoot = scope === \"global\" ? resolveGlobalPmRoot(process.cwd()) : pmRoot;\n const selectedRoot = scope === \"global\" ? roots.global : roots.project;\n return {\n pm_root: pmRoot,\n scope,\n settings_root: settingsRoot,\n selected_root: selectedRoot,\n roots,\n };\n}\n\nfunction resolveGithubOption(options: ExtensionCommandOptions): string | undefined {\n if (typeof options.gh === \"string\" && typeof options.github === \"string\" && options.gh.trim() !== options.github.trim()) {\n throw new PmCliError('Options \"--gh\" and \"--github\" must match when both are provided.', EXIT_CODE.USAGE);\n }\n if (typeof options.gh === \"string\" && options.gh.trim().length > 0) {\n return options.gh.trim();\n }\n if (typeof options.github === \"string\" && options.github.trim().length > 0) {\n return options.github.trim();\n }\n return undefined;\n}\n\nfunction getLifecycleActionFlag(action: ExtensionCommandAction): `--${string}` {\n return LIFECYCLE_ACTION_FLAGS[action];\n}\n\nfunction requireTarget(target: string | undefined, action: ExtensionCommandAction, options: ExtensionCommandOptions = {}): string {\n const normalized = target?.trim();\n if (!normalized) {\n if (action === \"init\") {\n throw new PmCliError(\n 'Action \"init\" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',\n EXIT_CODE.USAGE,\n );\n }\n const noun = options.vocabulary === \"package\" ? \"package\" : \"extension\";\n const targetName = action === \"install\" ? \"source\" : \"name\";\n const targetLabel = `${noun} ${targetName}`;\n const actionFlag = getLifecycleActionFlag(action);\n const commandTarget = `<${targetName}>`;\n const command = `pm ${noun} ${actionFlag} ${commandTarget}`;\n throw new PmCliError(\n `Action \"${action}\" requires ${targetLabel} input.`,\n EXIT_CODE.USAGE,\n {\n code: \"missing_lifecycle_target\",\n required: `Provide a ${targetName} target for ${action}.`,\n examples: [`pm ${noun} ${action} ${commandTarget}`, command, `pm ${noun} --help`],\n recovery: {\n attempted_command: `pm ${noun} ${action}`,\n suggested_retry: command,\n fallback_candidates: [\n {\n source: \"lifecycle_action\",\n command,\n reason: `flag-form ${action} command with required ${targetName} target`,\n },\n ],\n },\n },\n );\n }\n return normalized;\n}\n\nfunction collectGlobalOutputOverrideDoctorWarnings(\n activationResult: Awaited<ReturnType<typeof activateExtensions>>,\n): string[] {\n const warnings: string[] = [];\n for (const entry of activationResult.services.overrides) {\n if (entry.service !== \"output_format\") {\n continue;\n }\n warnings.push(`extension_output_service_override_global:${entry.service}:${entry.layer}:${entry.name}`);\n }\n for (const entry of activationResult.renderers.overrides) {\n warnings.push(`extension_output_renderer_override_global:${entry.format}:${entry.layer}:${entry.name}`);\n }\n return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Doctor advisory: flag loaded extensions that contribute GLOBAL schema (custom\n * item types or fields) yet also declare narrow `activation.commands`.\n *\n * Custom item types and fields must be present for the built-in commands the\n * extension does not own and cannot enumerate (`pm create <type>`,\n * `pm list --type <type>`, `pm validate`). Declaring `activation.commands` gates\n * lazy activation to only the listed command paths, so the package never\n * activates for those built-ins and its custom type silently fails to register —\n * a quiet footgun (decision pm-halx). The `schema` scaffold deliberately omits\n * the field; this advisory catches hand-authored packages that do not. It is\n * doctor-only and non-blocking — `pm health` does not surface it — so the author\n * can either drop `activation.commands` or, when the schema is intentionally\n * command-scoped, knowingly ignore the hint.\n */\nfunction collectSchemaNarrowActivationDoctorWarnings(\n loadResult: Awaited<ReturnType<typeof loadExtensions>>,\n activationResult: Awaited<ReturnType<typeof activateExtensions>>,\n): string[] {\n const schemaContributors = new Set<string>();\n for (const entry of activationResult.registrations.item_types) {\n if (entry.types.length > 0) {\n schemaContributors.add(`${entry.layer}:${normalizeExtensionNameForMatch(entry.name)}`);\n }\n }\n for (const entry of activationResult.registrations.item_fields) {\n if (entry.fields.length > 0) {\n schemaContributors.add(`${entry.layer}:${normalizeExtensionNameForMatch(entry.name)}`);\n }\n }\n const warnings: string[] = [];\n for (const extension of loadResult.loaded) {\n if ((extension.activation?.commands ?? []).length === 0) {\n continue;\n }\n if (schemaContributors.has(`${extension.layer}:${normalizeExtensionNameForMatch(extension.name)}`)) {\n warnings.push(`extension_schema_narrow_activation:${extension.layer}:${extension.name}`);\n }\n }\n return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Shared, per-invocation context threaded to each extension action handler: the\n * resolved action/scope/roots, the alias-normalized target, the accumulating\n * warnings sink, the caller options/globals, and the `withResult` builder that\n * stamps the canonical {@link ExtensionCommandResult} envelope.\n */\ninterface ExtensionActionContext {\n action: ExtensionCommandAction;\n normalizedTarget: string | undefined;\n scope: ExtensionScope;\n resolvedRoots: ReturnType<typeof resolveExtensionRootsForScope>;\n warnings: string[];\n options: ExtensionCommandOptions;\n global: GlobalOptions;\n withResult: (details: Record<string, unknown>) => ExtensionCommandResult;\n}\n\n/**\n * Reject option/action combinations that are only meaningful for a specific\n * lifecycle action — `--trace`/`--strict-exit`/`--fail-on-warn` require `--doctor`,\n * `--watch` requires `--reload`, `--runtime-probe` requires `--manage`,\n * `--fix-managed-state` requires `--manage`/`--doctor`, and\n * `--capability`/`--declarative` require `--init`/`--scaffold`. Each guard pairs a\n * \"flag is set\" predicate with the action(s) that permit it and throws a USAGE\n * error on the first mismatch.\n */\nfunction assertExtensionActionOptionScope(action: ExtensionCommandAction, options: ExtensionCommandOptions): void {\n const guards: Array<{ triggered: boolean; allowed: boolean; message: string }> = [\n {\n triggered: options.strictExit === true || options.failOnWarn === true,\n allowed: action === \"doctor\",\n message: \"--strict-exit and --fail-on-warn are only valid with --doctor.\",\n },\n { triggered: options.trace === true, allowed: action === \"doctor\", message: \"--trace is only valid with --doctor.\" },\n { triggered: options.watch === true, allowed: action === \"reload\", message: \"--watch is only valid with --reload.\" },\n {\n triggered: options.runtimeProbe === true,\n allowed: action === \"manage\",\n message: \"--runtime-probe is only valid with --manage.\",\n },\n {\n triggered: options.fixManagedState === true,\n allowed: action === \"manage\" || action === \"doctor\",\n message: \"--fix-managed-state is only valid with --manage or --doctor.\",\n },\n {\n triggered: options.capability !== undefined,\n allowed: action === \"init\",\n message: \"--capability is only valid with --init/--scaffold.\",\n },\n {\n triggered: options.declarative === true,\n allowed: action === \"init\",\n message: \"--declarative is only valid with --init/--scaffold.\",\n },\n ];\n for (const guard of guards) {\n if (guard.triggered && !guard.allowed) {\n throw new PmCliError(guard.message, EXIT_CODE.USAGE);\n }\n }\n}\n\n/* c8 ignore start -- alias-normalization matrix is covered by resolveAction tests; this only rewrites positional aliases */\n/**\n * Collapse a positional target that merely repeats the action keyword\n * (`pm extension doctor`, `reload`, `catalog`, or `init`/`scaffold`) to\n * `undefined` so the action handlers treat it as \"no target\" rather than an\n * extension name; otherwise the original target is returned unchanged.\n */\nfunction resolveNormalizedExtensionTarget(\n target: string | undefined,\n action: ExtensionCommandAction,\n options: ExtensionCommandOptions,\n): string | undefined {\n const normalizedInput = target?.trim().toLowerCase();\n if (action === \"doctor\" && normalizedInput === \"doctor\") {\n return undefined;\n }\n if (action === \"reload\" && normalizedInput === \"reload\") {\n return undefined;\n }\n if (action === \"catalog\" && normalizedInput === \"catalog\") {\n return undefined;\n }\n const inferredInitAlias =\n action === \"init\" &&\n options.init !== true &&\n options.scaffold !== true &&\n (normalizedInput === \"init\" || normalizedInput === \"scaffold\");\n if (inferredInitAlias) {\n return undefined;\n }\n return target;\n}\n/* c8 ignore stop */\n\n/**\n * Entry point for the `pm extension` / `pm package` command surface. Resolves the\n * requested lifecycle action and scope, rejects out-of-scope option usage,\n * normalizes positional aliases, then dispatches to the matching action handler —\n * each of which reads and writes managed-extension state, runtime-probes, and\n * returns the canonical {@link ExtensionCommandResult}. `--doctor` results are\n * flagged for native (non-JSON-wrapped) output.\n */\nexport async function runExtension(\n target: string | undefined,\n options: ExtensionCommandOptions,\n global: GlobalOptions,\n): Promise<ExtensionCommandResult> {\n const action = resolveAction(target, options);\n assertExtensionActionOptionScope(action, options);\n const normalizedTarget = resolveNormalizedExtensionTarget(target, action, options);\n const scope = resolveScope(options);\n const resolvedRoots = resolveExtensionRootsForScope(scope, global);\n const warnings: string[] = [];\n const withResult = (details: Record<string, unknown>): ExtensionCommandResult => {\n const result: ExtensionCommandResult = {\n ok: true,\n action,\n scope,\n roots: action === \"catalog\" && typeof options.fields === \"string\" && options.fields.trim().length > 0\n ? {\n project: \"project\",\n global: \"global\",\n selected: scope,\n settings_root: \"project\",\n }\n : {\n project: resolvedRoots.roots.project,\n global: resolvedRoots.roots.global,\n selected: resolvedRoots.selected_root,\n settings_root: resolvedRoots.settings_root,\n },\n warnings: [...new Set(warnings)].sort((left, right) => left.localeCompare(right)),\n details,\n };\n if (action === \"doctor\") {\n Object.defineProperty(result, NATIVE_OUTPUT_MARKER, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n }\n return result;\n };\n const ctx: ExtensionActionContext = {\n action,\n normalizedTarget,\n scope,\n resolvedRoots,\n warnings,\n options,\n global,\n withResult,\n };\n return EXTENSION_ACTION_HANDLERS[action](ctx);\n}\n\nasync function runExtensionInitAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, normalizedTarget, options, withResult } = ctx;\n const githubOption = resolveGithubOption(options);\n if (githubOption !== undefined || (typeof options.ref === \"string\" && options.ref.trim().length > 0)) {\n throw new PmCliError('Action \"init\" does not accept --gh/--github/--ref options.', EXIT_CODE.USAGE);\n }\n const scaffoldTarget = requireTarget(normalizedTarget, action, options);\n const scaffold = await scaffoldExtensionProject(\n scaffoldTarget,\n options.vocabulary ?? \"extension\",\n options.capability,\n options.declarative === true,\n );\n const quotedTargetPath = JSON.stringify(scaffold.target_path);\n // Forward-slash the path for the copy-pasteable `cd` hint: Windows cmd.exe /\n // PowerShell reject the doubled backslashes JSON.stringify emits, while both\n // shells (and POSIX) accept forward slashes.\n const quotedShellTargetPath = JSON.stringify(scaffold.target_path.replace(/\\\\/g, \"/\"));\n return withResult({\n scaffolded: scaffold.created_directory || scaffold.files.some((entry) => entry.status === \"created\"),\n extension: {\n name: scaffold.extension_name,\n command: scaffold.command_name,\n },\n capability: scaffold.capability,\n style: scaffold.style,\n target_path: scaffold.target_path,\n created_directory: scaffold.created_directory,\n files: scaffold.files,\n next_steps: [\n // Extensions are authored AND loaded as TypeScript (ADR pm-2c28 / pm-m1uz):\n // the manifest entry is ./index.ts and pm strips types on load (Node\n // >=22.18), so there is no compile/build step — install dependencies, then\n // install the scaffold directly.\n ...(options.vocabulary === \"package\"\n ? [`Install dependencies: cd ${quotedShellTargetPath}, then run \"npm install\"`]\n : [\n `Install type-check dependencies: cd ${quotedShellTargetPath}, then run \"npm install -D typescript @types/node @unbrained/pm-cli\"`,\n ]),\n `Install the scaffold: ${options.vocabulary === \"package\" ? \"pm install --project\" : \"pm extension --install --project\"} ${quotedTargetPath}`,\n `Smoke-test command path: pm ${scaffold.command_name}`,\n ...(options.vocabulary === \"package\"\n ? [`Validate the package: cd ${quotedShellTargetPath}, then run \"npm run typecheck\" and \"npm test\"`]\n : [`Type-check the source (optional): cd ${quotedShellTargetPath}, then run \"npx tsc --noEmit\"`]),\n `Run diagnostics: ${options.vocabulary === \"package\" ? \"pm package doctor\" : \"pm extension --doctor\"} --project --detail summary`,\n ],\n });\n}\n\nasync function runExtensionReloadAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { normalizedTarget, resolvedRoots, warnings, options, global, withResult } = ctx;\n if (normalizedTarget !== undefined) {\n throw new PmCliError('Action \"reload\" does not accept a target argument.', EXIT_CODE.USAGE);\n }\n const settings = await readSettings(resolvedRoots.settings_root);\n const reloadToken = nextExtensionReloadToken();\n const reloaded = await loadExtensions({\n pmRoot: resolvedRoots.settings_root,\n settings,\n cwd: process.cwd(),\n noExtensions: global.noExtensions,\n reload_token: reloadToken,\n cache_bust: true,\n });\n warnings.push(...reloaded.warnings);\n const activation = await activateExtensions(reloaded);\n warnings.push(...activation.warnings);\n const details = {\n reload: {\n token: reloadToken,\n cache_bust: true,\n watch: options.watch === true,\n },\n loaded_count: reloaded.loaded.length,\n failed_count: reloaded.failed.length,\n activated_count: Math.max(0, reloaded.loaded.length - activation.failed.length),\n activation_failed_count: activation.failed.length,\n loaded_extensions: reloaded.loaded.map((entry) => ({\n name: entry.name,\n layer: entry.layer,\n version: entry.version,\n })),\n failed_extensions: reloaded.failed.map((entry) => ({\n name: entry.name,\n layer: entry.layer,\n error: entry.error,\n })),\n activation_failures: activation.failed.map((entry) => ({\n name: entry.name,\n layer: entry.layer,\n error: entry.error,\n })),\n };\n if (options.watch === true) {\n warnings.push(\"extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only\");\n }\n return withResult(details);\n}\n\nasync function runExtensionCatalogAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { normalizedTarget, scope, options, global, withResult } = ctx;\n if (typeof normalizedTarget === \"string\" && normalizedTarget.length > 0 && normalizedTarget !== \"catalog\") {\n throw new PmCliError('Action \"catalog\" does not accept a package target.', EXIT_CODE.USAGE);\n }\n return withResult(await buildBundledPackageCatalog(scope, global, options));\n}\n\n/* c8 ignore start -- source-shape branch combinations are exercised in install-source focused tests */\n/**\n * Build the persisted managed-source record for an install from its resolved\n * shape: a bundled builtin alias, a local path, an npm package, or (the default) a\n * GitHub repository, capturing the location/commit/subpath provenance the manage\n * and upgrade flows later read back.\n */\nfunction buildInstallManagedSource(\n bundledAliasName: string | null,\n bundledPackageName: string | null,\n installSource: ReturnType<typeof parseExtensionInstallSource>,\n resolvedSource: Awaited<ReturnType<typeof resolveInstallSource>>,\n): ManagedExtensionSource {\n if (bundledAliasName) {\n return {\n kind: \"builtin\",\n input: bundledAliasName,\n location: bundledAliasName,\n name: bundledAliasName,\n ...(bundledPackageName === null ? {} : { package: bundledPackageName }),\n };\n }\n if (installSource.kind === \"local\") {\n return {\n kind: \"local\",\n input: installSource.input,\n location: installSource.absolute_path,\n };\n }\n if (installSource.kind === \"npm\") {\n return {\n kind: \"npm\",\n input: installSource.input,\n location: resolvedSource.resolved_subpath ?? \".\",\n package: resolvedSource.npm_package,\n version: resolvedSource.npm_version,\n };\n }\n return {\n kind: \"github\",\n input: installSource.input,\n location: resolvedSource.resolved_subpath ?? installSource.subpath ?? \".\",\n repository: installSource.repository,\n owner: installSource.owner,\n repo: installSource.repo,\n ref: installSource.ref,\n subpath: resolvedSource.resolved_subpath ?? installSource.subpath,\n commit: resolvedSource.commit,\n };\n}\n/* c8 ignore stop */\n\n/**\n * Run the install body while holding the per-destination install lock: read\n * settings and managed state, copy the validated extension into the scope root\n * unless it is already installed in place, upsert the managed entry and activation\n * state, scaffold any contributed item-type folders, runtime-probe the freshly\n * installed command paths, and return the install result envelope.\n */\nasync function performExtensionInstallUnderLock(\n ctx: ExtensionActionContext,\n input: {\n validated: Awaited<ReturnType<typeof validateExtensionDirectory>>;\n destinationDirectoryName: string;\n bundledAliasName: string | null;\n bundledPackageName: string | null;\n installSource: ReturnType<typeof parseExtensionInstallSource>;\n resolvedSource: Awaited<ReturnType<typeof resolveInstallSource>>;\n },\n): Promise<ExtensionCommandResult> {\n const { scope, resolvedRoots, warnings, global, withResult } = ctx;\n const { validated, destinationDirectoryName, bundledAliasName, bundledPackageName, installSource, resolvedSource } = input;\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const destinationDirectory = path.join(resolvedRoots.selected_root, destinationDirectoryName);\n const destinationExists = await pathExists(destinationDirectory);\n const installInPlace = await areDirectoriesEquivalent(validated.directory, destinationDirectory);\n\n await fs.mkdir(resolvedRoots.selected_root, { recursive: true });\n if (!installInPlace) {\n await copyExtensionDirectoryForInstall(validated.directory, destinationDirectory);\n }\n await ensureExtensionModuleTypeMarker(destinationDirectory);\n\n const sourceRecord = buildInstallManagedSource(bundledAliasName, bundledPackageName, installSource, resolvedSource);\n\n const now = nowIso();\n const existingManagedEntry = managedStateRead.state.entries.find(\n (entry) => normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(validated.manifest.name),\n );\n const sourceUnchanged =\n existingManagedEntry !== undefined &&\n existingManagedEntry.manifest_version === validated.manifest.version &&\n managedExtensionSourcesEquivalent(existingManagedEntry.source, sourceRecord);\n const managedState = upsertManagedEntry(managedStateRead.state, {\n name: validated.manifest.name,\n directory: destinationDirectoryName,\n scope,\n manifest_version: validated.manifest.version,\n manifest_entry: validated.manifest.entry,\n capabilities: [...validated.manifest.capabilities],\n installed_at: existingManagedEntry?.installed_at ?? now,\n updated_at: sourceUnchanged ? existingManagedEntry.updated_at : now,\n source: sourceRecord,\n });\n await writeManagedExtensionState(resolvedRoots.selected_root, managedState);\n\n const activationChanged = ensureActivated(settings, validated.manifest.name);\n if (activationChanged) {\n await writeSettings(resolvedRoots.settings_root, settings, \"settings:write\");\n }\n const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);\n warnings.push(...refreshedInstalled.warnings);\n const runtimeProbe = await probeRuntimeCommandPathsForInstall(\n resolvedRoots.pm_root,\n settings,\n refreshedInstalled.extensions,\n global,\n );\n warnings.push(...runtimeProbe.warnings);\n // Scaffold the folders for any item types the installed package contributes\n // so the tracker is immediately healthy — matching `pm schema add-type` and\n // `pm profile apply`, the other paths that register a type. Without this a\n // freshly-installed schema package leaves a `missing_directory` health\n // warning until the first item of its type is created. Scoped to project\n // installs, where `pm_root` is unambiguously the tracker the type folders\n // belong to; a global install is not tied to one tracker, so its folders are\n // created lazily on first use in each project.\n const installedItemTypeDefinitions = runtimeProbe.item_type_registrations\n .filter((entry) => normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(validated.manifest.name))\n .flatMap((entry) => entry.types.map((type) => ({ name: type.name, folder: type.folder })));\n if (scope === \"project\" && installedItemTypeDefinitions.length > 0) {\n await ensureTypeFolderScaffold(resolvedRoots.pm_root, installedItemTypeDefinitions, warnings, \"install:type-folder\");\n }\n const commandSummary = summarizeRuntimeCommandPathsForExtension(validated.manifest.name, runtimeProbe.installed);\n const installActivationFailure = findActivationFailureByName(\n validated.manifest.name,\n runtimeProbe.activation_failures,\n scope,\n );\n const runtimeActivationStatus = resolveInstallRuntimeActivationStatus(\n validated.manifest.name,\n scope,\n runtimeProbe.installed,\n installActivationFailure,\n );\n\n return withResult({\n extension: {\n name: validated.manifest.name,\n version: validated.manifest.version,\n entry: validated.manifest.entry,\n capabilities: validated.manifest.capabilities,\n directory: destinationDirectoryName,\n },\n source: sourceRecord,\n destination_path: destinationDirectory,\n overwritten: destinationExists && !installInPlace,\n installed_in_place: installInPlace,\n activated: true,\n settings_changed: activationChanged,\n runtime_activation_status: runtimeActivationStatus,\n command_paths: commandSummary.command_paths,\n action_paths: commandSummary.action_paths,\n command_discovery: buildInstallCommandDiscovery(validated.manifest.name, sourceRecord, commandSummary),\n activation_diagnostics: {\n failed_count: runtimeProbe.activation_failures.length,\n failed: runtimeProbe.activation_failures,\n installed_extension_failed: installActivationFailure ?? null,\n },\n });\n}\n\nasync function runExtensionInstallAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, normalizedTarget, resolvedRoots, warnings, options, global, withResult } = ctx;\n const githubOption = resolveGithubOption(options);\n const explicitSourceInput = githubOption ?? requireTarget(normalizedTarget, action, options);\n if (typeof githubOption !== \"string\" && isBundledPackageInstallAllTarget(explicitSourceInput)) {\n if (typeof options.ref === \"string\" && options.ref.trim().length > 0) {\n throw new PmCliError('Action \"install all\" does not accept --ref.', EXIT_CODE.USAGE);\n }\n const aliases = await listBundledPackageAliases();\n const packages: Array<{ alias: string; result: ExtensionCommandResult }> = [];\n for (const alias of aliases) {\n packages.push({\n alias,\n result: await runExtension(alias, { ...options, install: true }, global),\n });\n }\n for (const entry of packages) {\n warnings.push(...entry.result.warnings);\n }\n return withResult({\n installed_all: true,\n installed_count: packages.length,\n packages: packages.map((entry) => ({\n alias: entry.alias,\n ok: entry.result.ok,\n extension: (entry.result.details as { extension?: unknown }).extension,\n source: (entry.result.details as { source?: unknown }).source,\n destination_path: (entry.result.details as { destination_path?: unknown }).destination_path,\n activated: (entry.result.details as { activated?: unknown }).activated,\n settings_changed: (entry.result.details as { settings_changed?: unknown }).settings_changed,\n command_paths: (entry.result.details as { command_paths?: unknown }).command_paths,\n action_paths: (entry.result.details as { action_paths?: unknown }).action_paths,\n command_discovery: (entry.result.details as { command_discovery?: unknown }).command_discovery,\n warnings: entry.result.warnings,\n })),\n });\n }\n /* c8 ignore start -- github/local alias-source split is exercised in install-action integration tests */\n const bundledAliasSource =\n typeof githubOption === \"string\" ? null : await resolveBundledExtensionAliasSource(explicitSourceInput);\n /* c8 ignore stop */\n const bundledAliasName = bundledAliasSource === null ? null : explicitSourceInput.trim().toLowerCase();\n const bundledPackageName = bundledAliasName === null ? null : await resolveBundledPackageNpmName(bundledAliasName);\n const sourceInput = bundledAliasSource ?? explicitSourceInput;\n /* c8 ignore start -- install-source branch combinations are covered in install-sources focused tests */\n const installSource = parseExtensionInstallSource(sourceInput, {\n forceGithub: typeof githubOption === \"string\",\n ref: options.ref,\n });\n /* c8 ignore stop */\n const resolvedSource = await resolveInstallSource(installSource);\n try {\n const validated = await validateExtensionDirectory(resolvedSource.directory);\n const destinationDirectoryName = normalizeManagedDirectoryName(validated.manifest.name);\n return await withExtensionInstallLock(resolvedRoots.settings_root, destinationDirectoryName, () =>\n performExtensionInstallUnderLock(ctx, {\n validated,\n destinationDirectoryName,\n bundledAliasName,\n bundledPackageName,\n installSource,\n resolvedSource,\n }),\n );\n } finally {\n /* c8 ignore start -- cleanup hooks are only present for transient install sources */\n if (resolvedSource.cleanup) {\n await resolvedSource.cleanup();\n }\n /* c8 ignore stop */\n }\n}\n\nasync function runExtensionAdoptAllAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { normalizedTarget, scope, resolvedRoots, warnings, options, withResult } = ctx;\n if (normalizedTarget !== undefined) {\n throw new PmCliError('Action \"adopt-all\" does not accept a target argument.', EXIT_CODE.USAGE);\n }\n const githubOption = resolveGithubOption(options);\n if (githubOption !== undefined || (typeof options.ref === \"string\" && options.ref.trim().length > 0)) {\n throw new PmCliError('Action \"adopt-all\" does not accept --gh/--github/--ref options.', EXIT_CODE.USAGE);\n }\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n const adoption = await adoptUnmanagedExtensions(\n resolvedRoots.selected_root,\n scope,\n installed.extensions,\n managedStateRead.state,\n );\n const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, adoption.state);\n warnings.push(...refreshedInstalled.warnings);\n const triage = buildExtensionTriageSummary(scope, warnings, refreshedInstalled.extensions, options);\n warnings.push(...triage.warnings);\n /* c8 ignore start -- refresh-entry optional metadata is display-only and exercised indirectly */\n const adoptedDetails = adoption.adopted_entries.map((entry) => {\n const refreshedEntry =\n refreshedInstalled.extensions.find(\n (candidate) =>\n normalizeExtensionNameForMatch(candidate.name) === normalizeExtensionNameForMatch(entry.name) &&\n normalizeExtensionNameForMatch(candidate.directory) === normalizeExtensionNameForMatch(entry.directory),\n ) ??\n /* c8 ignore next 3 -- fallback only matters if a manifest renames between adopt and refresh */\n refreshedInstalled.extensions.find(\n (candidate) => normalizeExtensionNameForMatch(candidate.directory) === normalizeExtensionNameForMatch(entry.directory),\n );\n return {\n ...entry,\n update_check_status: refreshedEntry?.update_check_status ?? null,\n update_check_reason: refreshedEntry?.update_check_reason ?? null,\n };\n });\n /* c8 ignore stop */\n /* c8 ignore start -- adopt-all summary booleans are deterministic mirrors of adoptedDetails length */\n return withResult({\n adopted_all: adoptedDetails.length > 0,\n adopted_count: adoptedDetails.length,\n already_managed_count: adoption.already_managed_count,\n extensions: adoptedDetails,\n triage,\n warning_codes: triage.warning_codes,\n update_health_partial: triage.update_health_partial,\n update_health_coverage: triage.update_health_coverage,\n });\n /* c8 ignore stop */\n}\n\nasync function runExtensionAdoptAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, normalizedTarget, scope, resolvedRoots, warnings, options, withResult } = ctx;\n const extensionTarget = requireTarget(normalizedTarget, action, options);\n const githubOption = resolveGithubOption(options);\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);\n if (!candidate) {\n throw new PmCliError(`Installed extension \"${extensionTarget}\" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);\n }\n if (candidate.managed) {\n return withResult({\n adopted: false,\n already_managed: true,\n extension: {\n name: candidate.name,\n directory: candidate.directory,\n },\n });\n }\n\n const extensionDirectory = path.join(resolvedRoots.selected_root, candidate.directory);\n const validated = await validateExtensionDirectory(extensionDirectory);\n const now = nowIso();\n const sourceRecord: ManagedExtensionSource =\n githubOption === undefined\n ? {\n kind: \"local\",\n input: extensionTarget,\n location: extensionDirectory,\n }\n : (() => {\n const parsed = parseExtensionInstallSource(githubOption, {\n forceGithub: true,\n ref: options.ref,\n });\n /* c8 ignore start -- forceGithub guarantees a github-kind install source */\n if (parsed.kind !== \"github\") {\n throw new PmCliError(`Invalid GitHub shorthand \"${githubOption}\".`, EXIT_CODE.USAGE);\n }\n /* c8 ignore stop */\n /* c8 ignore start -- github subpath defaults are validated in install-source parser tests */\n return {\n kind: \"github\",\n input: parsed.input,\n location: parsed.subpath ?? \".\",\n repository: parsed.repository,\n owner: parsed.owner,\n repo: parsed.repo,\n ref: parsed.ref,\n subpath: parsed.subpath,\n };\n /* c8 ignore stop */\n })();\n const managedState = upsertManagedEntry(managedStateRead.state, {\n name: validated.manifest.name,\n directory: candidate.directory,\n scope,\n manifest_version: validated.manifest.version,\n manifest_entry: validated.manifest.entry,\n capabilities: [...validated.manifest.capabilities],\n installed_at: now,\n updated_at: now,\n source: sourceRecord,\n });\n await writeManagedExtensionState(resolvedRoots.selected_root, managedState);\n const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);\n warnings.push(...refreshedInstalled.warnings);\n /* c8 ignore start -- fallback only matters if a manifest renames between adopt and refresh */\n const refreshedEntry =\n refreshedInstalled.extensions.find(\n (entry) => normalizeExtensionNameForMatch(entry.name) === normalizeExtensionNameForMatch(validated.manifest.name),\n ) ??\n refreshedInstalled.extensions.find(\n (entry) => normalizeExtensionNameForMatch(entry.directory) === normalizeExtensionNameForMatch(candidate.directory),\n );\n /* c8 ignore stop */\n\n /* c8 ignore start -- adopt result mirrors refreshedEntry optionals for display only */\n return withResult({\n adopted: true,\n extension: {\n name: validated.manifest.name,\n directory: candidate.directory,\n version: validated.manifest.version,\n entry: validated.manifest.entry,\n },\n source: sourceRecord,\n update_check_status: refreshedEntry?.update_check_status ?? null,\n update_check_reason: refreshedEntry?.update_check_reason ?? null,\n });\n /* c8 ignore stop */\n}\n\nasync function runExtensionUninstallAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, normalizedTarget, scope, resolvedRoots, warnings, options, withResult } = ctx;\n const extensionTarget = requireTarget(normalizedTarget, action, options);\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);\n if (!candidate) {\n throw new PmCliError(`Installed extension \"${extensionTarget}\" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);\n }\n const destinationDirectory = path.join(resolvedRoots.selected_root, candidate.directory);\n await fs.rm(destinationDirectory, { recursive: true, force: true });\n\n const updatedState: ManagedExtensionState = {\n ...managedStateRead.state,\n updated_at: nowIso(),\n /* c8 ignore start -- uninstall filter keeps both name+directory guards for legacy managed-state migrations */\n entries: managedStateRead.state.entries.filter(\n (entry) =>\n normalizeExtensionNameForMatch(entry.name) !== normalizeExtensionNameForMatch(candidate.name) &&\n normalizeExtensionNameForMatch(entry.directory) !== normalizeExtensionNameForMatch(candidate.directory),\n ),\n /* c8 ignore stop */\n };\n await writeManagedExtensionState(resolvedRoots.selected_root, updatedState);\n\n const stateChanged = clearExtensionState(settings, candidate.name);\n if (stateChanged) {\n await writeSettings(resolvedRoots.settings_root, settings, \"settings:write\");\n }\n\n return withResult({\n removed: true,\n extension: {\n name: candidate.name,\n directory: candidate.directory,\n },\n destination_path: destinationDirectory,\n settings_changed: stateChanged,\n });\n}\n\nasync function runExtensionActivateDeactivateAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, normalizedTarget, scope, resolvedRoots, warnings, options, withResult } = ctx;\n const extensionTarget = requireTarget(normalizedTarget, action, options);\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n const candidate = await resolveInstalledExtensionCandidate(installed.extensions, extensionTarget);\n if (!candidate) {\n throw new PmCliError(`Installed extension \"${extensionTarget}\" was not found in ${scope} scope.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settingsChanged = action === \"activate\" ? ensureActivated(settings, candidate.name) : ensureDeactivated(settings, candidate.name);\n if (settingsChanged) {\n await writeSettings(resolvedRoots.settings_root, settings, \"settings:write\");\n }\n\n return withResult({\n extension: {\n name: candidate.name,\n directory: candidate.directory,\n },\n active: action === \"activate\",\n settings_changed: settingsChanged,\n settings: {\n enabled: [...settings.extensions.enabled],\n disabled: [...settings.extensions.disabled],\n },\n });\n}\n\n/**\n * Assemble the doctor remediation hints: the triage remediations, vocabulary-aware\n * advice to inspect load failures and activation failures, and a note when a\n * managed-state fix adopted entries. Blank entries are trimmed and the list is\n * de-duplicated.\n */\nfunction buildDoctorRemediation(\n baseRemediation: string[],\n loadFailureCount: number,\n activationFailureCount: number,\n vocabulary: ExtensionCommandOptions[\"vocabulary\"],\n managedStateFix: AdoptUnmanagedExtensionsResult | null,\n): string[] {\n return [\n ...new Set(\n [\n ...baseRemediation,\n /* c8 ignore start -- vocabulary-specific remediation branches are copy-only variants */\n ...(loadFailureCount > 0\n ? [\n vocabulary === \"package\"\n ? \"Run pm package explore --project and pm package explore --global to inspect load failures.\"\n : \"Run pm extension --explore --project and pm extension --explore --global to inspect load failures.\",\n ]\n : []),\n ...(activationFailureCount > 0\n ? [\n vocabulary === \"package\"\n ? \"Review activation failures in pm package doctor --detail deep output.\"\n : \"Review activation failures in pm extension --doctor --detail deep output.\",\n ]\n : []),\n /* c8 ignore stop */\n ...(managedStateFix && managedStateFix.adopted_entries.length > 0\n ? [`Managed-state fix adopted ${managedStateFix.adopted_entries.length} extension(s).`]\n : []),\n ].map((entry) => entry.trim()).filter((entry) => entry.length > 0),\n ),\n ];\n}\n\nasync function runExtensionDoctorAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { normalizedTarget, scope, resolvedRoots, warnings, options, global, withResult } = ctx;\n if (normalizedTarget && normalizedTarget.trim().length > 0) {\n throw new PmCliError('Action \"doctor\" does not accept a target argument.', EXIT_CODE.USAGE);\n }\n const detailMode = parseDoctorDetailMode(options.detail);\n const includeTrace = options.trace === true;\n if (includeTrace && detailMode !== \"deep\") {\n throw new PmCliError(\"--trace requires --detail deep with --doctor.\", EXIT_CODE.USAGE);\n }\n const settings = await readSettings(resolvedRoots.settings_root);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n let managedState = managedStateRead.state;\n const managedStateFix =\n options.fixManagedState === true\n ? await adoptUnmanagedExtensions(\n resolvedRoots.selected_root,\n scope,\n installed.extensions,\n managedStateRead.state,\n )\n : null;\n if (managedStateFix) {\n managedState = managedStateFix.state;\n }\n const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);\n warnings.push(...refreshedInstalled.warnings);\n\n const loadResult = await loadExtensions({\n pmRoot: resolvedRoots.pm_root,\n settings,\n cwd: process.cwd(),\n noExtensions: global.noExtensions === true,\n });\n const activationResult = await activateExtensions({\n ...loadResult,\n loaded: loadResult.loaded,\n });\n warnings.push(...loadResult.warnings);\n warnings.push(...classifyDoctorLoadFailureWarnings(loadResult.failed));\n warnings.push(...activationResult.warnings);\n warnings.push(...classifyDoctorActivationFailureWarnings(activationResult.failed));\n warnings.push(...classifyUnusedCapabilityWarnings(loadResult, activationResult));\n warnings.push(...collectGlobalOutputOverrideDoctorWarnings(activationResult));\n warnings.push(...collectSchemaNarrowActivationDoctorWarnings(loadResult, activationResult));\n const runtimeInstalledExtensions = applyDoctorRuntimeActivationState(refreshedInstalled.extensions, loadResult, activationResult);\n const doctorConsistency = buildDoctorConsistencySummary(\n scope,\n runtimeInstalledExtensions,\n loadResult.loaded.map((entry) => ({ layer: entry.layer, name: entry.name })),\n loadResult.failed.map((entry) => ({ name: entry.name })),\n loadResult.disabled_by_flag,\n );\n warnings.push(...doctorConsistency.warnings);\n const updateCheckWarnings = runtimeInstalledExtensions\n .filter((entry) => entry.update_check_status === \"failed\")\n .map((entry) => `extension_update_check_failed:${entry.name}`);\n warnings.push(...updateCheckWarnings);\n\n const triage = buildExtensionTriageSummary(scope, warnings, runtimeInstalledExtensions, options);\n warnings.push(...triage.warnings);\n const normalizedWarnings = [...triage.warnings];\n const policySummary = {\n mode: loadResult.policy.mode,\n trust_mode: loadResult.policy.trust_mode,\n require_provenance: loadResult.policy.require_provenance,\n default_sandbox_profile: loadResult.policy.default_sandbox_profile,\n // Honest trust model (ADR pm-6ef3): keep this caveat to one concise line.\n sandbox_enforcement:\n \"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)\",\n trusted_extensions_count: loadResult.policy.trusted_extensions.length,\n allowed_extensions_count: loadResult.policy.allowed_extensions.length,\n blocked_extensions_count: loadResult.policy.blocked_extensions.length,\n allowed_capabilities_count: loadResult.policy.allowed_capabilities.length,\n blocked_capabilities_count: loadResult.policy.blocked_capabilities.length,\n allowed_surfaces_count: loadResult.policy.allowed_surfaces.length,\n blocked_surfaces_count: loadResult.policy.blocked_surfaces.length,\n allowed_commands_count: loadResult.policy.allowed_commands.length,\n blocked_commands_count: loadResult.policy.blocked_commands.length,\n allowed_actions_count: loadResult.policy.allowed_actions.length,\n blocked_actions_count: loadResult.policy.blocked_actions.length,\n allowed_services_count: loadResult.policy.allowed_services.length,\n blocked_services_count: loadResult.policy.blocked_services.length,\n extension_override_count: loadResult.policy.extension_overrides.length,\n };\n const capabilityGuidance = collectUnknownCapabilityGuidance(normalizedWarnings);\n const capabilityContract = buildCapabilityContractMetadata();\n const warningCodes = triage.warning_codes;\n const remediation = buildDoctorRemediation(\n triage.remediation,\n loadResult.failed.length,\n activationResult.failed.length,\n options.vocabulary,\n managedStateFix,\n );\n\n const summary = {\n status: triage.status,\n scope,\n warning_count: triage.warning_count,\n warning_codes: warningCodes,\n total_extensions: runtimeInstalledExtensions.length,\n managed_total: runtimeInstalledExtensions.filter((entry) => entry.managed).length,\n enabled_total: runtimeInstalledExtensions.filter((entry) => entry.enabled).length,\n active_total: runtimeInstalledExtensions.filter((entry) => entry.active).length,\n unmanaged_loaded_extension_count: triage.unmanaged_loaded_extension_count,\n unmanaged_action_required_extension_count: triage.unmanaged_action_required_extension_count,\n unmanaged_expected_extension_count: triage.unmanaged_expected_extension_count,\n runtime_active_total: runtimeInstalledExtensions.filter((entry) => entry.runtime_active === true).length,\n activation_status_totals: {\n ok: runtimeInstalledExtensions.filter((entry) => entry.activation_status === \"ok\").length,\n failed: runtimeInstalledExtensions.filter((entry) => entry.activation_status === \"failed\").length,\n not_loaded: runtimeInstalledExtensions.filter((entry) => entry.activation_status === \"not_loaded\").length,\n unknown: runtimeInstalledExtensions.filter((entry) => entry.activation_status === \"unknown\").length,\n },\n unknown_capability_count: capabilityGuidance.length,\n capability_contract_version: capabilityContract.version,\n update_available_total: runtimeInstalledExtensions.filter((entry) => entry.update_available === true).length,\n update_health_coverage: triage.update_health_coverage,\n update_health_partial: triage.update_health_partial,\n update_check_failed_total: runtimeInstalledExtensions.filter((entry) => entry.update_check_status === \"failed\").length,\n load_failure_count: loadResult.failed.length,\n activation_failure_count: activationResult.failed.length,\n blocking_failure_count: loadResult.failed.length + activationResult.failed.length,\n has_blocking_failures: loadResult.failed.length + activationResult.failed.length > 0,\n consistency_warning_count: doctorConsistency.warnings.length,\n trace_enabled: includeTrace,\n policy: policySummary,\n remediation,\n };\n\n const managedStateFixSummary = managedStateFix\n ? {\n requested: true,\n applied: managedStateFix.adopted_entries.length > 0,\n adopted_count: managedStateFix.adopted_entries.length,\n already_managed_count: managedStateFix.already_managed_count,\n adopted_extensions: managedStateFix.adopted_entries.map((entry) => entry.name),\n }\n : {\n requested: false,\n applied: false,\n adopted_count: 0,\n already_managed_count: refreshedInstalled.extensions.filter((entry) => entry.managed).length,\n adopted_extensions: [] as string[],\n };\n\n const details: Record<string, unknown> = {\n mode: detailMode,\n summary,\n triage,\n trace_enabled: includeTrace,\n capability_contract: capabilityContract,\n capability_guidance: capabilityGuidance,\n managed_state_fix: managedStateFixSummary,\n policy: loadResult.policy,\n };\n if (detailMode === \"deep\") {\n const activationFailedDetails = includeTrace\n ? activationResult.failed\n : activationResult.failed.map((entry) => {\n const { trace: _trace, ...rest } = entry;\n return rest;\n });\n details.deep = {\n warnings: normalizedWarnings,\n warning_codes: warningCodes,\n capability_contract: capabilityContract,\n capability_guidance: capabilityGuidance,\n trace_enabled: includeTrace,\n managed_state: {\n path: managedStateRead.path,\n count: managedState.entries.length,\n entries: managedState.entries,\n },\n installed_extensions: runtimeInstalledExtensions,\n load: {\n roots: loadResult.roots,\n policy: loadResult.policy,\n warnings: loadResult.warnings,\n failed: loadResult.failed,\n loaded: loadResult.loaded.map((entry) => ({\n layer: entry.layer,\n directory: entry.directory,\n name: entry.name,\n version: entry.version,\n entry: entry.entry,\n priority: entry.priority,\n })),\n },\n activation: {\n failed: activationFailedDetails,\n warnings: activationResult.warnings,\n hook_counts: activationResult.hook_counts,\n registration_counts: activationResult.registration_counts,\n parser_override_count: activationResult.parser_override_count,\n preflight_override_count: activationResult.preflight_override_count,\n service_override_count: activationResult.service_override_count,\n renderer_override_count: activationResult.renderer_override_count,\n },\n consistency: doctorConsistency.summary,\n };\n if (includeTrace) {\n (details.deep as Record<string, unknown>).trace = {\n activation_failures: activationResult.failed\n .filter((entry) => entry.trace !== undefined)\n .map((entry) => ({\n layer: entry.layer,\n name: entry.name,\n entry_path: entry.entry_path,\n error: entry.error,\n method: entry.trace?.method,\n command: entry.trace?.command,\n capability: entry.trace?.capability,\n missing_capability: entry.trace?.missing_capability,\n registration_index: entry.trace?.registration_index,\n expected_schema: entry.trace?.expected_schema,\n hint: entry.trace?.hint,\n received: entry.trace?.received,\n })),\n };\n }\n }\n return withResult(details);\n}\n\nasync function runExtensionDescribeAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { normalizedTarget, scope, resolvedRoots, warnings, options, global, withResult } = ctx;\n const settings = await readSettings(resolvedRoots.settings_root);\n const loadResult = await loadExtensions({\n pmRoot: resolvedRoots.pm_root,\n settings,\n cwd: process.cwd(),\n noExtensions: global.noExtensions === true,\n });\n const activationResult = await activateExtensions(loadResult);\n warnings.push(...loadResult.warnings);\n warnings.push(...activationResult.warnings);\n const describeResult = buildExtensionDescribeResult(normalizedTarget, loadResult, activationResult);\n if (normalizedTarget !== undefined && describeResult.extensions.length === 0) {\n const noun = options.vocabulary === \"package\" ? \"package\" : \"extension\";\n const loadedNames = [\n ...new Set(\n loadResult.loaded.map((entry) =>\n options.vocabulary === \"package\" && typeof entry.source_package === \"string\" && entry.source_package.trim().length > 0\n ? entry.source_package.trim()\n : entry.name,\n ),\n ),\n ].sort((left, right) => left.localeCompare(right));\n const loadedHint = loadedNames.length > 0 ? ` Loaded ${noun} names: ${loadedNames.join(\", \")}.` : \"\";\n throw new PmCliError(\n `No loaded ${noun} named \"${normalizedTarget}\" was found in ${scope} scope.${loadedHint} Run pm ${noun} explore to list discovered ${noun}s.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n return withResult({\n target: describeResult.target,\n total: describeResult.total,\n extensions: describeResult.extensions,\n union: describeResult.union,\n });\n}\n\n/* c8 ignore start -- explore/manage action split is validated by dedicated command-action tests */\nasync function runExtensionExploreManageAction(ctx: ExtensionActionContext): Promise<ExtensionCommandResult> {\n const { action, scope, resolvedRoots, warnings, options, global, withResult } = ctx;\n const settings = await readSettings(resolvedRoots.settings_root);\n const configuredPolicy = buildExtensionPolicyDetails(settings.extensions.policy);\n const managedStateRead = await readManagedExtensionState(resolvedRoots.selected_root);\n warnings.push(...managedStateRead.warnings);\n const installed = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedStateRead.state);\n warnings.push(...installed.warnings);\n\n let managedState = managedStateRead.state;\n const managedStateFix =\n action === \"manage\" && options.fixManagedState === true\n ? await adoptUnmanagedExtensions(\n resolvedRoots.selected_root,\n scope,\n installed.extensions,\n managedStateRead.state,\n )\n : null;\n if (managedStateFix) {\n managedState = managedStateFix.state;\n }\n if (action === \"manage\") {\n const updates = await Promise.all(\n managedState.entries.map(async (entry) => {\n if (entry.source.kind !== \"github\") {\n return entry;\n }\n const updateStatus = await checkGithubUpdate(entry.source);\n return {\n ...entry,\n last_update_check_at: updateStatus.checked_at,\n last_update_remote_commit: updateStatus.remote_commit,\n update_available: updateStatus.available,\n update_error: updateStatus.error,\n };\n }),\n );\n managedState = {\n ...managedState,\n updated_at: nowIso(),\n entries: sortManagedEntries(updates),\n };\n await writeManagedExtensionState(resolvedRoots.selected_root, managedState);\n }\n\n const refreshedInstalled = await listInstalledExtensions(resolvedRoots.selected_root, scope, settings, managedState);\n warnings.push(...refreshedInstalled.warnings);\n if (action === \"manage\") {\n const updateWarnings = refreshedInstalled.extensions\n .filter((entry) => entry.update_check_status === \"failed\")\n .map((entry) => `extension_update_check_failed:${entry.name}`);\n warnings.push(...updateWarnings);\n }\n let runtimeProbeSummary: Record<string, unknown> | undefined;\n let runtimeInstalledExtensions = refreshedInstalled.extensions;\n let runtimeActivationFailures: ActivationFailureDiagnostic[] | undefined;\n if (action === \"explore\" || options.runtimeProbe === true) {\n const loadResult = await loadExtensions({\n pmRoot: resolvedRoots.pm_root,\n settings,\n cwd: process.cwd(),\n noExtensions: global.noExtensions === true,\n });\n const activationResult = await activateExtensions({\n ...loadResult,\n loaded: loadResult.loaded,\n });\n warnings.push(...loadResult.warnings);\n warnings.push(...activationResult.warnings);\n runtimeInstalledExtensions = applyDoctorRuntimeActivationState(refreshedInstalled.extensions, loadResult, activationResult);\n runtimeActivationFailures = collectActivationFailureDiagnostics(activationResult.failed);\n runtimeProbeSummary = {\n requested: true,\n executed: true,\n reason: action === \"explore\" ? \"explore_defaults_to_runtime_probe\" : \"runtime_probe_requested\",\n load_failure_count: loadResult.failed.length,\n activation_failure_count: activationResult.failed.length,\n warning_count: [...new Set([...loadResult.warnings, ...activationResult.warnings])].length,\n policy: loadResult.policy,\n };\n } else if (action === \"manage\") {\n runtimeProbeSummary = {\n requested: false,\n executed: false,\n };\n }\n\n const triage = buildExtensionTriageSummary(scope, warnings, runtimeInstalledExtensions, options);\n warnings.push(...triage.warnings);\n const details: Record<string, unknown> = {\n total: runtimeInstalledExtensions.length,\n managed_total: runtimeInstalledExtensions.filter((entry) => entry.managed).length,\n enabled_total: runtimeInstalledExtensions.filter((entry) => entry.enabled).length,\n active_total: runtimeInstalledExtensions.filter((entry) => entry.active).length,\n extensions: runtimeInstalledExtensions,\n triage,\n policy: configuredPolicy,\n };\n if (runtimeActivationFailures !== undefined) {\n details.activation_diagnostics = {\n failed_count: runtimeActivationFailures.length,\n failed: runtimeActivationFailures,\n };\n }\n if (action === \"explore\") {\n details.runtime_probe = runtimeProbeSummary;\n }\n if (action === \"manage\") {\n details.runtime_probe = runtimeProbeSummary;\n details.managed_state_fix =\n managedStateFix !== null\n ? {\n requested: true,\n applied: managedStateFix.adopted_entries.length > 0,\n adopted_count: managedStateFix.adopted_entries.length,\n adopted_extensions: managedStateFix.adopted_entries.map((entry) => entry.name),\n already_managed_count: managedStateFix.already_managed_count,\n }\n : {\n requested: false,\n applied: false,\n adopted_count: 0,\n adopted_extensions: [],\n already_managed_count: runtimeInstalledExtensions.filter((entry) => entry.managed).length,\n };\n }\n return withResult(details);\n}\n/* c8 ignore stop */\n\n// Dispatch table from lifecycle action to its handler. `explore`/`manage` and\n// `activate`/`deactivate` share a handler that branches on `ctx.action`; the\n// closed ExtensionCommandAction union guarantees every action has an entry, so\n// runExtension needs no unsupported-action fallthrough.\nconst EXTENSION_ACTION_HANDLERS: Record<\n ExtensionCommandAction,\n (ctx: ExtensionActionContext) => Promise<ExtensionCommandResult>\n> = {\n init: runExtensionInitAction,\n install: runExtensionInstallAction,\n uninstall: runExtensionUninstallAction,\n explore: runExtensionExploreManageAction,\n manage: runExtensionExploreManageAction,\n describe: runExtensionDescribeAction,\n reload: runExtensionReloadAction,\n doctor: runExtensionDoctorAction,\n catalog: runExtensionCatalogAction,\n adopt: runExtensionAdoptAction,\n \"adopt-all\": runExtensionAdoptAllAction,\n activate: runExtensionActivateDeactivateAction,\n deactivate: runExtensionActivateDeactivateAction,\n};\n\nexport const _testOnly = {\n adoptUnmanagedExtensions,\n buildExtensionPolicyDetails,\n buildInstallCommandDiscovery,\n checkGithubUpdate,\n clearExtensionState,\n collectActivationFailureDiagnostics,\n findActivationFailureByName,\n resolveInstallRuntimeActivationStatus,\n collectGlobalOutputOverrideDoctorWarnings,\n collectSchemaNarrowActivationDoctorWarnings,\n copyExtensionDirectoryWithoutSelfNesting,\n isErrnoCode,\n isRetriableExtensionInstallCopyError,\n listInstalledExtensions,\n requireTarget,\n resolveAction,\n resolveCommandDiscoveryPackageName,\n resolveGithubOption,\n resolveInstalledExtensionCandidate,\n resolveScope,\n resolveUpdateCheckResolution,\n withExtensionInstallLock,\n};\n", "/**\n * @module cli/commands/extension/managed-state\n *\n * Implements extension package-management support for Managed State.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { EXIT_CODE } from \"../../../core/shared/constants.js\";\nimport { PmCliError } from \"../../../core/shared/errors.js\";\nimport { nowIso } from \"../../../core/shared/time.js\";\nimport { normalizeExtensionNameForMatch, normalizeStringList } from \"./shared.js\";\nimport type { ExtensionScope } from \"../extension.js\";\n\nconst MANAGED_EXTENSION_STATE_FILENAME = \".managed-extensions.json\";\nconst MANAGED_EXTENSION_STATE_VERSION = 1;\n\n/**\n * Documents the managed extension source payload exchanged by command, SDK, and package integrations.\n */\nexport interface ManagedExtensionSource {\n kind: \"local\" | \"github\" | \"npm\" | \"builtin\";\n input: string;\n location: string;\n name?: string;\n package?: string;\n version?: string;\n repository?: string;\n owner?: string;\n repo?: string;\n ref?: string;\n subpath?: string;\n commit?: string;\n}\n\n/**\n * Documents the managed extension record payload exchanged by command, SDK, and package integrations.\n */\nexport interface ManagedExtensionRecord {\n name: string;\n directory: string;\n scope: ExtensionScope;\n manifest_version: string;\n manifest_entry: string;\n capabilities: string[];\n installed_at: string;\n updated_at: string;\n source: ManagedExtensionSource;\n last_update_check_at?: string;\n last_update_remote_commit?: string;\n update_available?: boolean | null;\n update_error?: string;\n}\n\n/**\n * Documents the managed extension state payload exchanged by command, SDK, and package integrations.\n */\nexport interface ManagedExtensionState {\n version: number;\n updated_at: string;\n entries: ManagedExtensionRecord[];\n}\n\n/**\n * Documents the managed extension state read result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ManagedExtensionStateReadResult {\n path: string;\n state: ManagedExtensionState;\n warnings: string[];\n}\n\n/**\n * Implements resolve managed extension state path for the public runtime surface of this module.\n */\nexport function resolveManagedExtensionStatePath(extensionsRoot: string): string {\n return path.join(extensionsRoot, MANAGED_EXTENSION_STATE_FILENAME);\n}\n\n/**\n * Implements create empty managed extension state for the public runtime surface of this module.\n */\nexport function createEmptyManagedExtensionState(): ManagedExtensionState {\n return {\n version: MANAGED_EXTENSION_STATE_VERSION,\n updated_at: nowIso(),\n entries: [],\n };\n}\n\n/**\n * Implements sort managed entries for the public runtime surface of this module.\n */\nexport function sortManagedEntries(entries: ManagedExtensionRecord[]): ManagedExtensionRecord[] {\n return [...entries].sort((left, right) => {\n const byScope = left.scope.localeCompare(right.scope);\n if (byScope !== 0) {\n return byScope;\n }\n const byName = left.name.localeCompare(right.name);\n if (byName !== 0) {\n return byName;\n }\n return left.directory.localeCompare(right.directory);\n });\n}\n\n/**\n * Implements managed extension sources equivalent for the public runtime surface of this module.\n */\nexport function managedExtensionSourcesEquivalent(left: ManagedExtensionSource, right: ManagedExtensionSource): boolean {\n if (left.kind !== right.kind || left.input !== right.input || left.location !== right.location) {\n return false;\n }\n if (left.kind === \"npm\" && right.kind === \"npm\") {\n return left.package === right.package && left.version === right.version;\n }\n if (left.kind === \"github\" && right.kind === \"github\") {\n return left.repository === right.repository && left.ref === right.ref && left.subpath === right.subpath && left.commit === right.commit;\n }\n if (left.kind === \"builtin\" && right.kind === \"builtin\") {\n return left.name === right.name;\n }\n return true;\n}\n\n/**\n * Narrow `value` to a string, or `undefined` for any other type — the\n * normalization applied to every optional managed-state string field so an\n * absent or malformed value is dropped rather than carried through as `unknown`.\n */\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Type guard asserting `entry` carries every always-present managed-record field\n * with the right primitive type: a non-empty `name`/`directory`, a known\n * {@link ExtensionScope}, string manifest metadata, a `string[]` capability\n * list, and string `installed_at`/`updated_at` timestamps. The optional columns\n * (`source` plus the update-check fields) are validated separately by the\n * caller, so this guard narrows only the required columns.\n */\nfunction hasRequiredManagedRecordFields(\n entry: Record<string, unknown>,\n): entry is Record<string, unknown> &\n Pick<\n ManagedExtensionRecord,\n \"name\" | \"directory\" | \"scope\" | \"manifest_version\" | \"manifest_entry\" | \"capabilities\" | \"installed_at\" | \"updated_at\"\n > {\n return (\n typeof entry.name === \"string\" &&\n entry.name.trim().length > 0 &&\n typeof entry.directory === \"string\" &&\n entry.directory.trim().length > 0 &&\n (entry.scope === \"project\" || entry.scope === \"global\") &&\n typeof entry.manifest_version === \"string\" &&\n typeof entry.manifest_entry === \"string\" &&\n Array.isArray(entry.capabilities) &&\n entry.capabilities.every((value): value is string => typeof value === \"string\") &&\n typeof entry.installed_at === \"string\" &&\n typeof entry.updated_at === \"string\"\n );\n}\n\n/**\n * Normalize one persisted managed-extension source object, returning `null` when\n * the discriminant (`kind`) or the required `input`/`location` strings are\n * missing or malformed so the caller can skip the owning record.\n */\nfunction normalizeManagedSource(raw: unknown): ManagedExtensionSource | null {\n if (typeof raw !== \"object\" || raw === null) {\n return null;\n }\n const source = raw as Record<string, unknown>;\n if (\n (source.kind !== \"local\" && source.kind !== \"github\" && source.kind !== \"npm\" && source.kind !== \"builtin\") ||\n typeof source.input !== \"string\" ||\n typeof source.location !== \"string\"\n ) {\n return null;\n }\n return {\n kind: source.kind,\n input: source.input,\n location: source.location,\n name: optionalString(source.name),\n package: optionalString(source.package),\n version: optionalString(source.version),\n repository: optionalString(source.repository),\n owner: optionalString(source.owner),\n repo: optionalString(source.repo),\n ref: optionalString(source.ref),\n subpath: optionalString(source.subpath),\n commit: optionalString(source.commit),\n };\n}\n\n/**\n * Normalize one persisted managed-extension record, returning `null` when any\n * required field or its `source` is missing or malformed so {@link\n * normalizeManagedState} can drop the entry without discarding the rest of the\n * file.\n */\nfunction normalizeManagedRecord(raw: unknown): ManagedExtensionRecord | null {\n if (typeof raw !== \"object\" || raw === null) {\n return null;\n }\n const entry = raw as Record<string, unknown>;\n if (!hasRequiredManagedRecordFields(entry)) {\n return null;\n }\n const source = normalizeManagedSource(entry.source);\n if (!source) {\n return null;\n }\n return {\n name: entry.name.trim(),\n directory: entry.directory.trim(),\n scope: entry.scope,\n manifest_version: entry.manifest_version,\n manifest_entry: entry.manifest_entry,\n capabilities: normalizeStringList(entry.capabilities),\n installed_at: entry.installed_at,\n updated_at: entry.updated_at,\n source,\n last_update_check_at: optionalString(entry.last_update_check_at),\n last_update_remote_commit: optionalString(entry.last_update_remote_commit),\n update_available:\n typeof entry.update_available === \"boolean\" || entry.update_available === null\n ? entry.update_available\n : undefined,\n update_error: optionalString(entry.update_error),\n };\n}\n\n/**\n * Implements normalize managed state for the public runtime surface of this module.\n */\nexport function normalizeManagedState(raw: unknown): ManagedExtensionState | null {\n if (typeof raw !== \"object\" || raw === null) {\n return null;\n }\n const candidate = raw as Record<string, unknown>;\n if (candidate.version !== MANAGED_EXTENSION_STATE_VERSION || !Array.isArray(candidate.entries)) {\n return null;\n }\n\n const entries: ManagedExtensionRecord[] = [];\n for (const rawEntry of candidate.entries) {\n const record = normalizeManagedRecord(rawEntry);\n if (record) {\n entries.push(record);\n }\n }\n return {\n version: MANAGED_EXTENSION_STATE_VERSION,\n updated_at: optionalString(candidate.updated_at) ?? nowIso(),\n entries: sortManagedEntries(entries),\n };\n}\n\n/**\n * Implements read managed extension state for the public runtime surface of this module.\n */\nexport async function readManagedExtensionState(extensionsRoot: string): Promise<ManagedExtensionStateReadResult> {\n const statePath = resolveManagedExtensionStatePath(extensionsRoot);\n const fallback = createEmptyManagedExtensionState();\n try {\n const raw = await fs.readFile(statePath, \"utf8\");\n const parsed = JSON.parse(raw) as unknown;\n const normalized = normalizeManagedState(parsed);\n if (!normalized) {\n throw new PmCliError(\n `Managed extension state file \"${statePath}\" has an invalid schema. Repair or remove it before mutating extension state.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n return {\n path: statePath,\n state: normalized,\n warnings: [],\n };\n } catch (error: unknown) {\n if (error instanceof PmCliError) {\n throw error;\n }\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\") {\n return {\n path: statePath,\n state: fallback,\n warnings: [],\n };\n }\n throw new PmCliError(\n `Managed extension state file \"${statePath}\" could not be read. Repair or remove it before mutating extension state.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n}\n\n/**\n * Implements write managed extension state for the public runtime surface of this module.\n */\nexport async function writeManagedExtensionState(extensionsRoot: string, state: ManagedExtensionState): Promise<void> {\n const statePath = resolveManagedExtensionStatePath(extensionsRoot);\n const normalized: ManagedExtensionState = {\n version: MANAGED_EXTENSION_STATE_VERSION,\n updated_at: nowIso(),\n entries: sortManagedEntries(state.entries),\n };\n await fs.mkdir(extensionsRoot, { recursive: true });\n await fs.writeFile(statePath, `${JSON.stringify(normalized, null, 2)}\\n`, \"utf8\");\n}\n\n\n/**\n * Implements upsert managed entry for the public runtime surface of this module.\n */\nexport function upsertManagedEntry(state: ManagedExtensionState, entry: ManagedExtensionRecord): ManagedExtensionState {\n const updatedEntries = state.entries.filter(\n (candidate) =>\n normalizeExtensionNameForMatch(candidate.name) !== normalizeExtensionNameForMatch(entry.name) &&\n normalizeExtensionNameForMatch(candidate.directory) !== normalizeExtensionNameForMatch(entry.directory),\n );\n updatedEntries.push(entry);\n return {\n ...state,\n updated_at: nowIso(),\n entries: sortManagedEntries(updatedEntries),\n };\n}\n", "/**\n * @module cli/commands/extension/install-sources\n *\n * Implements extension package-management support for Install Sources.\n */\nimport { execFile } from \"node:child_process\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { promisify } from \"node:util\";\nimport { collectPackageExtensionDirectories } from \"../../../core/packages/manifest.js\";\nimport { resolvePmPackageRootFromModule } from \"../../../core/packages/root.js\";\nimport { pathExists } from \"../../../core/fs/fs-utils.js\";\nimport { isPathWithinDirectory } from \"../../../core/fs/path-utils.js\";\nimport { EXIT_CODE } from \"../../../core/shared/constants.js\";\nimport { PmCliError, type PmCliErrorContext } from \"../../../core/shared/errors.js\";\nimport { listBundledPackageAliases } from \"./bundled-catalog.js\";\n\nconst execFileAsync = promisify(execFile);\nconst PM_CLI_PACKAGE_NAME = \"@unbrained/pm-cli\";\nlet bundledPackageAliasesCache: { key: string; aliases: string[] } | undefined;\n\ninterface LocalInstallSource {\n kind: \"local\";\n input: string;\n absolute_path: string;\n}\n\ninterface GithubInstallSource {\n kind: \"github\";\n input: string;\n owner: string;\n repo: string;\n repository: string;\n ref?: string;\n subpath?: string;\n}\n\ninterface NpmInstallSource {\n kind: \"npm\";\n input: string;\n spec: string;\n}\n\ntype InstallSource = LocalInstallSource | GithubInstallSource | NpmInstallSource;\n\ninterface ResolvedInstallSource {\n source: InstallSource;\n directory: string;\n resolved_subpath?: string;\n commit?: string;\n npm_package?: string;\n npm_version?: string;\n cleanup?: () => Promise<void>;\n}\n\nfunction parseGithubPathSpec(pathSpec: string, input: string, refOverride?: string): GithubInstallSource | null {\n const segments = pathSpec\n .split(\"/\")\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n if (segments.length < 2) {\n return null;\n }\n const owner = segments[0];\n const repo = segments[1].replace(/\\.git$/i, \"\");\n if (owner.length === 0 || repo.length === 0) {\n return null;\n }\n const tail = segments.slice(2);\n let ref: string | undefined;\n let subpath: string | undefined;\n if (tail[0] === \"tree\" && tail.length >= 2) {\n ref = tail[1];\n subpath = tail.slice(2).join(\"/\");\n } else if (tail.length > 0) {\n subpath = tail.join(\"/\");\n }\n if (typeof refOverride === \"string\" && refOverride.trim().length > 0) {\n ref = refOverride.trim();\n }\n return {\n kind: \"github\",\n input,\n owner,\n repo,\n repository: `https://github.com/${owner}/${repo}.git`,\n ref,\n subpath: subpath && subpath.length > 0 ? subpath : undefined,\n };\n}\n\nfunction parseNpmInstallSource(normalizedInput: string, forceGithub: boolean, refOverride: string | undefined): InstallSource {\n const spec = normalizedInput.slice(\"npm:\".length).trim();\n if (spec.length === 0) {\n throw new PmCliError('npm package source must include a package spec after \"npm:\".', EXIT_CODE.USAGE);\n }\n if (forceGithub) {\n throw new PmCliError('Options \"--gh/--github\" cannot be combined with npm: package sources.', EXIT_CODE.USAGE);\n }\n if (refOverride) {\n throw new PmCliError('Option \"--ref\" cannot be combined with npm: package sources.', EXIT_CODE.USAGE);\n }\n return {\n kind: \"npm\",\n input: normalizedInput,\n spec,\n };\n}\n\n/**\n * Implements parse extension install source for the public runtime surface of this module.\n */\nexport function parseExtensionInstallSource(input: string, options: { forceGithub?: boolean; ref?: string } = {}): InstallSource {\n const normalizedInput = input.trim();\n if (normalizedInput.length === 0) {\n throw new PmCliError(\"Extension source is required for --install.\", EXIT_CODE.USAGE);\n }\n const refOverride = typeof options.ref === \"string\" && options.ref.trim().length > 0 ? options.ref.trim() : undefined;\n\n if (normalizedInput.startsWith(\"npm:\")) {\n return parseNpmInstallSource(normalizedInput, options.forceGithub === true, refOverride);\n }\n\n const maybeGithubByUrl = (() => {\n try {\n const parsed = new URL(normalizedInput);\n if (parsed.hostname !== \"github.com\") {\n return null;\n }\n const pathSpec = parsed.pathname.replace(/^\\/+/, \"\");\n return parseGithubPathSpec(pathSpec, normalizedInput, refOverride);\n } catch {\n return null;\n }\n })();\n if (maybeGithubByUrl) {\n return maybeGithubByUrl;\n }\n\n const strippedDomainInput = normalizedInput.startsWith(\"github.com/\") ? normalizedInput.slice(\"github.com/\".length) : null;\n if (strippedDomainInput) {\n const parsed = parseGithubPathSpec(strippedDomainInput, normalizedInput, refOverride);\n if (!parsed) {\n throw new PmCliError(`Invalid GitHub source \"${normalizedInput}\".`, EXIT_CODE.USAGE);\n }\n return parsed;\n }\n\n if (options.forceGithub) {\n const parsed = parseGithubPathSpec(normalizedInput, normalizedInput, refOverride);\n if (!parsed) {\n throw new PmCliError(`Invalid GitHub shorthand \"${normalizedInput}\".`, EXIT_CODE.USAGE);\n }\n return parsed;\n }\n\n if (/^https?:\\/\\//i.test(normalizedInput)) {\n throw new PmCliError(\n `Unsupported extension source URL \"${normalizedInput}\". Supported remote source host: github.com.`,\n EXIT_CODE.USAGE,\n );\n }\n\n return {\n kind: \"local\",\n input: normalizedInput,\n absolute_path: path.resolve(process.cwd(), normalizedInput),\n };\n}\n\n/**\n * Implements run git command for the public runtime surface of this module.\n */\nexport async function runGitCommand(\n args: string[],\n execRunner: typeof execFileAsync = execFileAsync,\n): Promise<string> {\n try {\n const result = await execRunner(\"git\", args, { encoding: \"utf8\" });\n return (result.stdout ?? \"\").trim();\n } catch (error: unknown) {\n /* c8 ignore start -- stderr-vs-error-message precedence is validated in integration command-runner paths */\n const stderr = typeof error === \"object\" && error !== null && \"stderr\" in error ? String((error as { stderr: unknown }).stderr) : \"\";\n const message = stderr.trim().length > 0 ? stderr.trim() : error instanceof Error ? error.message : String(error);\n /* c8 ignore stop */\n throw new PmCliError(`Git command failed: git ${args.join(\" \")}\\n${message}`, EXIT_CODE.GENERIC_FAILURE);\n }\n}\n\n/**\n * Implements resolve npm command name for the public runtime surface of this module.\n */\nexport function resolveNpmCommandName(platform: NodeJS.Platform = process.platform): \"npm\" | \"npm.cmd\" {\n return platform === \"win32\" ? \"npm.cmd\" : \"npm\";\n}\n\n/**\n * Implements should run npm command in shell for the public runtime surface of this module.\n */\nexport function shouldRunNpmCommandInShell(platform: NodeJS.Platform = process.platform): boolean {\n return platform === \"win32\";\n}\n\nasync function runNpmCommand(\n args: string[],\n cwd?: string,\n execRunner: typeof execFileAsync = execFileAsync,\n): Promise<string> {\n const npmCommand = resolveNpmCommandName();\n try {\n const result = await execRunner(npmCommand, args, { cwd, encoding: \"utf8\", shell: shouldRunNpmCommandInShell() });\n return (result.stdout ?? \"\").trim();\n } catch (error: unknown) {\n const stderr = typeof error === \"object\" && error !== null && \"stderr\" in error ? String((error as { stderr: unknown }).stderr) : \"\";\n const message = stderr.trim().length > 0 ? stderr.trim() : error instanceof Error ? error.message : String(error);\n throw new PmCliError(`npm command failed: ${npmCommand} ${args.join(\" \")}\\n${message}`, EXIT_CODE.GENERIC_FAILURE);\n }\n}\n\nfunction npmPackageNameFromSpec(spec: string): string {\n const trimmed = spec.trim();\n const withoutAlias = trimmed.includes(\"@file:\") ? trimmed.slice(0, trimmed.lastIndexOf(\"@file:\")) : trimmed;\n if (withoutAlias.startsWith(\"@\")) {\n const scoped = withoutAlias.match(/^(@[^/@\\s]+\\/[^/@\\s]+)/);\n return scoped?.[1] ?? withoutAlias;\n }\n const unscoped = withoutAlias.match(/^([^/@\\s]+)/);\n return unscoped?.[1] ?? withoutAlias;\n}\n\n/**\n * Implements check whether npm not found error for the public runtime surface of this module.\n */\nexport function isNpmNotFoundError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n const normalized = message.toLowerCase();\n return (\n normalized.includes(\"npm err! code e404\") ||\n normalized.includes(\"404 not found\") ||\n normalized.includes(\"is not in this registry\")\n );\n}\n\n/**\n * Implements check whether npm pack not found error for the public runtime surface of this module.\n */\nexport function isNpmPackNotFoundError(error: unknown): boolean {\n const message = error instanceof Error ? error.message : String(error);\n const normalized = message.toLowerCase();\n return isNpmNotFoundError(error) || normalized.includes(\"not found\");\n}\n\nfunction isFirstPartyPmPackageName(packageName: string): boolean {\n const normalized = packageName.trim().toLowerCase();\n return normalized.startsWith(\"@unbrained/pm-\") || normalized.startsWith(\"pm-\");\n}\n\n/**\n * Implements build npm not found recovery for the public runtime surface of this module.\n */\nexport function buildNpmNotFoundRecovery(spec: string): {\n message: string;\n context: PmCliErrorContext;\n} {\n const packageName = npmPackageNameFromSpec(spec);\n const isFirstPartyPackage = isFirstPartyPmPackageName(packageName);\n const repoName = packageName.replace(/^.*\\//, \"\");\n const githubSource = isFirstPartyPackage ? `github.com/unbraind/${repoName}` : undefined;\n const nextBestCommand = githubSource ? `pm install --project ${githubSource}` : undefined;\n return {\n message: isFirstPartyPackage\n ? `npm package \"${spec}\" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`\n : `npm package \"${spec}\" was not found in the registry.`,\n context: {\n code: \"npm_package_not_found\",\n required: \"Use an install source that exists, or publish the npm package before installing it with npm:<name>.\",\n why: \"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.\",\n examples: nextBestCommand ? [nextBestCommand, `pm package catalog --project --json`] : [`npm view ${packageName}`, `pm package catalog --project --json`],\n nextSteps: nextBestCommand\n ? [\n `Try ${nextBestCommand} if the repository exists.`,\n \"Use pm package catalog --project --json to inspect bundled package aliases before installing.\",\n ]\n : [\n `Verify ${packageName} exists in the npm registry and that you have access to it.`,\n \"Use pm package catalog --project --json to inspect bundled package aliases before installing.\",\n ],\n recovery: {\n attempted_command: `pm install --project npm:${spec}`,\n normalized_args: [\"install\", \"--project\", `npm:${spec}`],\n ...(githubSource && nextBestCommand\n ? {\n fallback_candidates: [\n {\n source: githubSource,\n command: nextBestCommand,\n reason: \"canonical first-party GitHub repository fallback for unpublished pm packages\",\n },\n ],\n next_best_command: nextBestCommand,\n }\n : {}),\n },\n },\n };\n}\n\n/**\n * Implements wrap npm pack resolution error for the public runtime surface of this module.\n */\nexport function wrapNpmPackResolutionError(spec: string, error: unknown): PmCliError | null {\n if (!isNpmPackNotFoundError(error)) {\n return null;\n }\n const recovery = buildNpmNotFoundRecovery(spec);\n return new PmCliError(recovery.message, EXIT_CODE.NOT_FOUND, recovery.context);\n}\n\nasync function resolveLocalNpmPackagePath(spec: string): Promise<string | null> {\n if (path.isAbsolute(spec) || spec.startsWith(\".\") || spec.startsWith(\"..\")) {\n const absolutePath = path.resolve(process.cwd(), spec);\n return (await pathExists(absolutePath)) ? absolutePath : null;\n }\n\n try {\n const parsed = new URL(spec);\n if (parsed.protocol === \"file:\") {\n const absolutePath = fileURLToPath(parsed);\n return (await pathExists(absolutePath)) ? absolutePath : null;\n }\n } catch {\n // Registry package specs are not URLs.\n }\n\n if (!/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n const absolutePath = path.resolve(process.cwd(), spec);\n if (await pathExists(absolutePath)) {\n return absolutePath;\n }\n }\n\n return null;\n}\n\nasync function resolveNpmPackSpec(spec: string): Promise<string> {\n const localPath = await resolveLocalNpmPackagePath(spec);\n if (localPath) {\n // Hand npm pack a NATIVE filesystem path, never a percent-encoded file URL:\n // npm opens the spec literally, so spaces (`%20`) or a Windows 8.3 `~` short\n // name (`%7E`) escaped by pathToFileURL make pack fail ENOENT on every\n // platform (GH-363). resolveLocalNpmPackagePath already decoded the path.\n return localPath;\n }\n\n const localFileAlias = normalizeNpmLocalFileAliasSpec(spec);\n if (localFileAlias !== spec) {\n return localFileAlias;\n }\n\n if (/^[a-z][a-z0-9+.-]*:/i.test(spec)) {\n return spec;\n }\n\n return spec;\n}\n\n/**\n * Implements normalize npm local file alias spec for the public runtime surface of this module.\n */\nexport function normalizeNpmLocalFileAliasSpec(spec: string, cwd: string = process.cwd()): string {\n const marker = \"@file:\";\n const markerIndex = spec.lastIndexOf(marker);\n if (markerIndex <= 0) {\n return spec;\n }\n const packageName = spec.slice(0, markerIndex);\n const target = spec.slice(markerIndex + marker.length);\n if (packageName.trim().length === 0 || target.trim().length === 0) {\n return spec;\n }\n // `file://host/share` (exactly two leading slashes) is a UNC / network spec,\n // not a local path — leave it for npm to resolve.\n if (target.startsWith(\"//\") && !target.startsWith(\"///\")) {\n return spec;\n }\n // A bare relative target resolves against cwd.\n if (!target.startsWith(\"/\")) {\n return `${packageName}@${path.resolve(cwd, target)}`;\n }\n // Resolve an absolute `file:` URL target to a NATIVE, percent-DECODED path\n // (never an encoded file URL): npm opens the alias target literally, so an\n // escaped path — spaces (`%20`) or a Windows 8.3 `~` short name escaped to\n // `%7E` — fails ENOENT on every platform (GH-363). Decode via URL +\n // decodeURIComponent rather than fileURLToPath, which throws\n // ERR_INVALID_FILE_URL_PATH for a driveless absolute path supplied on Windows;\n // strip the leading slash before a Windows drive letter (`/C:/x` -> `C:/x`).\n let decodedPath: string;\n try {\n decodedPath = decodeURIComponent(new URL(`file:${target}`).pathname);\n } catch {\n // Malformed percent-encoding (e.g. `%ZZ`) makes decodeURIComponent throw a\n // URIError; leave the spec untouched so npm surfaces a clear error instead\n // of crashing the CLI on an uncaught exception.\n return spec;\n }\n const nativePath = /^\\/[A-Za-z]:/.test(decodedPath) ? decodedPath.slice(1) : decodedPath;\n return `${packageName}@${nativePath}`;\n}\n\nfunction parsePackedNpmPackage(stdout: string, packDirectory: string): { tarball: string; package?: string; version?: string } {\n try {\n const parsed = JSON.parse(stdout) as Array<{ filename?: unknown; name?: unknown; version?: unknown }>;\n const first = Array.isArray(parsed) ? parsed[0] : undefined;\n if (first && typeof first.filename === \"string\" && first.filename.trim().length > 0) {\n return {\n tarball: path.resolve(packDirectory, first.filename),\n package: typeof first.name === \"string\" ? first.name : undefined,\n version: typeof first.version === \"string\" ? first.version : undefined,\n };\n }\n } catch {\n // Fall back to the last stdout line for older npm output.\n }\n const lastLine = stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .at(-1);\n if (!lastLine) {\n throw new PmCliError(\"npm pack did not report a tarball filename.\", EXIT_CODE.GENERIC_FAILURE);\n }\n return {\n tarball: path.resolve(packDirectory, lastLine),\n };\n}\n\nasync function resolveNpmSourceDirectory(source: NpmInstallSource): Promise<{\n directory: string;\n package?: string;\n version?: string;\n cleanup: () => Promise<void>;\n}> {\n return resolveNpmSourceDirectoryWithRunner(source, runNpmCommand);\n}\n\nasync function resolveNpmSourceDirectoryWithRunner(\n source: NpmInstallSource,\n npmRunner: typeof runNpmCommand,\n): Promise<{\n directory: string;\n package?: string;\n version?: string;\n cleanup: () => Promise<void>;\n}> {\n const localPackageRoot = await resolveLocalNpmPackagePath(source.spec);\n if (localPackageRoot) {\n const packageJsonPath = path.join(localPackageRoot, \"package.json\");\n const packageJson = (await pathExists(packageJsonPath))\n ? JSON.parse(await fs.readFile(packageJsonPath, \"utf8\")) as { name?: unknown; version?: unknown }\n : {};\n return {\n directory: await resolvePackageExtensionDirectory(localPackageRoot, source.input),\n package: typeof packageJson.name === \"string\" ? packageJson.name : undefined,\n version: typeof packageJson.version === \"string\" ? packageJson.version : undefined,\n cleanup: async () => {},\n };\n }\n\n const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), \"pm-npm-package-source-\"));\n const packDirectory = path.join(tempRoot, \"pack\");\n const extractDirectory = path.join(tempRoot, \"extract\");\n await fs.mkdir(packDirectory, { recursive: true });\n await fs.mkdir(extractDirectory, { recursive: true });\n\n try {\n const packSpec = await resolveNpmPackSpec(source.spec);\n const packStdout = await npmRunner([\"pack\", packSpec, \"--json\", \"--pack-destination\", packDirectory]);\n const packed = parsePackedNpmPackage(packStdout, packDirectory);\n await execFileAsync(\"tar\", [\"-xzf\", packed.tarball, \"-C\", extractDirectory], { encoding: \"utf8\" });\n const packageRoot = path.join(extractDirectory, \"package\");\n await installNpmPackageRuntimeDependencies(packageRoot);\n const directory = await resolvePackageExtensionDirectory(packageRoot, source.input);\n return {\n directory,\n package: packed.package,\n version: packed.version,\n cleanup: async () => {\n await fs.rm(tempRoot, { recursive: true, force: true });\n },\n };\n } catch (error: unknown) {\n await fs.rm(tempRoot, { recursive: true, force: true });\n const wrappedError = wrapNpmPackResolutionError(source.spec, error);\n if (wrappedError) {\n throw wrappedError;\n }\n throw error;\n }\n}\n\nasync function installNpmPackageRuntimeDependencies(packageRoot: string): Promise<void> {\n const packageJsonPath = path.join(packageRoot, \"package.json\");\n if (!(await pathExists(packageJsonPath))) {\n return;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fs.readFile(packageJsonPath, \"utf8\")) as unknown;\n } catch {\n return;\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return;\n }\n\n const manifest = parsed as { dependencies?: unknown; optionalDependencies?: unknown; peerDependencies?: unknown };\n const dependencySpecs = runtimeDependencyInstallSpecs(manifest);\n const shouldLinkHostedPmCli = hasHostedPmCliDependency(manifest);\n if (dependencySpecs.length === 0 && !shouldLinkHostedPmCli) {\n return;\n }\n\n const runtimeOnlyManifest = { ...(parsed as Record<string, unknown>) };\n delete runtimeOnlyManifest.devDependencies;\n const installManifest = { ...runtimeOnlyManifest };\n removeHostedPmCliDependency(installManifest);\n await fs.writeFile(packageJsonPath, `${JSON.stringify(installManifest, null, 2)}\\n`, \"utf8\");\n try {\n await Promise.all([\n fs.rm(path.join(packageRoot, \"package-lock.json\"), { force: true }),\n fs.rm(path.join(packageRoot, \"npm-shrinkwrap.json\"), { force: true }),\n ]);\n\n if (dependencySpecs.length > 0) {\n await runNpmCommand(\n [\n \"install\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--fund=false\",\n \"--package-lock=false\",\n \"--no-save\",\n \"--omit=peer\",\n ...dependencySpecs,\n ],\n packageRoot,\n );\n }\n\n if (shouldLinkHostedPmCli) {\n await linkHostedPmCliDependency(packageRoot);\n }\n } finally {\n await fs.writeFile(packageJsonPath, `${JSON.stringify(runtimeOnlyManifest, null, 2)}\\n`, \"utf8\");\n }\n}\n\nfunction hasHostedPmCliDependency(manifest: {\n dependencies?: unknown;\n optionalDependencies?: unknown;\n peerDependencies?: unknown;\n}): boolean {\n for (const dependencyMap of [manifest.dependencies, manifest.optionalDependencies, manifest.peerDependencies]) {\n if (typeof dependencyMap === \"object\" && dependencyMap !== null && PM_CLI_PACKAGE_NAME in dependencyMap) {\n return true;\n }\n }\n return false;\n}\n\nfunction removeHostedPmCliDependency(manifest: Record<string, unknown>): void {\n for (const field of [\"dependencies\", \"optionalDependencies\", \"peerDependencies\"] as const) {\n const dependencyMap = manifest[field];\n if (typeof dependencyMap !== \"object\" || dependencyMap === null) {\n continue;\n }\n const nextMap = { ...(dependencyMap as Record<string, unknown>) };\n delete nextMap[PM_CLI_PACKAGE_NAME];\n if (Object.keys(nextMap).length === 0) {\n delete manifest[field];\n } else {\n manifest[field] = nextMap;\n }\n }\n}\n\nasync function linkHostedPmCliDependency(packageRoot: string): Promise<void> {\n const hostPackageRoot = resolvePmPackageRootFromModule(import.meta.url, [\"../../../..\"]);\n const [scope, packageName] = PM_CLI_PACKAGE_NAME.split(\"/\");\n const scopedDirectory = path.join(packageRoot, \"node_modules\", scope);\n const linkPath = path.join(scopedDirectory, packageName);\n await fs.mkdir(scopedDirectory, { recursive: true });\n await fs.rm(linkPath, { recursive: true, force: true });\n await fs.symlink(hostPackageRoot, linkPath, resolveDirectorySymlinkType(process.platform));\n}\n\nfunction resolveDirectorySymlinkType(platform: NodeJS.Platform): \"dir\" | \"junction\" {\n return platform === \"win32\" ? \"junction\" : \"dir\";\n}\n\nfunction runtimeDependencyInstallSpecs(manifest: {\n dependencies?: unknown;\n optionalDependencies?: unknown;\n peerDependencies?: unknown;\n}): string[] {\n const specs = new Map<string, string>();\n for (const dependencyMap of [manifest.dependencies, manifest.optionalDependencies, manifest.peerDependencies]) {\n if (typeof dependencyMap !== \"object\" || dependencyMap === null) {\n continue;\n }\n for (const [name, version] of Object.entries(dependencyMap)) {\n if (\n name === PM_CLI_PACKAGE_NAME ||\n typeof version !== \"string\" ||\n version.trim().length === 0 ||\n specs.has(name)\n ) {\n continue;\n }\n specs.set(name, `${name}@${version.trim()}`);\n }\n }\n return [...specs.values()];\n}\n\nasync function resolvePackageExtensionDirectory(packageRoot: string, sourceLabel: string): Promise<string> {\n const discovered = await collectPackageExtensionDirectories(packageRoot);\n if (discovered.length === 1) {\n return discovered[0];\n }\n if (discovered.length > 1) {\n const choices = discovered\n .map((entry) => path.relative(packageRoot, entry).replaceAll(path.sep, \"/\"))\n .sort((left, right) => left.localeCompare(right));\n throw new PmCliError(\n `Package source \"${sourceLabel}\" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${choices.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n }\n throw new PmCliError(\n `Unable to locate a pm extension manifest in package source \"${sourceLabel}\". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,\n EXIT_CODE.USAGE,\n );\n}\n\nasync function resolveGithubSourceDirectory(cloneDirectory: string, source: GithubInstallSource): Promise<{ directory: string; resolved_subpath?: string }> {\n const candidatePaths: string[] = [];\n /* c8 ignore start -- subpath candidate expansion permutations are covered by source-resolution integration suites */\n if (source.subpath) {\n candidatePaths.push(source.subpath);\n candidatePaths.push(path.posix.join(\".agents/pm/extensions\", source.subpath));\n candidatePaths.push(path.posix.join(\".custom/pm-extensions\", source.subpath));\n candidatePaths.push(path.posix.join(\".custom/pm-extension\", source.subpath));\n }\n /* c8 ignore stop */\n\n for (const candidate of candidatePaths) {\n const absolute = path.resolve(cloneDirectory, candidate);\n if (!isPathWithinDirectory(cloneDirectory, absolute)) {\n // source.subpath is user-controlled; never resolve a manifest outside the\n // cloned repository (path-traversal guard).\n continue;\n }\n if (await pathExists(path.join(absolute, \"manifest.json\"))) {\n return { directory: absolute, resolved_subpath: candidate };\n }\n }\n\n if (await pathExists(path.join(cloneDirectory, \"manifest.json\"))) {\n return { directory: cloneDirectory, resolved_subpath: \".\" };\n }\n\n const discoveredDirectory = await resolvePackageExtensionDirectory(cloneDirectory, source.input);\n return {\n directory: discoveredDirectory,\n resolved_subpath: path.relative(cloneDirectory, discoveredDirectory).replaceAll(path.sep, \"/\"),\n };\n}\n\n/**\n * Bare package-ish names (no path separators, or a single-scope npm name) that\n * miss local resolution are almost always intended as npm or bundled installs,\n * so the not-found error must route agents to those sources instead of dead-ending.\n */\nfunction looksLikeBarePackageName(input: string): boolean {\n const trimmed = input.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\".\") || trimmed.startsWith(\"~\")) {\n return false;\n }\n if (trimmed.startsWith(\"@\")) {\n return trimmed.split(\"/\").length === 2;\n }\n return !trimmed.includes(\"/\") && !trimmed.includes(\"\\\\\");\n}\n\nasync function buildLocalSourceNotFoundError(source: LocalInstallSource): Promise<PmCliError> {\n const baseMessage = `Local extension source does not exist: \"${source.absolute_path}\".`;\n const input = source.input.trim();\n if (!looksLikeBarePackageName(input)) {\n return new PmCliError(baseMessage, EXIT_CODE.NOT_FOUND);\n }\n let bundledAliases: string[] = [];\n try {\n const envPackageRoot = process.env.PM_CLI_PACKAGE_ROOT;\n const cacheKey = typeof envPackageRoot === \"string\" && envPackageRoot.trim().length > 0\n ? path.resolve(envPackageRoot.trim())\n : \"\";\n if (bundledPackageAliasesCache?.key !== cacheKey) {\n bundledPackageAliasesCache = {\n key: cacheKey,\n aliases: await listBundledPackageAliases(),\n };\n }\n bundledAliases = bundledPackageAliasesCache.aliases;\n } catch {\n // Alias discovery is best-effort; the npm: hint alone still unblocks agents.\n }\n const nextSteps = [\n `Retry with pm install npm:${input} if the package is published to npm.`,\n `Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${bundledAliases.join(\", \")}`,\n ];\n return new PmCliError(\n `${baseMessage} \"${input}\" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as \"npm:${input}\".`,\n EXIT_CODE.NOT_FOUND,\n {\n code: \"local_source_not_found_bare_name\",\n required: `Use \"npm:${input}\" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,\n why: \"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.\",\n examples: [\n `pm install npm:${input}`,\n \"pm package catalog --project --json\",\n ],\n nextSteps,\n recovery: {\n attempted_command: `pm install ${input}`,\n normalized_args: [\"install\", input],\n next_best_command: `pm install npm:${input}`,\n },\n },\n );\n}\n\n/**\n * Implements resolve install source for the public runtime surface of this module.\n */\nexport async function resolveInstallSource(source: InstallSource): Promise<ResolvedInstallSource> {\n if (source.kind === \"local\") {\n let localStats;\n try {\n localStats = await fs.stat(source.absolute_path);\n } catch {\n throw await buildLocalSourceNotFoundError(source);\n }\n if (!localStats.isDirectory()) {\n throw new PmCliError(`Local extension source must be a directory: \"${source.absolute_path}\".`, EXIT_CODE.USAGE);\n }\n const directory = await resolvePackageExtensionDirectory(source.absolute_path, source.input);\n return {\n source,\n directory,\n };\n }\n\n if (source.kind === \"npm\") {\n const resolved = await resolveNpmSourceDirectory(source);\n return {\n source,\n directory: resolved.directory,\n cleanup: resolved.cleanup,\n resolved_subpath: path.relative(path.dirname(resolved.directory), resolved.directory).replaceAll(path.sep, \"/\"),\n npm_package: resolved.package,\n npm_version: resolved.version,\n };\n }\n\n const cloneDirectory = await fs.mkdtemp(path.join(os.tmpdir(), \"pm-extension-source-\"));\n const cloneArgs = [\"clone\", \"--depth\", \"1\"];\n if (source.ref) {\n cloneArgs.push(\"--branch\", source.ref);\n }\n cloneArgs.push(source.repository, cloneDirectory);\n\n try {\n await runGitCommand(cloneArgs);\n const commit = await runGitCommand([\"-C\", cloneDirectory, \"rev-parse\", \"HEAD\"]);\n const resolved = await resolveGithubSourceDirectory(cloneDirectory, source);\n return {\n source,\n directory: resolved.directory,\n resolved_subpath: resolved.resolved_subpath,\n commit,\n cleanup: async () => {\n await fs.rm(cloneDirectory, { recursive: true, force: true });\n },\n };\n } catch (error: unknown) {\n await fs.rm(cloneDirectory, { recursive: true, force: true });\n throw error;\n }\n}\n\n/**\n * Implements are directories equivalent for the public runtime surface of this module.\n */\nexport async function areDirectoriesEquivalent(left: string, right: string): Promise<boolean> {\n if (!(await pathExists(left)) || !(await pathExists(right))) {\n return false;\n }\n const [leftRealPath, rightRealPath] = await Promise.all([fs.realpath(left), fs.realpath(right)]);\n return leftRealPath === rightRealPath;\n}\n\nexport const _testOnlyInstallSources = {\n installNpmPackageRuntimeDependencies,\n npmPackageNameFromSpec,\n parsePackedNpmPackage,\n resolveNpmSourceDirectoryWithRunner,\n resolveNpmSourceDirectory,\n resolveNpmPackSpec,\n resolvePackageExtensionDirectory,\n runtimeDependencyInstallSpecs,\n hasHostedPmCliDependency,\n removeHostedPmCliDependency,\n linkHostedPmCliDependency,\n resolveDirectorySymlinkType,\n runNpmCommand,\n};\n", "/**\n * @module cli/commands/extension/bundled-catalog\n *\n * Implements extension package-management support for Bundled Catalog.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectPackageExtensionDirectories, PM_PACKAGE_RESOURCE_KINDS, readPmPackageManifest } from \"../../../core/packages/manifest.js\";\nimport { resolvePmPackageRootFromModule } from \"../../../core/packages/root.js\";\nimport { pathExists } from \"../../../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../../core/shared/errors.js\";\nimport { splitCommaList } from \"../../../core/shared/split-comma-list.js\";\nimport { resolveExtensionRoots } from \"../../../core/extensions/loader.js\";\nimport { resolvePmRoot } from \"../../../core/store/paths.js\";\nimport { validateExtensionDirectory } from \"./shared.js\";\nimport { readManagedExtensionState } from \"./managed-state.js\";\nimport type { ExtensionCommandOptions, ExtensionScope } from \"../extension.js\";\n\nconst PM_PACKAGE_ROOT_ENV = \"PM_CLI_PACKAGE_ROOT\";\nconst LEGACY_BUNDLED_PACKAGE_ALIASES: Record<string, { package_directory: string; legacy_extension_directory: string }> = {\n beads: {\n package_directory: \"pm-beads\",\n legacy_extension_directory: \"beads\",\n },\n todos: {\n package_directory: \"pm-todos\",\n legacy_extension_directory: \"todos\",\n },\n};\nconst BUNDLED_PACKAGE_INSTALL_ALL_TARGETS = new Set([\"*\", \"all\"]);\n\ninterface BundledPackageEntry {\n alias: string;\n package_directory: string;\n package_root: string;\n package_name: string | null;\n}\n\nfunction resolvePackageRootCandidates(): string[] {\n const candidates: string[] = [];\n const envRoot = process.env[PM_PACKAGE_ROOT_ENV];\n /* c8 ignore start -- env-root override branch is exercised by package-root integration tests */\n if (typeof envRoot === \"string\" && envRoot.trim().length > 0) {\n candidates.push(path.resolve(envRoot.trim()));\n }\n /* c8 ignore stop */\n candidates.push(resolvePmPackageRootFromModule(import.meta.url, [\"../../../..\"]));\n return [...new Set(candidates)];\n}\n\n/**\n * Implements resolve bundled extension alias source for the public runtime surface of this module.\n */\nexport async function resolveBundledExtensionAliasSource(input: string): Promise<string | null> {\n const normalized = input.trim().toLowerCase();\n const packageRoot = await resolveBundledPackageRoot(normalized);\n if (packageRoot) {\n return packageRoot;\n }\n\n const alias = LEGACY_BUNDLED_PACKAGE_ALIASES[normalized];\n /* c8 ignore start -- known aliases resolve through package manifests in normal runtime */\n if (!alias) {\n return null;\n }\n /* c8 ignore stop */\n /* c8 ignore start -- exercised only when legacy extension paths exist without package manifests */\n for (const packageRoot of resolvePackageRootCandidates()) {\n const legacyExtensionPath = path.join(packageRoot, \".agents\", \"pm\", \"extensions\", alias.legacy_extension_directory);\n if (await pathExists(path.join(legacyExtensionPath, \"manifest.json\"))) {\n return legacyExtensionPath;\n }\n }\n return null;\n /* c8 ignore stop */\n}\n\n/**\n * Implements check whether bundled package install all target for the public runtime surface of this module.\n */\nexport function isBundledPackageInstallAllTarget(input: string): boolean {\n return BUNDLED_PACKAGE_INSTALL_ALL_TARGETS.has(input.trim().toLowerCase());\n}\n\nfunction derivePackageAlias(packageDirectory: string): string {\n return packageDirectory.replace(/^pm-/i, \"\").trim().toLowerCase();\n}\n\nasync function collectManifestPackageEntries(\n packagesRoot: string,\n entriesByAlias: Map<string, BundledPackageEntry>,\n): Promise<void> {\n const entries = await fs.readdir(packagesRoot, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"pm-\")) {\n continue;\n }\n const candidateRoot = path.join(packagesRoot, entry.name);\n if (!(await pathExists(path.join(candidateRoot, \"package.json\")))) {\n continue;\n }\n const manifest = await readPmPackageManifest(candidateRoot);\n const aliases = manifest.aliases && manifest.aliases.length > 0\n ? manifest.aliases\n : [derivePackageAlias(entry.name)];\n for (const alias of aliases) {\n const normalizedAlias = alias.trim().toLowerCase();\n if (normalizedAlias.length === 0 || entriesByAlias.has(normalizedAlias)) {\n continue;\n }\n entriesByAlias.set(normalizedAlias, {\n alias: normalizedAlias,\n package_directory: entry.name,\n package_root: candidateRoot,\n package_name: manifest.package_name ?? null,\n });\n }\n }\n}\n\nasync function collectBundledPackageEntries(): Promise<BundledPackageEntry[]> {\n const entriesByAlias = new Map<string, BundledPackageEntry>();\n for (const packageRoot of resolvePackageRootCandidates()) {\n const packagesRoot = path.join(packageRoot, \"packages\");\n if (!(await pathExists(packagesRoot))) {\n continue;\n }\n await collectManifestPackageEntries(packagesRoot, entriesByAlias);\n }\n\n for (const [alias, legacy] of Object.entries(LEGACY_BUNDLED_PACKAGE_ALIASES)) {\n /* c8 ignore start -- canonical aliases are present in bundled package manifests */\n if (entriesByAlias.has(alias)) {\n continue;\n }\n /* c8 ignore stop */\n /* c8 ignore start -- compatibility fallback when only legacy package layout exists */\n for (const packageRoot of resolvePackageRootCandidates()) {\n const packagePath = path.join(packageRoot, \"packages\", legacy.package_directory);\n if (await pathExists(path.join(packagePath, \"package.json\"))) {\n entriesByAlias.set(alias, {\n alias,\n package_directory: legacy.package_directory,\n package_root: packagePath,\n package_name: null,\n });\n break;\n }\n }\n /* c8 ignore stop */\n }\n\n return [...entriesByAlias.values()].sort((left, right) => left.alias.localeCompare(right.alias));\n}\n\n/**\n * Implements list bundled package aliases for the public runtime surface of this module.\n */\nexport async function listBundledPackageAliases(): Promise<string[]> {\n return (await collectBundledPackageEntries()).map((entry) => entry.alias);\n}\n\n/**\n * Implements resolve bundled package root for the public runtime surface of this module.\n * Accepts every spelling agents naturally reach for: the catalog alias\n * (\"kanban\"), the package directory (\"pm-kanban\"), and the published npm name\n * (\"@unbrained/pm-kanban\").\n */\nexport async function resolveBundledPackageRoot(alias: string): Promise<string | null> {\n const normalized = alias.trim().toLowerCase();\n const entry = (await collectBundledPackageEntries()).find(\n (candidate) =>\n candidate.alias === normalized ||\n candidate.package_directory.toLowerCase() === normalized ||\n candidate.package_name?.toLowerCase() === normalized,\n );\n return entry?.package_root ?? null;\n}\n\n/**\n * Resolve the published npm package name for a bundled alias so install flows\n * can persist it as managed-source provenance (`source.package`). Returns null\n * when the alias is unknown or the bundled package manifest lacks a name.\n */\nexport async function resolveBundledPackageNpmName(alias: string): Promise<string | null> {\n const packageRoot = await resolveBundledPackageRoot(alias);\n if (!packageRoot) {\n return null;\n }\n const manifest = await readPmPackageManifest(packageRoot);\n return manifest.package_name ?? null;\n}\n\n/**\n * Implements resolve bundled alias manifest name for the public runtime surface of this module.\n */\nexport async function resolveBundledAliasManifestName(input: string): Promise<string | null> {\n const bundledAliasSource = await resolveBundledExtensionAliasSource(input);\n if (!bundledAliasSource) {\n return null;\n }\n try {\n const extensionDirectories = await collectPackageExtensionDirectories(bundledAliasSource);\n if (extensionDirectories.length !== 1) {\n return null;\n }\n const validated = await validateExtensionDirectory(extensionDirectories[0]);\n return validated.manifest.name;\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve the catalog link block for a bundled package, preferring the explicit\n * `catalog.links.*` manifest fields and falling back to the package's\n * repository/bugs/homepage/npm metadata. The npm link is synthesized from the\n * package name unless the package is private or unnamed.\n */\nfunction buildBundledCatalogLinks(manifest: Awaited<ReturnType<typeof readPmPackageManifest>>): {\n docs: string | undefined;\n npm: string | undefined;\n repository: string | undefined;\n report: string | undefined;\n} {\n return {\n docs: manifest.catalog?.links?.docs ?? manifest.package_homepage,\n npm:\n manifest.catalog?.links?.npm ??\n (manifest.package_name && manifest.package_private !== true\n ? `https://www.npmjs.com/package/${encodeURIComponent(manifest.package_name)}`\n : undefined),\n repository: manifest.catalog?.links?.repository ?? manifest.package_repository_url,\n report: manifest.catalog?.links?.report ?? manifest.package_bugs_url,\n };\n}\n\n/**\n * Build one bundled-package catalog entry from its manifest, marking it\n * `installed` when the managed state for `scope` already records the package by\n * built-in alias or resolved location, and projecting the metadata-only resource\n * kinds (everything except installable `extensions`) that the package ships.\n */\nfunction buildBundledCatalogPackageEntry(\n manifest: Awaited<ReturnType<typeof readPmPackageManifest>>,\n bundledEntry: BundledPackageEntry,\n scope: ExtensionScope,\n installedBuiltinAliases: Set<string>,\n installedLocations: Set<string>,\n): Record<string, unknown> {\n const installScopeFlag = scope === \"global\" ? \"--global\" : \"--project\";\n const metadataOnlyResources = Object.fromEntries(\n PM_PACKAGE_RESOURCE_KINDS\n .filter((resourceKind) => resourceKind !== \"extensions\")\n .map((resourceKind) => [resourceKind, manifest.resources[resourceKind] ?? []])\n .filter(([, entries]) => Array.isArray(entries) && entries.length > 0),\n );\n return {\n alias: bundledEntry.alias,\n bundled: true,\n available: true,\n installed:\n installedBuiltinAliases.has(bundledEntry.alias) ||\n installedLocations.has(path.resolve(bundledEntry.package_root)),\n install_target: bundledEntry.alias,\n install_command: `pm install ${bundledEntry.alias} ${installScopeFlag}`,\n package_name: manifest.package_name,\n package_version: manifest.package_version,\n description: manifest.catalog?.summary ?? manifest.package_description,\n keywords: manifest.package_keywords ?? [],\n resources: manifest.resources,\n installable_resources: {\n extensions: manifest.resources.extensions ?? [],\n },\n metadata_only_resources: metadataOnlyResources,\n catalog: {\n display_name: manifest.catalog?.display_name,\n category: manifest.catalog?.category,\n tags: manifest.catalog?.tags ?? manifest.package_keywords ?? [],\n links: buildBundledCatalogLinks(manifest),\n media: manifest.catalog?.media,\n },\n };\n}\n\n/**\n * Implements build bundled package catalog for the public runtime surface of this module.\n */\nexport async function buildBundledPackageCatalog(scope: ExtensionScope, global: GlobalOptions, options: ExtensionCommandOptions = {}): Promise<{\n total: number;\n scope: ExtensionScope;\n installable_resource_kinds: string[];\n metadata_only_resource_kinds: string[];\n packages: Array<Record<string, unknown>>;\n}> {\n const roots = resolveExtensionRoots(resolvePmRoot(process.cwd(), global.path), process.cwd());\n const selectedRoot = scope === \"global\" ? roots.global : roots.project;\n const managedStateRead = await readManagedExtensionState(selectedRoot);\n const installedLocations = new Set(\n managedStateRead.state.entries\n .filter((entry) => entry.scope === scope)\n .filter((entry) => entry.source.kind !== \"builtin\")\n .map((entry) => path.resolve(entry.source.location)),\n );\n const installedBuiltinAliases = new Set(\n managedStateRead.state.entries\n .filter((entry) => entry.scope === scope && entry.source.kind === \"builtin\")\n .flatMap((entry) => [entry.source.name, entry.source.input, entry.source.location])\n .filter((value): value is string => typeof value === \"string\" && value.trim().length > 0)\n .map((value) => value.trim().toLowerCase()),\n );\n const packages: Array<Record<string, unknown>> = [];\n\n for (const bundledEntry of await collectBundledPackageEntries()) {\n const manifest = await readPmPackageManifest(bundledEntry.package_root);\n packages.push(\n buildBundledCatalogPackageEntry(manifest, bundledEntry, scope, installedBuiltinAliases, installedLocations),\n );\n }\n\n const fields = parsePackageCatalogFields(options.fields);\n const outputPackages = fields ? packages.map((entry) => projectPackageCatalogEntry(entry, fields)) : packages;\n return {\n total: outputPackages.length,\n scope,\n installable_resource_kinds: [\"extensions\"],\n metadata_only_resource_kinds: PM_PACKAGE_RESOURCE_KINDS.filter((resourceKind) => resourceKind !== \"extensions\"),\n packages: outputPackages,\n };\n}\n\nconst PACKAGE_CATALOG_FIELD_KEYS = new Set([\n \"alias\",\n \"bundled\",\n \"available\",\n \"installed\",\n \"install_target\",\n \"install_command\",\n \"package_name\",\n \"package_version\",\n \"description\",\n \"keywords\",\n \"resources\",\n \"installable_resources\",\n \"metadata_only_resources\",\n \"catalog\",\n \"category\",\n \"display_name\",\n]);\n\nfunction parsePackageCatalogFields(raw: string | undefined): string[] | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const fields = splitCommaList(raw);\n if (fields.length === 0) {\n throw new PmCliError(\"Package catalog --fields requires a comma-separated list of field names\", EXIT_CODE.USAGE);\n }\n const unknown = fields.filter((field) => !PACKAGE_CATALOG_FIELD_KEYS.has(field));\n if (unknown.length > 0) {\n throw new PmCliError(`Unknown package catalog --fields value(s): ${unknown.join(\", \")}`, EXIT_CODE.USAGE, {\n examples: [\n \"pm package list --project --fields alias,installed,install_command\",\n \"pm package catalog --project --fields alias,package_name,category\",\n ],\n });\n }\n return fields;\n}\n\nfunction projectPackageCatalogEntry(entry: Record<string, unknown>, fields: string[]): Record<string, unknown> {\n const projected: Record<string, unknown> = {};\n for (const field of fields) {\n if (field === \"category\") {\n projected[field] = (entry.catalog as { category?: unknown } | undefined)?.category ?? null;\n } else if (field === \"display_name\") {\n projected[field] = (entry.catalog as { display_name?: unknown } | undefined)?.display_name ?? null;\n } else {\n projected[field] = entry[field] ?? null;\n }\n }\n return projected;\n}\n\nexport const _testOnlyBundledCatalog = {\n parsePackageCatalogFields,\n projectPackageCatalogEntry,\n};\n", "/**\n * @module cli/commands/extension/doctor\n *\n * Implements extension package-management support for Doctor.\n */\nimport {\n activateExtensions,\n loadExtensions,\n reconcileExtensionCapabilityUsage,\n} from \"../../../core/extensions/index.js\";\nimport {\n EXTENSION_CAPABILITY_CONTRACT,\n KNOWN_EXTENSION_CAPABILITIES,\n parseLegacyExtensionCapabilityAliasWarning,\n parseUnknownExtensionCapabilityWarning,\n type UnknownExtensionCapabilityWarningDetails,\n} from \"../../../core/extensions/loader.js\";\nimport { EXIT_CODE } from \"../../../core/shared/constants.js\";\nimport { PmCliError } from \"../../../core/shared/errors.js\";\nimport { normalizeExtensionNameForMatch } from \"./shared.js\";\nimport type {\n ExtensionCollisionPlan,\n ExtensionCommandOptions,\n ExtensionDoctorDetailMode,\n ExtensionScope,\n ExtensionTriageSummary,\n ExtensionUpdateCheckStatus,\n ManagedExtensionSummary,\n} from \"../extension.js\";\n\ninterface RuntimeActivationPaths {\n commandPathsByExtension: Map<string, Set<string>>;\n actionPathsByExtension: Map<string, Set<string>>;\n}\n\nfunction addRuntimePath(pathsByExtension: Map<string, Set<string>>, extensionName: string, pathValue: string): void {\n const normalizedName = normalizeExtensionNameForMatch(extensionName);\n const normalizedPath = pathValue.trim();\n if (normalizedName.length === 0 || normalizedPath.length === 0) {\n return;\n }\n const existing = pathsByExtension.get(normalizedName) ?? new Set<string>();\n existing.add(normalizedPath);\n pathsByExtension.set(normalizedName, existing);\n}\n\nfunction collectRuntimeActivationPaths(\n activationResult: Awaited<ReturnType<typeof activateExtensions>>,\n): RuntimeActivationPaths {\n const commandPathsByExtension = new Map<string, Set<string>>();\n const actionPathsByExtension = new Map<string, Set<string>>();\n for (const registration of activationResult.registrations.commands) {\n addRuntimePath(commandPathsByExtension, registration.name, registration.command);\n addRuntimePath(actionPathsByExtension, registration.name, registration.action);\n }\n for (const handler of activationResult.commands.handlers) {\n addRuntimePath(commandPathsByExtension, handler.name, handler.command);\n }\n for (const override of activationResult.commands.overrides) {\n addRuntimePath(commandPathsByExtension, override.name, override.command);\n }\n return { commandPathsByExtension, actionPathsByExtension };\n}\n\nfunction sortedRuntimePaths(values: Set<string> | undefined): string[] | undefined {\n if (!values || values.size === 0) {\n return undefined;\n }\n return [...values].sort((left, right) => left.localeCompare(right));\n}\n\nfunction resolveDoctorActivationStatus(params: {\n enabled: boolean;\n normalizedName: string;\n loadedNames: Set<string>;\n loadFailedNames: Set<string>;\n activationFailedNames: Set<string>;\n}): Pick<ManagedExtensionSummary, \"runtime_active\" | \"activation_status\"> {\n const { enabled, normalizedName, loadedNames, loadFailedNames, activationFailedNames } = params;\n if (!enabled) {\n return { runtime_active: false, activation_status: \"not_loaded\" };\n }\n if (loadFailedNames.has(normalizedName) || activationFailedNames.has(normalizedName)) {\n return { runtime_active: false, activation_status: \"failed\" };\n }\n if (loadedNames.has(normalizedName)) {\n return { runtime_active: true, activation_status: \"ok\" };\n }\n return { runtime_active: false, activation_status: \"not_loaded\" };\n}\n\n/**\n * Implements apply doctor runtime activation state for the public runtime surface of this module.\n */\nexport function applyDoctorRuntimeActivationState(\n extensions: ManagedExtensionSummary[],\n loadResult: Awaited<ReturnType<typeof loadExtensions>>,\n activationResult: Awaited<ReturnType<typeof activateExtensions>>,\n): ManagedExtensionSummary[] {\n const loadedNames = new Set(loadResult.loaded.map((entry) => normalizeExtensionNameForMatch(entry.name)));\n const loadFailedNames = new Set(loadResult.failed.map((entry) => normalizeExtensionNameForMatch(entry.name)));\n const activationFailedNames = new Set(activationResult.failed.map((entry) => normalizeExtensionNameForMatch(entry.name)));\n const { commandPathsByExtension, actionPathsByExtension } = collectRuntimeActivationPaths(activationResult);\n\n return extensions.map((entry) => {\n const normalizedName = normalizeExtensionNameForMatch(entry.name);\n const commandPaths = sortedRuntimePaths(commandPathsByExtension.get(normalizedName));\n const actionPaths = sortedRuntimePaths(actionPathsByExtension.get(normalizedName));\n const runtimeMetadata = {\n ...(commandPaths ? { command_paths: commandPaths } : {}),\n ...(actionPaths ? { action_paths: actionPaths } : {}),\n };\n const activationStatus = resolveDoctorActivationStatus({\n enabled: entry.enabled,\n normalizedName,\n loadedNames,\n loadFailedNames,\n activationFailedNames,\n });\n return {\n ...entry,\n ...activationStatus,\n ...runtimeMetadata,\n };\n });\n}\n\nfunction summarizePolicyWarnings(warnings: string[]): {\n warning_count: number;\n violation_count: number;\n blocked_count: number;\n} {\n let warningCount = 0;\n let violationCount = 0;\n let blockedCount = 0;\n for (const warning of warnings) {\n if (!warning.startsWith(\"extension_policy_\")) {\n continue;\n }\n warningCount += 1;\n if (warning.startsWith(\"extension_policy_violation_\")) {\n violationCount += 1;\n continue;\n }\n if (warning.startsWith(\"extension_policy_blocked_\")) {\n blockedCount += 1;\n }\n }\n return {\n warning_count: warningCount,\n violation_count: violationCount,\n blocked_count: blockedCount,\n };\n}\n\nfunction lifecycleFlagCommand(options: ExtensionCommandOptions, action: string): string {\n return options.vocabulary === \"package\" ? `pm package --${action}` : `pm extension --${action}`;\n}\n\nconst REGISTRATION_COLLISION_WARNING_CODES = new Set([\n \"extension_command_handler_collision\",\n \"extension_command_override_collision\",\n \"extension_command_override_handler_overlap\",\n \"extension_parser_override_collision\",\n \"extension_preflight_override_collision\",\n \"extension_renderer_collision\",\n \"extension_service_override_collision\",\n]);\n\n/**\n * Implements check whether registration collision warning for the public runtime surface of this module.\n */\nfunction isRegistrationCollisionWarning(warning: string): boolean {\n return REGISTRATION_COLLISION_WARNING_CODES.has(warningCode(warning));\n}\n\nfunction isExtensionLayer(value: string | undefined): value is \"project\" | \"global\" {\n return value === \"project\" || value === \"global\";\n}\n\ninterface RegistrationCollisionWarningParts {\n code: string;\n surface: string;\n winner: { layer: \"project\" | \"global\"; name: string };\n displaced: { layer: \"project\" | \"global\"; name: string };\n}\n\nfunction parseRegistrationCollisionWarning(warning: string): RegistrationCollisionWarningParts | null {\n const parts = warning.split(\":\");\n const code = parts[0];\n if (!code || !REGISTRATION_COLLISION_WARNING_CODES.has(code)) {\n return null;\n }\n // Collision warnings end with winnerLayer:winnerName:displacedLayer:displacedName.\n // Surface identifiers before that suffix may contain colons, so parse from the right.\n const winnerLayer = parts.at(-4);\n const winnerName = parts.at(-3)?.trim();\n const displacedLayer = parts.at(-2);\n const displacedName = parts.at(-1)?.trim();\n if (\n !isExtensionLayer(winnerLayer) ||\n !isExtensionLayer(displacedLayer) ||\n !winnerName ||\n !displacedName\n ) {\n return null;\n }\n return {\n code,\n surface: parts.slice(1, -4).join(\":\") || \"global\",\n winner: { layer: winnerLayer, name: winnerName },\n displaced: { layer: displacedLayer, name: displacedName },\n };\n}\n\nfunction collectRegistrationCollisionExtensionNames(warnings: string[]): string[] {\n const names = new Set<string>();\n for (const warning of warnings) {\n const parsed = parseRegistrationCollisionWarning(warning);\n if (!parsed) {\n continue;\n }\n names.add(parsed.winner.name);\n names.add(parsed.displaced.name);\n }\n return [...names].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Implements build registration collision remediation for the public runtime surface of this module.\n */\nexport function buildRegistrationCollisionRemediation(\n warnings: string[],\n commands: { deactivate: string; doctor: string },\n): string | null {\n const registrationCollisionWarnings = warnings.filter(isRegistrationCollisionWarning);\n if (registrationCollisionWarnings.length === 0) {\n return null;\n }\n const collisionNames = collectRegistrationCollisionExtensionNames(registrationCollisionWarnings);\n const collisionNameText = collisionNames.length > 0 ? ` Conflicting extensions: ${collisionNames.join(\", \")}.` : \"\";\n return (\n `Extension registration collisions or handler/override overlaps detected.${collisionNameText} Single-winner surfaces can hide earlier package behavior. ` +\n `Deactivate one conflicting package with ${commands.deactivate}, ` +\n `or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${commands.doctor}.`\n );\n}\n\nfunction buildRegistrationCollisionPlan(\n scope: ExtensionScope,\n warnings: string[],\n extensions: ManagedExtensionSummary[],\n options: ExtensionCommandOptions,\n): ExtensionCollisionPlan | undefined {\n const collisions = warnings\n .map((warning) => parseRegistrationCollisionWarning(warning))\n .filter((entry): entry is RegistrationCollisionWarningParts => entry !== null)\n .sort((left, right) =>\n `${left.code}:${left.surface}:${left.winner.name}:${left.displaced.name}`.localeCompare(\n `${right.code}:${right.surface}:${right.winner.name}:${right.displaced.name}`,\n ),\n );\n if (collisions.length === 0) {\n return undefined;\n }\n const scopeFlag = scope === \"global\" ? \"--global\" : \"--project\";\n const deactivatePrefix = lifecycleFlagCommand(options, \"deactivate\");\n const doctorCommand = `${lifecycleFlagCommand(options, \"doctor\")} ${scopeFlag} --detail deep --trace`;\n const extensionByName = new Map(extensions.map((entry) => [normalizeExtensionNameForMatch(entry.name), entry]));\n const affectedByName = new Map<string, number>();\n for (const collision of collisions) {\n for (const name of [collision.winner.name, collision.displaced.name]) {\n const normalizedName = normalizeExtensionNameForMatch(name);\n affectedByName.set(normalizedName, (affectedByName.get(normalizedName) ?? 0) + 1);\n }\n }\n const remediationCandidates = [...affectedByName.entries()]\n .map(([normalizedName, affectedCollisions]) => {\n const extension = extensionByName.get(normalizedName);\n const extensionName = extension?.name ?? normalizedName;\n const commandPaths = extension?.command_paths ?? [];\n const actionPaths = extension?.action_paths ?? [];\n return {\n action: \"deactivate\" as const,\n extension: extensionName,\n command: `${deactivatePrefix} ${extensionName} ${scopeFlag}`,\n affected_collisions: affectedCollisions,\n feature_loss: {\n command_paths: [...commandPaths].sort((left, right) => left.localeCompare(right)),\n action_paths: [...actionPaths].sort((left, right) => left.localeCompare(right)),\n },\n };\n })\n .sort((left, right) => {\n const affectedDelta = right.affected_collisions - left.affected_collisions;\n if (affectedDelta !== 0) {\n return affectedDelta;\n }\n const leftSurfaceCount = left.feature_loss.command_paths.length + left.feature_loss.action_paths.length;\n const rightSurfaceCount = right.feature_loss.command_paths.length + right.feature_loss.action_paths.length;\n if (leftSurfaceCount !== rightSurfaceCount) {\n return leftSurfaceCount - rightSurfaceCount;\n }\n return left.extension.localeCompare(right.extension);\n });\n\n return {\n status: \"conflicts_detected\",\n collision_count: collisions.length,\n extension_count: affectedByName.size,\n next_best_command: doctorCommand,\n collisions,\n remediation_candidates: remediationCandidates,\n };\n}\n\n/**\n * Implements classify doctor load failure warnings for the public runtime surface of this module.\n */\nexport function classifyDoctorLoadFailureWarnings(loadFailures: Array<{ name: string; error: string }>): string[] {\n const warnings: string[] = [];\n for (const failure of loadFailures) {\n const normalizedError = failure.error.toLowerCase();\n if (\n normalizedError.includes(\"cannot find package '@unbrained/pm-cli'\") ||\n normalizedError.includes('cannot find module \"@unbrained/pm-cli\"') ||\n normalizedError.includes(\"cannot find module '@unbrained/pm-cli'\")\n ) {\n warnings.push(`extension_load_failed_sdk_dependency_missing:${failure.name}`);\n }\n if (\n normalizedError.includes(\"cannot use import statement outside a module\") ||\n normalizedError.includes(\"to load an es module\") ||\n normalizedError.includes(\"must use import to load es module\")\n ) {\n warnings.push(`extension_load_failed_module_mode_mismatch:${failure.name}`);\n }\n }\n return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Implements classify doctor activation failure warnings for the public runtime surface of this module.\n */\nexport function classifyDoctorActivationFailureWarnings(\n activationFailures: Array<{ name: string; trace?: { missing_capability?: string; capability?: string } }> = [],\n): string[] {\n const failures = Array.isArray(activationFailures) ? activationFailures : [];\n const warnings: string[] = [];\n for (const failure of failures) {\n if (!failure || typeof failure.name !== \"string\") {\n continue;\n }\n const missingCapability = failure.trace?.missing_capability ?? failure.trace?.capability;\n if (typeof missingCapability === \"string\" && missingCapability.trim().length > 0) {\n warnings.push(`extension_capability_missing:${failure.name}:${missingCapability.trim().toLowerCase()}`);\n }\n }\n return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Classify advisory least-privilege warnings for capabilities each loaded\n * extension declares in its manifest but never registers against.\n *\n * Emits one `extension_capability_unused:<layer>:<name>:<capability>` token per\n * over-broad grant. These are advisory hygiene hints — they never block — that\n * tell an author to trim the manifest (or add the missing registration). The\n * inverse failure (registering a surface whose capability is undeclared) is the\n * blocking `extension_capability_missing` warning emitted during activation.\n */\nexport function classifyUnusedCapabilityWarnings(\n loadResult: Awaited<ReturnType<typeof loadExtensions>>,\n activationResult: Awaited<ReturnType<typeof activateExtensions>>,\n): string[] {\n const warnings: string[] = [];\n for (const entry of reconcileExtensionCapabilityUsage(loadResult.loaded, activationResult)) {\n for (const capability of entry.unused) {\n warnings.push(`extension_capability_unused:${entry.layer}:${entry.name}:${capability}`);\n }\n }\n return [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Inputs every triage remediation message can reference: the lifecycle command\n * options and resolved `scopeFlag`/`scope`, plus the two numeric totals\n * (`updateCheckFailedTotal`, `policyWarningCount`) whose own warning-driven rules\n * fire purely on a count rather than a warning prefix.\n */\ninterface TriageRemediationContext {\n options: ExtensionCommandOptions;\n scope: ExtensionScope;\n scopeFlag: string;\n updateCheckFailedTotal: number;\n policyWarningCount: number;\n}\n\n/**\n * One warning-driven remediation rule: `matches` decides whether the emitted\n * warning set (or a {@link TriageRemediationContext} count) warrants the hint,\n * and `build` renders the scope-aware message. Replacing the former\n * if-prefix ladder with this table keeps {@link buildExtensionTriageSummary}\n * under the complexity ceiling while preserving message order and content.\n */\ninterface TriageRemediationRule {\n matches: (warnings: readonly string[], ctx: TriageRemediationContext) => boolean;\n build: (ctx: TriageRemediationContext) => string;\n}\n\n/**\n * Ordered remediation rules evaluated while at least one warning is present. The\n * order is load-bearing — it is the order remediation hints appear in doctor\n * output — so new rules must be inserted at the intended position rather than\n * appended.\n */\nconst TRIAGE_REMEDIATION_RULES: readonly TriageRemediationRule[] = [\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_manifest_\")),\n build: (ctx) =>\n `Run ${lifecycleFlagCommand(ctx.options, \"explore\")} ${ctx.scopeFlag} to inspect discovered manifests and directories.`,\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_capability_unknown:\")),\n build: () =>\n `Unknown extension capabilities detected. Allowed capabilities: ${KNOWN_EXTENSION_CAPABILITIES.join(\", \")}. ` +\n \"Review extension_capability_unknown warning details for suggested replacements.\",\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_capability_legacy_alias:\")),\n build: () =>\n \"Legacy extension capability aliases were auto-remapped to canonical capabilities. \" +\n \"Update manifests to canonical names (migration/validation -> schema).\",\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_capability_missing:\")),\n build: (ctx) =>\n `Extension activation failed because code registered a surface missing from manifest capabilities. ` +\n `Run ${lifecycleFlagCommand(ctx.options, \"doctor\")} ${ctx.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`,\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_capability_unused:\")),\n build: (ctx) =>\n \"Extension manifests declare capabilities that are never registered against. \" +\n `Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${lifecycleFlagCommand(ctx.options, \"doctor\")} ${ctx.scopeFlag} --detail deep --trace for per-extension registration counts.`,\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_command_definition_legacy_handler_alias:\")),\n build: () =>\n \"Extension command definitions using legacy handler were auto-remapped. \" +\n \"Update command definitions to use run: (context) => ... for forward compatibility.\",\n },\n {\n matches: (warnings) =>\n warnings.some(\n (warning) =>\n warning.startsWith(\"extension_output_service_override_global:\") ||\n warning.startsWith(\"extension_output_renderer_override_global:\"),\n ),\n build: () =>\n \"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering.\",\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_schema_narrow_activation:\")),\n build: () =>\n \"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or — if the schema is intentionally command-scoped — knowingly ignore this advisory.\",\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_load_failed_sdk_dependency_missing:\")),\n build: (ctx) =>\n `Detected extension load failures caused by missing SDK dependency resolution. ` +\n `Ensure extension package dependencies include \"@unbrained/pm-cli\" and reinstall dependencies before running ${lifecycleFlagCommand(ctx.options, \"doctor\")} ${ctx.scopeFlag}.`,\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_load_failed_module_mode_mismatch:\")),\n build: (ctx) =>\n `Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json \"type\": \"module\" ` +\n `or use an explicit .mjs entry and rerun ${lifecycleFlagCommand(ctx.options, \"doctor\")} ${ctx.scopeFlag}.`,\n },\n {\n matches: (warnings) =>\n warnings.some(\n (warning) =>\n warning.startsWith(\"extension_pm_min_version_\") || warning.startsWith(\"extension_pm_max_version_\"),\n ),\n build: (ctx) =>\n \"Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version \" +\n `with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${lifecycleFlagCommand(ctx.options, \"doctor\")} ${ctx.scopeFlag}.`,\n },\n {\n matches: (_warnings, ctx) => ctx.updateCheckFailedTotal > 0,\n build: (ctx) =>\n `Run ${lifecycleFlagCommand(ctx.options, \"manage\")} ${ctx.scopeFlag} after validating network and repository access.`,\n },\n {\n matches: (warnings) => warnings.some((warning) => warning.startsWith(\"extension_manager_state_\")),\n build: (ctx) => `Review and repair ${ctx.scope} managed extension state file if schema/read warnings persist.`,\n },\n {\n matches: (_warnings, ctx) => ctx.policyWarningCount > 0,\n build: () =>\n \"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces.\",\n },\n];\n\n/**\n * Build the ordered remediation hints for a triage summary. Warning-driven rules\n * (collision remediation first, then {@link TRIAGE_REMEDIATION_RULES}) only run\n * when at least one warning is present; the update-health coverage and\n * availability hints always run; and a \"no immediate action\" fallback is\n * appended when nothing else applied.\n */\nfunction buildExtensionTriageRemediation(params: {\n normalizedWarnings: string[];\n options: ExtensionCommandOptions;\n scope: ExtensionScope;\n scopeFlag: string;\n updateCheckFailedTotal: number;\n policyWarningCount: number;\n updateHealthPartial: boolean;\n skippedUnmanagedTotal: number;\n skippedNonGithubTotal: number;\n updateAvailableTotal: number;\n}): string[] {\n const {\n normalizedWarnings,\n options,\n scope,\n scopeFlag,\n updateCheckFailedTotal,\n policyWarningCount,\n updateHealthPartial,\n skippedUnmanagedTotal,\n skippedNonGithubTotal,\n updateAvailableTotal,\n } = params;\n const remediation: string[] = [];\n const ctx: TriageRemediationContext = { options, scope, scopeFlag, updateCheckFailedTotal, policyWarningCount };\n if (normalizedWarnings.length > 0) {\n const registrationCollisionRemediation = buildRegistrationCollisionRemediation(normalizedWarnings, {\n deactivate: `${lifecycleFlagCommand(options, \"deactivate\")} <name> ${scopeFlag}`,\n doctor: `${lifecycleFlagCommand(options, \"doctor\")} ${scopeFlag} --detail deep --trace`,\n });\n if (registrationCollisionRemediation) {\n remediation.push(registrationCollisionRemediation);\n }\n for (const rule of TRIAGE_REMEDIATION_RULES) {\n if (rule.matches(normalizedWarnings, ctx)) {\n remediation.push(rule.build(ctx));\n }\n }\n }\n if (updateHealthPartial) {\n remediation.push(\n `Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${lifecycleFlagCommand(options, \"manage\")} ${scopeFlag} --fix-managed-state (or ${lifecycleFlagCommand(options, \"adopt-all\")} ${scopeFlag}, ${lifecycleFlagCommand(options, \"adopt\")} <name> ${scopeFlag}, or reinstall via ${lifecycleFlagCommand(options, \"install\")} ${scopeFlag} <source>).`,\n );\n } else if (skippedUnmanagedTotal > 0) {\n remediation.push(\n `Loaded unmanaged extensions are currently treated as informational. Use ${lifecycleFlagCommand(options, \"manage\")} ${scopeFlag} --fix-managed-state to adopt them for update checks.`,\n );\n }\n if (skippedNonGithubTotal > 0) {\n remediation.push(`Non-GitHub managed extensions are skipped by update checks. Use doctor output for non-update diagnostics.`);\n }\n if (updateAvailableTotal > 0) {\n remediation.push(`Update available managed extensions via ${lifecycleFlagCommand(options, \"install\")} ${scopeFlag} <source>.`);\n }\n if (remediation.length === 0) {\n remediation.push(`No immediate action required. Re-run ${lifecycleFlagCommand(options, \"manage\")} ${scopeFlag} after extension changes.`);\n }\n return remediation;\n}\n\n/**\n * Implements build extension triage summary for the public runtime surface of this module.\n */\nexport function buildExtensionTriageSummary(\n scope: ExtensionScope,\n warnings: string[],\n extensions: ManagedExtensionSummary[],\n options: ExtensionCommandOptions = {},\n): ExtensionTriageSummary {\n const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n const managedTotal = extensions.filter((entry) => entry.managed).length;\n const enabledTotal = extensions.filter((entry) => entry.enabled).length;\n const activeTotal = extensions.filter((entry) => entry.active).length;\n const updateAvailableTotal = extensions.filter((entry) => entry.update_available === true).length;\n const unmanagedExtensions = extensions.filter((entry) => entry.managed === false);\n const unmanagedExpectedExtensions = unmanagedExtensions\n .filter((entry) => isExpectedUnmanagedExtension(entry))\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right));\n const unmanagedActionRequiredExtensions = unmanagedExtensions\n .filter((entry) => !isExpectedUnmanagedExtension(entry))\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right));\n const updateCheckStatusTotals: Record<ExtensionUpdateCheckStatus, number> = {\n checked: 0,\n skipped_unmanaged: 0,\n skipped_non_github: 0,\n failed: 0,\n not_checked: 0,\n };\n for (const entry of extensions) {\n updateCheckStatusTotals[entry.update_check_status] += 1;\n }\n const updateCheckFailedTotal = updateCheckStatusTotals.failed;\n const skippedUnmanagedTotal = updateCheckStatusTotals.skipped_unmanaged;\n const skippedNonGithubTotal = updateCheckStatusTotals.skipped_non_github;\n const updateHealthPartial = unmanagedActionRequiredExtensions.length > 0;\n const updateHealthCoverage = updateHealthPartial ? \"partial\" : \"full\";\n const partialCoverageWarnings = updateHealthPartial\n ? [`extension_update_health_partial_coverage:skipped_unmanaged:${unmanagedActionRequiredExtensions.length}`]\n : [];\n const effectiveWarnings = [...new Set([...normalizedWarnings, ...partialCoverageWarnings])].sort((left, right) =>\n left.localeCompare(right),\n );\n const warningCodes = [...new Set(effectiveWarnings.map((value) => warningCode(value)))].sort((left, right) =>\n left.localeCompare(right),\n );\n const policyWarnings = summarizePolicyWarnings(effectiveWarnings);\n const scopeFlag = scope === \"global\" ? \"--global\" : \"--project\";\n const collisionPlan = buildRegistrationCollisionPlan(scope, normalizedWarnings, extensions, options);\n const remediation = buildExtensionTriageRemediation({\n normalizedWarnings,\n options,\n scope,\n scopeFlag,\n updateCheckFailedTotal,\n policyWarningCount: policyWarnings.warning_count,\n updateHealthPartial,\n skippedUnmanagedTotal,\n skippedNonGithubTotal,\n updateAvailableTotal,\n });\n return {\n status: effectiveWarnings.length === 0 ? \"ok\" : \"warn\",\n warning_count: effectiveWarnings.length,\n warning_codes: warningCodes,\n warnings: effectiveWarnings,\n policy_warning_count: policyWarnings.warning_count,\n policy_violation_count: policyWarnings.violation_count,\n policy_blocked_count: policyWarnings.blocked_count,\n total_extensions: extensions.length,\n managed_total: managedTotal,\n enabled_total: enabledTotal,\n active_total: activeTotal,\n update_available_total: updateAvailableTotal,\n update_health_coverage: updateHealthCoverage,\n update_health_partial: updateHealthPartial,\n unmanaged_loaded_extension_count: unmanagedExtensions.length,\n unmanaged_loaded_extensions: unmanagedExtensions\n .map((entry) => entry.name)\n .sort((left, right) => left.localeCompare(right)),\n unmanaged_expected_extension_count: unmanagedExpectedExtensions.length,\n unmanaged_expected_extensions: unmanagedExpectedExtensions,\n unmanaged_action_required_extension_count: unmanagedActionRequiredExtensions.length,\n unmanaged_action_required_extensions: unmanagedActionRequiredExtensions,\n update_check_status_totals: updateCheckStatusTotals,\n update_check_failed_total: updateCheckFailedTotal,\n top_warnings: effectiveWarnings.slice(0, 8),\n remediation,\n ...(collisionPlan ? { collision_plan: collisionPlan } : {}),\n };\n}\n\n/**\n * Implements parse doctor detail mode for the public runtime surface of this module.\n */\nexport function parseDoctorDetailMode(raw: string | undefined): ExtensionDoctorDetailMode {\n if (!raw || raw.trim().length === 0) {\n return \"summary\";\n }\n const normalized = raw.trim().toLowerCase();\n if (normalized === \"summary\" || normalized === \"deep\") {\n return normalized;\n }\n throw new PmCliError(`Invalid --detail value \"${raw}\". Expected summary or deep.`, EXIT_CODE.USAGE);\n}\n\nfunction warningCode(value: string): string {\n const normalized = value.trim();\n const separator = normalized.indexOf(\":\");\n if (separator === -1) {\n return normalized;\n }\n return normalized.slice(0, separator);\n}\n\n/**\n * Implements collect unknown capability guidance for the public runtime surface of this module.\n */\nexport function collectUnknownCapabilityGuidance(warnings: string[]): UnknownExtensionCapabilityWarningDetails[] {\n const seen = new Set<string>();\n const guidance: UnknownExtensionCapabilityWarningDetails[] = [];\n for (const warning of warnings) {\n const parsedDetails = (() => {\n const unknownWarning = parseUnknownExtensionCapabilityWarning(warning);\n if (unknownWarning) {\n return [unknownWarning];\n }\n return parseLegacyExtensionCapabilityAliasWarning(warning);\n })();\n for (const parsed of parsedDetails) {\n const key = `${parsed.layer}:${parsed.name}:${parsed.capability}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n guidance.push(parsed);\n }\n }\n return guidance;\n}\n\n/**\n * Implements build capability contract metadata for the public runtime surface of this module.\n */\nexport function buildCapabilityContractMetadata(): {\n version: number;\n capabilities: string[];\n legacy_aliases: Record<string, string>;\n} {\n return {\n version: EXTENSION_CAPABILITY_CONTRACT.version,\n capabilities: [...EXTENSION_CAPABILITY_CONTRACT.capabilities],\n legacy_aliases: { ...EXTENSION_CAPABILITY_CONTRACT.legacy_aliases },\n };\n}\n\nfunction isExpectedUnmanagedExtension(entry: ManagedExtensionSummary): boolean {\n const normalizedName = normalizeExtensionNameForMatch(entry.name);\n const normalizedDirectory = normalizeExtensionNameForMatch(entry.directory);\n if (normalizedName.startsWith(\"builtin-\")) {\n return true;\n }\n return normalizedDirectory === \"beads\" || normalizedDirectory === \"todos\";\n}\n\n/**\n * Implements build doctor consistency summary for the public runtime surface of this module.\n */\nexport function buildDoctorConsistencySummary(\n scope: ExtensionScope,\n installedExtensions: ManagedExtensionSummary[],\n loadedExtensions: Array<{ layer: string; name: string }>,\n failedLoads: Array<{ name: string }>,\n disabledByFlag: boolean,\n): {\n warnings: string[];\n summary: {\n active_project_count: number;\n loaded_project_count: number;\n active_project_names: string[];\n loaded_project_names: string[];\n missing_active_project_names: string[];\n };\n} {\n if (scope !== \"project\" || disabledByFlag) {\n return {\n warnings: [],\n summary: {\n active_project_count: 0,\n loaded_project_count: 0,\n active_project_names: [],\n loaded_project_names: [],\n missing_active_project_names: [],\n },\n };\n }\n\n const activeProjectNames = [\n ...new Set(\n installedExtensions\n .filter((entry) => entry.active)\n .map((entry) => normalizeExtensionNameForMatch(entry.name)),\n ),\n ].sort((left, right) => left.localeCompare(right));\n const loadedProjectNames = [\n ...new Set(\n loadedExtensions\n .filter((entry) => entry.layer === \"project\")\n .map((entry) => normalizeExtensionNameForMatch(entry.name)),\n ),\n ].sort((left, right) => left.localeCompare(right));\n const failedLoadNames = new Set(failedLoads.map((entry) => normalizeExtensionNameForMatch(entry.name)));\n const missingActiveProjectNames = activeProjectNames\n .filter((name) => !loadedProjectNames.includes(name) && !failedLoadNames.has(name))\n .sort((left, right) => left.localeCompare(right));\n\n const warnings = missingActiveProjectNames.length > 0\n ? [`extension_doctor_consistency_active_not_loaded:${missingActiveProjectNames.join(\",\")}`]\n : [];\n\n return {\n warnings,\n summary: {\n active_project_count: activeProjectNames.length,\n loaded_project_count: loadedProjectNames.length,\n active_project_names: activeProjectNames,\n loaded_project_names: loadedProjectNames,\n missing_active_project_names: missingActiveProjectNames,\n },\n };\n}\n", "/**\n * @module cli/commands/init\n *\n * Implements the pm init command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport readline from \"node:readline/promises\";\nimport { stdin as input, stdout as output } from \"node:process\";\nimport { getActiveExtensionRegistrations, runActiveOnWriteHooks } from \"../../core/extensions/index.js\";\nimport { pathExists, readFileIfExists, writeFileAtomic } from \"../../core/fs/fs-utils.js\";\nimport { normalizePrefix } from \"../../core/item/id.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport {\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,\n ensureRuntimeSchemaFileScaffold,\n filePathForSchemaSection,\n normalizeRuntimeSchemaSettings,\n} from \"../../core/schema/runtime-schema.js\";\nimport {\n parseItemTypesFile,\n serializeItemTypesFile,\n upsertItemType,\n} from \"../../core/schema/item-types-file.js\";\nimport {\n normalizeTypePresetName,\n resolveTypePresetDefinitions,\n TYPE_PRESET_NAMES,\n type TypePresetName,\n} from \"../../core/schema/type-presets.js\";\nimport { EXIT_CODE, GOVERNANCE_PRESET_DEFAULTS, PM_REQUIRED_SUBDIRS, SETTINGS_DEFAULTS } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings, writeSettings } from \"../../core/store/settings.js\";\nimport type { GovernancePreset, PmSettings } from \"../../types/index.js\";\nimport { runExtension, type ExtensionCommandResult } from \"./extension.js\";\nimport {\n INIT_AGENT_GUIDANCE_MODE_VALUES,\n runInitAgentGuidance,\n type InitAgentGuidanceMode,\n type InitAgentGuidanceSummary,\n} from \"./init-agent-guidance.js\";\n\n/**\n * Documents the init installed packages summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface InitInstalledPackagesSummary {\n installed_all: boolean;\n installed_count: number;\n packages: Array<{\n alias: string;\n ok: boolean;\n }>;\n}\n\n/**\n * Restricts init type preset name values accepted by command, SDK, and storage contracts.\n */\nexport type InitTypePresetName = TypePresetName;\n\n/**\n * Documents the init registered type preset summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface InitRegisteredTypePresetSummary {\n name: InitTypePresetName;\n registered: string[];\n updated: string[];\n file: string;\n}\n\n/**\n * Documents the init agent-guidance summary plus generated next-step hints returned by init.\n */\nexport type InitAgentGuidanceResult = InitAgentGuidanceSummary & { next_steps: string[] };\n\n/**\n * Documents the init result payload exchanged by command, SDK, and package integrations.\n */\nexport interface InitResult {\n ok: boolean;\n path: string;\n settings: PmSettings;\n created_dirs: string[];\n warnings: string[];\n governance_preset: GovernancePreset;\n wizard_used: boolean;\n registered_type_preset?: InitRegisteredTypePresetSummary;\n installed_packages?: InitInstalledPackagesSummary;\n next_steps: string[];\n agent_guidance: InitAgentGuidanceResult;\n}\n\n/**\n * Documents the init command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface InitCommandOptions {\n preset?: string;\n defaults?: boolean;\n author?: string;\n withPackages?: boolean;\n agentGuidance?: string;\n typePreset?: string;\n force?: boolean;\n}\n\n/**\n * Concise projection of an InitResult for the default (toon) renderer. It keeps\n * every piece of information that only init can surface — the resolved path, id\n * prefix, governance preset, telemetry capture level, created-directory count,\n * the full warnings list (including `already_exists:` markers), agent-guidance\n * summary, and next steps — but replaces the verbose full settings tree (~190\n * lines) with a compact `settings` summary. Use --verbose for the full tree.\n */\nexport interface InitConciseResult {\n ok: boolean;\n path: string;\n id_prefix: string;\n governance_preset: GovernancePreset;\n telemetry: {\n enabled: boolean;\n capture_level: string;\n };\n output_format: string;\n created_dirs_count: number;\n created_dirs: string[];\n warnings: string[];\n wizard_used: boolean;\n registered_type_preset?: InitRegisteredTypePresetSummary;\n installed_packages?: InitInstalledPackagesSummary;\n next_steps: string[];\n agent_guidance: InitAgentGuidanceResult;\n hint: string;\n}\n\n/**\n * Implements summarize init result for the public runtime surface of this module.\n */\nexport function summarizeInitResult(result: InitResult): InitConciseResult {\n return {\n ok: result.ok,\n path: result.path,\n id_prefix: result.settings.id_prefix,\n governance_preset: result.governance_preset,\n telemetry: {\n enabled: result.settings.telemetry.enabled,\n capture_level: result.settings.telemetry.capture_level,\n },\n output_format: result.settings.output.default_format,\n created_dirs_count: result.created_dirs.length,\n created_dirs: result.created_dirs,\n warnings: result.warnings,\n wizard_used: result.wizard_used,\n ...(result.registered_type_preset ? { registered_type_preset: result.registered_type_preset } : {}),\n ...(result.installed_packages ? { installed_packages: result.installed_packages } : {}),\n next_steps: result.next_steps,\n agent_guidance: result.agent_guidance,\n hint: \"Re-run with --verbose for the full settings tree.\",\n };\n}\n\nexport const _testOnly = {\n normalizeInitGovernancePreset,\n normalizeInitTypePreset,\n normalizeOptionalInitAuthor,\n normalizeInitAgentGuidanceMode,\n isPathLikeInitTarget,\n resolveInitInvocation,\n parseYesNoChoice,\n applyGovernancePreset,\n runInitWizard,\n setInitReadlineFactoryForTests,\n summarizeInstalledPackages,\n registerInitTypePreset,\n assertExplicitTrackerPathIsNotWorkspaceRoot,\n isLikelyWorkspaceRoot,\n};\n\ntype InitReadlineInterface = ReturnType<typeof readline.createInterface>;\nlet createInitReadlineInterface = (): InitReadlineInterface => readline.createInterface({ input, output });\n\ninterface InitNormalizedOptions {\n presetFromOption: BuiltinGovernancePreset | undefined;\n useDefaults: boolean;\n authorFromOption: string | undefined;\n installBundledPackages: boolean;\n agentGuidanceMode: InitAgentGuidanceMode;\n typePreset: InitTypePresetName | undefined;\n}\n\ninterface InitSettingsResolution {\n settings: PmSettings;\n normalizedPrefix: string;\n chosenPreset: BuiltinGovernancePreset | undefined;\n wizardUsed: boolean;\n}\n\nfunction setInitReadlineFactoryForTests(factory: (() => InitReadlineInterface) | undefined): void {\n createInitReadlineInterface = factory ?? (() => readline.createInterface({ input, output }));\n}\n\nfunction cloneDefaults(): PmSettings {\n return structuredClone(SETTINGS_DEFAULTS);\n}\n\ntype BuiltinGovernancePreset = Exclude<GovernancePreset, \"custom\">;\nconst BUILTIN_GOVERNANCE_PRESETS: BuiltinGovernancePreset[] = [\"minimal\", \"default\", \"strict\"];\nfunction normalizeInitGovernancePreset(rawValue: string | undefined): BuiltinGovernancePreset | undefined {\n if (rawValue === undefined) {\n return undefined;\n }\n const normalized = rawValue.trim().toLowerCase().replaceAll(\"-\", \"_\");\n if (normalized.length === 0) {\n throw new PmCliError(\"--preset must not be empty\", EXIT_CODE.USAGE);\n }\n if (normalized === \"minimal\" || normalized === \"default\" || normalized === \"strict\") {\n return normalized;\n }\n if (normalized === \"lite\" || normalized === \"minimum\") {\n return \"minimal\";\n }\n throw new PmCliError(\n `Invalid --preset value \"${rawValue}\". Allowed: ${BUILTIN_GOVERNANCE_PRESETS.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction normalizeInitTypePreset(rawValue: string | undefined): InitTypePresetName | undefined {\n if (rawValue === undefined) {\n return undefined;\n }\n if (rawValue.trim().length === 0) {\n throw new PmCliError(\"--type-preset must not be empty\", EXIT_CODE.USAGE);\n }\n try {\n // Non-undefined input never returns undefined; the shared normalizer throws\n // a plain Error for empty/unknown values, which we re-map to init's --type-preset\n // PmCliError wording for a consistent CLI surface.\n return normalizeTypePresetName(rawValue) as InitTypePresetName;\n } catch {\n throw new PmCliError(\n `Invalid --type-preset value \"${rawValue}\". Allowed: ${TYPE_PRESET_NAMES.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n }\n}\n\nfunction normalizeOptionalInitAuthor(rawValue: string | undefined): string | undefined {\n if (rawValue === undefined) {\n return undefined;\n }\n const normalized = rawValue.trim();\n if (normalized.length === 0) {\n throw new PmCliError(\"--author must not be empty\", EXIT_CODE.USAGE);\n }\n return normalized;\n}\n\nfunction isPathLikeInitTarget(rawValue: string | undefined): boolean {\n if (rawValue === undefined) {\n return false;\n }\n const trimmed = rawValue.trim();\n if (trimmed.length === 0) {\n return false;\n }\n return path.isAbsolute(trimmed) || trimmed.startsWith(\".\") || trimmed.includes(\"/\") || trimmed.includes(\"\\\\\");\n}\n\nfunction resolveInitInvocation(\n cwd: string,\n global: GlobalOptions,\n prefixArg: string | undefined,\n): { pmRoot: string; prefixArg: string | undefined; positional_target?: string } {\n if (global.path === undefined && isPathLikeInitTarget(prefixArg)) {\n const positionalTarget = path.resolve(cwd, prefixArg!.trim());\n return {\n pmRoot: positionalTarget,\n prefixArg: undefined,\n positional_target: positionalTarget,\n };\n }\n return {\n pmRoot: resolvePmRoot(cwd, global.path),\n prefixArg,\n };\n}\n\nfunction normalizeInitAgentGuidanceMode(rawValue: string | undefined): InitAgentGuidanceMode {\n if (rawValue === undefined) {\n return \"ask\";\n }\n const normalized = rawValue.trim().toLowerCase().replaceAll(\"-\", \"_\");\n if (normalized.length === 0) {\n throw new PmCliError(\"--agent-guidance must not be empty\", EXIT_CODE.USAGE);\n }\n if (normalized === \"ask\" || normalized === \"add\" || normalized === \"skip\" || normalized === \"status\") {\n return normalized;\n }\n throw new PmCliError(\n `Invalid --agent-guidance value \"${rawValue}\". Allowed: ${INIT_AGENT_GUIDANCE_MODE_VALUES.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction parseYesNoChoice(answer: string, currentDefault: boolean): boolean {\n const normalized = answer.trim().toLowerCase();\n if (normalized.length === 0) {\n return currentDefault;\n }\n if (normalized === \"y\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"n\" || normalized === \"no\") {\n return false;\n }\n return currentDefault;\n}\n\nfunction applyGovernancePreset(settings: PmSettings, preset: BuiltinGovernancePreset): void {\n const knobs = GOVERNANCE_PRESET_DEFAULTS[preset];\n settings.governance = {\n preset,\n ...knobs,\n };\n settings.validation.parent_reference = knobs.parent_reference;\n settings.validation.metadata_profile = knobs.metadata_profile;\n}\n\nfunction isInstalledPackageEntry(value: unknown): value is { alias?: unknown; ok?: unknown } {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction summarizeInstalledPackages(result: ExtensionCommandResult): InitInstalledPackagesSummary {\n const details = result.details as {\n installed_all?: unknown;\n installed_count?: unknown;\n packages?: Array<{\n alias?: unknown;\n ok?: unknown;\n }>;\n };\n return {\n installed_all: details.installed_all === true,\n installed_count: typeof details.installed_count === \"number\" ? details.installed_count : 0,\n packages: Array.isArray(details.packages)\n ? details.packages.filter(isInstalledPackageEntry).map((entry) => ({\n alias: typeof entry.alias === \"string\" ? entry.alias : \"\",\n ok: entry.ok === true,\n }))\n : [],\n };\n}\n\nasync function registerInitTypePreset(\n pmRoot: string,\n settings: PmSettings,\n preset: InitTypePresetName,\n): Promise<InitRegisteredTypePresetSummary> {\n const schema = normalizeRuntimeSchemaSettings(settings.schema);\n const typesPath = filePathForSchemaSection(pmRoot, schema.files.types, DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types);\n const parsed = parseItemTypesFile(await readFileIfExists(typesPath));\n let nextFile = parsed;\n const registered: string[] = [];\n const updated: string[] = [];\n for (const normalized of resolveTypePresetDefinitions(preset)) {\n const upsert = upsertItemType(nextFile, normalized);\n nextFile = upsert.file;\n (upsert.replaced ? updated : registered).push(upsert.definition.name);\n }\n await writeFileAtomic(typesPath, serializeItemTypesFile(nextFile));\n return {\n name: preset,\n registered,\n updated,\n file: typesPath,\n };\n}\n\nasync function isLikelyWorkspaceRoot(candidate: string): Promise<boolean> {\n const indicators = [\n \".git\",\n \"package.json\",\n \"pnpm-workspace.yaml\",\n \"AGENTS.md\",\n path.join(\".agents\", \"pm\"),\n ];\n for (const indicator of indicators) {\n if (await pathExists(path.join(candidate, indicator))) {\n return true;\n }\n }\n return false;\n}\n\nasync function assertExplicitTrackerPathIsNotWorkspaceRoot(pmRoot: string, global: GlobalOptions, force: boolean): Promise<void> {\n if (global.path === undefined || force) {\n return;\n }\n if (await pathExists(path.join(pmRoot, \"settings.json\"))) {\n return;\n }\n if (!(await isLikelyWorkspaceRoot(pmRoot))) {\n return;\n }\n const nestedTracker = path.join(pmRoot, \".agents\", \"pm\");\n throw new PmCliError(\n `Refusing to initialize tracker files directly in workspace root \"${pmRoot}\".`,\n EXIT_CODE.USAGE,\n {\n code: \"workspace_root_pm_path\",\n type: \"urn:pm-cli:error:workspace_root_pm_path\",\n why: \"--pm-path/--path points at the tracker storage directory itself, not the repository workspace. Point it at .agents/pm or pass --force if you intentionally want root-level tracker files.\",\n examples: [\n `pm --pm-path ${nestedTracker} init --yes`,\n \"pm init --yes\",\n `pm --pm-path ${pmRoot} init --yes --force`,\n ],\n nextSteps: [\n \"Use --pm-path <repo>/.agents/pm for repository-local tracker storage.\",\n \"Use PM_PATH only for sandboxed tests or explicit tracker roots.\",\n \"Pass --force only when root-level tracker files are intentional.\",\n ],\n recovery: {\n next_best_command: `pm --pm-path ${nestedTracker} init --yes`,\n },\n },\n );\n}\n\nasync function ensureInitDirectories(pmRoot: string, subdirs: readonly string[]): Promise<{\n createdDirs: string[];\n warnings: string[];\n}> {\n const createdDirs: string[] = [];\n const warnings: string[] = [];\n for (const subdir of subdirs) {\n const target = subdir ? path.join(pmRoot, subdir) : pmRoot;\n const existed = await pathExists(target);\n await fs.mkdir(target, { recursive: true });\n if (existed) {\n warnings.push(`already_exists:${target}`);\n } else {\n createdDirs.push(target);\n }\n warnings.push(\n ...(await runActiveOnWriteHooks({\n path: target,\n scope: \"project\",\n op: \"init:ensure_dir\",\n })),\n );\n }\n return { createdDirs, warnings };\n}\n\nasync function runInitWizard(initialPrefix: string, telemetryDefault: boolean): Promise<{\n prefix: string;\n preset: BuiltinGovernancePreset;\n telemetry_enabled: boolean;\n}> {\n const rl = createInitReadlineInterface();\n try {\n output.write(\"pm init setup wizard (agent-optimized)\\n\");\n output.write(\"This walkthrough is non-destructive and each choice can be changed later with pm config.\\n\\n\");\n\n output.write(\"1/3 Item ID prefix\\n\");\n output.write(\"Prefix is prepended to generated IDs (for example pm-a1b2).\\n\");\n const prefixAnswer = await rl.question(`Item ID prefix [${initialPrefix}]: `);\n const resolvedPrefix = prefixAnswer.trim().length > 0 ? normalizePrefix(prefixAnswer) : initialPrefix;\n\n output.write(\"\\n2/3 Governance preset\\n\");\n output.write(\"minimal: no ownership blocking, progressive create defaults, close validation off.\\n\");\n output.write(\"default: ownership conflict warnings, progressive create defaults, close validation warn.\\n\");\n output.write(\"strict: ownership blocking, strict create defaults, close validation strict.\\n\");\n const presetAnswer = await rl.question(\"Governance preset [minimal/default/strict] (default: minimal): \");\n const presetChoice = presetAnswer.trim().length > 0 ? presetAnswer.trim() : \"minimal\";\n // The wizard is forgiving: a typo'd/unknown preset defaults to minimal with a\n // notice instead of throwing and aborting an in-progress interactive setup.\n // normalizeInitGovernancePreset returns a concrete preset for valid input and\n // throws (never returns undefined) for invalid non-empty input, so the result is\n // always a BuiltinGovernancePreset on the success path.\n let resolvedPreset: BuiltinGovernancePreset = \"minimal\";\n try {\n resolvedPreset = normalizeInitGovernancePreset(presetChoice) as BuiltinGovernancePreset;\n } catch {\n output.write(`Unrecognized governance preset \"${presetChoice}\"; using minimal.\\n`);\n }\n\n output.write(\"\\n3/3 Project telemetry\\n\");\n output.write(\"Telemetry helps improve reliability and can be disabled anytime via pm config.\\n\");\n const telemetryLabel = telemetryDefault ? \"Y/n\" : \"y/N\";\n const telemetryAnswer = await rl.question(`Enable telemetry for this project? [${telemetryLabel}] `);\n const telemetryEnabled = parseYesNoChoice(telemetryAnswer, telemetryDefault);\n\n output.write(\"\\n\");\n return {\n prefix: resolvedPrefix,\n preset: resolvedPreset,\n telemetry_enabled: telemetryEnabled,\n };\n } finally {\n rl.close();\n }\n}\n\nfunction normalizeInitCommandOptions(options: InitCommandOptions): InitNormalizedOptions {\n return {\n presetFromOption: normalizeInitGovernancePreset(options.preset),\n useDefaults: options.defaults === true,\n authorFromOption: normalizeOptionalInitAuthor(options.author),\n installBundledPackages: options.withPackages === true,\n agentGuidanceMode: normalizeInitAgentGuidanceMode(options.agentGuidance),\n typePreset: normalizeInitTypePreset(options.typePreset),\n };\n}\n\nfunction collectExistingSettingsPendingChanges(params: {\n settings: PmSettings;\n normalizedPrefix: string;\n prefixArg: string | undefined;\n presetFromOption: BuiltinGovernancePreset | undefined;\n authorFromOption: string | undefined;\n}): string[] {\n const pendingChanges: string[] = [];\n if (params.prefixArg !== undefined && params.settings.id_prefix !== params.normalizedPrefix) {\n pendingChanges.push(\"id_prefix\");\n }\n if (params.presetFromOption !== undefined && params.settings.governance.preset !== params.presetFromOption) {\n pendingChanges.push(\"governance_preset\");\n }\n if (params.authorFromOption !== undefined && params.settings.author_default !== params.authorFromOption) {\n pendingChanges.push(\"author_default\");\n }\n return pendingChanges;\n}\n\nfunction assertExistingSettingsUpdateAllowed(settingsPath: string, pendingChanges: string[], force: boolean): void {\n if (pendingChanges.length === 0 || force) {\n return;\n }\n throw new PmCliError(\n `Refusing to update existing tracker settings at ${settingsPath} without --force.`,\n EXIT_CODE.USAGE,\n {\n code: \"init_existing_settings_requires_force\",\n type: \"urn:pm-cli:error:init_existing_settings_requires_force\",\n required: `--force for ${pendingChanges.join(\", \")}`,\n why: \"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.\",\n examples: [\n \"pm init --yes\",\n \"pm init ./sandbox-pm --yes\",\n \"pm init acme --yes --force\",\n ],\n nextSteps: [\n \"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.\",\n \"If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force.\",\n ],\n },\n );\n}\n\nfunction applyExistingSettingsUpdates(params: {\n settings: PmSettings;\n normalizedPrefix: string;\n prefixArg: string | undefined;\n presetFromOption: BuiltinGovernancePreset | undefined;\n authorFromOption: string | undefined;\n warnings: string[];\n}): boolean {\n let changed = false;\n if (params.prefixArg !== undefined && params.settings.id_prefix !== params.normalizedPrefix) {\n params.settings.id_prefix = params.normalizedPrefix;\n params.warnings.push(`updated:id_prefix:${params.normalizedPrefix}`);\n changed = true;\n }\n if (params.presetFromOption !== undefined && params.settings.governance.preset !== params.presetFromOption) {\n applyGovernancePreset(params.settings, params.presetFromOption);\n params.warnings.push(`updated:governance_preset:${params.presetFromOption}`);\n changed = true;\n }\n if (params.authorFromOption !== undefined && params.settings.author_default !== params.authorFromOption) {\n params.settings.author_default = params.authorFromOption;\n params.warnings.push(`updated:author_default:${params.authorFromOption}`);\n changed = true;\n }\n return changed;\n}\n\nasync function loadExistingInitSettings(params: {\n pmRoot: string;\n settingsPath: string;\n normalizedPrefix: string;\n prefixArg: string | undefined;\n options: InitCommandOptions;\n normalizedOptions: InitNormalizedOptions;\n warnings: string[];\n}): Promise<InitSettingsResolution> {\n const settings = await readSettings(params.pmRoot);\n params.warnings.push(`already_exists:${params.settingsPath}`);\n const pendingChanges = collectExistingSettingsPendingChanges({\n settings,\n normalizedPrefix: params.normalizedPrefix,\n prefixArg: params.prefixArg,\n presetFromOption: params.normalizedOptions.presetFromOption,\n authorFromOption: params.normalizedOptions.authorFromOption,\n });\n assertExistingSettingsUpdateAllowed(params.settingsPath, pendingChanges, params.options.force === true);\n if (\n applyExistingSettingsUpdates({\n settings,\n normalizedPrefix: params.normalizedPrefix,\n prefixArg: params.prefixArg,\n presetFromOption: params.normalizedOptions.presetFromOption,\n authorFromOption: params.normalizedOptions.authorFromOption,\n warnings: params.warnings,\n })\n ) {\n await writeSettings(params.pmRoot, settings);\n }\n return {\n settings,\n normalizedPrefix: params.normalizedPrefix,\n chosenPreset: params.normalizedOptions.presetFromOption,\n wizardUsed: false,\n };\n}\n\nasync function createNewInitSettings(params: {\n pmRoot: string;\n normalizedPrefix: string;\n normalizedOptions: InitNormalizedOptions;\n}): Promise<InitSettingsResolution> {\n let normalizedPrefix = params.normalizedPrefix;\n let chosenPreset = params.normalizedOptions.presetFromOption;\n let chosenTelemetryEnabled: boolean | undefined;\n let wizardUsed = false;\n if (\n params.normalizedOptions.presetFromOption === undefined &&\n !params.normalizedOptions.useDefaults &&\n process.stdin.isTTY === true &&\n process.stdout.isTTY === true\n ) {\n const wizardChoices = await runInitWizard(normalizedPrefix, SETTINGS_DEFAULTS.telemetry.enabled);\n normalizedPrefix = wizardChoices.prefix;\n chosenPreset = wizardChoices.preset;\n chosenTelemetryEnabled = wizardChoices.telemetry_enabled;\n wizardUsed = true;\n }\n const effectivePreset = chosenPreset ?? \"minimal\";\n const settings = cloneDefaults();\n settings.id_prefix = normalizedPrefix;\n applyGovernancePreset(settings, effectivePreset);\n if (params.normalizedOptions.authorFromOption !== undefined) {\n settings.author_default = params.normalizedOptions.authorFromOption;\n }\n if (chosenTelemetryEnabled !== undefined) {\n settings.telemetry.enabled = chosenTelemetryEnabled;\n settings.telemetry.first_run_prompt_completed = true;\n }\n await writeSettings(params.pmRoot, settings);\n return {\n settings,\n normalizedPrefix,\n chosenPreset,\n wizardUsed,\n };\n}\n\nasync function resolveInitSettings(params: {\n pmRoot: string;\n settingsPath: string;\n settingsExists: boolean;\n normalizedPrefix: string;\n prefixArg: string | undefined;\n options: InitCommandOptions;\n normalizedOptions: InitNormalizedOptions;\n warnings: string[];\n}): Promise<InitSettingsResolution> {\n if (params.settingsExists) {\n return await loadExistingInitSettings(params);\n }\n return await createNewInitSettings({\n pmRoot: params.pmRoot,\n normalizedPrefix: params.normalizedPrefix,\n normalizedOptions: params.normalizedOptions,\n });\n}\n\nasync function applyInitAgentGuidance(params: {\n pmRoot: string;\n cwd: string;\n agentGuidanceMode: InitAgentGuidanceMode;\n settings: PmSettings;\n warnings: string[];\n}): Promise<InitAgentGuidanceResult> {\n const agentGuidanceResult = await runInitAgentGuidance({\n pm_root: params.pmRoot,\n cwd: params.cwd,\n mode: params.agentGuidanceMode,\n interactive: process.stdin.isTTY === true && process.stdout.isTTY === true,\n settings: params.settings,\n });\n params.warnings.push(...agentGuidanceResult.warnings);\n if (agentGuidanceResult.settings_changed) {\n await writeSettings(params.pmRoot, params.settings);\n }\n return {\n ...agentGuidanceResult.summary,\n next_steps: agentGuidanceResult.next_steps,\n };\n}\n\nasync function ensureInitRuntimeSchemaFiles(\n pmRoot: string,\n settings: PmSettings,\n): Promise<{\n createdDirs: string[];\n warnings: string[];\n}> {\n const createdDirs: string[] = [];\n const warnings: string[] = [];\n const runtimeSchemaScaffold = await ensureRuntimeSchemaFileScaffold(pmRoot, settings.schema);\n for (const createdPath of runtimeSchemaScaffold.created_paths) {\n createdDirs.push(createdPath);\n warnings.push(\n ...(await runActiveOnWriteHooks({\n path: createdPath,\n scope: \"project\",\n op: \"init:runtime_schema_file\",\n })),\n );\n }\n return { createdDirs, warnings };\n}\n\nasync function maybeRegisterInitTypePreset(params: {\n pmRoot: string;\n settings: PmSettings;\n typePreset: InitTypePresetName | undefined;\n warnings: string[];\n}): Promise<InitRegisteredTypePresetSummary | undefined> {\n if (params.typePreset === undefined) {\n return undefined;\n }\n const registeredTypePreset = await registerInitTypePreset(params.pmRoot, params.settings, params.typePreset);\n params.warnings.push(`registered_type_preset:${params.typePreset}`);\n params.warnings.push(\n ...(await runActiveOnWriteHooks({\n path: registeredTypePreset.file,\n scope: \"project\",\n op: \"init:type_preset\",\n })),\n );\n return registeredTypePreset;\n}\n\nasync function ensureInitTypeDirectories(params: {\n pmRoot: string;\n settings: PmSettings;\n createdDirs: string[];\n warnings: string[];\n}): Promise<void> {\n const typeRegistry = resolveItemTypeRegistry(params.settings, getActiveExtensionRegistrations());\n const customTypeFolders = typeRegistry.folders.filter((folder) => !(PM_REQUIRED_SUBDIRS as readonly string[]).includes(folder));\n const scaffold = await ensureInitDirectories(params.pmRoot, customTypeFolders);\n params.createdDirs.push(...scaffold.createdDirs);\n params.warnings.push(...scaffold.warnings);\n}\n\nasync function maybeInstallInitBundledPackages(\n installBundledPackages: boolean,\n global: GlobalOptions,\n warnings: string[],\n): Promise<InitInstalledPackagesSummary | undefined> {\n if (!installBundledPackages) {\n return undefined;\n }\n const packageInstallResult = await runExtension(\"all\", { install: true, project: true }, global);\n warnings.push(...packageInstallResult.warnings);\n const installedPackages = summarizeInstalledPackages(packageInstallResult);\n if (!installedPackages.installed_all || installedPackages.packages.some((entry) => !entry.ok)) {\n throw new PmCliError(\"pm init --with-packages did not install all bundled packages successfully.\", EXIT_CODE.GENERIC_FAILURE);\n }\n return installedPackages;\n}\n\nfunction buildInitNextSteps(params: {\n installBundledPackages: boolean;\n registeredTypePreset: InitRegisteredTypePresetSummary | undefined;\n agentGuidanceNextSteps: string[];\n}): string[] {\n const nextSteps: string[] = [\n 'Create your first item: pm create --type Task --title \"<title>\"',\n 'List active items: pm list',\n 'Get agent-friendly project context: pm context',\n ];\n if (!params.installBundledPackages) {\n nextSteps.push(\n \"Add optional packages for richer workflows: pm install calendar --project, pm install templates --project, pm install guide-shell --project\",\n );\n nextSteps.push(\"Or install everything bundled: pm init --with-packages (idempotent on re-run)\");\n } else {\n nextSteps.push(\"Explore newly-available commands: pm cal, pm templates, pm guide\");\n }\n if (params.registeredTypePreset) {\n nextSteps.push(`Inspect registered preset types: pm schema list, pm schema show ${params.registeredTypePreset.registered[0] ?? params.registeredTypePreset.updated[0]}`);\n }\n nextSteps.push(\"Set PM_AUTHOR=<your-agent-id> so mutations attribute to the right caller.\");\n for (const guidanceNextStep of params.agentGuidanceNextSteps) {\n if (!nextSteps.includes(guidanceNextStep)) {\n nextSteps.push(guidanceNextStep);\n }\n }\n return nextSteps;\n}\n\n/**\n * Implements run init for the public runtime surface of this module.\n */\nexport async function runInit(\n prefixArg: string | undefined,\n global: GlobalOptions,\n options: InitCommandOptions = {},\n): Promise<InitResult> {\n const cwd = process.cwd();\n const invocation = resolveInitInvocation(cwd, global, prefixArg);\n const pmRoot = invocation.pmRoot;\n prefixArg = invocation.prefixArg;\n await assertExplicitTrackerPathIsNotWorkspaceRoot(pmRoot, global, options.force === true);\n const createdDirs: string[] = [];\n const warnings: string[] = [];\n const baseDirs = await ensureInitDirectories(pmRoot, PM_REQUIRED_SUBDIRS);\n createdDirs.push(...baseDirs.createdDirs);\n warnings.push(...baseDirs.warnings);\n\n const settingsPath = path.join(pmRoot, \"settings.json\");\n const settingsExists = await pathExists(settingsPath);\n const normalizedOptions = normalizeInitCommandOptions(options);\n const settingsResolution = await resolveInitSettings({\n pmRoot,\n settingsPath,\n settingsExists,\n normalizedPrefix: normalizePrefix(prefixArg),\n prefixArg,\n options,\n normalizedOptions,\n warnings,\n });\n let { settings } = settingsResolution;\n\n const agentGuidance = await applyInitAgentGuidance({\n pmRoot,\n cwd,\n agentGuidanceMode: normalizedOptions.agentGuidanceMode,\n settings,\n warnings,\n });\n\n const schemaFiles = await ensureInitRuntimeSchemaFiles(pmRoot, settings);\n createdDirs.push(...schemaFiles.createdDirs);\n warnings.push(...schemaFiles.warnings);\n\n const registeredTypePreset = await maybeRegisterInitTypePreset({\n pmRoot,\n settings,\n typePreset: normalizedOptions.typePreset,\n warnings,\n });\n if (registeredTypePreset) {\n settings = await readSettings(pmRoot);\n }\n\n await ensureInitTypeDirectories({ pmRoot, settings, createdDirs, warnings });\n const installedPackages = await maybeInstallInitBundledPackages(normalizedOptions.installBundledPackages, global, warnings);\n\n const nextSteps = buildInitNextSteps({\n installBundledPackages: normalizedOptions.installBundledPackages,\n registeredTypePreset,\n agentGuidanceNextSteps: agentGuidance.next_steps,\n });\n\n return {\n ok: true,\n path: pmRoot,\n settings,\n created_dirs: createdDirs,\n warnings,\n governance_preset: settings.governance.preset,\n wizard_used: settingsResolution.wizardUsed,\n ...(registeredTypePreset ? { registered_type_preset: registeredTypePreset } : {}),\n ...(installedPackages ? { installed_packages: installedPackages } : {}),\n next_steps: nextSteps,\n agent_guidance: agentGuidance,\n };\n}\n", "/**\n * @module cli/commands/init-agent-guidance\n *\n * Implements the pm init agent guidance command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport readline from \"node:readline/promises\";\nimport { stdin as input, stdout as output } from \"node:process\";\nimport { runActiveOnWriteHooks } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport type { PmSettings } from \"../../types/index.js\";\n\n/**\n * Restricts init agent guidance mode values accepted by command, SDK, and storage contracts.\n */\nexport type InitAgentGuidanceMode = \"ask\" | \"add\" | \"skip\" | \"status\";\n\nexport const INIT_AGENT_GUIDANCE_MODE_VALUES: InitAgentGuidanceMode[] = [\"ask\", \"add\", \"skip\", \"status\"];\n\nconst AGENT_GUIDANCE_TARGET_FILENAMES = [\"AGENTS.md\", \"CLAUDE.md\"] as const;\nconst AGENT_GUIDANCE_REQUIRED_TOKENS = [\n \"pm init\",\n \"pm context\",\n \"pm search\",\n \"pm create\",\n \"pm claim\",\n \"pm files\",\n \"pm docs\",\n \"pm test --run\",\n \"pm close\",\n \"pm release\",\n \"pm_author\",\n] as const;\nconst AGENT_GUIDANCE_REQUIRED_TOKEN_THRESHOLD = 8;\nconst AGENT_GUIDANCE_TEMPLATE_VERSION = 1;\nconst AGENT_GUIDANCE_START_MARKER_PREFIX = \"<!-- pm-cli:agent-guidance:start:\";\nconst AGENT_GUIDANCE_START_MARKER = `<!-- pm-cli:agent-guidance:start:v${AGENT_GUIDANCE_TEMPLATE_VERSION} -->`;\nconst AGENT_GUIDANCE_END_MARKER = \"<!-- pm-cli:agent-guidance:end -->\";\nconst AGENT_GUIDANCE_ADD_LATER_HINT = \"Add workflow guidance later: pm init --agent-guidance add\";\n\nexport const _testOnly = {\n toPortableRelativePath,\n ensureTrailingNewline,\n detectLineEnding,\n findGuidanceBlockRange,\n buildAgentGuidanceBlock,\n upsertAgentGuidanceBlock,\n resolveProjectRoot,\n resolveTargetGuidancePath,\n parsePromptChoice,\n pushUnique,\n promptForGuidanceWrite,\n normalizeAgentGuidanceState,\n applyAgentGuidanceState,\n writeGuidanceFile,\n setAgentGuidanceReadlineFactoryForTests,\n};\n\ntype AgentGuidanceReadlineInterface = ReturnType<typeof readline.createInterface>;\nlet createAgentGuidanceReadlineInterface = (): AgentGuidanceReadlineInterface => readline.createInterface({ input, output });\n\nfunction setAgentGuidanceReadlineFactoryForTests(factory: (() => AgentGuidanceReadlineInterface) | undefined): void {\n createAgentGuidanceReadlineInterface = factory ?? (() => readline.createInterface({ input, output }));\n}\n\ninterface AgentGuidanceFileScan {\n file_path: string;\n exists: boolean;\n has_guidance: boolean;\n has_marker: boolean;\n}\n\ninterface AgentGuidanceBlockRange {\n start_index: number;\n end_index: number;\n}\n\n/**\n * Documents the init agent guidance summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface InitAgentGuidanceSummary {\n mode: InitAgentGuidanceMode;\n present: boolean;\n prompted: boolean;\n applied: boolean;\n skipped: boolean;\n declined: boolean;\n prompt_completed: boolean;\n template_version: number;\n target_file: string;\n checked_files: string[];\n files_with_guidance: string[];\n missing_files: string[];\n}\n\n/**\n * Documents the run init agent guidance options payload exchanged by command, SDK, and package integrations.\n */\nexport interface RunInitAgentGuidanceOptions {\n pm_root: string;\n cwd: string;\n mode: InitAgentGuidanceMode;\n interactive: boolean;\n settings: PmSettings;\n}\n\n/**\n * Documents the run init agent guidance result payload exchanged by command, SDK, and package integrations.\n */\nexport interface RunInitAgentGuidanceResult {\n summary: InitAgentGuidanceSummary;\n warnings: string[];\n next_steps: string[];\n settings_changed: boolean;\n}\n\nfunction toPortableRelativePath(projectRoot: string, targetPath: string): string {\n const relative = path.relative(projectRoot, targetPath);\n if (relative.length === 0) {\n return path.basename(targetPath);\n }\n return relative.split(path.sep).join(\"/\");\n}\n\nfunction ensureTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nfunction detectLineEnding(value: string): \"\\n\" | \"\\r\\n\" {\n return value.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n}\n\nfunction findGuidanceBlockRange(content: string): AgentGuidanceBlockRange | null {\n const startIndex = content.indexOf(AGENT_GUIDANCE_START_MARKER_PREFIX);\n if (startIndex === -1) {\n return null;\n }\n const endMarkerIndex = content.indexOf(AGENT_GUIDANCE_END_MARKER, startIndex);\n if (endMarkerIndex === -1) {\n return null;\n }\n return {\n start_index: startIndex,\n end_index: endMarkerIndex + AGENT_GUIDANCE_END_MARKER.length,\n };\n}\n\nfunction hasGuidanceMarker(content: string): boolean {\n return findGuidanceBlockRange(content) !== null;\n}\n\nfunction buildAgentGuidanceBlock(lineEnding: \"\\n\" | \"\\r\\n\"): string {\n const lines = [\n AGENT_GUIDANCE_START_MARKER,\n \"## pm Workflow (Agent Quickstart)\",\n \"\",\n \"- Orient before mutate: `pm context --limit 10`, `pm search \\\"<keywords>\\\" --limit 10`, `pm list-open --limit 20`.\",\n \"- Claim and execute: `pm claim <id>` then `pm update <id> --status in_progress`.\",\n \"- Link evidence while coding: `pm files <id> --add ...`, `pm docs <id> --add ...`, `pm test <id> --add command=\\\"node scripts/run-tests.mjs test -- ...\\\"`.\",\n \"- Verify and close: `pm test <id> --run --progress`, `pm close <id> \\\"<evidence>\\\" --validate-close warn`, `pm release <id>`.\",\n \"- Set `PM_AUTHOR=<stable-agent-id>` before mutation commands.\",\n \"\",\n AGENT_GUIDANCE_END_MARKER,\n \"\",\n ];\n return lines.join(lineEnding);\n}\n\nfunction upsertAgentGuidanceBlock(existingContent: string): { next_content: string; changed: boolean } {\n const lineEnding = detectLineEnding(existingContent);\n const nextBlock = buildAgentGuidanceBlock(lineEnding);\n const existingRange = findGuidanceBlockRange(existingContent);\n if (existingRange) {\n const trailingContent = existingContent.slice(existingRange.end_index);\n const normalizedTrailingContent = trailingContent.startsWith(\"\\r\\n\")\n ? trailingContent.slice(2)\n : trailingContent.startsWith(\"\\n\")\n ? trailingContent.slice(1)\n : trailingContent;\n const nextContent = ensureTrailingNewline(\n `${existingContent.slice(0, existingRange.start_index)}${nextBlock}${normalizedTrailingContent}`,\n );\n return {\n next_content: nextContent,\n changed: nextContent !== existingContent,\n };\n }\n const separator = existingContent.length === 0 ? \"\" : existingContent.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const nextContent = ensureTrailingNewline(`${existingContent}${separator}${nextBlock}`);\n return {\n next_content: nextContent,\n changed: nextContent !== existingContent,\n };\n}\n\nfunction resolveProjectRoot(pmRoot: string, cwd: string): string {\n const parent = path.dirname(pmRoot);\n if (path.basename(pmRoot) === \"pm\" && path.basename(parent) === \".agents\") {\n return path.dirname(parent);\n }\n return path.resolve(cwd, pmRoot);\n}\n\nfunction resolveTargetGuidancePath(scans: AgentGuidanceFileScan[], projectRoot: string): string {\n const existingAgents = scans.find((entry) => path.basename(entry.file_path) === \"AGENTS.md\" && entry.exists);\n if (existingAgents) {\n return existingAgents.file_path;\n }\n const existingAny = scans.find((entry) => entry.exists);\n if (existingAny) {\n return existingAny.file_path;\n }\n return path.join(projectRoot, \"AGENTS.md\");\n}\n\nfunction parsePromptChoice(answer: string, currentDefault: boolean): boolean {\n const normalized = answer.trim().toLowerCase();\n if (normalized.length === 0) {\n return currentDefault;\n }\n if (normalized === \"y\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"n\" || normalized === \"no\") {\n return false;\n }\n return currentDefault;\n}\n\nasync function promptForGuidanceWrite(targetRelativePath: string): Promise<boolean> {\n const rl = createAgentGuidanceReadlineInterface();\n try {\n output.write(\"\\nAgent guidance check\\n\");\n output.write(\"No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.\\n\");\n const answer = await rl.question(`Add a compact pm workflow section to ${targetRelativePath}? [Y/n] `);\n output.write(\"\\n\");\n return parsePromptChoice(answer, true);\n } finally {\n rl.close();\n }\n}\n\nfunction normalizeAgentGuidanceState(settings: PmSettings): PmSettings[\"agent_guidance\"] {\n const current = settings.agent_guidance;\n return {\n prompt_completed: current?.prompt_completed === true,\n declined: current?.declined === true,\n declined_at: typeof current?.declined_at === \"string\" ? current.declined_at : \"\",\n template_version:\n typeof current?.template_version === \"number\" && Number.isInteger(current.template_version) && current.template_version > 0\n ? current.template_version\n : AGENT_GUIDANCE_TEMPLATE_VERSION,\n last_checked_files: Array.isArray(current?.last_checked_files)\n ? [...new Set(current.last_checked_files.map((value) => value.trim()).filter((value) => value.length > 0))].sort(\n (left, right) => left.localeCompare(right),\n )\n : [],\n };\n}\n\nasync function scanGuidanceFiles(projectRoot: string): Promise<AgentGuidanceFileScan[]> {\n const scans: AgentGuidanceFileScan[] = [];\n for (const filename of AGENT_GUIDANCE_TARGET_FILENAMES) {\n const filePath = path.join(projectRoot, filename);\n const exists = await pathExists(filePath);\n if (!exists) {\n scans.push({\n file_path: filePath,\n exists,\n has_guidance: false,\n has_marker: false,\n });\n continue;\n }\n const content = await fs.readFile(filePath, \"utf8\");\n const contentLower = content.toLowerCase();\n const tokenHits = AGENT_GUIDANCE_REQUIRED_TOKENS.filter((token) => contentLower.includes(token));\n const hasMarker = hasGuidanceMarker(content);\n scans.push({\n file_path: filePath,\n exists,\n has_guidance: hasMarker || tokenHits.length >= AGENT_GUIDANCE_REQUIRED_TOKEN_THRESHOLD,\n has_marker: hasMarker,\n });\n }\n return scans;\n}\n\nfunction pushUnique(target: string[], value: string): void {\n if (!target.includes(value)) {\n target.push(value);\n }\n}\n\nfunction applyAgentGuidanceState(\n settings: PmSettings,\n currentState: PmSettings[\"agent_guidance\"],\n): { changed: boolean; state: PmSettings[\"agent_guidance\"] } {\n const existing = normalizeAgentGuidanceState(settings);\n const changed = JSON.stringify(existing) !== JSON.stringify(currentState);\n if (changed) {\n settings.agent_guidance = currentState;\n }\n return { changed, state: currentState };\n}\n\nasync function writeGuidanceFile(filePath: string): Promise<{ changed: boolean; warnings: string[] }> {\n const exists = await pathExists(filePath);\n const currentContent = exists ? await fs.readFile(filePath, \"utf8\") : \"\";\n const nextContent = upsertAgentGuidanceBlock(currentContent);\n if (!nextContent.changed) {\n return { changed: false, warnings: [] };\n }\n await fs.writeFile(filePath, nextContent.next_content, \"utf8\");\n return {\n changed: true,\n warnings: await runActiveOnWriteHooks({\n path: filePath,\n scope: \"project\",\n op: \"init:agent_guidance_file\",\n }),\n };\n}\n\nfunction buildInitAgentGuidanceSummary(params: {\n mode: InitAgentGuidanceMode;\n scans: AgentGuidanceFileScan[];\n projectRoot: string;\n targetRelativePath: string;\n prompted: boolean;\n applied: boolean;\n skipped: boolean;\n state: PmSettings[\"agent_guidance\"];\n}): InitAgentGuidanceSummary {\n return {\n mode: params.mode,\n present: params.scans.some((entry) => entry.has_guidance),\n prompted: params.prompted,\n applied: params.applied,\n skipped: params.skipped,\n declined: params.state.declined,\n prompt_completed: params.state.prompt_completed,\n template_version: params.state.template_version,\n target_file: params.targetRelativePath,\n checked_files: params.scans.map((entry) => toPortableRelativePath(params.projectRoot, entry.file_path)),\n files_with_guidance: params.scans\n .filter((entry) => entry.has_guidance)\n .map((entry) => toPortableRelativePath(params.projectRoot, entry.file_path)),\n missing_files: params.scans\n .filter((entry) => !entry.exists)\n .map((entry) => toPortableRelativePath(params.projectRoot, entry.file_path)),\n };\n}\n\nasync function refreshGuidanceScansAfterApply(\n applied: boolean,\n scans: AgentGuidanceFileScan[],\n projectRoot: string,\n): Promise<AgentGuidanceFileScan[]> {\n return applied ? await scanGuidanceFiles(projectRoot) : scans;\n}\n\ninterface InitAgentGuidanceFlowState {\n warnings: string[];\n nextSteps: string[];\n prompted: boolean;\n applied: boolean;\n skipped: boolean;\n state: PmSettings[\"agent_guidance\"];\n}\n\ninterface InitAgentGuidanceModeContext {\n mode: InitAgentGuidanceMode;\n interactive: boolean;\n targetPath: string;\n targetRelativePath: string;\n checkedFiles: string[];\n presentBefore: boolean;\n}\n\nfunction markAgentGuidanceRunState(\n flow: InitAgentGuidanceFlowState,\n checkedFiles: string[],\n partial: Partial<PmSettings[\"agent_guidance\"]>,\n): void {\n flow.state = {\n ...flow.state,\n ...partial,\n template_version: AGENT_GUIDANCE_TEMPLATE_VERSION,\n last_checked_files: checkedFiles,\n };\n}\n\nasync function addAgentGuidanceBlockIfMissing(\n flow: InitAgentGuidanceFlowState,\n context: Pick<InitAgentGuidanceModeContext, \"presentBefore\" | \"targetPath\" | \"targetRelativePath\">,\n): Promise<void> {\n if (context.presentBefore) {\n return;\n }\n const writeResult = await writeGuidanceFile(context.targetPath);\n flow.warnings.push(...writeResult.warnings);\n if (writeResult.changed) {\n flow.applied = true;\n flow.warnings.push(`agent_guidance:added:${context.targetRelativePath}`);\n }\n}\n\nfunction handleAgentGuidanceStatusMode(flow: InitAgentGuidanceFlowState, presentBefore: boolean): void {\n if (!presentBefore) {\n flow.warnings.push(\"agent_guidance:missing\");\n pushUnique(flow.nextSteps, AGENT_GUIDANCE_ADD_LATER_HINT);\n }\n}\n\nfunction handleAgentGuidanceSkipMode(flow: InitAgentGuidanceFlowState, checkedFiles: string[]): void {\n flow.skipped = true;\n markAgentGuidanceRunState(flow, checkedFiles, {\n prompt_completed: true,\n declined: true,\n declined_at: flow.state.declined_at || new Date().toISOString(),\n });\n flow.warnings.push(\"agent_guidance:explicit_skip\");\n pushUnique(flow.nextSteps, AGENT_GUIDANCE_ADD_LATER_HINT);\n}\n\nasync function handleAgentGuidanceAddMode(\n flow: InitAgentGuidanceFlowState,\n context: InitAgentGuidanceModeContext,\n): Promise<void> {\n await addAgentGuidanceBlockIfMissing(flow, context);\n markAgentGuidanceRunState(flow, context.checkedFiles, {\n prompt_completed: true,\n declined: false,\n declined_at: \"\",\n });\n}\n\nfunction handlePresentAgentGuidance(flow: InitAgentGuidanceFlowState, checkedFiles: string[]): void {\n if (flow.state.declined) {\n markAgentGuidanceRunState(flow, checkedFiles, {\n prompt_completed: true,\n declined: false,\n declined_at: \"\",\n });\n }\n}\n\nfunction handleDeclinedAgentGuidance(flow: InitAgentGuidanceFlowState): void {\n flow.skipped = true;\n flow.warnings.push(\"agent_guidance:skipped_declined\");\n pushUnique(flow.nextSteps, AGENT_GUIDANCE_ADD_LATER_HINT);\n}\n\nasync function handleInteractiveAgentGuidancePrompt(\n flow: InitAgentGuidanceFlowState,\n context: InitAgentGuidanceModeContext,\n): Promise<void> {\n flow.prompted = true;\n const approved = await promptForGuidanceWrite(context.targetRelativePath);\n if (approved) {\n await addAgentGuidanceBlockIfMissing(flow, context);\n markAgentGuidanceRunState(flow, context.checkedFiles, {\n prompt_completed: true,\n declined: false,\n declined_at: \"\",\n });\n return;\n }\n flow.skipped = true;\n markAgentGuidanceRunState(flow, context.checkedFiles, {\n prompt_completed: true,\n declined: true,\n declined_at: new Date().toISOString(),\n });\n flow.warnings.push(\"agent_guidance:declined\");\n pushUnique(flow.nextSteps, AGENT_GUIDANCE_ADD_LATER_HINT);\n}\n\nfunction handleNonInteractiveMissingAgentGuidance(flow: InitAgentGuidanceFlowState): void {\n flow.warnings.push(\"agent_guidance:missing_non_interactive\");\n pushUnique(flow.nextSteps, AGENT_GUIDANCE_ADD_LATER_HINT);\n}\n\nasync function applyAgentGuidanceMode(\n initialState: PmSettings[\"agent_guidance\"],\n context: InitAgentGuidanceModeContext,\n): Promise<InitAgentGuidanceFlowState> {\n const flow: InitAgentGuidanceFlowState = {\n warnings: [],\n nextSteps: [],\n prompted: false,\n applied: false,\n skipped: false,\n state: initialState,\n };\n\n if (context.mode === \"status\") {\n handleAgentGuidanceStatusMode(flow, context.presentBefore);\n return flow;\n }\n if (context.mode === \"skip\") {\n handleAgentGuidanceSkipMode(flow, context.checkedFiles);\n return flow;\n }\n if (context.mode === \"add\") {\n await handleAgentGuidanceAddMode(flow, context);\n return flow;\n }\n if (context.presentBefore) {\n handlePresentAgentGuidance(flow, context.checkedFiles);\n return flow;\n }\n if (flow.state.prompt_completed && flow.state.declined) {\n handleDeclinedAgentGuidance(flow);\n return flow;\n }\n if (context.interactive) {\n await handleInteractiveAgentGuidancePrompt(flow, context);\n return flow;\n }\n handleNonInteractiveMissingAgentGuidance(flow);\n return flow;\n}\n\n/**\n * Implements run init agent guidance for the public runtime surface of this module.\n */\nexport async function runInitAgentGuidance(options: RunInitAgentGuidanceOptions): Promise<RunInitAgentGuidanceResult> {\n const projectRoot = resolveProjectRoot(options.pm_root, options.cwd);\n let scans = await scanGuidanceFiles(projectRoot);\n const targetPath = resolveTargetGuidancePath(scans, projectRoot);\n const targetRelativePath = toPortableRelativePath(projectRoot, targetPath);\n const checkedFiles = scans.map((entry) => toPortableRelativePath(projectRoot, entry.file_path));\n const presentBefore = scans.some((entry) => entry.has_guidance);\n const flow = await applyAgentGuidanceMode(normalizeAgentGuidanceState(options.settings), {\n mode: options.mode,\n interactive: options.interactive,\n targetPath,\n targetRelativePath,\n checkedFiles,\n presentBefore,\n });\n\n const stateUpdate = applyAgentGuidanceState(options.settings, flow.state);\n scans = await refreshGuidanceScansAfterApply(flow.applied, scans, projectRoot);\n\n const summary = buildInitAgentGuidanceSummary({\n mode: options.mode,\n scans,\n projectRoot,\n targetRelativePath,\n prompted: flow.prompted,\n applied: flow.applied,\n skipped: flow.skipped,\n state: flow.state,\n });\n\n return {\n summary,\n warnings: flow.warnings,\n next_steps: flow.nextSteps,\n settings_changed: stateUpdate.changed,\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;;;;;;;;AAMV,IAAM,4BAA4B;EACvC;EACA;EACA;EACA;EACA;;AA8DK,IAAM,yCACX,OAAO,OAAO;EACZ,YAAY,OAAO,OAAO;IACxB;IACA;IACA;IACA;GACD;EACD,MAAM,OAAO,OAAO;IAClB;IACA;GACD;EACD,UAAU,OAAO,OAAO;IACtB;IACA;GACD;EACD,QAAQ,OAAO,OAAO;IACpB;IACA;GAC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QF,IAAM,iCAAyF;EAC7F,UAAU,CAAC,UAAU;EACrB,OAAO,CAAC,YAAY,OAAO;EAC3B,QAAQ,CAAC,YAAY,QAAQ;EAC7B,WAAW,CAAC,YAAY,UAAU,WAAW;EAC7C,QAAQ,CAAC,YAAY,QAAQ;;;;EAI7B,SAAS,CAAC,YAAY,QAAQ;EAC9B,WAAW,CAAC,YAAY,WAAW;;;;EAInC,QAAQ,CAAC,YAAY,UAAU,QAAQ;EACvC,WAAW,CAAC,YAAY,WAAW;EACnC,UAAU,CAAC,YAAY,UAAU;;AAGnC,IAAM,mCAAgF;EACpF,UAAU;EACV,OAAO;EACP,QAAQ;EACR,WAAW;EACX,QAAQ;EACR,SAAS;EACT,WAAW;EACX,QAAQ;EACR,WAAW;EACX,UAAU;;AAGZ,IAAM,qBAAkE;EACtE,UAAU;EACV,OACE;EACF,QACE;EACF,WACE;EACF,QACE;EACF,SACE;EACF,WACE;EACF,QACE;EACF,WACE;EACF,UACE;;AAGJ,IAAM,sBAAmE;EACvE,UACE;EACF,OACE;EACF,QACE;EACF,WACE;EACF,QACE;EACF,SACE;EACF,WACE;EACF,QACE;EACF,WACE;EACF,UACE;;AAGJ,IAAM,kBAAkB;AAExB,IAAM,qCAA6F;EACjG,UAAU,CAAA;EACV,OAAO;IACL;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,UAAU;IACR;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;AAIJ,IAAM,uCAA+F;EACnG,UAAU,CAAA;EACV,OAAO;IACL;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,QAAQ;IACN;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,UAAU;IACR;IACA;IACA;IACA;IACA;IACA;IACA;;;AAMJ,IAAM,iCAAqF;EACzF,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;AAOJ,IAAM,mCAAuF;EAC3F,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;AAQJ,IAAM,oCAAwF;EAC5F,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;EAEF,WAAW;IACT;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;AAWJ,SAAS,4BAA4B,YAAyC,YAAmC;AAC/G,MAAI,eAAe,UAAU;AAC3B,WAAO,wBAAwB,UAAU;EAC3C;AACA,MAAI,eAAe,WAAW;AAC5B,WAAO,wBAAwB,UAAU;EAC3C;AACA,SAAO,wBAAwB,UAAU,qGAAqG,UAAU;AAC1J;AAOA,SAAS,qCACP,YACA,YAAmC;AAEnC,MAAI,eAAe,UAAU;AAC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SAAS,CAAC;MACxD;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;;EAEJ;AACA,MAAI,eAAe,aAAa;AAC9B,WAAO;MACL,GAAG;MACH;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,+BAA+B,KAAK,UAAU,WAAW,CAAC;MAC1D;MACA;MACA,cAAc,KAAK,UAAU,GAAG,aAAa,IAAI,CAAC;MAClD;;EAEJ;AACA,MAAI,eAAe,UAAU;AAC3B,WAAO;;;;;;MAML;MACA,aAAa,KAAK,UAAU,WAAW,CAAC;MACxC;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,iBAAiB,KAAK,UAAU,aAAa,CAAC;MAC9C;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,wBAAwB,KAAK,UAAU,WAAW,CAAC;MACnD;MACA;MACA;MACA;MACA;MACA;MACA;;EAEJ;AACA,MAAI,eAAe,aAAa;AAC9B,WAAO;MACL,GAAG;MACH;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;;EAEJ;AACA,MAAI,eAAe,YAAY;AAC7B,WAAO;MACL,GAAG;MACH;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,+BAA+B,KAAK,UAAU,WAAW,CAAC;MAC1D;MACA;MACA,6BAA6B,KAAK,UAAU,aAAa,CAAC;MAC1D;;EAEJ;AACA,SAAO;IACL,GAAG;IACH;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;AAEJ;AAYA,SAAS,sBACP,eACA,aACA,YAAuC;AAEvC,QAAM,eAAe,eAAe;AACpC,QAAM,gBAAgB,eAAe;AACrC,QAAM,mBAAmB,eAAe;AACxC,QAAM,gBAAgB,eAAe;AACrC,QAAM,iBAAiB,eAAe;AACtC,QAAM,mBAAmB,eAAe;AACxC,QAAM,gBAAgB,eAAe;AACrC,QAAM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AAK,UAAU,uBAAuB,CAAC;IAChE;IACA,4BAA4B,KAAK,UAAU,uBAAuB,CAAC;IACnE;IACA;IACA;IACA,2CAA2C,mBAAmB;IAC9D,qDAAqD,mBAAmB;IACxE;IACA;IACA,QAAQ,KAAK,UAAU,GAAG,aAAa,yCAAyC,CAAC;IACjF;IACA;IACA;IACA;IACA;IACA;IACA,aAAa,KAAK,UAAU,aAAa,CAAC;IAC1C,qBAAqB,mBAAmB;IACxC;IACA;IACA;IACA;IACA;IACA;IACA,+DAA+D,KAAK,UAAU,WAAW,CAAC;IAC1F;IACA;IACA;IACA;IACA;IACA,0DAA0D,KAAK,UAAU,WAAW,CAAC;IACrF;IACA;IACA;IACA,iBAAiB,KAAK,UAAU,aAAa,CAAC;IAC9C,kBAAkB,KAAK,UAAU,WAAW,CAAC;;;IAG7C,GAAI,gBAAgB,CAAC,qBAAqB,IAAI,CAAA;IAC9C;IACA;IACA;IACA;IACA;IACA;IACA;IACA,GAAG;IACH;IACA;IACA,GAAG,oCAAoC,eAAe,aAAa,YAAY,mBAAmB;IAClG,KAAK,IAAI;AACb;AAcA,SAAS,8BACP,aACA,aACA,YAAuC;AAKvC,QAAM,iBAAiB,4BAA4B,YAAY,SAAS;AACxE,QAAM,oBAAoB,qCAAqC,YAAY,SAAS;AACpF,SAAO;IACL,KAAK,WAAW;IAChB;IACA;IACA;IACA;IACA;IACA;IACA,kGAA6F,sCAAsC,UAAU,CAAC;IAC9I;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAM,WAAW;IACjB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,4BAA4B,wCAAwC,UAAU,CAAC;IAC/E;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,GAAG;IACH;IACA;IACA;IACA,4EAA4E,yBAAyB;IACrG,oGAAoG,uBAAuB;IAC3H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C/E,UAAM,mBAAmB,oBAAoB,UAAU;AAIvD,UAAM,YAAY;MAChB;MACA;MACA;MACA;MACA,KAAK,IAAI;AACX,UAAM,QAAQ,0BAA0B,aAAa;AACrD,UAAM,uBAAuB,0BAA0B,UAAU;AACjE,UAAM,uBAAuB;MAC3B;MACA,YAAY,oBAAoB;MAChC;MACA;MACA,GAAG,0BAA0B,eAAe,aAAa,YAAY,KAAK;MAC1E;MACA;MACA;MACA,GAAG,2BAA2B,aAAa,YAAY,KAAK;MAC5D;MACA;MACA;MACA;MACA;MACA;;AAEF,UAAM,gBAAgB;MACpB,KAAK,WAAW;MAChB;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,MAAM,WAAW;MACjB;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,GAAG;MACH;MACA;MACA,GAAG,mCAAmC,UAAU;MAChD,GAAG,qCAAqC,YAAY,SAAS;MAC7D;MACA;MACA;MACA,4EAA4E,yBAAyB;MACrG,oGAAoG,uBAAuB;MAC3H;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA,KAAK,IAAI;AAKX,WAAO;MACL,gBAAgB;MAChB,iBAAiB;MACjB,YAAY,cAAc,2BAA2B,eAAe,aAAa,UAAU,IAAI;MAC/F,iBAAiB,cAAc,iCAAiC,eAAe,aAAa,UAAU,IAAI;MAC1G,iBAAiB;MACjB,cAAc;MACd,aAAa,cAAc,8BAA8B,aAAa,aAAa,UAAU,IAAI;;EAErG;AACA,QAAM,SAAS;IACb,KAAK,aAAa;IAClB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,MAAM,WAAW;IACjB;IACA;IACA,GAAG,qCAAqC,UAAU;IAClD,GAAG,qCAAqC,YAAY,WAAW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ACA,mBAAmB,kBAAkB;IACrC;IACA;GACD;AAED,QAAM,cAAc,MAAM,6BAA6B,QAAQ,QAAQ;AACvE,cAAY,KAAK,GAAG,YAAY,WAAW;AAC3C,WAAS,KAAK,GAAG,YAAY,QAAQ;AAErC,QAAM,uBAAuB,MAAM,4BAA4B;IAC7D;IACA;IACA,YAAY,kBAAkB;IAC9B;GACD;AACD,MAAI,sBAAsB;AACxB,eAAW,MAAM,aAAa,MAAM;EACtC;AAEA,QAAM,0BAA0B,EAAE,QAAQ,UAAU,aAAa,SAAQ,CAAE;AAC3E,QAAM,oBAAoB,MAAM,gCAAgC,kBAAkB,wBAAwBC,SAAQ,QAAQ;AAE1H,QAAM,YAAY,mBAAmB;IACnC,wBAAwB,kBAAkB;IAC1C;IACA,wBAAwB,cAAc;GACvC;AAED,SAAO;IACL,IAAI;IACJ,MAAM;IACN;IACA,cAAc;IACd;IACA,mBAAmB,SAAS,WAAW;IACvC,aAAa,mBAAmB;IAChC,GAAI,uBAAuB,EAAE,wBAAwB,qBAAoB,IAAK,CAAA;IAC9E,GAAI,oBAAoB,EAAE,oBAAoB,kBAAiB,IAAK,CAAA;IACpE,YAAY;IACZ,gBAAgB;;AAEpB;",
6
+ "names": ["fs", "path", "path", "fs", "execFile", "fs", "os", "path", "promisify", "fs", "path", "path", "fs", "fs", "path", "fs", "path", "path", "input", "packageRoot", "fs", "global", "input", "path", "fs", "execFileAsync", "promisify", "execFile", "path", "fs", "os", "global", "managedEntry", "output", "input", "fs", "path", "readline", "input", "output", "fs", "path", "path", "nextContent", "fs", "readline", "input", "output", "path", "global", "fs", "output"]
7
+ }