@unbrained/pm-cli 2026.7.13 → 2026.7.14

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 (487) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +28 -0
  3. package/dist/cli/commands/aggregate.d.ts +1 -1
  4. package/dist/cli/commands/aggregate.js +18 -6
  5. package/dist/cli/commands/aggregate.js.map +1 -1
  6. package/dist/cli/commands/context.d.ts +16 -1
  7. package/dist/cli/commands/context.js +98 -16
  8. package/dist/cli/commands/context.js.map +1 -1
  9. package/dist/cli/commands/create.d.ts +1 -1
  10. package/dist/cli/commands/create.js +11 -7
  11. package/dist/cli/commands/create.js.map +1 -1
  12. package/dist/cli/commands/deps.d.ts +6 -96
  13. package/dist/cli/commands/deps.js +4 -214
  14. package/dist/cli/commands/deps.js.map +1 -1
  15. package/dist/cli/commands/docs.d.ts +2 -44
  16. package/dist/cli/commands/docs.js +8 -13
  17. package/dist/cli/commands/docs.js.map +1 -1
  18. package/dist/cli/commands/files.d.ts +6 -134
  19. package/dist/cli/commands/files.js +4 -294
  20. package/dist/cli/commands/files.js.map +1 -1
  21. package/dist/cli/commands/get.js +15 -2
  22. package/dist/cli/commands/get.js.map +1 -1
  23. package/dist/cli/commands/list.js +5 -6
  24. package/dist/cli/commands/list.js.map +1 -1
  25. package/dist/cli/commands/next.d.ts +3 -1
  26. package/dist/cli/commands/next.js +77 -20
  27. package/dist/cli/commands/next.js.map +1 -1
  28. package/dist/cli/commands/update-many.js +6 -3
  29. package/dist/cli/commands/update-many.js.map +1 -1
  30. package/dist/cli/commands/update.js +14 -7
  31. package/dist/cli/commands/update.js.map +1 -1
  32. package/dist/cli/commands/validate.d.ts +1 -1
  33. package/dist/cli/commands/validate.js +32 -35
  34. package/dist/cli/commands/validate.js.map +1 -1
  35. package/dist/cli/main.d.ts +2 -14
  36. package/dist/cli/main.js +27 -8
  37. package/dist/cli/main.js.map +1 -1
  38. package/dist/cli-bundle/chunks/append-DYQWQK2J.js +11 -0
  39. package/dist/cli-bundle/chunks/{append-2FS6MVG7.js → append-PVZJDM6J.js} +5 -5
  40. package/dist/cli-bundle/chunks/{chunk-J2WAWP4U.js → chunk-2FNWQXZ2.js} +4 -4
  41. package/dist/cli-bundle/chunks/{chunk-YFGYDZRP.js → chunk-2GA3NK35.js} +4 -4
  42. package/dist/cli-bundle/chunks/{chunk-XFEIASAC.js → chunk-2QIQGYPW.js} +2 -2
  43. package/dist/cli-bundle/chunks/{chunk-3WCGYH5Q.js → chunk-3CMRNVTO.js} +7 -7
  44. package/dist/cli-bundle/chunks/chunk-3HKUXVKV.js +9 -0
  45. package/dist/cli-bundle/chunks/{chunk-VDAZPPRU.js → chunk-3I3LRT2G.js} +2 -2
  46. package/dist/cli-bundle/chunks/{chunk-3P3RFJIQ.js → chunk-3TL7WOEF.js} +2 -2
  47. package/dist/cli-bundle/chunks/{chunk-4SHJ5JS3.js → chunk-44LNIULG.js} +4 -4
  48. package/dist/cli-bundle/chunks/{chunk-QFOAWBOB.js → chunk-4DY4KPQI.js} +11 -10
  49. package/dist/cli-bundle/chunks/{chunk-QFOAWBOB.js.map → chunk-4DY4KPQI.js.map} +2 -2
  50. package/dist/cli-bundle/chunks/{chunk-BVCF4ULV.js → chunk-4RXTMU57.js} +5 -5
  51. package/dist/cli-bundle/chunks/{chunk-XMI2TRY5.js → chunk-4WREH7RT.js} +4 -4
  52. package/dist/cli-bundle/chunks/{chunk-JYUGUXFW.js → chunk-5CT5BW6E.js} +5 -5
  53. package/dist/cli-bundle/chunks/{chunk-NA5SBIB4.js → chunk-5URI7TPJ.js} +44 -44
  54. package/dist/cli-bundle/chunks/chunk-5URI7TPJ.js.map +7 -0
  55. package/dist/cli-bundle/chunks/{chunk-QGH6WL6L.js → chunk-655STMGA.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-DGKBWCMA.js → chunk-6IIVBC56.js} +4 -4
  57. package/dist/cli-bundle/chunks/{chunk-SRQLQUO6.js → chunk-6MHSBDGD.js} +7 -7
  58. package/dist/cli-bundle/chunks/{chunk-SRQLQUO6.js.map → chunk-6MHSBDGD.js.map} +2 -2
  59. package/dist/cli-bundle/chunks/{chunk-D4GPNYYP.js → chunk-6OTZMORS.js} +6 -6
  60. package/dist/cli-bundle/chunks/{chunk-JVRVXO6M.js → chunk-6PKA3SJQ.js} +6 -6
  61. package/dist/cli-bundle/chunks/{chunk-2PR4ZTRO.js → chunk-6TTOHMTB.js} +8 -8
  62. package/dist/cli-bundle/chunks/{chunk-2PR4ZTRO.js.map → chunk-6TTOHMTB.js.map} +1 -1
  63. package/dist/cli-bundle/chunks/chunk-6X5MZ5R2.js +9 -0
  64. package/dist/cli-bundle/chunks/chunk-76UBY2EE.js +5 -0
  65. package/dist/cli-bundle/chunks/{chunk-ZS2KPCJN.js → chunk-7QDSYUMF.js} +7 -7
  66. package/dist/cli-bundle/chunks/{chunk-Z7TFPIJ6.js → chunk-7TQMR6LK.js} +7 -7
  67. package/dist/cli-bundle/chunks/{chunk-AHA4POA6.js → chunk-ABRCOSDC.js} +3 -3
  68. package/dist/cli-bundle/chunks/{chunk-XY3CC3EM.js → chunk-AFWZRL7M.js} +59 -53
  69. package/dist/cli-bundle/chunks/chunk-AFWZRL7M.js.map +7 -0
  70. package/dist/cli-bundle/chunks/{chunk-KQJVTQVK.js → chunk-ANSJHDOZ.js} +2 -2
  71. package/dist/cli-bundle/chunks/{chunk-OMT4NO7T.js → chunk-B5DZYTT3.js} +113 -24
  72. package/dist/cli-bundle/chunks/chunk-B5DZYTT3.js.map +7 -0
  73. package/dist/cli-bundle/chunks/chunk-B7SWOIP6.js +5 -0
  74. package/dist/cli-bundle/chunks/{chunk-D2LXG7WX.js → chunk-BN62TO2S.js} +5 -5
  75. package/dist/cli-bundle/chunks/chunk-BN62TO2S.js.map +1 -0
  76. package/dist/cli-bundle/chunks/{chunk-ZTSV7P2T.js → chunk-BPD26E3P.js} +357 -42
  77. package/dist/cli-bundle/chunks/chunk-BPD26E3P.js.map +1 -0
  78. package/dist/cli-bundle/chunks/{chunk-RKGFUC4O.js → chunk-CDJYP7OQ.js} +36 -14
  79. package/dist/cli-bundle/chunks/chunk-CDJYP7OQ.js.map +1 -0
  80. package/dist/cli-bundle/chunks/{chunk-VLFLRFJP.js → chunk-CIOZ376P.js} +20 -13
  81. package/dist/cli-bundle/chunks/chunk-CIOZ376P.js.map +1 -0
  82. package/dist/cli-bundle/chunks/{chunk-HXTCZSAI.js → chunk-DBZVUJTK.js} +3 -3
  83. package/dist/cli-bundle/chunks/{chunk-2QNOWOIB.js → chunk-DO5RGJXT.js} +3 -3
  84. package/dist/cli-bundle/chunks/{chunk-MKONZ4UO.js → chunk-DRNJPEPQ.js} +4 -4
  85. package/dist/cli-bundle/chunks/{chunk-XDT2PSXA.js → chunk-DVOLZJ3C.js} +12 -11
  86. package/dist/cli-bundle/chunks/{chunk-XDT2PSXA.js.map → chunk-DVOLZJ3C.js.map} +1 -1
  87. package/dist/cli-bundle/chunks/{chunk-H36FXA7B.js → chunk-DYEX6NFH.js} +4 -4
  88. package/dist/cli-bundle/chunks/{chunk-G3IB5GTD.js → chunk-E2WC6S4P.js} +15 -11
  89. package/dist/cli-bundle/chunks/chunk-E2WC6S4P.js.map +7 -0
  90. package/dist/cli-bundle/chunks/{chunk-GAJ7U7B4.js → chunk-ERL2YFJ2.js} +3 -3
  91. package/dist/cli-bundle/chunks/{chunk-FPEYOFEF.js → chunk-F7PSHRNO.js} +3 -3
  92. package/dist/cli-bundle/chunks/{chunk-UH7OLT6F.js → chunk-FDSBDNYE.js} +2 -2
  93. package/dist/cli-bundle/chunks/{chunk-DGJF32JF.js → chunk-FIGXOCEQ.js} +66 -21
  94. package/dist/cli-bundle/chunks/chunk-FIGXOCEQ.js.map +7 -0
  95. package/dist/cli-bundle/chunks/{chunk-RQAY7C5T.js → chunk-FJZDA6MS.js} +3 -3
  96. package/dist/cli-bundle/chunks/{chunk-B4TVNGRX.js → chunk-FO7GMJKG.js} +3 -3
  97. package/dist/cli-bundle/chunks/chunk-FRQ63VPB.js +5 -0
  98. package/dist/cli-bundle/chunks/{chunk-UTYNQ2WH.js → chunk-FS6UM5WH.js} +48 -27
  99. package/dist/cli-bundle/chunks/chunk-FS6UM5WH.js.map +7 -0
  100. package/dist/cli-bundle/chunks/{chunk-U252II47.js → chunk-FTQLW4JD.js} +4 -4
  101. package/dist/cli-bundle/chunks/{chunk-TNGLCRKS.js → chunk-GSEADLRH.js} +1821 -1809
  102. package/dist/cli-bundle/chunks/chunk-GSEADLRH.js.map +1 -0
  103. package/dist/cli-bundle/chunks/{chunk-TGG7YGMC.js → chunk-GXXC7QSK.js} +53 -47
  104. package/dist/cli-bundle/chunks/chunk-GXXC7QSK.js.map +1 -0
  105. package/dist/cli-bundle/chunks/{chunk-AGD4VZXH.js → chunk-H2QBAKLQ.js} +3 -3
  106. package/dist/cli-bundle/chunks/{chunk-CJVQ4XIG.js → chunk-HAMLIWAF.js} +4 -4
  107. package/dist/cli-bundle/chunks/{chunk-56DX6QYG.js → chunk-HL7V2PHX.js} +19 -13
  108. package/dist/cli-bundle/chunks/chunk-HL7V2PHX.js.map +1 -0
  109. package/dist/cli-bundle/chunks/{chunk-7QOIQTPB.js → chunk-HLHSQ5CA.js} +4 -4
  110. package/dist/cli-bundle/chunks/{chunk-AHC7J6XD.js → chunk-IA3YFTXT.js} +6 -6
  111. package/dist/cli-bundle/chunks/{chunk-5ZCVF4WF.js → chunk-IAPHYPRL.js} +2 -2
  112. package/dist/cli-bundle/chunks/{chunk-OCSQWIOW.js → chunk-IFZA4VB5.js} +4 -4
  113. package/dist/cli-bundle/chunks/{chunk-6O2HJENY.js → chunk-IGED7NH2.js} +61 -48
  114. package/dist/cli-bundle/chunks/chunk-IGED7NH2.js.map +7 -0
  115. package/dist/cli-bundle/chunks/{chunk-RPCCQDG2.js → chunk-ILLUE5DI.js} +36 -14
  116. package/dist/cli-bundle/chunks/chunk-ILLUE5DI.js.map +7 -0
  117. package/dist/cli-bundle/chunks/{chunk-4WMFM77X.js → chunk-J4NZOP3I.js} +5 -5
  118. package/dist/cli-bundle/chunks/{chunk-57JVERX3.js → chunk-JAF4TUQ7.js} +4 -4
  119. package/dist/cli-bundle/chunks/chunk-JAF4TUQ7.js.map +7 -0
  120. package/dist/cli-bundle/chunks/{chunk-MTNKSSSO.js → chunk-JL7WZ4O2.js} +3 -3
  121. package/dist/cli-bundle/chunks/{chunk-AZ52LTCY.js → chunk-K7WNZ7KD.js} +3 -3
  122. package/dist/cli-bundle/chunks/{chunk-2OLSXXIV.js → chunk-KADLSPIU.js} +4 -4
  123. package/dist/cli-bundle/chunks/{chunk-RQKORMM4.js → chunk-KB726FMH.js} +4 -4
  124. package/dist/cli-bundle/chunks/{chunk-WKSFBBZT.js → chunk-L24HCJFC.js} +114 -25
  125. package/dist/cli-bundle/chunks/chunk-L24HCJFC.js.map +1 -0
  126. package/dist/cli-bundle/chunks/{chunk-LDO24J5I.js → chunk-LWTIRS3Y.js} +365 -43
  127. package/dist/cli-bundle/chunks/chunk-LWTIRS3Y.js.map +7 -0
  128. package/dist/cli-bundle/chunks/{chunk-TZTQ4TVV.js → chunk-M6ASXYCU.js} +4 -4
  129. package/dist/cli-bundle/chunks/{chunk-WDDOAU7Z.js → chunk-M7EWN4TF.js} +3 -3
  130. package/dist/cli-bundle/chunks/{chunk-327DSGW2.js → chunk-MD6ULIPJ.js} +3 -3
  131. package/dist/cli-bundle/chunks/{chunk-OKDBHOON.js → chunk-MKL4CP2I.js} +61 -48
  132. package/dist/cli-bundle/chunks/chunk-MKL4CP2I.js.map +1 -0
  133. package/dist/cli-bundle/chunks/{chunk-M52DG2QJ.js → chunk-MQZ3PLCF.js} +2 -2
  134. package/dist/cli-bundle/chunks/{chunk-GQ2CQNGI.js → chunk-N3CMP4NI.js} +2 -2
  135. package/dist/cli-bundle/chunks/{chunk-J7SBFUZC.js → chunk-NAQYVWSQ.js} +4 -4
  136. package/dist/cli-bundle/chunks/{chunk-U2GMYP3L.js → chunk-NKW36AMT.js} +4 -4
  137. package/dist/cli-bundle/chunks/{chunk-5WEYOVZ7.js → chunk-OBDLEQG5.js} +19 -12
  138. package/dist/cli-bundle/chunks/chunk-OBDLEQG5.js.map +7 -0
  139. package/dist/cli-bundle/chunks/{chunk-VL4LYTJN.js → chunk-OI4S4KCI.js} +18 -12
  140. package/dist/cli-bundle/chunks/chunk-OI4S4KCI.js.map +7 -0
  141. package/dist/cli-bundle/chunks/{chunk-FCVVMAEX.js → chunk-P6MYFH6K.js} +60 -22
  142. package/dist/cli-bundle/chunks/chunk-P6MYFH6K.js.map +1 -0
  143. package/dist/cli-bundle/chunks/{chunk-FTQQAPRX.js → chunk-PHKP3AGR.js} +8 -8
  144. package/dist/cli-bundle/chunks/{chunk-WVUXNIYO.js → chunk-Q37E63AM.js} +4 -4
  145. package/dist/cli-bundle/chunks/{chunk-JVXV7ANV.js → chunk-Q7E6OYZK.js} +2 -2
  146. package/dist/cli-bundle/chunks/{chunk-WVUYATII.js → chunk-QABYZYLU.js} +4 -4
  147. package/dist/cli-bundle/chunks/{chunk-QRRUGIJN.js → chunk-QASRVKUQ.js} +45 -45
  148. package/dist/cli-bundle/chunks/chunk-QASRVKUQ.js.map +1 -0
  149. package/dist/cli-bundle/chunks/{chunk-L4262MFB.js → chunk-QK2ZN6UL.js} +14 -5
  150. package/dist/cli-bundle/chunks/{chunk-L4262MFB.js.map → chunk-QK2ZN6UL.js.map} +1 -1
  151. package/dist/cli-bundle/chunks/{chunk-7TQPV7HR.js → chunk-QSPARJWF.js} +2 -2
  152. package/dist/cli-bundle/chunks/{chunk-GTKILM6F.js → chunk-QZ7LT3XE.js} +3 -3
  153. package/dist/cli-bundle/chunks/{chunk-L3VKY6R6.js → chunk-RA5AIAMP.js} +3 -3
  154. package/dist/cli-bundle/chunks/{chunk-BJS27ALI.js → chunk-RGXD5JJR.js} +6 -6
  155. package/dist/cli-bundle/chunks/{chunk-TSEPW2P6.js → chunk-RMF3IOYQ.js} +7 -7
  156. package/dist/cli-bundle/chunks/{chunk-QXYKH56X.js → chunk-T4BRCB6Z.js} +1894 -1875
  157. package/dist/cli-bundle/chunks/chunk-T4BRCB6Z.js.map +7 -0
  158. package/dist/cli-bundle/chunks/{chunk-TGGTXC52.js → chunk-TH7U4KLY.js} +3 -3
  159. package/dist/cli-bundle/chunks/{chunk-LP4UATP6.js → chunk-TWLDBKQU.js} +3 -3
  160. package/dist/cli-bundle/chunks/{chunk-OTZ3C2NE.js → chunk-TZ2PSLLT.js} +49 -28
  161. package/dist/cli-bundle/chunks/chunk-TZ2PSLLT.js.map +1 -0
  162. package/dist/cli-bundle/chunks/{chunk-UK222BHQ.js → chunk-TZRTLMWM.js} +4 -4
  163. package/dist/cli-bundle/chunks/{chunk-6E6S2X6S.js → chunk-UB2QYSTO.js} +8 -8
  164. package/dist/cli-bundle/chunks/{chunk-S6CXUSYC.js → chunk-UGTVWL3E.js} +5 -5
  165. package/dist/cli-bundle/chunks/{chunk-BNS6QHTZ.js → chunk-UJ4HJYWL.js} +2 -2
  166. package/dist/cli-bundle/chunks/{chunk-BYVOEJPQ.js → chunk-UKUIIBDW.js} +4 -4
  167. package/dist/cli-bundle/chunks/{chunk-SGDBVR7X.js → chunk-UVBA6F5A.js} +2 -2
  168. package/dist/cli-bundle/chunks/{chunk-DZRZMBBF.js → chunk-VJTAEIPC.js} +5 -5
  169. package/dist/cli-bundle/chunks/{chunk-74PWVJON.js → chunk-W6HZ55JO.js} +2 -2
  170. package/dist/cli-bundle/chunks/{chunk-HR2MQAO5.js → chunk-WD6MSYMP.js} +13 -4
  171. package/dist/cli-bundle/chunks/{chunk-HR2MQAO5.js.map → chunk-WD6MSYMP.js.map} +2 -2
  172. package/dist/cli-bundle/chunks/{chunk-P7IFURWH.js → chunk-WPAWZW7S.js} +2 -2
  173. package/dist/cli-bundle/chunks/{chunk-36LEOWSX.js → chunk-WQUEHPZB.js} +2 -2
  174. package/dist/cli-bundle/chunks/{chunk-FCKJF7G2.js → chunk-WRKB56FC.js} +3 -3
  175. package/dist/cli-bundle/chunks/{chunk-KR5EHAN4.js → chunk-X3GYR4P2.js} +2 -2
  176. package/dist/cli-bundle/chunks/{chunk-J567OZJY.js → chunk-X6BVXQ52.js} +16 -12
  177. package/dist/cli-bundle/chunks/chunk-X6BVXQ52.js.map +1 -0
  178. package/dist/cli-bundle/chunks/chunk-Y72FV7RM.js +178 -0
  179. package/dist/cli-bundle/chunks/chunk-Y72FV7RM.js.map +7 -0
  180. package/dist/cli-bundle/chunks/{chunk-OWW2KXOV.js → chunk-YQYG2V23.js} +2 -2
  181. package/dist/cli-bundle/chunks/{chunk-G2SCT7BC.js → chunk-YVKE5ZDM.js} +4 -4
  182. package/dist/cli-bundle/chunks/{chunk-QHIN4UTF.js → chunk-ZAYYDNB3.js} +4 -4
  183. package/dist/cli-bundle/chunks/chunk-ZHBI2AP7.js +9 -0
  184. package/dist/cli-bundle/chunks/chunk-ZNP64HOW.js +175 -0
  185. package/dist/cli-bundle/chunks/chunk-ZNP64HOW.js.map +1 -0
  186. package/dist/cli-bundle/chunks/{chunk-GNVBUNJQ.js → chunk-ZTRBSABY.js} +3 -3
  187. package/dist/cli-bundle/chunks/{chunk-PY32KGQU.js → chunk-ZUKSZVBW.js} +5 -5
  188. package/dist/cli-bundle/chunks/{close-CU56F47E.js → close-LZECOMHO.js} +5 -5
  189. package/dist/cli-bundle/chunks/close-RI4JQQHU.js +12 -0
  190. package/dist/cli-bundle/chunks/close-many-LY2XJ52M.js +21 -0
  191. package/dist/cli-bundle/chunks/{close-many-ZQ2WP67J.js → close-many-ZHI6A5TN.js} +12 -12
  192. package/dist/cli-bundle/chunks/comments-35M273DN.js +13 -0
  193. package/dist/cli-bundle/chunks/{comments-UDUMKXL6.js → comments-AJWRTFZ5.js} +7 -7
  194. package/dist/cli-bundle/chunks/{copy-VFHECFBV.js → copy-GMXYKBXT.js} +4 -4
  195. package/dist/cli-bundle/chunks/copy-NPYM7M7U.js +9 -0
  196. package/dist/cli-bundle/chunks/create-F53OBTOU.js +27 -0
  197. package/dist/cli-bundle/chunks/{create-CE2X3SGF.js → create-HU4Q7RJX.js} +11 -9
  198. package/dist/cli-bundle/chunks/{delete-2JXQCHHT.js → delete-GSDZLTRC.js} +4 -4
  199. package/dist/cli-bundle/chunks/delete-ODRWJWAM.js +10 -0
  200. package/dist/cli-bundle/chunks/deps-U57I7EAK.js +16 -0
  201. package/dist/cli-bundle/chunks/{deps-FPXNLO6C.js → deps-WWB7P2GT.js} +7 -4
  202. package/dist/cli-bundle/chunks/docs-G7N4E2JO.js +14 -0
  203. package/dist/cli-bundle/chunks/{docs-AMAR4OHU.js → docs-MQIY2ZQS.js} +7 -7
  204. package/dist/cli-bundle/chunks/files-TBZD7V6H.js +18 -0
  205. package/dist/cli-bundle/chunks/{files-JFHN7DYM.js → files-TTY6N2AV.js} +7 -7
  206. package/dist/cli-bundle/chunks/focus-U5TRVCRS.js +10 -0
  207. package/dist/cli-bundle/chunks/{focus-QFN2RRZ7.js → focus-XT6YVFFX.js} +5 -5
  208. package/dist/cli-bundle/chunks/{history-compact-G34XMABV.js → history-compact-KKVUWB4V.js} +8 -8
  209. package/dist/cli-bundle/chunks/{history-compact-SAHT5D46.js → history-compact-M7GHYVFN.js} +8 -8
  210. package/dist/cli-bundle/chunks/{history-redact-IFJDNKLZ.js → history-redact-3DVZOILD.js} +6 -6
  211. package/dist/cli-bundle/chunks/history-redact-JIHZLHDP.js +16 -0
  212. package/dist/cli-bundle/chunks/{history-repair-NXLQTCVN.js → history-repair-ITDUMK4N.js} +8 -8
  213. package/dist/cli-bundle/chunks/history-repair-NAFCHLH7.js +18 -0
  214. package/dist/cli-bundle/chunks/{learnings-5CZKAMBS.js → learnings-FGO3NSFW.js} +7 -7
  215. package/dist/cli-bundle/chunks/learnings-SONGPSHI.js +13 -0
  216. package/dist/cli-bundle/chunks/notes-BSD53H2W.js +13 -0
  217. package/dist/cli-bundle/chunks/{notes-POMK37UI.js → notes-NQ6RXVW6.js} +7 -7
  218. package/dist/cli-bundle/chunks/{plan-YBNYNT3A.js → plan-2NNEO46V.js} +10 -10
  219. package/dist/cli-bundle/chunks/plan-AWLYGBNV.js +24 -0
  220. package/dist/cli-bundle/chunks/{profile-JNKSU6EQ.js → profile-AAQUU6T3.js} +9 -9
  221. package/dist/cli-bundle/chunks/{profile-A2WPVG6I.js → profile-U725ATWZ.js} +9 -9
  222. package/dist/cli-bundle/chunks/{register-list-query-UG4ZA5AU.js → register-list-query-BUWCYHBT.js} +14 -13
  223. package/dist/cli-bundle/chunks/{register-list-query-UG4ZA5AU.js.map → register-list-query-BUWCYHBT.js.map} +1 -1
  224. package/dist/cli-bundle/chunks/{register-list-query-KJULL4W3.js → register-list-query-KTZ6AGE7.js} +16 -15
  225. package/dist/cli-bundle/chunks/{register-list-query-KJULL4W3.js.map → register-list-query-KTZ6AGE7.js.map} +1 -1
  226. package/dist/cli-bundle/chunks/{register-mutation-3OXYXBKH.js → register-mutation-4FMGJJF7.js} +29 -29
  227. package/dist/cli-bundle/chunks/{register-mutation-WK265BM7.js → register-mutation-UELYYOR7.js} +29 -29
  228. package/dist/cli-bundle/chunks/{register-operations-C5SQH3FJ.js → register-operations-ISUX6LY5.js} +33 -29
  229. package/dist/cli-bundle/chunks/{register-operations-C5SQH3FJ.js.map → register-operations-ISUX6LY5.js.map} +1 -1
  230. package/dist/cli-bundle/chunks/{register-operations-FH3PBHYN.js → register-operations-JVW24J2Y.js} +35 -31
  231. package/dist/cli-bundle/chunks/{register-operations-FH3PBHYN.js.map → register-operations-JVW24J2Y.js.map} +1 -1
  232. package/dist/cli-bundle/chunks/{register-setup-CCK7CJVR.js → register-setup-5XNGKJ22.js} +15 -15
  233. package/dist/cli-bundle/chunks/{register-setup-CPZBGSOJ.js → register-setup-ZTNY6S7R.js} +15 -15
  234. package/dist/cli-bundle/chunks/restore-66GLMHIX.js +14 -0
  235. package/dist/cli-bundle/chunks/{restore-IVS5XGYR.js → restore-B3BAB6X2.js} +6 -6
  236. package/dist/cli-bundle/chunks/{schema-P2MF23JO.js → schema-LZNUYHDB.js} +6 -6
  237. package/dist/cli-bundle/chunks/schema-LZNUYHDB.js.map +7 -0
  238. package/dist/cli-bundle/chunks/{schema-R3U2REY4.js → schema-U7IM2DXV.js} +6 -6
  239. package/dist/cli-bundle/chunks/schema-U7IM2DXV.js.map +1 -0
  240. package/dist/cli-bundle/chunks/update-2XGHIVQ2.js +21 -0
  241. package/dist/cli-bundle/chunks/update-2XGHIVQ2.js.map +7 -0
  242. package/dist/cli-bundle/chunks/{update-YBIQESMH.js → update-Q3UCILNR.js} +12 -12
  243. package/dist/cli-bundle/chunks/update-Q3UCILNR.js.map +1 -0
  244. package/dist/cli-bundle/chunks/{update-many-F3CIV5SQ.js → update-many-75K57FS3.js} +19 -19
  245. package/dist/cli-bundle/chunks/update-many-75K57FS3.js.map +1 -0
  246. package/dist/cli-bundle/chunks/update-many-U42YA445.js +30 -0
  247. package/dist/cli-bundle/chunks/update-many-U42YA445.js.map +7 -0
  248. package/dist/cli-bundle/main.js +39 -16
  249. package/dist/cli-bundle/main.js.map +2 -2
  250. package/dist/cli-bundle/sdk-runtime.js +56 -53
  251. package/dist/cli-bundle/sdk-testing.js +6 -6
  252. package/dist/cli-bundle/sdk.js +115 -55
  253. package/dist/cli-bundle/sdk.js.map +2 -2
  254. package/dist/core/extensions/command-hook-context.d.ts +40 -0
  255. package/dist/core/extensions/command-hook-context.js +14 -0
  256. package/dist/core/extensions/command-hook-context.js.map +1 -0
  257. package/dist/core/extensions/index.d.ts +1 -0
  258. package/dist/core/extensions/index.js +4 -3
  259. package/dist/core/extensions/index.js.map +1 -1
  260. package/dist/core/item/parse.d.ts +2 -0
  261. package/dist/core/item/parse.js +11 -2
  262. package/dist/core/item/parse.js.map +1 -1
  263. package/dist/core/store/paths.d.ts +2 -0
  264. package/dist/core/store/paths.js +10 -2
  265. package/dist/core/store/paths.js.map +1 -1
  266. package/dist/mcp/tool-definitions.js +12 -2
  267. package/dist/mcp/tool-definitions.js.map +1 -1
  268. package/dist/sdk/context-packing.d.ts +114 -0
  269. package/dist/sdk/context-packing.js +219 -0
  270. package/dist/sdk/context-packing.js.map +1 -0
  271. package/dist/sdk/context-relevance.d.ts +1 -1
  272. package/dist/sdk/context-relevance.js +4 -2
  273. package/dist/sdk/context-relevance.js.map +1 -1
  274. package/dist/sdk/context-usage.d.ts +79 -0
  275. package/dist/sdk/context-usage.js +193 -0
  276. package/dist/sdk/context-usage.js.map +1 -0
  277. package/dist/sdk/dependencies.d.ts +145 -0
  278. package/dist/sdk/dependencies.js +327 -0
  279. package/dist/sdk/dependencies.js.map +1 -0
  280. package/dist/sdk/docs.d.ts +48 -0
  281. package/dist/sdk/docs.js +15 -0
  282. package/dist/sdk/docs.js.map +1 -0
  283. package/dist/sdk/files.d.ts +135 -0
  284. package/dist/sdk/files.js +320 -0
  285. package/dist/sdk/files.js.map +1 -0
  286. package/dist/sdk/index.d.ts +6 -0
  287. package/dist/sdk/index.js +8 -2
  288. package/dist/sdk/index.js.map +1 -1
  289. package/dist/{cli/commands → sdk}/linked-artifacts.d.ts +11 -5
  290. package/dist/{cli/commands → sdk}/linked-artifacts.js +49 -25
  291. package/dist/sdk/linked-artifacts.js.map +1 -0
  292. package/dist/sdk/runtime.d.ts +4 -4
  293. package/dist/sdk/runtime.js +7 -4
  294. package/dist/sdk/runtime.js.map +1 -1
  295. package/dist/sdk/workspace.js +3 -2
  296. package/dist/sdk/workspace.js.map +1 -1
  297. package/docs/AGENT_GUIDE.md +1 -1
  298. package/docs/CONFIGURATION.md +1 -0
  299. package/docs/PR_REVIEW_LOOP.md +21 -11
  300. package/docs/SDK.md +94 -0
  301. package/marketplace.json +2 -2
  302. package/package.json +1 -1
  303. package/packages/pm-beads/package.json +1 -1
  304. package/packages/pm-calendar/package.json +1 -1
  305. package/packages/pm-command-kit/package.json +1 -1
  306. package/packages/pm-governance-audit/package.json +1 -1
  307. package/packages/pm-guide-shell/package.json +1 -1
  308. package/packages/pm-kanban/package.json +1 -1
  309. package/packages/pm-lifecycle-hooks/package.json +1 -1
  310. package/packages/pm-linked-test-adapters/package.json +1 -1
  311. package/packages/pm-search-advanced/package.json +1 -1
  312. package/packages/pm-templates/package.json +1 -1
  313. package/packages/pm-todos/package.json +1 -1
  314. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  315. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  316. package/dist/cli/commands/linked-artifacts.js.map +0 -1
  317. package/dist/cli-bundle/chunks/append-CTKFDEAX.js +0 -11
  318. package/dist/cli-bundle/chunks/chunk-56DX6QYG.js.map +0 -1
  319. package/dist/cli-bundle/chunks/chunk-57JVERX3.js.map +0 -7
  320. package/dist/cli-bundle/chunks/chunk-5WEYOVZ7.js.map +0 -7
  321. package/dist/cli-bundle/chunks/chunk-6O2HJENY.js.map +0 -7
  322. package/dist/cli-bundle/chunks/chunk-CCAGZCZK.js +0 -17
  323. package/dist/cli-bundle/chunks/chunk-CCAGZCZK.js.map +0 -7
  324. package/dist/cli-bundle/chunks/chunk-D2LXG7WX.js.map +0 -1
  325. package/dist/cli-bundle/chunks/chunk-DGJF32JF.js.map +0 -7
  326. package/dist/cli-bundle/chunks/chunk-FCVVMAEX.js.map +0 -1
  327. package/dist/cli-bundle/chunks/chunk-FUOK7JZ6.js +0 -14
  328. package/dist/cli-bundle/chunks/chunk-FUOK7JZ6.js.map +0 -1
  329. package/dist/cli-bundle/chunks/chunk-G3IB5GTD.js.map +0 -7
  330. package/dist/cli-bundle/chunks/chunk-J567OZJY.js.map +0 -1
  331. package/dist/cli-bundle/chunks/chunk-LDO24J5I.js.map +0 -7
  332. package/dist/cli-bundle/chunks/chunk-NA5SBIB4.js.map +0 -7
  333. package/dist/cli-bundle/chunks/chunk-OKDBHOON.js.map +0 -1
  334. package/dist/cli-bundle/chunks/chunk-OMT4NO7T.js.map +0 -7
  335. package/dist/cli-bundle/chunks/chunk-OTZ3C2NE.js.map +0 -1
  336. package/dist/cli-bundle/chunks/chunk-QRRUGIJN.js.map +0 -1
  337. package/dist/cli-bundle/chunks/chunk-QXYKH56X.js.map +0 -7
  338. package/dist/cli-bundle/chunks/chunk-RKGFUC4O.js.map +0 -1
  339. package/dist/cli-bundle/chunks/chunk-RPCCQDG2.js.map +0 -7
  340. package/dist/cli-bundle/chunks/chunk-TGG7YGMC.js.map +0 -1
  341. package/dist/cli-bundle/chunks/chunk-TNGLCRKS.js.map +0 -1
  342. package/dist/cli-bundle/chunks/chunk-UTYNQ2WH.js.map +0 -7
  343. package/dist/cli-bundle/chunks/chunk-VL4LYTJN.js.map +0 -7
  344. package/dist/cli-bundle/chunks/chunk-VLFLRFJP.js.map +0 -1
  345. package/dist/cli-bundle/chunks/chunk-WKSFBBZT.js.map +0 -1
  346. package/dist/cli-bundle/chunks/chunk-XY3CC3EM.js.map +0 -7
  347. package/dist/cli-bundle/chunks/chunk-ZTSV7P2T.js.map +0 -1
  348. package/dist/cli-bundle/chunks/close-BWM7FTF4.js +0 -12
  349. package/dist/cli-bundle/chunks/close-many-AUHTVFUQ.js +0 -21
  350. package/dist/cli-bundle/chunks/comments-7D5VPBZI.js +0 -13
  351. package/dist/cli-bundle/chunks/copy-QJ6ZVWZV.js +0 -9
  352. package/dist/cli-bundle/chunks/create-FGMTTYOI.js +0 -25
  353. package/dist/cli-bundle/chunks/delete-L2GMMMPR.js +0 -10
  354. package/dist/cli-bundle/chunks/deps-KTFI4RWD.js +0 -13
  355. package/dist/cli-bundle/chunks/docs-VNURA275.js +0 -14
  356. package/dist/cli-bundle/chunks/files-UNFPZLTG.js +0 -18
  357. package/dist/cli-bundle/chunks/focus-MI2UHBP4.js +0 -10
  358. package/dist/cli-bundle/chunks/history-redact-VAHGBUHI.js +0 -16
  359. package/dist/cli-bundle/chunks/history-repair-DDYQXR43.js +0 -18
  360. package/dist/cli-bundle/chunks/learnings-VWJEKHEO.js +0 -13
  361. package/dist/cli-bundle/chunks/notes-NGVJJJQO.js +0 -13
  362. package/dist/cli-bundle/chunks/plan-U6SQJUFI.js +0 -24
  363. package/dist/cli-bundle/chunks/restore-AX6ZMGHZ.js +0 -14
  364. package/dist/cli-bundle/chunks/update-XYHF3YZF.js +0 -21
  365. package/dist/cli-bundle/chunks/update-many-5HKVHFUL.js +0 -30
  366. /package/dist/cli-bundle/chunks/{append-CTKFDEAX.js.map → append-DYQWQK2J.js.map} +0 -0
  367. /package/dist/cli-bundle/chunks/{append-2FS6MVG7.js.map → append-PVZJDM6J.js.map} +0 -0
  368. /package/dist/cli-bundle/chunks/{chunk-J2WAWP4U.js.map → chunk-2FNWQXZ2.js.map} +0 -0
  369. /package/dist/cli-bundle/chunks/{chunk-YFGYDZRP.js.map → chunk-2GA3NK35.js.map} +0 -0
  370. /package/dist/cli-bundle/chunks/{chunk-XFEIASAC.js.map → chunk-2QIQGYPW.js.map} +0 -0
  371. /package/dist/cli-bundle/chunks/{chunk-3WCGYH5Q.js.map → chunk-3CMRNVTO.js.map} +0 -0
  372. /package/dist/cli-bundle/chunks/{close-BWM7FTF4.js.map → chunk-3HKUXVKV.js.map} +0 -0
  373. /package/dist/cli-bundle/chunks/{chunk-VDAZPPRU.js.map → chunk-3I3LRT2G.js.map} +0 -0
  374. /package/dist/cli-bundle/chunks/{chunk-3P3RFJIQ.js.map → chunk-3TL7WOEF.js.map} +0 -0
  375. /package/dist/cli-bundle/chunks/{chunk-4SHJ5JS3.js.map → chunk-44LNIULG.js.map} +0 -0
  376. /package/dist/cli-bundle/chunks/{chunk-BVCF4ULV.js.map → chunk-4RXTMU57.js.map} +0 -0
  377. /package/dist/cli-bundle/chunks/{chunk-XMI2TRY5.js.map → chunk-4WREH7RT.js.map} +0 -0
  378. /package/dist/cli-bundle/chunks/{chunk-JYUGUXFW.js.map → chunk-5CT5BW6E.js.map} +0 -0
  379. /package/dist/cli-bundle/chunks/{chunk-QGH6WL6L.js.map → chunk-655STMGA.js.map} +0 -0
  380. /package/dist/cli-bundle/chunks/{chunk-DGKBWCMA.js.map → chunk-6IIVBC56.js.map} +0 -0
  381. /package/dist/cli-bundle/chunks/{chunk-D4GPNYYP.js.map → chunk-6OTZMORS.js.map} +0 -0
  382. /package/dist/cli-bundle/chunks/{chunk-JVRVXO6M.js.map → chunk-6PKA3SJQ.js.map} +0 -0
  383. /package/dist/cli-bundle/chunks/{close-many-AUHTVFUQ.js.map → chunk-6X5MZ5R2.js.map} +0 -0
  384. /package/dist/cli-bundle/chunks/{close-CU56F47E.js.map → chunk-76UBY2EE.js.map} +0 -0
  385. /package/dist/cli-bundle/chunks/{chunk-ZS2KPCJN.js.map → chunk-7QDSYUMF.js.map} +0 -0
  386. /package/dist/cli-bundle/chunks/{chunk-Z7TFPIJ6.js.map → chunk-7TQMR6LK.js.map} +0 -0
  387. /package/dist/cli-bundle/chunks/{chunk-AHA4POA6.js.map → chunk-ABRCOSDC.js.map} +0 -0
  388. /package/dist/cli-bundle/chunks/{chunk-KQJVTQVK.js.map → chunk-ANSJHDOZ.js.map} +0 -0
  389. /package/dist/cli-bundle/chunks/{close-many-ZQ2WP67J.js.map → chunk-B7SWOIP6.js.map} +0 -0
  390. /package/dist/cli-bundle/chunks/{chunk-HXTCZSAI.js.map → chunk-DBZVUJTK.js.map} +0 -0
  391. /package/dist/cli-bundle/chunks/{chunk-2QNOWOIB.js.map → chunk-DO5RGJXT.js.map} +0 -0
  392. /package/dist/cli-bundle/chunks/{chunk-MKONZ4UO.js.map → chunk-DRNJPEPQ.js.map} +0 -0
  393. /package/dist/cli-bundle/chunks/{chunk-H36FXA7B.js.map → chunk-DYEX6NFH.js.map} +0 -0
  394. /package/dist/cli-bundle/chunks/{chunk-GAJ7U7B4.js.map → chunk-ERL2YFJ2.js.map} +0 -0
  395. /package/dist/cli-bundle/chunks/{chunk-FPEYOFEF.js.map → chunk-F7PSHRNO.js.map} +0 -0
  396. /package/dist/cli-bundle/chunks/{chunk-UH7OLT6F.js.map → chunk-FDSBDNYE.js.map} +0 -0
  397. /package/dist/cli-bundle/chunks/{chunk-RQAY7C5T.js.map → chunk-FJZDA6MS.js.map} +0 -0
  398. /package/dist/cli-bundle/chunks/{chunk-B4TVNGRX.js.map → chunk-FO7GMJKG.js.map} +0 -0
  399. /package/dist/cli-bundle/chunks/{comments-UDUMKXL6.js.map → chunk-FRQ63VPB.js.map} +0 -0
  400. /package/dist/cli-bundle/chunks/{chunk-U252II47.js.map → chunk-FTQLW4JD.js.map} +0 -0
  401. /package/dist/cli-bundle/chunks/{chunk-AGD4VZXH.js.map → chunk-H2QBAKLQ.js.map} +0 -0
  402. /package/dist/cli-bundle/chunks/{chunk-CJVQ4XIG.js.map → chunk-HAMLIWAF.js.map} +0 -0
  403. /package/dist/cli-bundle/chunks/{chunk-7QOIQTPB.js.map → chunk-HLHSQ5CA.js.map} +0 -0
  404. /package/dist/cli-bundle/chunks/{chunk-AHC7J6XD.js.map → chunk-IA3YFTXT.js.map} +0 -0
  405. /package/dist/cli-bundle/chunks/{chunk-5ZCVF4WF.js.map → chunk-IAPHYPRL.js.map} +0 -0
  406. /package/dist/cli-bundle/chunks/{chunk-OCSQWIOW.js.map → chunk-IFZA4VB5.js.map} +0 -0
  407. /package/dist/cli-bundle/chunks/{chunk-4WMFM77X.js.map → chunk-J4NZOP3I.js.map} +0 -0
  408. /package/dist/cli-bundle/chunks/{chunk-MTNKSSSO.js.map → chunk-JL7WZ4O2.js.map} +0 -0
  409. /package/dist/cli-bundle/chunks/{chunk-AZ52LTCY.js.map → chunk-K7WNZ7KD.js.map} +0 -0
  410. /package/dist/cli-bundle/chunks/{chunk-2OLSXXIV.js.map → chunk-KADLSPIU.js.map} +0 -0
  411. /package/dist/cli-bundle/chunks/{chunk-RQKORMM4.js.map → chunk-KB726FMH.js.map} +0 -0
  412. /package/dist/cli-bundle/chunks/{chunk-TZTQ4TVV.js.map → chunk-M6ASXYCU.js.map} +0 -0
  413. /package/dist/cli-bundle/chunks/{chunk-WDDOAU7Z.js.map → chunk-M7EWN4TF.js.map} +0 -0
  414. /package/dist/cli-bundle/chunks/{chunk-327DSGW2.js.map → chunk-MD6ULIPJ.js.map} +0 -0
  415. /package/dist/cli-bundle/chunks/{chunk-M52DG2QJ.js.map → chunk-MQZ3PLCF.js.map} +0 -0
  416. /package/dist/cli-bundle/chunks/{chunk-GQ2CQNGI.js.map → chunk-N3CMP4NI.js.map} +0 -0
  417. /package/dist/cli-bundle/chunks/{chunk-J7SBFUZC.js.map → chunk-NAQYVWSQ.js.map} +0 -0
  418. /package/dist/cli-bundle/chunks/{chunk-U2GMYP3L.js.map → chunk-NKW36AMT.js.map} +0 -0
  419. /package/dist/cli-bundle/chunks/{chunk-FTQQAPRX.js.map → chunk-PHKP3AGR.js.map} +0 -0
  420. /package/dist/cli-bundle/chunks/{chunk-WVUXNIYO.js.map → chunk-Q37E63AM.js.map} +0 -0
  421. /package/dist/cli-bundle/chunks/{chunk-JVXV7ANV.js.map → chunk-Q7E6OYZK.js.map} +0 -0
  422. /package/dist/cli-bundle/chunks/{chunk-WVUYATII.js.map → chunk-QABYZYLU.js.map} +0 -0
  423. /package/dist/cli-bundle/chunks/{chunk-7TQPV7HR.js.map → chunk-QSPARJWF.js.map} +0 -0
  424. /package/dist/cli-bundle/chunks/{chunk-GTKILM6F.js.map → chunk-QZ7LT3XE.js.map} +0 -0
  425. /package/dist/cli-bundle/chunks/{chunk-L3VKY6R6.js.map → chunk-RA5AIAMP.js.map} +0 -0
  426. /package/dist/cli-bundle/chunks/{chunk-BJS27ALI.js.map → chunk-RGXD5JJR.js.map} +0 -0
  427. /package/dist/cli-bundle/chunks/{chunk-TSEPW2P6.js.map → chunk-RMF3IOYQ.js.map} +0 -0
  428. /package/dist/cli-bundle/chunks/{chunk-TGGTXC52.js.map → chunk-TH7U4KLY.js.map} +0 -0
  429. /package/dist/cli-bundle/chunks/{chunk-LP4UATP6.js.map → chunk-TWLDBKQU.js.map} +0 -0
  430. /package/dist/cli-bundle/chunks/{chunk-UK222BHQ.js.map → chunk-TZRTLMWM.js.map} +0 -0
  431. /package/dist/cli-bundle/chunks/{chunk-6E6S2X6S.js.map → chunk-UB2QYSTO.js.map} +0 -0
  432. /package/dist/cli-bundle/chunks/{chunk-S6CXUSYC.js.map → chunk-UGTVWL3E.js.map} +0 -0
  433. /package/dist/cli-bundle/chunks/{chunk-BNS6QHTZ.js.map → chunk-UJ4HJYWL.js.map} +0 -0
  434. /package/dist/cli-bundle/chunks/{chunk-BYVOEJPQ.js.map → chunk-UKUIIBDW.js.map} +0 -0
  435. /package/dist/cli-bundle/chunks/{chunk-SGDBVR7X.js.map → chunk-UVBA6F5A.js.map} +0 -0
  436. /package/dist/cli-bundle/chunks/{chunk-DZRZMBBF.js.map → chunk-VJTAEIPC.js.map} +0 -0
  437. /package/dist/cli-bundle/chunks/{chunk-74PWVJON.js.map → chunk-W6HZ55JO.js.map} +0 -0
  438. /package/dist/cli-bundle/chunks/{chunk-P7IFURWH.js.map → chunk-WPAWZW7S.js.map} +0 -0
  439. /package/dist/cli-bundle/chunks/{chunk-36LEOWSX.js.map → chunk-WQUEHPZB.js.map} +0 -0
  440. /package/dist/cli-bundle/chunks/{chunk-FCKJF7G2.js.map → chunk-WRKB56FC.js.map} +0 -0
  441. /package/dist/cli-bundle/chunks/{chunk-KR5EHAN4.js.map → chunk-X3GYR4P2.js.map} +0 -0
  442. /package/dist/cli-bundle/chunks/{chunk-OWW2KXOV.js.map → chunk-YQYG2V23.js.map} +0 -0
  443. /package/dist/cli-bundle/chunks/{chunk-G2SCT7BC.js.map → chunk-YVKE5ZDM.js.map} +0 -0
  444. /package/dist/cli-bundle/chunks/{chunk-QHIN4UTF.js.map → chunk-ZAYYDNB3.js.map} +0 -0
  445. /package/dist/cli-bundle/chunks/{comments-7D5VPBZI.js.map → chunk-ZHBI2AP7.js.map} +0 -0
  446. /package/dist/cli-bundle/chunks/{chunk-GNVBUNJQ.js.map → chunk-ZTRBSABY.js.map} +0 -0
  447. /package/dist/cli-bundle/chunks/{chunk-PY32KGQU.js.map → chunk-ZUKSZVBW.js.map} +0 -0
  448. /package/dist/cli-bundle/chunks/{copy-VFHECFBV.js.map → close-LZECOMHO.js.map} +0 -0
  449. /package/dist/cli-bundle/chunks/{copy-QJ6ZVWZV.js.map → close-RI4JQQHU.js.map} +0 -0
  450. /package/dist/cli-bundle/chunks/{create-FGMTTYOI.js.map → close-many-LY2XJ52M.js.map} +0 -0
  451. /package/dist/cli-bundle/chunks/{create-CE2X3SGF.js.map → close-many-ZHI6A5TN.js.map} +0 -0
  452. /package/dist/cli-bundle/chunks/{delete-L2GMMMPR.js.map → comments-35M273DN.js.map} +0 -0
  453. /package/dist/cli-bundle/chunks/{delete-2JXQCHHT.js.map → comments-AJWRTFZ5.js.map} +0 -0
  454. /package/dist/cli-bundle/chunks/{deps-FPXNLO6C.js.map → copy-GMXYKBXT.js.map} +0 -0
  455. /package/dist/cli-bundle/chunks/{deps-KTFI4RWD.js.map → copy-NPYM7M7U.js.map} +0 -0
  456. /package/dist/cli-bundle/chunks/{docs-VNURA275.js.map → create-F53OBTOU.js.map} +0 -0
  457. /package/dist/cli-bundle/chunks/{docs-AMAR4OHU.js.map → create-HU4Q7RJX.js.map} +0 -0
  458. /package/dist/cli-bundle/chunks/{files-JFHN7DYM.js.map → delete-GSDZLTRC.js.map} +0 -0
  459. /package/dist/cli-bundle/chunks/{files-UNFPZLTG.js.map → delete-ODRWJWAM.js.map} +0 -0
  460. /package/dist/cli-bundle/chunks/{focus-MI2UHBP4.js.map → deps-U57I7EAK.js.map} +0 -0
  461. /package/dist/cli-bundle/chunks/{focus-QFN2RRZ7.js.map → deps-WWB7P2GT.js.map} +0 -0
  462. /package/dist/cli-bundle/chunks/{history-compact-SAHT5D46.js.map → docs-G7N4E2JO.js.map} +0 -0
  463. /package/dist/cli-bundle/chunks/{history-compact-G34XMABV.js.map → docs-MQIY2ZQS.js.map} +0 -0
  464. /package/dist/cli-bundle/chunks/{history-redact-VAHGBUHI.js.map → files-TBZD7V6H.js.map} +0 -0
  465. /package/dist/cli-bundle/chunks/{history-redact-IFJDNKLZ.js.map → files-TTY6N2AV.js.map} +0 -0
  466. /package/dist/cli-bundle/chunks/{history-repair-DDYQXR43.js.map → focus-U5TRVCRS.js.map} +0 -0
  467. /package/dist/cli-bundle/chunks/{history-repair-NXLQTCVN.js.map → focus-XT6YVFFX.js.map} +0 -0
  468. /package/dist/cli-bundle/chunks/{learnings-5CZKAMBS.js.map → history-compact-KKVUWB4V.js.map} +0 -0
  469. /package/dist/cli-bundle/chunks/{learnings-VWJEKHEO.js.map → history-compact-M7GHYVFN.js.map} +0 -0
  470. /package/dist/cli-bundle/chunks/{notes-POMK37UI.js.map → history-redact-3DVZOILD.js.map} +0 -0
  471. /package/dist/cli-bundle/chunks/{notes-NGVJJJQO.js.map → history-redact-JIHZLHDP.js.map} +0 -0
  472. /package/dist/cli-bundle/chunks/{plan-YBNYNT3A.js.map → history-repair-ITDUMK4N.js.map} +0 -0
  473. /package/dist/cli-bundle/chunks/{plan-U6SQJUFI.js.map → history-repair-NAFCHLH7.js.map} +0 -0
  474. /package/dist/cli-bundle/chunks/{profile-JNKSU6EQ.js.map → learnings-FGO3NSFW.js.map} +0 -0
  475. /package/dist/cli-bundle/chunks/{profile-A2WPVG6I.js.map → learnings-SONGPSHI.js.map} +0 -0
  476. /package/dist/cli-bundle/chunks/{restore-AX6ZMGHZ.js.map → notes-BSD53H2W.js.map} +0 -0
  477. /package/dist/cli-bundle/chunks/{restore-IVS5XGYR.js.map → notes-NQ6RXVW6.js.map} +0 -0
  478. /package/dist/cli-bundle/chunks/{schema-R3U2REY4.js.map → plan-2NNEO46V.js.map} +0 -0
  479. /package/dist/cli-bundle/chunks/{schema-P2MF23JO.js.map → plan-AWLYGBNV.js.map} +0 -0
  480. /package/dist/cli-bundle/chunks/{update-YBIQESMH.js.map → profile-AAQUU6T3.js.map} +0 -0
  481. /package/dist/cli-bundle/chunks/{update-XYHF3YZF.js.map → profile-U725ATWZ.js.map} +0 -0
  482. /package/dist/cli-bundle/chunks/{register-mutation-3OXYXBKH.js.map → register-mutation-4FMGJJF7.js.map} +0 -0
  483. /package/dist/cli-bundle/chunks/{register-mutation-WK265BM7.js.map → register-mutation-UELYYOR7.js.map} +0 -0
  484. /package/dist/cli-bundle/chunks/{register-setup-CCK7CJVR.js.map → register-setup-5XNGKJ22.js.map} +0 -0
  485. /package/dist/cli-bundle/chunks/{register-setup-CPZBGSOJ.js.map → register-setup-ZTNY6S7R.js.map} +0 -0
  486. /package/dist/cli-bundle/chunks/{update-many-5HKVHFUL.js.map → restore-66GLMHIX.js.map} +0 -0
  487. /package/dist/cli-bundle/chunks/{update-many-F3CIV5SQ.js.map → restore-B3BAB6X2.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../core/fs/fs-utils.ts","../../../../../../../../core/packages/root.ts","../../../../../../../../core/extensions/extension-types.ts","../../../../../../../../core/shared/constants.ts","../../../../../../../../types.ts","../../../../../../../../core/item/item-type-definition.ts","../../../../../../../../core/item/type-registry.ts","../../../../../../../../core/store/paths.ts","../../../../../../../../core/shared/primitives.ts","../../../../../../../../core/shared/levenshtein.ts","../../../../../../../../core/extensions/extension-capability-aliases.ts","../../../../../../../../core/extensions/extension-registries.ts","../../../../../../../../core/extensions/extension-runtime-helpers.ts","../../../../../../../../core/extensions/extension-hook-runtime.ts","../../../../../../../../core/extensions/loader.ts","../../../../../../../../core/fs/path-utils.ts","../../../../../../../../core/extensions/flag-value-types.ts","../../../../../../../../core/extensions/item-field-types.ts","../../../../../../../../core/extensions/version-compat.ts","../../../../../../../../core/extensions/extension-policy.ts","../../../../../../../../core/extensions/capability-usage.ts","../../../../../../../../core/schema/runtime-schema.ts","../../../../../../../../core/shared/errors.ts","../../../../../../../../core/extensions/item-fields.ts","../../../../../../../../core/shared/memo.ts"],"sourcesContent":["/**\n * @module core/fs/fs-utils\n *\n * Provides filesystem helpers for Fs Utils.\n */\nimport * as fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport crypto from \"node:crypto\";\n\nconst WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 25, 50, 100];\n\n/** Implements ensure dir for the public runtime surface of this module. */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true });\n}\n\n/** Implements path exists for the public runtime surface of this module. */\nexport async function pathExists(targetPath: string): Promise<boolean> {\n try {\n await fs.access(targetPath);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Implements read file if exists for the public runtime surface of this module. */\nexport async function readFileIfExists(\n targetPath: string,\n): Promise<string | null> {\n try {\n return await fs.readFile(targetPath, \"utf8\");\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return null;\n }\n throw error;\n }\n}\n\n/** Implements write file atomic for the public runtime surface of this module. */\nexport async function writeFileAtomic(\n targetPath: string,\n contents: string,\n): Promise<void> {\n const dirPath = path.dirname(targetPath);\n await ensureDir(dirPath);\n const tempPath = path.join(\n dirPath,\n `.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString(\"hex\")}.tmp`,\n );\n await fs.writeFile(tempPath, contents, \"utf8\");\n try {\n await fs.rename(tempPath, targetPath);\n } catch (error: unknown) {\n if (\n process.platform === \"win32\" &&\n (isErrno(error, \"EPERM\") || isErrno(error, \"EBUSY\"))\n ) {\n let lastError = error;\n for (const delayMs of WINDOWS_RENAME_RETRY_DELAYS_MS) {\n await new Promise<void>((resolve) => setTimeout(resolve, delayMs));\n try {\n await fs.rename(tempPath, targetPath);\n return;\n } catch (retryError: unknown) {\n lastError = retryError;\n if (!isErrno(retryError, \"EPERM\") && !isErrno(retryError, \"EBUSY\")) {\n break;\n }\n }\n }\n try {\n await fs.unlink(tempPath);\n } catch {\n // Best-effort cleanup only.\n }\n throw lastError;\n }\n if (isErrno(error, \"EXDEV\")) {\n try {\n await fs.copyFile(tempPath, targetPath);\n } finally {\n try {\n await fs.unlink(tempPath);\n } catch {\n // Best-effort cleanup only.\n }\n }\n return;\n }\n try {\n await fs.unlink(tempPath);\n } catch {\n // Best-effort cleanup only.\n }\n throw error;\n }\n}\n\n/**\n * Append a single newline-terminated line to a file, opened with `O_APPEND`.\n *\n * Concurrency contract: `O_APPEND` makes the seek-to-EOF that precedes each\n * `write(2)` atomic, so independent appenders never overwrite each other's\n * bytes. For the common case the whole `${line}\\n` buffer is handed to the\n * kernel in one `write(2)`, which mainstream filesystems (ext4/xfs/apfs) commit\n * atomically under the inode lock — concurrent multi-process appends of small\n * records (e.g. the telemetry and OTLP-span queues) therefore stay\n * line-coherent without an external lock.\n *\n * The guarantee weakens only for a single record large enough that the OS\n * splits it across multiple `write(2)` calls (multi-KiB lines), where another\n * process's append could interleave between fragments. History JSONL — the only\n * caller that can produce large lines — is always written while the per-item\n * store lock is held (see core/store/item-store.ts), so those appends are\n * serialized regardless. Callers writing large records concurrently from\n * multiple processes must hold an equivalent lock.\n */\nexport async function appendLineAtomic(\n targetPath: string,\n line: string,\n): Promise<void> {\n const dirPath = path.dirname(targetPath);\n await ensureDir(dirPath);\n const handle = await fs.open(targetPath, \"a\");\n try {\n await handle.writeFile(`${line}\\n`, \"utf8\");\n } finally {\n await handle.close();\n }\n}\n\n/** Implements remove file if exists for the public runtime surface of this module. */\nexport async function removeFileIfExists(targetPath: string): Promise<void> {\n try {\n await fs.unlink(targetPath);\n } catch (error: unknown) {\n if (!isErrno(error, \"ENOENT\")) {\n throw error;\n }\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === code\n );\n}\n","/**\n * @module core/packages/root\n *\n * Discovers and validates pm package manifests for Root.\n */\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst PM_CLI_PACKAGE_NAME = \"@unbrained/pm-cli\";\n\nfunction packageJsonNamesPmCli(packageJsonPath: string): boolean {\n try {\n const parsed = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\")) as {\n name?: unknown;\n };\n return parsed.name === PM_CLI_PACKAGE_NAME;\n } catch {\n return false;\n }\n}\n\n/** Implements find pm package root from path for the public runtime surface of this module. */\nexport function findPmPackageRootFromPath(\n startPath: string,\n): string | undefined {\n let current =\n fs.existsSync(startPath) && fs.statSync(startPath).isDirectory()\n ? path.resolve(startPath)\n : path.dirname(path.resolve(startPath));\n\n while (true) {\n const packageJsonPath = path.join(current, \"package.json\");\n if (\n fs.existsSync(packageJsonPath) &&\n packageJsonNamesPmCli(packageJsonPath)\n ) {\n return current;\n }\n\n const parent = path.dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n}\n\n/** Implements resolve pm package root from module for the public runtime surface of this module. */\nexport function resolvePmPackageRootFromModule(\n metaUrl: string,\n fallbackRelativeSegments: string[] = [],\n): string {\n const modulePath = fileURLToPath(metaUrl);\n const discovered = findPmPackageRootFromPath(modulePath);\n if (discovered) {\n return discovered;\n }\n return path.resolve(path.dirname(modulePath), ...fallbackRelativeSegments);\n}\n\n/**\n * Read the pm-cli package version from the resolved package root's `package.json`.\n *\n * Centralizes the read+parse+guard logic shared by the CLI banner, the Sentry\n * release tag, the MCP `serverInfo`, and the upgrade check so they never drift.\n * Returns `undefined` when the version cannot be resolved; callers supply their\n * own fallback (the CLI/MCP use `\"0.0.0\"`). Resolution must never throw, so the\n * hot startup path is safe.\n */\nexport function resolvePmCliVersion(\n metaUrl: string,\n fallbackRelativeSegments: string[] = [],\n): string | undefined {\n try {\n const packageJsonPath = path.join(\n resolvePmPackageRootFromModule(metaUrl, fallbackRelativeSegments),\n \"package.json\",\n );\n if (!fs.existsSync(packageJsonPath)) {\n return undefined;\n }\n const parsed = JSON.parse(fs.readFileSync(packageJsonPath, \"utf8\")) as {\n version?: unknown;\n };\n return typeof parsed.version === \"string\" &&\n parsed.version.trim().length > 0\n ? parsed.version\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Implements resolve configured pm package root for the public runtime surface of this module. */\nexport function resolveConfiguredPmPackageRoot(\n env: NodeJS.ProcessEnv = process.env,\n envName = \"PM_CLI_PACKAGE_ROOT\",\n metaUrl?: string,\n fallbackRelativeSegments: string[] = [],\n): string {\n const envRoot = env[envName];\n if (typeof envRoot === \"string\" && envRoot.trim().length > 0) {\n return path.resolve(envRoot.trim());\n }\n if (metaUrl) {\n return resolvePmPackageRootFromModule(metaUrl, fallbackRelativeSegments);\n }\n return process.cwd();\n}\n","/**\n * @module core/extensions/extension-types\n *\n * Implements extension runtime contracts and governance for Extension Types.\n */\nimport type {\n ExtensionPolicyOverrideSettings,\n ExtensionPolicySettings,\n ItemDocument,\n ItemMetadata,\n ItemStatus,\n PmSettings,\n} from \"../../types/index.js\";\nimport type { GlobalOptions } from \"../shared/command-types.js\";\nimport type {\n ProjectProfileDefinition,\n ProjectProfileRegistrationInput,\n} from \"../profile/profile-presets.js\";\n\n/** Public contract for known extension capabilities, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_CAPABILITIES = [\n \"commands\",\n \"renderers\",\n \"hooks\",\n \"schema\",\n \"importers\",\n \"search\",\n \"parser\",\n \"preflight\",\n \"services\",\n] as const;\n/** Restricts extension capability values accepted by command, SDK, and storage contracts. */\nexport type ExtensionCapability = (typeof KNOWN_EXTENSION_CAPABILITIES)[number];\n/** Public contract for extension capability contract version, shared by SDK and presentation-layer consumers. */\nexport const EXTENSION_CAPABILITY_CONTRACT_VERSION = 2;\n/** Public contract for extension capability legacy aliases, shared by SDK and presentation-layer consumers. */\nexport const EXTENSION_CAPABILITY_LEGACY_ALIASES: Readonly<\n Record<string, ExtensionCapability>\n> = Object.freeze({\n migration: \"schema\",\n validation: \"schema\",\n});\n/** Public contract for extension capability contract, shared by SDK and presentation-layer consumers. */\nexport const EXTENSION_CAPABILITY_CONTRACT = Object.freeze({\n version: EXTENSION_CAPABILITY_CONTRACT_VERSION,\n capabilities: [...KNOWN_EXTENSION_CAPABILITIES],\n legacy_aliases: { ...EXTENSION_CAPABILITY_LEGACY_ALIASES },\n});\n\n/** Public contract for known extension policy modes, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_POLICY_MODES = [\"off\", \"warn\", \"enforce\"] as const;\n/** Restricts extension policy mode values accepted by command, SDK, and storage contracts. */\nexport type ExtensionPolicyMode = (typeof KNOWN_EXTENSION_POLICY_MODES)[number];\n/** Public contract for known extension trust modes, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_TRUST_MODES = [\"off\", \"warn\", \"enforce\"] as const;\n/** Restricts extension trust mode values accepted by command, SDK, and storage contracts. */\nexport type ExtensionTrustMode = (typeof KNOWN_EXTENSION_TRUST_MODES)[number];\n/** Public contract for known extension sandbox profiles, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_SANDBOX_PROFILES = [\n \"none\",\n \"restricted\",\n \"strict\",\n] as const;\n/** Restricts extension sandbox profile values accepted by command, SDK, and storage contracts. */\nexport type ExtensionSandboxProfile =\n (typeof KNOWN_EXTENSION_SANDBOX_PROFILES)[number];\n\n/** Public contract for known pm max version exceeded modes, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_PM_MAX_VERSION_EXCEEDED_MODES = [\"block\", \"warn\"] as const;\n/** How a `pm_max_version` violation is handled for an extension layer. */\nexport type PmMaxVersionExceededMode =\n (typeof KNOWN_PM_MAX_VERSION_EXCEEDED_MODES)[number];\n/** Optional per-layer override map for `extensions.policy.pm_max_version_exceeded_mode`. */\nexport interface PmMaxVersionExceededModeByLayer {\n /** Value that configures or reports global for this contract. */\n global?: PmMaxVersionExceededMode;\n /** Value that configures or reports project for this contract. */\n project?: PmMaxVersionExceededMode;\n}\n/** Settings value for `extensions.policy.pm_max_version_exceeded_mode`: either a single mode applied to both layers, or a per-layer override map. Unset (and any unset layer key) defaults to `\"block\"`. */\nexport type PmMaxVersionExceededModeSetting =\n | PmMaxVersionExceededMode\n | PmMaxVersionExceededModeByLayer;\n\n/** Public contract for known extension policy surfaces, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_POLICY_SURFACES = [\n \"commands.override\",\n \"commands.handler\",\n \"hooks.beforecommand\",\n \"hooks.aftercommand\",\n \"hooks.onwrite\",\n \"hooks.onread\",\n \"hooks.onindex\",\n \"schema.flags\",\n \"schema.itemfields\",\n \"schema.itemtypes\",\n \"schema.migrations\",\n \"schema.profiles\",\n \"parser.override\",\n \"preflight.override\",\n \"services.override\",\n \"renderers.override\",\n \"importers.importer\",\n \"importers.exporter\",\n \"search.provider\",\n \"search.vectorstore\",\n] as const;\n/** Restricts extension policy surface values accepted by command, SDK, and storage contracts. */\nexport type ExtensionPolicySurface =\n (typeof KNOWN_EXTENSION_POLICY_SURFACES)[number];\n\n/** Public contract for known extension service names, shared by SDK and presentation-layer consumers. */\nexport const KNOWN_EXTENSION_SERVICE_NAMES = [\n \"output_format\",\n \"error_format\",\n \"help_format\",\n \"lock_acquire\",\n \"lock_release\",\n \"history_append\",\n \"item_store_write\",\n \"item_store_delete\",\n \"context_relevance\",\n \"command_result\",\n] as const;\n/** Restricts extension service name values accepted by command, SDK, and storage contracts. */\nexport type ExtensionServiceName =\n (typeof KNOWN_EXTENSION_SERVICE_NAMES)[number];\n\n/** Documents the extension provenance metadata payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionProvenanceMetadata {\n /** Value that configures or reports source for this contract. */\n source?: string;\n /** Value that configures or reports signature for this contract. */\n signature?: string;\n /** Value that configures or reports attestation for this contract. */\n attestation?: string;\n /** Value that configures or reports verified for this contract. */\n verified?: boolean;\n}\n\n/** Documents the extension runtime permission declaration payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionRuntimePermissionDeclaration {\n /** Value that configures or reports fs read for this contract. */\n fs_read?: boolean;\n /** Value that configures or reports fs write for this contract. */\n fs_write?: boolean;\n /** Value that configures or reports network for this contract. */\n network?: boolean;\n /** Value that configures or reports env read for this contract. */\n env_read?: boolean;\n /** Value that configures or reports env write for this contract. */\n env_write?: boolean;\n /** Value that configures or reports process spawn for this contract. */\n process_spawn?: boolean;\n}\n\n/** Documents the extension activation metadata payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionActivationMetadata {\n /** Value that configures or reports commands for this contract. */\n commands?: string[];\n}\n\n/** Restricts extension policy override values accepted by command, SDK, and storage contracts. */\nexport type ExtensionPolicyOverride = ExtensionPolicyOverrideSettings;\n/** Extension governance policy as read from / serialized to settings. Extends the stored settings shape with `pm_max_version_exceeded_mode` (pm-k5e8), which relaxes the default-BLOCK on `pm_max_version` violations to warn-only — globally or per extension layer. */\nexport type ExtensionGovernancePolicy = ExtensionPolicySettings & {\n pm_max_version_exceeded_mode?: PmMaxVersionExceededModeSetting;\n};\n\n/** Documents the extension manifest engines payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionManifestEngines {\n /** Value that configures or reports pm for this contract. */\n pm?: string;\n /** Value that configures or reports node for this contract. */\n node?: string;\n [engine: string]: string | undefined;\n}\n\n/** Implements create default extension governance policy for the public runtime surface of this module. */\nexport function createDefaultExtensionGovernancePolicy(): ExtensionGovernancePolicy {\n return {\n mode: \"off\",\n trust_mode: \"off\",\n require_provenance: false,\n trusted_extensions: [],\n default_sandbox_profile: \"none\",\n allowed_extensions: [],\n blocked_extensions: [],\n allowed_capabilities: [],\n blocked_capabilities: [],\n allowed_surfaces: [],\n blocked_surfaces: [],\n allowed_commands: [],\n blocked_commands: [],\n allowed_actions: [],\n blocked_actions: [],\n allowed_services: [],\n blocked_services: [],\n extension_overrides: [],\n };\n}\n\n/** Restricts extension layer values accepted by command, SDK, and storage contracts. */\nexport type ExtensionLayer = \"global\" | \"project\";\n/** Restricts extension status values accepted by command, SDK, and storage contracts. */\nexport type ExtensionStatus = \"ok\" | \"warn\";\n\n/** Documents the extension manifest payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionManifest {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports version for this contract. */\n version: string;\n /** Value that configures or reports entry for this contract. */\n entry: string;\n /** Value that configures or reports priority for this contract. */\n priority: number;\n /** Value that configures or reports capabilities for this contract. */\n capabilities: string[];\n /** Value that configures or reports manifest version for this contract. */\n manifest_version?: number;\n /** Value that configures or reports pm min version for this contract. */\n pm_min_version?: string;\n /** Value that configures or reports pm max version for this contract. */\n pm_max_version?: string;\n /** Value that configures or reports engines for this contract. */\n engines?: ExtensionManifestEngines;\n /** Value that configures or reports trusted for this contract. */\n trusted?: boolean;\n /** Value that configures or reports provenance for this contract. */\n provenance?: ExtensionProvenanceMetadata;\n /** Value that configures or reports sandbox profile for this contract. */\n sandbox_profile?: ExtensionSandboxProfile;\n /** Value that configures or reports permissions for this contract. */\n permissions?: ExtensionRuntimePermissionDeclaration;\n /** Value that configures or reports activation for this contract. */\n activation?: ExtensionActivationMetadata;\n /** Value that configures or reports legacy capability aliases for this contract. */\n legacy_capability_aliases?: LegacyExtensionCapabilityAliasMapping[];\n}\n\n/** Documents the extension diagnostic payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionDiagnostic {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports directory for this contract. */\n directory: string;\n /** Filesystem path used for manifest resolution. */\n manifest_path: string;\n /** Value that configures or reports name for this contract. */\n name: string | null;\n /** Value that configures or reports version for this contract. */\n version: string | null;\n /** Value that configures or reports entry for this contract. */\n entry: string | null;\n /** Value that configures or reports priority for this contract. */\n priority: number | null;\n /** Filesystem path used for entry resolution. */\n entry_path: string | null;\n /** Whether enabled applies to this operation. */\n enabled: boolean | null;\n /** Lifecycle state reported for status. */\n status: ExtensionStatus;\n}\n\n/** Documents the effective extension payload exchanged by command, SDK, and package integrations. */\nexport interface EffectiveExtension {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports directory for this contract. */\n directory: string;\n /** Filesystem path used for manifest resolution. */\n manifest_path: string;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports source package for this contract. */\n source_package?: string;\n /** Value that configures or reports version for this contract. */\n version: string;\n /** Value that configures or reports entry for this contract. */\n entry: string;\n /** Value that configures or reports priority for this contract. */\n priority: number;\n /** Filesystem path used for entry resolution. */\n entry_path: string;\n /** Value that configures or reports manifest version for this contract. */\n manifest_version?: number;\n /** Value that configures or reports pm min version for this contract. */\n pm_min_version?: string;\n /** Value that configures or reports pm max version for this contract. */\n pm_max_version?: string;\n /** Value that configures or reports engines for this contract. */\n engines?: ExtensionManifestEngines;\n /** Value that configures or reports trusted for this contract. */\n trusted?: boolean;\n /** Value that configures or reports provenance for this contract. */\n provenance?: ExtensionProvenanceMetadata;\n /** Value that configures or reports sandbox profile for this contract. */\n sandbox_profile?: ExtensionSandboxProfile;\n /** Value that configures or reports permissions for this contract. */\n permissions?: ExtensionRuntimePermissionDeclaration;\n /** Value that configures or reports capabilities for this contract. */\n capabilities?: string[];\n /** Value that configures or reports activation for this contract. */\n activation?: ExtensionActivationMetadata;\n}\n\n/** Documents the extension discovery result payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionDiscoveryResult {\n /** Value that configures or reports disabled by flag for this contract. */\n disabled_by_flag: boolean;\n /** Value that configures or reports roots for this contract. */\n roots: {\n global: string;\n project: string;\n };\n /** Value that configures or reports configured enabled for this contract. */\n configured_enabled: string[];\n /** Value that configures or reports configured disabled for this contract. */\n configured_disabled: string[];\n /** Value that configures or reports discovered for this contract. */\n discovered: ExtensionDiagnostic[];\n /** Value that configures or reports effective for this contract. */\n effective: EffectiveExtension[];\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports policy for this contract. */\n policy: ExtensionGovernancePolicy;\n}\n\n/** Documents the loaded extension payload exchanged by command, SDK, and package integrations. */\nexport interface LoadedExtension extends EffectiveExtension {\n /** Value that configures or reports module for this contract. */\n module: unknown;\n}\n\n/** Documents the failed extension load payload exchanged by command, SDK, and package integrations. */\nexport interface FailedExtensionLoad {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Filesystem path used for entry resolution. */\n entry_path: string;\n /** Value that configures or reports error for this contract. */\n error: string;\n}\n\n/** Documents the extension load result payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionLoadResult extends ExtensionDiscoveryResult {\n /** Value that configures or reports loaded for this contract. */\n loaded: LoadedExtension[];\n /** Value that configures or reports failed for this contract. */\n failed: FailedExtensionLoad[];\n}\n\n/** Documents the before command hook context payload exchanged by command, SDK, and package integrations. */\nexport interface BeforeCommandHookContext {\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports args for this contract. */\n args: string[];\n /** Value that configures or reports options for this contract. */\n options?: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global?: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root: string;\n}\n\n/** Documents the after command hook context payload exchanged by command, SDK, and package integrations. */\nexport interface AfterCommandHookContext extends BeforeCommandHookContext {\n /** Whether the operation completed without a blocking failure. */\n ok: boolean;\n /** Value that configures or reports error for this contract. */\n error?: string;\n /** Value that configures or reports result for this contract. */\n result?: unknown;\n /** Value that configures or reports affected for this contract. */\n affected?: AfterCommandAffectedItem[];\n}\n\n/** Documents the after command affected item payload exchanged by command, SDK, and package integrations. */\nexport interface AfterCommandAffectedItem {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports op for this contract. */\n op?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n item_type?: string;\n /** Lifecycle state reported for previousthe record. */\n previous_status?: ItemStatus;\n /** Lifecycle state reported for status. */\n status?: ItemStatus;\n /** Value that configures or reports previous for this contract. */\n previous?: Partial<ItemMetadata>;\n /** Value that configures or reports current for this contract. */\n current?: Partial<ItemMetadata>;\n /** Value that configures or reports changed fields for this contract. */\n changed_fields?: string[];\n}\n\n/** Documents the on write hook context payload exchanged by command, SDK, and package integrations. */\nexport interface OnWriteHookContext {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope: \"project\" | \"global\";\n /** Value that configures or reports op for this contract. */\n op: string;\n /** Value that configures or reports item id for this contract. */\n item_id?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n item_type?: string;\n /** Value that configures or reports before for this contract. */\n before?: ItemDocument;\n /** Value that configures or reports after for this contract. */\n after?: ItemDocument;\n /** Value that configures or reports changed fields for this contract. */\n changed_fields?: string[];\n}\n\n/** Documents the on read hook context payload exchanged by command, SDK, and package integrations. */\nexport interface OnReadHookContext {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope: \"project\" | \"global\";\n}\n\n/** Documents the on index hook context payload exchanged by command, SDK, and package integrations. */\nexport interface OnIndexHookContext {\n /** Value that configures or reports mode for this contract. */\n mode: string;\n /** Value that configures or reports total items for this contract. */\n total_items?: number;\n}\n\n/** Restricts before command hook values accepted by command, SDK, and storage contracts. */\nexport type BeforeCommandHook = (\n context: BeforeCommandHookContext,\n) => Promise<void> | void;\n/** Restricts after command hook values accepted by command, SDK, and storage contracts. */\nexport type AfterCommandHook = (\n context: AfterCommandHookContext,\n) => Promise<void> | void;\n/** Restricts on write hook values accepted by command, SDK, and storage contracts. */\nexport type OnWriteHook = (context: OnWriteHookContext) => Promise<void> | void;\n/** Restricts on read hook values accepted by command, SDK, and storage contracts. */\nexport type OnReadHook = (context: OnReadHookContext) => Promise<void> | void;\n/** Restricts on index hook values accepted by command, SDK, and storage contracts. */\nexport type OnIndexHook = (context: OnIndexHookContext) => Promise<void> | void;\n/** Restricts output renderer format values accepted by command, SDK, and storage contracts. */\nexport type OutputRendererFormat = \"toon\" | \"json\";\n/** Restricts command override values accepted by command, SDK, and storage contracts. */\nexport type CommandOverride = (context: CommandOverrideContext) => unknown;\n/** Restricts renderer override values accepted by command, SDK, and storage contracts. */\nexport type RendererOverride = (\n context: RendererOverrideContext,\n) => string | null | undefined;\n/** Restricts command handler values accepted by command, SDK, and storage contracts. */\nexport type CommandHandler = (context: CommandHandlerContext) => unknown;\n/** Restricts parser override values accepted by command, SDK, and storage contracts. */\nexport type ParserOverride = (\n context: ParserOverrideContext,\n) => ParserOverrideDelta | Promise<ParserOverrideDelta>;\n/** Restricts preflight override values accepted by command, SDK, and storage contracts. */\nexport type PreflightOverride = (\n context: PreflightOverrideContext,\n) => PreflightOverrideDelta | Promise<PreflightOverrideDelta>;\n/** Restricts service override values accepted by command, SDK, and storage contracts. */\nexport type ServiceOverride = (context: ServiceOverrideContext) => unknown;\n\n/** Documents the registered extension hook payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionHook<THook> {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports run for this contract. */\n run: THook;\n}\n\n/** Documents the extension hook registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionHookRegistry {\n /** Value that configures or reports before command for this contract. */\n beforeCommand: Array<RegisteredExtensionHook<BeforeCommandHook>>;\n /** Value that configures or reports after command for this contract. */\n afterCommand: Array<RegisteredExtensionHook<AfterCommandHook>>;\n /** Value that configures or reports on write for this contract. */\n onWrite: Array<RegisteredExtensionHook<OnWriteHook>>;\n /** Value that configures or reports on read for this contract. */\n onRead: Array<RegisteredExtensionHook<OnReadHook>>;\n /** Value that configures or reports on index for this contract. */\n onIndex: Array<RegisteredExtensionHook<OnIndexHook>>;\n}\n\n/** Documents the command override context payload exchanged by command, SDK, and package integrations. */\nexport interface CommandOverrideContext {\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports args for this contract. */\n args: string[];\n /** Value that configures or reports options for this contract. */\n options?: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global?: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root: string;\n /** Value that configures or reports result for this contract. */\n result: unknown;\n}\n\n/** Documents the renderer override context payload exchanged by command, SDK, and package integrations. */\nexport interface RendererOverrideContext {\n /** Value that configures or reports format for this contract. */\n format: OutputRendererFormat;\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Value that configures or reports args for this contract. */\n args?: string[];\n /** Value that configures or reports options for this contract. */\n options?: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global?: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root?: string;\n /** Value that configures or reports result for this contract. */\n result: unknown;\n}\n\n/** Documents the command handler context payload exchanged by command, SDK, and package integrations. */\nexport interface CommandHandlerContext {\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports args for this contract. */\n args: string[];\n /** Value that configures or reports options for this contract. */\n options: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root: string;\n}\n\n/** Documents the parser override context payload exchanged by command, SDK, and package integrations. */\nexport type ParserOverrideContext = CommandHandlerContext;\n\n/** Documents the parser override delta payload exchanged by command, SDK, and package integrations. */\nexport interface ParserOverrideDelta {\n /** Value that configures or reports args for this contract. */\n args?: string[];\n /** Value that configures or reports options for this contract. */\n options?: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global?: GlobalOptions;\n}\n\n/** Documents the preflight override context payload exchanged by command, SDK, and package integrations. */\nexport interface PreflightOverrideContext extends CommandHandlerContext {\n /** Value that configures or reports decision for this contract. */\n decision: PreflightRuntimeDecision;\n}\n\n/** Documents the preflight runtime decision payload exchanged by command, SDK, and package integrations. */\nexport interface PreflightRuntimeDecision {\n /** Value that configures or reports enforce item format gate for this contract. */\n enforce_item_format_gate: boolean;\n /** Executes the preflight item format sync operation through the package runtime. */\n run_preflight_item_format_sync: boolean;\n /** Executes the extension migrations operation through the package runtime. */\n run_extension_migrations: boolean;\n /** Value that configures or reports enforce mandatory migration gate for this contract. */\n enforce_mandatory_migration_gate: boolean;\n}\n\n/** Documents the preflight override delta payload exchanged by command, SDK, and package integrations. */\nexport interface PreflightOverrideDelta extends ParserOverrideDelta {\n /** Value that configures or reports enforce item format gate for this contract. */\n enforce_item_format_gate?: boolean;\n /** Executes the preflight item format sync operation through the package runtime. */\n run_preflight_item_format_sync?: boolean;\n /** Executes the extension migrations operation through the package runtime. */\n run_extension_migrations?: boolean;\n /** Value that configures or reports enforce mandatory migration gate for this contract. */\n enforce_mandatory_migration_gate?: boolean;\n}\n\n/** Documents the service override context payload exchanged by command, SDK, and package integrations. */\nexport interface ServiceOverrideContext {\n /** Value that configures or reports service for this contract. */\n service: ExtensionServiceName;\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Value that configures or reports args for this contract. */\n args?: string[];\n /** Value that configures or reports options for this contract. */\n options?: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global?: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root?: string;\n /** Value that configures or reports payload for this contract. */\n payload: unknown;\n}\n\n/** Documents the extension command argument definition payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionCommandArgumentDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports variadic for this contract. */\n variadic?: boolean;\n /** Value that configures or reports description for this contract. */\n description?: string;\n}\n\n/** Documents the command definition payload exchanged by command, SDK, and package integrations. */\nexport interface CommandDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports run for this contract. */\n run?: CommandHandler;\n /**\n * @deprecated Use `run` instead. This alias remains for backward compatibility.\n */\n handler?: CommandHandler;\n /** Value that configures or reports action for this contract. */\n action?: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports intent for this contract. */\n intent?: string;\n /** Value that configures or reports examples for this contract. */\n examples?: string[];\n /** Value that configures or reports failure hints for this contract. */\n failure_hints?: string[];\n /** Value that configures or reports arguments for this contract. */\n arguments?: ExtensionCommandArgumentDefinition[];\n /** Value that configures or reports flags for this contract. */\n flags?: FlagDefinition[];\n}\n\n/**\n * Optional command-definition metadata for first-class importer/exporter\n * registration.\n *\n * `registerImporter`/`registerExporter` always create a `<name> import` /\n * `<name> export` command path. By default that path only has a handler. When\n * these options are supplied, the auto-created command also gains a full command\n * definition (description, flags, intent, examples, failure hints, positional\n * arguments) — surfaced in help and runtime contracts exactly like\n * `registerCommand`. The registration `name` and `run` handler are implicit, so\n * they are not part of this options object.\n */\nexport interface ImportExportRegistrationOptions {\n /** Value that configures or reports action for this contract. */\n action?: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports intent for this contract. */\n intent?: string;\n /** Value that configures or reports examples for this contract. */\n examples?: string[];\n /** Value that configures or reports failure hints for this contract. */\n failure_hints?: string[];\n /** Value that configures or reports arguments for this contract. */\n arguments?: ExtensionCommandArgumentDefinition[];\n /** Value that configures or reports flags for this contract. */\n flags?: FlagDefinition[];\n}\n\n/** Restricts flag value type values accepted by command, SDK, and storage contracts. */\nexport type FlagValueType = \"string\" | \"number\" | \"boolean\";\n\n/** Documents the flag definition payload exchanged by command, SDK, and package integrations. */\nexport interface FlagDefinition {\n /** Value that configures or reports long for this contract. */\n long?: string;\n /** Value that configures or reports short for this contract. */\n short?: string;\n /** Value that configures or reports value name for this contract. */\n value_name?: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Whether enabled applies to this operation. */\n enabled?: boolean;\n /** Value that configures or reports visible for this contract. */\n visible?: boolean;\n /** Canonical flag value type. Prefer this field; it is the one runtime contracts and help output read first. */\n value_type?: FlagValueType;\n /**\n * @deprecated Use `value_type`. Retained for backward compatibility: when\n * both are present `value_type` wins, and `type` resolves only when\n * `value_type` is absent (`value_type ?? type`).\n */\n type?: FlagValueType;\n /** When true, a repeated comma-list flag accumulates values across repeats — parity with core list flags such as `--tags` — instead of the last value winning. Mirrors the core `CliFlagContract.list` field so extension-registered list flags coalesce through the same bootstrap path. */\n list?: boolean;\n /** Default value applied when the flag is omitted. Surfaced to runtime contracts and help output. A `list` flag may default to an array of scalars (e.g. `[\"a\", \"b\"]`); the array is flattened/coerced like any list value. */\n default?: string | number | boolean | Array<string | number | boolean>;\n [key: string]: unknown;\n}\n\n/** Documents the schema field definition payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaFieldDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type: string;\n /** Value that configures or reports optional for this contract. */\n optional?: boolean;\n [key: string]: unknown;\n}\n\n/** Documents the schema item type command option policy definition payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaItemTypeCommandOptionPolicyDefinition {\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports option for this contract. */\n option: string;\n /** Whether enabled applies to this operation. */\n enabled?: boolean;\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports visible for this contract. */\n visible?: boolean;\n [key: string]: unknown;\n}\n\n/** Documents the schema item type option definition payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaItemTypeOptionDefinition {\n /** Value that configures or reports key for this contract. */\n key: string;\n /** Value that configures or reports values for this contract. */\n values?: string[];\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports aliases for this contract. */\n aliases?: string[];\n [key: string]: unknown;\n}\n\n/** Documents the schema item type definition payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaItemTypeDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports folder for this contract. */\n folder?: string;\n /** Value that configures or reports aliases for this contract. */\n aliases?: string[];\n /** Value that configures or reports required create fields for this contract. */\n required_create_fields?: string[];\n /** Value that configures or reports required create repeatables for this contract. */\n required_create_repeatables?: string[];\n /** Value that configures or reports command option policies for this contract. */\n command_option_policies?: SchemaItemTypeCommandOptionPolicyDefinition[];\n /** Value that configures or reports options for this contract. */\n options?: SchemaItemTypeOptionDefinition[];\n [key: string]: unknown;\n}\n\n/** Documents the schema migration run context payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaMigrationRunContext {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports command for this contract. */\n command: \"migration\";\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports extension for this contract. */\n extension: string;\n /** Value that configures or reports pm root for this contract. */\n pm_root: string;\n /** Lifecycle state reported for status. */\n status: string;\n}\n\n/** Restricts schema migration runner values accepted by command, SDK, and storage contracts. */\nexport type SchemaMigrationRunner = (\n context: SchemaMigrationRunContext,\n) => unknown | Promise<unknown>;\n\n/** Documents the schema migration definition payload exchanged by command, SDK, and package integrations. */\nexport interface SchemaMigrationDefinition {\n /** Stable identifier used to reference this record across commands and storage. */\n id?: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Lifecycle state reported for status. */\n status?: string;\n /** Value that configures or reports mandatory for this contract. */\n mandatory?: boolean;\n /** Value that configures or reports run for this contract. */\n run?: SchemaMigrationRunner;\n [key: string]: unknown;\n}\n\n/** Documents the import export context payload exchanged by command, SDK, and package integrations. */\nexport interface ImportExportContext {\n /** Value that configures or reports registration for this contract. */\n registration: string;\n /** Value that configures or reports action for this contract. */\n action: \"import\" | \"export\";\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports args for this contract. */\n args: string[];\n /** Value that configures or reports options for this contract. */\n options: Record<string, unknown>;\n /** Value that configures or reports global for this contract. */\n global: GlobalOptions;\n /** Value that configures or reports pm root for this contract. */\n pm_root: string;\n}\n\n/** Restricts importer values accepted by command, SDK, and storage contracts. */\nexport type Importer = (\n context: ImportExportContext,\n) => unknown | Promise<unknown>;\n/** Restricts exporter values accepted by command, SDK, and storage contracts. */\nexport type Exporter = (\n context: ImportExportContext,\n) => unknown | Promise<unknown>;\n\n/** Restricts extension search mode values accepted by command, SDK, and storage contracts. */\nexport type ExtensionSearchMode = \"keyword\" | \"semantic\" | \"hybrid\";\n\n/** Documents the search provider query context payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderQueryContext {\n /** Value that configures or reports query for this contract. */\n query: string;\n /** Value that configures or reports mode for this contract. */\n mode: ExtensionSearchMode;\n /** Value that configures or reports tokens for this contract. */\n tokens: string[];\n /** Value that configures or reports options for this contract. */\n options: Record<string, unknown>;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n /** Value that configures or reports documents for this contract. */\n documents: ItemDocument[];\n [key: string]: unknown;\n}\n\n/** Documents the search provider hit payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderHit {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports score for this contract. */\n score: number;\n /** Value that configures or reports matched fields for this contract. */\n matched_fields?: string[];\n [key: string]: unknown;\n}\n\n/** Restricts search provider query result values accepted by command, SDK, and storage contracts. */\nexport type SearchProviderQueryResult =\n | SearchProviderHit[]\n | { hits?: SearchProviderHit[] };\n\n/** Documents the search provider query expansion context payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderQueryExpansionContext {\n /** Value that configures or reports query for this contract. */\n query: string;\n /** Value that configures or reports mode for this contract. */\n mode: Exclude<ExtensionSearchMode, \"keyword\">;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n [key: string]: unknown;\n}\n\n/** Restricts search provider query expansion result values accepted by command, SDK, and storage contracts. */\nexport type SearchProviderQueryExpansionResult =\n | string[]\n | { queries?: string[] };\n\n/** Documents the search provider rerank candidate payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderRerankCandidate {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports text for this contract. */\n text: string;\n /** Value that configures or reports score for this contract. */\n score: number;\n}\n\n/** Documents the search provider rerank hit payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderRerankHit {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports score for this contract. */\n score: number;\n}\n\n/** Restricts search provider rerank result values accepted by command, SDK, and storage contracts. */\nexport type SearchProviderRerankResult =\n | SearchProviderRerankHit[]\n | { hits?: SearchProviderRerankHit[] };\n\n/** Documents the search provider rerank context payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderRerankContext {\n /** Value that configures or reports query for this contract. */\n query: string;\n /** Value that configures or reports mode for this contract. */\n mode: \"hybrid\";\n /** Value that configures or reports model for this contract. */\n model: string;\n /** Value that configures or reports top k for this contract. */\n top_k: number;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n /** Value that configures or reports candidates for this contract. */\n candidates: SearchProviderRerankCandidate[];\n [key: string]: unknown;\n}\n\n/** Documents the search provider embed batch context payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderEmbedBatchContext {\n /** Value that configures or reports inputs for this contract. */\n inputs: string[];\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n /** Value that configures or reports model for this contract. */\n model: string;\n [key: string]: unknown;\n}\n\n/** Documents the search provider embed context payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderEmbedContext {\n /** Value that configures or reports input for this contract. */\n input: string;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n /** Value that configures or reports model for this contract. */\n model: string;\n [key: string]: unknown;\n}\n\n/** Documents the search provider definition payload exchanged by command, SDK, and package integrations. */\nexport interface SearchProviderDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports query for this contract. */\n query?: (\n context: SearchProviderQueryContext,\n ) => SearchProviderQueryResult | Promise<SearchProviderQueryResult>;\n /** Value that configures or reports query expansion for this contract. */\n queryExpansion?: (\n context: SearchProviderQueryExpansionContext,\n ) =>\n | SearchProviderQueryExpansionResult\n | Promise<SearchProviderQueryExpansionResult>;\n /** Value that configures or reports query expansion for this contract. */\n query_expansion?: (\n context: SearchProviderQueryExpansionContext,\n ) =>\n | SearchProviderQueryExpansionResult\n | Promise<SearchProviderQueryExpansionResult>;\n /** Value that configures or reports rerank for this contract. */\n rerank?: (\n context: SearchProviderRerankContext,\n ) => SearchProviderRerankResult | Promise<SearchProviderRerankResult>;\n /** Value that configures or reports embed batch for this contract. */\n embedBatch?: (\n context: SearchProviderEmbedBatchContext,\n ) => number[][] | Promise<number[][]>;\n /** Value that configures or reports embed batch for this contract. */\n embed_batch?: (\n context: SearchProviderEmbedBatchContext,\n ) => number[][] | Promise<number[][]>;\n /** Value that configures or reports embed for this contract. */\n embed?: (context: SearchProviderEmbedContext) => number[] | Promise<number[]>;\n [key: string]: unknown;\n}\n\n/** Documents the vector store query hit payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreQueryHit {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports score for this contract. */\n score: number;\n /** Value that configures or reports payload for this contract. */\n payload?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/** Documents the vector store query context payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreQueryContext {\n /** Value that configures or reports vector for this contract. */\n vector: number[];\n /** Value that configures or reports limit for this contract. */\n limit: number;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n [key: string]: unknown;\n}\n\n/** Documents the vector store upsert point payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreUpsertPoint {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports vector for this contract. */\n vector: number[];\n /** Value that configures or reports payload for this contract. */\n payload?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/** Documents the vector store upsert context payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreUpsertContext {\n /** Value that configures or reports points for this contract. */\n points: VectorStoreUpsertPoint[];\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n [key: string]: unknown;\n}\n\n/** Documents the vector store delete context payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreDeleteContext {\n /** Value that configures or reports ids for this contract. */\n ids: string[];\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n [key: string]: unknown;\n}\n\n/** Documents the vector store adapter definition payload exchanged by command, SDK, and package integrations. */\nexport interface VectorStoreAdapterDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports query for this contract. */\n query?: (\n context: VectorStoreQueryContext,\n ) => VectorStoreQueryHit[] | Promise<VectorStoreQueryHit[]>;\n /** Value that configures or reports upsert for this contract. */\n upsert?: (context: VectorStoreUpsertContext) => unknown | Promise<unknown>;\n /** Value that configures or reports delete for this contract. */\n delete?: (context: VectorStoreDeleteContext) => unknown | Promise<unknown>;\n [key: string]: unknown;\n}\n\n/** Documents the registered extension command override payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionCommandOverride {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports run for this contract. */\n run: CommandOverride;\n}\n\n/** Documents the registered extension command handler payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionCommandHandler {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports run for this contract. */\n run: CommandHandler;\n}\n\n/** Documents the registered extension parser override payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionParserOverride {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports run for this contract. */\n run: ParserOverride;\n}\n\n/** Documents the registered extension preflight override payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionPreflightOverride {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports run for this contract. */\n run: PreflightOverride;\n}\n\n/** Documents the registered extension service override payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionServiceOverride {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports service for this contract. */\n service: ExtensionServiceName;\n /** Value that configures or reports run for this contract. */\n run: ServiceOverride;\n}\n\n/** Documents the registered extension renderer override payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionRendererOverride {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports format for this contract. */\n format: OutputRendererFormat;\n /** Value that configures or reports run for this contract. */\n run: RendererOverride;\n}\n\n/** Documents the extension command registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionCommandRegistry {\n /** Value that configures or reports overrides for this contract. */\n overrides: RegisteredExtensionCommandOverride[];\n /** Value that configures or reports handlers for this contract. */\n handlers: RegisteredExtensionCommandHandler[];\n}\n\n/** Documents the extension parser registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionParserRegistry {\n /** Value that configures or reports overrides for this contract. */\n overrides: RegisteredExtensionParserOverride[];\n}\n\n/** Documents the extension preflight registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionPreflightRegistry {\n /** Value that configures or reports overrides for this contract. */\n overrides: RegisteredExtensionPreflightOverride[];\n}\n\n/** Documents the extension service registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionServiceRegistry {\n /** Value that configures or reports overrides for this contract. */\n overrides: RegisteredExtensionServiceOverride[];\n}\n\n/** Documents the extension renderer registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionRendererRegistry {\n /** Value that configures or reports overrides for this contract. */\n overrides: RegisteredExtensionRendererOverride[];\n}\n\n/** Documents the registered extension flag definitions payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionFlagDefinitions {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports target command for this contract. */\n target_command: string;\n /** Value that configures or reports flags for this contract. */\n flags: FlagDefinition[];\n}\n\n/** Documents the registered extension command definition payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionCommandDefinition {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports source package for this contract. */\n source_package?: string;\n /** Value that configures or reports command for this contract. */\n command: string;\n /** Value that configures or reports action for this contract. */\n action: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports intent for this contract. */\n intent?: string;\n /** Value that configures or reports examples for this contract. */\n examples: string[];\n /** Value that configures or reports failure hints for this contract. */\n failure_hints: string[];\n /** Value that configures or reports arguments for this contract. */\n arguments: ExtensionCommandArgumentDefinition[];\n}\n\n/** Documents the registered extension schema field definitions payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionSchemaFieldDefinitions {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports fields for this contract. */\n fields: SchemaFieldDefinition[];\n}\n\n/** Documents the registered extension schema item type definitions payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionSchemaItemTypeDefinitions {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports types for this contract. */\n types: SchemaItemTypeDefinition[];\n}\n\n/** Documents the registered extension schema migration definition payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionSchemaMigrationDefinition {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports definition for this contract. */\n definition: SchemaMigrationDefinition;\n /** Value that configures or reports runtime definition for this contract. */\n runtime_definition: SchemaMigrationDefinition;\n}\n\n/** Documents the registered extension importer payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionImporter {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports importer for this contract. */\n importer: string;\n}\n\n/** Documents the registered extension exporter payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionExporter {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports exporter for this contract. */\n exporter: string;\n}\n\n/** Documents the registered extension search provider payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionSearchProvider {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports definition for this contract. */\n definition: SearchProviderDefinition;\n /** Value that configures or reports runtime definition for this contract. */\n runtime_definition: SearchProviderDefinition;\n}\n\n/** Documents the registered extension vector store adapter payload exchanged by command, SDK, and package integrations. */\nexport interface RegisteredExtensionVectorStoreAdapter {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports definition for this contract. */\n definition: VectorStoreAdapterDefinition;\n /** Value that configures or reports runtime definition for this contract. */\n runtime_definition: VectorStoreAdapterDefinition;\n}\n\n/**\n * Documents a project profile contributed by an extension via\n * `api.registerProfile(profile)`.\n *\n * A profile is the broadest customization primitive an extension can ship: it\n * bundles item types, custom statuses, fields, per-type workflows, config knobs,\n * create templates, and package recommendations into one declarative archetype\n * that `pm profile apply` stages idempotently — the same shape as the\n * core-baked archetypes. Registering one makes it resolvable by name through\n * `pm profile list/show/apply` for as long as the owning package is active.\n */\nexport interface RegisteredExtensionProjectProfile {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports profile for this contract. */\n profile: ProjectProfileDefinition;\n}\n\n/** Documents the extension registration registry payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionRegistrationRegistry {\n /** Value that configures or reports commands for this contract. */\n commands: RegisteredExtensionCommandDefinition[];\n /** Value that configures or reports flags for this contract. */\n flags: RegisteredExtensionFlagDefinitions[];\n /** Value that configures or reports item fields for this contract. */\n item_fields: RegisteredExtensionSchemaFieldDefinitions[];\n /** Value that configures or reports item types for this contract. */\n item_types: RegisteredExtensionSchemaItemTypeDefinitions[];\n /** Value that configures or reports migrations for this contract. */\n migrations: RegisteredExtensionSchemaMigrationDefinition[];\n /** Value that configures or reports profiles for this contract. */\n profiles: RegisteredExtensionProjectProfile[];\n /** Value that configures or reports importers for this contract. */\n importers: RegisteredExtensionImporter[];\n /** Value that configures or reports exporters for this contract. */\n exporters: RegisteredExtensionExporter[];\n /** Value that configures or reports search providers for this contract. */\n search_providers: RegisteredExtensionSearchProvider[];\n /** Value that configures or reports vector store adapters for this contract. */\n vector_store_adapters: RegisteredExtensionVectorStoreAdapter[];\n}\n\n/** Documents the extension registration counts payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionRegistrationCounts {\n /** Value that configures or reports commands for this contract. */\n commands: number;\n /** Value that configures or reports flags for this contract. */\n flags: number;\n /** Value that configures or reports item fields for this contract. */\n item_fields: number;\n /** Value that configures or reports item types for this contract. */\n item_types: number;\n /** Value that configures or reports migrations for this contract. */\n migrations: number;\n /** Value that configures or reports profiles for this contract. */\n profiles: number;\n /** Value that configures or reports importers for this contract. */\n importers: number;\n /** Value that configures or reports exporters for this contract. */\n exporters: number;\n /** Value that configures or reports search providers for this contract. */\n search_providers: number;\n /** Value that configures or reports vector store adapters for this contract. */\n vector_store_adapters: number;\n}\n\n/** Read-only identity an extension's `activate(api)` receives about itself, so authors can emit self-identifying logs, gate on their own version, and build better error messages without re-reading the on-disk manifest or duplicating metadata in-module. Exposed as `api.extension`. */\nexport interface ExtensionSelfIdentity {\n /** Value that configures or reports name for this contract. */\n readonly name: string;\n /** Value that configures or reports layer for this contract. */\n readonly layer: ExtensionLayer;\n /** Value that configures or reports version for this contract. */\n readonly version: string;\n /** Value that configures or reports capabilities for this contract. */\n readonly capabilities: readonly ExtensionCapability[];\n /** Value that configures or reports pm min version for this contract. */\n readonly pm_min_version?: string;\n /** Value that configures or reports pm max version for this contract. */\n readonly pm_max_version?: string;\n /** Value that configures or reports source package for this contract. */\n readonly source_package?: string;\n}\n\n/** Documents the extension api payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionApi {\n /** Read-only identity of the extension this `api` was created for. */\n readonly extension: ExtensionSelfIdentity;\n /** Value that configures or reports register command for this contract. */\n registerCommand(command: string, override: CommandOverride): void;\n /** Value that configures or reports register command for this contract. */\n registerCommand(definition: CommandDefinition): void;\n /** Value that configures or reports register parser for this contract. */\n registerParser(command: string, override: ParserOverride): void;\n /** Value that configures or reports register preflight for this contract. */\n registerPreflight(override: PreflightOverride): void;\n /** Value that configures or reports register service for this contract. */\n registerService(\n service: ExtensionServiceName,\n override: ServiceOverride,\n ): void;\n /** Value that configures or reports register flags for this contract. */\n registerFlags(targetCommand: string, flags: FlagDefinition[]): void;\n /** Value that configures or reports register item fields for this contract. */\n registerItemFields(fields: SchemaFieldDefinition[]): void;\n /** Value that configures or reports register item types for this contract. */\n registerItemTypes(types: SchemaItemTypeDefinition[]): void;\n /** Value that configures or reports register migration for this contract. */\n registerMigration(definition: SchemaMigrationDefinition): void;\n /** Value that configures or reports register profile for this contract. */\n registerProfile(profile: ProjectProfileRegistrationInput): void;\n /** Value that configures or reports register renderer for this contract. */\n registerRenderer(\n format: OutputRendererFormat,\n renderer: RendererOverride,\n ): void;\n /** Value that configures or reports register importer for this contract. */\n registerImporter(\n name: string,\n importer: Importer,\n options?: ImportExportRegistrationOptions,\n ): void;\n /** Value that configures or reports register exporter for this contract. */\n registerExporter(\n name: string,\n exporter: Exporter,\n options?: ImportExportRegistrationOptions,\n ): void;\n /** Value that configures or reports register search provider for this contract. */\n registerSearchProvider(provider: SearchProviderDefinition): void;\n /** Value that configures or reports register vector store adapter for this contract. */\n registerVectorStoreAdapter(adapter: VectorStoreAdapterDefinition): void;\n /** Value that configures or reports hooks for this contract. */\n hooks: {\n beforeCommand(hook: BeforeCommandHook): void;\n afterCommand(hook: AfterCommandHook): void;\n onWrite(hook: OnWriteHook): void;\n onRead(hook: OnReadHook): void;\n onIndex(hook: OnIndexHook): void;\n };\n}\n\n/** Documents the failed extension activation payload exchanged by command, SDK, and package integrations. */\nexport interface FailedExtensionActivation {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Filesystem path used for entry resolution. */\n entry_path: string;\n /** Value that configures or reports error for this contract. */\n error: string;\n /** Value that configures or reports trace for this contract. */\n trace?: ExtensionActivationFailureTrace;\n}\n\n/** Documents the extension activation failure trace payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionActivationFailureTrace {\n /** Value that configures or reports method for this contract. */\n method: string;\n /** `-1` means the failure happened before a numbered registration was accepted. */\n registration_index: number;\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Value that configures or reports capability for this contract. */\n capability?: ExtensionCapability;\n /** Value that configures or reports missing capability for this contract. */\n missing_capability?: ExtensionCapability;\n /** Value that configures or reports expected schema for this contract. */\n expected_schema: string;\n /** Value that configures or reports received for this contract. */\n received?: unknown;\n /** Value that configures or reports hint for this contract. */\n hint?: string;\n}\n\n/** Documents the extension activation result payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionActivationResult {\n /** Value that configures or reports hooks for this contract. */\n hooks: ExtensionHookRegistry;\n /** Value that configures or reports commands for this contract. */\n commands: ExtensionCommandRegistry;\n /** Value that configures or reports parsers for this contract. */\n parsers: ExtensionParserRegistry;\n /** Value that configures or reports preflight for this contract. */\n preflight: ExtensionPreflightRegistry;\n /** Value that configures or reports services for this contract. */\n services: ExtensionServiceRegistry;\n /** Value that configures or reports renderers for this contract. */\n renderers: ExtensionRendererRegistry;\n /** Value that configures or reports registrations for this contract. */\n registrations: ExtensionRegistrationRegistry;\n /** Value that configures or reports failed for this contract. */\n failed: FailedExtensionActivation[];\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports hook counts for this contract. */\n hook_counts: {\n before_command: number;\n after_command: number;\n on_write: number;\n on_read: number;\n on_index: number;\n };\n /** Number of command override entries represented by this result. */\n command_override_count: number;\n /** Number of command handler entries represented by this result. */\n command_handler_count: number;\n /** Number of parser override entries represented by this result. */\n parser_override_count: number;\n /** Number of preflight override entries represented by this result. */\n preflight_override_count: number;\n /** Number of service override entries represented by this result. */\n service_override_count: number;\n /** Number of renderer override entries represented by this result. */\n renderer_override_count: number;\n /** Value that configures or reports registration counts for this contract. */\n registration_counts: ExtensionRegistrationCounts;\n}\n\n/** Documents the extension candidate payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionCandidate {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports directory for this contract. */\n directory: string;\n /** Filesystem path used for manifest resolution. */\n manifest_path: string;\n /** Filesystem path used for entry resolution. */\n entry_path: string;\n /** Declarative package manifest consumed by the extension loader. */\n manifest: ExtensionManifest;\n /** Value that configures or reports source package for this contract. */\n source_package?: string;\n}\n\n/** Documents the extension layer scan result payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionLayerScanResult {\n /** Value that configures or reports diagnostics for this contract. */\n diagnostics: ExtensionDiagnostic[];\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports candidates for this contract. */\n candidates: ExtensionCandidate[];\n}\n\n/** Documents the scanned extension directory payload exchanged by command, SDK, and package integrations. */\nexport interface ScannedExtensionDirectory {\n /** Value that configures or reports diagnostic for this contract. */\n diagnostic: ExtensionDiagnostic;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports candidate for this contract. */\n candidate: ExtensionCandidate | null;\n}\n\n/** Documents the legacy extension capability alias mapping payload exchanged by command, SDK, and package integrations. */\nexport interface LegacyExtensionCapabilityAliasMapping {\n /** Value that configures or reports alias for this contract. */\n alias: string;\n /** Value that configures or reports target for this contract. */\n target: ExtensionCapability;\n}\n\n/** Documents the discover extensions options payload exchanged by command, SDK, and package integrations. */\nexport interface DiscoverExtensionsOptions {\n /** Value that configures or reports pm root for this contract. */\n pmRoot: string;\n /** Value that configures or reports settings for this contract. */\n settings: PmSettings;\n /** Value that configures or reports cwd for this contract. */\n cwd?: string;\n /** Value that configures or reports no extensions for this contract. */\n noExtensions?: boolean;\n /** Value that configures or reports ignore global extensions for this contract. */\n ignoreGlobalExtensions?: boolean;\n /** Value that configures or reports reload token for this contract. */\n reload_token?: string;\n /** Value that configures or reports cache bust for this contract. */\n cache_bust?: boolean;\n /** Optional import-stage filter. Discovery still reports the full effective set, but `loadExtensions` imports only entries accepted by this predicate. */\n extensionFilter?: (extension: EffectiveExtension) => boolean;\n}\n\n/** Documents the activatable extension payload exchanged by command, SDK, and package integrations. */\nexport interface ActivatableExtension {\n /** Registers this package's commands, actions, and runtime hooks with the host. */\n activate: (api: ExtensionApi) => void | Promise<void>;\n /** Optional teardown lifecycle hook, analogous to VS Code's `deactivate` export. Invoked when the host tears the extension down — on long-running MCP-server reload between requests, or via the `deactivateExtensions` primitive — so an extension can close connections, clear timers, and release buffers it opened during `activate`. */\n deactivate?: () => void | Promise<void>;\n}\n\n/** Documents the extension deactivation failure payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionDeactivationFailure {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports error for this contract. */\n error: string;\n}\n\n/** Documents the extension deactivation options payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionDeactivationOptions {\n /** Maximum time to wait for each extension's `deactivate` hook. Defaults to 5000ms so a hanging teardown cannot block host shutdown or reload. Set to 0 or Infinity only when the host intentionally wants to wait indefinitely. */\n deactivate_timeout_ms?: number;\n}\n\n/** Documents the extension deactivation result payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionDeactivationResult {\n /** Count of loaded extensions whose `deactivate` hook ran without throwing. */\n deactivated: number;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports failed for this contract. */\n failed: ExtensionDeactivationFailure[];\n}\n\n/** Documents the service override result payload exchanged by command, SDK, and package integrations. */\nexport interface ServiceOverrideResult {\n /** Value that configures or reports handled for this contract. */\n handled: boolean;\n /** Value that configures or reports result for this contract. */\n result: unknown;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the command override result payload exchanged by command, SDK, and package integrations. */\nexport interface CommandOverrideResult {\n /** Value that configures or reports overridden for this contract. */\n overridden: boolean;\n /** Value that configures or reports result for this contract. */\n result: unknown;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the command handler result payload exchanged by command, SDK, and package integrations. */\nexport interface CommandHandlerResult {\n /** Value that configures or reports handled for this contract. */\n handled: boolean;\n /** Value that configures or reports result for this contract. */\n result: unknown;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Human-readable, single-line, length-bounded message describing why an extension command handler failed. Surfaced to the user/CI so the real cause (e.g. \"Changelog is out of date: CHANGELOG.md\") is visible instead of only the opaque `extension_command_handler_failed` warning code. */\n errorMessage?: string;\n}\n\n/** Documents the parser override result payload exchanged by command, SDK, and package integrations. */\nexport interface ParserOverrideResult {\n /** Value that configures or reports overridden for this contract. */\n overridden: boolean;\n /** Value that configures or reports context for this contract. */\n context: CommandHandlerContext;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the preflight override result payload exchanged by command, SDK, and package integrations. */\nexport interface PreflightOverrideResult {\n /** Value that configures or reports overridden for this contract. */\n overridden: boolean;\n /** Value that configures or reports context for this contract. */\n context: CommandHandlerContext;\n /** Value that configures or reports decision for this contract. */\n decision: PreflightRuntimeDecision;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the renderer override result payload exchanged by command, SDK, and package integrations. */\nexport interface RendererOverrideResult {\n /** Value that configures or reports overridden for this contract. */\n overridden: boolean;\n /** Value that configures or reports rendered for this contract. */\n rendered: string | null;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the unknown extension capability warning details payload exchanged by command, SDK, and package integrations. */\nexport interface UnknownExtensionCapabilityWarningDetails {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports capability for this contract. */\n capability: string;\n /** Value that configures or reports allowed capabilities for this contract. */\n allowed_capabilities: string[];\n /** Value that configures or reports capability contract version for this contract. */\n capability_contract_version: number;\n /** Value that configures or reports suggested capability for this contract. */\n suggested_capability?: string;\n /** Value that configures or reports suggestion source for this contract. */\n suggestion_source?: \"legacy_alias\" | \"nearest_match\";\n /** Value that configures or reports legacy alias target for this contract. */\n legacy_alias_target?: string;\n}\n","/**\n * @module core/shared/constants\n *\n * Provides shared primitives and utilities for Constants.\n */\nimport type {\n BuiltinItemType,\n GovernancePreset,\n GovernanceSettings,\n ItemMetadata,\n PmSettings,\n RuntimeStatusDefinition,\n RuntimeWorkflowDefinition,\n} from \"../../types/index.js\";\nimport { createDefaultExtensionGovernancePolicy } from \"../extensions/extension-types.js\";\n\n/**\n * Canonical default lifecycle status model and workflow role mapping.\n *\n * Single source of truth: `SETTINGS_DEFAULTS.schema` references these, and\n * `src/core/schema/runtime-schema.ts` re-exports them as\n * `DEFAULT_RUNTIME_STATUS_DEFINITIONS` / `DEFAULT_RUNTIME_WORKFLOW`.\n */\nexport const DEFAULT_STATUS_DEFINITIONS: ReadonlyArray<RuntimeStatusDefinition> =\n Object.freeze([\n {\n id: \"draft\",\n roles: [\"draft\"],\n },\n {\n id: \"open\",\n roles: [\"active\", \"default_open\"],\n },\n {\n id: \"in_progress\",\n aliases: [\"in-progress\"],\n roles: [\"active\"],\n },\n {\n id: \"blocked\",\n roles: [\"blocked\"],\n },\n {\n id: \"closed\",\n roles: [\"terminal\", \"terminal_done\", \"default_close\"],\n },\n {\n id: \"canceled\",\n aliases: [\"cancelled\"],\n roles: [\"terminal\", \"terminal_canceled\", \"default_cancel\"],\n },\n ]);\n\n/** Fallback workflow definition used when callers do not provide an override. */\nexport const DEFAULT_WORKFLOW_DEFINITION: RuntimeWorkflowDefinition =\n Object.freeze({\n draft_status: \"draft\",\n open_status: \"open\",\n in_progress_status: \"in_progress\",\n blocked_status: \"blocked\",\n close_status: \"closed\",\n canceled_status: \"canceled\",\n });\n\n/** Public contract for pm dirname, shared by SDK and presentation-layer consumers. */\nexport const PM_DIRNAME = \".agents/pm\";\n/** Public contract for settings filename, shared by SDK and presentation-layer consumers. */\nexport const SETTINGS_FILENAME = \"settings.json\";\n\n/** GH-249: placeholder close reason recorded when `pm create --status closed` lands an item directly in the close status under `governance.require_close_reason` and no --message/--resolution text is available. Mirrors `pm update --status closed`'s \"Closed via pm update\" default so all three closure paths record a reason. */\nexport const CREATE_DIRECT_CLOSE_REASON_DEFAULT =\n \"Closed at creation via pm create\";\n\n/** Public contract for pm core required subdirs, shared by SDK and presentation-layer consumers. */\nexport const PM_CORE_REQUIRED_SUBDIRS = [\n \"\",\n \"epics\",\n \"features\",\n \"tasks\",\n \"chores\",\n \"issues\",\n \"schema\",\n \"history\",\n \"search\",\n \"extensions\",\n \"locks\",\n] as const;\n\n/** Public contract for pm optional type subdirs, shared by SDK and presentation-layer consumers. */\nexport const PM_OPTIONAL_TYPE_SUBDIRS = [\n \"decisions\",\n \"events\",\n \"reminders\",\n \"milestones\",\n \"meetings\",\n \"plans\",\n] as const;\n\n/** Public contract for pm required subdirs, shared by SDK and presentation-layer consumers. */\nexport const PM_REQUIRED_SUBDIRS = [\n ...PM_CORE_REQUIRED_SUBDIRS,\n ...PM_OPTIONAL_TYPE_SUBDIRS,\n] as const;\n\n/** Public contract for type to folder, shared by SDK and presentation-layer consumers. */\nexport const TYPE_TO_FOLDER: Record<BuiltinItemType, string> = {\n Epic: \"epics\",\n Feature: \"features\",\n Task: \"tasks\",\n Chore: \"chores\",\n Issue: \"issues\",\n Decision: \"decisions\",\n Event: \"events\",\n Reminder: \"reminders\",\n Milestone: \"milestones\",\n Meeting: \"meetings\",\n Plan: \"plans\",\n};\n\n/** Public contract for item metadata key order, shared by SDK and presentation-layer consumers. */\nexport const ITEM_METADATA_KEY_ORDER: ReadonlyArray<string> = [\n \"id\",\n \"title\",\n \"description\",\n \"type\",\n \"pm_format_version\",\n \"source_type\",\n \"type_options\",\n \"status\",\n \"priority\",\n \"tags\",\n \"created_at\",\n \"updated_at\",\n \"deadline\",\n \"reminders\",\n \"events\",\n \"closed_at\",\n \"assignee\",\n \"source_owner\",\n \"author\",\n \"estimated_minutes\",\n \"acceptance_criteria\",\n \"design\",\n \"external_ref\",\n \"definition_of_ready\",\n \"order\",\n \"goal\",\n \"objective\",\n \"value\",\n \"impact\",\n \"outcome\",\n \"why_now\",\n \"parent\",\n \"reviewer\",\n \"risk\",\n \"confidence\",\n \"sprint\",\n \"release\",\n \"blocked_by\",\n \"blocked_reason\",\n \"unblock_note\",\n \"reporter\",\n \"severity\",\n \"environment\",\n \"repro_steps\",\n \"resolution\",\n \"expected_result\",\n \"actual_result\",\n \"affected_version\",\n \"fixed_version\",\n \"component\",\n \"regression\",\n \"customer_impact\",\n \"dependencies\",\n \"comments\",\n \"notes\",\n \"learnings\",\n \"files\",\n \"tests\",\n \"test_runs\",\n \"docs\",\n \"close_reason\",\n \"duplicate_of\",\n \"plan_mode\",\n \"plan_scope\",\n \"plan_harness\",\n \"plan_resume_context\",\n \"plan_validation\",\n \"plan_decisions\",\n \"plan_discoveries\",\n \"plan_steps\",\n];\n\ntype BuiltinGovernancePreset = Exclude<GovernancePreset, \"custom\">;\n\n/** Public contract for governance preset defaults, shared by SDK and presentation-layer consumers. */\nexport const GOVERNANCE_PRESET_DEFAULTS: Record<\n BuiltinGovernancePreset,\n Omit<GovernanceSettings, \"preset\">\n> = {\n minimal: {\n ownership_enforcement: \"none\",\n create_mode_default: \"progressive\",\n close_validation_default: \"off\",\n require_close_reason: true,\n parent_reference: \"strict_error\",\n metadata_profile: \"core\",\n force_required_for_stale_lock: false,\n },\n default: {\n ownership_enforcement: \"warn\",\n create_mode_default: \"progressive\",\n close_validation_default: \"warn\",\n require_close_reason: true,\n parent_reference: \"strict_error\",\n metadata_profile: \"core\",\n force_required_for_stale_lock: true,\n },\n strict: {\n ownership_enforcement: \"strict\",\n create_mode_default: \"strict\",\n close_validation_default: \"strict\",\n require_close_reason: true,\n parent_reference: \"strict_error\",\n metadata_profile: \"strict\",\n force_required_for_stale_lock: true,\n },\n};\n\n/** Fallback validate stale blocker reason patterns used when callers do not provide an override. */\nexport const DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS = [\n \"no active blocker\",\n \"ready for planned execution sequencing\",\n \"work completed\",\n \"work is closed\",\n] as const;\n\n/** Fallback validate closure like metadata field patterns used when callers do not provide an override. */\nexport const DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS = {\n blocked_reason: [\n \"no active blocker because work is closed\",\n \"work is closed\",\n ],\n resolution: [\n \"closed with implementation evidence\",\n \"closed with verification evidence\",\n \"work completed and recorded\",\n \"work is closed\",\n ],\n actual_result: [\n \"closed and recorded\",\n \"work completed\",\n \"work completed and recorded\",\n ],\n} as const;\n\nfunction cloneOptionalArray<T>(\n values: readonly T[] | undefined,\n): T[] | undefined {\n return values ? [...values] : undefined;\n}\n\n/** Public contract for settings defaults, shared by SDK and presentation-layer consumers. */\nexport const SETTINGS_DEFAULTS: PmSettings = {\n version: 1,\n id_prefix: \"pm-\",\n author_default: \"\",\n item_format: \"toon\",\n locks: {\n ttl_seconds: 1800,\n wait_ms: 3000,\n },\n checkpoints: {\n retention_days: 14,\n },\n output: {\n default_format: \"toon\",\n },\n history: {\n missing_stream: \"auto_create\",\n compact_policy: {\n enabled: false,\n max_entries: 500,\n trigger: \"health_warn\",\n },\n },\n validation: {\n sprint_release_format: \"warn\",\n parent_reference: \"warn\",\n metadata_profile: \"core\",\n metadata_required_fields: [],\n lifecycle_stale_blocker_reason_patterns: [\n ...DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,\n ],\n lifecycle_closure_like_blocked_reason_patterns: [\n ...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason,\n ],\n lifecycle_closure_like_resolution_patterns: [\n ...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution,\n ],\n lifecycle_closure_like_actual_result_patterns: [\n ...DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result,\n ],\n estimate_defaults_by_type: {},\n },\n governance: {\n preset: \"minimal\",\n ...GOVERNANCE_PRESET_DEFAULTS.minimal,\n },\n workflow: {\n definition_of_done: [],\n },\n testing: {\n record_results_to_items: false,\n },\n telemetry: {\n enabled: true,\n first_run_prompt_completed: false,\n capture_level: \"redacted\",\n endpoint: \"https://pm-cli.unbrained.dev/v1/events\",\n installation_id: \"\",\n retention_days: 365,\n },\n agent_guidance: {\n prompt_completed: false,\n declined: false,\n declined_at: \"\",\n template_version: 1,\n last_checked_files: [],\n },\n item_types: {\n definitions: [],\n },\n schema: {\n version: 1,\n files: {\n types: \"schema/types.json\",\n statuses: \"schema/statuses.json\",\n fields: \"schema/fields.json\",\n workflows: \"schema/workflows.json\",\n },\n statuses: DEFAULT_STATUS_DEFINITIONS.map((definition) => ({\n ...definition,\n aliases: cloneOptionalArray(definition.aliases),\n roles: cloneOptionalArray(definition.roles),\n })),\n fields: [],\n workflow: { ...DEFAULT_WORKFLOW_DEFINITION },\n unknown_field_policy: \"allow\",\n },\n extensions: {\n enabled: [],\n disabled: [],\n policy: createDefaultExtensionGovernancePolicy(),\n },\n search: {\n score_threshold: 0,\n hybrid_semantic_weight: 0.7,\n max_results: 50,\n embedding_model: \"\",\n embedding_batch_size: 32,\n embedding_timeout_ms: 30_000,\n scanner_max_batch_retries: 3,\n provider: \"\",\n mutation_refresh_policy: \"semantic_configured\",\n query_expansion: {\n enabled: false,\n provider: \"\",\n },\n rerank: {\n enabled: false,\n model: \"\",\n top_k: 20,\n },\n },\n providers: {\n openai: {\n base_url: \"\",\n api_key: \"\",\n model: \"\",\n },\n ollama: {\n base_url: \"\",\n model: \"\",\n },\n },\n context: {\n default_depth: \"brief\",\n activity_limit: 10,\n stale_threshold_days: 7,\n sections: {\n hierarchy: true,\n activity: true,\n progress: true,\n recently_created: true,\n unparented: true,\n blockers: true,\n files: true,\n workload: true,\n staleness: true,\n tests: true,\n },\n },\n vector_store: {\n adapter: \"\",\n collection_name: \"pm_items\",\n qdrant: {\n url: \"\",\n api_key: \"\",\n },\n lancedb: {\n path: \"\",\n },\n },\n};\n\n/** Public contract for empty canonical document, shared by SDK and presentation-layer consumers. */\nexport const EMPTY_CANONICAL_DOCUMENT = {\n metadata: {},\n body: \"\",\n};\n\n/** Public contract for exit code, shared by SDK and presentation-layer consumers. */\nexport const EXIT_CODE = {\n SUCCESS: 0,\n GENERIC_FAILURE: 1,\n USAGE: 2,\n NOT_FOUND: 3,\n CONFLICT: 4,\n DEPENDENCY_FAILED: 5,\n} as const;\n\n/** Restricts telemetry error category values accepted by command, SDK, and storage contracts. */\nexport type TelemetryErrorCategory =\n | \"usage\"\n | \"validation\"\n | \"conflict\"\n | \"runtime\"\n | \"unknown\";\n\n/** Public contract for telemetry error category by code, shared by SDK and presentation-layer consumers. */\nexport const TELEMETRY_ERROR_CATEGORY_BY_CODE: Readonly<\n Record<string, TelemetryErrorCategory>\n> = Object.freeze({\n unknown_command: \"usage\",\n unknown_option: \"usage\",\n missing_required_option: \"usage\",\n missing_required_argument: \"usage\",\n invalid_command_usage: \"usage\",\n linked_test_value_not_quoted: \"usage\",\n invalid_argument_value: \"validation\",\n health_findings: \"validation\",\n validation_findings: \"validation\",\n close_through_update: \"validation\",\n no_update_fields: \"validation\",\n unsupported_update_option: \"validation\",\n tracker_not_initialized: \"validation\",\n item_not_found: \"validation\",\n ownership_conflict: \"conflict\",\n lock_conflict: \"conflict\",\n terminal_state_conflict: \"conflict\",\n dependency_failed: \"runtime\",\n command_failed: \"runtime\",\n unknown_error: \"runtime\",\n});\n\n/** Implements resolve telemetry error category for the public runtime surface of this module. */\nexport function resolveTelemetryErrorCategory(\n errorCode: string | undefined,\n): TelemetryErrorCategory {\n const normalized = (errorCode ?? \"\").trim().toLowerCase();\n if (normalized.length === 0) {\n return \"unknown\";\n }\n const explicit = TELEMETRY_ERROR_CATEGORY_BY_CODE[normalized];\n if (typeof explicit === \"string\") {\n return explicit;\n }\n if (normalized.includes(\"conflict\") || normalized.includes(\"locked\")) {\n return \"conflict\";\n }\n if (\n normalized.startsWith(\"unknown_\") ||\n normalized.startsWith(\"missing_required_\")\n ) {\n return \"usage\";\n }\n if (\n normalized.startsWith(\"invalid_\") ||\n normalized.endsWith(\"_not_found\") ||\n normalized.includes(\"validation\")\n ) {\n return \"validation\";\n }\n if (normalized.endsWith(\"_error\") || normalized.endsWith(\"_failed\")) {\n return \"runtime\";\n }\n return \"unknown\";\n}\n","/**\n * @module types\n *\n * Defines the shared project-management data model used by CLI, SDK, MCP, and packages.\n */\n/** Supported values accepted by the builtin item type contract. */\nexport const BUILTIN_ITEM_TYPE_VALUES = [\n \"Epic\",\n \"Feature\",\n \"Task\",\n \"Chore\",\n \"Issue\",\n \"Decision\",\n \"Event\",\n \"Reminder\",\n \"Milestone\",\n \"Meeting\",\n \"Plan\",\n] as const;\n/** Supported values accepted by the item type contract. */\nexport const ITEM_TYPE_VALUES = BUILTIN_ITEM_TYPE_VALUES;\n/** Restricts builtin item type values accepted by command, SDK, and storage contracts. */\nexport type BuiltinItemType = (typeof BUILTIN_ITEM_TYPE_VALUES)[number];\n/** Restricts item type values accepted by command, SDK, and storage contracts. */\nexport type ItemType = string;\n\n/** Supported values accepted by the status contract. */\nexport const STATUS_VALUES = [\n \"draft\",\n \"open\",\n \"in_progress\",\n \"blocked\",\n \"closed\",\n \"canceled\",\n] as const;\n/** Restricts item status values accepted by command, SDK, and storage contracts. */\nexport type ItemStatus = string;\n\n/** Supported values accepted by the runtime status role contract. */\nexport const RUNTIME_STATUS_ROLE_VALUES = [\n \"draft\",\n \"active\",\n \"blocked\",\n \"terminal\",\n \"terminal_done\",\n \"terminal_canceled\",\n \"default_open\",\n \"default_close\",\n \"default_cancel\",\n] as const;\n/** Restricts runtime status role values accepted by command, SDK, and storage contracts. */\nexport type RuntimeStatusRole = (typeof RUNTIME_STATUS_ROLE_VALUES)[number];\n\n/** Supported values accepted by the runtime field type contract. */\nexport const RUNTIME_FIELD_TYPE_VALUES = [\n \"string\",\n \"number\",\n \"boolean\",\n \"string_array\",\n] as const;\n/** Restricts runtime field type values accepted by command, SDK, and storage contracts. */\nexport type RuntimeFieldType = (typeof RUNTIME_FIELD_TYPE_VALUES)[number];\n\n/** Supported values accepted by the runtime field command contract. */\nexport const RUNTIME_FIELD_COMMAND_VALUES = [\n \"create\",\n \"update\",\n \"update_many\",\n \"list\",\n \"search\",\n \"calendar\",\n \"context\",\n] as const;\n/** Restricts runtime field command values accepted by command, SDK, and storage contracts. */\nexport type RuntimeFieldCommand = (typeof RUNTIME_FIELD_COMMAND_VALUES)[number];\n\n/** Supported values accepted by the runtime unknown field policy contract. */\nexport const RUNTIME_UNKNOWN_FIELD_POLICY_VALUES = [\n \"allow\",\n \"warn\",\n \"reject\",\n] as const;\n/** Restricts runtime unknown field policy values accepted by command, SDK, and storage contracts. */\nexport type RuntimeUnknownFieldPolicy =\n (typeof RUNTIME_UNKNOWN_FIELD_POLICY_VALUES)[number];\n\n/** Supported values accepted by the dependency kind contract. */\nexport const DEPENDENCY_KIND_VALUES = [\n \"blocks\",\n \"parent\",\n \"child\",\n \"parent_child\",\n \"child_of\",\n \"related\",\n \"related_to\",\n \"discovered_from\",\n \"blocked_by\",\n \"incident_from\",\n \"epic\",\n \"supersedes\",\n \"task\",\n] as const;\n/** Restricts dependency kind values accepted by command, SDK, and storage contracts. */\nexport type DependencyKind = (typeof DEPENDENCY_KIND_VALUES)[number];\n\n/** Supported values accepted by the scope contract. */\nexport const SCOPE_VALUES = [\"project\", \"global\"] as const;\n/** Restricts link scope values accepted by command, SDK, and storage contracts. */\nexport type LinkScope = (typeof SCOPE_VALUES)[number];\n\n/** Supported values accepted by the risk contract. */\nexport const RISK_VALUES = [\"low\", \"medium\", \"high\", \"critical\"] as const;\n/** Restricts risk level values accepted by command, SDK, and storage contracts. */\nexport type RiskLevel = (typeof RISK_VALUES)[number];\n\n/** Supported values accepted by the issue severity contract. */\nexport const ISSUE_SEVERITY_VALUES = [\n \"low\",\n \"medium\",\n \"high\",\n \"critical\",\n] as const;\n/** Restricts issue severity values accepted by command, SDK, and storage contracts. */\nexport type IssueSeverity = (typeof ISSUE_SEVERITY_VALUES)[number];\n\n/** Supported values accepted by the confidence text contract. */\nexport const CONFIDENCE_TEXT_VALUES = [\"low\", \"medium\", \"high\"] as const;\n/** Restricts confidence text level values accepted by command, SDK, and storage contracts. */\nexport type ConfidenceTextLevel = (typeof CONFIDENCE_TEXT_VALUES)[number];\n/** Restricts confidence value values accepted by command, SDK, and storage contracts. */\nexport type ConfidenceValue = number | ConfidenceTextLevel;\n\n/** Supported values accepted by the item format contract. */\nexport const ITEM_FORMAT_VALUES = [\"toon\", \"json_markdown\"] as const;\n/** Restricts item format values accepted by command, SDK, and storage contracts. */\nexport type ItemFormat = (typeof ITEM_FORMAT_VALUES)[number];\n\n/** Supported values accepted by the sprint release format policy contract. */\nexport const SPRINT_RELEASE_FORMAT_POLICY_VALUES = [\n \"warn\",\n \"strict_error\",\n] as const;\n/** Restricts sprint release format policy values accepted by command, SDK, and storage contracts. */\nexport type SprintReleaseFormatPolicy =\n (typeof SPRINT_RELEASE_FORMAT_POLICY_VALUES)[number];\n/** Supported values accepted by the parent reference policy contract. */\nexport const PARENT_REFERENCE_POLICY_VALUES = [\"warn\", \"strict_error\"] as const;\n/** Restricts parent reference policy values accepted by command, SDK, and storage contracts. */\nexport type ParentReferencePolicy =\n (typeof PARENT_REFERENCE_POLICY_VALUES)[number];\n/** Supported values accepted by the validate metadata profile contract. */\nexport const VALIDATE_METADATA_PROFILE_VALUES = [\n \"core\",\n \"strict\",\n \"custom\",\n] as const;\n/** Restricts validate metadata profile values accepted by command, SDK, and storage contracts. */\nexport type ValidateMetadataProfile =\n (typeof VALIDATE_METADATA_PROFILE_VALUES)[number];\n/** Supported values accepted by the governance preset contract. */\nexport const GOVERNANCE_PRESET_VALUES = [\n \"minimal\",\n \"default\",\n \"strict\",\n \"custom\",\n] as const;\n/** Restricts governance preset values accepted by command, SDK, and storage contracts. */\nexport type GovernancePreset = (typeof GOVERNANCE_PRESET_VALUES)[number];\n/** Supported values accepted by the governance ownership enforcement contract. */\nexport const GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES = [\n \"none\",\n \"warn\",\n \"strict\",\n] as const;\n/** Restricts governance ownership enforcement values accepted by command, SDK, and storage contracts. */\nexport type GovernanceOwnershipEnforcement =\n (typeof GOVERNANCE_OWNERSHIP_ENFORCEMENT_VALUES)[number];\n/** Supported values accepted by the governance create mode default contract. */\nexport const GOVERNANCE_CREATE_MODE_DEFAULT_VALUES = [\n \"progressive\",\n \"strict\",\n] as const;\n/** Restricts governance create mode default values accepted by command, SDK, and storage contracts. */\nexport type GovernanceCreateModeDefault =\n (typeof GOVERNANCE_CREATE_MODE_DEFAULT_VALUES)[number];\n/** Supported values accepted by the governance close validation default contract. */\nexport const GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES = [\n \"off\",\n \"warn\",\n \"strict\",\n] as const;\n/** Restricts governance close validation default values accepted by command, SDK, and storage contracts. */\nexport type GovernanceCloseValidationDefault =\n (typeof GOVERNANCE_CLOSE_VALIDATION_DEFAULT_VALUES)[number];\n/** Supported values accepted by the governance workflow enforcement contract. */\nexport const GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES = [\n \"off\",\n \"warn\",\n \"strict\",\n] as const;\n/** Restricts governance workflow enforcement values accepted by command, SDK, and storage contracts. */\nexport type GovernanceWorkflowEnforcement =\n (typeof GOVERNANCE_WORKFLOW_ENFORCEMENT_VALUES)[number];\n/** Supported values accepted by the validate metadata required field contract. */\nexport const VALIDATE_METADATA_REQUIRED_FIELD_VALUES = [\n \"author\",\n \"acceptance_criteria\",\n \"estimated_minutes\",\n \"close_reason\",\n \"reviewer\",\n \"risk\",\n \"confidence\",\n \"sprint\",\n \"release\",\n] as const;\n/** Restricts validate metadata required field values accepted by command, SDK, and storage contracts. */\nexport type ValidateMetadataRequiredField =\n (typeof VALIDATE_METADATA_REQUIRED_FIELD_VALUES)[number];\n\n/** Supported values accepted by the recurrence frequency contract. */\nexport const RECURRENCE_FREQUENCY_VALUES = [\n \"daily\",\n \"weekly\",\n \"monthly\",\n \"yearly\",\n] as const;\n/** Restricts recurrence frequency values accepted by command, SDK, and storage contracts. */\nexport type RecurrenceFrequency = (typeof RECURRENCE_FREQUENCY_VALUES)[number];\n\n/** Supported values accepted by the recurrence weekday contract. */\nexport const RECURRENCE_WEEKDAY_VALUES = [\n \"mon\",\n \"tue\",\n \"wed\",\n \"thu\",\n \"fri\",\n \"sat\",\n \"sun\",\n] as const;\n/** Restricts recurrence weekday values accepted by command, SDK, and storage contracts. */\nexport type RecurrenceWeekday = (typeof RECURRENCE_WEEKDAY_VALUES)[number];\n\n/** Canonical week-order index for a recurrence weekday (mon=0 .. sun=6). Shared by item serialization, create/update parsing, and calendar expansion so weekday ordering cannot drift between those modules. */\nexport function weekdayOrderIndex(value: RecurrenceWeekday): number {\n return RECURRENCE_WEEKDAY_VALUES.indexOf(value);\n}\n\n/** Documents the dependency payload exchanged by command, SDK, and package integrations. */\nexport interface Dependency {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports kind for this contract. */\n kind: DependencyKind;\n /** ISO 8601 timestamp recording when created occurred. */\n created_at: string;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Value that configures or reports source kind for this contract. */\n source_kind?: string;\n}\n\n/** Documents the comment payload exchanged by command, SDK, and package integrations. */\nexport interface Comment {\n /** ISO 8601 timestamp recording when created occurred. */\n created_at: string;\n /** Value that configures or reports author for this contract. */\n author: string;\n /** Value that configures or reports text for this contract. */\n text: string;\n}\n\n/** Documents the log note payload exchanged by command, SDK, and package integrations. */\nexport interface LogNote {\n /** ISO 8601 timestamp recording when created occurred. */\n created_at: string;\n /** Value that configures or reports author for this contract. */\n author: string;\n /** Value that configures or reports text for this contract. */\n text: string;\n}\n\n/** Documents the linked file payload exchanged by command, SDK, and package integrations. */\nexport interface LinkedFile {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope: LinkScope;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the linked test payload exchanged by command, SDK, and package integrations. */\nexport interface LinkedTest {\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Filesystem path used for path resolution. */\n path?: string;\n /** Value that configures or reports scope for this contract. */\n scope: LinkScope;\n /** Value that configures or reports timeout seconds for this contract. */\n timeout_seconds?: number;\n /** Strategy used to control pm context behavior. */\n pm_context_mode?: \"schema\" | \"tracker\" | \"auto\";\n /** Value that configures or reports env set for this contract. */\n env_set?: Record<string, string>;\n /** Value that configures or reports env clear for this contract. */\n env_clear?: string[];\n /** Value that configures or reports shared host safe for this contract. */\n shared_host_safe?: boolean;\n /** Value that configures or reports assert stdout contains for this contract. */\n assert_stdout_contains?: string[];\n /** Value that configures or reports assert stdout regex for this contract. */\n assert_stdout_regex?: string[];\n /** Value that configures or reports assert stderr contains for this contract. */\n assert_stderr_contains?: string[];\n /** Value that configures or reports assert stderr regex for this contract. */\n assert_stderr_regex?: string[];\n /** Value that configures or reports assert stdout min lines for this contract. */\n assert_stdout_min_lines?: number;\n /** Value that configures or reports assert json field equals for this contract. */\n assert_json_field_equals?: Record<string, string>;\n /** Value that configures or reports assert json field gte for this contract. */\n assert_json_field_gte?: Record<string, number>;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the linked doc payload exchanged by command, SDK, and package integrations. */\nexport interface LinkedDoc {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope: LinkScope;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the reminder payload exchanged by command, SDK, and package integrations. */\nexport interface Reminder {\n /** Value that configures or reports at for this contract. */\n at: string;\n /** Value that configures or reports text for this contract. */\n text: string;\n}\n\n/** Documents the recurrence rule payload exchanged by command, SDK, and package integrations. */\nexport interface RecurrenceRule {\n /** Value that configures or reports freq for this contract. */\n freq: RecurrenceFrequency;\n /** Value that configures or reports interval for this contract. */\n interval?: number;\n /** Value that configures or reports count for this contract. */\n count?: number;\n /** Value that configures or reports until for this contract. */\n until?: string;\n /** Value that configures or reports by weekday for this contract. */\n by_weekday?: RecurrenceWeekday[];\n /** Value that configures or reports by month day for this contract. */\n by_month_day?: number[];\n /** Value that configures or reports exdates for this contract. */\n exdates?: string[];\n}\n\n/** Documents the calendar event payload exchanged by command, SDK, and package integrations. */\nexport interface CalendarEvent {\n /** ISO 8601 timestamp recording when start occurred. */\n start_at: string;\n /** ISO 8601 timestamp recording when end occurred. */\n end_at?: string;\n /** Value that configures or reports title for this contract. */\n title?: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports location for this contract. */\n location?: string;\n /** Value that configures or reports all day for this contract. */\n all_day?: boolean;\n /** Value that configures or reports timezone for this contract. */\n timezone?: string;\n /** Value that configures or reports recurrence for this contract. */\n recurrence?: RecurrenceRule;\n}\n\n/** Supported values accepted by the plan mode contract. */\nexport const PLAN_MODE_VALUES = [\n \"draft\",\n \"research\",\n \"review\",\n \"approved\",\n \"executing\",\n \"paused\",\n \"completed\",\n \"superseded\",\n] as const;\n/** Restricts plan mode values accepted by command, SDK, and storage contracts. */\nexport type PlanMode = (typeof PLAN_MODE_VALUES)[number];\n\n/** Supported values accepted by the plan step status contract. */\nexport const PLAN_STEP_STATUS_VALUES = [\n \"pending\",\n \"in_progress\",\n \"completed\",\n \"blocked\",\n \"skipped\",\n \"superseded\",\n] as const;\n/** Restricts plan step status values accepted by command, SDK, and storage contracts. */\nexport type PlanStepStatus = (typeof PLAN_STEP_STATUS_VALUES)[number];\n\n/** Supported values accepted by the plan harness contract. */\nexport const PLAN_HARNESS_VALUES = [\n \"codex\",\n \"claude-code\",\n \"cursor\",\n \"generic\",\n] as const;\n/** Restricts plan harness values accepted by command, SDK, and storage contracts. */\nexport type PlanHarness = (typeof PLAN_HARNESS_VALUES)[number];\n\n/** Supported values accepted by the plan step link kind contract. */\nexport const PLAN_STEP_LINK_KIND_VALUES = [\n \"related\",\n \"blocks\",\n \"blocked_by\",\n \"depends_on\",\n \"discovered_from\",\n \"implements\",\n \"verifies\",\n \"supersedes\",\n] as const;\n/** Restricts plan step link kind values accepted by command, SDK, and storage contracts. */\nexport type PlanStepLinkKind = (typeof PLAN_STEP_LINK_KIND_VALUES)[number];\n\n/** Documents the plan step link payload exchanged by command, SDK, and package integrations. */\nexport interface PlanStepLink {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports kind for this contract. */\n kind: PlanStepLinkKind;\n /** Value that configures or reports note for this contract. */\n note?: string;\n /** Value that configures or reports required before step for this contract. */\n required_before_step?: boolean;\n}\n\n/** Documents the plan step file payload exchanged by command, SDK, and package integrations. */\nexport interface PlanStepFile {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope?: LinkScope;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the plan step test payload exchanged by command, SDK, and package integrations. */\nexport interface PlanStepTest {\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Filesystem path used for path resolution. */\n path?: string;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the plan step doc payload exchanged by command, SDK, and package integrations. */\nexport interface PlanStepDoc {\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports scope for this contract. */\n scope?: LinkScope;\n /** Value that configures or reports note for this contract. */\n note?: string;\n}\n\n/** Documents the plan step payload exchanged by command, SDK, and package integrations. */\nexport interface PlanStep {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports order for this contract. */\n order: number;\n /** Value that configures or reports title for this contract. */\n title: string;\n /** Value that configures or reports body for this contract. */\n body?: string;\n /** Lifecycle state reported for status. */\n status: PlanStepStatus;\n /** Value that configures or reports owner for this contract. */\n owner?: string;\n /** Value that configures or reports evidence for this contract. */\n evidence?: string;\n /** Value that configures or reports blocked reason for this contract. */\n blocked_reason?: string;\n /** Value that configures or reports superseded by for this contract. */\n superseded_by?: string;\n /** Value that configures or reports linked items for this contract. */\n linked_items?: PlanStepLink[];\n /** Value that configures or reports files for this contract. */\n files?: PlanStepFile[];\n /** Value that configures or reports tests for this contract. */\n tests?: PlanStepTest[];\n /** Value that configures or reports docs for this contract. */\n docs?: PlanStepDoc[];\n /** ISO 8601 timestamp recording when created occurred. */\n created_at: string;\n /** ISO 8601 timestamp recording when updated occurred. */\n updated_at: string;\n /** ISO 8601 timestamp recording when completed occurred. */\n completed_at?: string;\n}\n\n/** Documents the plan decision payload exchanged by command, SDK, and package integrations. */\nexport interface PlanDecision {\n /** Value that configures or reports ts for this contract. */\n ts: string;\n /** Value that configures or reports author for this contract. */\n author: string;\n /** Value that configures or reports decision for this contract. */\n decision: string;\n /** Value that configures or reports rationale for this contract. */\n rationale?: string;\n /** Value that configures or reports evidence for this contract. */\n evidence?: string;\n /** Value that configures or reports step id for this contract. */\n step_id?: string;\n}\n\n/** Documents the plan discovery payload exchanged by command, SDK, and package integrations. */\nexport interface PlanDiscovery {\n /** Value that configures or reports ts for this contract. */\n ts: string;\n /** Value that configures or reports author for this contract. */\n author: string;\n /** Value that configures or reports text for this contract. */\n text: string;\n /** Value that configures or reports step id for this contract. */\n step_id?: string;\n}\n\n/** Documents the plan validation check payload exchanged by command, SDK, and package integrations. */\nexport interface PlanValidationCheck {\n /** Value that configures or reports text for this contract. */\n text: string;\n /** Value that configures or reports command for this contract. */\n command?: string;\n /** Value that configures or reports expected for this contract. */\n expected?: string;\n}\n\n/** Documents the item type option definition payload exchanged by command, SDK, and package integrations. */\nexport interface ItemTypeOptionDefinition {\n /** Value that configures or reports key for this contract. */\n key: string;\n /** Value that configures or reports values for this contract. */\n values: string[];\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports aliases for this contract. */\n aliases?: string[];\n /** Value that configures or reports description for this contract. */\n description?: string;\n}\n\n/** Documents the item type command option policy payload exchanged by command, SDK, and package integrations. */\nexport interface ItemTypeCommandOptionPolicy {\n /** Value that configures or reports command for this contract. */\n command: \"create\" | \"update\";\n /** Value that configures or reports option for this contract. */\n option: string;\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports visible for this contract. */\n visible?: boolean;\n /** Whether enabled applies to this operation. */\n enabled?: boolean;\n}\n\n/** Documents the item type definition payload exchanged by command, SDK, and package integrations. */\nexport interface ItemTypeDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Status assigned to newly created items of this type when `--status` is not provided. Falls back to the workflow's open status when unset or invalid. */\n default_status?: string;\n /** Value that configures or reports folder for this contract. */\n folder?: string;\n /** Value that configures or reports aliases for this contract. */\n aliases?: string[];\n /** Value that configures or reports required create fields for this contract. */\n required_create_fields?: string[];\n /** Value that configures or reports required create repeatables for this contract. */\n required_create_repeatables?: string[];\n /** Value that configures or reports options for this contract. */\n options?: ItemTypeOptionDefinition[];\n /** Value that configures or reports command option policies for this contract. */\n command_option_policies?: ItemTypeCommandOptionPolicy[];\n}\n\n/** Documents the runtime status definition payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeStatusDefinition {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports aliases for this contract. */\n aliases?: string[];\n /** Value that configures or reports roles for this contract. */\n roles?: RuntimeStatusRole[];\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports order for this contract. */\n order?: number;\n}\n\n/** Documents the runtime field definition payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeFieldDefinition {\n /** Value that configures or reports key for this contract. */\n key: string;\n /** Value that configures or reports metadata key for this contract. */\n metadata_key?: string;\n /**\n * @deprecated Use metadata_key.\n */\n front_matter_key?: string;\n /** Value that configures or reports cli flag for this contract. */\n cli_flag?: string;\n /** Value that configures or reports cli aliases for this contract. */\n cli_aliases?: string[];\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type?: RuntimeFieldType;\n /** Value that configures or reports commands for this contract. */\n commands?: RuntimeFieldCommand[];\n /** Value that configures or reports repeatable for this contract. */\n repeatable?: boolean;\n /** Value that configures or reports required for this contract. */\n required?: boolean;\n /** Value that configures or reports required on create for this contract. */\n required_on_create?: boolean;\n /** Value that configures or reports required types for this contract. */\n required_types?: string[];\n /** Value that configures or reports allow unset for this contract. */\n allow_unset?: boolean;\n}\n\n/** Documents the runtime workflow definition payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeWorkflowDefinition {\n /** Lifecycle state reported for draftthe record. */\n draft_status?: string;\n /** Lifecycle state reported for openthe record. */\n open_status?: string;\n /** Lifecycle state reported for in progressthe record. */\n in_progress_status?: string;\n /** Lifecycle state reported for blockedthe record. */\n blocked_status?: string;\n /** Lifecycle state reported for closethe record. */\n close_status?: string;\n /** Lifecycle state reported for canceledthe record. */\n canceled_status?: string;\n}\n\n/** Documents the runtime schema file config payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeSchemaFileConfig {\n /** Value that configures or reports types for this contract. */\n types?: string;\n /** Value that configures or reports statuses for this contract. */\n statuses?: string;\n /** Value that configures or reports fields for this contract. */\n fields?: string;\n /** Value that configures or reports workflows for this contract. */\n workflows?: string;\n}\n\n/** Per-type allowed-transition rule. A type with no matching entry is unrestricted; a type with an entry allows only the listed [from, to] status pairs (status tokens are resolved case-insensitively through the status registry alias map; a same-status no-op is always allowed). */\nexport interface TypeWorkflowDefinition {\n /** Schema type that determines the shape and validation rules for this value. */\n type: string;\n /** Value that configures or reports allowed transitions for this contract. */\n allowed_transitions: [string, string][];\n}\n\n/** Documents the runtime schema settings payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeSchemaSettings {\n /** Value that configures or reports version for this contract. */\n version: number;\n /** Value that configures or reports files for this contract. */\n files: RuntimeSchemaFileConfig;\n /** Value that configures or reports statuses for this contract. */\n statuses: RuntimeStatusDefinition[];\n /** Value that configures or reports fields for this contract. */\n fields: RuntimeFieldDefinition[];\n /** Value that configures or reports workflow for this contract. */\n workflow: RuntimeWorkflowDefinition;\n /** Value that configures or reports type workflows for this contract. */\n type_workflows?: TypeWorkflowDefinition[];\n /** Value that configures or reports unknown field policy for this contract. */\n unknown_field_policy: RuntimeUnknownFieldPolicy;\n}\n\n/** Documents the item test run summary payload exchanged by command, SDK, and package integrations. */\nexport interface ItemTestRunSummary {\n /** Executes the id operation through the package runtime. */\n run_id: string;\n /** Value that configures or reports kind for this contract. */\n kind: \"test\" | \"test-all\";\n /** Lifecycle state reported for status. */\n status: \"passed\" | \"failed\" | \"stopped\" | \"canceled\";\n /** ISO 8601 timestamp recording when started occurred. */\n started_at: string;\n /** ISO 8601 timestamp recording when finished occurred. */\n finished_at: string;\n /** ISO 8601 timestamp recording when recorded occurred. */\n recorded_at: string;\n /** Value that configures or reports attempt for this contract. */\n attempt?: number;\n /** Value that configures or reports resumed from for this contract. */\n resumed_from?: string;\n /** Value that configures or reports passed for this contract. */\n passed: number;\n /** Value that configures or reports failed for this contract. */\n failed: number;\n /** Value that configures or reports skipped for this contract. */\n skipped: number;\n /** Value that configures or reports items for this contract. */\n items?: number;\n /** Value that configures or reports linked tests for this contract. */\n linked_tests?: number;\n /** Value that configures or reports fail on skipped triggered for this contract. */\n fail_on_skipped_triggered?: boolean;\n}\n\n/** Documents the item metadata payload exchanged by command, SDK, and package integrations. */\nexport interface ItemMetadata {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports title for this contract. */\n title: string;\n /** Value that configures or reports description for this contract. */\n description: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type: ItemType;\n /** On-disk item-metadata format version. Absent means the implicit baseline (version 1) and is never serialized; populated only once an item advances past the baseline via a future storage migration. See core/item/item-format-version. */\n pm_format_version?: number;\n /** Schema type that determines the shape and validation rules for this value. */\n source_type?: string;\n /** Inputs that customize the type operation. */\n type_options?: Record<string, string>;\n /** Lifecycle state reported for status. */\n status: ItemStatus;\n /** Value that configures or reports priority for this contract. */\n priority: 0 | 1 | 2 | 3 | 4;\n /** Value that configures or reports tags for this contract. */\n tags: string[];\n /** ISO 8601 timestamp recording when created occurred. */\n created_at: string;\n /** ISO 8601 timestamp recording when updated occurred. */\n updated_at: string;\n /** Value that configures or reports deadline for this contract. */\n deadline?: string;\n /** Value that configures or reports reminders for this contract. */\n reminders?: Reminder[];\n /** Value that configures or reports events for this contract. */\n events?: CalendarEvent[];\n /** ISO 8601 timestamp recording when closed occurred. */\n closed_at?: string;\n /** Value that configures or reports assignee for this contract. */\n assignee?: string;\n /** Value that configures or reports source owner for this contract. */\n source_owner?: string;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Value that configures or reports estimated minutes for this contract. */\n estimated_minutes?: number;\n /** Value that configures or reports acceptance criteria for this contract. */\n acceptance_criteria?: string;\n /** Value that configures or reports design for this contract. */\n design?: string;\n /** Value that configures or reports external ref for this contract. */\n external_ref?: string;\n /** Value that configures or reports definition of ready for this contract. */\n definition_of_ready?: string;\n /** Value that configures or reports order for this contract. */\n order?: number;\n /** Value that configures or reports goal for this contract. */\n goal?: string;\n /** Value that configures or reports objective for this contract. */\n objective?: string;\n /** Value that configures or reports value for this contract. */\n value?: string;\n /** Value that configures or reports impact for this contract. */\n impact?: string;\n /** Value that configures or reports outcome for this contract. */\n outcome?: string;\n /** Value that configures or reports why now for this contract. */\n why_now?: string;\n /** Value that configures or reports parent for this contract. */\n parent?: string;\n /** Value that configures or reports reviewer for this contract. */\n reviewer?: string;\n /** Value that configures or reports risk for this contract. */\n risk?: RiskLevel;\n /** Value that configures or reports confidence for this contract. */\n confidence?: ConfidenceValue;\n /** Value that configures or reports sprint for this contract. */\n sprint?: string;\n /** Value that configures or reports release for this contract. */\n release?: string;\n /** Value that configures or reports blocked by for this contract. */\n blocked_by?: string;\n /** Value that configures or reports blocked reason for this contract. */\n blocked_reason?: string;\n /** Value that configures or reports unblock note for this contract. */\n unblock_note?: string;\n /** Value that configures or reports reporter for this contract. */\n reporter?: string;\n /** Value that configures or reports severity for this contract. */\n severity?: IssueSeverity;\n /** Value that configures or reports environment for this contract. */\n environment?: string;\n /** Value that configures or reports repro steps for this contract. */\n repro_steps?: string;\n /** Value that configures or reports resolution for this contract. */\n resolution?: string;\n /** Structured result returned by the expected operation. */\n expected_result?: string;\n /** Structured result returned by the actual operation. */\n actual_result?: string;\n /** Value that configures or reports affected version for this contract. */\n affected_version?: string;\n /** Value that configures or reports fixed version for this contract. */\n fixed_version?: string;\n /** Value that configures or reports component for this contract. */\n component?: string;\n /** Value that configures or reports regression for this contract. */\n regression?: boolean;\n /** Value that configures or reports customer impact for this contract. */\n customer_impact?: string;\n /** Value that configures or reports dependencies for this contract. */\n dependencies?: Dependency[];\n /** Value that configures or reports comments for this contract. */\n comments?: Comment[];\n /** Value that configures or reports notes for this contract. */\n notes?: LogNote[];\n /** Value that configures or reports learnings for this contract. */\n learnings?: LogNote[];\n /** Value that configures or reports files for this contract. */\n files?: LinkedFile[];\n /** Value that configures or reports tests for this contract. */\n tests?: LinkedTest[];\n /** Value that configures or reports test runs for this contract. */\n test_runs?: ItemTestRunSummary[];\n /** Value that configures or reports docs for this contract. */\n docs?: LinkedDoc[];\n /** Value that configures or reports close reason for this contract. */\n close_reason?: string;\n /** Value that configures or reports duplicate of for this contract. */\n duplicate_of?: string;\n /** Strategy used to control plan behavior. */\n plan_mode?: PlanMode;\n /** Value that configures or reports plan scope for this contract. */\n plan_scope?: string;\n /** Value that configures or reports plan harness for this contract. */\n plan_harness?: PlanHarness;\n /** Value that configures or reports plan steps for this contract. */\n plan_steps?: PlanStep[];\n /** Value that configures or reports plan decisions for this contract. */\n plan_decisions?: PlanDecision[];\n /** Value that configures or reports plan discoveries for this contract. */\n plan_discoveries?: PlanDiscovery[];\n /** Value that configures or reports plan validation for this contract. */\n plan_validation?: PlanValidationCheck[];\n /** Value that configures or reports plan resume context for this contract. */\n plan_resume_context?: string;\n [key: string]: unknown;\n}\n\n/** Documents the item document payload exchanged by command, SDK, and package integrations. */\nexport interface ItemDocument {\n /** Value that configures or reports metadata for this contract. */\n metadata: ItemMetadata;\n /** Value that configures or reports body for this contract. */\n body: string;\n}\n\n/** Documents the history patch op payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryPatchOp {\n /** Value that configures or reports op for this contract. */\n op: \"add\" | \"remove\" | \"replace\" | \"move\" | \"copy\" | \"test\";\n /** Filesystem path used for path resolution. */\n path: string;\n /** Value that configures or reports from for this contract. */\n from?: string;\n /** Value that configures or reports value for this contract. */\n value?: unknown;\n}\n\n/** Documents the history entry payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryEntry {\n /** Value that configures or reports ts for this contract. */\n ts: string;\n /** Value that configures or reports author for this contract. */\n author: string;\n /** Value that configures or reports op for this contract. */\n op: string;\n /** Value that configures or reports patch for this contract. */\n patch: HistoryPatchOp[];\n /** Value that configures or reports before hash for this contract. */\n before_hash: string;\n /** Value that configures or reports after hash for this contract. */\n after_hash: string;\n /** Human-readable explanation suitable for logs and agent-facing output. */\n message?: string;\n}\n\n/** Supported values accepted by the context depth contract. */\nexport const CONTEXT_DEPTH_VALUES = [\n \"brief\",\n \"standard\",\n \"deep\",\n \"full\",\n] as const;\n/** Restricts context depth values accepted by command, SDK, and storage contracts. */\nexport type ContextDepth = (typeof CONTEXT_DEPTH_VALUES)[number];\n\n/** Supported values accepted by the context section contract. */\nexport const CONTEXT_SECTION_VALUES = [\n \"hierarchy\",\n \"activity\",\n \"progress\",\n \"recently_created\",\n \"unparented\",\n \"blockers\",\n \"files\",\n \"workload\",\n \"staleness\",\n \"tests\",\n] as const;\n/** Restricts context section name values accepted by command, SDK, and storage contracts. */\nexport type ContextSectionName = (typeof CONTEXT_SECTION_VALUES)[number];\n\n/** Documents the context section settings payload exchanged by command, SDK, and package integrations. */\nexport interface ContextSectionSettings {\n /** Value that configures or reports hierarchy for this contract. */\n hierarchy: boolean;\n /** Value that configures or reports activity for this contract. */\n activity: boolean;\n /** Value that configures or reports progress for this contract. */\n progress: boolean;\n /** Value that configures or reports recently created for this contract. */\n recently_created: boolean;\n /** Value that configures or reports unparented for this contract. */\n unparented: boolean;\n /** Value that configures or reports blockers for this contract. */\n blockers: boolean;\n /** Value that configures or reports files for this contract. */\n files: boolean;\n /** Value that configures or reports workload for this contract. */\n workload: boolean;\n /** Value that configures or reports staleness for this contract. */\n staleness: boolean;\n /** Value that configures or reports tests for this contract. */\n tests: boolean;\n}\n\n/** Documents the context settings payload exchanged by command, SDK, and package integrations. */\nexport interface ContextSettings {\n /** Fallback depth used when callers do not provide an override. */\n default_depth: ContextDepth;\n /** Value that configures or reports activity limit for this contract. */\n activity_limit: number;\n /** Value that configures or reports stale threshold days for this contract. */\n stale_threshold_days: number;\n /** Value that configures or reports sections for this contract. */\n sections: ContextSectionSettings;\n}\n\n/** Documents the governance settings payload exchanged by command, SDK, and package integrations. */\nexport interface GovernanceSettings {\n /** Value that configures or reports preset for this contract. */\n preset: GovernancePreset;\n /** Value that configures or reports ownership enforcement for this contract. */\n ownership_enforcement: GovernanceOwnershipEnforcement;\n /** Creates mode default using the validated operation inputs. */\n create_mode_default: GovernanceCreateModeDefault;\n /** Value that configures or reports close validation default for this contract. */\n close_validation_default: GovernanceCloseValidationDefault;\n /** Value that configures or reports require close reason for this contract. */\n require_close_reason: boolean;\n /** Value that configures or reports parent reference for this contract. */\n parent_reference: ParentReferencePolicy;\n /** Value that configures or reports metadata profile for this contract. */\n metadata_profile: ValidateMetadataProfile;\n /** Value that configures or reports force required for stale lock for this contract. */\n force_required_for_stale_lock: boolean;\n /** Schema type that determines the shape and validation rules for this value. */\n create_default_type?: string;\n /** Per-type allowed-transition enforcement mode for `pm update --status`. Read raw from settings (not preset-derived) so existing projects are unaffected when unset; defaults to \"off\". */\n workflow_enforcement?: GovernanceWorkflowEnforcement;\n}\n\n/** Restricts extension policy mode values accepted by command, SDK, and storage contracts. */\nexport type ExtensionPolicyMode = \"off\" | \"warn\" | \"enforce\";\n/** Restricts extension trust mode values accepted by command, SDK, and storage contracts. */\nexport type ExtensionTrustMode = \"off\" | \"warn\" | \"enforce\";\n/** Restricts extension sandbox profile values accepted by command, SDK, and storage contracts. */\nexport type ExtensionSandboxProfile = \"none\" | \"restricted\" | \"strict\";\n\n/** Documents the extension policy override settings payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionPolicyOverrideSettings {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Whether disabled applies to this operation. */\n disabled?: boolean;\n /** Value that configures or reports require trusted for this contract. */\n require_trusted?: boolean;\n /** Value that configures or reports require provenance for this contract. */\n require_provenance?: boolean;\n /** Value that configures or reports sandbox profile for this contract. */\n sandbox_profile?: ExtensionSandboxProfile;\n /** Value that configures or reports allowed capabilities for this contract. */\n allowed_capabilities?: string[];\n /** Value that configures or reports blocked capabilities for this contract. */\n blocked_capabilities?: string[];\n /** Value that configures or reports allowed surfaces for this contract. */\n allowed_surfaces?: string[];\n /** Value that configures or reports blocked surfaces for this contract. */\n blocked_surfaces?: string[];\n /** Value that configures or reports allowed commands for this contract. */\n allowed_commands?: string[];\n /** Value that configures or reports blocked commands for this contract. */\n blocked_commands?: string[];\n /** Value that configures or reports allowed actions for this contract. */\n allowed_actions?: string[];\n /** Value that configures or reports blocked actions for this contract. */\n blocked_actions?: string[];\n /** Value that configures or reports allowed services for this contract. */\n allowed_services?: string[];\n /** Value that configures or reports blocked services for this contract. */\n blocked_services?: string[];\n}\n\n/** Documents the extension policy settings payload exchanged by command, SDK, and package integrations. */\nexport interface ExtensionPolicySettings {\n /** Value that configures or reports mode for this contract. */\n mode: ExtensionPolicyMode;\n /** Strategy used to control trust behavior. */\n trust_mode: ExtensionTrustMode;\n /** Value that configures or reports require provenance for this contract. */\n require_provenance: boolean;\n /** Value that configures or reports trusted extensions for this contract. */\n trusted_extensions: string[];\n /** Fallback sandbox profile used when callers do not provide an override. */\n default_sandbox_profile: ExtensionSandboxProfile;\n /** Value that configures or reports allowed extensions for this contract. */\n allowed_extensions: string[];\n /** Value that configures or reports blocked extensions for this contract. */\n blocked_extensions: string[];\n /** Value that configures or reports allowed capabilities for this contract. */\n allowed_capabilities: string[];\n /** Value that configures or reports blocked capabilities for this contract. */\n blocked_capabilities: string[];\n /** Value that configures or reports allowed surfaces for this contract. */\n allowed_surfaces: string[];\n /** Value that configures or reports blocked surfaces for this contract. */\n blocked_surfaces: string[];\n /** Value that configures or reports allowed commands for this contract. */\n allowed_commands: string[];\n /** Value that configures or reports blocked commands for this contract. */\n blocked_commands: string[];\n /** Value that configures or reports allowed actions for this contract. */\n allowed_actions: string[];\n /** Value that configures or reports blocked actions for this contract. */\n blocked_actions: string[];\n /** Value that configures or reports allowed services for this contract. */\n allowed_services: string[];\n /** Value that configures or reports blocked services for this contract. */\n blocked_services: string[];\n /** Value that configures or reports extension overrides for this contract. */\n extension_overrides: ExtensionPolicyOverrideSettings[];\n}\n\n/** Documents the agent guidance settings payload exchanged by command, SDK, and package integrations. */\nexport interface AgentGuidanceSettings {\n /** Value that configures or reports prompt completed for this contract. */\n prompt_completed: boolean;\n /** Value that configures or reports declined for this contract. */\n declined: boolean;\n /** ISO 8601 timestamp recording when declined occurred. */\n declined_at: string;\n /** Value that configures or reports template version for this contract. */\n template_version: number;\n /** Value that configures or reports last checked files for this contract. */\n last_checked_files: string[];\n}\n\n/** Restricts search mutation refresh policy values accepted by command, SDK, and storage contracts. */\nexport type SearchMutationRefreshPolicy =\n | \"cache_only\"\n | \"semantic_configured\"\n | \"semantic_auto\";\n\n/** Documents the search query expansion settings payload exchanged by command, SDK, and package integrations. */\nexport interface SearchQueryExpansionSettings {\n /** Whether enabled applies to this operation. */\n enabled: boolean;\n /** Value that configures or reports provider for this contract. */\n provider: string;\n}\n\n/** Documents the search rerank settings payload exchanged by command, SDK, and package integrations. */\nexport interface SearchRerankSettings {\n /** Whether enabled applies to this operation. */\n enabled: boolean;\n /** Value that configures or reports model for this contract. */\n model: string;\n /** Value that configures or reports top k for this contract. */\n top_k: number;\n}\n\n/**\n * Config-driven policy for automatic history-stream compaction triage.\n *\n * When `enabled`, `pm health` surfaces an advisory warning for any history\n * stream whose non-empty entry count exceeds `max_entries`, and `pm\n * history-compact` bulk mode uses `max_entries` as its default `--all-over`\n * threshold so the configured policy drives corpus-wide sweeps. `trigger`\n * records operator intent — both values raise the health advisory; `auto`\n * additionally signals that scheduled/automatic sweeps are expected.\n */\nexport interface HistoryCompactPolicy {\n /** Whether enabled applies to this operation. */\n enabled: boolean;\n /** Value that configures or reports max entries for this contract. */\n max_entries: number;\n /** Value that configures or reports trigger for this contract. */\n trigger: \"health_warn\" | \"auto\";\n}\n\n/** Documents the pm settings payload exchanged by command, SDK, and package integrations. */\nexport interface PmSettings {\n /** Value that configures or reports version for this contract. */\n version: number;\n /** Value that configures or reports id prefix for this contract. */\n id_prefix: string;\n /** Value that configures or reports author default for this contract. */\n author_default: string;\n /** Value that configures or reports item format for this contract. */\n item_format: ItemFormat;\n /** Value that configures or reports locks for this contract. */\n locks: {\n ttl_seconds: number;\n /** Bounded wait budget (milliseconds) for acquiring a contended item lock before surfacing lock_conflict. 0 disables waiting (fail-fast). Overridable per invocation via PM_LOCK_WAIT_MS. */\n wait_ms: number;\n };\n /** Retention policy for bulk-mutation rollback checkpoints written by `update-many`/`close-many`. `pm gc --scope checkpoints` prunes checkpoint files older than `retention_days`; checkpoints with an unparseable `created_at` are retained (safety-first, mirroring the stale-lock sweep). */\n checkpoints: {\n retention_days: number;\n };\n /** Value that configures or reports output for this contract. */\n output: {\n default_format: \"toon\" | \"json\";\n };\n /** Value that configures or reports history for this contract. */\n history: {\n missing_stream: \"auto_create\" | \"strict_error\";\n compact_policy: HistoryCompactPolicy;\n };\n /** Value that configures or reports validation for this contract. */\n validation: {\n sprint_release_format: SprintReleaseFormatPolicy;\n parent_reference: ParentReferencePolicy;\n metadata_profile: ValidateMetadataProfile;\n metadata_required_fields: ValidateMetadataRequiredField[];\n lifecycle_stale_blocker_reason_patterns: string[];\n lifecycle_closure_like_blocked_reason_patterns: string[];\n lifecycle_closure_like_resolution_patterns: string[];\n lifecycle_closure_like_actual_result_patterns: string[];\n /** Per-type default estimates (minutes) used by `pm validate --auto-fix --fix-scope estimates` to backfill missing `estimated_minutes` (GH-212). Keys are item type names (case-insensitive); values are positive minutes that override the built-in defaults. Empty by default. */\n estimate_defaults_by_type: Record<string, number>;\n };\n /** Value that configures or reports governance for this contract. */\n governance: GovernanceSettings;\n /** Value that configures or reports workflow for this contract. */\n workflow: {\n definition_of_done: string[];\n };\n /** Value that configures or reports testing for this contract. */\n testing: {\n record_results_to_items: boolean;\n };\n /** Value that configures or reports telemetry for this contract. */\n telemetry: {\n enabled: boolean;\n first_run_prompt_completed: boolean;\n capture_level: \"minimal\" | \"redacted\" | \"max\";\n endpoint: string;\n installation_id: string;\n retention_days: number;\n };\n /** Value that configures or reports agent guidance for this contract. */\n agent_guidance: AgentGuidanceSettings;\n /** Value that configures or reports item types for this contract. */\n item_types: {\n definitions: ItemTypeDefinition[];\n };\n /** Value that configures or reports schema for this contract. */\n schema: RuntimeSchemaSettings;\n /** Value that configures or reports extensions for this contract. */\n extensions: {\n enabled: string[];\n disabled: string[];\n policy: ExtensionPolicySettings;\n };\n /** Value that configures or reports search for this contract. */\n search: {\n score_threshold: number;\n hybrid_semantic_weight: number;\n max_results: number;\n embedding_model: string;\n embedding_corpus_max_characters?: number;\n embedding_batch_size: number;\n embedding_timeout_ms: number;\n scanner_max_batch_retries: number;\n provider?: string;\n /** Optional allow-list of corpus field names embedded for semantic search (see DEFAULT_SEARCH_CORPUS_FIELDS in core/search/corpus.ts). When unset or empty, the full default field set is used (backward compatible). When set, only the named fields are embedded — letting teams opt structured signals (priority, assignee, risk, acceptance_criteria, etc.) in/out for token efficiency. Changing this re-flags items stale on the next refresh. */\n corpus_fields?: string[];\n mutation_refresh_policy: SearchMutationRefreshPolicy;\n query_expansion: SearchQueryExpansionSettings;\n rerank: SearchRerankSettings;\n /** Offline BM25 lexical-ranking parameters (pm-75k9), applied when `search.provider` is `bm25` (or auto-selected as the offline fallback) for semantic/hybrid queries. `k1` controls term-frequency saturation, `b` controls document-length normalization. Unset → Lucene defaults (1.2/0.75). */\n bm25?: {\n k1?: number;\n b?: number;\n };\n tuning?: {\n title_exact_bonus?: number;\n title_weight?: number;\n description_weight?: number;\n tags_weight?: number;\n status_weight?: number;\n body_weight?: number;\n comments_weight?: number;\n notes_weight?: number;\n learnings_weight?: number;\n dependencies_weight?: number;\n linked_content_weight?: number;\n };\n };\n /** Value that configures or reports providers for this contract. */\n providers: {\n openai: {\n base_url: string;\n api_key: string;\n model: string;\n };\n ollama: {\n base_url: string;\n model: string;\n };\n };\n /** Value that configures or reports context for this contract. */\n context: ContextSettings;\n /** Value that configures or reports vector store for this contract. */\n vector_store: {\n adapter?: string;\n collection_name: string;\n qdrant: {\n url: string;\n api_key: string;\n };\n lancedb: {\n path: string;\n };\n };\n}\n","/**\n * @module core/item/item-type-definition\n *\n * Defines item parsing, formatting, and lifecycle helpers for Item Type Definition.\n */\nimport type {\n ItemTypeCommandOptionPolicy,\n ItemTypeDefinition,\n ItemTypeOptionDefinition,\n} from \"../../types/index.js\";\n\n/**\n * Shared, pure normalization for {@link ItemTypeDefinition} objects, single-sourced\n * across the runtime item-type registry and settings persistence (pm-v798).\n *\n * The only genuine difference between the two callers is how a command-option\n * policy's `command` field is resolved:\n * - the runtime registry consumes untrusted extension/file definitions, so it\n * must trim+lowercase and reject anything that is not \"create\"/\"update\";\n * - settings persistence operates on already-validated definitions, so it keeps\n * the typed `command` value verbatim.\n *\n * That single difference is injected via {@link NormalizeItemTypeDefinitionOptions.resolvePolicyCommand};\n * everything else (name trim, optional folder, aliases, required_create_* fields,\n * options normalization, policy dedupe key + stable sort) is shared.\n */\n\n/** Dedupe + sort a string list: trim, drop blanks, unique, locale-sorted. */\nexport function normalizeItemTypeStringList(\n values: string[] | undefined,\n): string[] {\n return [\n ...new Set(\n (values ?? [])\n .map((value) => value.trim())\n .filter((value) => value.length > 0),\n ),\n ].sort((left, right) => left.localeCompare(right));\n}\n\n/** Normalize one type-option definition, or null when its key is blank. */\nexport function normalizeItemTypeOption(\n option: ItemTypeOptionDefinition,\n): ItemTypeOptionDefinition | null {\n const key = option.key.trim();\n if (key.length === 0) {\n return null;\n }\n const aliases = normalizeItemTypeStringList(option.aliases);\n const description = option.description?.trim();\n return {\n key,\n values: normalizeItemTypeStringList(option.values),\n required: option.required === true ? true : undefined,\n aliases: aliases.length > 0 ? aliases : undefined,\n description:\n description && description.length > 0 ? description : undefined,\n };\n}\n\n/** Resolves a raw policy `command` value to the canonical \"create\"/\"update\" type, or null to drop the policy. Lets each layer plug in its own strictness. */\nexport type ResolvePolicyCommand = (\n command: string,\n) => ItemTypeCommandOptionPolicy[\"command\"] | null;\n\n/** Pass-through resolver used by settings persistence: the value is already typed \"create\" | \"update\" by the settings validator, so it is kept verbatim. */\nexport const keepPolicyCommand: ResolvePolicyCommand = (command) =>\n command as ItemTypeCommandOptionPolicy[\"command\"];\n\n/** Strict resolver used by the runtime registry: trims + lowercases and rejects anything other than \"create\"/\"update\". */\nexport const strictPolicyCommand: ResolvePolicyCommand = (command) => {\n const normalized = command.trim().toLowerCase();\n return normalized === \"create\" || normalized === \"update\" ? normalized : null;\n};\n\n/** Normalize one command-option policy, or null when invalid (blank option / rejected command). */\nexport function normalizeItemTypeCommandOptionPolicy(\n policy: ItemTypeCommandOptionPolicy,\n resolvePolicyCommand: ResolvePolicyCommand,\n): ItemTypeCommandOptionPolicy | null {\n const command = resolvePolicyCommand(policy.command);\n if (command === null) {\n return null;\n }\n const option = policy.option.trim();\n if (option.length === 0) {\n return null;\n }\n return {\n command,\n option,\n required: policy.required,\n visible: policy.visible,\n enabled: policy.enabled,\n };\n}\n\n/** Dedupe by `${command}:${option-lowercased}` and stable-sort by command then option. */\nexport function normalizeItemTypeCommandOptionPolicies(\n policies: ItemTypeCommandOptionPolicy[] | undefined,\n resolvePolicyCommand: ResolvePolicyCommand,\n): ItemTypeCommandOptionPolicy[] {\n const dedupedByKey = new Map<string, ItemTypeCommandOptionPolicy>();\n for (const policy of policies ?? []) {\n const normalized = normalizeItemTypeCommandOptionPolicy(\n policy,\n resolvePolicyCommand,\n );\n if (!normalized) {\n continue;\n }\n dedupedByKey.set(\n `${normalized.command}:${normalized.option.toLowerCase()}`,\n normalized,\n );\n }\n return [...dedupedByKey.values()].sort((left, right) =>\n left.command === right.command\n ? left.option.localeCompare(right.option)\n : left.command.localeCompare(right.command),\n );\n}\n\n/** Documents the normalize item type definition options payload exchanged by command, SDK, and package integrations. */\nexport interface NormalizeItemTypeDefinitionOptions {\n /** How to resolve a raw policy `command` value (defaults to {@link keepPolicyCommand}). */\n resolvePolicyCommand?: ResolvePolicyCommand;\n}\n\nfunction normalizeOptionalStringList(\n values: string[] | undefined,\n preservePresence: boolean,\n): string[] | undefined {\n return preservePresence ? normalizeItemTypeStringList(values) : undefined;\n}\n\nfunction optionalNonEmptyString(value: string | undefined): string | undefined {\n const normalized = value?.trim();\n return normalized && normalized.length > 0 ? normalized : undefined;\n}\n\n/**\n * Normalize a full {@link ItemTypeDefinition}, returning null when the name is blank.\n *\n * Optional collection fields (`folder`, `aliases`, `required_create_fields`,\n * `required_create_repeatables`, `options`, `command_option_policies`) are only\n * emitted when present on the input (presence-preserving) so the distinction\n * between \"unset\" and \"set-but-empty\" survives the round-trip.\n */\nexport function normalizeItemTypeDefinition(\n definition: ItemTypeDefinition,\n options: NormalizeItemTypeDefinitionOptions = {},\n): ItemTypeDefinition | null {\n const resolvePolicyCommand =\n options.resolvePolicyCommand ?? keepPolicyCommand;\n const name = definition.name.trim();\n if (name.length === 0) {\n return null;\n }\n\n const hasRequiredCreateFields =\n definition.required_create_fields !== undefined;\n const hasRequiredCreateRepeatables =\n definition.required_create_repeatables !== undefined;\n const hasOptions = definition.options !== undefined;\n const hasCommandOptionPolicies =\n definition.command_option_policies !== undefined;\n\n const aliases = normalizeItemTypeStringList(definition.aliases);\n const normalizedOptions = (definition.options ?? [])\n .map((option) => normalizeItemTypeOption(option))\n .filter((option): option is ItemTypeOptionDefinition => option !== null)\n .sort((left, right) => left.key.localeCompare(right.key));\n const commandOptionPolicies = normalizeItemTypeCommandOptionPolicies(\n definition.command_option_policies,\n resolvePolicyCommand,\n );\n\n return {\n name,\n description: optionalNonEmptyString(definition.description),\n default_status: optionalNonEmptyString(definition.default_status),\n folder: optionalNonEmptyString(definition.folder),\n aliases: aliases.length > 0 ? aliases : undefined,\n required_create_fields: normalizeOptionalStringList(\n definition.required_create_fields,\n hasRequiredCreateFields,\n ),\n required_create_repeatables: normalizeOptionalStringList(\n definition.required_create_repeatables,\n hasRequiredCreateRepeatables,\n ),\n options: hasOptions ? normalizedOptions : undefined,\n command_option_policies: hasCommandOptionPolicies\n ? commandOptionPolicies\n : undefined,\n };\n}\n","/**\n * @module core/item/type-registry\n *\n * Defines item parsing, formatting, and lifecycle helpers for Type Registry.\n */\nimport { TYPE_TO_FOLDER } from \"../shared/constants.js\";\nimport type { ExtensionRegistrationRegistry } from \"../extensions/loader.js\";\nimport type {\n ItemTypeCommandOptionPolicy,\n ItemTypeDefinition,\n ItemTypeOptionDefinition,\n PmSettings,\n} from \"../../types/index.js\";\nimport { ITEM_TYPE_VALUES } from \"../../types/index.js\";\nimport {\n normalizeItemTypeDefinition as normalizeSharedItemTypeDefinition,\n normalizeItemTypeStringList,\n strictPolicyCommand,\n} from \"./item-type-definition.js\";\n\n/** Fallback required create fields used when callers do not provide an override. */\nexport const DEFAULT_REQUIRED_CREATE_FIELDS = [\n \"title\",\n \"description\",\n \"status\",\n \"priority\",\n \"tags\",\n \"body\",\n \"deadline\",\n \"estimatedMinutes\",\n \"acceptanceCriteria\",\n \"author\",\n \"message\",\n \"assignee\",\n] as const;\n\n/** Fallback required create repeatables used when callers do not provide an override. */\nexport const DEFAULT_REQUIRED_CREATE_REPEATABLES = [\n \"dep\",\n \"comment\",\n \"note\",\n \"learning\",\n \"file\",\n \"test\",\n \"doc\",\n] as const;\n\n/** Restricts command option policy command values accepted by command, SDK, and storage contracts. */\nexport type CommandOptionPolicyCommand = \"create\" | \"update\";\n\n// Keep aligned with cli/commands/shared-unset-fields.ts. This core registry\n// cannot import CLI unset metadata without creating a core -> CLI dependency.\n/** Public contract for common mutation command option keys, shared by SDK and presentation-layer consumers. */\nexport const COMMON_MUTATION_COMMAND_OPTION_KEYS = [\n \"deadline\",\n \"estimatedMinutes\",\n \"acceptanceCriteria\",\n \"definitionOfReady\",\n \"order\",\n \"goal\",\n \"objective\",\n \"value\",\n \"impact\",\n \"outcome\",\n \"whyNow\",\n \"assignee\",\n \"parent\",\n \"reviewer\",\n \"risk\",\n \"confidence\",\n \"sprint\",\n \"release\",\n \"blockedBy\",\n \"blockedReason\",\n \"unblockNote\",\n \"reporter\",\n \"severity\",\n \"environment\",\n \"reproSteps\",\n \"resolution\",\n \"expectedResult\",\n \"actualResult\",\n \"affectedVersion\",\n \"fixedVersion\",\n \"component\",\n \"regression\",\n \"customerImpact\",\n] as const;\n\nconst CREATE_COMMAND_OPTION_KEYS = [\n \"title\",\n \"description\",\n \"type\",\n \"status\",\n \"priority\",\n \"tags\",\n \"body\",\n ...COMMON_MUTATION_COMMAND_OPTION_KEYS,\n \"author\",\n \"message\",\n \"dep\",\n \"comment\",\n \"note\",\n \"learning\",\n \"file\",\n \"test\",\n \"doc\",\n \"reminder\",\n \"event\",\n \"typeOption\",\n \"field\",\n] as const;\n\nconst UPDATE_COMMAND_OPTION_KEYS = [\n \"title\",\n \"description\",\n \"body\",\n \"status\",\n \"closeReason\",\n \"priority\",\n \"type\",\n \"tags\",\n ...COMMON_MUTATION_COMMAND_OPTION_KEYS,\n \"author\",\n \"message\",\n \"comment\",\n \"note\",\n \"learning\",\n \"file\",\n \"test\",\n \"doc\",\n \"reminder\",\n \"event\",\n \"typeOption\",\n \"field\",\n \"ownershipMetadataBypass\",\n \"ownershipDependencyBypass\",\n \"force\",\n] as const;\n\nconst SHARED_COMMAND_OPTION_ALIASES: Record<string, string> = {\n \"close-reason\": \"closeReason\",\n close_reason: \"closeReason\",\n \"estimated-minutes\": \"estimatedMinutes\",\n estimated_minutes: \"estimatedMinutes\",\n estimate: \"estimatedMinutes\",\n \"acceptance-criteria\": \"acceptanceCriteria\",\n acceptance_criteria: \"acceptanceCriteria\",\n ac: \"acceptanceCriteria\",\n \"definition-of-ready\": \"definitionOfReady\",\n definition_of_ready: \"definitionOfReady\",\n rank: \"order\",\n \"why-now\": \"whyNow\",\n why_now: \"whyNow\",\n \"blocked-by\": \"blockedBy\",\n blocked_by: \"blockedBy\",\n \"blocked-reason\": \"blockedReason\",\n blocked_reason: \"blockedReason\",\n \"unblock-note\": \"unblockNote\",\n unblock_note: \"unblockNote\",\n \"repro-steps\": \"reproSteps\",\n repro_steps: \"reproSteps\",\n \"expected-result\": \"expectedResult\",\n expected_result: \"expectedResult\",\n \"actual-result\": \"actualResult\",\n actual_result: \"actualResult\",\n \"affected-version\": \"affectedVersion\",\n affected_version: \"affectedVersion\",\n \"fixed-version\": \"fixedVersion\",\n fixed_version: \"fixedVersion\",\n \"customer-impact\": \"customerImpact\",\n customer_impact: \"customerImpact\",\n \"type-option\": \"typeOption\",\n type_option: \"typeOption\",\n type_options: \"typeOption\",\n};\n\nconst CREATE_COMMAND_OPTION_ALIASES: Record<string, string> = {\n ...SHARED_COMMAND_OPTION_ALIASES,\n};\n\nconst UPDATE_COMMAND_OPTION_ALIASES: Record<string, string> = {\n ...SHARED_COMMAND_OPTION_ALIASES,\n};\n\nconst COMMON_MUTATION_COMMAND_OPTION_FLAG_LABEL_ENTRIES = [\n [\"deadline\", \"--deadline\"],\n [\"estimatedMinutes\", \"--estimate/--estimated-minutes\"],\n [\"acceptanceCriteria\", \"--acceptance-criteria/--ac\"],\n [\"definitionOfReady\", \"--definition-of-ready\"],\n [\"order\", \"--order/--rank\"],\n [\"goal\", \"--goal\"],\n [\"objective\", \"--objective\"],\n [\"value\", \"--value\"],\n [\"impact\", \"--impact\"],\n [\"outcome\", \"--outcome\"],\n [\"whyNow\", \"--why-now\"],\n [\"assignee\", \"--assignee\"],\n [\"parent\", \"--parent\"],\n [\"reviewer\", \"--reviewer\"],\n [\"risk\", \"--risk\"],\n [\"confidence\", \"--confidence\"],\n [\"sprint\", \"--sprint\"],\n [\"release\", \"--release\"],\n [\"blockedBy\", \"--blocked-by\"],\n [\"blockedReason\", \"--blocked-reason\"],\n [\"unblockNote\", \"--unblock-note\"],\n [\"reporter\", \"--reporter\"],\n [\"severity\", \"--severity\"],\n [\"environment\", \"--environment\"],\n [\"reproSteps\", \"--repro-steps\"],\n [\"resolution\", \"--resolution\"],\n [\"expectedResult\", \"--expected-result\"],\n [\"actualResult\", \"--actual-result\"],\n [\"affectedVersion\", \"--affected-version\"],\n [\"fixedVersion\", \"--fixed-version\"],\n [\"component\", \"--component\"],\n [\"regression\", \"--regression\"],\n [\"customerImpact\", \"--customer-impact\"],\n] as const;\n\nconst LINKED_RESOURCE_COMMAND_OPTION_FLAG_LABEL_ENTRIES = [\n [\"comment\", \"--comment\"],\n [\"note\", \"--note\"],\n [\"learning\", \"--learning\"],\n [\"file\", \"--file\"],\n [\"test\", \"--test\"],\n [\"doc\", \"--doc\"],\n [\"reminder\", \"--reminder\"],\n [\"event\", \"--event\"],\n [\"typeOption\", \"--type-option\"],\n] as const;\n\nfunction commandOptionLabelMap(\n entries: ReadonlyArray<readonly [string, string]>,\n): Record<string, string> {\n return Object.fromEntries(entries);\n}\n\nconst CREATE_COMMAND_OPTION_FLAG_LABELS = commandOptionLabelMap([\n [\"title\", \"--title\"],\n [\"description\", \"--description\"],\n [\"type\", \"--type\"],\n [\"status\", \"--status\"],\n [\"priority\", \"--priority\"],\n [\"tags\", \"--tags\"],\n [\"body\", \"--body\"],\n ...COMMON_MUTATION_COMMAND_OPTION_FLAG_LABEL_ENTRIES,\n [\"author\", \"--author\"],\n [\"message\", \"--message\"],\n [\"dep\", \"--dep\"],\n ...LINKED_RESOURCE_COMMAND_OPTION_FLAG_LABEL_ENTRIES,\n]);\n\nconst UPDATE_COMMAND_OPTION_FLAG_LABELS = commandOptionLabelMap([\n [\"title\", \"--title\"],\n [\"description\", \"--description\"],\n [\"body\", \"--body\"],\n [\"status\", \"--status\"],\n [\"closeReason\", \"--close-reason\"],\n [\"priority\", \"--priority\"],\n [\"type\", \"--type\"],\n [\"tags\", \"--tags\"],\n ...COMMON_MUTATION_COMMAND_OPTION_FLAG_LABEL_ENTRIES,\n ...LINKED_RESOURCE_COMMAND_OPTION_FLAG_LABEL_ENTRIES,\n [\"author\", \"--author\"],\n [\"message\", \"--message\"],\n [\"force\", \"--force\"],\n]);\n\n/** Documents the command option policy state payload exchanged by command, SDK, and package integrations. */\nexport interface CommandOptionPolicyState {\n /** Value that configures or reports required for this contract. */\n required: string[];\n /** Value that configures or reports hidden for this contract. */\n hidden: string[];\n /** Whether disabled applies to this operation. */\n disabled: string[];\n /** Value that configures or reports errors for this contract. */\n errors: string[];\n}\n\n/** Documents the resolved item type definition payload exchanged by command, SDK, and package integrations. */\nexport interface ResolvedItemTypeDefinition {\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Optional human description carried from the type definition. */\n description?: string;\n /** Value that configures or reports folder for this contract. */\n folder: string;\n /** Value that configures or reports aliases for this contract. */\n aliases: string[];\n /** Optional per-type status applied at create time when `--status` is omitted. */\n default_status?: string;\n /** Value that configures or reports required create fields for this contract. */\n required_create_fields: string[];\n /** Value that configures or reports required create repeatables for this contract. */\n required_create_repeatables: string[];\n /** Value that configures or reports options for this contract. */\n options: ItemTypeOptionDefinition[];\n /** Value that configures or reports command option policies for this contract. */\n command_option_policies: ItemTypeCommandOptionPolicy[];\n}\n\n/** Documents the item type registry payload exchanged by command, SDK, and package integrations. */\nexport interface ItemTypeRegistry {\n /** Value that configures or reports types for this contract. */\n types: string[];\n /** Value that configures or reports folders for this contract. */\n folders: string[];\n /** Value that configures or reports type to folder for this contract. */\n type_to_folder: Record<string, string>;\n /** Schema type that determines the shape and validation rules for this value. */\n by_type: Record<string, ResolvedItemTypeDefinition>;\n /** Schema type that determines the shape and validation rules for this value. */\n alias_to_type: Record<string, string>;\n}\n\nfunction normalizeCommandOptionToken(value: string): string {\n return value.trim().replace(/^--+/, \"\").toLowerCase();\n}\n\nfunction commandOptionKeys(\n command: CommandOptionPolicyCommand,\n): readonly string[] {\n return command === \"create\"\n ? CREATE_COMMAND_OPTION_KEYS\n : UPDATE_COMMAND_OPTION_KEYS;\n}\n\nfunction commandOptionAliases(\n command: CommandOptionPolicyCommand,\n): Record<string, string> {\n return command === \"create\"\n ? CREATE_COMMAND_OPTION_ALIASES\n : UPDATE_COMMAND_OPTION_ALIASES;\n}\n\n/** Implements canonicalize command option key for the public runtime surface of this module. */\nexport function canonicalizeCommandOptionKey(\n command: CommandOptionPolicyCommand,\n rawOption: string,\n): string | undefined {\n const normalizedToken = normalizeCommandOptionToken(rawOption);\n if (normalizedToken.length === 0) {\n return undefined;\n }\n const aliased = commandOptionAliases(command)[normalizedToken];\n if (aliased) {\n return aliased;\n }\n return commandOptionKeys(command).find(\n (candidate) => candidate.toLowerCase() === normalizedToken,\n );\n}\n\n/** Implements command option flag label for the public runtime surface of this module. */\nexport function commandOptionFlagLabel(\n command: CommandOptionPolicyCommand,\n optionKey: string,\n): string {\n const labels =\n command === \"create\"\n ? CREATE_COMMAND_OPTION_FLAG_LABELS\n : UPDATE_COMMAND_OPTION_FLAG_LABELS;\n return (\n labels[optionKey] ??\n `--${optionKey.replace(/([A-Z])/g, \"-$1\").toLowerCase()}`\n );\n}\n\n/** Implements to default folder for the public runtime surface of this module. */\nexport function toDefaultFolder(name: string): string {\n const normalized = toSlugToken(name);\n if (normalized.length === 0) {\n return \"items\";\n }\n return normalized.endsWith(\"s\") ? normalized : `${normalized}s`;\n}\n\nfunction toSlugToken(value: string): string {\n const trimmed = value.trim().toLowerCase();\n let slug = \"\";\n let pendingDash = false;\n for (const character of trimmed) {\n const code = character.charCodeAt(0);\n const isAlpha = code >= 97 && code <= 122;\n const isDigit = code >= 48 && code <= 57;\n if (isAlpha || isDigit) {\n if (pendingDash && slug.length > 0) {\n slug += \"-\";\n }\n slug += character;\n pendingDash = false;\n continue;\n }\n if (slug.length > 0) {\n pendingDash = true;\n }\n }\n return slug;\n}\n\n// Runtime registry consumes untrusted extension/file definitions, so it uses the\n// strict policy-command resolver (trim + lowercase, reject non-create/update). All\n// other normalization is single-sourced from ./item-type-definition.ts (pm-v798).\nfunction normalizeTypeDefinition(\n definition: ItemTypeDefinition,\n): ItemTypeDefinition | null {\n return normalizeSharedItemTypeDefinition(definition, {\n resolvePolicyCommand: strictPolicyCommand,\n });\n}\n\nfunction readStringArray(\n record: Record<string, unknown>,\n key: string,\n): string[] | undefined {\n const value = record[key];\n return Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : undefined;\n}\n\nfunction coerceOptionDefinitionFromUnknown(\n raw: unknown,\n): ItemTypeOptionDefinition | null {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return null;\n }\n const optionRecord = raw as Record<string, unknown>;\n if (typeof optionRecord.key !== \"string\") {\n return null;\n }\n return {\n key: optionRecord.key,\n values: readStringArray(optionRecord, \"values\") ?? [],\n required:\n optionRecord.required === undefined\n ? undefined\n : Boolean(optionRecord.required),\n aliases: readStringArray(optionRecord, \"aliases\"),\n description:\n typeof optionRecord.description === \"string\"\n ? optionRecord.description\n : undefined,\n };\n}\n\nfunction coerceCommandOptionPolicyFromUnknown(\n raw: unknown,\n): ItemTypeCommandOptionPolicy | null {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return null;\n }\n const policyRecord = raw as Record<string, unknown>;\n if (\n typeof policyRecord.command !== \"string\" ||\n typeof policyRecord.option !== \"string\"\n ) {\n return null;\n }\n const normalizedCommand = policyRecord.command.trim().toLowerCase();\n if (normalizedCommand !== \"create\" && normalizedCommand !== \"update\") {\n return null;\n }\n return {\n command: normalizedCommand,\n option: policyRecord.option,\n required:\n policyRecord.required === undefined\n ? undefined\n : Boolean(policyRecord.required),\n visible:\n policyRecord.visible === undefined\n ? undefined\n : Boolean(policyRecord.visible),\n enabled:\n policyRecord.enabled === undefined\n ? undefined\n : Boolean(policyRecord.enabled),\n };\n}\n\nfunction coerceOptionDefinitionsFromRecord(\n record: Record<string, unknown>,\n): ItemTypeOptionDefinition[] | undefined {\n if (!Array.isArray(record.options)) {\n return undefined;\n }\n return record.options\n .map((entry) => coerceOptionDefinitionFromUnknown(entry))\n .filter((entry): entry is ItemTypeOptionDefinition => entry !== null);\n}\n\nfunction coerceCommandOptionPoliciesFromRecord(\n record: Record<string, unknown>,\n): ItemTypeCommandOptionPolicy[] | undefined {\n if (!Array.isArray(record.command_option_policies)) {\n return undefined;\n }\n return record.command_option_policies\n .map((entry) => coerceCommandOptionPolicyFromUnknown(entry))\n .filter((entry): entry is ItemTypeCommandOptionPolicy => entry !== null);\n}\n\nfunction coerceTypeDefinitionFromUnknown(\n raw: unknown,\n): ItemTypeDefinition | null {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n const name = typeof record.name === \"string\" ? record.name : \"\";\n if (name.trim().length === 0) {\n return null;\n }\n const folder = typeof record.folder === \"string\" ? record.folder : undefined;\n const description =\n typeof record.description === \"string\" ? record.description : undefined;\n const defaultStatus =\n typeof record.default_status === \"string\"\n ? record.default_status\n : undefined;\n return {\n name,\n description,\n default_status: defaultStatus,\n folder,\n aliases: readStringArray(record, \"aliases\"),\n required_create_fields: readStringArray(record, \"required_create_fields\"),\n required_create_repeatables: readStringArray(\n record,\n \"required_create_repeatables\",\n ),\n options: coerceOptionDefinitionsFromRecord(record),\n command_option_policies: coerceCommandOptionPoliciesFromRecord(record),\n };\n}\n\nfunction resolveDefinitionRequiredCreateFields(\n normalizedDefinition: ItemTypeDefinition,\n existing: ResolvedItemTypeDefinition | undefined,\n): string[] {\n return normalizedDefinition.required_create_fields\n ? normalizeItemTypeStringList(normalizedDefinition.required_create_fields)\n : (existing?.required_create_fields ?? []);\n}\n\nfunction resolveDefinitionRequiredCreateRepeatables(\n normalizedDefinition: ItemTypeDefinition,\n existing: ResolvedItemTypeDefinition | undefined,\n): string[] {\n return normalizedDefinition.required_create_repeatables\n ? normalizeItemTypeStringList(\n normalizedDefinition.required_create_repeatables,\n )\n : (existing?.required_create_repeatables ?? []);\n}\n\nfunction resolveDefinitionOptions(\n normalizedDefinition: ItemTypeDefinition,\n existing: ResolvedItemTypeDefinition | undefined,\n): ItemTypeOptionDefinition[] {\n return normalizedDefinition.options\n ? normalizedDefinition.options\n : existing?.options\n ? [...existing.options]\n : [];\n}\n\nfunction resolveDefinitionCommandOptionPolicies(\n normalizedDefinition: ItemTypeDefinition,\n existing: ResolvedItemTypeDefinition | undefined,\n): ItemTypeCommandOptionPolicy[] {\n return normalizedDefinition.command_option_policies\n ? normalizedDefinition.command_option_policies\n : existing?.command_option_policies\n ? [...existing.command_option_policies]\n : [];\n}\n\nfunction buildResolvedTypeDefinition(\n normalizedDefinition: ItemTypeDefinition,\n existing: ResolvedItemTypeDefinition | undefined,\n): ResolvedItemTypeDefinition {\n const keepName = existing?.name ?? normalizedDefinition.name;\n const description = normalizedDefinition.description ?? existing?.description;\n const defaultStatus =\n normalizedDefinition.default_status ?? existing?.default_status;\n const resolvedDefinition: ResolvedItemTypeDefinition = {\n name: keepName,\n folder:\n normalizedDefinition.folder ??\n existing?.folder ??\n toDefaultFolder(keepName),\n aliases: normalizeItemTypeStringList([\n ...(existing?.aliases ?? []),\n ...(normalizedDefinition.aliases ?? []),\n ]),\n required_create_fields: resolveDefinitionRequiredCreateFields(\n normalizedDefinition,\n existing,\n ),\n required_create_repeatables: resolveDefinitionRequiredCreateRepeatables(\n normalizedDefinition,\n existing,\n ),\n options: resolveDefinitionOptions(normalizedDefinition, existing),\n command_option_policies: resolveDefinitionCommandOptionPolicies(\n normalizedDefinition,\n existing,\n ),\n };\n if (description) {\n resolvedDefinition.description = description;\n }\n if (defaultStatus) {\n resolvedDefinition.default_status = defaultStatus;\n }\n return resolvedDefinition;\n}\n\nfunction applyTypeDefinitions(\n source: ItemTypeDefinition[],\n target: Map<string, ResolvedItemTypeDefinition>,\n): void {\n for (const rawDefinition of source) {\n const normalizedDefinition = normalizeTypeDefinition(rawDefinition);\n if (!normalizedDefinition) {\n continue;\n }\n const lowerName = normalizedDefinition.name.toLowerCase();\n const existing = target.get(lowerName);\n target.set(\n lowerName,\n buildResolvedTypeDefinition(normalizedDefinition, existing),\n );\n }\n}\n\nfunction collectExtensionTypeDefinitions(\n registrations: ExtensionRegistrationRegistry | null | undefined,\n): ItemTypeDefinition[] {\n if (!registrations) {\n return [];\n }\n const definitions: ItemTypeDefinition[] = [];\n for (const registration of registrations.item_types ?? []) {\n const typeDefinitionsRaw = (registration as { types?: unknown[] }).types;\n if (!Array.isArray(typeDefinitionsRaw)) {\n continue;\n }\n for (const rawDefinition of typeDefinitionsRaw) {\n const normalized = coerceTypeDefinitionFromUnknown(rawDefinition);\n if (normalized) {\n definitions.push(normalized);\n }\n }\n }\n return definitions;\n}\n\n/** Implements resolve item type registry for the public runtime surface of this module. */\nexport function resolveItemTypeRegistry(\n settings: PmSettings,\n extensionRegistrations:\n | ExtensionRegistrationRegistry\n | null\n | undefined = null,\n): ItemTypeRegistry {\n const byLowerName = new Map<string, ResolvedItemTypeDefinition>();\n for (const builtin of ITEM_TYPE_VALUES) {\n byLowerName.set(builtin.toLowerCase(), {\n name: builtin,\n folder: TYPE_TO_FOLDER[builtin],\n aliases: [],\n required_create_fields: [...DEFAULT_REQUIRED_CREATE_FIELDS],\n required_create_repeatables: [...DEFAULT_REQUIRED_CREATE_REPEATABLES],\n options: [],\n command_option_policies: [],\n });\n }\n\n applyTypeDefinitions(settings.item_types?.definitions ?? [], byLowerName);\n applyTypeDefinitions(\n collectExtensionTypeDefinitions(extensionRegistrations),\n byLowerName,\n );\n\n const definitions = [...byLowerName.values()].sort((left, right) =>\n left.name.localeCompare(right.name),\n );\n const byType: Record<string, ResolvedItemTypeDefinition> = {};\n const aliasToType: Record<string, string> = {};\n const typeToFolder: Record<string, string> = {};\n for (const definition of definitions) {\n byType[definition.name] = definition;\n typeToFolder[definition.name] = definition.folder;\n aliasToType[definition.name.toLowerCase()] = definition.name;\n for (const alias of definition.aliases) {\n aliasToType[alias.toLowerCase()] = definition.name;\n }\n }\n const folders = [\n ...new Set(definitions.map((definition) => definition.folder)),\n ].sort((left, right) => left.localeCompare(right));\n return {\n types: definitions.map((definition) => definition.name),\n folders,\n type_to_folder: typeToFolder,\n by_type: byType,\n alias_to_type: aliasToType,\n };\n}\n\n/** Implements resolve type name for the public runtime surface of this module. */\nexport function resolveTypeName(\n rawType: string | undefined,\n registry: ItemTypeRegistry,\n): string | undefined {\n if (rawType === undefined) {\n return undefined;\n }\n return registry.alias_to_type[rawType.trim().toLowerCase()];\n}\n\n/** Implements resolve type definition for the public runtime surface of this module. */\nexport function resolveTypeDefinition(\n typeName: string | undefined,\n registry: ItemTypeRegistry,\n): ResolvedItemTypeDefinition | undefined {\n const resolvedName = resolveTypeName(typeName, registry);\n if (!resolvedName) {\n return undefined;\n }\n return registry.by_type[resolvedName];\n}\n\nfunction applyBaseRequiredCommandOptions(\n state: Pick<CommandOptionPolicyState, \"errors\"> & { required: Set<string> },\n typeDefinition: ResolvedItemTypeDefinition,\n command: CommandOptionPolicyCommand,\n baseRequiredOptions: Iterable<string>,\n): void {\n for (const rawBase of baseRequiredOptions) {\n const canonical = canonicalizeCommandOptionKey(command, rawBase);\n if (canonical) {\n state.required.add(canonical);\n continue;\n }\n state.errors.push(\n `Unsupported base required option \"${rawBase}\" for command \"${command}\" on type \"${typeDefinition.name}\"`,\n );\n }\n}\n\nfunction applyBooleanPolicySet(\n target: Set<string>,\n option: string,\n enabled: boolean,\n): void {\n if (enabled) {\n target.add(option);\n return;\n }\n target.delete(option);\n}\n\nfunction applyCommandOptionPolicy(\n state: Omit<CommandOptionPolicyState, \"required\" | \"hidden\" | \"disabled\"> & {\n required: Set<string>;\n hidden: Set<string>;\n disabled: Set<string>;\n },\n typeDefinition: ResolvedItemTypeDefinition,\n command: CommandOptionPolicyCommand,\n policy: ItemTypeCommandOptionPolicy,\n): void {\n const canonical = canonicalizeCommandOptionKey(command, policy.option);\n if (!canonical) {\n state.errors.push(\n `Unsupported command_option_policies option \"${policy.option}\" for command \"${command}\" on type \"${typeDefinition.name}\"`,\n );\n return;\n }\n if (policy.required !== undefined) {\n applyBooleanPolicySet(state.required, canonical, policy.required);\n }\n if (policy.visible !== undefined) {\n applyBooleanPolicySet(state.hidden, canonical, !policy.visible);\n }\n if (policy.enabled !== undefined) {\n applyBooleanPolicySet(state.disabled, canonical, !policy.enabled);\n }\n}\n\nfunction applyCommandOptionPolicies(\n state: Omit<CommandOptionPolicyState, \"required\" | \"hidden\" | \"disabled\"> & {\n required: Set<string>;\n hidden: Set<string>;\n disabled: Set<string>;\n },\n typeDefinition: ResolvedItemTypeDefinition,\n command: CommandOptionPolicyCommand,\n): void {\n for (const policy of typeDefinition.command_option_policies) {\n if (policy.command === command) {\n applyCommandOptionPolicy(state, typeDefinition, command, policy);\n }\n }\n}\n\nfunction appendRequiredDisabledPolicyErrors(\n state: Pick<CommandOptionPolicyState, \"errors\"> & {\n required: Set<string>;\n disabled: Set<string>;\n },\n typeDefinition: ResolvedItemTypeDefinition,\n command: CommandOptionPolicyCommand,\n): void {\n for (const option of state.required) {\n if (state.disabled.has(option)) {\n state.errors.push(\n `Option \"${option}\" cannot be both required and disabled for command \"${command}\" on type \"${typeDefinition.name}\"`,\n );\n }\n }\n}\n\n/** Implements resolve command option policy state for the public runtime surface of this module. */\nexport function resolveCommandOptionPolicyState(\n typeDefinition: ResolvedItemTypeDefinition,\n command: CommandOptionPolicyCommand,\n baseRequiredOptions: Iterable<string>,\n): CommandOptionPolicyState {\n const errors: string[] = [];\n const required = new Set<string>();\n const hidden = new Set<string>();\n const disabled = new Set<string>();\n const state = { required, hidden, disabled, errors };\n\n applyBaseRequiredCommandOptions(\n state,\n typeDefinition,\n command,\n baseRequiredOptions,\n );\n applyCommandOptionPolicies(state, typeDefinition, command);\n appendRequiredDisabledPolicyErrors(state, typeDefinition, command);\n\n return {\n required: [...required],\n hidden: [...hidden].sort((left, right) => left.localeCompare(right)),\n disabled: [...disabled].sort((left, right) => left.localeCompare(right)),\n errors,\n };\n}\n\nfunction buildTypeOptionAliasMap(\n typeDefinition: ResolvedItemTypeDefinition,\n): Map<string, ItemTypeOptionDefinition> {\n const optionByAlias = new Map<string, ItemTypeOptionDefinition>();\n for (const option of typeDefinition.options) {\n optionByAlias.set(option.key.toLowerCase(), option);\n for (const alias of option.aliases ?? []) {\n optionByAlias.set(alias.toLowerCase(), option);\n }\n }\n return optionByAlias;\n}\n\nfunction resolveTypeOptionValue(\n optionDefinition: ItemTypeOptionDefinition,\n trimmedValue: string,\n errors: string[],\n): string | undefined {\n const allowedValues = optionDefinition.values;\n if (allowedValues.length === 0) {\n return trimmedValue;\n }\n const valueLookup = new Map(\n allowedValues.map((value) => [value.toLowerCase(), value]),\n );\n const canonical = valueLookup.get(trimmedValue.toLowerCase());\n if (!canonical) {\n errors.push(\n `Invalid value \"${trimmedValue}\" for type option \"${optionDefinition.key}\". Allowed: ${allowedValues.join(\", \")}`,\n );\n return undefined;\n }\n return canonical;\n}\n\n/** Implements validate type options for the public runtime surface of this module. */\nexport function validateTypeOptions(\n typeName: string,\n rawTypeOptions: Record<string, string> | undefined,\n registry: ItemTypeRegistry,\n): { normalized: Record<string, string> | undefined; errors: string[] } {\n const typeDefinition = resolveTypeDefinition(typeName, registry);\n if (!typeDefinition) {\n return {\n normalized: undefined,\n errors: [`Unknown type \"${typeName}\"`],\n };\n }\n const errors: string[] = [];\n const optionByAlias = buildTypeOptionAliasMap(typeDefinition);\n\n const normalized: Record<string, string> = {};\n for (const [rawKey, rawValue] of Object.entries(rawTypeOptions ?? {})) {\n const trimmedKey = rawKey.trim();\n const trimmedValue = rawValue.trim();\n if (trimmedKey.length === 0) {\n errors.push(\"type option keys must not be empty\");\n continue;\n }\n if (trimmedValue.length === 0) {\n errors.push(`type option \"${trimmedKey}\" must not be empty`);\n continue;\n }\n const optionDefinition = optionByAlias.get(trimmedKey.toLowerCase());\n if (!optionDefinition) {\n const allowed = typeDefinition.options\n .map((option) => option.key)\n .join(\", \");\n errors.push(\n typeDefinition.options.length > 0\n ? `Unknown type option \"${trimmedKey}\" for type \"${typeDefinition.name}\". Allowed: ${allowed}`\n : `Type \"${typeDefinition.name}\" does not define any configurable type options`,\n );\n continue;\n }\n const resolvedValue = resolveTypeOptionValue(\n optionDefinition,\n trimmedValue,\n errors,\n );\n if (resolvedValue === undefined) {\n continue;\n }\n normalized[optionDefinition.key] = resolvedValue;\n }\n\n for (const option of typeDefinition.options) {\n if (option.required && !(option.key in normalized)) {\n errors.push(\n `Missing required type option \"${option.key}\" for type \"${typeDefinition.name}\"`,\n );\n }\n }\n\n const sortedKeys = Object.keys(normalized).sort((left, right) =>\n left.localeCompare(right),\n );\n if (sortedKeys.length === 0) {\n return {\n normalized: undefined,\n errors,\n };\n }\n return {\n normalized: Object.fromEntries(\n sortedKeys.map((key) => [key, normalized[key]]),\n ),\n errors,\n };\n}\n","/**\n * @module core/store/paths\n *\n * Reads and writes tracker storage with format-aware helpers for Paths.\n */\nimport { readFileSync, statSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n PM_DIRNAME,\n SETTINGS_FILENAME,\n TYPE_TO_FOLDER,\n} from \"../shared/constants.js\";\nimport { toDefaultFolder } from \"../item/type-registry.js\";\nimport type { ItemFormat, ItemType } from \"../../types/index.js\";\n\n/** Public contract for item file extension by format, shared by SDK and presentation-layer consumers. */\nexport const ITEM_FILE_EXTENSION_BY_FORMAT: Record<\n ItemFormat,\n \".md\" | \".toon\"\n> = {\n json_markdown: \".md\",\n toon: \".toon\",\n};\n\nconst ITEM_FORMAT_BY_EXTENSION = {\n \".md\": \"json_markdown\",\n \".toon\": \"toon\",\n} as const satisfies Record<string, ItemFormat>;\n\n/** Public contract for item file extensions, shared by SDK and presentation-layer consumers. */\nexport const ITEM_FILE_EXTENSIONS: Array<\n keyof typeof ITEM_FORMAT_BY_EXTENSION\n> = [\".md\", \".toon\"];\n\nfunction pathExists(pathValue: string): boolean {\n try {\n statSync(pathValue);\n return true;\n } catch {\n return false;\n }\n}\n\n// Adopting a bare <dir>/settings.json during implicit ancestor discovery must\n// not let an unrelated tool's settings.json hijack tracker resolution (and\n// receive pm writes), so root-layout candidates need a pm-specific marker.\n// `pm init` always writes both markers; explicit --path/PM_PATH targets skip\n// this check because they carry user intent.\nfunction isPmSettingsFile(settingsPath: string): boolean {\n try {\n const parsed: unknown = JSON.parse(readFileSync(settingsPath, \"utf8\"));\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n Array.isArray(parsed)\n ) {\n return false;\n }\n return \"id_prefix\" in parsed || \"item_format\" in parsed;\n } catch {\n return false;\n }\n}\n\nfunction discoverPmRootFromAncestors(cwd: string): string | undefined {\n let current = path.resolve(cwd);\n while (true) {\n const candidateRoot = path.join(current, PM_DIRNAME);\n const candidateSettingsPath = path.join(candidateRoot, SETTINGS_FILENAME);\n if (pathExists(candidateSettingsPath)) {\n return candidateRoot;\n }\n // Root-layout trackers (`pm init <dir>` writes settings.json directly into\n // <dir>) must be discoverable too; otherwise implicit invocations — and the\n // pm_root handed to extensions — fall back to a non-existent\n // <cwd>/.agents/pm (GH-495).\n const rootLayoutSettingsPath = path.join(current, SETTINGS_FILENAME);\n if (\n pathExists(rootLayoutSettingsPath) &&\n isPmSettingsFile(rootLayoutSettingsPath)\n ) {\n return current;\n }\n const parent = path.dirname(current);\n if (parent === current) {\n return undefined;\n }\n current = parent;\n }\n}\n\n/** Implements resolve pm root for the public runtime surface of this module. */\nexport function resolvePmRoot(cwd: string, cliPath?: string): string {\n const envPath = process.env.PM_PATH;\n const explicitPath = cliPath?.trim() || envPath?.trim();\n if (explicitPath) {\n const resolved = path.resolve(cwd, explicitPath);\n // When an explicit --path/PM_PATH points at a project root that contains an\n // initialized `.agents/pm`, resolve into it. Without this, an agent passing\n // the directory where it ran `pm init` (which creates `<dir>/.agents/pm`)\n // hits a hard \"tracker not initialized\" dead-end, while cwd discovery walks\n // up to find the same `.agents/pm`. We only redirect when the path itself is\n // not already a tracker root, so `pm init --path <dir>` (which writes\n // `<dir>/settings.json` directly) and existing tracker roots keep working.\n if (!pathExists(getSettingsPath(resolved))) {\n const nestedRoot = path.join(resolved, PM_DIRNAME);\n if (pathExists(getSettingsPath(nestedRoot))) {\n return nestedRoot;\n }\n }\n return resolved;\n }\n const discoveredRoot = discoverPmRootFromAncestors(cwd);\n if (discoveredRoot) {\n return discoveredRoot;\n }\n const selected = PM_DIRNAME;\n return path.resolve(cwd, selected);\n}\n\n/** Resolve the project workspace that owns a tracker root. */\nexport function resolveWorkspaceRoot(pmRoot: string): string {\n const normalizedRoot = path.resolve(pmRoot);\n const parent = path.dirname(normalizedRoot);\n return path.basename(normalizedRoot) === \"pm\" && path.basename(parent) === \".agents\"\n ? path.dirname(parent)\n : normalizedRoot;\n}\n\n/** Implements resolve global pm root for the public runtime surface of this module. */\nexport function resolveGlobalPmRoot(cwd: string): string {\n const envPath = process.env.PM_GLOBAL_PATH?.trim();\n const selected =\n envPath && envPath.length > 0\n ? envPath\n : path.join(os.homedir(), \".pm-cli\");\n return path.resolve(cwd, selected);\n}\n\n/** Implements get settings path for the public runtime surface of this module. */\nexport function getSettingsPath(pmRoot: string): string {\n return path.join(pmRoot, SETTINGS_FILENAME);\n}\n\n/** Implements get type dir path for the public runtime surface of this module. */\nexport function getTypeDirPath(\n pmRoot: string,\n type: ItemType,\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n): string {\n const folder = typeToFolder[type] ?? toDefaultFolder(type);\n return path.join(pmRoot, folder);\n}\n\n/** Implements get item path for the public runtime surface of this module. */\nexport function getItemPath(\n pmRoot: string,\n type: ItemType,\n id: string,\n itemFormat: ItemFormat = \"toon\",\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n): string {\n return path.join(\n getTypeDirPath(pmRoot, type, typeToFolder),\n `${id}${ITEM_FILE_EXTENSION_BY_FORMAT[itemFormat]}`,\n );\n}\n\n/** Implements get item format from path for the public runtime surface of this module. */\nexport function getItemFormatFromPath(itemPath: string): ItemFormat | null {\n const normalizedItemPath = itemPath.replaceAll(\"\\\\\", \"/\");\n const extension = path.posix\n .extname(normalizedItemPath)\n .toLowerCase() as keyof typeof ITEM_FORMAT_BY_EXTENSION;\n return ITEM_FORMAT_BY_EXTENSION[extension] ?? null;\n}\n\n/** Implements get history path for the public runtime surface of this module. */\nexport function getHistoryPath(pmRoot: string, id: string): string {\n return path.join(pmRoot, \"history\", `${id}.jsonl`);\n}\n\n/** Implements get lock path for the public runtime surface of this module. */\nexport function getLockPath(pmRoot: string, id: string): string {\n return path.join(pmRoot, \"locks\", `${id}.lock`);\n}\n\n/** Implements get runtime path for the public runtime surface of this module. */\nexport function getRuntimePath(pmRoot: string): string {\n return path.join(pmRoot, \"runtime\");\n}\n\n/** Implements get test runs path for the public runtime surface of this module. */\nexport function getTestRunsPath(pmRoot: string): string {\n return path.join(getRuntimePath(pmRoot), \"test-runs\");\n}\n\n/** Implements get test runs records path for the public runtime surface of this module. */\nexport function getTestRunsRecordsPath(pmRoot: string): string {\n return path.join(getTestRunsPath(pmRoot), \"runs\");\n}\n\n/** Implements get test run record path for the public runtime surface of this module. */\nexport function getTestRunRecordPath(pmRoot: string, runId: string): string {\n return path.join(getTestRunsRecordsPath(pmRoot), `${runId}.json`);\n}\n\n/** Implements get test runs stdout path for the public runtime surface of this module. */\nexport function getTestRunsStdoutPath(pmRoot: string): string {\n return path.join(getTestRunsPath(pmRoot), \"stdout\");\n}\n\n/** Implements get test runs stderr path for the public runtime surface of this module. */\nexport function getTestRunsStderrPath(pmRoot: string): string {\n return path.join(getTestRunsPath(pmRoot), \"stderr\");\n}\n\n/** Implements get test run stdout path for the public runtime surface of this module. */\nexport function getTestRunStdoutPath(pmRoot: string, runId: string): string {\n return path.join(getTestRunsStdoutPath(pmRoot), `${runId}.log`);\n}\n\n/** Implements get test run stderr path for the public runtime surface of this module. */\nexport function getTestRunStderrPath(pmRoot: string, runId: string): string {\n return path.join(getTestRunsStderrPath(pmRoot), `${runId}.log`);\n}\n\n/** Implements get test runs results path for the public runtime surface of this module. */\nexport function getTestRunsResultsPath(pmRoot: string): string {\n return path.join(getTestRunsPath(pmRoot), \"results\");\n}\n\n/** Implements get test run result path for the public runtime surface of this module. */\nexport function getTestRunResultPath(pmRoot: string, runId: string): string {\n return path.join(getTestRunsResultsPath(pmRoot), `${runId}.json`);\n}\n","/**\n * Common primitive utility functions shared across core modules.\n *\n * These reduce duplication of trivial helpers like string-presence checks,\n * error message extraction, and numeric array guards that were previously\n * duplicated in providers.ts, vector-stores.ts, lock.ts, cache.ts, and\n * several CLI command modules.\n */\n\n/** Return a trimmed non-empty string, or `null` for non-string/blank input. */\nexport function toNonEmptyString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\n/** Implements to non empty string or undefined for the public runtime surface of this module. */\nexport function toNonEmptyStringOrUndefined(\n value: unknown,\n): string | undefined {\n const result = toNonEmptyString(value);\n return result ?? undefined;\n}\n\n/** Implements trim trailing slashes for the public runtime surface of this module. */\nexport function trimTrailingSlashes(value: string): string {\n return value.replaceAll(/\\/+$/g, \"\");\n}\n\n/** Implements check whether finite number array for the public runtime surface of this module. */\nexport function isFiniteNumberArray(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.every((entry) => typeof entry === \"number\" && Number.isFinite(entry))\n );\n}\n\n/** Implements to error message for the public runtime surface of this module. */\nexport function toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const message = error.message.trim();\n return message.length > 0 ? message : error.name;\n }\n return String(error);\n}\n\n/** Parse either a finite numeric literal or a non-empty numeric string. Returns `null` for unsupported input types, empty strings, and non-finite numeric values. */\nexport function coerceFiniteNumber(value: unknown): number | null {\n const parsed =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\" && value.trim().length > 0\n ? Number(value.trim())\n : Number.NaN;\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/** Implements coerce positive integer for the public runtime surface of this module. */\nexport function coercePositiveInteger(value: unknown): number | null {\n const parsed = coerceFiniteNumber(value);\n if (parsed === null || parsed <= 0 || !Number.isInteger(parsed)) {\n return null;\n }\n return parsed;\n}\n\n/** Implements coerce number in range for the public runtime surface of this module. */\nexport function coerceNumberInRange(\n value: unknown,\n min: number,\n max: number,\n): number | null {\n const parsed = coerceFiniteNumber(value);\n if (parsed === null || parsed < min || parsed > max) {\n return null;\n }\n return parsed;\n}\n\n/**\n * Narrow a value to a plain object, returning `null` for non-objects,\n * `null`, and arrays. Returns the original reference (no clone).\n *\n * Matches the historical `asRecord` in src/cli/main.ts.\n */\nexport function asRecordOrNull(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * Narrow a value to a plain object, returning `null` only for non-objects and\n * `null` while accepting arrays (arrays are objects). Returns the original\n * reference (no clone).\n *\n * Matches the historical `asRecord` in src/core/extensions/loader.ts, which\n * intentionally omits the array guard.\n */\nexport function asRecordLoose(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\n/** Narrow a value to a property-bearing object or function. Dynamic module exports can be function/class values with static lifecycle properties, so activation boundaries need a wider record shape than plain-object parsing. */\nexport function asPropertyRecord(\n value: unknown,\n): Record<string, unknown> | null {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\") ||\n value === null\n ) {\n return null;\n }\n return value as Record<string, unknown>;\n}\n\n/** Resolve the module or default export record that owns an `activate` lifecycle function. Accepts object and function/class-shaped exports so runtime loading and SDK tests share the same extension interop rule. */\nexport function resolveActivatablePropertyRecord(\n value: unknown,\n): Record<string, unknown> | null {\n const moduleRecord = asPropertyRecord(value);\n if (!moduleRecord) {\n return null;\n }\n if (typeof moduleRecord.activate === \"function\") {\n return moduleRecord;\n }\n const defaultExport = asPropertyRecord(moduleRecord.default);\n return typeof defaultExport?.activate === \"function\" ? defaultExport : null;\n}\n\n/**\n * Narrow a value to a plain object, returning an empty object for non-objects,\n * `null`, and arrays. Returns a shallow clone of the source object.\n *\n * Matches the historical `asRecord` in src/mcp/server.ts.\n */\nexport function asRecordClone(value: unknown): Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? ({ ...value } as Record<string, unknown>)\n : {};\n}\n","/**\n * @module core/shared/levenshtein\n *\n * Provides shared primitives and utilities for Levenshtein.\n */\n// Optimal String Alignment (OSA) Damerau–Levenshtein: counts a single adjacent\n// transposition as one edit (e.g. \"titel\" vs \"title\", \"lst\" vs \"lts\" -> \"list\")\n// so flag/command typo suggestions catch transpositions at the same maxDistance\n// budget plain Levenshtein uses for substitutions. pm-fl0c #6 (2026-05-28):\n// fixed because plain Levenshtein scored \"titel\"->\"title\" at 2, defeating the\n// length-5 maxDistance=1 ceiling in suggestNearestLongFlags.\n/** Computes bounded Levenshtein distance for typo suggestions without scanning unnecessary suffixes. */\nexport function levenshteinDistanceWithinLimit(\n left: string,\n right: string,\n limit: number,\n): number | null {\n if (left === right) {\n return 0;\n }\n if (Math.abs(left.length - right.length) > limit) {\n return null;\n }\n const width = right.length + 1;\n const beforePrevious = new Array<number>(width);\n const previous = new Array<number>(width);\n const current = new Array<number>(width);\n for (let column = 0; column < width; column += 1) {\n beforePrevious[column] = 0;\n previous[column] = column;\n }\n for (let row = 1; row <= left.length; row += 1) {\n current[0] = row;\n let rowMin = current[0];\n for (let column = 1; column <= right.length; column += 1) {\n const cost = left[row - 1] === right[column - 1] ? 0 : 1;\n const substitution = previous[column - 1] + cost;\n const insertion = current[column - 1] + 1;\n const deletion = previous[column] + 1;\n let candidate = Math.min(substitution, insertion, deletion);\n if (\n row > 1 &&\n column > 1 &&\n left[row - 1] === right[column - 2] &&\n left[row - 2] === right[column - 1]\n ) {\n candidate = Math.min(candidate, beforePrevious[column - 2] + 1);\n }\n current[column] = candidate;\n if (candidate < rowMin) {\n rowMin = candidate;\n }\n }\n if (rowMin > limit) {\n return null;\n }\n for (let column = 0; column < width; column += 1) {\n beforePrevious[column] = previous[column];\n previous[column] = current[column];\n }\n }\n const result = previous[right.length];\n return result <= limit ? result : null;\n}\n","/**\n * @module core/extensions/extension-capability-aliases\n *\n * Implements extension runtime contracts and governance for Extension Capability Aliases.\n */\nimport {\n KNOWN_EXTENSION_CAPABILITIES,\n EXTENSION_CAPABILITY_CONTRACT_VERSION,\n EXTENSION_CAPABILITY_LEGACY_ALIASES,\n type ExtensionCapability,\n type ExtensionLayer,\n type LegacyExtensionCapabilityAliasMapping,\n type UnknownExtensionCapabilityWarningDetails,\n} from \"./extension-types.js\";\nimport { levenshteinDistanceWithinLimit } from \"../shared/levenshtein.js\";\n\n/** Implements normalize names for the public runtime surface of this module. */\nexport function normalizeNames(values: string[]): string[] {\n return [\n ...new Set(\n values.map((value) => value.trim()).filter((value) => value.length > 0),\n ),\n ].sort((a, b) => a.localeCompare(b));\n}\n\n/** Implements check whether known extension capability for the public runtime surface of this module. */\nexport function isKnownExtensionCapability(\n value: string,\n): value is ExtensionCapability {\n return (KNOWN_EXTENSION_CAPABILITIES as readonly string[]).includes(value);\n}\n\n/** Trim and lower-case a capability token, returning it only when it is a known canonical capability (otherwise `null`). Shared so capability normalization and known-capability filtering stay identical across the doctor and the SDK least-privilege helpers. */\nexport function normalizeKnownExtensionCapability(\n value: string,\n): ExtensionCapability | null {\n const normalized = value.trim().toLowerCase();\n return isKnownExtensionCapability(normalized) ? normalized : null;\n}\n\n/** Implements collect unknown extension capabilities for the public runtime surface of this module. */\nexport function collectUnknownExtensionCapabilities(\n capabilities: readonly string[],\n): string[] {\n return capabilities.filter(\n (capability) => !isKnownExtensionCapability(capability),\n );\n}\n\n/** Implements resolve legacy extension capability alias for the public runtime surface of this module. */\nexport function resolveLegacyExtensionCapabilityAlias(\n capability: string,\n): ExtensionCapability | null {\n const normalized = capability.trim().toLowerCase();\n if (normalized.length === 0) {\n return null;\n }\n return EXTENSION_CAPABILITY_LEGACY_ALIASES[normalized] ?? null;\n}\n\n/** Implements normalize manifest capabilities for the public runtime surface of this module. */\nexport function normalizeManifestCapabilities(\n rawCapabilities: readonly string[],\n): {\n capabilities: string[];\n legacy_aliases: LegacyExtensionCapabilityAliasMapping[];\n} {\n const normalizedCapabilities = normalizeNames(\n [...rawCapabilities].map((value) => value.toLowerCase()),\n );\n const remappedCapabilities: string[] = [];\n const legacyAliases: LegacyExtensionCapabilityAliasMapping[] = [];\n for (const capability of normalizedCapabilities) {\n const legacyAliasTarget = resolveLegacyExtensionCapabilityAlias(capability);\n if (legacyAliasTarget) {\n remappedCapabilities.push(legacyAliasTarget);\n legacyAliases.push({\n alias: capability,\n target: legacyAliasTarget,\n });\n continue;\n }\n remappedCapabilities.push(capability);\n }\n const dedupedLegacyAliases = [\n ...new Map(\n legacyAliases.map((entry) => [`${entry.alias}>${entry.target}`, entry]),\n ).values(),\n ].sort((left, right) => left.alias.localeCompare(right.alias));\n return {\n capabilities: normalizeNames(remappedCapabilities),\n legacy_aliases: dedupedLegacyAliases,\n };\n}\n\n/** Implements suggest known extension capability for the public runtime surface of this module. */\nexport function suggestKnownExtensionCapability(\n capability: string,\n): string | null {\n const normalized = capability.trim().toLowerCase();\n if (normalized.length === 0) {\n return null;\n }\n const legacyAlias = resolveLegacyExtensionCapabilityAlias(normalized);\n if (legacyAlias) {\n return legacyAlias;\n }\n const maxDistance = Math.max(1, Math.floor(normalized.length * 0.34));\n let bestMatch: string | null = null;\n let bestDistance = Number.POSITIVE_INFINITY;\n for (const candidate of KNOWN_EXTENSION_CAPABILITIES) {\n const distance = levenshteinDistanceWithinLimit(\n normalized,\n candidate,\n maxDistance,\n );\n if (distance !== null && distance < bestDistance) {\n bestDistance = distance;\n bestMatch = candidate;\n }\n }\n return bestMatch;\n}\n\n/** Implements format unknown extension capability warning for the public runtime surface of this module. */\nexport function formatUnknownExtensionCapabilityWarning(\n layer: ExtensionLayer,\n name: string,\n capability: string,\n): string {\n const allowed = KNOWN_EXTENSION_CAPABILITIES.join(\",\");\n const suggested = suggestKnownExtensionCapability(capability) ?? \"none\";\n return `extension_capability_unknown:${layer}:${name}:${capability}:allowed=${allowed}:suggested=${suggested}`;\n}\n\n/** Implements format legacy extension capability alias warning for the public runtime surface of this module. */\nexport function formatLegacyExtensionCapabilityAliasWarning(\n layer: ExtensionLayer,\n name: string,\n aliases: readonly LegacyExtensionCapabilityAliasMapping[],\n): string {\n const aliasesToken = aliases\n .map((entry) => `${entry.alias}>${entry.target}`)\n .join(\",\");\n return `extension_capability_legacy_alias:${layer}:${name}:aliases=${aliasesToken}`;\n}\n\n/** Implements parse unknown extension capability warning for the public runtime surface of this module. */\nexport function parseUnknownExtensionCapabilityWarning(\n warning: string,\n): UnknownExtensionCapabilityWarningDetails | null {\n const match =\n /^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(\n warning.trim(),\n );\n if (!match) {\n return null;\n }\n const [, layerRaw, name, capability, allowedRaw, suggestedRaw] = match;\n const layer = layerRaw as ExtensionLayer;\n const allowed_capabilities = allowedRaw\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n const legacyAlias = resolveLegacyExtensionCapabilityAlias(capability);\n const suggestedFromWarning =\n suggestedRaw === \"none\" ? undefined : suggestedRaw;\n const suggested_capability = suggestedFromWarning ?? legacyAlias ?? undefined;\n const suggestion_source = suggested_capability\n ? legacyAlias === suggested_capability\n ? \"legacy_alias\"\n : \"nearest_match\"\n : undefined;\n return {\n layer,\n name,\n capability,\n allowed_capabilities,\n capability_contract_version: EXTENSION_CAPABILITY_CONTRACT_VERSION,\n suggested_capability,\n suggestion_source,\n legacy_alias_target: legacyAlias ?? undefined,\n };\n}\n\n/** Implements parse legacy extension capability alias warning for the public runtime surface of this module. */\nexport function parseLegacyExtensionCapabilityAliasWarning(\n warning: string,\n): UnknownExtensionCapabilityWarningDetails[] {\n const match =\n /^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(\n warning.trim(),\n );\n if (!match) {\n return [];\n }\n const [, layerRaw, name, aliasesRaw] = match;\n const layer = layerRaw as ExtensionLayer;\n const allowedCapabilities = [...KNOWN_EXTENSION_CAPABILITIES];\n const parsed: UnknownExtensionCapabilityWarningDetails[] = [];\n for (const token of aliasesRaw.split(\",\")) {\n const [rawAlias, rawTarget] = token.split(\">\");\n const alias = rawAlias?.trim();\n const target = rawTarget?.trim().toLowerCase();\n if (!alias || !target || !isKnownExtensionCapability(target)) {\n continue;\n }\n parsed.push({\n layer,\n name,\n capability: alias,\n allowed_capabilities: allowedCapabilities,\n capability_contract_version: EXTENSION_CAPABILITY_CONTRACT_VERSION,\n suggested_capability: target,\n suggestion_source: \"legacy_alias\",\n legacy_alias_target: target,\n });\n }\n return parsed;\n}\n","/**\n * @module core/extensions/extension-registries\n *\n * Implements extension runtime contracts and governance for Extension Registries.\n */\nimport type {\n ExtensionHookRegistry,\n ExtensionCommandRegistry,\n ExtensionParserRegistry,\n ExtensionPreflightRegistry,\n ExtensionServiceRegistry,\n ExtensionRendererRegistry,\n ExtensionRegistrationRegistry,\n} from \"./extension-types.js\";\n\n/** Implements create empty extension hook registry for the public runtime surface of this module. */\nexport function createEmptyExtensionHookRegistry(): ExtensionHookRegistry {\n return {\n beforeCommand: [],\n afterCommand: [],\n onWrite: [],\n onRead: [],\n onIndex: [],\n };\n}\n\n/** Implements create empty extension command registry for the public runtime surface of this module. */\nexport function createEmptyExtensionCommandRegistry(): ExtensionCommandRegistry {\n return {\n overrides: [],\n handlers: [],\n };\n}\n\n/** Implements create empty extension parser registry for the public runtime surface of this module. */\nexport function createEmptyExtensionParserRegistry(): ExtensionParserRegistry {\n return {\n overrides: [],\n };\n}\n\n/** Implements create empty extension preflight registry for the public runtime surface of this module. */\nexport function createEmptyExtensionPreflightRegistry(): ExtensionPreflightRegistry {\n return {\n overrides: [],\n };\n}\n\n/** Implements create empty extension service registry for the public runtime surface of this module. */\nexport function createEmptyExtensionServiceRegistry(): ExtensionServiceRegistry {\n return {\n overrides: [],\n };\n}\n\n/** Implements create empty extension renderer registry for the public runtime surface of this module. */\nexport function createEmptyExtensionRendererRegistry(): ExtensionRendererRegistry {\n return {\n overrides: [],\n };\n}\n\n/** Implements create empty extension registration registry for the public runtime surface of this module. */\nexport function createEmptyExtensionRegistrationRegistry(): ExtensionRegistrationRegistry {\n return {\n commands: [],\n flags: [],\n item_fields: [],\n item_types: [],\n migrations: [],\n profiles: [],\n importers: [],\n exporters: [],\n search_providers: [],\n vector_store_adapters: [],\n };\n}\n","/**\n * @module core/extensions/extension-runtime-helpers\n *\n * Implements extension runtime contracts and governance for Extension Runtime Helpers.\n */\nimport type { GlobalOptions } from \"../shared/command-types.js\";\n\n/** Implements normalize command name for the public runtime surface of this module. */\nexport function normalizeCommandName(command: string): string {\n return command\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((part) => part.length > 0)\n .join(\" \");\n}\n\n/** Implements default global options for the public runtime surface of this module. */\nexport function defaultGlobalOptions(): GlobalOptions {\n return {\n json: false,\n quiet: false,\n noExtensions: false,\n profile: false,\n };\n}\n\n/** Implements clone command options snapshot for the public runtime surface of this module. */\nexport function cloneCommandOptionsSnapshot(\n options: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n return options ? cloneContextSnapshot(options) : {};\n}\n\n/** Implements clone global options snapshot for the public runtime surface of this module. */\nexport function cloneGlobalOptionsSnapshot(\n options: GlobalOptions | undefined,\n): GlobalOptions {\n return options ? cloneContextSnapshot(options) : defaultGlobalOptions();\n}\n\n/** Implements clone context snapshot for the public runtime surface of this module. */\nexport function cloneContextSnapshot<T>(value: T): T {\n return structuredClone(value);\n}\n","/**\n * @module core/extensions/extension-hook-runtime\n *\n * Implements extension runtime contracts and governance for Extension Hook Runtime.\n */\nimport {\n cloneCommandOptionsSnapshot,\n cloneContextSnapshot,\n cloneGlobalOptionsSnapshot,\n normalizeCommandName,\n} from \"./extension-runtime-helpers.js\";\nimport type {\n RegisteredExtensionHook,\n ExtensionHookRegistry,\n BeforeCommandHookContext,\n AfterCommandHookContext,\n OnWriteHookContext,\n OnReadHookContext,\n OnIndexHookContext,\n ExtensionCommandRegistry,\n CommandHandlerContext,\n CommandHandlerResult,\n ExtensionParserRegistry,\n ParserOverrideContext,\n ParserOverrideResult,\n ExtensionPreflightRegistry,\n PreflightOverrideContext,\n PreflightOverrideResult,\n PreflightRuntimeDecision,\n ExtensionServiceRegistry,\n ServiceOverrideContext,\n ServiceOverrideResult,\n CommandOverrideContext,\n CommandOverrideResult,\n ExtensionRendererRegistry,\n RendererOverrideContext,\n RendererOverrideResult,\n} from \"./extension-types.js\";\n\ntype HookName = keyof ExtensionHookRegistry;\n\nasync function executeRegisteredHooks<TContext>(\n entries: Array<\n RegisteredExtensionHook<(context: TContext) => Promise<void> | void>\n >,\n hookName: HookName,\n context: TContext,\n): Promise<string[]> {\n const warnings: string[] = [];\n for (const entry of entries) {\n try {\n await entry.run(cloneContextSnapshot(context));\n } catch {\n warnings.push(\n `extension_hook_failed:${entry.layer}:${entry.name}:${hookName}`,\n );\n }\n }\n return warnings;\n}\n\n/** Implements run before command hooks for the public runtime surface of this module. */\nexport async function runBeforeCommandHooks(\n hooks: ExtensionHookRegistry,\n context: BeforeCommandHookContext,\n): Promise<string[]> {\n return executeRegisteredHooks(hooks.beforeCommand, \"beforeCommand\", context);\n}\n\n/** Implements run after command hooks for the public runtime surface of this module. */\nexport async function runAfterCommandHooks(\n hooks: ExtensionHookRegistry,\n context: AfterCommandHookContext,\n): Promise<string[]> {\n return executeRegisteredHooks(hooks.afterCommand, \"afterCommand\", context);\n}\n\n/** Implements run on write hooks for the public runtime surface of this module. */\nexport async function runOnWriteHooks(\n hooks: ExtensionHookRegistry,\n context: OnWriteHookContext,\n): Promise<string[]> {\n return executeRegisteredHooks(hooks.onWrite, \"onWrite\", context);\n}\n\n/** Implements run on read hooks for the public runtime surface of this module. */\nexport async function runOnReadHooks(\n hooks: ExtensionHookRegistry,\n context: OnReadHookContext,\n): Promise<string[]> {\n return executeRegisteredHooks(hooks.onRead, \"onRead\", context);\n}\n\n/** Implements run on index hooks for the public runtime surface of this module. */\nexport async function runOnIndexHooks(\n hooks: ExtensionHookRegistry,\n context: OnIndexHookContext,\n): Promise<string[]> {\n return executeRegisteredHooks(hooks.onIndex, \"onIndex\", context);\n}\n\n/** Normalize an extension handler failure into a single-line, length-bounded message so the real cause can be surfaced to the user/CI without leaking multi-line stack noise or unbounded payloads. */\nfunction describeHandlerError(error: unknown): string {\n let raw = \"\";\n if (error instanceof Error && typeof error.message === \"string\") {\n raw = error.message;\n } else if (typeof error === \"string\") {\n raw = error;\n } else if (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as { message?: unknown }).message === \"string\"\n ) {\n // Extensions may throw plain/serialized objects that carry a message but do\n // not inherit from the base Error class.\n raw = (error as { message: string }).message;\n }\n const normalized = raw.replace(/\\s+/gu, \" \").trim();\n if (normalized.length === 0) {\n return \"\";\n }\n const maxLength = 300;\n return normalized.length > maxLength\n ? `${normalized.slice(0, maxLength - 1)}…`\n : normalized;\n}\n\n/** Implements run command handler for the public runtime surface of this module. */\nexport async function runCommandHandler(\n commands: ExtensionCommandRegistry,\n context: CommandHandlerContext,\n): Promise<CommandHandlerResult> {\n const command = normalizeCommandName(context.command);\n if (command.length === 0) {\n return {\n handled: false,\n result: null,\n warnings: [],\n };\n }\n\n const matched = [...commands.handlers]\n .reverse()\n .find((entry) => entry.command === command);\n if (!matched) {\n return {\n handled: false,\n result: null,\n warnings: [],\n };\n }\n\n try {\n const result = await matched.run({\n command,\n args: cloneContextSnapshot(context.args),\n options: cloneContextSnapshot(context.options),\n global: cloneContextSnapshot(context.global),\n pm_root: context.pm_root,\n });\n return {\n handled: true,\n result,\n warnings: [],\n };\n } catch (error: unknown) {\n const exitCode =\n typeof error === \"object\" && error !== null && \"exitCode\" in error\n ? (error as { exitCode?: unknown }).exitCode\n : undefined;\n if (typeof exitCode === \"number\" && Number.isFinite(exitCode)) {\n throw error;\n }\n return {\n handled: false,\n result: null,\n warnings: [\n `extension_command_handler_failed:${matched.layer}:${matched.name}:${matched.command}`,\n ],\n errorMessage: describeHandlerError(error),\n };\n }\n}\n\n/** Implements run parser override for the public runtime surface of this module. */\nexport async function runParserOverride(\n parsers: ExtensionParserRegistry,\n context: ParserOverrideContext,\n): Promise<ParserOverrideResult> {\n const command = normalizeCommandName(context.command);\n if (command.length === 0) {\n return {\n overridden: false,\n context: {\n command,\n args: cloneContextSnapshot(context.args),\n options: cloneCommandOptionsSnapshot(context.options),\n global: cloneGlobalOptionsSnapshot(context.global),\n pm_root: context.pm_root,\n },\n warnings: [],\n };\n }\n\n const matched = [...parsers.overrides]\n .reverse()\n .find((entry) => entry.command === command);\n if (!matched) {\n return {\n overridden: false,\n context: {\n command,\n args: cloneContextSnapshot(context.args),\n options: cloneCommandOptionsSnapshot(context.options),\n global: cloneGlobalOptionsSnapshot(context.global),\n pm_root: context.pm_root,\n },\n warnings: [],\n };\n }\n\n try {\n const delta =\n (await Promise.resolve(\n matched.run({\n command,\n args: cloneContextSnapshot(context.args),\n options: cloneCommandOptionsSnapshot(context.options),\n global: cloneGlobalOptionsSnapshot(context.global),\n pm_root: context.pm_root,\n }),\n )) ?? {};\n const nextArgs = Array.isArray(delta.args)\n ? cloneContextSnapshot(delta.args)\n : cloneContextSnapshot(context.args);\n const nextOptions = delta.options\n ? cloneCommandOptionsSnapshot(delta.options)\n : cloneCommandOptionsSnapshot(context.options);\n const nextGlobal = delta.global\n ? cloneGlobalOptionsSnapshot(delta.global)\n : cloneGlobalOptionsSnapshot(context.global);\n return {\n overridden: true,\n context: {\n command,\n args: nextArgs,\n options: nextOptions,\n global: nextGlobal,\n pm_root: context.pm_root,\n },\n warnings: [],\n };\n } catch {\n return {\n overridden: false,\n context: {\n command,\n args: cloneContextSnapshot(context.args),\n options: cloneCommandOptionsSnapshot(context.options),\n global: cloneGlobalOptionsSnapshot(context.global),\n pm_root: context.pm_root,\n },\n warnings: [\n `extension_parser_override_failed:${matched.layer}:${matched.name}:${matched.command}`,\n ],\n };\n }\n}\n\n/** Implements run preflight override for the public runtime surface of this module. */\nexport async function runPreflightOverride(\n preflight: ExtensionPreflightRegistry,\n context: PreflightOverrideContext,\n): Promise<PreflightOverrideResult> {\n const matched = [...preflight.overrides].reverse()[0];\n const baseContext: CommandHandlerContext = {\n command: normalizeCommandName(context.command),\n args: cloneContextSnapshot(context.args),\n options: cloneCommandOptionsSnapshot(context.options),\n global: cloneGlobalOptionsSnapshot(context.global),\n pm_root: context.pm_root,\n };\n const baseDecision: PreflightRuntimeDecision = cloneContextSnapshot(\n context.decision,\n );\n if (!matched) {\n return {\n overridden: false,\n context: baseContext,\n decision: baseDecision,\n warnings: [],\n };\n }\n\n try {\n const delta =\n (await Promise.resolve(\n matched.run({\n command: baseContext.command,\n args: cloneContextSnapshot(baseContext.args),\n options: cloneCommandOptionsSnapshot(baseContext.options),\n global: cloneGlobalOptionsSnapshot(baseContext.global),\n pm_root: baseContext.pm_root,\n decision: cloneContextSnapshot(baseDecision),\n }),\n )) ?? {};\n const nextContext: CommandHandlerContext = {\n command: baseContext.command,\n args: Array.isArray(delta.args)\n ? cloneContextSnapshot(delta.args)\n : baseContext.args,\n options: delta.options\n ? cloneCommandOptionsSnapshot(delta.options)\n : baseContext.options,\n global: delta.global\n ? cloneGlobalOptionsSnapshot(delta.global)\n : baseContext.global,\n pm_root: baseContext.pm_root,\n };\n const nextDecision: PreflightRuntimeDecision = {\n enforce_item_format_gate:\n typeof delta.enforce_item_format_gate === \"boolean\"\n ? delta.enforce_item_format_gate\n : baseDecision.enforce_item_format_gate,\n run_preflight_item_format_sync:\n typeof delta.run_preflight_item_format_sync === \"boolean\"\n ? delta.run_preflight_item_format_sync\n : baseDecision.run_preflight_item_format_sync,\n run_extension_migrations:\n typeof delta.run_extension_migrations === \"boolean\"\n ? delta.run_extension_migrations\n : baseDecision.run_extension_migrations,\n enforce_mandatory_migration_gate:\n typeof delta.enforce_mandatory_migration_gate === \"boolean\"\n ? delta.enforce_mandatory_migration_gate\n : baseDecision.enforce_mandatory_migration_gate,\n };\n return {\n overridden: true,\n context: nextContext,\n decision: nextDecision,\n warnings: [],\n };\n } catch {\n return {\n overridden: false,\n context: baseContext,\n decision: baseDecision,\n warnings: [\n `extension_preflight_override_failed:${matched.layer}:${matched.name}`,\n ],\n };\n }\n}\n\nfunction resolveDefaultServiceResult(\n context: ServiceOverrideContext,\n): ServiceOverrideResult {\n return {\n handled: false,\n result: context.payload,\n warnings: [],\n };\n}\n\nfunction matchingServiceOverrides(\n services: ExtensionServiceRegistry,\n service: ServiceOverrideContext[\"service\"],\n) {\n return [...services.overrides]\n .reverse()\n .filter((entry) => entry.service === service);\n}\n\nfunction buildServiceOverrideContext(context: ServiceOverrideContext) {\n return {\n service: context.service,\n command: context.command\n ? normalizeCommandName(context.command)\n : undefined,\n args: context.args ? cloneContextSnapshot(context.args) : undefined,\n options: context.options\n ? cloneCommandOptionsSnapshot(context.options)\n : undefined,\n global: context.global\n ? cloneGlobalOptionsSnapshot(context.global)\n : undefined,\n pm_root: context.pm_root,\n payload: cloneContextSnapshot(context.payload),\n };\n}\n\n/** Implements run service override sync for the public runtime surface of this module. */\nexport function runServiceOverrideSync(\n services: ExtensionServiceRegistry,\n context: ServiceOverrideContext,\n): ServiceOverrideResult {\n const matches = matchingServiceOverrides(services, context.service);\n if (matches.length === 0) {\n return resolveDefaultServiceResult(context);\n }\n\n const warnings: string[] = [];\n for (const matched of matches) {\n try {\n const serviceContext = buildServiceOverrideContext(context);\n const result = matched.run(serviceContext);\n if (result instanceof Promise) {\n warnings.push(\n `extension_service_override_async_unsupported:${matched.layer}:${matched.name}:${matched.service}`,\n );\n continue;\n }\n if (\n context.service === \"output_format\" &&\n (result === null ||\n result === undefined ||\n result === serviceContext.payload)\n ) {\n continue;\n }\n return {\n handled: true,\n result,\n warnings,\n };\n } catch {\n warnings.push(\n `extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`,\n );\n }\n }\n return {\n handled: false,\n result: context.payload,\n warnings,\n };\n}\n\n/** Implements run service override for the public runtime surface of this module. */\nexport async function runServiceOverride(\n services: ExtensionServiceRegistry,\n context: ServiceOverrideContext,\n): Promise<ServiceOverrideResult> {\n const matches = matchingServiceOverrides(services, context.service);\n if (matches.length === 0) {\n return resolveDefaultServiceResult(context);\n }\n\n const warnings: string[] = [];\n for (const matched of matches) {\n try {\n const serviceContext = buildServiceOverrideContext(context);\n const result = await Promise.resolve(matched.run(serviceContext));\n if (\n context.service === \"output_format\" &&\n (result === null ||\n result === undefined ||\n result === serviceContext.payload)\n ) {\n continue;\n }\n return {\n handled: true,\n result,\n warnings,\n };\n } catch {\n warnings.push(\n `extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`,\n );\n }\n }\n return {\n handled: false,\n result: context.payload,\n warnings,\n };\n}\n\n/** Implements run command override for the public runtime surface of this module. */\nexport function runCommandOverride(\n commands: ExtensionCommandRegistry,\n context: CommandOverrideContext,\n): CommandOverrideResult {\n const command = normalizeCommandName(context.command);\n if (command.length === 0) {\n return {\n overridden: false,\n result: context.result,\n warnings: [],\n };\n }\n\n const matched = [...commands.overrides]\n .reverse()\n .find((entry) => entry.command === command);\n if (!matched) {\n return {\n overridden: false,\n result: context.result,\n warnings: [],\n };\n }\n\n try {\n const overrideOptions = cloneCommandOptionsSnapshot(context.options);\n const overrideGlobal = cloneGlobalOptionsSnapshot(context.global);\n const overrideResult = matched.run({\n command,\n args: cloneContextSnapshot(context.args),\n options: overrideOptions,\n global: overrideGlobal,\n pm_root: context.pm_root,\n result: cloneContextSnapshot(context.result),\n });\n if (overrideResult instanceof Promise) {\n return {\n overridden: false,\n result: context.result,\n warnings: [\n `extension_command_override_async_unsupported:${matched.layer}:${matched.name}:${matched.command}`,\n ],\n };\n }\n return {\n overridden: true,\n result: overrideResult,\n warnings: [],\n };\n } catch {\n return {\n overridden: false,\n result: context.result,\n warnings: [\n `extension_command_override_failed:${matched.layer}:${matched.name}:${matched.command}`,\n ],\n };\n }\n}\n\n/** Implements run renderer override for the public runtime surface of this module. */\nexport function runRendererOverride(\n renderers: ExtensionRendererRegistry,\n context: RendererOverrideContext,\n): RendererOverrideResult {\n const matched = [...renderers.overrides]\n .reverse()\n .find((entry) => entry.format === context.format);\n if (!matched) {\n return {\n overridden: false,\n rendered: null,\n warnings: [],\n };\n }\n\n try {\n const rendererCommand =\n typeof context.command === \"string\"\n ? normalizeCommandName(context.command)\n : \"\";\n const rendererArgs = Array.isArray(context.args)\n ? cloneContextSnapshot(context.args)\n : [];\n const rendererOptions = cloneCommandOptionsSnapshot(context.options);\n const rendererGlobal = cloneGlobalOptionsSnapshot(context.global);\n const rendererPmRoot =\n typeof context.pm_root === \"string\" ? context.pm_root : \"\";\n const rendered = matched.run({\n format: context.format,\n command: rendererCommand,\n args: rendererArgs,\n options: rendererOptions,\n global: rendererGlobal,\n pm_root: rendererPmRoot,\n result: cloneContextSnapshot(context.result),\n });\n if (rendered === null || rendered === undefined) {\n return {\n overridden: false,\n rendered: null,\n warnings: [],\n };\n }\n if (typeof rendered !== \"string\") {\n return {\n overridden: false,\n rendered: null,\n warnings: [\n `extension_renderer_invalid_result:${matched.layer}:${matched.name}:${matched.format}`,\n ],\n };\n }\n return {\n overridden: true,\n rendered,\n warnings: [],\n };\n } catch {\n return {\n overridden: false,\n rendered: null,\n warnings: [\n `extension_renderer_failed:${matched.layer}:${matched.name}:${matched.format}`,\n ],\n };\n }\n}\n","/**\n * @module core/extensions/loader\n *\n * Implements extension runtime contracts and governance for Loader.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { pathExists } from \"../fs/fs-utils.js\";\nimport { isPathWithinDirectory } from \"../fs/path-utils.js\";\nimport { resolvePmPackageRootFromModule } from \"../packages/root.js\";\nimport { resolveGlobalPmRoot } from \"../store/paths.js\";\nimport {\n asRecordLoose,\n resolveActivatablePropertyRecord,\n} from \"../shared/primitives.js\";\nimport {\n flattenFlagListValue,\n isFlagDefaultValueCoercible,\n resolveFlagValueKind,\n} from \"./flag-value-types.js\";\nimport {\n KNOWN_ITEM_FIELD_TYPES,\n normalizeItemFieldType,\n suggestKnownItemFieldType,\n} from \"./item-field-types.js\";\nimport {\n compareComparableVersions,\n evaluatePmMaxVersionBound,\n evaluatePmMinVersionBound,\n parseComparableVersion,\n type PmVersionBoundEvaluation,\n} from \"./version-compat.js\";\nimport type {\n ProjectProfileDefinition,\n ProjectProfileRegistrationInput,\n} from \"../profile/profile-presets.js\";\n// Cohesive helper groups now live in sibling modules. They are imported for the\n// discovery/activation code that stays here and re-exported below so existing\n// import sites (sdk/index.ts, commands/extension.ts, health.ts, tests, …) keep\n// importing everything from \"./loader.js\" unchanged.\nimport {\n normalizeNames,\n isKnownExtensionCapability,\n collectUnknownExtensionCapabilities,\n normalizeManifestCapabilities,\n formatUnknownExtensionCapabilityWarning,\n formatLegacyExtensionCapabilityAliasWarning,\n} from \"./extension-capability-aliases.js\";\nimport {\n normalizeExtensionPolicy,\n serializeExtensionPolicy,\n hydrateExtensionPolicy,\n normalizePolicySandboxProfile,\n evaluateExtensionPolicyForExtension,\n evaluateExtensionPolicyForCapability,\n evaluateExtensionPolicyForRegistration,\n type NormalizedExtensionPolicy,\n type PolicyExtensionRef,\n} from \"./extension-policy.js\";\nimport {\n createEmptyExtensionHookRegistry,\n createEmptyExtensionCommandRegistry,\n createEmptyExtensionParserRegistry,\n createEmptyExtensionPreflightRegistry,\n createEmptyExtensionServiceRegistry,\n createEmptyExtensionRendererRegistry,\n createEmptyExtensionRegistrationRegistry,\n} from \"./extension-registries.js\";\nimport {\n normalizeCommandName,\n cloneContextSnapshot,\n} from \"./extension-runtime-helpers.js\";\nexport {\n parseUnknownExtensionCapabilityWarning,\n parseLegacyExtensionCapabilityAliasWarning,\n} from \"./extension-capability-aliases.js\";\nexport {\n createEmptyExtensionHookRegistry,\n createEmptyExtensionCommandRegistry,\n createEmptyExtensionParserRegistry,\n createEmptyExtensionPreflightRegistry,\n createEmptyExtensionServiceRegistry,\n createEmptyExtensionRendererRegistry,\n createEmptyExtensionRegistrationRegistry,\n} from \"./extension-registries.js\";\nexport {\n runBeforeCommandHooks,\n runAfterCommandHooks,\n runOnWriteHooks,\n runOnReadHooks,\n runOnIndexHooks,\n runCommandHandler,\n runParserOverride,\n runPreflightOverride,\n runServiceOverrideSync,\n runServiceOverride,\n runCommandOverride,\n runRendererOverride,\n} from \"./extension-hook-runtime.js\";\nimport {\n KNOWN_EXTENSION_CAPABILITIES,\n KNOWN_EXTENSION_SERVICE_NAMES,\n createDefaultExtensionGovernancePolicy,\n type ExtensionDeactivationFailure,\n type ExtensionDeactivationOptions,\n type ExtensionDeactivationResult,\n type ExtensionSelfIdentity,\n type ExtensionCapability,\n type ExtensionPolicySurface,\n type ExtensionSandboxProfile,\n type ExtensionGovernancePolicy,\n type PmMaxVersionExceededMode,\n type ExtensionLayer,\n type ExtensionManifest,\n type ExtensionManifestEngines,\n type ExtensionDiagnostic,\n type EffectiveExtension,\n type ExtensionDiscoveryResult,\n type LoadedExtension,\n type FailedExtensionLoad,\n type ExtensionLoadResult,\n type BeforeCommandHook,\n type AfterCommandHook,\n type OnWriteHook,\n type OnReadHook,\n type OnIndexHook,\n type OutputRendererFormat,\n type CommandOverride,\n type RendererOverride,\n type CommandHandler,\n type ParserOverride,\n type PreflightOverride,\n type ServiceOverride,\n type ExtensionHookRegistry,\n type ExtensionServiceName,\n type ExtensionCommandArgumentDefinition,\n type CommandDefinition,\n type FlagDefinition,\n type SchemaFieldDefinition,\n type SchemaItemTypeDefinition,\n type SchemaMigrationDefinition,\n type ImportExportRegistrationOptions,\n type Importer,\n type Exporter,\n type SearchProviderDefinition,\n type VectorStoreAdapterDefinition,\n type RegisteredExtensionParserOverride,\n type RegisteredExtensionServiceOverride,\n type RegisteredExtensionRendererOverride,\n type ExtensionCommandRegistry,\n type ExtensionParserRegistry,\n type ExtensionPreflightRegistry,\n type ExtensionServiceRegistry,\n type ExtensionRendererRegistry,\n type RegisteredExtensionCommandDefinition,\n type RegisteredExtensionSchemaMigrationDefinition,\n type RegisteredExtensionSearchProvider,\n type RegisteredExtensionVectorStoreAdapter,\n type ExtensionRegistrationRegistry,\n type ExtensionRegistrationCounts,\n type ExtensionApi,\n type FailedExtensionActivation,\n type ExtensionActivationFailureTrace,\n type ExtensionActivationResult,\n type ExtensionCandidate,\n type ExtensionLayerScanResult,\n type ScannedExtensionDirectory,\n type LegacyExtensionCapabilityAliasMapping,\n type DiscoverExtensionsOptions,\n type ActivatableExtension,\n} from \"./extension-types.js\";\nexport * from \"./extension-types.js\";\n\n/** Fallback extension priority used when callers do not provide an override. */\nexport const DEFAULT_EXTENSION_PRIORITY = 100;\nlet currentPmCliVersionPromise: Promise<string | null> | null = null;\n\n/* Types now in extension-types.ts - re-exported via `export * from \"./extension-types.js\"` above */\n\nconst DEFAULT_EXTENSION_POLICY: ExtensionGovernancePolicy = Object.freeze(\n createDefaultExtensionGovernancePolicy(),\n);\n\nlet extensionReloadEpoch = 0;\n\n/** Implements next extension reload token for the public runtime surface of this module. */\nexport function nextExtensionReloadToken(seed = Date.now()): string {\n extensionReloadEpoch += 1;\n return `${extensionReloadEpoch}-${seed}`;\n}\n\nfunction parseOptionalManifestString(\n candidate: Record<string, unknown>,\n field: string,\n): string | null | undefined {\n const value = candidate[field];\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return null;\n }\n return value.trim();\n}\n\nfunction parseManifestEngines(\n value: unknown,\n): ExtensionManifestEngines | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const enginesRecord = asRecordLoose(value);\n if (!enginesRecord) {\n return null;\n }\n const engines: ExtensionManifestEngines = {};\n for (const key of Object.keys(enginesRecord).sort((left, right) =>\n left.localeCompare(right),\n )) {\n if (key.trim().length === 0) {\n return null;\n }\n const engineValue = enginesRecord[key];\n if (typeof engineValue !== \"string\" || engineValue.trim().length === 0) {\n return null;\n }\n engines[key.trim()] = engineValue.trim();\n }\n return Object.keys(engines).length > 0 ? engines : undefined;\n}\n\n/** Parse a required manifest string field, returning `null` when it is absent, non-string, or blank. */\nfunction parseRequiredManifestString(\n candidate: Record<string, unknown>,\n field: string,\n): string | null {\n const value = candidate[field];\n if (typeof value !== \"string\" || value.trim().length === 0) {\n return null;\n }\n return value.trim();\n}\n\n/** Parse an optional integer value (`undefined` when absent, `null` when present but not an integer). */\nfunction parseOptionalIntegerValue(value: unknown): number | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n return null;\n }\n return value;\n}\n\n/** Parse an optional boolean value (`undefined` when absent, `null` when present but not a boolean). */\nfunction parseOptionalBooleanValue(value: unknown): boolean | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== \"boolean\") {\n return null;\n }\n return value;\n}\n\n/** Parse the optional integer `priority`, defaulting to {@link DEFAULT_EXTENSION_PRIORITY} when absent and rejecting (`null`) a non-integer. */\nfunction parseManifestPriority(\n candidate: Record<string, unknown>,\n): number | null {\n const value = parseOptionalIntegerValue(candidate.priority);\n return value === undefined ? DEFAULT_EXTENSION_PRIORITY : value;\n}\n\n/** Parse the optional `sandbox_profile`, rejecting (`null`) any value that does not round-trip through {@link normalizePolicySandboxProfile}. */\nfunction parseManifestSandboxProfile(\n candidate: Record<string, unknown>,\n): ExtensionSandboxProfile | null | undefined {\n const value = candidate.sandbox_profile;\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value !== \"string\") {\n return null;\n }\n const normalizedProfile = normalizePolicySandboxProfile(value);\n if (normalizedProfile !== value.trim().toLowerCase()) {\n return null;\n }\n return normalizedProfile;\n}\n\n/** Return the trimmed string when `value` is a non-blank string, otherwise `undefined`. */\nfunction optionalTrimmedString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0\n ? value.trim()\n : undefined;\n}\n\n/** Parse the optional `provenance` record (`undefined` absent, `null` malformed), keeping only the present trimmed string fields and a boolean `verified`. */\nfunction parseManifestProvenance(\n value: unknown,\n): ExtensionManifest[\"provenance\"] | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const provenanceRecord = asRecordLoose(value);\n if (!provenanceRecord) {\n return null;\n }\n const source = optionalTrimmedString(provenanceRecord.source);\n const signature = optionalTrimmedString(provenanceRecord.signature);\n const attestation = optionalTrimmedString(provenanceRecord.attestation);\n const verified =\n provenanceRecord.verified === undefined ||\n provenanceRecord.verified === null\n ? undefined\n : typeof provenanceRecord.verified === \"boolean\"\n ? provenanceRecord.verified\n : null;\n if (verified === null) {\n return null;\n }\n return {\n ...(source ? { source } : {}),\n ...(signature ? { signature } : {}),\n ...(attestation ? { attestation } : {}),\n ...(typeof verified === \"boolean\" ? { verified } : {}),\n };\n}\n\n/** Parse the optional `permissions` record (`undefined` absent, `null` malformed), keeping only the boolean grants that are present. */\nfunction parseManifestPermissions(\n value: unknown,\n): ExtensionManifest[\"permissions\"] | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const permissionsRecord = asRecordLoose(value);\n if (!permissionsRecord) {\n return null;\n }\n const fsRead = parseOptionalBooleanValue(permissionsRecord.fs_read);\n const fsWrite = parseOptionalBooleanValue(permissionsRecord.fs_write);\n const network = parseOptionalBooleanValue(permissionsRecord.network);\n const envRead = parseOptionalBooleanValue(permissionsRecord.env_read);\n const envWrite = parseOptionalBooleanValue(permissionsRecord.env_write);\n const processSpawn = parseOptionalBooleanValue(\n permissionsRecord.process_spawn,\n );\n if (\n [fsRead, fsWrite, network, envRead, envWrite, processSpawn].includes(null)\n ) {\n return null;\n }\n return {\n ...(typeof fsRead === \"boolean\" ? { fs_read: fsRead } : {}),\n ...(typeof fsWrite === \"boolean\" ? { fs_write: fsWrite } : {}),\n ...(typeof network === \"boolean\" ? { network } : {}),\n ...(typeof envRead === \"boolean\" ? { env_read: envRead } : {}),\n ...(typeof envWrite === \"boolean\" ? { env_write: envWrite } : {}),\n ...(typeof processSpawn === \"boolean\"\n ? { process_spawn: processSpawn }\n : {}),\n };\n}\n\n/** Parse the optional `capabilities` array, normalizing legacy aliases; returns empty lists when absent and `null` when the field is not a string array. */\nfunction parseManifestCapabilities(\n value: unknown,\n): {\n capabilities: string[];\n legacy_aliases: LegacyExtensionCapabilityAliasMapping[];\n} | null {\n if (value === undefined || value === null) {\n return { capabilities: [], legacy_aliases: [] };\n }\n if (\n !Array.isArray(value) ||\n value.some((entry) => typeof entry !== \"string\")\n ) {\n return null;\n }\n const normalizedCapabilities = normalizeManifestCapabilities(\n value as string[],\n );\n return {\n capabilities: normalizedCapabilities.capabilities,\n legacy_aliases: normalizedCapabilities.legacy_aliases,\n };\n}\n\n/** Parse the optional `activation` block, returning the de-duplicated sorted `commands` set, `undefined` when no command activation is declared, and `null` when the block is malformed. */\nfunction parseManifestActivation(\n value: unknown,\n): ExtensionManifest[\"activation\"] | null | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n const activationRecord = asRecordLoose(value);\n if (!activationRecord) {\n return null;\n }\n const rawCommands = activationRecord.commands;\n if (rawCommands === undefined || rawCommands === null) {\n return undefined;\n }\n if (\n !Array.isArray(rawCommands) ||\n rawCommands.some((entry) => typeof entry !== \"string\")\n ) {\n return null;\n }\n const commands = [\n ...new Set(\n rawCommands\n .map((entry) => normalizeCommandName(entry))\n .filter((entry) => entry.length > 0),\n ),\n ].sort((left, right) => left.localeCompare(right));\n return commands.length > 0 ? { commands } : undefined;\n}\n\n/** The optional metadata fields a manifest may declare, parsed and validated as a single bundle so {@link parseManifest} stays a thin orchestrator. */\ninterface ParsedManifestMetadata {\n manifest_version: number | undefined;\n pm_min_version: string | undefined;\n pm_max_version: string | undefined;\n engines: ExtensionManifestEngines | undefined;\n trusted: boolean | undefined;\n sandbox_profile: ExtensionSandboxProfile | undefined;\n provenance: ExtensionManifest[\"provenance\"];\n permissions: ExtensionManifest[\"permissions\"];\n capabilities: string[];\n legacy_capability_aliases: LegacyExtensionCapabilityAliasMapping[];\n activation: ExtensionManifest[\"activation\"];\n}\n\n/** Parse every optional manifest metadata field, returning `null` as soon as any one is malformed. */\nfunction parseManifestMetadata(\n candidate: Record<string, unknown>,\n): ParsedManifestMetadata | null {\n const manifestVersion = parseOptionalIntegerValue(candidate.manifest_version);\n if (manifestVersion === null) {\n return null;\n }\n const pmMinVersion = parseOptionalManifestString(candidate, \"pm_min_version\");\n if (pmMinVersion === null) {\n return null;\n }\n const pmMaxVersion = parseOptionalManifestString(candidate, \"pm_max_version\");\n if (pmMaxVersion === null) {\n return null;\n }\n const engines = parseManifestEngines(candidate.engines);\n if (engines === null) {\n return null;\n }\n const trusted = parseOptionalBooleanValue(candidate.trusted);\n if (trusted === null) {\n return null;\n }\n const sandboxProfile = parseManifestSandboxProfile(candidate);\n if (sandboxProfile === null) {\n return null;\n }\n const provenance = parseManifestProvenance(candidate.provenance);\n if (provenance === null) {\n return null;\n }\n const permissions = parseManifestPermissions(candidate.permissions);\n if (permissions === null) {\n return null;\n }\n const capabilities = parseManifestCapabilities(candidate.capabilities);\n if (capabilities === null) {\n return null;\n }\n const activation = parseManifestActivation(candidate.activation);\n if (activation === null) {\n return null;\n }\n return {\n manifest_version: manifestVersion,\n pm_min_version: pmMinVersion,\n pm_max_version: pmMaxVersion,\n engines,\n trusted,\n sandbox_profile: sandboxProfile,\n provenance,\n permissions,\n capabilities: capabilities.capabilities,\n legacy_capability_aliases: capabilities.legacy_aliases,\n activation,\n };\n}\n\nfunction parseManifest(raw: unknown): ExtensionManifest | null {\n if (typeof raw !== \"object\" || raw === null) {\n return null;\n }\n const candidate = raw as Record<string, unknown>;\n const name = parseRequiredManifestString(candidate, \"name\");\n if (name === null) {\n return null;\n }\n const version = parseRequiredManifestString(candidate, \"version\");\n if (version === null) {\n return null;\n }\n const entry = parseRequiredManifestString(candidate, \"entry\");\n if (entry === null) {\n return null;\n }\n const priority = parseManifestPriority(candidate);\n if (priority === null) {\n return null;\n }\n const metadata = parseManifestMetadata(candidate);\n if (metadata === null) {\n return null;\n }\n return {\n name,\n version,\n entry,\n priority,\n manifest_version: metadata.manifest_version,\n pm_min_version: metadata.pm_min_version,\n pm_max_version: metadata.pm_max_version,\n engines: metadata.engines,\n trusted: metadata.trusted,\n provenance: metadata.provenance,\n sandbox_profile: metadata.sandbox_profile,\n permissions: metadata.permissions,\n activation: metadata.activation,\n capabilities: metadata.capabilities,\n legacy_capability_aliases:\n metadata.legacy_capability_aliases.length > 0\n ? metadata.legacy_capability_aliases\n : undefined,\n };\n}\n\nfunction shouldEnable(\n name: string,\n enabled: Set<string>,\n disabled: Set<string>,\n): boolean {\n if (disabled.has(name)) {\n return false;\n }\n if (enabled.size === 0) {\n return true;\n }\n return enabled.has(name);\n}\n\n/** Resolve symlinks on both paths before the containment check so a link inside the directory cannot escape it. */\nexport async function isCanonicalPathWithinDirectory(\n directory: string,\n targetPath: string,\n): Promise<boolean> {\n const [resolvedDirectory, resolvedTargetPath] = await Promise.all([\n fs.realpath(directory),\n fs.realpath(targetPath),\n ]);\n return isPathWithinDirectory(resolvedDirectory, resolvedTargetPath);\n}\n\n/** Implements resolve extension roots for the public runtime surface of this module. */\nexport function resolveExtensionRoots(\n pmRoot: string,\n cwd = process.cwd(),\n): { global: string; project: string } {\n return {\n global: path.join(resolveGlobalPmRoot(cwd), \"extensions\"),\n project: path.join(pmRoot, \"extensions\"),\n };\n}\n\nasync function listExtensionDirectories(\n extensionsRoot: string,\n): Promise<string[]> {\n try {\n const entries = await fs.readdir(extensionsRoot, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort((a, b) => a.localeCompare(b));\n } catch {\n return [];\n }\n}\n\nfunction summarizeCandidate(candidate: ExtensionCandidate): EffectiveExtension {\n const summary: EffectiveExtension = {\n layer: candidate.layer,\n directory: candidate.directory,\n manifest_path: candidate.manifest_path,\n name: candidate.manifest.name,\n version: candidate.manifest.version,\n entry: candidate.manifest.entry,\n priority: candidate.manifest.priority,\n entry_path: candidate.entry_path,\n manifest_version: candidate.manifest.manifest_version,\n pm_min_version: candidate.manifest.pm_min_version,\n pm_max_version: candidate.manifest.pm_max_version,\n engines: candidate.manifest.engines,\n trusted: candidate.manifest.trusted,\n provenance: candidate.manifest.provenance,\n sandbox_profile: candidate.manifest.sandbox_profile,\n permissions: candidate.manifest.permissions,\n capabilities: [...candidate.manifest.capabilities],\n activation: candidate.manifest.activation\n ? {\n commands: [...(candidate.manifest.activation.commands as string[])],\n }\n : undefined,\n };\n if (candidate.source_package) {\n summary.source_package = candidate.source_package;\n }\n return summary;\n}\n\nfunction normalizeManagedSourcePackage(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0\n ? value.trim()\n : undefined;\n}\n\nasync function readManagedExtensionSourcePackages(\n extensionsRoot: string,\n): Promise<Map<string, string>> {\n const packages = new Map<string, string>();\n try {\n const parsed = JSON.parse(\n await fs.readFile(\n path.join(extensionsRoot, \".managed-extensions.json\"),\n \"utf8\",\n ),\n ) as unknown;\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n !Array.isArray((parsed as { entries?: unknown }).entries)\n ) {\n return packages;\n }\n for (const entry of (parsed as { entries: unknown[] }).entries) {\n if (typeof entry !== \"object\" || entry === null) {\n continue;\n }\n const record = entry as {\n directory?: unknown;\n name?: unknown;\n source?: { package?: unknown };\n };\n const sourcePackage = normalizeManagedSourcePackage(\n record.source?.package,\n );\n if (!sourcePackage) {\n continue;\n }\n if (\n typeof record.directory === \"string\" &&\n record.directory.trim().length > 0\n ) {\n packages.set(`directory:${record.directory.trim()}`, sourcePackage);\n }\n if (typeof record.name === \"string\" && record.name.trim().length > 0) {\n packages.set(`name:${record.name.trim()}`, sourcePackage);\n }\n }\n } catch {\n return packages;\n }\n return packages;\n}\n\nfunction sortCandidates(\n candidates: ExtensionCandidate[],\n): ExtensionCandidate[] {\n return [...candidates].sort((left, right) => {\n if (left.manifest.priority !== right.manifest.priority) {\n return left.manifest.priority - right.manifest.priority;\n }\n const byName = left.manifest.name.localeCompare(right.manifest.name);\n if (byName !== 0) {\n return byName;\n }\n return left.directory.localeCompare(right.directory);\n });\n}\n\nfunction buildEffectiveExtensions(\n globalCandidates: ExtensionCandidate[],\n projectCandidates: ExtensionCandidate[],\n): ExtensionCandidate[] {\n const ordered = [\n ...sortCandidates(globalCandidates),\n ...sortCandidates(projectCandidates),\n ];\n const effective: ExtensionCandidate[] = [];\n for (const candidate of ordered) {\n const existingIndex = effective.findIndex(\n (entry) => entry.manifest.name === candidate.manifest.name,\n );\n if (existingIndex >= 0) {\n effective.splice(existingIndex, 1);\n }\n effective.push(candidate);\n }\n return effective;\n}\n\nasync function scanExtensionLayer(\n layer: ExtensionLayer,\n extensionsRoot: string,\n enabled: Set<string>,\n disabled: Set<string>,\n pmMaxVersionExceededMode: PmMaxVersionExceededMode,\n): Promise<ExtensionLayerScanResult> {\n const diagnostics: ExtensionDiagnostic[] = [];\n const warnings: string[] = [];\n const candidates: ExtensionCandidate[] = [];\n const directories = await listExtensionDirectories(extensionsRoot);\n const managedSourcePackages =\n await readManagedExtensionSourcePackages(extensionsRoot);\n\n for (const directory of directories) {\n const scanned = await scanExtensionDirectory(\n layer,\n extensionsRoot,\n directory,\n enabled,\n disabled,\n managedSourcePackages,\n pmMaxVersionExceededMode,\n );\n diagnostics.push(scanned.diagnostic);\n warnings.push(...scanned.warnings);\n if (scanned.candidate) {\n candidates.push(scanned.candidate);\n }\n }\n\n return { diagnostics, warnings, candidates };\n}\n\nfunction emptyExtensionLayerScan(): ExtensionLayerScanResult {\n return { diagnostics: [], warnings: [], candidates: [] };\n}\n\n/** Build the `warn`-status scan result for a directory whose manifest is missing or unparseable, carrying the supplied diagnostic warning and no candidate. */\nfunction buildUnavailableExtensionScan(\n layer: ExtensionLayer,\n directory: string,\n manifestPath: string,\n warning: string,\n): ScannedExtensionDirectory {\n return {\n diagnostic: {\n layer,\n directory,\n manifest_path: manifestPath,\n name: null,\n version: null,\n entry: null,\n priority: null,\n entry_path: null,\n enabled: null,\n status: \"warn\",\n },\n warnings: [warning],\n candidate: null,\n };\n}\n\n/** Collect the non-fatal load warnings for a parsed extension manifest, in detection order: legacy capability aliases, unknown capabilities, an entry outside or absent from the extension directory, then the pm version floor/ceiling incompatibility warnings. */\nfunction collectScannedExtensionWarnings(\n layer: ExtensionLayer,\n manifest: ExtensionManifest,\n entryWithinDirectory: boolean,\n entryExists: boolean,\n pmVersionCompatibility: { allowed: boolean; warning?: string },\n pmMaxVersionCompatibility: { allowed: boolean; warning?: string },\n): string[] {\n const extensionWarnings: string[] = [];\n if (\n Array.isArray(manifest.legacy_capability_aliases) &&\n manifest.legacy_capability_aliases.length > 0\n ) {\n extensionWarnings.push(\n formatLegacyExtensionCapabilityAliasWarning(\n layer,\n manifest.name,\n manifest.legacy_capability_aliases,\n ),\n );\n }\n for (const capability of collectUnknownExtensionCapabilities(\n manifest.capabilities,\n )) {\n extensionWarnings.push(\n formatUnknownExtensionCapabilityWarning(layer, manifest.name, capability),\n );\n }\n if (!entryWithinDirectory) {\n extensionWarnings.push(\n `extension_entry_outside_extension:${layer}:${manifest.name}`,\n );\n } else if (!entryExists) {\n extensionWarnings.push(`extension_entry_missing:${layer}:${manifest.name}`);\n }\n if (pmVersionCompatibility.warning) {\n extensionWarnings.push(pmVersionCompatibility.warning);\n }\n if (pmMaxVersionCompatibility.warning) {\n extensionWarnings.push(pmMaxVersionCompatibility.warning);\n }\n return extensionWarnings;\n}\n\nasync function scanExtensionDirectory(\n layer: ExtensionLayer,\n extensionsRoot: string,\n directory: string,\n enabled: Set<string>,\n disabled: Set<string>,\n managedSourcePackages: ReadonlyMap<string, string>,\n pmMaxVersionExceededMode: PmMaxVersionExceededMode,\n): Promise<ScannedExtensionDirectory> {\n const extensionDir = path.join(extensionsRoot, directory);\n const manifestPath = path.join(extensionDir, \"manifest.json\");\n if (!(await pathExists(manifestPath))) {\n return buildUnavailableExtensionScan(\n layer,\n directory,\n manifestPath,\n `extension_manifest_missing:${layer}:${directory}`,\n );\n }\n\n let manifest: ExtensionManifest | null;\n try {\n const parsed = JSON.parse(\n await fs.readFile(manifestPath, \"utf8\"),\n ) as unknown;\n manifest = parseManifest(parsed);\n } catch {\n manifest = null;\n }\n\n if (!manifest) {\n return buildUnavailableExtensionScan(\n layer,\n directory,\n manifestPath,\n `extension_manifest_invalid:${layer}:${directory}`,\n );\n }\n\n const entryPath = path.resolve(extensionDir, manifest.entry);\n const entryWithinDirectoryByPath = isPathWithinDirectory(\n extensionDir,\n entryPath,\n );\n const entryExists = entryWithinDirectoryByPath\n ? await pathExists(entryPath)\n : false;\n const entryWithinDirectory =\n entryWithinDirectoryByPath && entryExists\n ? await isCanonicalPathWithinDirectory(extensionDir, entryPath)\n : entryWithinDirectoryByPath;\n const enabledForLoad = shouldEnable(manifest.name, enabled, disabled);\n const pmVersionCompatibility = await evaluatePmMinVersionCompatibility(\n layer,\n manifest,\n );\n const pmMaxVersionCompatibility = await evaluatePmMaxVersionCompatibility(\n layer,\n manifest,\n pmMaxVersionExceededMode,\n );\n const extensionWarnings = collectScannedExtensionWarnings(\n layer,\n manifest,\n entryWithinDirectory,\n entryExists,\n pmVersionCompatibility,\n pmMaxVersionCompatibility,\n );\n const extensionReady =\n entryWithinDirectory &&\n entryExists &&\n pmVersionCompatibility.allowed &&\n pmMaxVersionCompatibility.allowed;\n const sourcePackage =\n managedSourcePackages.get(`directory:${directory}`) ??\n managedSourcePackages.get(`name:${manifest.name}`);\n\n return {\n diagnostic: {\n layer,\n directory,\n manifest_path: manifestPath,\n name: manifest.name,\n version: manifest.version,\n entry: manifest.entry,\n priority: manifest.priority,\n entry_path: entryPath,\n enabled: enabledForLoad,\n status: extensionReady ? \"ok\" : \"warn\",\n },\n warnings: extensionWarnings,\n candidate:\n extensionReady && enabledForLoad\n ? {\n layer,\n directory,\n manifest_path: manifestPath,\n entry_path: entryPath,\n manifest,\n source_package: sourcePackage,\n }\n : null,\n };\n}\n\n/** Implements discover extensions for the public runtime surface of this module. */\nexport async function discoverExtensions(\n options: DiscoverExtensionsOptions,\n): Promise<ExtensionDiscoveryResult> {\n const roots = resolveExtensionRoots(\n options.pmRoot,\n options.cwd ?? process.cwd(),\n );\n const configured_enabled = normalizeNames(\n options.settings.extensions.enabled,\n );\n const configured_disabled = normalizeNames(\n options.settings.extensions.disabled,\n );\n const policy = normalizeExtensionPolicy(options.settings);\n const serializedPolicy = serializeExtensionPolicy(policy);\n\n if (options.noExtensions) {\n return {\n disabled_by_flag: true,\n roots,\n configured_enabled,\n configured_disabled,\n discovered: [],\n effective: [],\n warnings: [...policy.warnings],\n policy: serializedPolicy,\n };\n }\n\n const enabled = new Set(configured_enabled);\n const disabled = new Set(configured_disabled);\n const globalScan =\n options.ignoreGlobalExtensions === true\n ? emptyExtensionLayerScan()\n : await scanExtensionLayer(\n \"global\",\n roots.global,\n enabled,\n disabled,\n policy.pmMaxVersionExceededMode.global,\n );\n const projectScan = await scanExtensionLayer(\n \"project\",\n roots.project,\n enabled,\n disabled,\n policy.pmMaxVersionExceededMode.project,\n );\n const policyWarnings: string[] = [...policy.warnings];\n const effectiveCandidates = buildEffectiveExtensions(\n globalScan.candidates,\n projectScan.candidates,\n );\n const effective: EffectiveExtension[] = [];\n for (const candidate of effectiveCandidates) {\n const extensionRef = {\n layer: candidate.layer,\n name: candidate.manifest.name,\n trusted: candidate.manifest.trusted === true,\n provenanceVerified: candidate.manifest.provenance?.verified === true,\n sandboxProfile: candidate.manifest.sandbox_profile,\n permissions:\n candidate.manifest.permissions &&\n typeof candidate.manifest.permissions === \"object\"\n ? {\n fs_read: candidate.manifest.permissions.fs_read,\n fs_write: candidate.manifest.permissions.fs_write,\n network: candidate.manifest.permissions.network,\n env_read: candidate.manifest.permissions.env_read,\n env_write: candidate.manifest.permissions.env_write,\n process_spawn: candidate.manifest.permissions.process_spawn,\n }\n : undefined,\n };\n const extensionDecision = evaluateExtensionPolicyForExtension(\n policy,\n extensionRef,\n );\n if (extensionDecision.warning) {\n policyWarnings.push(extensionDecision.warning);\n }\n if (!extensionDecision.allowed) {\n continue;\n }\n for (const capability of candidate.manifest.capabilities) {\n const capabilityDecision = evaluateExtensionPolicyForCapability(\n policy,\n extensionRef,\n capability,\n );\n if (capabilityDecision.warning) {\n policyWarnings.push(capabilityDecision.warning);\n }\n }\n effective.push(summarizeCandidate(candidate));\n }\n\n return {\n disabled_by_flag: false,\n roots,\n configured_enabled,\n configured_disabled,\n discovered: [...globalScan.diagnostics, ...projectScan.diagnostics],\n effective,\n warnings: [\n ...new Set([\n ...globalScan.warnings,\n ...projectScan.warnings,\n ...policyWarnings,\n ]),\n ],\n policy: serializedPolicy,\n };\n}\n\nfunction formatUnknownError(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n return String(error);\n}\n\nasync function readCurrentPmCliVersion(): Promise<string | null> {\n try {\n const packageRoot = resolvePmPackageRootFromModule(import.meta.url, [\n \"../../..\",\n ]);\n const raw = await fs.readFile(\n path.join(packageRoot, \"package.json\"),\n \"utf8\",\n );\n const parsed = JSON.parse(raw) as { version?: unknown };\n return typeof parsed.version === \"string\" &&\n parsed.version.trim().length > 0\n ? parsed.version.trim()\n : null;\n } catch {\n return null;\n }\n}\n\nfunction resolveCurrentPmCliVersion(): Promise<string | null> {\n currentPmCliVersionPromise ??= readCurrentPmCliVersion();\n return currentPmCliVersionPromise;\n}\n\nfunction formatPmVersionCompatibilityWarning(\n layer: ExtensionLayer,\n manifest: ExtensionManifest,\n evaluation: PmVersionBoundEvaluation,\n): string | undefined {\n const current = evaluation.current ?? \"unknown\";\n if (evaluation.kind === \"pm_min_version\") {\n switch (evaluation.status) {\n case \"invalid\":\n return `extension_pm_min_version_invalid:${layer}:${manifest.name}:required=${evaluation.required}`;\n case \"unchecked\":\n return `extension_pm_min_version_unchecked:${layer}:${manifest.name}:required=${evaluation.required}:current=${current}`;\n case \"unmet\":\n return `extension_pm_min_version_unmet:${layer}:${manifest.name}:required=${evaluation.required}:current=${current}`;\n default:\n return undefined;\n }\n }\n switch (evaluation.status) {\n case \"invalid\":\n return `extension_pm_max_version_invalid:${layer}:${manifest.name}:allowed=${evaluation.required}`;\n case \"unchecked\":\n return `extension_pm_max_version_unchecked:${layer}:${manifest.name}:allowed=${evaluation.required}:current=${current}`;\n case \"exceeded_warn\":\n return `extension_pm_max_version_exceeded_warn:${layer}:${manifest.name}:allowed=${evaluation.required}:current=${current}`;\n case \"exceeded\":\n return `extension_pm_max_version_exceeded:${layer}:${manifest.name}:allowed=${evaluation.required}:current=${current}`;\n default:\n return undefined;\n }\n}\n\nasync function evaluatePmMinVersionCompatibility(\n layer: ExtensionLayer,\n manifest: ExtensionManifest,\n): Promise<{ allowed: boolean; warning?: string }> {\n // Resolve the current CLI version only when a bound is declared, so the common\n // no-bound case never reads package.json.\n if (manifest.pm_min_version === undefined) {\n return { allowed: true };\n }\n const evaluation = evaluatePmMinVersionBound(\n manifest.pm_min_version,\n await resolveCurrentPmCliVersion(),\n );\n const warning = formatPmVersionCompatibilityWarning(\n layer,\n manifest,\n evaluation,\n );\n return warning\n ? { allowed: evaluation.allowed, warning }\n : { allowed: evaluation.allowed };\n}\n\nasync function evaluatePmMaxVersionCompatibility(\n layer: ExtensionLayer,\n manifest: ExtensionManifest,\n exceededMode: PmMaxVersionExceededMode,\n): Promise<{ allowed: boolean; warning?: string }> {\n if (manifest.pm_max_version === undefined) {\n return { allowed: true };\n }\n const evaluation = evaluatePmMaxVersionBound(\n manifest.pm_max_version,\n await resolveCurrentPmCliVersion(),\n exceededMode,\n );\n const warning = formatPmVersionCompatibilityWarning(\n layer,\n manifest,\n evaluation,\n );\n return warning\n ? { allowed: evaluation.allowed, warning }\n : { allowed: evaluation.allowed };\n}\n\nasync function fingerprintPath(pathToInspect: string): Promise<string> {\n try {\n const stats = await fs.stat(pathToInspect);\n return `${Math.trunc(stats.mtimeMs)}-${stats.size}`;\n } catch {\n return \"missing\";\n }\n}\n\nasync function resolveExtensionImportHref(\n extension: EffectiveExtension,\n options: DiscoverExtensionsOptions,\n): Promise<string> {\n const baseUrl = new URL(pathToFileURL(extension.entry_path).href);\n const shouldCacheBust =\n options.cache_bust === true || typeof options.reload_token === \"string\";\n if (!shouldCacheBust) {\n return baseUrl.href;\n }\n const [entryFingerprint, manifestFingerprint] = await Promise.all([\n fingerprintPath(extension.entry_path),\n fingerprintPath(extension.manifest_path),\n ]);\n const reloadToken = options.reload_token ?? nextExtensionReloadToken();\n baseUrl.searchParams.set(\"pm_ext_reload\", reloadToken);\n baseUrl.searchParams.set(\"pm_ext_entry\", entryFingerprint);\n baseUrl.searchParams.set(\"pm_ext_manifest\", manifestFingerprint);\n return baseUrl.href;\n}\n\n/** Implements load extensions for the public runtime surface of this module. */\nexport async function loadExtensions(\n options: DiscoverExtensionsOptions,\n): Promise<ExtensionLoadResult> {\n const discovery = await discoverExtensions(options);\n const loaded: LoadedExtension[] = [];\n const failed: FailedExtensionLoad[] = [];\n const warnings = [...discovery.warnings];\n\n if (discovery.disabled_by_flag) {\n return {\n ...discovery,\n warnings,\n loaded,\n failed,\n };\n }\n\n const extensionsToLoad =\n typeof options.extensionFilter === \"function\"\n ? discovery.effective.filter(options.extensionFilter)\n : discovery.effective;\n for (const extension of extensionsToLoad) {\n try {\n const importHref = await resolveExtensionImportHref(extension, options);\n const module = await import(importHref);\n loaded.push({\n ...extension,\n module,\n });\n } catch (error: unknown) {\n warnings.push(\n `extension_load_failed:${extension.layer}:${extension.name}`,\n );\n failed.push({\n layer: extension.layer,\n name: extension.name,\n entry_path: extension.entry_path,\n error: formatUnknownError(error),\n });\n }\n }\n\n return {\n ...discovery,\n warnings,\n loaded,\n failed,\n };\n}\n\nconst DEFAULT_EXTENSION_DEACTIVATE_TIMEOUT_MS = 5_000;\nconst MAX_EXTENSION_DEACTIVATE_TIMEOUT_MS = 2_147_483_647;\n\nfunction toActivatableExtension(\n source: Record<string, unknown>,\n): ActivatableExtension {\n // Bind to `source` so a module/default-export authored with methods (or a class\n // instance) keeps its `this` across both lifecycle calls — `activate` is a\n // method call on a fresh object and `deactivate` is invoked bare, so without\n // binding the two would see different (or undefined) `this`.\n const activate = source.activate as ActivatableExtension[\"activate\"];\n const activatable: ActivatableExtension = {\n activate: activate.bind(source),\n };\n if (typeof source.deactivate === \"function\") {\n const deactivate = source.deactivate as NonNullable<\n ActivatableExtension[\"deactivate\"]\n >;\n activatable.deactivate = deactivate.bind(source);\n }\n return activatable;\n}\n\nfunction resolveActivatableExtension(\n module: unknown,\n): ActivatableExtension | null {\n const activatableRecord = resolveActivatablePropertyRecord(module);\n return activatableRecord ? toActivatableExtension(activatableRecord) : null;\n}\n\n/**\n * Run the optional `deactivate` teardown hook for every loaded extension that\n * exports one. Best-effort: a throwing teardown is captured as a warning and a\n * failure entry rather than propagated, so one extension cannot block another's\n * cleanup. Hosts call this on shutdown/reload (e.g. the MCP server between\n * native-action requests) to release resources opened during `activate`.\n *\n * Pass the `activationResult` to skip extensions whose `activate` failed — they\n * never fully initialized, so (VS Code-style) their `deactivate` must not run.\n * Teardowns run concurrently and each hook has a bounded timeout by default, so\n * one slow or hanging hook cannot serialize the rest or block the host\n * indefinitely unless the host explicitly disables the timeout; the returned\n * warnings/failures preserve loaded order.\n */\nexport async function deactivateExtensions(\n loadResult: ExtensionLoadResult,\n activationResult?: Pick<ExtensionActivationResult, \"failed\">,\n options: ExtensionDeactivationOptions = {},\n): Promise<ExtensionDeactivationResult> {\n const timeoutMs = normalizeExtensionDeactivateTimeout(\n options?.deactivate_timeout_ms,\n );\n const failedActivationKeys = new Set(\n (activationResult?.failed ?? []).map(\n (entry) => `${entry.layer}:${entry.name}`,\n ),\n );\n const targets: Array<{\n extension: LoadedExtension;\n deactivate: () => void | Promise<void>;\n }> = [];\n for (const extension of loadResult.loaded) {\n if (failedActivationKeys.has(`${extension.layer}:${extension.name}`)) {\n continue;\n }\n const activatable = resolveActivatableExtension(extension.module);\n if (!activatable || typeof activatable.deactivate !== \"function\") {\n continue;\n }\n targets.push({ extension, deactivate: activatable.deactivate });\n }\n const outcomes = await Promise.all(\n targets.map(async ({ extension, deactivate }) => {\n try {\n await runExtensionDeactivateWithTimeout(deactivate, timeoutMs);\n return { ok: true as const };\n } catch (error: unknown) {\n return {\n ok: false as const,\n layer: extension.layer,\n name: extension.name,\n error: formatUnknownError(error),\n };\n }\n }),\n );\n const warnings: string[] = [];\n const failed: ExtensionDeactivationFailure[] = [];\n let deactivated = 0;\n for (const outcome of outcomes) {\n if (outcome.ok) {\n deactivated += 1;\n continue;\n }\n warnings.push(\n `extension_deactivate_failed:${outcome.layer}:${outcome.name}`,\n );\n failed.push({\n layer: outcome.layer,\n name: outcome.name,\n error: outcome.error,\n });\n }\n return { deactivated, warnings, failed };\n}\n\nfunction normalizeExtensionDeactivateTimeout(rawTimeout: unknown): number {\n if (typeof rawTimeout !== \"number\" || rawTimeout < 0) {\n return DEFAULT_EXTENSION_DEACTIVATE_TIMEOUT_MS;\n }\n if (rawTimeout === 0 || rawTimeout === Infinity) {\n return 0;\n }\n if (!Number.isFinite(rawTimeout)) {\n return DEFAULT_EXTENSION_DEACTIVATE_TIMEOUT_MS;\n }\n return Math.min(\n MAX_EXTENSION_DEACTIVATE_TIMEOUT_MS,\n Math.max(1, Math.floor(rawTimeout)),\n );\n}\n\nasync function runExtensionDeactivateWithTimeout(\n deactivate: () => void | Promise<void>,\n timeoutMs: number,\n): Promise<void> {\n if (timeoutMs === 0) {\n await deactivate();\n return;\n }\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n try {\n // A timed-out deactivate promise may still finish later; JavaScript promises\n // are not cancellable, so the host only stops waiting and consumes any late\n // rejection from the hook.\n const deactivatePromise = Promise.resolve().then(() => deactivate());\n deactivatePromise.catch(() => {});\n await Promise.race([\n deactivatePromise,\n new Promise<never>((_, reject) => {\n timeoutHandle = setTimeout(() => {\n reject(\n new Error(`extension deactivate timed out after ${timeoutMs}ms`),\n );\n }, timeoutMs);\n timeoutHandle.unref?.();\n }),\n ]);\n } finally {\n clearTimeout(timeoutHandle as ReturnType<typeof setTimeout>);\n }\n}\n\nfunction isOutputRendererFormat(value: string): value is OutputRendererFormat {\n return value === \"toon\" || value === \"json\";\n}\n\nfunction isExtensionServiceName(value: string): value is ExtensionServiceName {\n return KNOWN_EXTENSION_SERVICE_NAMES.includes(value as ExtensionServiceName);\n}\n\nfunction assertHookHandler(hookName: string, hook: unknown): void {\n if (typeof hook !== \"function\") {\n throw new TypeError(`api.hooks.${hookName} requires a function handler`);\n }\n}\n\nfunction assertNonEmptyString(name: string, value: unknown): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${name} requires a non-empty string`);\n }\n return value.trim();\n}\n\nfunction assertFunctionHandler(name: string, value: unknown): void {\n if (typeof value !== \"function\") {\n throw new TypeError(`${name} requires a function handler`);\n }\n}\n\nfunction normalizeRegistrationName(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((part) => part.length > 0)\n .join(\" \");\n}\n\nfunction toRegistrationCommandPath(\n name: string,\n action: \"import\" | \"export\",\n): string {\n return normalizeCommandName(`${name} ${action}`);\n}\n\nfunction sanitizeRegistrationValue(value: unknown): unknown {\n if (value === null) {\n return null;\n }\n if (Array.isArray(value)) {\n return value.map((entry) => sanitizeRegistrationValue(entry));\n }\n if (typeof value === \"function\") {\n return \"[Function]\";\n }\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n if (typeof value === \"symbol\") {\n return value.toString();\n }\n if (typeof value === \"object\") {\n const record = value as Record<string, unknown>;\n const normalized: Record<string, unknown> = {};\n const keys = Object.keys(record).sort((left, right) =>\n left.localeCompare(right),\n );\n for (const key of keys) {\n normalized[key] = sanitizeRegistrationValue(record[key]);\n }\n return normalized;\n }\n return value;\n}\n\nfunction cloneRuntimeRegistrationValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((entry) => cloneRuntimeRegistrationValue(entry));\n }\n if (typeof value === \"object\" && value !== null) {\n const record = value as Record<string, unknown>;\n const cloned: Record<string, unknown> = {};\n for (const key of Object.keys(record).sort((left, right) =>\n left.localeCompare(right),\n )) {\n cloned[key] = cloneRuntimeRegistrationValue(record[key]);\n }\n return cloned;\n }\n return value;\n}\n\nconst EXTENSION_REGISTRATION_TRACE_SYMBOL = Symbol(\n \"extension_registration_trace\",\n);\n\ntype RegistrationTraceCarrier = Error & {\n [EXTENSION_REGISTRATION_TRACE_SYMBOL]?: ExtensionActivationFailureTrace;\n};\n\nfunction createRegistrationValidationError(\n message: string,\n trace: ExtensionActivationFailureTrace,\n): TypeError {\n const error = new TypeError(message) as RegistrationTraceCarrier;\n Object.defineProperty(error, EXTENSION_REGISTRATION_TRACE_SYMBOL, {\n value: trace,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return error;\n}\n\nfunction extractRegistrationValidationTrace(\n error: unknown,\n): ExtensionActivationFailureTrace | undefined {\n if (!(error instanceof Error)) {\n return undefined;\n }\n return (error as RegistrationTraceCarrier)[\n EXTENSION_REGISTRATION_TRACE_SYMBOL\n ];\n}\n\nfunction normalizeRegistrationRecord(\n name: string,\n value: unknown,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${name} requires an object definition`);\n }\n return sanitizeRegistrationValue(value) as Record<string, unknown>;\n}\n\nfunction normalizeRuntimeRegistrationRecord(\n name: string,\n value: unknown,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${name} requires an object definition`);\n }\n return cloneRuntimeRegistrationValue(value) as Record<string, unknown>;\n}\n\nfunction normalizeRegistrationRecordList(\n name: string,\n value: unknown,\n): Array<Record<string, unknown>> {\n if (!Array.isArray(value)) {\n throw new TypeError(`${name} requires an array of object definitions`);\n }\n return value.map((entry) => normalizeRegistrationRecord(name, entry));\n}\n\nfunction asRegistrationRecord(\n name: string,\n value: unknown,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${name} requires an object definition`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction assertOptionalBooleanField(name: string, value: unknown): void {\n if (value !== undefined && typeof value !== \"boolean\") {\n throw new TypeError(`${name} must be a boolean when provided`);\n }\n}\n\nfunction assertOptionalStringField(name: string, value: unknown): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${name} must be a non-empty string when provided`);\n }\n}\n\nfunction isFlagDefaultScalar(value: unknown): boolean {\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nfunction assertOptionalFlagDefaultField(name: string, value: unknown): void {\n if (value === undefined) {\n return;\n }\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n if (!isFlagDefaultScalar(item)) {\n throw new TypeError(\n `${name}[${index}] must be a string, number, or boolean`,\n );\n }\n }\n return;\n }\n if (!isFlagDefaultScalar(value)) {\n throw new TypeError(\n `${name} must be a string, number, or boolean, or an array of these when provided`,\n );\n }\n}\n\nfunction assertOptionalStringArrayField(name: string, value: unknown): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n throw new TypeError(\n `${name} must be an array of non-empty strings when provided`,\n );\n }\n for (const [index, entry] of value.entries()) {\n if (typeof entry !== \"string\" || entry.trim().length === 0) {\n throw new TypeError(`${name}[${index}] must be a non-empty string`);\n }\n }\n}\n\nfunction normalizeOptionalStringArrayField(\n name: string,\n value: unknown,\n): string[] {\n assertOptionalStringArrayField(name, value);\n if (!Array.isArray(value)) {\n return [];\n }\n const normalized: string[] = [];\n const seen = new Set<string>();\n for (const entry of value) {\n const trimmed = entry.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n return normalized;\n}\n\nfunction normalizeCommandActionName(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .replace(/[\\s_]+/g, \"-\")\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction resolveCommandDefinitionAction(\n commandPath: string,\n action: unknown,\n): string {\n if (action === undefined) {\n return commandPath.replace(/\\s+/g, \"-\");\n }\n if (typeof action !== \"string\" || action.trim().length === 0) {\n throw new TypeError(\n \"registerCommand definition.action must be a non-empty string when provided\",\n );\n }\n const normalized = normalizeCommandActionName(action);\n if (normalized.length === 0) {\n throw new TypeError(\n \"registerCommand definition.action must contain alphanumeric characters\",\n );\n }\n return normalized;\n}\n\nfunction normalizeCommandDefinitionArguments(\n value: unknown,\n): ExtensionCommandArgumentDefinition[] {\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new TypeError(\n \"registerCommand definition.arguments must be an array when provided\",\n );\n }\n const normalized: ExtensionCommandArgumentDefinition[] = [];\n for (const [index, entry] of value.entries()) {\n const record = asRegistrationRecord(\n `registerCommand definition.arguments[${index}]`,\n entry,\n );\n const name = assertNonEmptyString(\n `registerCommand definition.arguments[${index}].name`,\n record.name,\n );\n assertOptionalBooleanField(\n `registerCommand definition.arguments[${index}].required`,\n record.required,\n );\n assertOptionalBooleanField(\n `registerCommand definition.arguments[${index}].variadic`,\n record.variadic,\n );\n assertOptionalStringField(\n `registerCommand definition.arguments[${index}].description`,\n record.description,\n );\n if (name.includes(\" \")) {\n throw new TypeError(\n `registerCommand definition.arguments[${index}].name must not contain spaces`,\n );\n }\n const definition: ExtensionCommandArgumentDefinition = {\n name,\n };\n if (record.required === true) {\n definition.required = true;\n }\n if (record.variadic === true) {\n definition.variadic = true;\n }\n if (typeof record.description === \"string\") {\n definition.description = record.description.trim();\n }\n normalized.push(definition);\n }\n\n const variadicIndexes = normalized\n .map((argument, index) => (argument.variadic ? index : -1))\n .filter((index) => index >= 0);\n if (variadicIndexes.length > 1) {\n throw new TypeError(\n \"registerCommand definition.arguments supports at most one variadic argument\",\n );\n }\n if (\n variadicIndexes.length === 1 &&\n variadicIndexes[0] !== normalized.length - 1\n ) {\n throw new TypeError(\n \"registerCommand definition.arguments variadic argument must be the final argument\",\n );\n }\n\n return normalized;\n}\n\nfunction validateFlagDefinitions(flags: unknown): void {\n if (!Array.isArray(flags)) {\n throw new TypeError(\n \"registerFlags flags requires an array of object definitions\",\n );\n }\n for (const [index, raw] of flags.entries()) {\n const record = asRegistrationRecord(`registerFlags flags[${index}]`, raw);\n const long = record.long;\n const short = record.short;\n if (long === undefined && short === undefined) {\n throw new TypeError(\n `registerFlags flags[${index}] requires at least one of long or short`,\n );\n }\n assertOptionalStringField(`registerFlags flags[${index}].long`, long);\n assertOptionalStringField(`registerFlags flags[${index}].short`, short);\n assertOptionalStringField(\n `registerFlags flags[${index}].value_name`,\n record.value_name,\n );\n assertOptionalStringField(\n `registerFlags flags[${index}].description`,\n record.description,\n );\n assertOptionalBooleanField(\n `registerFlags flags[${index}].required`,\n record.required,\n );\n assertOptionalBooleanField(\n `registerFlags flags[${index}].enabled`,\n record.enabled,\n );\n assertOptionalBooleanField(\n `registerFlags flags[${index}].visible`,\n record.visible,\n );\n assertOptionalBooleanField(\n `registerFlags flags[${index}].list`,\n record.list,\n );\n assertOptionalFlagDefaultField(\n `registerFlags flags[${index}].default`,\n record.default,\n );\n if (Array.isArray(record.default) && record.list !== true) {\n throw new TypeError(\n `registerFlags flags[${index}].default cannot be an array unless list is true.`,\n );\n }\n assertFlagValueTypeAndDefault(`registerFlags flags[${index}]`, record);\n }\n}\n\n/** Reject a declared `value_type`/`type` that is not a known flag value kind, and a `default` whose value(s) would not cleanly coerce under that kind — so the typed-flag contract is enforced at registration instead of silently leaving an untyped value to surface at use time. */\nfunction assertFlagValueTypeAndDefault(\n label: string,\n record: Record<string, unknown>,\n): void {\n const declaredType =\n (typeof record.value_type === \"string\" ? record.value_type : undefined) ??\n (typeof record.type === \"string\" ? record.type : undefined);\n if (declaredType === undefined) {\n return;\n }\n const kind = resolveFlagValueKind(declaredType);\n if (kind === null) {\n throw new TypeError(\n `${label} value_type \"${declaredType}\" is not a known flag value type (expected one of: string, number, boolean).`,\n );\n }\n if (record.default === undefined) {\n return;\n }\n // For list flags, validate the default exactly as the runtime will see it —\n // comma-joined strings and nested arrays are flattened first — so a valid\n // default like `value_type: \"number\", default: \"10,20\"` is not wrongly rejected.\n const defaults =\n record.list === true\n ? flattenFlagListValue(record.default)\n : [record.default];\n for (const [defaultIndex, defaultValue] of defaults.entries()) {\n if (\n !isFlagDefaultValueCoercible(\n defaultValue as string | number | boolean,\n kind,\n )\n ) {\n const suffix =\n defaults.length > 1 ? `default[${defaultIndex}]` : \"default\";\n throw new TypeError(\n `${label}.${suffix} (${JSON.stringify(defaultValue)}) is not coercible to ${kind}.`,\n );\n }\n }\n}\n\nfunction validateItemFieldDefinitions(fields: unknown): void {\n if (!Array.isArray(fields)) {\n throw new TypeError(\n \"registerItemFields fields requires an array of object definitions\",\n );\n }\n for (const [index, raw] of fields.entries()) {\n const record = asRegistrationRecord(\n `registerItemFields fields[${index}]`,\n raw,\n );\n assertNonEmptyString(\n `registerItemFields fields[${index}].name`,\n record.name,\n );\n const fieldType = assertNonEmptyString(\n `registerItemFields fields[${index}].type`,\n record.type,\n );\n if (normalizeItemFieldType(fieldType) === null) {\n const suggestion = suggestKnownItemFieldType(fieldType);\n const hint = suggestion ? ` Did you mean \"${suggestion}\"?` : \"\";\n throw new TypeError(\n `registerItemFields fields[${index}].type \"${fieldType}\" is not a known field type ` +\n `(expected one of: ${KNOWN_ITEM_FIELD_TYPES.join(\", \")}).${hint}`,\n );\n }\n assertOptionalBooleanField(\n `registerItemFields fields[${index}].optional`,\n record.optional,\n );\n }\n}\n\nfunction validateItemTypeDefinitions(types: unknown): void {\n if (!Array.isArray(types)) {\n throw new TypeError(\n \"registerItemTypes types requires an array of object definitions\",\n );\n }\n for (const [typeIndex, raw] of types.entries()) {\n const record = asRegistrationRecord(\n `registerItemTypes types[${typeIndex}]`,\n raw,\n );\n assertNonEmptyString(\n `registerItemTypes types[${typeIndex}].name`,\n record.name,\n );\n assertOptionalStringField(\n `registerItemTypes types[${typeIndex}].folder`,\n record.folder,\n );\n assertOptionalStringArrayField(\n `registerItemTypes types[${typeIndex}].aliases`,\n record.aliases,\n );\n assertOptionalStringArrayField(\n `registerItemTypes types[${typeIndex}].required_create_fields`,\n record.required_create_fields,\n );\n assertOptionalStringArrayField(\n `registerItemTypes types[${typeIndex}].required_create_repeatables`,\n record.required_create_repeatables,\n );\n\n if (record.command_option_policies !== undefined) {\n if (!Array.isArray(record.command_option_policies)) {\n throw new TypeError(\n `registerItemTypes types[${typeIndex}].command_option_policies must be an array when provided`,\n );\n }\n for (const [\n policyIndex,\n rawPolicy,\n ] of record.command_option_policies.entries()) {\n const policy = asRegistrationRecord(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}]`,\n rawPolicy,\n );\n assertNonEmptyString(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}].command`,\n policy.command,\n );\n assertNonEmptyString(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}].option`,\n policy.option,\n );\n assertOptionalBooleanField(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}].enabled`,\n policy.enabled,\n );\n assertOptionalBooleanField(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}].required`,\n policy.required,\n );\n assertOptionalBooleanField(\n `registerItemTypes types[${typeIndex}].command_option_policies[${policyIndex}].visible`,\n policy.visible,\n );\n }\n }\n\n if (record.options !== undefined) {\n if (!Array.isArray(record.options)) {\n throw new TypeError(\n `registerItemTypes types[${typeIndex}].options must be an array when provided`,\n );\n }\n for (const [optionIndex, rawOption] of record.options.entries()) {\n const option = asRegistrationRecord(\n `registerItemTypes types[${typeIndex}].options[${optionIndex}]`,\n rawOption,\n );\n assertNonEmptyString(\n `registerItemTypes types[${typeIndex}].options[${optionIndex}].key`,\n option.key,\n );\n assertOptionalStringArrayField(\n `registerItemTypes types[${typeIndex}].options[${optionIndex}].values`,\n option.values,\n );\n assertOptionalBooleanField(\n `registerItemTypes types[${typeIndex}].options[${optionIndex}].required`,\n option.required,\n );\n assertOptionalStringArrayField(\n `registerItemTypes types[${typeIndex}].options[${optionIndex}].aliases`,\n option.aliases,\n );\n }\n }\n }\n}\n\nfunction validateMigrationDefinition(definition: unknown): void {\n const record = asRegistrationRecord(\n \"registerMigration definition\",\n definition,\n );\n if (record.id !== undefined && typeof record.id !== \"string\") {\n throw new TypeError(\n \"registerMigration definition.id must be a string when provided\",\n );\n }\n if (\n record.description !== undefined &&\n typeof record.description !== \"string\"\n ) {\n throw new TypeError(\n \"registerMigration definition.description must be a string when provided\",\n );\n }\n if (record.status !== undefined && typeof record.status !== \"string\") {\n throw new TypeError(\n \"registerMigration definition.status must be a string when provided\",\n );\n }\n assertOptionalBooleanField(\n \"registerMigration definition.mandatory\",\n record.mandatory,\n );\n if (record.run !== undefined && typeof record.run !== \"function\") {\n throw new TypeError(\n \"registerMigration definition.run must be a function when provided\",\n );\n }\n}\n\n/**\n * The seven array-valued dimensions a {@link ProjectProfileDefinition} stages.\n * Each is \"optional-by-emptiness\": an omitted dimension normalizes to an empty\n * array so the profile planner can iterate every dimension unconditionally.\n */\nconst PROJECT_PROFILE_DIMENSIONS = [\n \"types\",\n \"statuses\",\n \"fields\",\n \"workflows\",\n \"config\",\n \"templates\",\n \"packages\",\n] as const;\n\n/** Validates the field shapes the profile planner, `pm profile show/apply/lint`, and `describeProjectProfile` dereference without re-checking, so a structurally well-formed but type-violating extension entry (e.g. a workflow whose `type` is a number, or whose `allowed_transitions` is not an array) is rejected here rather than crashing a downstream consumer. Dimensions whose consumers already coerce or gracefully reject malformed values (statuses, fields, config) need no shape check. The `entry` is an already-confirmed non-null object. */\nfunction validateProjectProfileEntryShape(\n dimension: string,\n index: number,\n entry: Record<string, unknown>,\n): void {\n const at = `registerProfile profile.${dimension}[${index}]`;\n if (dimension === \"types\") {\n if (entry.name !== undefined && typeof entry.name !== \"string\") {\n throw new TypeError(`${at}.name must be a string when provided`);\n }\n return;\n }\n if (dimension === \"workflows\") {\n if (typeof entry.type !== \"string\") {\n throw new TypeError(`${at}.type must be a string`);\n }\n if (!Array.isArray(entry.allowed_transitions)) {\n throw new TypeError(`${at}.allowed_transitions must be an array`);\n }\n for (const [pairIndex, pair] of entry.allowed_transitions.entries()) {\n if (!Array.isArray(pair)) {\n throw new TypeError(\n `${at}.allowed_transitions[${pairIndex}] must be a [from, to] array`,\n );\n }\n }\n return;\n }\n if (dimension === \"templates\") {\n if (typeof entry.name !== \"string\") {\n throw new TypeError(`${at}.name must be a string`);\n }\n if (\n typeof entry.options !== \"object\" ||\n entry.options === null ||\n Array.isArray(entry.options)\n ) {\n throw new TypeError(`${at}.options must be an object`);\n }\n return;\n }\n if (dimension === \"packages\") {\n if (typeof entry.spec !== \"string\") {\n throw new TypeError(`${at}.spec must be a string`);\n }\n }\n}\n\nfunction validateProjectProfileDefinition(profile: unknown): void {\n const record = asRegistrationRecord(\"registerProfile profile\", profile);\n assertNonEmptyString(\"registerProfile profile.name\", record.name);\n assertNonEmptyString(\"registerProfile profile.title\", record.title);\n if (record.summary !== undefined && typeof record.summary !== \"string\") {\n throw new TypeError(\n \"registerProfile profile.summary must be a string when provided\",\n );\n }\n for (const dimension of PROJECT_PROFILE_DIMENSIONS) {\n const value = record[dimension];\n if (value === undefined) {\n continue;\n }\n if (!Array.isArray(value)) {\n throw new TypeError(\n `registerProfile profile.${dimension} must be an array when provided`,\n );\n }\n // Each dimension entry must be a non-null object: a primitive or null entry\n // (e.g. `statuses: [null]`, `types: [42]`) survives an array-only check but\n // crashes the profile planner and `pm profile show` when they read `entry.id`\n // / `entry.key` / `entry.type` later. Reject it at the registration boundary.\n for (const [index, entry] of value.entries()) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n throw new TypeError(\n `registerProfile profile.${dimension}[${index}] must be an object`,\n );\n }\n // Beyond \"is an object\", validate the specific field shapes consumers\n // dereference so a type-violating entry can never crash the planner, the\n // `pm profile` surfaces, or describeProjectProfile downstream.\n validateProjectProfileEntryShape(\n dimension,\n index,\n entry as Record<string, unknown>,\n );\n }\n }\n}\n\n/**\n * Fills an already-validated profile snapshot's optional surfaces — an absent\n * `summary` becomes an empty string and every omitted dimension an empty array —\n * so the stored definition always has the full {@link ProjectProfileDefinition}\n * shape the profile planner and `pm profile` resolution rely on. It runs after\n * validation on the cloned snapshot, so it only ever supplies missing defaults\n * and never has to coerce an invalid type (those are already rejected).\n */\nfunction applyProjectProfileDefaults(\n profile: Record<string, unknown>,\n): ProjectProfileDefinition {\n if (profile.summary === undefined) {\n profile.summary = \"\";\n }\n for (const dimension of PROJECT_PROFILE_DIMENSIONS) {\n if (profile[dimension] === undefined) {\n profile[dimension] = [];\n }\n }\n return profile as unknown as ProjectProfileDefinition;\n}\n\nfunction attachRuntimeDefinition<\n TEntry extends { definition: Record<string, unknown> },\n>(entry: TEntry, runtimeDefinition: Record<string, unknown>): TEntry {\n Object.defineProperty(entry, \"runtime_definition\", {\n value: runtimeDefinition,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n return entry;\n}\n\nfunction getDeclaredExtensionCapabilities(\n extension: LoadedExtension,\n): Set<ExtensionCapability> | null {\n if (!Array.isArray(extension.capabilities)) {\n return null;\n }\n const declared = new Set<ExtensionCapability>();\n for (const capability of extension.capabilities) {\n const normalized = capability.trim().toLowerCase();\n if (isKnownExtensionCapability(normalized)) {\n declared.add(normalized);\n }\n }\n return declared;\n}\n\nfunction assertExtensionCapability(\n extension: LoadedExtension,\n capability: ExtensionCapability,\n method: string,\n): void {\n const declared = getDeclaredExtensionCapabilities(extension);\n // Keep direct unit tests that construct LoadedExtension fixtures without\n // capability metadata backwards-compatible while enforcing manifest-declared\n // capabilities for runtime-loaded extensions.\n if (declared === null) {\n return;\n }\n if (!declared.has(capability)) {\n throw createRegistrationValidationError(\n `${method} requires capability '${capability}' in extension manifest capabilities`,\n {\n method,\n registration_index: -1,\n capability,\n missing_capability: capability,\n expected_schema: `\"capabilities\": [..., \"${capability}\"]`,\n received: extension.capabilities,\n hint: `Add \"${capability}\" to ${extension.name} manifest capabilities, or remove the ${method} registration call.`,\n },\n );\n }\n}\n\nfunction buildExtensionSelfIdentity(\n extension: LoadedExtension,\n): ExtensionSelfIdentity {\n return Object.freeze({\n name: extension.name,\n layer: extension.layer,\n version: extension.version,\n capabilities: Object.freeze(\n (extension.capabilities ?? []).filter(\n (capability): capability is ExtensionCapability =>\n (KNOWN_EXTENSION_CAPABILITIES as readonly string[]).includes(\n capability,\n ),\n ),\n ) as readonly ExtensionCapability[],\n pm_min_version: extension.pm_min_version,\n pm_max_version: extension.pm_max_version,\n source_package: extension.source_package,\n });\n}\n\nfunction buildPolicyExtensionRef(\n extension: LoadedExtension,\n): PolicyExtensionRef {\n return {\n layer: extension.layer,\n name: extension.name,\n trusted: extension.trusted === true,\n provenanceVerified: extension.provenance?.verified === true,\n sandboxProfile: extension.sandbox_profile,\n permissions:\n extension.permissions && typeof extension.permissions === \"object\"\n ? {\n fs_read: extension.permissions.fs_read,\n fs_write: extension.permissions.fs_write,\n network: extension.permissions.network,\n env_read: extension.permissions.env_read,\n env_write: extension.permissions.env_write,\n process_spawn: extension.permissions.process_spawn,\n }\n : undefined,\n };\n}\n\ninterface ExtensionRegistrationPolicyDetails {\n command?: string;\n action?: string;\n service?: string;\n}\n\nclass ExtensionApiRegistrar implements ExtensionApi {\n public readonly extension: ExtensionSelfIdentity;\n public readonly hooks: ExtensionApi[\"hooks\"];\n readonly #loadedExtension: LoadedExtension;\n readonly #extensionRef: PolicyExtensionRef;\n readonly #hookRegistry: ExtensionHookRegistry;\n readonly #commandRegistry: ExtensionCommandRegistry;\n readonly #parserRegistry: ExtensionParserRegistry;\n readonly #preflightRegistry: ExtensionPreflightRegistry;\n readonly #serviceRegistry: ExtensionServiceRegistry;\n readonly #rendererRegistry: ExtensionRendererRegistry;\n readonly #registrationRegistry: ExtensionRegistrationRegistry;\n readonly #activationWarnings: string[];\n readonly #policy: NormalizedExtensionPolicy;\n\n public constructor(\n extension: LoadedExtension,\n hooks: ExtensionHookRegistry,\n commands: ExtensionCommandRegistry,\n parsers: ExtensionParserRegistry,\n preflight: ExtensionPreflightRegistry,\n services: ExtensionServiceRegistry,\n renderers: ExtensionRendererRegistry,\n registrations: ExtensionRegistrationRegistry,\n activationWarnings: string[],\n policy: NormalizedExtensionPolicy,\n ) {\n this.#loadedExtension = extension;\n this.extension = buildExtensionSelfIdentity(extension);\n this.#extensionRef = buildPolicyExtensionRef(extension);\n this.#hookRegistry = hooks;\n this.#commandRegistry = commands;\n this.#parserRegistry = parsers;\n this.#preflightRegistry = preflight;\n this.#serviceRegistry = services;\n this.#rendererRegistry = renderers;\n this.#registrationRegistry = registrations;\n this.#activationWarnings = activationWarnings;\n this.#policy = policy;\n this.registerCommand = this.registerCommand.bind(this);\n this.registerParser = this.registerParser.bind(this);\n this.registerPreflight = this.registerPreflight.bind(this);\n this.registerService = this.registerService.bind(this);\n this.registerFlags = this.registerFlags.bind(this);\n this.registerItemFields = this.registerItemFields.bind(this);\n this.registerItemTypes = this.registerItemTypes.bind(this);\n this.registerMigration = this.registerMigration.bind(this);\n this.registerProfile = this.registerProfile.bind(this);\n this.registerRenderer = this.registerRenderer.bind(this);\n this.registerImporter = this.registerImporter.bind(this);\n this.registerExporter = this.registerExporter.bind(this);\n this.registerSearchProvider = this.registerSearchProvider.bind(this);\n this.registerVectorStoreAdapter =\n this.registerVectorStoreAdapter.bind(this);\n this.hooks = {\n beforeCommand: (hook) => this.registerBeforeCommand(hook),\n afterCommand: (hook) => this.registerAfterCommand(hook),\n onWrite: (hook) => this.registerOnWrite(hook),\n onRead: (hook) => this.registerOnRead(hook),\n onIndex: (hook) => this.registerOnIndex(hook),\n };\n }\n\n private allowRegistration(\n surface: ExtensionPolicySurface,\n method: string,\n capability?: ExtensionCapability,\n details?: ExtensionRegistrationPolicyDetails,\n ): boolean {\n const decision = evaluateExtensionPolicyForRegistration(\n this.#policy,\n this.#extensionRef,\n surface,\n method,\n capability,\n details,\n );\n if (decision.warning) {\n this.#activationWarnings.push(decision.warning);\n }\n return decision.allowed;\n }\n\n private registerCommandTrace(\n mode: \"override\" | \"definition\",\n command: string | undefined,\n expectedSchema: string,\n received: unknown,\n hint?: string,\n ): ExtensionActivationFailureTrace {\n return {\n method: \"registerCommand\",\n registration_index:\n mode === \"override\"\n ? this.#commandRegistry.overrides.length\n : this.#commandRegistry.handlers.length,\n command,\n expected_schema: expectedSchema,\n received: sanitizeRegistrationValue(received),\n hint,\n };\n }\n\n private registerCommandOverride(\n command: string,\n override: CommandOverride | undefined,\n ): void {\n const normalizedCommand = normalizeCommandName(command);\n if (normalizedCommand.length === 0) {\n throw createRegistrationValidationError(\n \"registerCommand requires a non-empty command name\",\n this.registerCommandTrace(\n \"override\",\n command,\n 'registerCommand(\"<command>\", (context) => unknown)',\n command,\n \"Provide a non-empty command path as the first argument.\",\n ),\n );\n }\n if (typeof override !== \"function\") {\n const trace = this.registerCommandTrace(\n \"override\",\n normalizedCommand,\n 'registerCommand(\"<command>\", (context) => unknown)',\n override,\n \"Provide a function as the second registerCommand argument.\",\n );\n throw createRegistrationValidationError(\n `registerCommand requires an override function when command name is provided (command=\"${normalizedCommand}\", registration_index=${trace.registration_index})`,\n trace,\n );\n }\n if (\n !this.allowRegistration(\n \"commands.override\",\n \"registerCommand\",\n \"commands\",\n { command: normalizedCommand },\n )\n ) {\n return;\n }\n this.#commandRegistry.overrides.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n command: normalizedCommand,\n run: override,\n });\n }\n\n private resolveCommandDefinitionRunHandler(\n definition: CommandDefinition,\n normalizedCommand: string,\n ): CommandHandler | undefined {\n const runHandler =\n typeof definition.run === \"function\" ? definition.run : undefined;\n const legacyHandler =\n typeof definition.handler === \"function\" ? definition.handler : undefined;\n if (!runHandler && legacyHandler) {\n this.#activationWarnings.push(\n `extension_command_definition_legacy_handler_alias:${this.#loadedExtension.layer}:${this.#loadedExtension.name}:${normalizedCommand}`,\n );\n }\n return runHandler ?? legacyHandler;\n }\n\n private registerCommandDefinition(definition: CommandDefinition): void {\n if (typeof definition !== \"object\" || definition === null) {\n throw createRegistrationValidationError(\n \"registerCommand requires a command definition object\",\n this.registerCommandTrace(\n \"definition\",\n undefined,\n \"{ name: string; run: (context) => unknown; }\",\n definition,\n 'Use registerCommand({ name: \"command path\", run: (context) => ... }).',\n ),\n );\n }\n if (typeof definition.name !== \"string\") {\n throw createRegistrationValidationError(\n \"registerCommand requires a command definition name\",\n this.registerCommandTrace(\n \"definition\",\n undefined,\n \"{ name: string; run: (context) => unknown; }\",\n definition,\n \"Set command definition.name to a non-empty string command path.\",\n ),\n );\n }\n\n const normalizedCommand = normalizeCommandName(definition.name);\n if (normalizedCommand.length === 0) {\n throw createRegistrationValidationError(\n \"registerCommand requires a non-empty command definition name\",\n this.registerCommandTrace(\n \"definition\",\n definition.name,\n \"{ name: string; run: (context) => unknown; }\",\n definition,\n \"Ensure command definition.name contains a non-empty command path.\",\n ),\n );\n }\n const resolvedHandler = this.resolveCommandDefinitionRunHandler(\n definition,\n normalizedCommand,\n );\n if (typeof resolvedHandler !== \"function\") {\n const trace = this.registerCommandTrace(\n \"definition\",\n normalizedCommand,\n \"{ name: string; run: (context) => unknown; }\",\n resolvedHandler,\n \"Define command definition.run as a function.\",\n );\n throw createRegistrationValidationError(\n `registerCommand requires a command definition run handler (command=\"${normalizedCommand}\", registration_index=${trace.registration_index})`,\n trace,\n );\n }\n try {\n assertOptionalStringField(\n \"registerCommand definition.action\",\n definition.action,\n );\n assertOptionalStringField(\n \"registerCommand definition.description\",\n definition.description,\n );\n assertOptionalStringField(\n \"registerCommand definition.intent\",\n definition.intent,\n );\n const action = resolveCommandDefinitionAction(\n normalizedCommand,\n definition.action,\n );\n if (\n !this.allowRegistration(\n \"commands.handler\",\n \"registerCommand\",\n \"commands\",\n { command: normalizedCommand, action },\n )\n ) {\n return;\n }\n const description = definition.description?.trim();\n const intent = definition.intent?.trim();\n const examples = normalizeOptionalStringArrayField(\n \"registerCommand definition.examples\",\n definition.examples,\n );\n const failureHints = normalizeOptionalStringArrayField(\n \"registerCommand definition.failure_hints\",\n definition.failure_hints,\n );\n const argumentsDefinition = normalizeCommandDefinitionArguments(\n definition.arguments,\n );\n\n if (definition.flags !== undefined) {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n \"registerCommand flags\",\n );\n if (\n this.allowRegistration(\n \"schema.flags\",\n \"registerCommand flags\",\n \"schema\",\n )\n ) {\n validateFlagDefinitions(definition.flags);\n this.#registrationRegistry.flags.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n target_command: normalizedCommand,\n flags: normalizeRegistrationRecordList(\n \"registerCommand definition.flags\",\n definition.flags,\n ),\n });\n }\n }\n\n const registration: RegisteredExtensionCommandDefinition = {\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n source_package: this.#loadedExtension.source_package,\n command: normalizedCommand,\n action,\n examples,\n failure_hints: failureHints,\n arguments: argumentsDefinition,\n };\n if (description) {\n registration.description = description;\n }\n if (intent) {\n registration.intent = intent;\n }\n this.#registrationRegistry.commands.push(registration);\n } catch (error: unknown) {\n const reason = formatUnknownError(error);\n const trace = this.registerCommandTrace(\n \"definition\",\n normalizedCommand,\n \"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }\",\n definition,\n reason,\n );\n throw createRegistrationValidationError(\n `registerCommand definition metadata invalid (command=\"${normalizedCommand}\", registration_index=${trace.registration_index}): ${reason}`,\n trace,\n );\n }\n this.#commandRegistry.handlers.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n command: normalizedCommand,\n run: resolvedHandler,\n });\n }\n\n public registerCommand(\n commandOrDefinition: string | CommandDefinition,\n override?: CommandOverride,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"commands\",\n \"registerCommand\",\n );\n if (typeof commandOrDefinition === \"string\") {\n this.registerCommandOverride(commandOrDefinition, override);\n return;\n }\n this.registerCommandDefinition(commandOrDefinition);\n }\n\n public registerParser(command: string, override: ParserOverride): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"parser\",\n \"registerParser\",\n );\n if (\n !this.allowRegistration(\"parser.override\", \"registerParser\", \"parser\")\n ) {\n return;\n }\n const normalizedCommand = normalizeCommandName(\n assertNonEmptyString(\"registerParser command\", command),\n );\n assertFunctionHandler(\"registerParser override\", override);\n this.#parserRegistry.overrides.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n command: normalizedCommand,\n run: override,\n });\n }\n\n public registerPreflight(override: PreflightOverride): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"preflight\",\n \"registerPreflight\",\n );\n if (\n !this.allowRegistration(\n \"preflight.override\",\n \"registerPreflight\",\n \"preflight\",\n )\n ) {\n return;\n }\n assertFunctionHandler(\"registerPreflight override\", override);\n this.#preflightRegistry.overrides.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: override,\n });\n }\n\n public registerService(\n service: ExtensionServiceName,\n override: ServiceOverride,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"services\",\n \"registerService\",\n );\n const normalizedService = String(service).trim().toLowerCase();\n if (!isExtensionServiceName(normalizedService)) {\n throw new TypeError(\n `registerService service must be one of: ${KNOWN_EXTENSION_SERVICE_NAMES.join(\", \")}`,\n );\n }\n if (\n !this.allowRegistration(\n \"services.override\",\n \"registerService\",\n \"services\",\n { service: normalizedService },\n )\n ) {\n return;\n }\n assertFunctionHandler(\"registerService override\", override);\n this.#serviceRegistry.overrides.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n service: normalizedService as ExtensionServiceName,\n run: override,\n });\n }\n\n public registerRenderer(\n format: OutputRendererFormat,\n renderer: RendererOverride,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"renderers\",\n \"registerRenderer\",\n );\n if (\n !this.allowRegistration(\n \"renderers.override\",\n \"registerRenderer\",\n \"renderers\",\n )\n ) {\n return;\n }\n if (typeof renderer !== \"function\") {\n throw new TypeError(\"registerRenderer requires a renderer function\");\n }\n const normalizedFormat = String(format).trim().toLowerCase();\n if (!isOutputRendererFormat(normalizedFormat)) {\n throw new Error(\n `registerRenderer format must be toon|json, received: ${String(format)}`,\n );\n }\n this.#rendererRegistry.overrides.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n format: normalizedFormat,\n run: renderer,\n });\n }\n\n public registerFlags(targetCommand: string, flags: FlagDefinition[]): void {\n assertExtensionCapability(this.#loadedExtension, \"schema\", \"registerFlags\");\n if (!this.allowRegistration(\"schema.flags\", \"registerFlags\", \"schema\")) {\n return;\n }\n const normalizedTargetCommand = normalizeCommandName(\n assertNonEmptyString(\"registerFlags targetCommand\", targetCommand),\n );\n validateFlagDefinitions(flags);\n const normalizedFlags = normalizeRegistrationRecordList(\n \"registerFlags flags\",\n flags,\n );\n if (normalizedFlags.length === 0) {\n throw new TypeError(\n \"registerFlags requires at least one flag definition\",\n );\n }\n this.#registrationRegistry.flags.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n target_command: normalizedTargetCommand,\n flags: normalizedFlags,\n });\n }\n\n public registerItemFields(fields: SchemaFieldDefinition[]): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n \"registerItemFields\",\n );\n if (\n !this.allowRegistration(\n \"schema.itemfields\",\n \"registerItemFields\",\n \"schema\",\n )\n ) {\n return;\n }\n validateItemFieldDefinitions(fields);\n const normalizedFields = normalizeRegistrationRecordList(\n \"registerItemFields fields\",\n fields,\n ) as SchemaFieldDefinition[];\n if (normalizedFields.length === 0) {\n throw new TypeError(\n \"registerItemFields requires at least one field definition\",\n );\n }\n this.#registrationRegistry.item_fields.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n fields: normalizedFields,\n });\n }\n\n public registerItemTypes(types: SchemaItemTypeDefinition[]): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n \"registerItemTypes\",\n );\n if (\n !this.allowRegistration(\"schema.itemtypes\", \"registerItemTypes\", \"schema\")\n ) {\n return;\n }\n validateItemTypeDefinitions(types);\n const normalizedTypes = normalizeRegistrationRecordList(\n \"registerItemTypes types\",\n types,\n ) as SchemaItemTypeDefinition[];\n if (normalizedTypes.length === 0) {\n throw new TypeError(\n \"registerItemTypes requires at least one type definition\",\n );\n }\n this.#registrationRegistry.item_types.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n types: normalizedTypes,\n });\n }\n\n public registerMigration(definition: SchemaMigrationDefinition): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n \"registerMigration\",\n );\n if (\n !this.allowRegistration(\n \"schema.migrations\",\n \"registerMigration\",\n \"schema\",\n )\n ) {\n return;\n }\n validateMigrationDefinition(definition);\n const runtimeDefinition = normalizeRuntimeRegistrationRecord(\n \"registerMigration definition\",\n definition,\n );\n this.#registrationRegistry.migrations.push(\n attachRuntimeDefinition(\n {\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n definition: normalizeRegistrationRecord(\n \"registerMigration definition\",\n definition,\n ),\n },\n runtimeDefinition,\n ) as RegisteredExtensionSchemaMigrationDefinition,\n );\n }\n\n public registerProfile(profile: ProjectProfileRegistrationInput): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n \"registerProfile\",\n );\n if (\n !this.allowRegistration(\"schema.profiles\", \"registerProfile\", \"schema\")\n ) {\n return;\n }\n // Snapshot first, then validate and default the snapshot: cloning resolves\n // any getters once into plain data decoupled from the caller's object, so\n // validation and storage operate on the same value — a getter cannot present\n // one value to validation and another to the registry. Defaults are applied\n // only after validation, so an invalid type is rejected, not silently coerced.\n const snapshot = cloneRuntimeRegistrationValue(profile);\n validateProjectProfileDefinition(snapshot);\n this.#registrationRegistry.profiles.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n profile: applyProjectProfileDefaults(snapshot as Record<string, unknown>),\n });\n }\n\n private applyImportExportCommandMetadata(\n method: \"registerImporter\" | \"registerExporter\",\n commandPath: string,\n options: ImportExportRegistrationOptions | undefined,\n ): void {\n if (\n options !== undefined &&\n (typeof options !== \"object\" || options === null || Array.isArray(options))\n ) {\n throw new TypeError(`${method} options must be an object when provided`);\n }\n const defaultDescription = `${method === \"registerImporter\" ? \"Import\" : \"Export\"} items with the registered extension adapter.`;\n const defaultArguments = [\n {\n name: \"file\",\n required: false,\n description: \"Optional input or output file path.\",\n },\n ];\n const resolvedOptions: ImportExportRegistrationOptions = {\n ...options,\n description: options?.description ?? defaultDescription,\n arguments: options?.arguments ?? defaultArguments,\n };\n assertOptionalStringField(`${method} options.action`, resolvedOptions.action);\n assertOptionalStringField(\n `${method} options.description`,\n resolvedOptions.description,\n );\n assertOptionalStringField(`${method} options.intent`, resolvedOptions.intent);\n const action = resolveCommandDefinitionAction(commandPath, resolvedOptions.action);\n const examples = normalizeOptionalStringArrayField(\n `${method} options.examples`,\n resolvedOptions.examples,\n );\n const failureHints = normalizeOptionalStringArrayField(\n `${method} options.failure_hints`,\n resolvedOptions.failure_hints,\n );\n const argumentsDefinition = normalizeCommandDefinitionArguments(\n resolvedOptions.arguments,\n );\n\n if (resolvedOptions.flags !== undefined) {\n assertExtensionCapability(\n this.#loadedExtension,\n \"schema\",\n `${method} options.flags`,\n );\n // Route metadata flags through the same surface-policy gate as registerFlags so\n // enforce-mode policies blocking schema.flags are honored even when importers are allowed.\n if (\n this.allowRegistration(\n \"schema.flags\",\n `${method} options.flags`,\n \"schema\",\n )\n ) {\n validateFlagDefinitions(resolvedOptions.flags);\n this.#registrationRegistry.flags.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n target_command: commandPath,\n flags: normalizeRegistrationRecordList(\n `${method} options.flags`,\n resolvedOptions.flags,\n ),\n });\n }\n }\n\n const registration: RegisteredExtensionCommandDefinition = {\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n source_package: this.#loadedExtension.source_package,\n command: commandPath,\n action,\n examples,\n failure_hints: failureHints,\n arguments: argumentsDefinition,\n };\n const description = resolvedOptions.description?.trim();\n if (description) {\n registration.description = description;\n }\n const intent = resolvedOptions.intent?.trim();\n if (intent) {\n registration.intent = intent;\n }\n this.#registrationRegistry.commands.push(registration);\n }\n\n public registerImporter(\n name: string,\n importer: Importer,\n options?: ImportExportRegistrationOptions,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"importers\",\n \"registerImporter\",\n );\n if (\n !this.allowRegistration(\n \"importers.importer\",\n \"registerImporter\",\n \"importers\",\n )\n ) {\n return;\n }\n const normalizedName = normalizeRegistrationName(\n assertNonEmptyString(\"registerImporter name\", name),\n );\n assertFunctionHandler(\"registerImporter importer\", importer);\n const commandPath = toRegistrationCommandPath(normalizedName, \"import\");\n // Validate and register optional command metadata before mutating the registry\n // so an invalid options object leaves no partial importer registration.\n this.applyImportExportCommandMetadata(\n \"registerImporter\",\n commandPath,\n options,\n );\n this.#registrationRegistry.importers.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n importer: normalizedName,\n });\n this.#commandRegistry.handlers.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n command: commandPath,\n run: async (context) =>\n importer({\n registration: normalizedName,\n action: \"import\",\n command: context.command,\n args: cloneContextSnapshot(context.args),\n options: cloneContextSnapshot(context.options),\n global: cloneContextSnapshot(context.global),\n pm_root: context.pm_root,\n }),\n });\n }\n\n public registerExporter(\n name: string,\n exporter: Exporter,\n options?: ImportExportRegistrationOptions,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"importers\",\n \"registerExporter\",\n );\n if (\n !this.allowRegistration(\n \"importers.exporter\",\n \"registerExporter\",\n \"importers\",\n )\n ) {\n return;\n }\n const normalizedName = normalizeRegistrationName(\n assertNonEmptyString(\"registerExporter name\", name),\n );\n assertFunctionHandler(\"registerExporter exporter\", exporter);\n const commandPath = toRegistrationCommandPath(normalizedName, \"export\");\n // Validate and register optional command metadata before mutating the registry\n // so an invalid options object leaves no partial exporter registration.\n this.applyImportExportCommandMetadata(\n \"registerExporter\",\n commandPath,\n options,\n );\n this.#registrationRegistry.exporters.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n exporter: normalizedName,\n });\n this.#commandRegistry.handlers.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n command: commandPath,\n run: async (context) =>\n exporter({\n registration: normalizedName,\n action: \"export\",\n command: context.command,\n args: cloneContextSnapshot(context.args),\n options: cloneContextSnapshot(context.options),\n global: cloneContextSnapshot(context.global),\n pm_root: context.pm_root,\n }),\n });\n }\n\n public registerSearchProvider(provider: SearchProviderDefinition): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"search\",\n \"registerSearchProvider\",\n );\n if (\n !this.allowRegistration(\n \"search.provider\",\n \"registerSearchProvider\",\n \"search\",\n )\n ) {\n return;\n }\n const runtimeDefinition = normalizeRuntimeRegistrationRecord(\n \"registerSearchProvider provider\",\n provider,\n );\n this.#registrationRegistry.search_providers.push(\n attachRuntimeDefinition(\n {\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n definition: normalizeRegistrationRecord(\n \"registerSearchProvider provider\",\n provider,\n ),\n },\n runtimeDefinition,\n ) as RegisteredExtensionSearchProvider,\n );\n }\n\n public registerVectorStoreAdapter(\n adapter: VectorStoreAdapterDefinition,\n ): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"search\",\n \"registerVectorStoreAdapter\",\n );\n if (\n !this.allowRegistration(\n \"search.vectorstore\",\n \"registerVectorStoreAdapter\",\n \"search\",\n )\n ) {\n return;\n }\n const runtimeDefinition = normalizeRuntimeRegistrationRecord(\n \"registerVectorStoreAdapter adapter\",\n adapter,\n );\n this.#registrationRegistry.vector_store_adapters.push(\n attachRuntimeDefinition(\n {\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n definition: normalizeRegistrationRecord(\n \"registerVectorStoreAdapter adapter\",\n adapter,\n ),\n },\n runtimeDefinition,\n ) as RegisteredExtensionVectorStoreAdapter,\n );\n }\n\n private registerBeforeCommand(hook: BeforeCommandHook): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"hooks\",\n \"api.hooks.beforeCommand\",\n );\n if (\n !this.allowRegistration(\n \"hooks.beforecommand\",\n \"api.hooks.beforeCommand\",\n \"hooks\",\n )\n ) {\n return;\n }\n assertHookHandler(\"beforeCommand\", hook);\n this.#hookRegistry.beforeCommand.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: hook,\n });\n }\n\n private registerAfterCommand(hook: AfterCommandHook): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"hooks\",\n \"api.hooks.afterCommand\",\n );\n if (\n !this.allowRegistration(\n \"hooks.aftercommand\",\n \"api.hooks.afterCommand\",\n \"hooks\",\n )\n ) {\n return;\n }\n assertHookHandler(\"afterCommand\", hook);\n this.#hookRegistry.afterCommand.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: hook,\n });\n }\n\n private registerOnWrite(hook: OnWriteHook): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"hooks\",\n \"api.hooks.onWrite\",\n );\n if (\n !this.allowRegistration(\"hooks.onwrite\", \"api.hooks.onWrite\", \"hooks\")\n ) {\n return;\n }\n assertHookHandler(\"onWrite\", hook);\n this.#hookRegistry.onWrite.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: hook,\n });\n }\n\n private registerOnRead(hook: OnReadHook): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"hooks\",\n \"api.hooks.onRead\",\n );\n if (!this.allowRegistration(\"hooks.onread\", \"api.hooks.onRead\", \"hooks\")) {\n return;\n }\n assertHookHandler(\"onRead\", hook);\n this.#hookRegistry.onRead.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: hook,\n });\n }\n\n private registerOnIndex(hook: OnIndexHook): void {\n assertExtensionCapability(\n this.#loadedExtension,\n \"hooks\",\n \"api.hooks.onIndex\",\n );\n if (\n !this.allowRegistration(\"hooks.onindex\", \"api.hooks.onIndex\", \"hooks\")\n ) {\n return;\n }\n assertHookHandler(\"onIndex\", hook);\n this.#hookRegistry.onIndex.push({\n layer: this.#loadedExtension.layer,\n name: this.#loadedExtension.name,\n run: hook,\n });\n }\n}\n\nfunction createExtensionApi(\n extension: LoadedExtension,\n hooks: ExtensionHookRegistry,\n commands: ExtensionCommandRegistry,\n parsers: ExtensionParserRegistry,\n preflight: ExtensionPreflightRegistry,\n services: ExtensionServiceRegistry,\n renderers: ExtensionRendererRegistry,\n registrations: ExtensionRegistrationRegistry,\n activationWarnings: string[],\n policy: NormalizedExtensionPolicy,\n): ExtensionApi {\n return new ExtensionApiRegistrar(\n extension,\n hooks,\n commands,\n parsers,\n preflight,\n services,\n renderers,\n registrations,\n activationWarnings,\n policy,\n );\n}\n\nfunction getRegistrationCounts(\n registrations: ExtensionRegistrationRegistry,\n): ExtensionRegistrationCounts {\n const commandCount = registrations.commands.length;\n const flagCount = registrations.flags.reduce(\n (total, entry) => total + entry.flags.length,\n 0,\n );\n const itemFieldCount = registrations.item_fields.reduce(\n (total, entry) => total + entry.fields.length,\n 0,\n );\n const itemTypeCount = registrations.item_types.reduce(\n (total, entry) => total + entry.types.length,\n 0,\n );\n return {\n commands: commandCount,\n flags: flagCount,\n item_fields: itemFieldCount,\n item_types: itemTypeCount,\n migrations: registrations.migrations.length,\n profiles: registrations.profiles.length,\n importers: registrations.importers.length,\n exporters: registrations.exporters.length,\n search_providers: registrations.search_providers.length,\n vector_store_adapters: registrations.vector_store_adapters.length,\n };\n}\n\nfunction collectCommandCollisionWarnings(\n commands: ExtensionCommandRegistry,\n): string[] {\n const warnings: string[] = [];\n const collectByCommand = <\n TEntry extends { layer: ExtensionLayer; name: string; command: string },\n >(\n entries: TEntry[],\n codePrefix: string,\n ): void => {\n const grouped = new Map<string, TEntry[]>();\n for (const entry of entries) {\n const bucket = grouped.get(entry.command) ?? [];\n bucket.push(entry);\n grouped.set(entry.command, bucket);\n }\n for (const command of [...grouped.keys()].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const bucket = grouped.get(command)!;\n if (bucket.length <= 1) {\n continue;\n }\n const winner = bucket[bucket.length - 1];\n for (const displaced of bucket.slice(0, -1)) {\n warnings.push(\n `${codePrefix}:${command}:${winner.layer}:${winner.name}:${displaced.layer}:${displaced.name}`,\n );\n }\n }\n };\n\n collectByCommand(commands.handlers, \"extension_command_handler_collision\");\n collectByCommand(commands.overrides, \"extension_command_override_collision\");\n\n const handlerCommands = new Set(\n commands.handlers.map((entry) => entry.command),\n );\n const overlapCommands = [\n ...new Set(commands.overrides.map((entry) => entry.command)),\n ].filter((command) => handlerCommands.has(command));\n overlapCommands.sort((left, right) => left.localeCompare(right));\n for (const command of overlapCommands) {\n const handlers = commands.handlers.filter(\n (entry) => entry.command === command,\n );\n const overrides = commands.overrides.filter(\n (entry) => entry.command === command,\n );\n for (const override of overrides) {\n for (const handler of handlers) {\n warnings.push(\n `extension_command_override_handler_overlap:${command}:${override.layer}:${override.name}:${handler.layer}:${handler.name}`,\n );\n }\n }\n }\n\n return warnings;\n}\n\nfunction collectRendererCollisionWarnings(\n renderers: ExtensionRendererRegistry,\n): string[] {\n const grouped = new Map<\n OutputRendererFormat,\n RegisteredExtensionRendererOverride[]\n >();\n for (const entry of renderers.overrides) {\n const bucket = grouped.get(entry.format) ?? [];\n bucket.push(entry);\n grouped.set(entry.format, bucket);\n }\n const warnings: string[] = [];\n for (const format of [...grouped.keys()].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const bucket = grouped.get(format)!;\n if (bucket.length <= 1) {\n continue;\n }\n const winner = bucket[bucket.length - 1];\n for (const displaced of bucket.slice(0, -1)) {\n warnings.push(\n `extension_renderer_collision:${format}:${winner.layer}:${winner.name}:${displaced.layer}:${displaced.name}`,\n );\n }\n }\n return warnings;\n}\n\nfunction collectParserCollisionWarnings(\n parsers: ExtensionParserRegistry,\n): string[] {\n const warnings: string[] = [];\n const grouped = new Map<string, RegisteredExtensionParserOverride[]>();\n for (const entry of parsers.overrides) {\n const bucket = grouped.get(entry.command) ?? [];\n bucket.push(entry);\n grouped.set(entry.command, bucket);\n }\n for (const command of [...grouped.keys()].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const bucket = grouped.get(command)!;\n if (bucket.length <= 1) {\n continue;\n }\n const winner = bucket[bucket.length - 1];\n for (const displaced of bucket.slice(0, -1)) {\n warnings.push(\n `extension_parser_override_collision:${command}:${winner.layer}:${winner.name}:${displaced.layer}:${displaced.name}`,\n );\n }\n }\n return warnings;\n}\n\nfunction collectPreflightCollisionWarnings(\n preflight: ExtensionPreflightRegistry,\n): string[] {\n if (preflight.overrides.length <= 1) {\n return [];\n }\n const winner = preflight.overrides[preflight.overrides.length - 1];\n return preflight.overrides\n .slice(0, -1)\n .map(\n (displaced) =>\n `extension_preflight_override_collision:${winner.layer}:${winner.name}:${displaced.layer}:${displaced.name}`,\n );\n}\n\n// Services whose runtime semantics are chain/fall-through (each override gets a chance);\n// for those, registering multiple overrides is by design, not a collision.\nconst CHAINED_SERVICE_NAMES: ReadonlySet<ExtensionServiceName> =\n new Set<ExtensionServiceName>([\"output_format\"]);\n\nfunction collectServiceCollisionWarnings(\n services: ExtensionServiceRegistry,\n): string[] {\n const warnings: string[] = [];\n const grouped = new Map<\n ExtensionServiceName,\n RegisteredExtensionServiceOverride[]\n >();\n for (const entry of services.overrides) {\n const bucket = grouped.get(entry.service) ?? [];\n bucket.push(entry);\n grouped.set(entry.service, bucket);\n }\n for (const service of [...grouped.keys()].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const bucket = grouped.get(service)!;\n if (bucket.length <= 1) {\n continue;\n }\n if (CHAINED_SERVICE_NAMES.has(service)) {\n continue;\n }\n const winner = bucket[bucket.length - 1];\n for (const displaced of bucket.slice(0, -1)) {\n warnings.push(\n `extension_service_override_collision:${service}:${winner.layer}:${winner.name}:${displaced.layer}:${displaced.name}`,\n );\n }\n }\n return warnings;\n}\n\n/** Implements activate extensions for the public runtime surface of this module. */\nexport async function activateExtensions(\n loadResult: ExtensionLoadResult,\n): Promise<ExtensionActivationResult> {\n const policy = hydrateExtensionPolicy(\n loadResult.policy ?? DEFAULT_EXTENSION_POLICY,\n );\n const hooks = createEmptyExtensionHookRegistry();\n const commands = createEmptyExtensionCommandRegistry();\n const parsers = createEmptyExtensionParserRegistry();\n const preflight = createEmptyExtensionPreflightRegistry();\n const services = createEmptyExtensionServiceRegistry();\n const renderers = createEmptyExtensionRendererRegistry();\n const registrations = createEmptyExtensionRegistrationRegistry();\n const failed: FailedExtensionActivation[] = [];\n const warnings: string[] = [];\n\n for (const extension of loadResult.loaded) {\n const activatable = resolveActivatableExtension(extension.module);\n if (!activatable) {\n continue;\n }\n\n try {\n await activatable.activate(\n createExtensionApi(\n extension,\n hooks,\n commands,\n parsers,\n preflight,\n services,\n renderers,\n registrations,\n warnings,\n policy,\n ),\n );\n } catch (error: unknown) {\n warnings.push(\n `extension_activate_failed:${extension.layer}:${extension.name}`,\n );\n const trace = extractRegistrationValidationTrace(error);\n failed.push({\n layer: extension.layer,\n name: extension.name,\n entry_path: extension.entry_path,\n error: formatUnknownError(error),\n trace,\n });\n }\n }\n\n const collisionWarnings = [\n ...collectCommandCollisionWarnings(commands),\n ...collectParserCollisionWarnings(parsers),\n ...collectPreflightCollisionWarnings(preflight),\n ...collectServiceCollisionWarnings(services),\n ...collectRendererCollisionWarnings(renderers),\n ];\n const mergedWarnings = [...new Set([...warnings, ...collisionWarnings])];\n\n return {\n hooks,\n commands,\n parsers,\n preflight,\n services,\n renderers,\n registrations,\n failed,\n warnings: mergedWarnings,\n hook_counts: {\n before_command: hooks.beforeCommand.length,\n after_command: hooks.afterCommand.length,\n on_write: hooks.onWrite.length,\n on_read: hooks.onRead.length,\n on_index: hooks.onIndex.length,\n },\n command_override_count: commands.overrides.length,\n command_handler_count: commands.handlers.length,\n parser_override_count: parsers.overrides.length,\n preflight_override_count: preflight.overrides.length,\n service_override_count: services.overrides.length,\n renderer_override_count: renderers.overrides.length,\n registration_counts: getRegistrationCounts(registrations),\n };\n}\n\n/** Public contract for test only loader, shared by SDK and presentation-layer consumers. */\nexport const _testOnlyLoader = {\n assertFlagValueTypeAndDefault,\n assertOptionalStringField,\n compareComparableVersions,\n collectCommandCollisionWarnings,\n collectParserCollisionWarnings,\n collectRendererCollisionWarnings,\n collectServiceCollisionWarnings,\n createExtensionApi,\n createRegistrationValidationError,\n evaluatePmMaxVersionCompatibility,\n evaluatePmMinVersionCompatibility,\n extractRegistrationValidationTrace,\n fingerprintPath,\n getRegistrationCounts,\n normalizeCommandDefinitionArguments,\n normalizeExtensionDeactivateTimeout,\n normalizeOptionalStringArrayField,\n normalizeRegistrationRecord,\n normalizeRegistrationRecordList,\n normalizeRuntimeRegistrationRecord,\n parseComparableVersion,\n parseManifest,\n readCurrentPmCliVersion,\n readManagedExtensionSourcePackages,\n resolveExtensionImportHref,\n resolveCurrentPmCliVersion,\n resolveCommandDefinitionAction,\n sanitizeRegistrationValue,\n validateItemFieldDefinitions,\n resetCurrentPmCliVersionCacheForTest: () => {\n currentPmCliVersionPromise = null;\n },\n};\n","/**\n * @module core/fs/path-utils\n *\n * Provides filesystem helpers for Path Utils.\n */\nimport path from \"path\";\n\n/** Implements check whether path within directory for the public runtime surface of this module. */\nexport function isPathWithinDirectory(\n directory: string,\n targetPath: string,\n): boolean {\n const relative = path.relative(directory, targetPath);\n if (relative.length === 0) {\n return true;\n }\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n}\n","/** Canonical coercion kinds an extension flag can declare via `value_type` (or the deprecated `type` alias). The runtime also accepts a few common aliases (`int`/`integer`/`float` -> number, `bool` -> boolean) so author intent is honored without surprises. */\n/** Canonical scalar value kinds accepted by extension command flag definitions. */\nexport type FlagValueKind = \"string\" | \"number\" | \"boolean\";\n\nconst FLAG_VALUE_KIND_BY_ALIAS: Readonly<Record<string, FlagValueKind>> =\n Object.freeze({\n string: \"string\",\n number: \"number\",\n int: \"number\",\n integer: \"number\",\n float: \"number\",\n boolean: \"boolean\",\n bool: \"boolean\",\n });\n\n/** Resolve a declared flag value type (string) to its canonical kind, or `null` when it is not a recognized type/alias. Matching is trim- and case-insensitive. */\nexport function resolveFlagValueKind(raw: unknown): FlagValueKind | null {\n if (typeof raw !== \"string\") {\n return null;\n }\n return FLAG_VALUE_KIND_BY_ALIAS[raw.trim().toLowerCase()] ?? null;\n}\n\n/** Flatten a `list` flag value (or default) into its individual entries the same way the runtime does: nested arrays are flattened and comma-joined strings are split, with surrounding whitespace trimmed and empty segments dropped. No type coercion is applied. Shared by the CLI coercion path and the registration-time default validator so the two never disagree. */\nexport function flattenFlagListValue(value: unknown): unknown[] {\n const entries: unknown[] = [];\n const collect = (input: unknown): void => {\n if (Array.isArray(input)) {\n for (const item of input) {\n collect(item);\n }\n return;\n }\n if (typeof input === \"string\") {\n for (const part of input.split(\",\")) {\n const trimmed = part.trim();\n if (trimmed.length > 0) {\n entries.push(trimmed);\n }\n }\n return;\n }\n if (input !== undefined && input !== null) {\n entries.push(input);\n }\n };\n collect(value);\n return entries;\n}\n\n/** Whether a scalar flag default would cleanly coerce under the declared kind, mirroring the runtime coercion rules in `coerceLooseCommandOptionsWithFlagDefinitions`. Used to reject contradictory definitions (e.g. `value_type: \"number\"` with `default: \"abc\"`) at registration instead of letting an untyped value pass through to activation. */\nexport function isFlagDefaultValueCoercible(\n value: string | number | boolean,\n kind: FlagValueKind,\n): boolean {\n if (kind === \"string\") {\n return true;\n }\n if (kind === \"number\") {\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n return (\n typeof value === \"string\" &&\n value.trim().length > 0 &&\n Number.isFinite(Number(value))\n );\n }\n if (typeof value === \"boolean\") {\n return true;\n }\n return (\n typeof value === \"string\" &&\n [\"true\", \"false\", \"1\", \"0\"].includes(value.trim().toLowerCase())\n );\n}\n","/**\n * @module core/extensions/item-field-types\n *\n * Implements extension runtime contracts and governance for Item Field Types.\n */\nimport { levenshteinDistanceWithinLimit } from \"../shared/levenshtein.js\";\n\n/**\n * Canonical coercion kinds accepted for extension-registered custom item fields.\n *\n * A `registerItemFields` definition declares one of these as its `type`; the\n * value is later coerced by that kind (see `coerceRegisteredFieldValue`). Keep\n * this list in lock-step with the coercion switch in `item-fields.ts`.\n */\nexport const KNOWN_ITEM_FIELD_TYPES = [\n \"string\",\n \"number\",\n \"boolean\",\n \"array\",\n \"object\",\n] as const;\n/** Restricts known item field type values accepted by command, SDK, and storage contracts. */\nexport type KnownItemFieldType = (typeof KNOWN_ITEM_FIELD_TYPES)[number];\n\n/** Normalize a declared field type to its canonical kind, or `null` when the value is not a known type. Matching is trim- and case-insensitive. */\nexport function normalizeItemFieldType(\n value: string,\n): KnownItemFieldType | null {\n const normalized = value.trim().toLowerCase();\n return (KNOWN_ITEM_FIELD_TYPES as readonly string[]).includes(normalized)\n ? (normalized as KnownItemFieldType)\n : null;\n}\n\n/** Suggest a known field type for a typo'd declaration (e.g. `\"strnig\"` -> `\"string\"`), using the shared OSA Damerau–Levenshtein helper so adjacent transpositions count as a single edit. Returns the first canonical type within the proportional edit budget (in declaration order — the kinds are distinct enough that at most one matches), or `null` when nothing is close enough. */\nexport function suggestKnownItemFieldType(\n value: string,\n): KnownItemFieldType | null {\n const normalized = value.trim().toLowerCase();\n if (normalized.length === 0) {\n return null;\n }\n const limit = Math.max(1, Math.floor(normalized.length * 0.34));\n for (const candidate of KNOWN_ITEM_FIELD_TYPES) {\n if (levenshteinDistanceWithinLimit(normalized, candidate, limit) !== null) {\n return candidate;\n }\n }\n return null;\n}\n","/**\n * @module core/extensions/version-compat\n *\n * Single source of truth for extension-manifest version-bound compatibility.\n *\n * An extension manifest may declare an inclusive `pm_min_version` lower bound and\n * an inclusive `pm_max_version` upper bound. At load time the\n * {@link ../extensions/loader.js | loader} compares them against the running pm\n * CLI version and skips (or warns about) an extension that falls outside the\n * supported window. The comparison and the per-bound status semantics live here\n * so the runtime loader and the author-time SDK helper\n * (`checkExtensionManifestCompatibility`) share one implementation and can never\n * drift — the same \"agrees with the loader by construction\" guarantee the\n * declarative authoring helpers (`describeExtensionBlueprint`,\n * `deriveExtensionCapabilities`) already provide.\n *\n * The functions here are pure: they take an already-resolved current version\n * (the loader resolves it from `package.json`; the SDK caller supplies a target\n * version) and return structured outcomes. Warning-string formatting and\n * version resolution stay with the loader; finding/message presentation stays\n * with the SDK.\n */\nimport type { PmMaxVersionExceededMode } from \"./extension-types.js\";\n\n/** The two inclusive manifest version bounds pm evaluates at load time. */\nexport type PmVersionBoundKind = \"pm_min_version\" | \"pm_max_version\";\n\n/**\n * The outcome of evaluating a single manifest version bound against a pm version.\n *\n * - `absent`: the bound is not declared — nothing to enforce.\n * - `ok`: the bound is declared and satisfied by the current version.\n * - `invalid`: the declared bound is malformed (unparseable, or a range prefix on\n * `pm_max_version`); the loader treats the extension as incompatible and skips it.\n * - `unchecked`: the bound is well-formed but cannot be compared against the\n * current version (the current version is unknown or not comparable); the\n * extension still loads, with an advisory warning.\n * - `unmet`: the current version is older than the inclusive `pm_min_version`\n * lower bound; the loader skips the extension (only emitted for `pm_min_version`).\n * - `exceeded`: the current version is newer than the inclusive `pm_max_version`\n * upper bound and the exceeded mode is `block`; the loader skips the extension\n * (only emitted for `pm_max_version`).\n * - `exceeded_warn`: the current version is newer than `pm_max_version` but the\n * exceeded mode is `warn`, so the extension loads with an advisory warning\n * (only emitted for `pm_max_version`).\n */\nexport type PmVersionBoundStatus =\n | \"absent\"\n | \"ok\"\n | \"invalid\"\n | \"unchecked\"\n | \"unmet\"\n | \"exceeded\"\n | \"exceeded_warn\";\n\n/** The structured result of evaluating one manifest version bound, consumed by the loader (to format its `extension_pm_*_version_*` warning strings) and the SDK (to build author-time compatibility findings). */\nexport interface PmVersionBoundEvaluation {\n /** Which bound this evaluation describes. */\n kind: PmVersionBoundKind;\n /** The classified outcome of comparing the bound against the current version. */\n status: PmVersionBoundStatus;\n /** Whether the bound permits the extension to load (`false` only for `invalid`/`unmet`/`exceeded`). */\n allowed: boolean;\n /** The declared bound value, verbatim; the empty string when the bound is absent. */\n required: string;\n /** The current version compared against, or `null` when it could not be resolved. */\n current: string | null;\n}\n\nfunction formatVersionBoundValue(value: unknown): string {\n return typeof value === \"string\" ? value : String(value);\n}\n\n/**\n * Parse a comparable release string into numeric segments, or `null` when it is\n * not an interpretable dotted-numeric version.\n *\n * Leniently strips a leading inclusive-minimum `>=` and an optional `v` prefix\n * (so `engines.pm`-style `\">=2026.5.31\"` and `\"v1.2.3\"` both parse), then drops\n * any build/pre-release suffix and keeps the leading dotted-numeric release.\n */\nexport function parseComparableVersion(value: string): number[] | null {\n const normalized = value\n .trim()\n .replace(/^>=\\s*/, \"\")\n .replace(/^v/i, \"\");\n const release = normalized.split(/[+-]/, 1)[0];\n if (!/^\\d+(?:[.-]\\d+)*$/.test(release)) {\n return null;\n }\n return release.split(/[.-]/).map((part) => Number(part));\n}\n\n/**\n * Compare two comparable version strings segment by segment.\n *\n * Returns `1` when `currentVersion` is greater, `-1` when it is smaller, `0` when\n * equal, and `null` when either side is not an interpretable version (so callers\n * can classify the comparison as `unchecked`). Missing trailing segments are\n * treated as `0`, so `1.2` and `1.2.0` compare equal.\n */\nexport function compareComparableVersions(\n currentVersion: string,\n otherVersion: string,\n): number | null {\n const currentParts = parseComparableVersion(currentVersion);\n const otherParts = parseComparableVersion(otherVersion);\n if (!currentParts || !otherParts) {\n return null;\n }\n const width = Math.max(currentParts.length, otherParts.length);\n for (let index = 0; index < width; index += 1) {\n const current = currentParts[index] ?? 0;\n const other = otherParts[index] ?? 0;\n if (current > other) {\n return 1;\n }\n if (current < other) {\n return -1;\n }\n }\n return 0;\n}\n\n/**\n * Evaluate a manifest `pm_min_version` inclusive lower bound against the current\n * pm version.\n *\n * An omitted bound is `absent`; a blank, non-string, or unparseable bound is\n * `invalid`; an unknown or incomparable current version is `unchecked`; a current\n * version below the bound is `unmet`; otherwise the bound is satisfied (`ok`).\n * `currentVersion` is `null` when the loader could not resolve the running CLI\n * version.\n */\nexport function evaluatePmMinVersionBound(\n required: unknown,\n currentVersion: string | null,\n): PmVersionBoundEvaluation {\n if (required === undefined || required === null) {\n return {\n kind: \"pm_min_version\",\n status: \"absent\",\n allowed: true,\n required: \"\",\n current: currentVersion,\n };\n }\n const declared = formatVersionBoundValue(required);\n if (typeof required !== \"string\" || declared.trim().length === 0) {\n return {\n kind: \"pm_min_version\",\n status: \"invalid\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n if (!parseComparableVersion(declared)) {\n return {\n kind: \"pm_min_version\",\n status: \"invalid\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n if (currentVersion === null) {\n return {\n kind: \"pm_min_version\",\n status: \"unchecked\",\n allowed: true,\n required: declared,\n current: null,\n };\n }\n const comparison = compareComparableVersions(currentVersion, declared);\n if (comparison === null) {\n return {\n kind: \"pm_min_version\",\n status: \"unchecked\",\n allowed: true,\n required: declared,\n current: currentVersion,\n };\n }\n if (comparison < 0) {\n return {\n kind: \"pm_min_version\",\n status: \"unmet\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n return {\n kind: \"pm_min_version\",\n status: \"ok\",\n allowed: true,\n required: declared,\n current: currentVersion,\n };\n}\n\n/**\n * Evaluate a manifest `pm_max_version` inclusive upper bound against the current\n * pm version.\n *\n * An omitted bound is `absent`. A blank or non-string bound is `invalid`. The\n * upper bound must be an exact version: a range prefix (`<`/`>`/`=`/`~`/`^`) is\n * rejected as `invalid`, because\n * {@link parseComparableVersion} leniently strips a leading `>=` for\n * `engines.pm` min-version compatibility and would otherwise turn a range-like\n * `\">=2026.6.1\"` into an inclusive max and wrongly block newer CLIs. An\n * unparseable bound is `invalid`; an unknown or incomparable current version is\n * `unchecked`; a current version above the bound is `exceeded` (or\n * `exceeded_warn` when `exceededMode` is `warn`, so the extension still loads\n * during a controlled upgrade window); otherwise the bound is satisfied (`ok`).\n */\nexport function evaluatePmMaxVersionBound(\n required: unknown,\n currentVersion: string | null,\n exceededMode: PmMaxVersionExceededMode,\n): PmVersionBoundEvaluation {\n if (required === undefined || required === null) {\n return {\n kind: \"pm_max_version\",\n status: \"absent\",\n allowed: true,\n required: \"\",\n current: currentVersion,\n };\n }\n const declared = formatVersionBoundValue(required);\n if (typeof required !== \"string\" || declared.trim().length === 0) {\n return {\n kind: \"pm_max_version\",\n status: \"invalid\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n if (/^[<>=~^]/.test(declared.trim()) || !parseComparableVersion(declared)) {\n return {\n kind: \"pm_max_version\",\n status: \"invalid\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n if (currentVersion === null) {\n return {\n kind: \"pm_max_version\",\n status: \"unchecked\",\n allowed: true,\n required: declared,\n current: null,\n };\n }\n const comparison = compareComparableVersions(currentVersion, declared);\n if (comparison === null) {\n return {\n kind: \"pm_max_version\",\n status: \"unchecked\",\n allowed: true,\n required: declared,\n current: currentVersion,\n };\n }\n if (comparison > 0) {\n if (exceededMode === \"warn\") {\n return {\n kind: \"pm_max_version\",\n status: \"exceeded_warn\",\n allowed: true,\n required: declared,\n current: currentVersion,\n };\n }\n return {\n kind: \"pm_max_version\",\n status: \"exceeded\",\n allowed: false,\n required: declared,\n current: currentVersion,\n };\n }\n return {\n kind: \"pm_max_version\",\n status: \"ok\",\n allowed: true,\n required: declared,\n current: currentVersion,\n };\n}\n","/**\n * @module core/extensions/extension-policy\n *\n * Implements extension runtime contracts and governance for Extension Policy.\n */\nimport {\n KNOWN_EXTENSION_POLICY_MODES,\n KNOWN_EXTENSION_POLICY_SURFACES,\n KNOWN_EXTENSION_SANDBOX_PROFILES,\n KNOWN_EXTENSION_TRUST_MODES,\n KNOWN_PM_MAX_VERSION_EXCEEDED_MODES,\n type ExtensionCapability,\n type ExtensionGovernancePolicy,\n type ExtensionLayer,\n type ExtensionPolicyMode,\n type ExtensionPolicyOverride,\n type ExtensionPolicySurface,\n type ExtensionSandboxProfile,\n type ExtensionTrustMode,\n type PmMaxVersionExceededMode,\n type PmMaxVersionExceededModeSetting,\n} from \"./extension-types.js\";\nimport { isKnownExtensionCapability } from \"./extension-capability-aliases.js\";\nimport { normalizeCommandName } from \"./extension-runtime-helpers.js\";\nimport type { PmSettings } from \"../../types/index.js\";\n\ninterface NormalizedExtensionPolicyOverride {\n name: string;\n disabled: boolean;\n requireTrusted: boolean;\n requireProvenance: boolean;\n sandboxProfile?: ExtensionSandboxProfile;\n allowedCapabilities: Set<string>;\n blockedCapabilities: Set<string>;\n allowedSurfaces: Set<string>;\n blockedSurfaces: Set<string>;\n allowedCommands: Set<string>;\n blockedCommands: Set<string>;\n allowedActions: Set<string>;\n blockedActions: Set<string>;\n allowedServices: Set<string>;\n blockedServices: Set<string>;\n}\n\n/** Concrete per-layer resolution of `pm_max_version_exceeded_mode` (default: block). */\nexport interface NormalizedPmMaxVersionExceededMode {\n /** Value that configures or reports global for this contract. */\n global: PmMaxVersionExceededMode;\n /** Value that configures or reports project for this contract. */\n project: PmMaxVersionExceededMode;\n}\n\n/** Documents the normalized extension policy payload exchanged by command, SDK, and package integrations. */\nexport interface NormalizedExtensionPolicy {\n /** Value that configures or reports mode for this contract. */\n mode: ExtensionPolicyMode;\n /** Strategy used to control trust behavior. */\n trustMode: ExtensionTrustMode;\n /** Strategy used to control pm max version exceeded behavior. */\n pmMaxVersionExceededMode: NormalizedPmMaxVersionExceededMode;\n /** Value that configures or reports require provenance for this contract. */\n requireProvenance: boolean;\n /** Value that configures or reports trusted extensions for this contract. */\n trustedExtensions: Set<string>;\n /** Fallback sandbox profile used when callers do not provide an override. */\n defaultSandboxProfile: ExtensionSandboxProfile;\n /** Value that configures or reports allowed extensions for this contract. */\n allowedExtensions: Set<string>;\n /** Value that configures or reports blocked extensions for this contract. */\n blockedExtensions: Set<string>;\n /** Value that configures or reports allowed capabilities for this contract. */\n allowedCapabilities: Set<string>;\n /** Value that configures or reports blocked capabilities for this contract. */\n blockedCapabilities: Set<string>;\n /** Value that configures or reports allowed surfaces for this contract. */\n allowedSurfaces: Set<string>;\n /** Value that configures or reports blocked surfaces for this contract. */\n blockedSurfaces: Set<string>;\n /** Value that configures or reports allowed commands for this contract. */\n allowedCommands: Set<string>;\n /** Value that configures or reports blocked commands for this contract. */\n blockedCommands: Set<string>;\n /** Value that configures or reports allowed actions for this contract. */\n allowedActions: Set<string>;\n /** Value that configures or reports blocked actions for this contract. */\n blockedActions: Set<string>;\n /** Value that configures or reports allowed services for this contract. */\n allowedServices: Set<string>;\n /** Value that configures or reports blocked services for this contract. */\n blockedServices: Set<string>;\n /** Value that configures or reports overrides by name for this contract. */\n overridesByName: Map<string, NormalizedExtensionPolicyOverride>;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n}\n\n/** Documents the policy extension ref payload exchanged by command, SDK, and package integrations. */\nexport interface PolicyExtensionRef {\n /** Value that configures or reports layer for this contract. */\n layer: ExtensionLayer;\n /** Value that configures or reports name for this contract. */\n name: string;\n /** Value that configures or reports trusted for this contract. */\n trusted?: boolean;\n /** Value that configures or reports provenance verified for this contract. */\n provenanceVerified?: boolean;\n /** Value that configures or reports sandbox profile for this contract. */\n sandboxProfile?: ExtensionSandboxProfile;\n /** Value that configures or reports permissions for this contract. */\n permissions?: Record<string, boolean | undefined>;\n}\n\nfunction normalizePolicyName(value: string | undefined): string {\n if (typeof value !== \"string\") {\n return \"\";\n }\n return value.trim().toLowerCase();\n}\n\nfunction normalizePolicyStringSet(\n values: readonly string[] | undefined,\n): Set<string> {\n return new Set(\n (values ?? [])\n .map((value) => value.trim().toLowerCase())\n .filter((value) => value.length > 0),\n );\n}\n\nfunction normalizePolicySurfaceToken(value: string): string {\n const normalized = value.trim().toLowerCase();\n if (normalized.length === 0) {\n return \"\";\n }\n const segments = normalized\n .split(/[.:/]/)\n .map((segment) => segment.replace(/[\\s_-]+/g, \"\"))\n .filter((segment) => segment.length > 0);\n if (segments.length === 0) {\n return \"\";\n }\n if (segments.length === 1) {\n return segments[0];\n }\n return `${segments[0]}.${segments.slice(1).join(\"\")}`;\n}\n\nfunction normalizePolicySurfaceSet(\n values: readonly string[] | undefined,\n): Set<string> {\n return new Set(\n (values ?? [])\n .map((value) => normalizePolicySurfaceToken(value))\n .filter((value) => value.length > 0),\n );\n}\n\nfunction normalizePolicyMode(value: string | undefined): ExtensionPolicyMode {\n const normalized = normalizePolicyName(value);\n if (\n (KNOWN_EXTENSION_POLICY_MODES as readonly string[]).includes(normalized)\n ) {\n return normalized as ExtensionPolicyMode;\n }\n return \"off\";\n}\n\nfunction normalizePolicyTrustMode(\n value: string | undefined,\n): ExtensionTrustMode {\n const normalized = normalizePolicyName(value);\n if ((KNOWN_EXTENSION_TRUST_MODES as readonly string[]).includes(normalized)) {\n return normalized as ExtensionTrustMode;\n }\n return \"off\";\n}\n\n/** Implements normalize policy sandbox profile for the public runtime surface of this module. */\nexport function normalizePolicySandboxProfile(\n value: string | undefined,\n): ExtensionSandboxProfile {\n const normalized = normalizePolicyName(value);\n if (\n (KNOWN_EXTENSION_SANDBOX_PROFILES as readonly string[]).includes(normalized)\n ) {\n return normalized as ExtensionSandboxProfile;\n }\n return \"none\";\n}\n\nfunction normalizePmMaxVersionExceededModeValue(\n value: unknown,\n): PmMaxVersionExceededMode | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim().toLowerCase();\n return (KNOWN_PM_MAX_VERSION_EXCEEDED_MODES as readonly string[]).includes(\n normalized,\n )\n ? (normalized as PmMaxVersionExceededMode)\n : undefined;\n}\n\n/** Resolve `extensions.policy.pm_max_version_exceeded_mode` to a concrete per-layer mode map. Accepts a single mode string (applied to both layers) or a `{ global?, project? }` override map; anything unset or unknown defaults to the safe `\"block\"`. */\nexport function normalizePmMaxVersionExceededMode(\n value: PmMaxVersionExceededModeSetting | undefined,\n): NormalizedPmMaxVersionExceededMode {\n if (typeof value === \"string\") {\n const mode = normalizePmMaxVersionExceededModeValue(value) ?? \"block\";\n return { global: mode, project: mode };\n }\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n return {\n global: normalizePmMaxVersionExceededModeValue(value.global) ?? \"block\",\n project: normalizePmMaxVersionExceededModeValue(value.project) ?? \"block\",\n };\n }\n return { global: \"block\", project: \"block\" };\n}\n\nfunction serializePmMaxVersionExceededMode(\n mode: NormalizedPmMaxVersionExceededMode,\n): PmMaxVersionExceededModeSetting {\n return mode.global === mode.project\n ? mode.global\n : { global: mode.global, project: mode.project };\n}\n\nfunction toSortedList(values: Iterable<string>): string[] {\n return [...new Set(values)].sort((left, right) => left.localeCompare(right));\n}\n\nfunction buildExtensionPolicyOverride(\n rawOverride: ExtensionPolicyOverride,\n): { name: string; normalized: NormalizedExtensionPolicyOverride } | null {\n const name = normalizePolicyName(rawOverride.name);\n if (name.length === 0) {\n return null;\n }\n return {\n name,\n normalized: {\n name,\n disabled: rawOverride.disabled === true,\n requireTrusted: rawOverride.require_trusted === true,\n requireProvenance: rawOverride.require_provenance === true,\n sandboxProfile:\n rawOverride.sandbox_profile !== undefined\n ? normalizePolicySandboxProfile(rawOverride.sandbox_profile)\n : undefined,\n allowedCapabilities: normalizePolicyStringSet(\n rawOverride.allowed_capabilities,\n ),\n blockedCapabilities: normalizePolicyStringSet(\n rawOverride.blocked_capabilities,\n ),\n allowedSurfaces: normalizePolicySurfaceSet(rawOverride.allowed_surfaces),\n blockedSurfaces: normalizePolicySurfaceSet(rawOverride.blocked_surfaces),\n allowedCommands: normalizePolicyStringSet(rawOverride.allowed_commands),\n blockedCommands: normalizePolicyStringSet(rawOverride.blocked_commands),\n allowedActions: normalizePolicyStringSet(rawOverride.allowed_actions),\n blockedActions: normalizePolicyStringSet(rawOverride.blocked_actions),\n allowedServices: normalizePolicyStringSet(rawOverride.allowed_services),\n blockedServices: normalizePolicyStringSet(rawOverride.blocked_services),\n },\n };\n}\n\nfunction collectExtensionPolicyOverrides(\n rawOverrides: readonly ExtensionPolicyOverride[] | undefined,\n): Map<string, NormalizedExtensionPolicyOverride> {\n const overridesByName = new Map<string, NormalizedExtensionPolicyOverride>();\n for (const rawOverride of rawOverrides ?? []) {\n const built = buildExtensionPolicyOverride(rawOverride);\n if (built) {\n overridesByName.set(built.name, built.normalized);\n }\n }\n return overridesByName;\n}\n\n/**\n * Collect the deduplicated, alphabetically-sorted `extension_policy_unknown_*`\n * warnings for a normalized policy: every allow/block capability and surface\n * token — at the top level and inside each per-extension override — that is not a\n * recognized {@link ExtensionCapability} or known policy surface. Overrides are\n * walked in name order and the final list is re-sorted, so the result is stable\n * regardless of insertion order.\n */\nfunction collectExtensionPolicyWarnings(normalized: {\n allowedCapabilities: Set<string>;\n blockedCapabilities: Set<string>;\n allowedSurfaces: Set<string>;\n blockedSurfaces: Set<string>;\n overridesByName: Map<string, NormalizedExtensionPolicyOverride>;\n}): string[] {\n const warnings: string[] = [];\n const sortedOverrides = [...normalized.overridesByName.values()].sort(\n (left, right) => left.name.localeCompare(right.name),\n );\n for (const capability of toSortedList([\n ...normalized.allowedCapabilities,\n ...normalized.blockedCapabilities,\n ])) {\n if (!isKnownExtensionCapability(capability)) {\n warnings.push(`extension_policy_unknown_capability:${capability}`);\n }\n }\n for (const override of sortedOverrides) {\n for (const capability of toSortedList([\n ...override.allowedCapabilities,\n ...override.blockedCapabilities,\n ])) {\n if (!isKnownExtensionCapability(capability)) {\n warnings.push(\n `extension_policy_unknown_capability:${override.name}:${capability}`,\n );\n }\n }\n }\n const knownSurfaces = new Set<string>(KNOWN_EXTENSION_POLICY_SURFACES);\n for (const surface of toSortedList([\n ...normalized.allowedSurfaces,\n ...normalized.blockedSurfaces,\n ])) {\n if (!knownSurfaces.has(surface)) {\n warnings.push(`extension_policy_unknown_surface:${surface}`);\n }\n }\n for (const override of sortedOverrides) {\n for (const surface of toSortedList([\n ...override.allowedSurfaces,\n ...override.blockedSurfaces,\n ])) {\n if (!knownSurfaces.has(surface)) {\n warnings.push(\n `extension_policy_unknown_surface:${override.name}:${surface}`,\n );\n }\n }\n }\n return [...new Set(warnings)].sort((left, right) =>\n left.localeCompare(right),\n );\n}\n\n/**\n * Normalize the raw `extensions.policy` settings block into the canonical\n * {@link NormalizedExtensionPolicy} used across loading, registration, and the\n * doctor surface: modes/trust/sandbox coerced to known values, every allow/block\n * list lower-cased and de-duplicated into a set, per-extension overrides indexed by\n * name, and unknown-capability/surface tokens surfaced as warnings. A missing\n * policy block resolves to the all-defaults policy (mode/trust `off`).\n */\nexport function normalizeExtensionPolicy(\n settings: PmSettings,\n): NormalizedExtensionPolicy {\n const policy: Partial<ExtensionGovernancePolicy> =\n (settings.extensions?.policy as ExtensionGovernancePolicy | undefined) ??\n {};\n const allowedCapabilities = normalizePolicyStringSet(\n policy.allowed_capabilities,\n );\n const blockedCapabilities = normalizePolicyStringSet(\n policy.blocked_capabilities,\n );\n const allowedSurfaces = normalizePolicySurfaceSet(policy.allowed_surfaces);\n const blockedSurfaces = normalizePolicySurfaceSet(policy.blocked_surfaces);\n const overridesByName = collectExtensionPolicyOverrides(\n policy.extension_overrides,\n );\n return {\n mode: normalizePolicyMode(policy.mode),\n trustMode: normalizePolicyTrustMode(policy.trust_mode),\n pmMaxVersionExceededMode: normalizePmMaxVersionExceededMode(\n policy.pm_max_version_exceeded_mode,\n ),\n requireProvenance: policy.require_provenance === true,\n trustedExtensions: normalizePolicyStringSet(policy.trusted_extensions),\n defaultSandboxProfile: normalizePolicySandboxProfile(\n policy.default_sandbox_profile,\n ),\n allowedExtensions: normalizePolicyStringSet(policy.allowed_extensions),\n blockedExtensions: normalizePolicyStringSet(policy.blocked_extensions),\n allowedCapabilities,\n blockedCapabilities,\n allowedSurfaces,\n blockedSurfaces,\n allowedCommands: normalizePolicyStringSet(policy.allowed_commands),\n blockedCommands: normalizePolicyStringSet(policy.blocked_commands),\n allowedActions: normalizePolicyStringSet(policy.allowed_actions),\n blockedActions: normalizePolicyStringSet(policy.blocked_actions),\n allowedServices: normalizePolicyStringSet(policy.allowed_services),\n blockedServices: normalizePolicyStringSet(policy.blocked_services),\n overridesByName,\n warnings: collectExtensionPolicyWarnings({\n allowedCapabilities,\n blockedCapabilities,\n allowedSurfaces,\n blockedSurfaces,\n overridesByName,\n }),\n };\n}\n\n/** Implements serialize extension policy for the public runtime surface of this module. */\nexport function serializeExtensionPolicy(\n policy: NormalizedExtensionPolicy,\n): ExtensionGovernancePolicy {\n const overrides = [...policy.overridesByName.values()]\n .sort((left, right) => left.name.localeCompare(right.name))\n .map((override) => ({\n name: override.name,\n ...(override.disabled ? { disabled: true } : {}),\n ...(override.requireTrusted ? { require_trusted: true } : {}),\n ...(override.requireProvenance ? { require_provenance: true } : {}),\n ...(override.sandboxProfile\n ? { sandbox_profile: override.sandboxProfile }\n : {}),\n ...(override.allowedCapabilities.size > 0\n ? { allowed_capabilities: toSortedList(override.allowedCapabilities) }\n : {}),\n ...(override.blockedCapabilities.size > 0\n ? { blocked_capabilities: toSortedList(override.blockedCapabilities) }\n : {}),\n ...(override.allowedSurfaces.size > 0\n ? { allowed_surfaces: toSortedList(override.allowedSurfaces) }\n : {}),\n ...(override.blockedSurfaces.size > 0\n ? { blocked_surfaces: toSortedList(override.blockedSurfaces) }\n : {}),\n ...(override.allowedCommands.size > 0\n ? { allowed_commands: toSortedList(override.allowedCommands) }\n : {}),\n ...(override.blockedCommands.size > 0\n ? { blocked_commands: toSortedList(override.blockedCommands) }\n : {}),\n ...(override.allowedActions.size > 0\n ? { allowed_actions: toSortedList(override.allowedActions) }\n : {}),\n ...(override.blockedActions.size > 0\n ? { blocked_actions: toSortedList(override.blockedActions) }\n : {}),\n ...(override.allowedServices.size > 0\n ? { allowed_services: toSortedList(override.allowedServices) }\n : {}),\n ...(override.blockedServices.size > 0\n ? { blocked_services: toSortedList(override.blockedServices) }\n : {}),\n }));\n return {\n mode: policy.mode,\n trust_mode: policy.trustMode,\n pm_max_version_exceeded_mode: serializePmMaxVersionExceededMode(\n policy.pmMaxVersionExceededMode,\n ),\n require_provenance: policy.requireProvenance,\n trusted_extensions: toSortedList(policy.trustedExtensions),\n default_sandbox_profile: policy.defaultSandboxProfile,\n allowed_extensions: toSortedList(policy.allowedExtensions),\n blocked_extensions: toSortedList(policy.blockedExtensions),\n allowed_capabilities: toSortedList(policy.allowedCapabilities),\n blocked_capabilities: toSortedList(policy.blockedCapabilities),\n allowed_surfaces: toSortedList(policy.allowedSurfaces),\n blocked_surfaces: toSortedList(policy.blockedSurfaces),\n allowed_commands: toSortedList(policy.allowedCommands),\n blocked_commands: toSortedList(policy.blockedCommands),\n allowed_actions: toSortedList(policy.allowedActions),\n blocked_actions: toSortedList(policy.blockedActions),\n allowed_services: toSortedList(policy.allowedServices),\n blocked_services: toSortedList(policy.blockedServices),\n extension_overrides: overrides,\n };\n}\n\n/** Implements hydrate extension policy for the public runtime surface of this module. */\nexport function hydrateExtensionPolicy(\n policy: ExtensionGovernancePolicy,\n): NormalizedExtensionPolicy {\n const overridesByName = collectExtensionPolicyOverrides(\n policy.extension_overrides,\n );\n return {\n mode: normalizePolicyMode(policy.mode),\n trustMode: normalizePolicyTrustMode(policy.trust_mode),\n pmMaxVersionExceededMode: normalizePmMaxVersionExceededMode(\n policy.pm_max_version_exceeded_mode,\n ),\n requireProvenance: policy.require_provenance === true,\n trustedExtensions: normalizePolicyStringSet(policy.trusted_extensions),\n defaultSandboxProfile: normalizePolicySandboxProfile(\n policy.default_sandbox_profile,\n ),\n allowedExtensions: normalizePolicyStringSet(policy.allowed_extensions),\n blockedExtensions: normalizePolicyStringSet(policy.blocked_extensions),\n allowedCapabilities: normalizePolicyStringSet(policy.allowed_capabilities),\n blockedCapabilities: normalizePolicyStringSet(policy.blocked_capabilities),\n allowedSurfaces: normalizePolicySurfaceSet(policy.allowed_surfaces),\n blockedSurfaces: normalizePolicySurfaceSet(policy.blocked_surfaces),\n allowedCommands: normalizePolicyStringSet(policy.allowed_commands),\n blockedCommands: normalizePolicyStringSet(policy.blocked_commands),\n allowedActions: normalizePolicyStringSet(policy.allowed_actions),\n blockedActions: normalizePolicyStringSet(policy.blocked_actions),\n allowedServices: normalizePolicyStringSet(policy.allowed_services),\n blockedServices: normalizePolicyStringSet(policy.blocked_services),\n overridesByName,\n warnings: [],\n };\n}\n\nfunction resolvePolicyOverride(\n policy: NormalizedExtensionPolicy,\n extensionName: string,\n): NormalizedExtensionPolicyOverride | null {\n return policy.overridesByName.get(normalizePolicyName(extensionName)) ?? null;\n}\n\nfunction evaluatePolicySet(\n allowed: Set<string>,\n blocked: Set<string>,\n value: string,\n notAllowlistedReason: string,\n blockedReason: string,\n): string | null {\n if (blocked.has(value)) {\n return blockedReason;\n }\n if (allowed.size > 0 && !allowed.has(value)) {\n return notAllowlistedReason;\n }\n return null;\n}\n\nfunction resolvePolicyCapabilityReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n capability: string,\n): string | null {\n const normalizedCapability = capability.trim().toLowerCase();\n const override = resolvePolicyOverride(policy, extension.name);\n const allowed =\n override && override.allowedCapabilities.size > 0\n ? override.allowedCapabilities\n : policy.allowedCapabilities;\n const blocked = new Set<string>([\n ...policy.blockedCapabilities,\n ...(override ? override.blockedCapabilities : []),\n ]);\n return evaluatePolicySet(\n allowed,\n blocked,\n normalizedCapability,\n \"capability_not_allowlisted\",\n \"capability_blocked\",\n );\n}\n\nfunction resolvePolicySurfaceReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n surface: ExtensionPolicySurface,\n): string | null {\n const override = resolvePolicyOverride(policy, extension.name);\n const allowed =\n override && override.allowedSurfaces.size > 0\n ? override.allowedSurfaces\n : policy.allowedSurfaces;\n const blocked = new Set<string>([\n ...policy.blockedSurfaces,\n ...(override ? override.blockedSurfaces : []),\n ]);\n return evaluatePolicySet(\n allowed,\n blocked,\n surface,\n \"surface_not_allowlisted\",\n \"surface_blocked\",\n );\n}\n\nfunction resolvePolicyCommandReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n command: string,\n): string | null {\n const normalizedCommand = normalizeCommandName(command);\n if (normalizedCommand.length === 0) {\n return null;\n }\n const override = resolvePolicyOverride(policy, extension.name);\n const allowed =\n override && override.allowedCommands.size > 0\n ? override.allowedCommands\n : policy.allowedCommands;\n const blocked = new Set<string>([\n ...policy.blockedCommands,\n ...(override ? override.blockedCommands : []),\n ]);\n return evaluatePolicySet(\n allowed,\n blocked,\n normalizedCommand,\n \"command_not_allowlisted\",\n \"command_blocked\",\n );\n}\n\nfunction resolvePolicyActionReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n action: string,\n): string | null {\n const normalizedAction = normalizePolicyName(action).replace(/\\s+/g, \"-\");\n if (normalizedAction.length === 0) {\n return null;\n }\n const override = resolvePolicyOverride(policy, extension.name);\n const allowed =\n override && override.allowedActions.size > 0\n ? override.allowedActions\n : policy.allowedActions;\n const blocked = new Set<string>([\n ...policy.blockedActions,\n ...(override ? override.blockedActions : []),\n ]);\n return evaluatePolicySet(\n allowed,\n blocked,\n normalizedAction,\n \"action_not_allowlisted\",\n \"action_blocked\",\n );\n}\n\nfunction resolvePolicyServiceReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n service: string,\n): string | null {\n const normalizedService = normalizePolicyName(service);\n if (normalizedService.length === 0) {\n return null;\n }\n const override = resolvePolicyOverride(policy, extension.name);\n const allowed =\n override && override.allowedServices.size > 0\n ? override.allowedServices\n : policy.allowedServices;\n const blocked = new Set<string>([\n ...policy.blockedServices,\n ...(override ? override.blockedServices : []),\n ]);\n return evaluatePolicySet(\n allowed,\n blocked,\n normalizedService,\n \"service_not_allowlisted\",\n \"service_blocked\",\n );\n}\n\nfunction resolvePolicyExtensionReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n): string | null {\n const name = normalizePolicyName(extension.name);\n const override = resolvePolicyOverride(policy, extension.name);\n if (override?.disabled === true) {\n return \"extension_override_disabled\";\n }\n return evaluatePolicySet(\n policy.allowedExtensions,\n policy.blockedExtensions,\n name,\n \"extension_not_allowlisted\",\n \"extension_blocked\",\n );\n}\n\nfunction resolvePolicyTrustReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n): string | null {\n if (policy.trustMode === \"off\") {\n return null;\n }\n const override = resolvePolicyOverride(policy, extension.name);\n const name = normalizePolicyName(extension.name);\n const trusted = extension.trusted === true;\n const provenanceVerified = extension.provenanceVerified === true;\n\n if (\n policy.trustedExtensions.size > 0 &&\n !policy.trustedExtensions.has(name)\n ) {\n return \"extension_not_trusted\";\n }\n if (\n (override?.requireTrusted === true ||\n policy.trustMode === \"warn\" ||\n policy.trustMode === \"enforce\") &&\n !trusted\n ) {\n return \"extension_untrusted\";\n }\n if (\n (policy.requireProvenance || override?.requireProvenance === true) &&\n !provenanceVerified\n ) {\n return \"provenance_missing_or_unverified\";\n }\n return null;\n}\n\nfunction resolvePolicySandboxReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n): string | null {\n if (policy.mode === \"off\") {\n return null;\n }\n const override = resolvePolicyOverride(policy, extension.name);\n const profile =\n override?.sandboxProfile ??\n extension.sandboxProfile ??\n policy.defaultSandboxProfile;\n if (profile === \"none\") {\n return null;\n }\n const permissions = extension.permissions;\n if (!permissions) {\n return \"sandbox_permissions_missing\";\n }\n\n const hasPermission = (name: keyof typeof permissions): boolean =>\n permissions[name] === true;\n if (profile === \"restricted\") {\n if (hasPermission(\"process_spawn\")) {\n return \"sandbox_restricted_disallows_process_spawn\";\n }\n if (hasPermission(\"env_write\")) {\n return \"sandbox_restricted_disallows_env_write\";\n }\n return null;\n }\n\n // Remaining profile branch is strict (none/restricted returned above).\n if (hasPermission(\"process_spawn\")) {\n return \"sandbox_strict_disallows_process_spawn\";\n }\n if (hasPermission(\"network\")) {\n return \"sandbox_strict_disallows_network\";\n }\n if (hasPermission(\"fs_write\")) {\n return \"sandbox_strict_disallows_fs_write\";\n }\n if (hasPermission(\"env_write\")) {\n return \"sandbox_strict_disallows_env_write\";\n }\n return null;\n}\n\nfunction buildPolicyWarning(\n mode: \"blocked\" | \"violation\",\n scope: \"extension\" | \"capability\" | \"registration\" | \"trust\",\n extension: PolicyExtensionRef,\n reason: string,\n details: Record<string, string> = {},\n): string {\n const tokens = Object.entries(details)\n .sort((left, right) => left[0].localeCompare(right[0]))\n .map(([key, value]) => `${key}=${value}`)\n .join(\":\");\n const suffix = tokens.length > 0 ? `:${tokens}` : \"\";\n return `extension_policy_${mode}_${scope}:${extension.layer}:${extension.name}:reason=${reason}${suffix}`;\n}\n\n/** Evaluate the layer-level governance policy for one extension by combining the extension allow/block decision, the trust-mode decision, and the sandbox-profile decision. Reasons are weighed in extension → trust → sandbox order: the first reason whose governing mode is `enforce` blocks the extension; otherwise the first whose mode is `warn` surfaces a non-blocking violation warning; otherwise the extension is allowed. The all-`off` short-circuit skips reason resolution entirely. */\nexport function evaluateExtensionPolicyForExtension(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n): { allowed: boolean; warning: string | null } {\n if (policy.mode === \"off\" && policy.trustMode === \"off\") {\n return { allowed: true, warning: null };\n }\n const violations: Array<{\n reason: string;\n scope: \"extension\" | \"trust\";\n mode: ExtensionPolicyMode | ExtensionTrustMode;\n }> = [];\n const reason = resolvePolicyExtensionReason(policy, extension);\n if (reason) {\n violations.push({ reason, scope: \"extension\", mode: policy.mode });\n }\n const trustReason = resolvePolicyTrustReason(policy, extension);\n if (trustReason) {\n violations.push({\n reason: trustReason,\n scope: \"trust\",\n mode: policy.trustMode,\n });\n }\n const sandboxReason = resolvePolicySandboxReason(policy, extension);\n if (sandboxReason) {\n violations.push({\n reason: sandboxReason,\n scope: \"extension\",\n mode: policy.mode,\n });\n }\n const enforced = violations.find((violation) => violation.mode === \"enforce\");\n if (enforced) {\n return {\n allowed: false,\n warning: buildPolicyWarning(\n \"blocked\",\n enforced.scope,\n extension,\n enforced.reason,\n ),\n };\n }\n const warned = violations.find((violation) => violation.mode === \"warn\");\n if (warned) {\n return {\n allowed: true,\n warning: buildPolicyWarning(\n \"violation\",\n warned.scope,\n extension,\n warned.reason,\n ),\n };\n }\n return { allowed: true, warning: null };\n}\n\n/** Implements evaluate extension policy for capability for the public runtime surface of this module. */\nexport function evaluateExtensionPolicyForCapability(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n capability: string,\n): { allowed: boolean; warning: string | null } {\n if (policy.mode === \"off\") {\n return { allowed: true, warning: null };\n }\n const reason = resolvePolicyCapabilityReason(policy, extension, capability);\n if (!reason) {\n return { allowed: true, warning: null };\n }\n return {\n allowed: policy.mode === \"warn\",\n warning: buildPolicyWarning(\n policy.mode === \"warn\" ? \"violation\" : \"blocked\",\n \"capability\",\n extension,\n reason,\n { capability: capability.trim().toLowerCase() },\n ),\n };\n}\n\n/** Optional command/action/service identifiers carried by a surface registration. */\ninterface RegistrationPolicyDetails {\n command?: string;\n action?: string;\n service?: string;\n}\n\n/** Resolve the first applicable registration-policy reason for a surface registration, weighed in capability → surface → command → action → service precedence. Returns `null` when the registration violates no allow/block rule. */\nfunction resolveRegistrationPolicyReason(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n surface: ExtensionPolicySurface,\n capability: ExtensionCapability | undefined,\n detail: RegistrationPolicyDetails,\n): string | null {\n const capabilityReason =\n typeof capability === \"string\"\n ? resolvePolicyCapabilityReason(policy, extension, capability)\n : null;\n const surfaceReason = resolvePolicySurfaceReason(policy, extension, surface);\n const commandReason = detail.command\n ? resolvePolicyCommandReason(policy, extension, detail.command)\n : null;\n const actionReason = detail.action\n ? resolvePolicyActionReason(policy, extension, detail.action)\n : null;\n const serviceReason = detail.service\n ? resolvePolicyServiceReason(policy, extension, detail.service)\n : null;\n return (\n capabilityReason ??\n surfaceReason ??\n commandReason ??\n actionReason ??\n serviceReason\n );\n}\n\n/**\n * Build the detail token map attached to a registration-policy warning: the\n * normalized method and surface plus whichever of capability/command/action/service\n * the registration carries. {@link buildPolicyWarning} sorts and joins these into\n * the warning's `key=value` suffix.\n */\nfunction buildRegistrationPolicyWarningDetails(\n method: string,\n surface: ExtensionPolicySurface,\n capability: ExtensionCapability | undefined,\n detail: RegistrationPolicyDetails,\n): Record<string, string> {\n const warningDetails: Record<string, string> = {\n method: normalizePolicyName(method).replace(/\\s+/g, \"_\"),\n surface,\n };\n if (capability) {\n warningDetails.capability = capability;\n }\n if (detail.command) {\n warningDetails.command = normalizeCommandName(detail.command);\n }\n if (detail.action) {\n warningDetails.action = normalizePolicyName(detail.action).replace(\n /\\s+/g,\n \"-\",\n );\n }\n if (detail.service) {\n warningDetails.service = normalizePolicyName(detail.service);\n }\n return warningDetails;\n}\n\n/** Evaluate the governance policy for a single capability/surface registration an extension performs during activation. When `mode` is `off` the registration is always allowed; otherwise the first allow/block reason (capability → surface → command → action → service) blocks the registration under `enforce` or surfaces a non-blocking violation warning under `warn`. */\nexport function evaluateExtensionPolicyForRegistration(\n policy: NormalizedExtensionPolicy,\n extension: PolicyExtensionRef,\n surface: ExtensionPolicySurface,\n method: string,\n capability?: ExtensionCapability,\n details?: {\n command?: string;\n action?: string;\n service?: string;\n },\n): { allowed: boolean; warning: string | null } {\n if (policy.mode === \"off\") {\n return { allowed: true, warning: null };\n }\n const detail = details ?? {};\n const reason = resolveRegistrationPolicyReason(\n policy,\n extension,\n surface,\n capability,\n detail,\n );\n if (!reason) {\n return { allowed: true, warning: null };\n }\n const warning = buildPolicyWarning(\n policy.mode === \"warn\" ? \"violation\" : \"blocked\",\n \"registration\",\n extension,\n reason,\n buildRegistrationPolicyWarningDetails(method, surface, capability, detail),\n );\n return {\n allowed: policy.mode === \"warn\",\n warning,\n };\n}\n","/**\n * @module core/extensions/capability-usage\n *\n * Reconciles the capabilities an extension manifest *declares* against the\n * capabilities it actually *exercises* during activation.\n *\n * The loader already enforces the opposite direction — registering a surface\n * whose capability is absent from `manifest.capabilities` throws an\n * `extension_capability_missing` activation failure. This module closes the\n * least-privilege loop by detecting capabilities a manifest declares but never\n * registers against, so package authors can trim manifests to the minimum\n * grant. Every declared-but-unused capability is an over-broad permission a\n * reviewer would otherwise have to catch by hand.\n */\nimport type {\n ExtensionActivationResult,\n ExtensionCapability,\n ExtensionLayer,\n} from \"./extension-types.js\";\nimport { normalizeKnownExtensionCapability } from \"./extension-capability-aliases.js\";\n\n/**\n * Canonical map from each known extension capability to the human-readable\n * registration surfaces that exercise it.\n *\n * The `satisfies Record<ExtensionCapability, ...>` guard makes this exhaustive\n * at compile time: adding a capability to `KNOWN_EXTENSION_CAPABILITIES`\n * without giving it a registration surface here fails the build, which prevents\n * a capability that has *no* surface from being perpetually flagged as unused.\n */\nexport const EXTENSION_CAPABILITY_REGISTRATION_SURFACES = {\n commands: [\"registerCommand\", \"command override\", \"command handler\"],\n renderers: [\"registerRenderer\"],\n hooks: [\n \"hooks.beforeCommand\",\n \"hooks.afterCommand\",\n \"hooks.onWrite\",\n \"hooks.onRead\",\n \"hooks.onIndex\",\n ],\n schema: [\n \"registerFlags\",\n \"registerItemFields\",\n \"registerItemTypes\",\n \"registerMigration\",\n \"registerProfile\",\n ],\n importers: [\"registerImporter\", \"registerExporter\"],\n search: [\"registerSearchProvider\", \"registerVectorStoreAdapter\"],\n parser: [\"registerParser\"],\n preflight: [\"registerPreflight\"],\n services: [\"registerService\"],\n} as const satisfies Record<ExtensionCapability, readonly string[]>;\n\n/** Per-extension reconciliation of declared versus exercised capabilities. */\nexport interface ExtensionCapabilityUsageReconciliation {\n /** Layer the extension was loaded from (`global` or `project`). */\n layer: ExtensionLayer;\n /** Extension name as it appears in the manifest. */\n name: string;\n /** Known capabilities declared in the manifest, sorted and de-duplicated. */\n declared: ExtensionCapability[];\n /** Known capabilities the extension actually registered against, sorted. */\n used: ExtensionCapability[];\n /** Declared capabilities with no matching registration (least-privilege gap). */\n unused: ExtensionCapability[];\n}\n\n/** Options for {@link collectUsedExtensionCapabilities}. */\nexport interface CollectUsedExtensionCapabilitiesOptions {\n /** Restrict the result to a single extension by name. Names are matched case-insensitively after trimming. Omit to union across every extension in the activation result. */\n extensionName?: string;\n /** Restrict the result to a set of extension names. This preserves the single-name option while allowing package aliases that activate multiple extensions to summarize their combined capability surface. */\n extensionNames?: readonly string[];\n}\n\n// `layer` is a closed enum (`\"global\" | \"project\"`) that never contains a\n// colon, so the first colon always separates the layer from the (possibly\n// colon-bearing) name — making the key collision-proof without serialization.\nconst USAGE_KEY_SEPARATOR = \":\";\n\nfunction usageKey(layer: ExtensionLayer, name: string): string {\n return `${layer}${USAGE_KEY_SEPARATOR}${normalizeExtensionName(name)}`;\n}\n\nfunction usageKeyName(key: string): string {\n return key.slice(key.indexOf(USAGE_KEY_SEPARATOR) + 1);\n}\n\n/**\n * Canonical extension-name normalization (trim + lowercase) used to match an\n * `extensionName` filter against a registration's stored `name`.\n *\n * Activation stores `extension.name` verbatim — the synthetic test-activation\n * path (`activateExtensionForTest`) never trims it — so any helper that filters\n * by extension name must normalize both sides with this function to stay\n * consistent, including {@link ../extensions/activation-summary.js#describeExtensionActivation}.\n */\nexport function normalizeExtensionName(name: string): string {\n return name.trim().toLowerCase();\n}\n\nfunction normalizeDeclaredCapabilities(\n capabilities: readonly string[] | undefined,\n): ExtensionCapability[] {\n if (!Array.isArray(capabilities)) {\n return [];\n }\n const known = new Set<ExtensionCapability>();\n for (const capability of capabilities) {\n // Unknown capabilities are reported by the separate unknown-capability\n // diagnostic; reconciling them here would double-report a typo as \"unused\".\n const normalized = normalizeKnownExtensionCapability(capability);\n if (normalized !== null) {\n known.add(normalized);\n }\n }\n return [...known].sort((left, right) => left.localeCompare(right));\n}\n\nfunction attributeCapabilityUsage(\n activation: ExtensionActivationResult,\n): Map<string, Set<ExtensionCapability>> {\n const usage = new Map<string, Set<ExtensionCapability>>();\n const record = (\n entries: ReadonlyArray<{ layer: ExtensionLayer; name: string }>,\n capability: ExtensionCapability,\n ): void => {\n for (const entry of entries) {\n const key = usageKey(entry.layer, entry.name);\n let exercised = usage.get(key);\n if (exercised === undefined) {\n exercised = new Set<ExtensionCapability>();\n usage.set(key, exercised);\n }\n exercised.add(capability);\n }\n };\n const {\n registrations,\n commands,\n parsers,\n preflight,\n services,\n renderers,\n hooks,\n } = activation;\n record(registrations.commands, \"commands\");\n record(commands.overrides, \"commands\");\n record(commands.handlers, \"commands\");\n record(registrations.flags, \"schema\");\n record(registrations.item_fields, \"schema\");\n record(registrations.item_types, \"schema\");\n record(registrations.migrations, \"schema\");\n record(registrations.profiles, \"schema\");\n record(registrations.importers, \"importers\");\n record(registrations.exporters, \"importers\");\n record(registrations.search_providers, \"search\");\n record(registrations.vector_store_adapters, \"search\");\n record(parsers.overrides, \"parser\");\n record(preflight.overrides, \"preflight\");\n record(services.overrides, \"services\");\n record(renderers.overrides, \"renderers\");\n record(hooks.beforeCommand, \"hooks\");\n record(hooks.afterCommand, \"hooks\");\n record(hooks.onWrite, \"hooks\");\n record(hooks.onRead, \"hooks\");\n record(hooks.onIndex, \"hooks\");\n return usage;\n}\n\n/**\n * Collect the known capabilities exercised across an activation result.\n *\n * Without {@link CollectUsedExtensionCapabilitiesOptions.extensionName} the\n * result unions every extension in the activation; with it, only the matching\n * extension's registrations contribute (across both layers).\n */\nexport function collectUsedExtensionCapabilities(\n activation: ExtensionActivationResult,\n options: CollectUsedExtensionCapabilitiesOptions = {},\n): ExtensionCapability[] {\n const usage = attributeCapabilityUsage(activation);\n const filters = new Set<string>();\n if (options.extensionName !== undefined) {\n filters.add(normalizeExtensionName(options.extensionName));\n }\n for (const name of options.extensionNames ?? []) {\n filters.add(normalizeExtensionName(name));\n }\n const used = new Set<ExtensionCapability>();\n for (const [key, capabilities] of usage) {\n if (filters.size > 0 && !filters.has(usageKeyName(key))) {\n continue;\n }\n for (const capability of capabilities) {\n used.add(capability);\n }\n }\n return [...used].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Reconcile each loaded extension's declared capabilities against what it\n * exercised during activation.\n *\n * Extensions with no known declared capabilities are skipped — there is nothing\n * to reconcile. The returned entries preserve every reconcilable extension even\n * when `unused` is empty so callers can report fully-minimal manifests too.\n */\nexport function reconcileExtensionCapabilityUsage(\n loaded: ReadonlyArray<{\n layer: ExtensionLayer;\n name: string;\n capabilities?: readonly string[];\n }>,\n activation: ExtensionActivationResult,\n): ExtensionCapabilityUsageReconciliation[] {\n const usage = attributeCapabilityUsage(activation);\n const reconciliations: ExtensionCapabilityUsageReconciliation[] = [];\n for (const extension of loaded) {\n const declared = normalizeDeclaredCapabilities(extension.capabilities);\n if (declared.length === 0) {\n continue;\n }\n const exercised =\n usage.get(usageKey(extension.layer, extension.name)) ??\n new Set<ExtensionCapability>();\n const used = [...exercised].sort((left, right) =>\n left.localeCompare(right),\n );\n const unused = declared.filter((capability) => !exercised.has(capability));\n reconciliations.push({\n layer: extension.layer,\n name: extension.name,\n declared,\n used,\n unused,\n });\n }\n return reconciliations;\n}\n","/**\n * @module core/schema/runtime-schema\n *\n * Resolves configurable schema, fields, statuses, and workflows for Runtime Schema.\n */\nimport path from \"node:path\";\nimport {\n pathExists,\n readFileIfExists,\n writeFileAtomic,\n} from \"../fs/fs-utils.js\";\nimport {\n DEFAULT_STATUS_DEFINITIONS,\n DEFAULT_WORKFLOW_DEFINITION,\n} from \"../shared/constants.js\";\nimport {\n RUNTIME_FIELD_COMMAND_VALUES,\n RUNTIME_FIELD_TYPE_VALUES,\n RUNTIME_STATUS_ROLE_VALUES,\n RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,\n STATUS_VALUES,\n} from \"../../types/index.js\";\nimport type {\n ItemTypeDefinition,\n RuntimeFieldCommand,\n RuntimeFieldDefinition,\n RuntimeFieldType,\n RuntimeSchemaSettings,\n RuntimeStatusDefinition,\n RuntimeStatusRole,\n RuntimeWorkflowDefinition,\n TypeWorkflowDefinition,\n} from \"../../types/index.js\";\n\nexport type { RuntimeFieldCommand } from \"../../types/index.js\";\n\n/** Fallback runtime schema file paths used when callers do not provide an override. */\nexport const DEFAULT_RUNTIME_SCHEMA_FILE_PATHS = Object.freeze({\n types: \"schema/types.json\",\n statuses: \"schema/statuses.json\",\n fields: \"schema/fields.json\",\n workflows: \"schema/workflows.json\",\n});\n\n// Default lifecycle status model and workflow role mapping live in\n// src/core/shared/constants.ts as the single source of truth (also referenced\n// by SETTINGS_DEFAULTS). Re-exported here under the historical names.\n/** Fallback runtime workflow used when callers do not provide an override. */\nexport const DEFAULT_RUNTIME_WORKFLOW: RuntimeWorkflowDefinition =\n DEFAULT_WORKFLOW_DEFINITION;\n\n/** Fallback runtime status definitions used when callers do not provide an override. */\nexport const DEFAULT_RUNTIME_STATUS_DEFINITIONS: ReadonlyArray<RuntimeStatusDefinition> =\n DEFAULT_STATUS_DEFINITIONS;\n\nconst DEFAULT_RUNTIME_FIELD_COMMANDS: RuntimeFieldCommand[] = [\n \"create\",\n \"update\",\n];\n\n/** Documents the runtime status definition resolved payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeStatusDefinitionResolved {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports aliases for this contract. */\n aliases: string[];\n /** Value that configures or reports roles for this contract. */\n roles: RuntimeStatusRole[];\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Value that configures or reports order for this contract. */\n order: number;\n}\n\n/** Documents the runtime field definition resolved payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeFieldDefinitionResolved {\n /** Value that configures or reports key for this contract. */\n key: string;\n /** Value that configures or reports metadata key for this contract. */\n metadata_key: string;\n /** Value that configures or reports cli flag for this contract. */\n cli_flag: string;\n /** Value that configures or reports cli aliases for this contract. */\n cli_aliases: string[];\n /** Value that configures or reports description for this contract. */\n description?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type: RuntimeFieldType;\n /** Value that configures or reports commands for this contract. */\n commands: RuntimeFieldCommand[];\n /** Value that configures or reports repeatable for this contract. */\n repeatable: boolean;\n /** Value that configures or reports required for this contract. */\n required: boolean;\n /** Value that configures or reports required on create for this contract. */\n required_on_create: boolean;\n /** Value that configures or reports required types for this contract. */\n required_types: string[];\n /** Value that configures or reports allow unset for this contract. */\n allow_unset: boolean;\n}\n\n/** Documents the runtime status registry payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeStatusRegistry {\n /** Value that configures or reports definitions for this contract. */\n definitions: RuntimeStatusDefinitionResolved[];\n /** Value that configures or reports by id for this contract. */\n by_id: Map<string, RuntimeStatusDefinitionResolved>;\n /** Value that configures or reports alias to id for this contract. */\n alias_to_id: Map<string, string>;\n /** Value that configures or reports terminal statuses for this contract. */\n terminal_statuses: Set<string>;\n /** Value that configures or reports terminal done statuses for this contract. */\n terminal_done_statuses: Set<string>;\n /** Value that configures or reports terminal canceled statuses for this contract. */\n terminal_canceled_statuses: Set<string>;\n /** Value that configures or reports active statuses for this contract. */\n active_statuses: Set<string>;\n /** Value that configures or reports blocked statuses for this contract. */\n blocked_statuses: Set<string>;\n /** Value that configures or reports draft statuses for this contract. */\n draft_statuses: Set<string>;\n /** Lifecycle state reported for openthe record. */\n open_status: string;\n /** Lifecycle state reported for closethe record. */\n close_status: string;\n /** Lifecycle state reported for canceledthe record. */\n canceled_status: string;\n}\n\n/** Documents the runtime field registry payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeFieldRegistry {\n /** Value that configures or reports definitions for this contract. */\n definitions: RuntimeFieldDefinitionResolved[];\n /** Value that configures or reports by key for this contract. */\n by_key: Map<string, RuntimeFieldDefinitionResolved>;\n /** Value that configures or reports by cli token for this contract. */\n by_cli_token: Map<string, RuntimeFieldDefinitionResolved>;\n /** Value that configures or reports command to fields for this contract. */\n command_to_fields: Map<RuntimeFieldCommand, RuntimeFieldDefinitionResolved[]>;\n}\n\n/** Documents the runtime schema file bootstrap result payload exchanged by command, SDK, and package integrations. */\nexport interface RuntimeSchemaFileBootstrapResult {\n /** Value that configures or reports created paths for this contract. */\n created_paths: string[];\n}\n\n/** Documents the loaded runtime schema sections payload exchanged by command, SDK, and package integrations. */\nexport interface LoadedRuntimeSchemaSections {\n /** Value that configures or reports schema for this contract. */\n schema: RuntimeSchemaSettings;\n /** Value that configures or reports type definitions from file for this contract. */\n type_definitions_from_file: ItemTypeDefinition[] | undefined;\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** Value that configures or reports created paths for this contract. */\n created_paths: string[];\n}\n\nconst RUNTIME_STATUS_ROLE_SET = new Set<string>(RUNTIME_STATUS_ROLE_VALUES);\nconst RUNTIME_FIELD_TYPE_SET = new Set<string>(RUNTIME_FIELD_TYPE_VALUES);\nconst RUNTIME_FIELD_COMMAND_SET = new Set<string>(RUNTIME_FIELD_COMMAND_VALUES);\nconst RUNTIME_UNKNOWN_FIELD_POLICY_SET = new Set<string>(\n RUNTIME_UNKNOWN_FIELD_POLICY_VALUES,\n);\n\nfunction normalizeStringList(values: string[] | undefined): string[] {\n const candidates = Array.isArray(values) ? values : [];\n return [\n ...new Set(\n candidates\n .map((value) => (typeof value === \"string\" ? value.trim() : \"\"))\n .filter((value) => value.length > 0),\n ),\n ].sort((left, right) => left.localeCompare(right));\n}\n\nfunction normalizeStatusToken(value: unknown): string {\n return typeof value === \"string\"\n ? value\n .trim()\n .toLowerCase()\n .replaceAll(/[\\s-]+/g, \"_\")\n : \"\";\n}\n\nfunction normalizeStatusId(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n return undefined;\n }\n const normalized = normalizeStatusToken(value);\n return normalized.length > 0 ? normalized : undefined;\n}\n\nfunction stripFlagPrefix(value: string): string {\n return value.startsWith(\"--\") ? value.slice(2) : value;\n}\n\nfunction normalizeCliToken(value: unknown): string {\n return typeof value === \"string\"\n ? stripFlagPrefix(\n value\n .trim()\n .toLowerCase()\n .replaceAll(/[\\s_]+/g, \"-\"),\n )\n : \"\";\n}\n\nfunction keyToDefaultCliFlag(value: string): string {\n return value.replaceAll(\"_\", \"-\");\n}\n\nfunction toCamelCase(input: string): string {\n const segments = input\n .replaceAll(/[^A-Za-z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter((segment) => segment.length > 0)\n .map((segment) => segment.toLowerCase());\n if (segments.length === 0) {\n return input;\n }\n const [first, ...rest] = segments;\n return `${first}${rest.map((segment) => `${segment.slice(0, 1).toUpperCase()}${segment.slice(1)}`).join(\"\")}`;\n}\n\nfunction normalizeRuntimeStatusDefinition(\n definition: RuntimeStatusDefinition,\n fallbackOrder: number,\n): RuntimeStatusDefinitionResolved | null {\n const id = normalizeStatusId(definition.id);\n if (!id) {\n return null;\n }\n const aliases = normalizeStringList(definition.aliases)\n .map((value) => normalizeStatusToken(value))\n .filter((value) => value !== id);\n const roles = normalizeStringList(definition.roles).filter(\n (value): value is RuntimeStatusRole => RUNTIME_STATUS_ROLE_SET.has(value),\n );\n const description = definition.description?.trim();\n const order =\n typeof definition.order === \"number\" && Number.isFinite(definition.order)\n ? definition.order\n : fallbackOrder;\n return {\n id,\n aliases,\n roles,\n description:\n description && description.length > 0 ? description : undefined,\n order,\n };\n}\n\nfunction normalizeRuntimeWorkflow(\n workflow: RuntimeWorkflowDefinition | undefined,\n): RuntimeWorkflowDefinition {\n return {\n draft_status: normalizeStatusId(workflow?.draft_status),\n open_status: normalizeStatusId(workflow?.open_status),\n in_progress_status: normalizeStatusId(workflow?.in_progress_status),\n blocked_status: normalizeStatusId(workflow?.blocked_status),\n close_status: normalizeStatusId(workflow?.close_status),\n canceled_status: normalizeStatusId(workflow?.canceled_status),\n };\n}\n\ninterface TypeWorkflowAccumulatorRecord {\n type: string;\n pairs: [string, string][];\n denyAll: boolean;\n}\n\nfunction appendTypeWorkflowPair(\n record: TypeWorkflowAccumulatorRecord,\n pair: unknown,\n): void {\n if (!Array.isArray(pair) || pair.length !== 2) {\n return;\n }\n const from = normalizeStatusToken(pair[0]);\n const to = normalizeStatusToken(pair[1]);\n if (from.length === 0 || to.length === 0) {\n return;\n }\n if (\n record.pairs.some(\n (candidate) => candidate[0] === from && candidate[1] === to,\n )\n ) {\n return;\n }\n record.pairs.push([from, to]);\n}\n\nfunction normalizedTypeWorkflowEntry(\n entry: TypeWorkflowDefinition,\n): { typeKey: string; record: TypeWorkflowAccumulatorRecord } | null {\n const rawType = typeof entry?.type === \"string\" ? entry.type.trim() : \"\";\n if (rawType.length === 0 || !Array.isArray(entry?.allowed_transitions)) {\n return null;\n }\n const record: TypeWorkflowAccumulatorRecord = {\n type: rawType,\n pairs: [],\n denyAll: entry.allowed_transitions.length === 0,\n };\n for (const pair of entry.allowed_transitions) {\n appendTypeWorkflowPair(record, pair);\n }\n return { typeKey: rawType.toLowerCase(), record };\n}\n\nfunction normalizeTypeWorkflowDefinitions(\n workflows: TypeWorkflowDefinition[] | undefined,\n): TypeWorkflowDefinition[] | undefined {\n if (!Array.isArray(workflows) || workflows.length === 0) {\n return undefined;\n }\n // Keep the raw (trimmed) type name so it round-trips verbatim; comparison is\n // case-insensitive downstream (resolveTypeWorkflows lower-cases). from/to\n // status tokens use the same normalization rules as runtime statuses.\n //\n // An EXPLICIT empty `allowed_transitions: []` is a deliberate DENY-ALL rule and\n // MUST survive normalization (it must NOT collapse to \"no entry\", which would\n // leave the type unrestricted). But a NON-empty array whose every pair is\n // malformed (e.g. a 3-element tuple typo) must be DROPPED like other malformed\n // schema-file content, NOT silently turned into a deny-all rule — otherwise a\n // typo would start failing every update for that type under strict enforcement.\n const byTypeKey = new Map<string, TypeWorkflowAccumulatorRecord>();\n for (const entry of workflows) {\n const normalized = normalizedTypeWorkflowEntry(entry);\n if (normalized === null) {\n continue;\n }\n const record = byTypeKey.get(normalized.typeKey) ?? normalized.record;\n record.denyAll ||= normalized.record.denyAll;\n for (const pair of normalized.record.pairs) {\n appendTypeWorkflowPair(record, pair);\n }\n byTypeKey.set(normalized.typeKey, record);\n }\n const normalized: TypeWorkflowDefinition[] = [];\n for (const record of byTypeKey.values()) {\n // Keep when there is at least one valid transition OR an explicit deny-all was\n // declared; drop nonempty-but-all-malformed entries (treated as typos).\n if (record.pairs.length > 0 || record.denyAll) {\n normalized.push({ type: record.type, allowed_transitions: record.pairs });\n }\n }\n normalized.sort((left, right) => left.type.localeCompare(right.type));\n return normalized.length > 0 ? normalized : undefined;\n}\n\nfunction normalizeRuntimeFieldDefinition(\n definition: RuntimeFieldDefinition,\n): RuntimeFieldDefinitionResolved | null {\n const key = normalizeStatusToken(definition.key ?? \"\");\n if (!key) {\n return null;\n }\n const metadataKey = normalizeStatusToken(\n definition.metadata_key ?? definition.front_matter_key ?? key,\n );\n const cliFlag = normalizeCliToken(\n definition.cli_flag ?? keyToDefaultCliFlag(key),\n );\n if (!cliFlag) {\n return null;\n }\n const cliAliases = normalizeStringList(definition.cli_aliases)\n .map((value) => normalizeCliToken(value))\n .filter((value) => value.length > 0 && value !== cliFlag);\n const typeCandidate =\n typeof definition.type === \"string\"\n ? definition.type.trim().toLowerCase()\n : \"string\";\n const type = RUNTIME_FIELD_TYPE_SET.has(typeCandidate)\n ? (typeCandidate as RuntimeFieldType)\n : \"string\";\n const commands = (() => {\n const normalized = normalizeStringList(definition.commands).filter(\n (value): value is RuntimeFieldCommand =>\n RUNTIME_FIELD_COMMAND_SET.has(value),\n );\n if (normalized.length > 0) {\n return normalized;\n }\n return [...DEFAULT_RUNTIME_FIELD_COMMANDS];\n })();\n const description = definition.description?.trim();\n const requiredTypes = normalizeStringList(definition.required_types);\n return {\n key,\n metadata_key: metadataKey,\n cli_flag: cliFlag,\n cli_aliases: cliAliases,\n description:\n description && description.length > 0 ? description : undefined,\n type,\n commands,\n repeatable: definition.repeatable === true || type === \"string_array\",\n required: definition.required === true,\n required_on_create: definition.required_on_create === true,\n required_types: requiredTypes,\n allow_unset: definition.allow_unset !== false,\n };\n}\n\nfunction normalizeRuntimeStatusDefinitions(\n statusesSource: ReadonlyArray<RuntimeStatusDefinition>,\n): RuntimeStatusDefinitionResolved[] {\n const dedupedById = new Map<string, RuntimeStatusDefinitionResolved>();\n for (const [index, definition] of statusesSource.entries()) {\n const normalized = normalizeRuntimeStatusDefinition(definition, index);\n if (normalized) {\n dedupedById.set(normalized.id, normalized);\n }\n }\n const values = sortRuntimeStatusDefinitions([...dedupedById.values()]);\n if (values.length > 0) {\n return values;\n }\n return sortRuntimeStatusDefinitions(\n DEFAULT_RUNTIME_STATUS_DEFINITIONS.map((definition, index) =>\n normalizeRuntimeStatusDefinition(definition, index),\n ).filter(\n (definition): definition is RuntimeStatusDefinitionResolved =>\n definition !== null,\n ),\n );\n}\n\nfunction sortRuntimeStatusDefinitions(\n definitions: RuntimeStatusDefinitionResolved[],\n): RuntimeStatusDefinitionResolved[] {\n return definitions.sort((left, right) =>\n left.order === right.order\n ? left.id.localeCompare(right.id)\n : left.order - right.order,\n );\n}\n\nfunction normalizeRuntimeFieldDefinitions(\n fieldsSource: ReadonlyArray<RuntimeFieldDefinition> | undefined,\n): RuntimeFieldDefinitionResolved[] {\n const dedupedByKey = new Map<string, RuntimeFieldDefinitionResolved>();\n for (const definition of fieldsSource ?? []) {\n const normalized = normalizeRuntimeFieldDefinition(definition);\n if (normalized) {\n dedupedByKey.set(normalized.key, normalized);\n }\n }\n return [...dedupedByKey.values()].sort((left, right) =>\n left.key.localeCompare(right.key),\n );\n}\n\nfunction serializeRuntimeStatusDefinition(\n definition: RuntimeStatusDefinitionResolved,\n): RuntimeStatusDefinition {\n return {\n id: definition.id,\n aliases:\n definition.aliases.length > 0 ? [...definition.aliases] : undefined,\n roles: definition.roles.length > 0 ? [...definition.roles] : undefined,\n description: definition.description,\n order: definition.order,\n };\n}\n\nfunction serializeRuntimeFieldDefinition(\n definition: RuntimeFieldDefinitionResolved,\n): RuntimeFieldDefinition {\n return {\n key: definition.key,\n metadata_key:\n definition.metadata_key !== definition.key\n ? definition.metadata_key\n : undefined,\n cli_flag:\n definition.cli_flag !== keyToDefaultCliFlag(definition.key)\n ? definition.cli_flag\n : undefined,\n cli_aliases:\n definition.cli_aliases.length > 0\n ? [...definition.cli_aliases]\n : undefined,\n description: definition.description,\n type: definition.type,\n commands: [...definition.commands],\n repeatable: definition.repeatable === true ? true : undefined,\n required: definition.required === true ? true : undefined,\n required_on_create:\n definition.required_on_create === true ? true : undefined,\n required_types:\n definition.required_types.length > 0\n ? [...definition.required_types]\n : undefined,\n allow_unset: definition.allow_unset === false ? false : undefined,\n };\n}\n\nfunction normalizeUnknownFieldPolicy(\n policy: RuntimeSchemaSettings[\"unknown_field_policy\"] | undefined,\n): RuntimeSchemaSettings[\"unknown_field_policy\"] {\n const candidate =\n typeof policy === \"string\" ? policy.trim().toLowerCase() : \"allow\";\n return RUNTIME_UNKNOWN_FIELD_POLICY_SET.has(candidate)\n ? (candidate as RuntimeSchemaSettings[\"unknown_field_policy\"])\n : \"allow\";\n}\n\n/** Implements normalize runtime schema settings for the public runtime surface of this module. */\nexport function normalizeRuntimeSchemaSettings(\n schema: Partial<RuntimeSchemaSettings> | undefined,\n): RuntimeSchemaSettings {\n const files = {\n ...DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,\n ...schema?.files,\n };\n const statusesSource =\n schema?.statuses && schema.statuses.length > 0\n ? schema.statuses\n : DEFAULT_RUNTIME_STATUS_DEFINITIONS;\n const normalizedStatuses = normalizeRuntimeStatusDefinitions(statusesSource);\n const normalizedFields = normalizeRuntimeFieldDefinitions(schema?.fields);\n return {\n version:\n typeof schema?.version === \"number\" && Number.isFinite(schema.version)\n ? Math.floor(schema.version)\n : 1,\n files,\n statuses: normalizedStatuses.map(serializeRuntimeStatusDefinition),\n fields: normalizedFields.map(serializeRuntimeFieldDefinition),\n workflow: {\n ...DEFAULT_RUNTIME_WORKFLOW,\n ...normalizeRuntimeWorkflow(schema?.workflow),\n },\n type_workflows: normalizeTypeWorkflowDefinitions(schema?.type_workflows),\n unknown_field_policy: normalizeUnknownFieldPolicy(\n schema?.unknown_field_policy,\n ),\n };\n}\n\nfunction serializeJson(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\nfunction buildTypesFileSeed(): unknown {\n return {\n definitions: [],\n };\n}\n\nfunction buildStatusesFileSeed(): unknown {\n return {\n statuses: DEFAULT_RUNTIME_STATUS_DEFINITIONS,\n };\n}\n\nfunction buildFieldsFileSeed(): unknown {\n return {\n fields: [],\n };\n}\n\nfunction buildWorkflowsFileSeed(): unknown {\n return {\n workflow: DEFAULT_RUNTIME_WORKFLOW,\n };\n}\n\nfunction parseOptionalJson(\n raw: string,\n warningKey: string,\n warnings: string[],\n): unknown | undefined {\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n warnings.push(warningKey);\n return undefined;\n }\n}\n\nfunction readTypeDefinitionsFromSchemaFile(\n parsed: unknown,\n): ItemTypeDefinition[] | undefined {\n if (Array.isArray(parsed)) {\n return parsed as ItemTypeDefinition[];\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return undefined;\n }\n const record = parsed as Record<string, unknown>;\n if (Array.isArray(record.definitions)) {\n return record.definitions as ItemTypeDefinition[];\n }\n if (typeof record.item_types === \"object\" && record.item_types !== null) {\n const itemTypesRecord = record.item_types as Record<string, unknown>;\n if (Array.isArray(itemTypesRecord.definitions)) {\n return itemTypesRecord.definitions as ItemTypeDefinition[];\n }\n }\n return undefined;\n}\n\nfunction readStatusesFromSchemaFile(\n parsed: unknown,\n): RuntimeStatusDefinition[] | undefined {\n if (Array.isArray(parsed)) {\n return parsed as RuntimeStatusDefinition[];\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return undefined;\n }\n const record = parsed as Record<string, unknown>;\n if (Array.isArray(record.statuses)) {\n return record.statuses as RuntimeStatusDefinition[];\n }\n if (Array.isArray(record.definitions)) {\n return record.definitions as RuntimeStatusDefinition[];\n }\n return undefined;\n}\n\nfunction readFieldsFromSchemaFile(\n parsed: unknown,\n): RuntimeFieldDefinition[] | undefined {\n if (Array.isArray(parsed)) {\n return parsed as RuntimeFieldDefinition[];\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n return undefined;\n }\n const record = parsed as Record<string, unknown>;\n if (Array.isArray(record.fields)) {\n return record.fields as RuntimeFieldDefinition[];\n }\n if (Array.isArray(record.definitions)) {\n return record.definitions as RuntimeFieldDefinition[];\n }\n return undefined;\n}\n\nfunction readWorkflowFromSchemaFile(\n parsed: unknown,\n): RuntimeWorkflowDefinition | undefined {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return undefined;\n }\n const record = parsed as Record<string, unknown>;\n if (\n typeof record.workflow === \"object\" &&\n record.workflow !== null &&\n !Array.isArray(record.workflow)\n ) {\n return record.workflow as RuntimeWorkflowDefinition;\n }\n if (\n typeof record.workflows === \"object\" &&\n record.workflows !== null &&\n !Array.isArray(record.workflows)\n ) {\n return record.workflows as RuntimeWorkflowDefinition;\n }\n return record as RuntimeWorkflowDefinition;\n}\n\nfunction readTypeWorkflowsFromSchemaFile(\n parsed: unknown,\n): TypeWorkflowDefinition[] | undefined {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return undefined;\n }\n const record = parsed as Record<string, unknown>;\n if (Array.isArray(record.type_workflows)) {\n return record.type_workflows as TypeWorkflowDefinition[];\n }\n return undefined;\n}\n\n/** Implements file path for schema section for the public runtime surface of this module. */\nexport function filePathForSchemaSection(\n pmRoot: string,\n configuredPath: string | undefined,\n fallbackPath: string,\n): string {\n const normalized = configuredPath?.trim() || fallbackPath;\n if (path.isAbsolute(normalized)) {\n return normalized;\n }\n return path.join(pmRoot, normalized);\n}\n\n/** Resolves the active tracker's `schema/types.json` path so user-facing hints (e.g. the invalid-type error) point at the real `--pm-path` location instead of the hardcoded `.agents/pm` default. Mirrors how `pm schema add/remove-type` report their target path. */\nexport function resolveItemTypesFilePath(\n pmRoot: string,\n schema: RuntimeSchemaSettings,\n): string {\n return filePathForSchemaSection(\n pmRoot,\n schema.files.types,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types,\n );\n}\n\n/** Implements ensure runtime schema file scaffold for the public runtime surface of this module. */\nexport async function ensureRuntimeSchemaFileScaffold(\n pmRoot: string,\n schema: RuntimeSchemaSettings,\n): Promise<RuntimeSchemaFileBootstrapResult> {\n const normalizedSchema = normalizeRuntimeSchemaSettings(schema);\n const specs: Array<{ path: string; seed: unknown }> = [\n {\n path: filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.types,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types,\n ),\n seed: buildTypesFileSeed(),\n },\n {\n path: filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.statuses,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.statuses,\n ),\n seed: buildStatusesFileSeed(),\n },\n {\n path: filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.fields,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields,\n ),\n seed: buildFieldsFileSeed(),\n },\n {\n path: filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.workflows,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows,\n ),\n seed: buildWorkflowsFileSeed(),\n },\n ];\n const createdPaths: string[] = [];\n for (const spec of specs) {\n if (await pathExists(spec.path)) {\n continue;\n }\n await writeFileAtomic(spec.path, serializeJson(spec.seed));\n createdPaths.push(spec.path);\n }\n return {\n created_paths: createdPaths,\n };\n}\n\n/** Implements load runtime schema from optional files for the public runtime surface of this module. */\nexport async function loadRuntimeSchemaFromOptionalFiles(\n pmRoot: string,\n schema: RuntimeSchemaSettings,\n): Promise<LoadedRuntimeSchemaSections> {\n const normalizedSchema = normalizeRuntimeSchemaSettings(schema);\n const warnings: string[] = [];\n const typeFilePath = filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.types,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types,\n );\n const statusFilePath = filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.statuses,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.statuses,\n );\n const fieldsFilePath = filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.fields,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields,\n );\n const workflowsFilePath = filePathForSchemaSection(\n pmRoot,\n normalizedSchema.files.workflows,\n DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows,\n );\n\n let loadedTypeDefinitions: ItemTypeDefinition[] | undefined;\n let loadedStatuses: RuntimeStatusDefinition[] | undefined;\n let loadedFields: RuntimeFieldDefinition[] | undefined;\n let loadedWorkflow: RuntimeWorkflowDefinition | undefined;\n let loadedTypeWorkflows: TypeWorkflowDefinition[] | undefined;\n\n const readAndParse = async (\n targetPath: string,\n warningKey: string,\n ): Promise<unknown | undefined> => {\n const raw = await readFileIfExists(targetPath);\n if (raw === null) {\n return undefined;\n }\n return parseOptionalJson(raw, warningKey, warnings);\n };\n\n const parsedTypes = await readAndParse(\n typeFilePath,\n \"runtime_schema_types_invalid_json\",\n );\n if (parsedTypes !== undefined) {\n loadedTypeDefinitions = readTypeDefinitionsFromSchemaFile(parsedTypes);\n if (loadedTypeDefinitions === undefined) {\n warnings.push(\"runtime_schema_types_invalid_shape\");\n }\n }\n\n const parsedStatuses = await readAndParse(\n statusFilePath,\n \"runtime_schema_statuses_invalid_json\",\n );\n if (parsedStatuses !== undefined) {\n loadedStatuses = readStatusesFromSchemaFile(parsedStatuses);\n if (loadedStatuses === undefined) {\n warnings.push(\"runtime_schema_statuses_invalid_shape\");\n }\n }\n\n const parsedFields = await readAndParse(\n fieldsFilePath,\n \"runtime_schema_fields_invalid_json\",\n );\n if (parsedFields !== undefined) {\n loadedFields = readFieldsFromSchemaFile(parsedFields);\n if (loadedFields === undefined) {\n warnings.push(\"runtime_schema_fields_invalid_shape\");\n }\n }\n\n const parsedWorkflow = await readAndParse(\n workflowsFilePath,\n \"runtime_schema_workflows_invalid_json\",\n );\n if (parsedWorkflow !== undefined) {\n loadedWorkflow = readWorkflowFromSchemaFile(parsedWorkflow);\n if (loadedWorkflow === undefined) {\n warnings.push(\"runtime_schema_workflows_invalid_shape\");\n }\n // type_workflows live alongside `workflow` in the same file; their absence\n // is not an error (the file may carry only the lifecycle workflow block).\n loadedTypeWorkflows = readTypeWorkflowsFromSchemaFile(parsedWorkflow);\n }\n\n const mergedSchema = normalizeRuntimeSchemaSettings({\n ...normalizedSchema,\n statuses: [...normalizedSchema.statuses, ...(loadedStatuses ?? [])],\n fields: [...normalizedSchema.fields, ...(loadedFields ?? [])],\n workflow: {\n ...normalizedSchema.workflow,\n ...loadedWorkflow,\n },\n type_workflows: [\n ...(normalizedSchema.type_workflows ?? []),\n ...(loadedTypeWorkflows ?? []),\n ],\n });\n\n return {\n schema: mergedSchema,\n type_definitions_from_file: loadedTypeDefinitions,\n warnings,\n created_paths: [],\n };\n}\n\nfunction preferredStatusForRole(\n definitions: RuntimeStatusDefinitionResolved[],\n role: RuntimeStatusRole,\n fallbackValues: string[],\n): string | undefined {\n const withRole = definitions.filter((definition) =>\n definition.roles.includes(role),\n );\n if (withRole.length > 0) {\n return withRole[0].id;\n }\n const normalizedFallbacks = fallbackValues\n .map((value) => normalizeStatusId(value))\n .filter((value): value is string => typeof value === \"string\");\n for (const normalized of normalizedFallbacks) {\n if (definitions.some((definition) => definition.id === normalized)) {\n return normalized;\n }\n }\n return definitions[0]?.id;\n}\n\n/** Implements resolve runtime status registry for the public runtime surface of this module. */\nexport function resolveRuntimeStatusRegistry(\n schema: RuntimeSchemaSettings,\n): RuntimeStatusRegistry {\n const normalizedSchema = normalizeRuntimeSchemaSettings(schema);\n const definitions = normalizedSchema.statuses\n .map((definition, index) =>\n normalizeRuntimeStatusDefinition(definition, index),\n )\n .filter(\n (definition): definition is RuntimeStatusDefinitionResolved =>\n definition !== null,\n );\n const aliasToId = new Map<string, string>();\n const byId = new Map<string, RuntimeStatusDefinitionResolved>();\n for (const definition of definitions) {\n byId.set(definition.id, definition);\n aliasToId.set(definition.id, definition.id);\n aliasToId.set(definition.id.replaceAll(\"_\", \"-\"), definition.id);\n aliasToId.set(definition.id.replaceAll(\"_\", \" \"), definition.id);\n for (const alias of definition.aliases) {\n aliasToId.set(alias, definition.id);\n aliasToId.set(alias.replaceAll(\"_\", \"-\"), definition.id);\n aliasToId.set(alias.replaceAll(\"_\", \" \"), definition.id);\n }\n }\n const terminalStatuses = new Set<string>();\n const terminalDoneStatuses = new Set<string>();\n const terminalCanceledStatuses = new Set<string>();\n const activeStatuses = new Set<string>();\n const blockedStatuses = new Set<string>();\n const draftStatuses = new Set<string>();\n for (const definition of definitions) {\n const roles = new Set(definition.roles);\n if (\n roles.has(\"terminal\") ||\n roles.has(\"terminal_done\") ||\n roles.has(\"terminal_canceled\")\n ) {\n terminalStatuses.add(definition.id);\n }\n if (roles.has(\"terminal_done\")) {\n terminalDoneStatuses.add(definition.id);\n }\n if (roles.has(\"terminal_canceled\")) {\n terminalCanceledStatuses.add(definition.id);\n }\n if (roles.has(\"active\")) {\n activeStatuses.add(definition.id);\n }\n if (roles.has(\"blocked\")) {\n blockedStatuses.add(definition.id);\n }\n if (roles.has(\"draft\")) {\n draftStatuses.add(definition.id);\n }\n }\n const workflow = normalizedSchema.workflow;\n const openStatus =\n normalizeStatusId(workflow.open_status) ??\n preferredStatusForRole(definitions, \"default_open\", [\n \"open\",\n \"in_progress\",\n STATUS_VALUES[0],\n ]);\n const closeStatus =\n normalizeStatusId(workflow.close_status) ??\n preferredStatusForRole(definitions, \"default_close\", [\n \"closed\",\n \"done\",\n \"complete\",\n ]);\n const canceledStatus =\n normalizeStatusId(workflow.canceled_status) ??\n preferredStatusForRole(definitions, \"default_cancel\", [\n \"canceled\",\n \"cancelled\",\n ]);\n\n return {\n definitions,\n by_id: byId,\n alias_to_id: aliasToId,\n terminal_statuses: terminalStatuses,\n terminal_done_statuses: terminalDoneStatuses,\n terminal_canceled_statuses: terminalCanceledStatuses,\n active_statuses: activeStatuses,\n blocked_statuses: blockedStatuses,\n draft_statuses: draftStatuses,\n open_status: openStatus as string,\n close_status: closeStatus as string,\n canceled_status: canceledStatus as string,\n };\n}\n\n/** Implements normalize status input with registry for the public runtime surface of this module. */\nexport function normalizeStatusInputWithRegistry(\n value: unknown,\n registry: RuntimeStatusRegistry,\n): string | undefined {\n const normalized = normalizeStatusToken(value);\n if (!normalized) {\n return undefined;\n }\n return registry.alias_to_id.get(normalized);\n}\n\n/** Implements resolve runtime field registry for the public runtime surface of this module. */\nexport function resolveRuntimeFieldRegistry(\n schema: RuntimeSchemaSettings,\n): RuntimeFieldRegistry {\n const normalizedSchema = normalizeRuntimeSchemaSettings(schema);\n const dedupedByKey = new Map<string, RuntimeFieldDefinitionResolved>();\n const normalizedFields = normalizedSchema.fields\n .map((definition) => normalizeRuntimeFieldDefinition(definition))\n .filter(\n (definition): definition is RuntimeFieldDefinitionResolved =>\n definition !== null,\n );\n for (const normalized of normalizedFields) {\n dedupedByKey.set(normalized.key, normalized);\n }\n const definitions = [...dedupedByKey.values()].sort((left, right) =>\n left.key.localeCompare(right.key),\n );\n const byKey = new Map<string, RuntimeFieldDefinitionResolved>();\n const byCliToken = new Map<string, RuntimeFieldDefinitionResolved>();\n const commandToFields = new Map<\n RuntimeFieldCommand,\n RuntimeFieldDefinitionResolved[]\n >();\n for (const definition of definitions) {\n byKey.set(definition.key, definition);\n byCliToken.set(definition.cli_flag, definition);\n for (const alias of definition.cli_aliases) {\n byCliToken.set(alias, definition);\n }\n for (const command of definition.commands) {\n const existing = commandToFields.get(command) ?? [];\n existing.push(definition);\n commandToFields.set(command, existing);\n }\n }\n for (const [command, fieldDefinitions] of commandToFields.entries()) {\n fieldDefinitions.sort((left, right) => left.key.localeCompare(right.key));\n commandToFields.set(command, fieldDefinitions);\n }\n return {\n definitions,\n by_key: byKey,\n by_cli_token: byCliToken,\n command_to_fields: commandToFields,\n };\n}\n\n/** Implements runtime field option target for the public runtime surface of this module. */\nexport function runtimeFieldOptionTarget(\n field: RuntimeFieldDefinitionResolved,\n): string {\n return toCamelCase(field.key);\n}\n\n/** Implements status is terminal for the public runtime surface of this module. */\nexport function statusIsTerminal(\n status: string,\n registry: RuntimeStatusRegistry,\n): boolean {\n const normalized = normalizeStatusInputWithRegistry(status, registry);\n if (!normalized) {\n return false;\n }\n return registry.terminal_statuses.has(normalized);\n}\n","/**\n * @module core/shared/errors\n *\n * Provides shared primitives and utilities for Errors.\n */\n/** Carries structured recovery guidance attached to expected pm CLI errors. */\nexport interface PmCliErrorRecoveryPayload {\n /** Strategy used to control recovery behavior. */\n recovery_mode?: \"compact\";\n /** Value that configures or reports attempted command for this contract. */\n attempted_command?: string;\n /** Value that configures or reports normalized args for this contract. */\n normalized_args?: string[];\n /** Value that configures or reports provided fields for this contract. */\n provided_fields?: string[];\n /** Value that configures or reports missing for this contract. */\n missing?: string[];\n /** Value that configures or reports missing required fields for this contract. */\n missing_required_fields?: string[];\n /** Value that configures or reports suggested flags for this contract. */\n suggested_flags?: string[];\n /** Value that configures or reports suggested retry for this contract. */\n suggested_retry?: string;\n /** Elapsed time in milliseconds for retry after. */\n retry_after_ms?: number;\n /** Value that configures or reports fallback candidates for this contract. */\n fallback_candidates?: Array<{\n source: string;\n command: string;\n reason: string;\n }>;\n /** Value that configures or reports next best command for this contract. */\n next_best_command?: string;\n}\n\n/** Documents the pm cli error context payload exchanged by command, SDK, and package integrations. */\nexport interface PmCliErrorContext {\n /** Value that configures or reports code for this contract. */\n code?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type?: string;\n /** Value that configures or reports required for this contract. */\n required?: string;\n /** Value that configures or reports why for this contract. */\n why?: string;\n /** Value that configures or reports examples for this contract. */\n examples?: string[];\n /** Value that configures or reports next steps for this contract. */\n nextSteps?: string[];\n /** Value that configures or reports recovery for this contract. */\n recovery?: PmCliErrorRecoveryPayload;\n}\n\n/** Implements the exported pm cli error runtime abstraction for core/shared/errors.ts. */\nexport class PmCliError extends Error {\n /** Value that configures or reports exit code for this contract. */\n public readonly exitCode: number;\n /** Value that configures or reports context for this contract. */\n public readonly context: PmCliErrorContext;\n\n /** Value that configures or reports constructor for this contract. */\n constructor(\n message: string,\n exitCode: number,\n context: PmCliErrorContext = {},\n ) {\n super(message);\n this.name = \"PmCliError\";\n this.exitCode = exitCode;\n this.context = context;\n }\n}\n","/**\n * @module core/extensions/item-fields\n *\n * Implements extension runtime contracts and governance for Item Fields.\n */\nimport type { ExtensionRegistrationRegistry } from \"./loader.js\";\nimport {\n normalizeItemFieldType,\n type KnownItemFieldType,\n} from \"./item-field-types.js\";\nimport { EXIT_CODE, ITEM_METADATA_KEY_ORDER } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\n\nconst reservedItemFieldNames = new Set(ITEM_METADATA_KEY_ORDER);\n\n/** Item metadata keys extension-provided fields may never shadow, exposed without mutation methods. */\nexport const RESERVED_ITEM_FIELD_NAMES: ReadonlySet<string> = Object.freeze({\n get size(): number {\n return reservedItemFieldNames.size;\n },\n has(value: string): boolean {\n return reservedItemFieldNames.has(value);\n },\n entries(): IterableIterator<[string, string]> {\n return reservedItemFieldNames.entries();\n },\n keys(): IterableIterator<string> {\n return reservedItemFieldNames.keys();\n },\n values(): IterableIterator<string> {\n return reservedItemFieldNames.values();\n },\n forEach(\n callback: (value: string, value2: string, set: ReadonlySet<string>) => void,\n thisArg?: unknown,\n ): void {\n reservedItemFieldNames.forEach((value) =>\n callback.call(thisArg, value, value, RESERVED_ITEM_FIELD_NAMES),\n );\n },\n [Symbol.iterator](): IterableIterator<string> {\n return reservedItemFieldNames.values();\n },\n});\n\nfunction normalizeFieldName(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFieldType(value: unknown): KnownItemFieldType | null {\n if (typeof value !== \"string\") {\n return null;\n }\n return normalizeItemFieldType(value);\n}\n\nfunction cloneFieldValue<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n\nfunction parseFieldAssignment(raw: string): { key: string; value: string } {\n const trimmed = raw.trim();\n const separatorIndex = trimmed.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new PmCliError(\n `--field entries must use name=value syntax, received: ${raw}`,\n EXIT_CODE.USAGE,\n );\n }\n // `separatorIndex > 0` guarantees a non-`=` first character on the already\n // trimmed string, so the trimmed key is always non-empty here.\n const key = trimmed.slice(0, separatorIndex).trim();\n const value = trimmed.slice(separatorIndex + 1);\n return { key, value };\n}\n\nfunction parseJsonFieldValue(\n raw: string,\n fieldName: string,\n expectedType: \"array\" | \"object\",\n): unknown {\n try {\n const parsed = JSON.parse(raw);\n if (expectedType === \"array\" && Array.isArray(parsed)) {\n return parsed;\n }\n if (\n expectedType === \"object\" &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n return parsed;\n }\n } catch {\n // Fall through to the typed usage error below.\n }\n throw new PmCliError(\n `--field ${fieldName}=... must be valid JSON ${expectedType}`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction coerceRegisteredFieldValue(\n fieldName: string,\n fieldType: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\",\n raw: string,\n): unknown {\n if (fieldType === \"string\") {\n return raw;\n }\n if (fieldType === \"number\") {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new PmCliError(\n `--field ${fieldName}=... must be a number`,\n EXIT_CODE.USAGE,\n );\n }\n const parsed = Number(trimmed);\n if (!Number.isFinite(parsed)) {\n throw new PmCliError(\n `--field ${fieldName}=... must be a number`,\n EXIT_CODE.USAGE,\n );\n }\n return parsed;\n }\n if (fieldType === \"boolean\") {\n const normalized = raw.trim().toLowerCase();\n if (normalized === \"true\" || normalized === \"1\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"false\" || normalized === \"0\" || normalized === \"no\") {\n return false;\n }\n throw new PmCliError(\n `--field ${fieldName}=... must be one of true|false|1|0|yes|no`,\n EXIT_CODE.USAGE,\n );\n }\n return parseJsonFieldValue(raw, fieldName, fieldType);\n}\n\nfunction collectRegisteredFieldDefinitions(\n registrations: ExtensionRegistrationRegistry | null,\n): Map<\n string,\n { name: string; type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" }\n> {\n const definitions = new Map<\n string,\n { name: string; type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" }\n >();\n if (!registrations) {\n return definitions;\n }\n for (const registration of registrations.item_fields) {\n for (const definition of registration.fields) {\n const fieldName = normalizeFieldName(definition.name);\n const fieldType = normalizeFieldType(definition.type);\n if (!fieldName || !fieldType) {\n continue;\n }\n const existing = definitions.get(fieldName);\n if (existing && existing.type !== fieldType) {\n throw new PmCliError(\n `Extension item field \"${fieldName}\" is declared with conflicting types: ${existing.type}, ${fieldType}`,\n EXIT_CODE.USAGE,\n {\n code: \"extension_item_field_type_conflict\",\n nextSteps: [\n \"Make every active extension declaration for this field use the same type.\",\n ],\n },\n );\n }\n definitions.set(fieldName, { name: fieldName, type: fieldType });\n }\n }\n return definitions;\n}\n\nfunction assertNotReservedItemFieldName(fieldName: string): void {\n if (!RESERVED_ITEM_FIELD_NAMES.has(fieldName)) {\n return;\n }\n throw new PmCliError(\n `Extension item field \"${fieldName}\" collides with built-in item metadata \"${fieldName}\"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...RESERVED_ITEM_FIELD_NAMES].sort((left, right) => left.localeCompare(right)).join(\", \")}.`,\n EXIT_CODE.USAGE,\n {\n code: \"extension_item_field_reserved\",\n nextSteps: [\n \"Rename the extension item field, preferably with an extension-specific prefix.\",\n ],\n },\n );\n}\n\n/** Implements collect registered item field names for the public runtime surface of this module. */\nexport function collectRegisteredItemFieldNames(\n registrations: ExtensionRegistrationRegistry | null,\n): string[] {\n return [...collectRegisteredFieldDefinitions(registrations).keys()].sort(\n (left, right) => left.localeCompare(right),\n );\n}\n\n/** Implements parse registered item field assignments for the public runtime surface of this module. */\nexport function parseRegisteredItemFieldAssignments(\n rawFields: string[] | undefined,\n registrations: ExtensionRegistrationRegistry | null,\n): Record<string, unknown> {\n if (!rawFields || rawFields.length === 0) {\n return {};\n }\n const definitions = collectRegisteredFieldDefinitions(registrations);\n const values: Record<string, unknown> = {};\n for (const raw of rawFields) {\n const { key, value } = parseFieldAssignment(raw);\n const definition = definitions.get(key);\n if (!definition) {\n const known = [...definitions.keys()].sort((left, right) =>\n left.localeCompare(right),\n );\n throw new PmCliError(\n `--field ${key} is not declared by an active extension item-field registration`,\n EXIT_CODE.USAGE,\n {\n code: \"extension_item_field_unknown\",\n recovery: { provided_fields: known },\n nextSteps:\n known.length > 0\n ? [`Use one of the declared fields: ${known.join(\", \")}`]\n : [\n \"Activate an extension that calls registerItemFields before setting extension fields.\",\n ],\n },\n );\n }\n assertNotReservedItemFieldName(definition.name);\n values[definition.name] = coerceRegisteredFieldValue(\n definition.name,\n definition.type,\n value,\n );\n }\n return values;\n}\n\nfunction isValidFieldType(\n value: unknown,\n expectedType: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\",\n): boolean {\n if (expectedType === \"string\") {\n return typeof value === \"string\";\n }\n if (expectedType === \"number\") {\n return typeof value === \"number\" && Number.isFinite(value);\n }\n if (expectedType === \"boolean\") {\n return typeof value === \"boolean\";\n }\n if (expectedType === \"array\") {\n return Array.isArray(value);\n }\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAllowedFieldValue(\n value: unknown,\n allowed: unknown[] | undefined,\n): boolean {\n if (!allowed || allowed.length === 0) {\n return true;\n }\n return allowed.some((candidate) => Object.is(candidate, value));\n}\n\n/** Implements apply registered item field defaults and validation for the public runtime surface of this module. */\nexport function applyRegisteredItemFieldDefaultsAndValidation(\n itemMetadata: Record<string, unknown>,\n registrations: ExtensionRegistrationRegistry | null,\n options: { skipDefaultFields?: ReadonlySet<string> } = {},\n): void {\n if (!registrations) {\n return;\n }\n collectRegisteredFieldDefinitions(registrations);\n for (const registration of registrations.item_fields) {\n for (const definition of registration.fields) {\n const fieldName = normalizeFieldName(definition.name);\n if (!fieldName) {\n continue;\n }\n assertNotReservedItemFieldName(fieldName);\n if (\n !(fieldName in itemMetadata) &&\n !options.skipDefaultFields?.has(fieldName) &&\n Object.prototype.hasOwnProperty.call(definition, \"default\")\n ) {\n itemMetadata[fieldName] = cloneFieldValue(definition.default);\n }\n\n const currentValue = itemMetadata[fieldName];\n if (currentValue === undefined) {\n continue;\n }\n const expectedType = normalizeFieldType(definition.type);\n if (expectedType && !isValidFieldType(currentValue, expectedType)) {\n throw new TypeError(\n `Item field \"${fieldName}\" must be of type ${expectedType}`,\n );\n }\n\n const allowedValues = Array.isArray(definition.values)\n ? definition.values\n : undefined;\n if (!isAllowedFieldValue(currentValue, allowedValues)) {\n throw new TypeError(\n `Item field \"${fieldName}\" must match one of the configured allowed values`,\n );\n }\n }\n }\n}\n","/**\n * @module core/shared/memo\n *\n * Provides shared primitives and utilities for capped memoization maps.\n */\n\n/** Drop the oldest-inserted half of a memo map (Map preserves insertion order), so a size-cap hit mid-scan keeps the newest-inserted half instead of cold-starting the memo. Callers that re-insert entries on hit (the envelope memo) get LRU eviction; the scalar comparator memos evict purely by insertion order. */\nexport function evictOldestMemoEntries<Value>(memo: Map<string, Value>): void {\n let remaining = Math.ceil(memo.size / 2);\n for (const key of memo.keys()) {\n if (remaining === 0) {\n return;\n }\n memo.delete(key);\n remaining -= 1;\n }\n}\n"],"names":["fs","path","path","pathExists","path","fs","path","path","fs","path","path","normalized","path"],"mappings":";;;AAKA,YAAY,QAAQ;AACpB,OAAO,UAAU;AACjB,OAAO,YAAY;AAEnB,IAAM,iCAAiC,CAAC,IAAI,IAAI,IAAI,GAAG;AAGvD,eAAsB,UAAU,SAAe;AAC7C,QAAS,SAAM,SAAS,EAAE,WAAW,KAAI,CAAE;AAC7C;AAGA,eAAsB,WAAW,YAAkB;AACjD,MAAI;AACF,UAAS,UAAO,UAAU;A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AAM,2BAA2B;EACtC;EACA;EACA;EACA;EACA;EACA;;AAIK,IAAM,sBAAsB;EACjC,GAAG;EACH,GAAG;;AAIE,IAAM,iBAAkD;EAC7D,MAAM;EACN,SAAS;EACT,MAAM;EACN,OAAO;EACP,OAAO;EACP,UAAU;EACV,OAAO;EACP,UAAU;EACV,WAAW;EACX,SAAS;EACT,MAAM;;AAID,IAAM,0BAAiD;EAC5D;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAMK,IAAM,6BAGT;EACF,SAAS;IACP,uBAAuB;IACvB,qBAAqB;IACrB,0BAA0B;IAC1B,sBAAsB;IACtB,kBAAkB;IAClB,kBAAkB;IAClB,+BAA+B;;EAEjC,SAAS;IACP,uBAAuB;IACvB,qBAAqB;IACrB,0BAA0B;IAC1B,sBAAsB;IACtB,kBAAkB;IAClB,kBAAkB;IAClB,+BAA+B;;EAEjC,QAAQ;IACN,uBAAuB;IACvB,qBAAqB;IACrB,0BAA0B;IAC1B,sBAAsB;IACtB,kBAAkB;IAClB,kBAAkB;IAClB,+BAA+B;;;AAK5B,IAAM,iDAAiD;EAC5D;EACA;EACA;EACA;;AAIK,IAAM,wDAAwD;EACnE,gBAAgB;IACd;IACA;;EAEF,YAAY;IACV;IACA;IACA;IACA;;EAEF,eAAe;IACb;IACA;IACA;;;AAIJ,SAAS,mBACP,QAAgC;AAEhC,SAAO,SAAS,CAAC,GAAG,MAAM,IAAI;AAChC;AAGO,IAAM,oBAAgC;EAC3C,SAAS;EACT,WAAW;EAC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,uBAAuB,WAAW,MAAM;IAChD,SAAS,QAAQ,SAAS,IAAI,UAAU;IACxC,wBAAwB,4BACtB,WAAW,wBACX,uBAAuB;IAEzB,6BAA6B,4BAC3B,WAAW,6BACX,4BAA4B;IAE9B,SAAS,aAAa,oBAAoB;IAC1C,yBAAyB,2BACrB,wBACA;;AAER;;;AChLO,IAAM,iCAAiC;EAC5C;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAIK,IAAM,sCAAsC;EACjD;EACA;EACA;EACA;EACA;EACA;EACA;;AASK,IAAM,sCAAsC;EACjD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGF,IAAM,6BAA6B;EACjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGF,IAAM,6BAA6B;EACjC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAGF,IAAM,gCAAwD;EAC5D,gBAAgB;EAChB,cAAc;EACd,qBAAqB;EACrB,mBAAmB;EACnB,UAAU;EACV,uBAAuB;EACvB,qBAAqB;EACrB,IAAI;EACJ,uBAAuB;EACvB,qBAAqB;EACrB,MAAM;EACN,WAAW;EACX,SAAS;EACT,cAAc;EACd,YAAY;EACZ,kBAAkB;EAClB,gBAAgB;EAChB,gBAAgB;EAChB,cAAc;EACd,eAAe;EACf,aAAa;EACb,mBAAmB;EACnB,iBAAiB;EACjB,iBAAiB;EACjB,eAAe;EACf,oBAAoB;EACpB,kBAAkB;EAClB,iBAAiB;EACjB,eAAe;EACf,mBAAmB;EACnB,iBAAiB;EACj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