@unbrained/pm-cli 2026.7.20 → 2026.7.21

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 (421) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +11 -0
  3. package/dist/cli/commander-usage.d.ts +1 -1
  4. package/dist/cli/commander-usage.js +5 -5
  5. package/dist/cli/commander-usage.js.map +1 -1
  6. package/dist/cli/commands/completion.js +13 -5
  7. package/dist/cli/commands/completion.js.map +1 -1
  8. package/dist/cli/commands/contracts.js +4 -3
  9. package/dist/cli/commands/contracts.js.map +1 -1
  10. package/dist/cli/error-guidance.d.ts +2 -0
  11. package/dist/cli/error-guidance.js +7 -2
  12. package/dist/cli/error-guidance.js.map +1 -1
  13. package/dist/cli/main.d.ts +1 -5
  14. package/dist/cli/main.js +12 -50
  15. package/dist/cli/main.js.map +1 -1
  16. package/dist/cli/register-list-query.js +13 -3
  17. package/dist/cli/register-list-query.js.map +1 -1
  18. package/dist/cli/register-mutation.js +45 -3
  19. package/dist/cli/register-mutation.js.map +1 -1
  20. package/dist/cli/register-structured-mutation.d.ts +14 -0
  21. package/dist/cli/register-structured-mutation.js +62 -0
  22. package/dist/cli/register-structured-mutation.js.map +1 -0
  23. package/dist/cli/registration-helpers.js +5 -3
  24. package/dist/cli/registration-helpers.js.map +1 -1
  25. package/dist/cli-bundle/bundle-manifest.json +280 -296
  26. package/dist/cli-bundle/chunks/{append-E6V54WOQ.js → append-7OVFYR3C.js} +3 -3
  27. package/dist/cli-bundle/chunks/{append-NNJ3EFIT.js → append-DFETHAZL.js} +3 -3
  28. package/dist/cli-bundle/chunks/{chunk-C3KD7U3T.js → chunk-2L6ZP22J.js} +241 -10
  29. package/dist/cli-bundle/chunks/chunk-2L6ZP22J.js.map +7 -0
  30. package/dist/cli-bundle/chunks/{chunk-KZEANWJS.js → chunk-4PUUNQDV.js} +98 -30
  31. package/dist/cli-bundle/chunks/chunk-4PUUNQDV.js.map +7 -0
  32. package/dist/cli-bundle/chunks/{chunk-RDV4ZFYS.js → chunk-4QOB7L7I.js} +7 -9
  33. package/dist/cli-bundle/chunks/{chunk-RDV4ZFYS.js.map → chunk-4QOB7L7I.js.map} +1 -1
  34. package/dist/cli-bundle/chunks/{chunk-3LPFHE3P.js → chunk-4QSQ6XDK.js} +62 -20
  35. package/dist/cli-bundle/chunks/chunk-4QSQ6XDK.js.map +1 -0
  36. package/dist/cli-bundle/chunks/{chunk-QJKL5PHS.js → chunk-7656MAUL.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-3AO5VSDR.js → chunk-7RW4JCU2.js} +328 -6
  38. package/dist/cli-bundle/chunks/chunk-7RW4JCU2.js.map +7 -0
  39. package/dist/cli-bundle/chunks/{chunk-X6K5XTTN.js → chunk-7W2UAXXT.js} +5 -5
  40. package/dist/cli-bundle/chunks/{chunk-SSKOQNMS.js → chunk-ABWCF646.js} +9 -11
  41. package/dist/cli-bundle/chunks/{chunk-SSKOQNMS.js.map → chunk-ABWCF646.js.map} +1 -1
  42. package/dist/cli-bundle/chunks/{chunk-WVA4DVNV.js → chunk-ADBTSVGK.js} +71 -33
  43. package/dist/cli-bundle/chunks/chunk-ADBTSVGK.js.map +7 -0
  44. package/dist/cli-bundle/chunks/{chunk-J4FBIFU6.js → chunk-AELMUANP.js} +12 -6
  45. package/dist/cli-bundle/chunks/chunk-AELMUANP.js.map +1 -0
  46. package/dist/cli-bundle/chunks/{chunk-4F6BWJ4J.js → chunk-AMJPSANK.js} +57 -36
  47. package/dist/cli-bundle/chunks/chunk-AMJPSANK.js.map +7 -0
  48. package/dist/cli-bundle/chunks/{chunk-6VIJ7UA5.js → chunk-AS4SAZ5R.js} +850 -819
  49. package/dist/cli-bundle/chunks/chunk-AS4SAZ5R.js.map +7 -0
  50. package/dist/cli-bundle/chunks/{chunk-SG74J6MV.js → chunk-ATBCUC7Y.js} +574 -5
  51. package/dist/cli-bundle/chunks/chunk-ATBCUC7Y.js.map +1 -0
  52. package/dist/cli-bundle/chunks/{chunk-5OK4UGFV.js → chunk-BXNDKOR2.js} +3 -3
  53. package/dist/cli-bundle/chunks/{chunk-KSPWRNVP.js → chunk-CPX275C6.js} +2 -2
  54. package/dist/cli-bundle/chunks/{chunk-JH2ZSLO3.js → chunk-DZRV2OPA.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-L7BH7IWU.js → chunk-E5XMKOSB.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-CQTQKUUV.js → chunk-EWJWSNRU.js} +3 -3
  57. package/dist/cli-bundle/chunks/{chunk-DAQ45GCS.js → chunk-F2LBF7XJ.js} +22 -15
  58. package/dist/cli-bundle/chunks/chunk-F2LBF7XJ.js.map +7 -0
  59. package/dist/cli-bundle/chunks/{chunk-6XMUURSS.js → chunk-FJIFFBJX.js} +64 -33
  60. package/dist/cli-bundle/chunks/chunk-FJIFFBJX.js.map +1 -0
  61. package/dist/cli-bundle/chunks/{chunk-E7ICD63T.js → chunk-FO6OSVEN.js} +4 -6
  62. package/dist/cli-bundle/chunks/{chunk-E7ICD63T.js.map → chunk-FO6OSVEN.js.map} +1 -1
  63. package/dist/cli-bundle/chunks/{chunk-3MCTMJXI.js → chunk-FPBMLYPI.js} +2 -2
  64. package/dist/cli-bundle/chunks/{chunk-UZDQXNUB.js → chunk-FSE2IKJQ.js} +46 -5
  65. package/dist/cli-bundle/chunks/chunk-FSE2IKJQ.js.map +1 -0
  66. package/dist/cli-bundle/chunks/{chunk-IX677TRO.js → chunk-GKX4NJ7U.js} +8 -10
  67. package/dist/cli-bundle/chunks/{chunk-IX677TRO.js.map → chunk-GKX4NJ7U.js.map} +1 -1
  68. package/dist/cli-bundle/chunks/{chunk-DVDBQA3B.js → chunk-GTK4DTEW.js} +5 -5
  69. package/dist/cli-bundle/chunks/chunk-H7EAER5L.js +974 -0
  70. package/dist/cli-bundle/chunks/chunk-H7EAER5L.js.map +1 -0
  71. package/dist/cli-bundle/chunks/{chunk-5UX66S6U.js → chunk-ICDAQ4TD.js} +316 -8
  72. package/dist/cli-bundle/chunks/chunk-ICDAQ4TD.js.map +1 -0
  73. package/dist/cli-bundle/chunks/{chunk-YQQNAKW3.js → chunk-JFD5LPMI.js} +6 -8
  74. package/dist/cli-bundle/chunks/{chunk-YQQNAKW3.js.map → chunk-JFD5LPMI.js.map} +1 -1
  75. package/dist/cli-bundle/chunks/{chunk-QANSTTC7.js → chunk-JXCW2TI2.js} +6 -8
  76. package/dist/cli-bundle/chunks/{chunk-QANSTTC7.js.map → chunk-JXCW2TI2.js.map} +1 -1
  77. package/dist/cli-bundle/chunks/{chunk-GSJSM5BJ.js → chunk-K36WV5J6.js} +76 -13
  78. package/dist/cli-bundle/chunks/chunk-K36WV5J6.js.map +1 -0
  79. package/dist/cli-bundle/chunks/{chunk-GVI6FAFG.js → chunk-K55VMLSS.js} +7 -5
  80. package/dist/cli-bundle/chunks/chunk-K55VMLSS.js.map +7 -0
  81. package/dist/cli-bundle/chunks/{chunk-GIQSU6S2.js → chunk-KBLZ3AA5.js} +2 -2
  82. package/dist/cli-bundle/chunks/{chunk-XJF7CDNH.js → chunk-KH44WBAT.js} +2 -2
  83. package/dist/cli-bundle/chunks/{chunk-GV2262OF.js → chunk-LAV26CQG.js} +2 -2
  84. package/dist/cli-bundle/chunks/{chunk-VDO2JMD4.js → chunk-LVC72YRD.js} +2 -2
  85. package/dist/cli-bundle/chunks/{chunk-3VY6MIEO.js → chunk-LZYP423P.js} +35 -6
  86. package/dist/cli-bundle/chunks/chunk-LZYP423P.js.map +7 -0
  87. package/dist/cli-bundle/chunks/{chunk-ZYPFOO3L.js → chunk-MATHDCGG.js} +3 -3
  88. package/dist/cli-bundle/chunks/{chunk-OV7MSW3I.js → chunk-MWQ2HC2A.js} +99 -31
  89. package/dist/cli-bundle/chunks/chunk-MWQ2HC2A.js.map +1 -0
  90. package/dist/cli-bundle/chunks/{chunk-NHT3F4WZ.js → chunk-NUF7ROFH.js} +840 -816
  91. package/dist/cli-bundle/chunks/chunk-NUF7ROFH.js.map +1 -0
  92. package/dist/cli-bundle/chunks/{chunk-AOEOYL3S.js → chunk-O4BCOJTZ.js} +3 -3
  93. package/dist/cli-bundle/chunks/{chunk-RJO3YAFM.js → chunk-OCUBRA6D.js} +2 -2
  94. package/dist/cli-bundle/chunks/{chunk-5IZJWSDB.js → chunk-OG5DVFMA.js} +22 -15
  95. package/dist/cli-bundle/chunks/chunk-OG5DVFMA.js.map +1 -0
  96. package/dist/cli-bundle/chunks/{chunk-I577UHC7.js → chunk-OR42SO64.js} +2 -2
  97. package/dist/cli-bundle/chunks/{chunk-ZOJ3LR7O.js → chunk-OY7DMU5P.js} +2 -2
  98. package/dist/cli-bundle/chunks/{chunk-HEWM6CEN.js → chunk-P7MTHPJQ.js} +50 -9
  99. package/dist/cli-bundle/chunks/chunk-P7MTHPJQ.js.map +7 -0
  100. package/dist/cli-bundle/chunks/{chunk-2BO4CA46.js → chunk-PFNHX655.js} +236 -12
  101. package/dist/cli-bundle/chunks/{chunk-2BO4CA46.js.map → chunk-PFNHX655.js.map} +1 -1
  102. package/dist/cli-bundle/chunks/{chunk-ZV2NTVMJ.js → chunk-PONKZPCJ.js} +2 -2
  103. package/dist/cli-bundle/chunks/{chunk-THAOZG4U.js → chunk-PQSEQD6E.js} +8 -6
  104. package/dist/cli-bundle/chunks/chunk-PQSEQD6E.js.map +1 -0
  105. package/dist/cli-bundle/chunks/chunk-PWDEHT3L.js +991 -0
  106. package/dist/cli-bundle/chunks/chunk-PWDEHT3L.js.map +7 -0
  107. package/dist/cli-bundle/chunks/{chunk-UX6SSO2I.js → chunk-PZC2FUOQ.js} +2 -2
  108. package/dist/cli-bundle/chunks/{chunk-WUVEBQW6.js → chunk-QG4GFLQ6.js} +3 -5
  109. package/dist/cli-bundle/chunks/{chunk-WUVEBQW6.js.map → chunk-QG4GFLQ6.js.map} +1 -1
  110. package/dist/cli-bundle/chunks/{chunk-VQIHNHMJ.js → chunk-QIH77CAG.js} +2 -2
  111. package/dist/cli-bundle/chunks/{chunk-R3EWPG4A.js → chunk-QJIKE24M.js} +2 -2
  112. package/dist/cli-bundle/chunks/{chunk-QLZ643FM.js → chunk-QOOTOD3W.js} +10 -12
  113. package/dist/cli-bundle/chunks/{chunk-QLZ643FM.js.map → chunk-QOOTOD3W.js.map} +1 -1
  114. package/dist/cli-bundle/chunks/{chunk-MYSS5H2A.js → chunk-R3P6FZJW.js} +5 -7
  115. package/dist/cli-bundle/chunks/{chunk-MYSS5H2A.js.map → chunk-R3P6FZJW.js.map} +1 -1
  116. package/dist/cli-bundle/chunks/{chunk-G3COA6GS.js → chunk-RNPZYNHS.js} +56 -35
  117. package/dist/cli-bundle/chunks/chunk-RNPZYNHS.js.map +1 -0
  118. package/dist/cli-bundle/chunks/{chunk-T44FMVRL.js → chunk-RPESLSO5.js} +62 -20
  119. package/dist/cli-bundle/chunks/chunk-RPESLSO5.js.map +7 -0
  120. package/dist/cli-bundle/chunks/{chunk-INSTSQNZ.js → chunk-SY4SFZSD.js} +595 -3
  121. package/dist/cli-bundle/chunks/chunk-SY4SFZSD.js.map +7 -0
  122. package/dist/cli-bundle/chunks/{chunk-HB3P4M52.js → chunk-TRSHFPRZ.js} +2 -2
  123. package/dist/cli-bundle/chunks/{chunk-HRW7GF6T.js → chunk-UCBDQI5E.js} +2 -2
  124. package/dist/cli-bundle/chunks/{chunk-4U4Z6AHI.js → chunk-V22ZPOKN.js} +2 -2
  125. package/dist/cli-bundle/chunks/{chunk-JM6YAXTR.js → chunk-VHXHVTUU.js} +2 -2
  126. package/dist/cli-bundle/chunks/{chunk-LPEYZRUR.js → chunk-VJQG4BIM.js} +35 -6
  127. package/dist/cli-bundle/chunks/chunk-VJQG4BIM.js.map +1 -0
  128. package/dist/cli-bundle/chunks/{chunk-D6NXDNP3.js → chunk-VLRGDBLY.js} +2 -2
  129. package/dist/cli-bundle/chunks/{chunk-JAPE62Y5.js → chunk-VNTCM3VW.js} +3 -3
  130. package/dist/cli-bundle/chunks/{chunk-FDHPAVVB.js → chunk-VXOOB6YX.js} +2 -2
  131. package/dist/cli-bundle/chunks/{chunk-GFQP7HAZ.js → chunk-VZIZB6QH.js} +3 -5
  132. package/dist/cli-bundle/chunks/{chunk-GFQP7HAZ.js.map → chunk-VZIZB6QH.js.map} +1 -1
  133. package/dist/cli-bundle/chunks/{chunk-HQ3SB4CN.js → chunk-X3W65QK3.js} +2 -2
  134. package/dist/cli-bundle/chunks/{chunk-RZJLNXFG.js → chunk-XJTABV3X.js} +3 -3
  135. package/dist/cli-bundle/chunks/{chunk-GVT754PX.js → chunk-YCIUJJOD.js} +11 -5
  136. package/dist/cli-bundle/chunks/chunk-YCIUJJOD.js.map +7 -0
  137. package/dist/cli-bundle/chunks/{chunk-IJNK6WW2.js → chunk-Z75ONV25.js} +75 -12
  138. package/dist/cli-bundle/chunks/chunk-Z75ONV25.js.map +7 -0
  139. package/dist/cli-bundle/chunks/{chunk-4L23AGQ7.js → chunk-Z7VWXXJM.js} +5 -7
  140. package/dist/cli-bundle/chunks/{chunk-4L23AGQ7.js.map → chunk-Z7VWXXJM.js.map} +1 -1
  141. package/dist/cli-bundle/chunks/{chunk-YBT7O4KT.js → chunk-ZTVA4KLN.js} +4 -6
  142. package/dist/cli-bundle/chunks/{chunk-YBT7O4KT.js.map → chunk-ZTVA4KLN.js.map} +1 -1
  143. package/dist/cli-bundle/chunks/{chunk-TYHJDFYW.js → chunk-ZVZGXPQ5.js} +2 -2
  144. package/dist/cli-bundle/chunks/{close-many-SDA426VT.js → close-many-5RZXVN4J.js} +5 -6
  145. package/dist/cli-bundle/chunks/{close-many-UTZANOCQ.js → close-many-RZVTUGBG.js} +5 -6
  146. package/dist/cli-bundle/chunks/{comments-LZN6FXXC.js → comments-TPU7QRBL.js} +4 -4
  147. package/dist/cli-bundle/chunks/{comments-VBQ345ND.js → comments-Z4KV6FU3.js} +4 -4
  148. package/dist/cli-bundle/chunks/{create-GG4RBCGC.js → create-EIFBIVNQ.js} +6 -6
  149. package/dist/cli-bundle/chunks/{create-JBC5KUW6.js → create-RGSPN5GD.js} +6 -6
  150. package/dist/cli-bundle/chunks/{deps-FI4O6NQS.js → deps-UH5EQQUY.js} +3 -3
  151. package/dist/cli-bundle/chunks/{deps-DELOO4TL.js → deps-YG7UF3VR.js} +3 -3
  152. package/dist/cli-bundle/chunks/{docs-6Z2MP526.js → docs-G32TK6XS.js} +4 -4
  153. package/dist/cli-bundle/chunks/{docs-2UYBP5D6.js → docs-JWWNRC27.js} +4 -4
  154. package/dist/cli-bundle/chunks/{files-HKEAN5MA.js → files-3H32UQ4K.js} +4 -4
  155. package/dist/cli-bundle/chunks/{files-HEUGSJZL.js → files-4ALMCSKB.js} +4 -4
  156. package/dist/cli-bundle/chunks/{history-compact-7NDVP3PT.js → history-compact-77BT2LUB.js} +3 -4
  157. package/dist/cli-bundle/chunks/{history-compact-65YVN5DB.js → history-compact-VCKGTX64.js} +3 -4
  158. package/dist/cli-bundle/chunks/{history-redact-7YBL4XSG.js → history-redact-LJPZPNFA.js} +2 -3
  159. package/dist/cli-bundle/chunks/{history-redact-IZGNJBU4.js → history-redact-PWTTJ3XS.js} +2 -3
  160. package/dist/cli-bundle/chunks/{history-repair-7M4PYQUH.js → history-repair-I7CBNCV3.js} +5 -6
  161. package/dist/cli-bundle/chunks/{history-repair-GNGETJLI.js → history-repair-YTDZRK5E.js} +5 -6
  162. package/dist/cli-bundle/chunks/{learnings-3YXDRWFT.js → learnings-CYNOICKR.js} +4 -4
  163. package/dist/cli-bundle/chunks/{learnings-ALC6IMNL.js → learnings-KTYW3AL7.js} +4 -4
  164. package/dist/cli-bundle/chunks/{notes-7JMLQ447.js → notes-FGO63FXL.js} +4 -4
  165. package/dist/cli-bundle/chunks/{notes-JFCLTC5C.js → notes-ZERD3KB2.js} +4 -4
  166. package/dist/cli-bundle/chunks/{plan-T3XB3WTK.js → plan-OFJUBIM5.js} +7 -7
  167. package/dist/cli-bundle/chunks/{plan-KOIPWVOZ.js → plan-SGCDDTYR.js} +7 -7
  168. package/dist/cli-bundle/chunks/{profile-OILJHKUW.js → profile-3THJPIQY.js} +4 -5
  169. package/dist/cli-bundle/chunks/{profile-RJXA7PGS.js → profile-XEZAMMBW.js} +4 -5
  170. package/dist/cli-bundle/chunks/{register-list-query-CFVG75P3.js → register-list-query-BR435Q2H.js} +19 -16
  171. package/dist/cli-bundle/chunks/register-list-query-BR435Q2H.js.map +1 -0
  172. package/dist/cli-bundle/chunks/{register-list-query-E7UVY4TN.js → register-list-query-RWTWLOBE.js} +18 -15
  173. package/dist/cli-bundle/chunks/register-list-query-RWTWLOBE.js.map +7 -0
  174. package/dist/cli-bundle/chunks/{register-mutation-IQ55E25C.js → register-mutation-HLWC2WNP.js} +167 -31
  175. package/dist/cli-bundle/chunks/register-mutation-HLWC2WNP.js.map +1 -0
  176. package/dist/cli-bundle/chunks/{register-mutation-4VJTXBZW.js → register-mutation-ZJX5AZM5.js} +173 -30
  177. package/dist/cli-bundle/chunks/register-mutation-ZJX5AZM5.js.map +7 -0
  178. package/dist/cli-bundle/chunks/{register-operations-AR7RMX4W.js → register-operations-744YBJMV.js} +23 -25
  179. package/dist/cli-bundle/chunks/{register-operations-AR7RMX4W.js.map → register-operations-744YBJMV.js.map} +1 -1
  180. package/dist/cli-bundle/chunks/{register-operations-NOLZGORC.js → register-operations-UEBJH6AN.js} +21 -23
  181. package/dist/cli-bundle/chunks/{register-operations-NOLZGORC.js.map → register-operations-UEBJH6AN.js.map} +1 -1
  182. package/dist/cli-bundle/chunks/{register-setup-EYZ7VTPZ.js → register-setup-5DA4UZXI.js} +7 -8
  183. package/dist/cli-bundle/chunks/{register-setup-EYZ7VTPZ.js.map → register-setup-5DA4UZXI.js.map} +1 -1
  184. package/dist/cli-bundle/chunks/{register-setup-BB77VUEE.js → register-setup-6H25M3BH.js} +9 -10
  185. package/dist/cli-bundle/chunks/{register-setup-BB77VUEE.js.map → register-setup-6H25M3BH.js.map} +1 -1
  186. package/dist/cli-bundle/chunks/{restore-ZH65GZFB.js → restore-6TDVSATY.js} +4 -5
  187. package/dist/cli-bundle/chunks/{restore-L6IAGOD7.js → restore-RSL7C7LO.js} +4 -5
  188. package/dist/cli-bundle/chunks/{schema-4ERWM5QJ.js → schema-HFXFSGPG.js} +2 -3
  189. package/dist/cli-bundle/chunks/{schema-55DL3Q52.js → schema-TPVTIJPO.js} +2 -3
  190. package/dist/cli-bundle/chunks/{update-FW6FKDOP.js → update-LJZCL5SI.js} +7 -7
  191. package/dist/cli-bundle/chunks/{update-TJHSPRPT.js → update-SIA7LH5Y.js} +7 -7
  192. package/dist/cli-bundle/chunks/{update-many-PWXX5WHO.js → update-many-BDBZVGQL.js} +11 -12
  193. package/dist/cli-bundle/chunks/{update-many-NNALYQCN.js → update-many-MOY3A5B3.js} +11 -12
  194. package/dist/cli-bundle/main.js +60 -85
  195. package/dist/cli-bundle/main.js.map +2 -2
  196. package/dist/cli-bundle/sdk-runtime.js +37 -37
  197. package/dist/cli-bundle/sdk.js +126 -291
  198. package/dist/cli-bundle/sdk.js.map +4 -4
  199. package/dist/core/item/parse.d.ts +1 -1
  200. package/dist/core/item/parse.js +13 -7
  201. package/dist/core/item/parse.js.map +1 -1
  202. package/dist/core/output/mutation-projection.d.ts +2 -0
  203. package/dist/core/output/mutation-projection.js +33 -2
  204. package/dist/core/output/mutation-projection.js.map +1 -1
  205. package/dist/core/output/output.d.ts +4 -0
  206. package/dist/core/output/output.js +18 -13
  207. package/dist/core/output/output.js.map +1 -1
  208. package/dist/core/shared/command-types.d.ts +4 -0
  209. package/dist/core/shared/command-types.js +2 -2
  210. package/dist/core/shared/command-types.js.map +1 -1
  211. package/dist/mcp/server.js +39 -4
  212. package/dist/mcp/server.js.map +1 -1
  213. package/dist/mcp/tool-definitions.js +45 -4
  214. package/dist/mcp/tool-definitions.js.map +1 -1
  215. package/dist/sdk/cli-bootstrap.d.ts +2 -0
  216. package/dist/sdk/cli-bootstrap.js +20 -27
  217. package/dist/sdk/cli-bootstrap.js.map +1 -1
  218. package/dist/sdk/cli-contracts/enum-contracts.d.ts +2 -2
  219. package/dist/sdk/cli-contracts/enum-contracts.js +7 -2
  220. package/dist/sdk/cli-contracts/enum-contracts.js.map +1 -1
  221. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  222. package/dist/sdk/cli-contracts/flag-contracts.js +21 -2
  223. package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
  224. package/dist/sdk/cli-contracts/tool-option-contracts.js +10 -2
  225. package/dist/sdk/cli-contracts/tool-option-contracts.js.map +1 -1
  226. package/dist/sdk/cli-contracts/tool-parameter-tables.js +16 -3
  227. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  228. package/dist/sdk/cli-contracts/tool-schema.js +6 -2
  229. package/dist/sdk/cli-contracts/tool-schema.js.map +1 -1
  230. package/dist/sdk/cli-contracts.d.ts +1 -1
  231. package/dist/sdk/cli-contracts.js +3 -3
  232. package/dist/sdk/cli-contracts.js.map +1 -1
  233. package/dist/sdk/cli-program.js +4 -2
  234. package/dist/sdk/cli-program.js.map +1 -1
  235. package/dist/sdk/dependencies.d.ts +3 -2
  236. package/dist/sdk/dependencies.js +13 -12
  237. package/dist/sdk/dependencies.js.map +1 -1
  238. package/dist/sdk/error-runtime.d.ts +10 -0
  239. package/dist/sdk/error-runtime.js +59 -0
  240. package/dist/sdk/error-runtime.js.map +1 -0
  241. package/dist/sdk/graph/analytics.d.ts +9 -0
  242. package/dist/sdk/graph/analytics.js +24 -13
  243. package/dist/sdk/graph/analytics.js.map +1 -1
  244. package/dist/sdk/graph/assembly.d.ts +39 -0
  245. package/dist/sdk/graph/assembly.js +92 -12
  246. package/dist/sdk/graph/assembly.js.map +1 -1
  247. package/dist/sdk/graph/cache.d.ts +4 -1
  248. package/dist/sdk/graph/cache.js +17 -4
  249. package/dist/sdk/graph/cache.js.map +1 -1
  250. package/dist/sdk/graph/centrality.d.ts +82 -0
  251. package/dist/sdk/graph/centrality.js +259 -0
  252. package/dist/sdk/graph/centrality.js.map +1 -0
  253. package/dist/sdk/graph/durable-cache.d.ts +71 -0
  254. package/dist/sdk/graph/durable-cache.js +205 -0
  255. package/dist/sdk/graph/durable-cache.js.map +1 -0
  256. package/dist/sdk/graph/governance.d.ts +69 -1
  257. package/dist/sdk/graph/governance.js +143 -35
  258. package/dist/sdk/graph/governance.js.map +1 -1
  259. package/dist/sdk/graph/index.d.ts +7 -4
  260. package/dist/sdk/graph/index.js +8 -5
  261. package/dist/sdk/graph/index.js.map +1 -1
  262. package/dist/sdk/graph/mutation-advisory.d.ts +35 -4
  263. package/dist/sdk/graph/mutation-advisory.js +124 -35
  264. package/dist/sdk/graph/mutation-advisory.js.map +1 -1
  265. package/dist/sdk/graph/remediation.js +12 -2
  266. package/dist/sdk/graph/remediation.js.map +1 -1
  267. package/dist/sdk/graph/run.d.ts +133 -2
  268. package/dist/sdk/graph/run.js +217 -8
  269. package/dist/sdk/graph/run.js.map +1 -1
  270. package/dist/sdk/graph/scheduling.d.ts +59 -0
  271. package/dist/sdk/graph/scheduling.js +125 -0
  272. package/dist/sdk/graph/scheduling.js.map +1 -0
  273. package/dist/sdk/graph/traversal.d.ts +11 -0
  274. package/dist/sdk/graph/traversal.js +16 -2
  275. package/dist/sdk/graph/traversal.js.map +1 -1
  276. package/dist/sdk/index.d.ts +4 -0
  277. package/dist/sdk/index.js +6 -2
  278. package/dist/sdk/index.js.map +1 -1
  279. package/dist/sdk/runtime-input.js +7 -2
  280. package/dist/sdk/runtime-input.js.map +1 -1
  281. package/dist/sdk/runtime-primitives.d.ts +10 -0
  282. package/dist/sdk/runtime-primitives.js +14 -0
  283. package/dist/sdk/runtime-primitives.js.map +1 -0
  284. package/dist/sdk/runtime.d.ts +15 -0
  285. package/dist/sdk/runtime.js +16 -3
  286. package/dist/sdk/runtime.js.map +1 -1
  287. package/dist/sdk/structured-mutations.d.ts +21 -0
  288. package/dist/sdk/structured-mutations.js +375 -0
  289. package/dist/sdk/structured-mutations.js.map +1 -0
  290. package/docs/COMMANDS.md +85 -5
  291. package/docs/RELATIONSHIP_GRAPH.md +48 -7
  292. package/docs/SDK.md +78 -3
  293. package/marketplace.json +2 -2
  294. package/package.json +1 -1
  295. package/packages/pm-beads/package.json +1 -1
  296. package/packages/pm-calendar/package.json +1 -1
  297. package/packages/pm-command-kit/package.json +1 -1
  298. package/packages/pm-governance-audit/package.json +1 -1
  299. package/packages/pm-guide-shell/package.json +1 -1
  300. package/packages/pm-kanban/package.json +1 -1
  301. package/packages/pm-lifecycle-hooks/package.json +1 -1
  302. package/packages/pm-linked-test-adapters/package.json +1 -1
  303. package/packages/pm-search-advanced/package.json +1 -1
  304. package/packages/pm-templates/package.json +1 -1
  305. package/packages/pm-todos/package.json +1 -1
  306. package/packages/pm-vcs/package.json +1 -1
  307. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  308. package/plugins/pm-claude/README.md +5 -3
  309. package/plugins/pm-claude/commands/pm-init.md +1 -1
  310. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  311. package/dist/cli-bundle/chunks/chunk-3AO5VSDR.js.map +0 -7
  312. package/dist/cli-bundle/chunks/chunk-3LPFHE3P.js.map +0 -1
  313. package/dist/cli-bundle/chunks/chunk-3VY6MIEO.js.map +0 -7
  314. package/dist/cli-bundle/chunks/chunk-4F6BWJ4J.js.map +0 -7
  315. package/dist/cli-bundle/chunks/chunk-5IZJWSDB.js.map +0 -1
  316. package/dist/cli-bundle/chunks/chunk-5UX66S6U.js.map +0 -1
  317. package/dist/cli-bundle/chunks/chunk-6C2ZZX5Z.js +0 -286
  318. package/dist/cli-bundle/chunks/chunk-6C2ZZX5Z.js.map +0 -1
  319. package/dist/cli-bundle/chunks/chunk-6VIJ7UA5.js.map +0 -7
  320. package/dist/cli-bundle/chunks/chunk-6XMUURSS.js.map +0 -1
  321. package/dist/cli-bundle/chunks/chunk-C3KD7U3T.js.map +0 -7
  322. package/dist/cli-bundle/chunks/chunk-CFHAODHQ.js +0 -334
  323. package/dist/cli-bundle/chunks/chunk-CFHAODHQ.js.map +0 -1
  324. package/dist/cli-bundle/chunks/chunk-DAQ45GCS.js.map +0 -7
  325. package/dist/cli-bundle/chunks/chunk-E6LEMURX.js +0 -249
  326. package/dist/cli-bundle/chunks/chunk-E6LEMURX.js.map +0 -7
  327. package/dist/cli-bundle/chunks/chunk-G3COA6GS.js.map +0 -1
  328. package/dist/cli-bundle/chunks/chunk-GSJSM5BJ.js.map +0 -1
  329. package/dist/cli-bundle/chunks/chunk-GVI6FAFG.js.map +0 -7
  330. package/dist/cli-bundle/chunks/chunk-GVT754PX.js.map +0 -7
  331. package/dist/cli-bundle/chunks/chunk-HEWM6CEN.js.map +0 -7
  332. package/dist/cli-bundle/chunks/chunk-IJNK6WW2.js.map +0 -7
  333. package/dist/cli-bundle/chunks/chunk-INSTSQNZ.js.map +0 -7
  334. package/dist/cli-bundle/chunks/chunk-J4FBIFU6.js.map +0 -1
  335. package/dist/cli-bundle/chunks/chunk-KZEANWJS.js.map +0 -7
  336. package/dist/cli-bundle/chunks/chunk-LPEYZRUR.js.map +0 -1
  337. package/dist/cli-bundle/chunks/chunk-NHT3F4WZ.js.map +0 -1
  338. package/dist/cli-bundle/chunks/chunk-OV7MSW3I.js.map +0 -1
  339. package/dist/cli-bundle/chunks/chunk-P7JTWYLH.js +0 -246
  340. package/dist/cli-bundle/chunks/chunk-P7JTWYLH.js.map +0 -1
  341. package/dist/cli-bundle/chunks/chunk-R5U2VZ3K.js +0 -344
  342. package/dist/cli-bundle/chunks/chunk-R5U2VZ3K.js.map +0 -7
  343. package/dist/cli-bundle/chunks/chunk-SG74J6MV.js.map +0 -1
  344. package/dist/cli-bundle/chunks/chunk-T44FMVRL.js.map +0 -7
  345. package/dist/cli-bundle/chunks/chunk-THAOZG4U.js.map +0 -1
  346. package/dist/cli-bundle/chunks/chunk-UQLXSG72.js +0 -289
  347. package/dist/cli-bundle/chunks/chunk-UQLXSG72.js.map +0 -7
  348. package/dist/cli-bundle/chunks/chunk-UZDQXNUB.js.map +0 -1
  349. package/dist/cli-bundle/chunks/chunk-WVA4DVNV.js.map +0 -7
  350. package/dist/cli-bundle/chunks/register-list-query-CFVG75P3.js.map +0 -1
  351. package/dist/cli-bundle/chunks/register-list-query-E7UVY4TN.js.map +0 -7
  352. package/dist/cli-bundle/chunks/register-mutation-4VJTXBZW.js.map +0 -7
  353. package/dist/cli-bundle/chunks/register-mutation-IQ55E25C.js.map +0 -1
  354. /package/dist/cli-bundle/chunks/{append-E6V54WOQ.js.map → append-7OVFYR3C.js.map} +0 -0
  355. /package/dist/cli-bundle/chunks/{append-NNJ3EFIT.js.map → append-DFETHAZL.js.map} +0 -0
  356. /package/dist/cli-bundle/chunks/{chunk-QJKL5PHS.js.map → chunk-7656MAUL.js.map} +0 -0
  357. /package/dist/cli-bundle/chunks/{chunk-X6K5XTTN.js.map → chunk-7W2UAXXT.js.map} +0 -0
  358. /package/dist/cli-bundle/chunks/{chunk-5OK4UGFV.js.map → chunk-BXNDKOR2.js.map} +0 -0
  359. /package/dist/cli-bundle/chunks/{chunk-KSPWRNVP.js.map → chunk-CPX275C6.js.map} +0 -0
  360. /package/dist/cli-bundle/chunks/{chunk-JH2ZSLO3.js.map → chunk-DZRV2OPA.js.map} +0 -0
  361. /package/dist/cli-bundle/chunks/{chunk-L7BH7IWU.js.map → chunk-E5XMKOSB.js.map} +0 -0
  362. /package/dist/cli-bundle/chunks/{chunk-CQTQKUUV.js.map → chunk-EWJWSNRU.js.map} +0 -0
  363. /package/dist/cli-bundle/chunks/{chunk-3MCTMJXI.js.map → chunk-FPBMLYPI.js.map} +0 -0
  364. /package/dist/cli-bundle/chunks/{chunk-DVDBQA3B.js.map → chunk-GTK4DTEW.js.map} +0 -0
  365. /package/dist/cli-bundle/chunks/{chunk-GIQSU6S2.js.map → chunk-KBLZ3AA5.js.map} +0 -0
  366. /package/dist/cli-bundle/chunks/{chunk-XJF7CDNH.js.map → chunk-KH44WBAT.js.map} +0 -0
  367. /package/dist/cli-bundle/chunks/{chunk-GV2262OF.js.map → chunk-LAV26CQG.js.map} +0 -0
  368. /package/dist/cli-bundle/chunks/{chunk-VDO2JMD4.js.map → chunk-LVC72YRD.js.map} +0 -0
  369. /package/dist/cli-bundle/chunks/{chunk-ZYPFOO3L.js.map → chunk-MATHDCGG.js.map} +0 -0
  370. /package/dist/cli-bundle/chunks/{chunk-AOEOYL3S.js.map → chunk-O4BCOJTZ.js.map} +0 -0
  371. /package/dist/cli-bundle/chunks/{chunk-RJO3YAFM.js.map → chunk-OCUBRA6D.js.map} +0 -0
  372. /package/dist/cli-bundle/chunks/{chunk-I577UHC7.js.map → chunk-OR42SO64.js.map} +0 -0
  373. /package/dist/cli-bundle/chunks/{chunk-ZOJ3LR7O.js.map → chunk-OY7DMU5P.js.map} +0 -0
  374. /package/dist/cli-bundle/chunks/{chunk-ZV2NTVMJ.js.map → chunk-PONKZPCJ.js.map} +0 -0
  375. /package/dist/cli-bundle/chunks/{chunk-UX6SSO2I.js.map → chunk-PZC2FUOQ.js.map} +0 -0
  376. /package/dist/cli-bundle/chunks/{chunk-VQIHNHMJ.js.map → chunk-QIH77CAG.js.map} +0 -0
  377. /package/dist/cli-bundle/chunks/{chunk-R3EWPG4A.js.map → chunk-QJIKE24M.js.map} +0 -0
  378. /package/dist/cli-bundle/chunks/{chunk-HB3P4M52.js.map → chunk-TRSHFPRZ.js.map} +0 -0
  379. /package/dist/cli-bundle/chunks/{chunk-HRW7GF6T.js.map → chunk-UCBDQI5E.js.map} +0 -0
  380. /package/dist/cli-bundle/chunks/{chunk-4U4Z6AHI.js.map → chunk-V22ZPOKN.js.map} +0 -0
  381. /package/dist/cli-bundle/chunks/{chunk-JM6YAXTR.js.map → chunk-VHXHVTUU.js.map} +0 -0
  382. /package/dist/cli-bundle/chunks/{chunk-D6NXDNP3.js.map → chunk-VLRGDBLY.js.map} +0 -0
  383. /package/dist/cli-bundle/chunks/{chunk-JAPE62Y5.js.map → chunk-VNTCM3VW.js.map} +0 -0
  384. /package/dist/cli-bundle/chunks/{chunk-FDHPAVVB.js.map → chunk-VXOOB6YX.js.map} +0 -0
  385. /package/dist/cli-bundle/chunks/{chunk-HQ3SB4CN.js.map → chunk-X3W65QK3.js.map} +0 -0
  386. /package/dist/cli-bundle/chunks/{chunk-RZJLNXFG.js.map → chunk-XJTABV3X.js.map} +0 -0
  387. /package/dist/cli-bundle/chunks/{chunk-TYHJDFYW.js.map → chunk-ZVZGXPQ5.js.map} +0 -0
  388. /package/dist/cli-bundle/chunks/{close-many-SDA426VT.js.map → close-many-5RZXVN4J.js.map} +0 -0
  389. /package/dist/cli-bundle/chunks/{close-many-UTZANOCQ.js.map → close-many-RZVTUGBG.js.map} +0 -0
  390. /package/dist/cli-bundle/chunks/{comments-LZN6FXXC.js.map → comments-TPU7QRBL.js.map} +0 -0
  391. /package/dist/cli-bundle/chunks/{comments-VBQ345ND.js.map → comments-Z4KV6FU3.js.map} +0 -0
  392. /package/dist/cli-bundle/chunks/{create-GG4RBCGC.js.map → create-EIFBIVNQ.js.map} +0 -0
  393. /package/dist/cli-bundle/chunks/{create-JBC5KUW6.js.map → create-RGSPN5GD.js.map} +0 -0
  394. /package/dist/cli-bundle/chunks/{deps-FI4O6NQS.js.map → deps-UH5EQQUY.js.map} +0 -0
  395. /package/dist/cli-bundle/chunks/{deps-DELOO4TL.js.map → deps-YG7UF3VR.js.map} +0 -0
  396. /package/dist/cli-bundle/chunks/{docs-6Z2MP526.js.map → docs-G32TK6XS.js.map} +0 -0
  397. /package/dist/cli-bundle/chunks/{docs-2UYBP5D6.js.map → docs-JWWNRC27.js.map} +0 -0
  398. /package/dist/cli-bundle/chunks/{files-HKEAN5MA.js.map → files-3H32UQ4K.js.map} +0 -0
  399. /package/dist/cli-bundle/chunks/{files-HEUGSJZL.js.map → files-4ALMCSKB.js.map} +0 -0
  400. /package/dist/cli-bundle/chunks/{history-compact-7NDVP3PT.js.map → history-compact-77BT2LUB.js.map} +0 -0
  401. /package/dist/cli-bundle/chunks/{history-compact-65YVN5DB.js.map → history-compact-VCKGTX64.js.map} +0 -0
  402. /package/dist/cli-bundle/chunks/{history-redact-7YBL4XSG.js.map → history-redact-LJPZPNFA.js.map} +0 -0
  403. /package/dist/cli-bundle/chunks/{history-redact-IZGNJBU4.js.map → history-redact-PWTTJ3XS.js.map} +0 -0
  404. /package/dist/cli-bundle/chunks/{history-repair-7M4PYQUH.js.map → history-repair-I7CBNCV3.js.map} +0 -0
  405. /package/dist/cli-bundle/chunks/{history-repair-GNGETJLI.js.map → history-repair-YTDZRK5E.js.map} +0 -0
  406. /package/dist/cli-bundle/chunks/{learnings-3YXDRWFT.js.map → learnings-CYNOICKR.js.map} +0 -0
  407. /package/dist/cli-bundle/chunks/{learnings-ALC6IMNL.js.map → learnings-KTYW3AL7.js.map} +0 -0
  408. /package/dist/cli-bundle/chunks/{notes-7JMLQ447.js.map → notes-FGO63FXL.js.map} +0 -0
  409. /package/dist/cli-bundle/chunks/{notes-JFCLTC5C.js.map → notes-ZERD3KB2.js.map} +0 -0
  410. /package/dist/cli-bundle/chunks/{plan-T3XB3WTK.js.map → plan-OFJUBIM5.js.map} +0 -0
  411. /package/dist/cli-bundle/chunks/{plan-KOIPWVOZ.js.map → plan-SGCDDTYR.js.map} +0 -0
  412. /package/dist/cli-bundle/chunks/{profile-OILJHKUW.js.map → profile-3THJPIQY.js.map} +0 -0
  413. /package/dist/cli-bundle/chunks/{profile-RJXA7PGS.js.map → profile-XEZAMMBW.js.map} +0 -0
  414. /package/dist/cli-bundle/chunks/{restore-ZH65GZFB.js.map → restore-6TDVSATY.js.map} +0 -0
  415. /package/dist/cli-bundle/chunks/{restore-L6IAGOD7.js.map → restore-RSL7C7LO.js.map} +0 -0
  416. /package/dist/cli-bundle/chunks/{schema-4ERWM5QJ.js.map → schema-HFXFSGPG.js.map} +0 -0
  417. /package/dist/cli-bundle/chunks/{schema-55DL3Q52.js.map → schema-TPVTIJPO.js.map} +0 -0
  418. /package/dist/cli-bundle/chunks/{update-FW6FKDOP.js.map → update-LJZCL5SI.js.map} +0 -0
  419. /package/dist/cli-bundle/chunks/{update-TJHSPRPT.js.map → update-SIA7LH5Y.js.map} +0 -0
  420. /package/dist/cli-bundle/chunks/{update-many-PWXX5WHO.js.map → update-many-BDBZVGQL.js.map} +0 -0
  421. /package/dist/cli-bundle/chunks/{update-many-NNALYQCN.js.map → update-many-MOY3A5B3.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../sdk/history-compact.ts","../../../../../../../../core/history/history-compact-bulk.ts"],"sourcesContent":["/**\n * @module sdk/history-compact\n *\n * Implements the pm history compact command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHistoryEntry } from \"../core/history/history.js\";\nimport {\n selectHistoryCompactBulkTargets,\n type HistoryCompactBulkCandidate,\n type HistoryCompactBulkSkipReason,\n type HistoryCompactScope,\n} from \"../core/history/history-compact-bulk.js\";\nimport {\n executeHistoryRewrite,\n writeHistoryRawWithRollback,\n} from \"../core/history/history-rewrite.js\";\nimport {\n cloneEmptyReplayDocument,\n historyEntriesToRaw,\n replayHash,\n replayToItemDocument,\n toReplayDocument,\n verifyHistoryChain,\n type ReplayDocument,\n} from \"../core/history/replay.js\";\nimport { applyHistoryPatch } from \"../core/history/projection.js\";\nimport { readHistoryEntries } from \"../core/history/read.js\";\nimport { resolveItemTypeRegistry } from \"../core/item/type-registry.js\";\nimport { lifecycleClassifierFromStatusRegistry } from \"../core/governance/metadata-coverage.js\";\nimport { resolveRuntimeStatusRegistry } from \"../core/schema/runtime-schema.js\";\nimport { listAllItemMetadataLight } from \"../core/store/item-store.js\";\nimport { pathExists, readFileIfExists } from \"../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../core/shared/command-types.js\";\nimport { PmCliError } from \"../core/shared/errors.js\";\nimport { nowIso } from \"../core/shared/time.js\";\nimport {\n getActiveExtensionRegistrations,\n runActiveOnReadHooks,\n runActiveOnWriteHooks,\n} from \"../core/extensions/index.js\";\nimport { readLocatedItem } from \"../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../core/store/paths.js\";\nimport { readSettings } from \"../core/store/settings.js\";\nimport { resolveAuthor } from \"../core/shared/author.js\";\nimport type { HistoryEntry } from \"../types/index.js\";\nimport { resolveHistorySubject } from \"./history-redact.js\";\n\n/** Documents the history compact command options payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactCommandOptions {\n /** Value that configures or reports before for this contract. */\n before?: string;\n /** Value that configures or reports dry run for this contract. */\n dryRun?: boolean;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Human-readable explanation suitable for logs and agent-facing output. */\n message?: string;\n /** Value that configures or reports force for this contract. */\n force?: boolean;\n}\n\ntype HistoryCompactBoundaryKind = \"default\" | \"version\" | \"timestamp\";\n\ninterface HistoryCompactBoundary {\n kind: HistoryCompactBoundaryKind;\n raw: string | null;\n compactCount: number;\n retainedCount: number;\n}\n\ninterface HistoryCompactCurrentItem {\n loadedItem: Awaited<ReturnType<typeof readLocatedItem>> | null;\n currentItemRawBeforeLock: string | null;\n matchedChainBefore: boolean | null;\n}\n\n/** Documents the history compact result payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactResult {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports dry run for this contract. */\n dry_run: boolean;\n /** Value that configures or reports changed for this contract. */\n changed: boolean;\n /** Value that configures or reports compact boundary for this contract. */\n compact_boundary: {\n kind: HistoryCompactBoundaryKind;\n before: string | null;\n entries_compacted: number;\n entries_retained: number;\n first_retained_entry: number | null;\n };\n /** Value that configures or reports history for this contract. */\n history: {\n path: string;\n entries_scanned: number;\n entries_after: number;\n baseline_entry_added: boolean;\n audit_entry_added: boolean;\n verify_ok: boolean;\n verify_errors: string[];\n };\n /** Value that configures or reports item for this contract. */\n item: {\n exists: boolean;\n path: string | null;\n matched_chain_before: boolean | null;\n };\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** ISO 8601 timestamp recording when generated occurred. */\n generated_at: string;\n}\n\nfunction parseBeforeBoundary(\n before: string | undefined,\n entries: HistoryEntry[],\n): HistoryCompactBoundary {\n if (before === undefined) {\n return {\n kind: \"default\",\n raw: null,\n compactCount: entries.length,\n retainedCount: 0,\n };\n }\n\n const raw = before.trim();\n if (raw.length === 0) {\n throw new PmCliError(\n \"history-compact --before requires a non-empty value.\",\n EXIT_CODE.USAGE,\n );\n }\n\n if (/^\\d+$/.test(raw)) {\n const version = Number.parseInt(raw, 10);\n if (\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > entries.length + 1\n ) {\n throw new PmCliError(\n `history-compact --before version must be between 1 and ${entries.length + 1}.`,\n EXIT_CODE.USAGE,\n );\n }\n const compactCount = Math.max(0, Math.min(entries.length, version - 1));\n return {\n kind: \"version\",\n raw,\n compactCount,\n retainedCount: entries.length - compactCount,\n };\n }\n\n const beforeTs = Date.parse(raw);\n if (!Number.isFinite(beforeTs)) {\n throw new PmCliError(\n `Invalid history-compact --before value \"${before}\". Use a version number or ISO timestamp.`,\n EXIT_CODE.USAGE,\n );\n }\n\n let compactCount = 0;\n for (const [index, entry] of entries.entries()) {\n const entryTs = Date.parse(entry.ts);\n if (!Number.isFinite(entryTs)) {\n throw new PmCliError(\n `History for this item contains invalid timestamp at entry ${index + 1}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n if (entryTs >= beforeTs) {\n break;\n }\n compactCount += 1;\n }\n\n return {\n kind: \"timestamp\",\n raw,\n compactCount,\n retainedCount: entries.length - compactCount,\n };\n}\n\nfunction replayHistoryAndResolveCheckpoint(\n entries: HistoryEntry[],\n compactCount: number,\n): {\n checkpoint: ReplayDocument;\n finalReplay: ReplayDocument;\n} {\n let replay = cloneEmptyReplayDocument();\n let checkpoint = cloneEmptyReplayDocument();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (replayHash(replay) !== entry.before_hash) {\n throw new PmCliError(\n `history-compact detected before-hash drift at entry ${index + 1}; run pm history-repair first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n replay = applyHistoryPatch(replay, entry.patch, index + 1, entry.op);\n if (replayHash(replay) !== entry.after_hash) {\n throw new PmCliError(\n `history-compact detected after-hash drift at entry ${index + 1}; run pm history-repair first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n if (index + 1 === compactCount) {\n checkpoint = structuredClone(replay);\n }\n }\n return {\n checkpoint,\n finalReplay: replay,\n };\n}\n\nfunction reanchorRetainedEntries(\n retainedEntries: HistoryEntry[],\n seed: ReplayDocument,\n retainedEntryOffset: number,\n): {\n entries: HistoryEntry[];\n finalReplay: ReplayDocument;\n} {\n let replay = structuredClone(seed);\n const rewritten: HistoryEntry[] = [];\n for (const [index, entry] of retainedEntries.entries()) {\n const beforeHash = replayHash(replay);\n replay = applyHistoryPatch(\n replay,\n entry.patch,\n retainedEntryOffset + index + 1,\n entry.op,\n );\n rewritten.push({\n ...entry,\n before_hash: beforeHash,\n after_hash: replayHash(replay),\n });\n }\n return {\n entries: rewritten,\n finalReplay: replay,\n };\n}\n\nasync function loadHistoryCompactCurrentItem(\n subject: Awaited<ReturnType<typeof resolveHistorySubject>>,\n settings: Awaited<ReturnType<typeof readSettings>>,\n historyEntries: HistoryEntry[],\n): Promise<HistoryCompactCurrentItem> {\n const loadedItem = subject.located\n ? await readLocatedItem(subject.located, { schema: settings.schema })\n : null;\n if (!loadedItem) {\n return {\n loadedItem: null,\n currentItemRawBeforeLock: null,\n matchedChainBefore: null,\n };\n }\n return {\n loadedItem,\n currentItemRawBeforeLock: loadedItem.raw,\n matchedChainBefore:\n replayHash(toReplayDocument(loadedItem.document)) ===\n historyEntries[historyEntries.length - 1]?.after_hash,\n };\n}\n\nfunction buildHistoryCompactMessage(\n options: HistoryCompactCommandOptions,\n boundary: HistoryCompactBoundary,\n): string {\n if (\n typeof options.message === \"string\" &&\n options.message.trim().length > 0\n ) {\n return options.message;\n }\n if (boundary.raw === null) {\n return `history-compact compacted full stream (${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n }).`;\n }\n return `history-compact compacted ${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n } before ${boundary.raw}.`;\n}\n\nfunction buildHistoryCompactBaselineMessage(\n boundary: HistoryCompactBoundary,\n): string {\n if (boundary.raw === null) {\n return `history-compact baseline snapshot after compacting ${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n }.`;\n }\n return `history-compact baseline snapshot before ${boundary.raw}.`;\n}\n\nfunction buildHistoryCompactEntries(params: {\n historyEntries: HistoryEntry[];\n boundary: HistoryCompactBoundary;\n changed: boolean;\n dryRun: boolean;\n author: string;\n options: HistoryCompactCommandOptions;\n}): {\n rewrittenEntries: HistoryEntry[];\n baselineEntryAdded: boolean;\n auditEntryAdded: boolean;\n} {\n if (!params.changed) {\n return {\n rewrittenEntries: params.historyEntries,\n baselineEntryAdded: false,\n auditEntryAdded: false,\n };\n }\n const { checkpoint, finalReplay } = replayHistoryAndResolveCheckpoint(\n params.historyEntries,\n params.boundary.compactCount,\n );\n const retained = params.historyEntries.slice(params.boundary.compactCount);\n const reanchored = reanchorRetainedEntries(\n retained,\n checkpoint,\n params.boundary.compactCount,\n );\n const baselineEntry = createHistoryEntry({\n nowIso: nowIso(),\n author: params.author,\n op: \"history_compact_baseline\",\n before: replayToItemDocument(cloneEmptyReplayDocument()),\n after: replayToItemDocument(checkpoint),\n message: buildHistoryCompactBaselineMessage(params.boundary),\n });\n const rewrittenEntries = [baselineEntry, ...reanchored.entries];\n if (!params.dryRun) {\n rewrittenEntries.push(\n createHistoryEntry({\n nowIso: nowIso(),\n author: params.author,\n op: \"history_compact\",\n before: replayToItemDocument(finalReplay),\n after: replayToItemDocument(finalReplay),\n message: buildHistoryCompactMessage(params.options, params.boundary),\n }),\n );\n }\n return {\n rewrittenEntries,\n baselineEntryAdded: true,\n auditEntryAdded: !params.dryRun,\n };\n}\n\nasync function applyHistoryCompactRewrite(params: {\n pmRoot: string;\n subject: Awaited<ReturnType<typeof resolveHistorySubject>>;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeRegistry: ReturnType<typeof resolveItemTypeRegistry>;\n historyRawBeforeLock: string;\n currentItemRawBeforeLock: string | null;\n author: string;\n force: boolean | undefined;\n loadedItem: Awaited<ReturnType<typeof readLocatedItem>> | null;\n historyPath: string;\n rewrittenEntries: HistoryEntry[];\n}): Promise<string[]> {\n return executeHistoryRewrite({\n pmRoot: params.pmRoot,\n subject: params.subject,\n settings: params.settings,\n typeRegistry: params.typeRegistry,\n historyRawBeforeLock: params.historyRawBeforeLock,\n currentItemRawBeforeLock: params.currentItemRawBeforeLock,\n operation: \"history-compact\",\n author: params.author,\n force: params.force,\n itemDocument: params.loadedItem?.document ?? null,\n applyRewrite: async ({ historyRawUnderLock }) =>\n writeHistoryRawWithRollback({\n historyPath: params.historyPath,\n nextHistoryRaw: historyEntriesToRaw(params.rewrittenEntries),\n historyRawUnderLock,\n }),\n applyPostRewrite: async () =>\n runActiveOnWriteHooks({\n path: params.historyPath,\n scope: \"project\",\n op: \"history_compact:history\",\n }),\n });\n}\n\n/** Implements run history compact for the public runtime surface of this module. */\nexport async function runHistoryCompact(\n id: string,\n options: HistoryCompactCommandOptions,\n global: GlobalOptions,\n): Promise<HistoryCompactResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const subject = await resolveHistorySubject(\n pmRoot,\n id,\n settings,\n typeRegistry.type_to_folder,\n );\n const historyPath = subject.historyPath;\n const historyRawBeforeLock = await readFileIfExists(historyPath);\n if (historyRawBeforeLock === null) {\n throw new PmCliError(\n `No history stream exists for ${subject.id}.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n const historyEntries = await readHistoryEntries(historyPath, subject.id);\n if (historyEntries.length === 0) {\n throw new PmCliError(\n `No history entries exist for ${subject.id}; nothing to compact.`,\n EXIT_CODE.USAGE,\n );\n }\n\n const chainVerification = verifyHistoryChain(historyEntries);\n if (!chainVerification.ok) {\n throw new PmCliError(\n `history-compact requires a valid history chain (${chainVerification.errors.join(\", \")}). Run pm history-repair ${subject.id} first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n\n const boundary = parseBeforeBoundary(options.before, historyEntries);\n const changed = boundary.compactCount > 0;\n const dryRun = Boolean(options.dryRun);\n const author = resolveAuthor(options.author, settings.author_default);\n const warnings: string[] = [];\n if (!changed) {\n warnings.push(\"history_compact_noop_before_boundary\");\n }\n\n const currentItem = await loadHistoryCompactCurrentItem(\n subject,\n settings,\n historyEntries,\n );\n if (currentItem.matchedChainBefore === false) {\n warnings.push(\"history_compact_item_chain_mismatch\");\n }\n\n const { rewrittenEntries, baselineEntryAdded, auditEntryAdded } =\n buildHistoryCompactEntries({\n historyEntries,\n boundary,\n changed,\n dryRun,\n author,\n options,\n });\n\n const rewrittenVerify = verifyHistoryChain(rewrittenEntries);\n if (!rewrittenVerify.ok) {\n throw new PmCliError(\n `history-compact produced an invalid rewritten chain (${rewrittenVerify.errors.join(\", \")}).`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n\n if (changed && !dryRun) {\n warnings.push(\n ...(await applyHistoryCompactRewrite({\n pmRoot,\n subject,\n settings,\n typeRegistry,\n historyRawBeforeLock,\n currentItemRawBeforeLock: currentItem.currentItemRawBeforeLock,\n author,\n force: options.force,\n loadedItem: currentItem.loadedItem,\n historyPath,\n rewrittenEntries,\n })),\n );\n }\n\n const firstRetainedEntry =\n boundary.retainedCount > 0 ? boundary.compactCount + 1 : null;\n return {\n id: subject.id,\n dry_run: dryRun,\n changed,\n compact_boundary: {\n kind: boundary.kind,\n before: boundary.raw,\n entries_compacted: boundary.compactCount,\n entries_retained: boundary.retainedCount,\n first_retained_entry: firstRetainedEntry,\n },\n history: {\n path: historyPath,\n entries_scanned: historyEntries.length,\n entries_after: rewrittenEntries.length,\n baseline_entry_added: baselineEntryAdded,\n audit_entry_added: auditEntryAdded,\n verify_ok: rewrittenVerify.ok,\n verify_errors: rewrittenVerify.errors,\n },\n item: {\n exists: subject.located !== null,\n path: subject.located?.itemPath ?? null,\n matched_chain_before: currentItem.matchedChainBefore,\n },\n warnings: [...new Set(warnings)].sort((left, right) =>\n left.localeCompare(right),\n ),\n generated_at: nowIso(),\n };\n}\n\n/** Default entry floor below which a stream is treated as already compact. */\nexport const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES = 3;\n\n/** Documents the bulk history compact command options payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactBulkCommandOptions {\n /** Value that configures or reports ids for this contract. */\n ids?: string[];\n /** Value that configures or reports scope for this contract. */\n scope?: HistoryCompactScope;\n /** Value that configures or reports all over for this contract. */\n allOver?: number;\n /** Value that configures or reports min entries for this contract. */\n minEntries?: number;\n /** Value that configures or reports dry run for this contract. */\n dryRun?: boolean;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Human-readable explanation suitable for logs and agent-facing output. */\n message?: string;\n /** Value that configures or reports force for this contract. */\n force?: boolean;\n}\n\n/** Per-item outcome row in a bulk compaction pass. */\nexport interface HistoryCompactBulkItemResult {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports outcome for this contract. */\n outcome: \"compacted\" | \"skipped\" | \"errored\";\n /** Value that configures or reports entries before for this contract. */\n entries_before: number;\n /** Value that configures or reports entries after for this contract. */\n entries_after: number | null;\n /** Value that configures or reports skip reason for this contract. */\n skip_reason: HistoryCompactBulkSkipReason | null;\n /** Value that configures or reports changed for this contract. */\n changed: boolean;\n /** Value that configures or reports error for this contract. */\n error: string | null;\n}\n\n/** Documents the bulk history compact result payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactBulkResult {\n /** Value that configures or reports bulk for this contract. */\n bulk: true;\n /** Value that configures or reports dry run for this contract. */\n dry_run: boolean;\n /** Value that configures or reports mode for this contract. */\n mode: \"ids\" | \"scan\";\n /** Value that configures or reports scope for this contract. */\n scope: HistoryCompactScope | null;\n /** Value that configures or reports criteria for this contract. */\n criteria: {\n min_entries: number;\n all_over: number | null;\n policy_threshold_applied: boolean;\n };\n /** Value that configures or reports totals for this contract. */\n totals: {\n streams_considered: number;\n selected: number;\n items_compacted: number;\n items_skipped: number;\n items_errored: number;\n };\n /** Value that configures or reports results for this contract. */\n results: HistoryCompactBulkItemResult[];\n /** ISO 8601 timestamp recording when generated occurred. */\n generated_at: string;\n}\n\n/** Enforce the `pm history-compact` target contract shared by the CLI and MCP surfaces: exactly one selection mode — a single item `<id>`, an explicit `--ids` list, or a scan selector (`--all-over` / `--closed` / `--all-streams`). */\nexport function assertHistoryCompactTarget(\n id: string | undefined,\n bulk: { ids?: string[]; allOver?: number; scope?: HistoryCompactScope },\n): void {\n const hasIds = bulk.ids !== undefined && bulk.ids.length > 0;\n const hasScan = bulk.allOver !== undefined || bulk.scope !== undefined;\n const selectorCount =\n (id !== undefined ? 1 : 0) + (hasIds ? 1 : 0) + (hasScan ? 1 : 0);\n if (selectorCount === 0) {\n throw new PmCliError(\n \"history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).\",\n EXIT_CODE.USAGE,\n );\n }\n if (id !== undefined && (hasIds || hasScan)) {\n throw new PmCliError(\n \"history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.\",\n EXIT_CODE.USAGE,\n );\n }\n if (hasIds && hasScan) {\n throw new PmCliError(\n \"history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.\",\n EXIT_CODE.USAGE,\n );\n }\n}\n\nfunction countHistoryStreamEntries(raw: string): number {\n let count = 0;\n for (const line of raw.split(/\\r?\\n/)) {\n if (line.trim().length > 0) {\n count += 1;\n }\n }\n return count;\n}\n\nasync function collectHistoryCompactBulkCandidates(params: {\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeToFolder: Record<string, string>;\n}): Promise<{\n candidates: HistoryCompactBulkCandidate[];\n preselectionErrors: HistoryCompactBulkItemResult[];\n}> {\n const statusRegistry = resolveRuntimeStatusRegistry(params.settings.schema);\n const classifier = lifecycleClassifierFromStatusRegistry(statusRegistry);\n const items = await listAllItemMetadataLight(\n params.pmRoot,\n params.settings.item_format,\n params.typeToFolder,\n undefined,\n params.settings.schema,\n );\n const bucketById = new Map(\n items.map((item) => [item.id, classifier.classify(item.status)] as const),\n );\n const historyDir = path.join(params.pmRoot, \"history\");\n const candidates: HistoryCompactBulkCandidate[] = [];\n const preselectionErrors: HistoryCompactBulkItemResult[] = [];\n if (!(await pathExists(historyDir))) {\n return { candidates, preselectionErrors };\n }\n const historyFiles = (await fs.readdir(historyDir))\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .sort((left, right) => left.localeCompare(right));\n for (const fileName of historyFiles) {\n const historyPath = path.join(historyDir, fileName);\n const id = fileName.slice(0, -\".jsonl\".length);\n try {\n const raw = await fs.readFile(historyPath, \"utf8\");\n await runActiveOnReadHooks({ path: historyPath, scope: \"project\" });\n candidates.push({\n id,\n entries: countHistoryStreamEntries(raw),\n bucket: bucketById.get(id) ?? null,\n });\n } catch (error) {\n preselectionErrors.push({\n id,\n outcome: \"errored\",\n entries_before: 0,\n entries_after: null,\n skip_reason: null,\n changed: false,\n /* c8 ignore next -- non-Error throws are normalized in defensive fallback. */\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return { candidates, preselectionErrors };\n}\n\nasync function runHistoryCompactBulkRow(params: {\n row: ReturnType<typeof selectHistoryCompactBulkTargets>[number];\n options: HistoryCompactBulkCommandOptions;\n dryRun: boolean;\n global: GlobalOptions;\n}): Promise<{\n result: HistoryCompactBulkItemResult;\n selected: boolean;\n compacted: boolean;\n errored: boolean;\n}> {\n if (!params.row.selected) {\n return {\n selected: false,\n compacted: false,\n errored: false,\n result: {\n id: params.row.id,\n outcome: \"skipped\",\n entries_before: params.row.entries,\n entries_after: null,\n skip_reason: params.row.skip_reason,\n changed: false,\n error: null,\n },\n };\n }\n try {\n const result = await runHistoryCompact(\n params.row.id,\n {\n dryRun: params.dryRun,\n author: params.options.author,\n message: params.options.message,\n force: params.options.force,\n },\n params.global,\n );\n return {\n selected: true,\n compacted: true,\n errored: false,\n result: {\n id: params.row.id,\n outcome: \"compacted\",\n entries_before: params.row.entries,\n entries_after: result.history.entries_after,\n skip_reason: null,\n changed: result.changed,\n error: null,\n },\n };\n } catch (error) {\n return {\n selected: true,\n compacted: false,\n errored: true,\n result: {\n id: params.row.id,\n outcome: \"errored\",\n entries_before: params.row.entries,\n entries_after: null,\n skip_reason: null,\n changed: false,\n /* c8 ignore next -- non-Error throws are normalized in defensive fallback. */\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n}\n\n/**\n * Bulk history compaction: compact every history stream matching the requested\n * selection (explicit `--ids`, a `--scope` lifecycle filter, and/or an\n * `--all-over <N>` entry threshold) in one audited pass. Each selected stream is\n * compacted with the same single-item logic ({@link runHistoryCompact}); one\n * failing stream never aborts the rest, and the caller decides the exit code\n * from `totals.items_errored`.\n *\n * When `history.compact_policy` is enabled and no explicit `--all-over` is\n * given, the policy's `max_entries` is used as the scan threshold so the\n * configured policy drives the sweep.\n */\nexport async function runHistoryCompactBulk(\n options: HistoryCompactBulkCommandOptions,\n global: GlobalOptions,\n): Promise<HistoryCompactBulkResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const { candidates, preselectionErrors } =\n await collectHistoryCompactBulkCandidates({\n pmRoot,\n settings,\n typeToFolder: typeRegistry.type_to_folder,\n });\n\n const mode: \"ids\" | \"scan\" =\n options.ids !== undefined && options.ids.length > 0 ? \"ids\" : \"scan\";\n const minEntries =\n options.minEntries ?? HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES;\n const policy = settings.history.compact_policy;\n const policyThresholdApplied =\n mode === \"scan\" && options.allOver === undefined && policy.enabled;\n const allOver =\n options.allOver ??\n (policyThresholdApplied ? policy.max_entries : undefined);\n\n const selection = selectHistoryCompactBulkTargets(candidates, {\n ids: options.ids,\n scope: options.scope,\n minEntries,\n allOver,\n });\n\n const dryRun = Boolean(options.dryRun);\n const results: HistoryCompactBulkItemResult[] = [...preselectionErrors];\n const totals = {\n streams_considered: candidates.length + preselectionErrors.length,\n selected: 0,\n items_compacted: 0,\n items_skipped: 0,\n items_errored: preselectionErrors.length,\n };\n for (const row of selection) {\n const outcome = await runHistoryCompactBulkRow({\n row,\n options,\n dryRun,\n global,\n });\n results.push(outcome.result);\n if (!outcome.selected) {\n totals.items_skipped += 1;\n continue;\n }\n totals.selected += 1;\n if (outcome.compacted) {\n totals.items_compacted += 1;\n }\n if (outcome.errored) {\n totals.items_errored += 1;\n }\n }\n\n return {\n bulk: true,\n dry_run: dryRun,\n mode,\n scope: options.scope ?? null,\n criteria: {\n min_entries: minEntries,\n all_over: allOver ?? null,\n policy_threshold_applied: policyThresholdApplied,\n },\n totals,\n results,\n generated_at: nowIso(),\n };\n}\n","/**\n * @module core/history/history-compact-bulk\n *\n * Pure selection logic for bulk history-stream compaction. Given a set of\n * history-stream candidates (id, entry count, and lifecycle bucket of the\n * owning item) plus the requested selection criteria, this module decides which\n * streams should be compacted and which are skipped (and why).\n *\n * The module performs no filesystem access and imports no heavy runtime\n * dependencies — the command layer reads streams and item statuses, hands the\n * resolved candidates here, then executes per-item compaction on the selection\n * this module returns. Keeping selection pure makes the matrix of scope /\n * threshold / explicit-id rules trivially testable without touching disk.\n */\n\nimport type { LifecycleBucket } from \"../governance/metadata-coverage.js\";\n\n/** Bulk-compaction scope: only closed items, or every history stream. */\nexport type HistoryCompactScope = \"closed\" | \"all-streams\";\n\n/** Why a candidate stream was not selected for compaction. */\nexport type HistoryCompactBulkSkipReason =\n | \"no_stream\"\n | \"already_compact\"\n | \"scope_mismatch\"\n | \"below_threshold\";\n\n/**\n * One history stream considered for bulk compaction.\n *\n * `bucket` is the lifecycle bucket of the owning item, or `null` when no item\n * matches the stream (an orphan history file). Orphan streams never satisfy a\n * `closed` scope filter but are eligible under `all-streams`.\n */\nexport interface HistoryCompactBulkCandidate {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports entries for this contract. */\n entries: number;\n /** Value that configures or reports bucket for this contract. */\n bucket: LifecycleBucket | null;\n}\n\n/** Selection criteria resolved from the command flags + policy defaults. */\nexport interface HistoryCompactBulkCriteria {\n /** Explicit, ordered list of item ids to compact. When non-empty the selection runs in \"ids\" mode: scope/allOver are ignored and only the `minEntries` floor applies. Duplicates are collapsed, preserving first-seen order. */\n ids?: string[];\n /** Lifecycle scope filter for scan mode (ignored in ids mode). */\n scope?: HistoryCompactScope;\n /** Streams with at most this many entries are skipped as `already_compact` (compaction collapses a stream to a 2-entry baseline+audit pair, so smaller streams gain nothing). Applies in both modes. */\n minEntries: number;\n /** Scan mode only: when set, only streams with strictly more entries than this are selected. Streams above `minEntries` but at/below `allOver` are skipped as `below_threshold`. */\n allOver?: number;\n}\n\n/** Per-candidate selection outcome. */\nexport interface HistoryCompactBulkSelectionRow {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports entries for this contract. */\n entries: number;\n /** Value that configures or reports selected for this contract. */\n selected: boolean;\n /** Value that configures or reports skip reason for this contract. */\n skip_reason: HistoryCompactBulkSkipReason | null;\n}\n\nfunction selectIdsMode(\n ids: string[],\n byId: ReadonlyMap<string, HistoryCompactBulkCandidate>,\n minEntries: number,\n): HistoryCompactBulkSelectionRow[] {\n const seen = new Set<string>();\n const rows: HistoryCompactBulkSelectionRow[] = [];\n for (const rawId of ids) {\n const id = rawId.trim();\n if (id.length === 0 || seen.has(id)) {\n continue;\n }\n seen.add(id);\n const candidate = byId.get(id);\n if (candidate === undefined) {\n rows.push({ id, entries: 0, selected: false, skip_reason: \"no_stream\" });\n continue;\n }\n if (candidate.entries <= minEntries) {\n rows.push({\n id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"already_compact\",\n });\n continue;\n }\n rows.push({\n id,\n entries: candidate.entries,\n selected: true,\n skip_reason: null,\n });\n }\n return rows;\n}\n\nfunction selectScanMode(\n candidates: HistoryCompactBulkCandidate[],\n criteria: HistoryCompactBulkCriteria,\n): HistoryCompactBulkSelectionRow[] {\n const ordered = [...candidates].sort(\n (a, b) => b.entries - a.entries || a.id.localeCompare(b.id),\n );\n const rows: HistoryCompactBulkSelectionRow[] = [];\n for (const candidate of ordered) {\n if (criteria.scope === \"closed\" && candidate.bucket !== \"closed\") {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"scope_mismatch\",\n });\n continue;\n }\n if (candidate.entries <= criteria.minEntries) {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"already_compact\",\n });\n continue;\n }\n if (\n criteria.allOver !== undefined &&\n candidate.entries <= criteria.allOver\n ) {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"below_threshold\",\n });\n continue;\n }\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: true,\n skip_reason: null,\n });\n }\n return rows;\n}\n\n/**\n * Decide which history streams to compact.\n *\n * Runs in \"ids\" mode when `criteria.ids` is non-empty (exact, ordered set,\n * honouring only the `minEntries` floor) and \"scan\" mode otherwise (every\n * candidate, filtered by scope and entry thresholds, ordered deepest-first).\n */\nexport function selectHistoryCompactBulkTargets(\n candidates: HistoryCompactBulkCandidate[],\n criteria: HistoryCompactBulkCriteria,\n): HistoryCompactBulkSelectionRow[] {\n if (criteria.ids !== undefined && criteria.ids.length > 0) {\n const byId = new Map(\n candidates.map((candidate) => [candidate.id, candidate]),\n );\n return selectIdsMode(criteria.ids, byId, criteria.minEntries);\n }\n return selectScanMode(candidates, criteria);\n}\n"],"names":["compactCount"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;;;AC6DjB,SAAS,cACP,KACA,MACA,YAAkB;AAElB,QAAM,OAAO,oBAAI,IAAG;AACpB,QAAM,OAAyC,CAAA;AAC/C,aAAW,SAAS,KAAK;AACvB,UAAM,KAAK,MAAM,KAAI;AACrB,QAAI,GAAG,WAAW,KAAK,KAAK,IAAI,EAAE,GAAG;AACnC;IACF;AACA,SAAK,IAAI,EAAE;AACX,UAAM,YAAY,KAAK,IAAI,EAAE;AAC7B,QAAI,cAAc,QAAW;AAC3B,WAAK,KAAK,EAAE,IAAI,SAAS,GAAG,UAAU,OAAO,aAAa,YAAW,CAAE;AACvE;IACF;AACA,QAAI,UAAU,WAAW,YAAY;AACnC,WAAK,KAAK;QACR;QACA,SAAS,UAAU;QACnB,UAAU;QACV,aAAa;OACd;AACD;IACF;AACA,SAAK,KAAK;MACR;MACA,SAAS,UAAU;MACnB,UAAU;MACV,aAAa;KACd;EACH;AACA,SAAO;AACT;AAEA,SAAS,eACP,YACA,UAAoC;AAEpC,QAAM,UAAU,CAAC,GAAG,UAAU,EAAE,KAC9B,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AAE7D,QAAM,OAAyC,CAAA;AAC/C,aAAW,aAAa,SAAS;AAC/B,QAAI,SAAS,UAAU,YAAY,UAAU,WAAW,UAAU;AAChE,W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ACrB,0BAA0B;;IAE5B;IACA;IACA,cAAc,OAAM;;AAExB","debugId":"9a360c17-f01f-5885-b30d-30361c04ceac"}
1
+ {"version":3,"sources":["../../../../../../../../sdk/history-compact.ts","../../../../../../../../core/history/history-compact-bulk.ts"],"sourcesContent":["/**\n * @module sdk/history-compact\n *\n * Implements the pm history compact command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHistoryEntry } from \"../core/history/history.js\";\nimport {\n selectHistoryCompactBulkTargets,\n type HistoryCompactBulkCandidate,\n type HistoryCompactBulkSkipReason,\n type HistoryCompactScope,\n} from \"../core/history/history-compact-bulk.js\";\nimport {\n executeHistoryRewrite,\n writeHistoryRawWithRollback,\n} from \"../core/history/history-rewrite.js\";\nimport {\n cloneEmptyReplayDocument,\n historyEntriesToRaw,\n replayHash,\n replayToItemDocument,\n toReplayDocument,\n verifyHistoryChain,\n type ReplayDocument,\n} from \"../core/history/replay.js\";\nimport { applyHistoryPatch } from \"../core/history/projection.js\";\nimport { readHistoryEntries } from \"../core/history/read.js\";\nimport { resolveItemTypeRegistry } from \"../core/item/type-registry.js\";\nimport { lifecycleClassifierFromStatusRegistry } from \"../core/governance/metadata-coverage.js\";\nimport { resolveRuntimeStatusRegistry } from \"../core/schema/runtime-schema.js\";\nimport { listAllItemMetadataLight } from \"../core/store/item-store.js\";\nimport { pathExists, readFileIfExists } from \"../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../core/shared/command-types.js\";\nimport { PmCliError } from \"../core/shared/errors.js\";\nimport { nowIso } from \"../core/shared/time.js\";\nimport {\n getActiveExtensionRegistrations,\n runActiveOnReadHooks,\n runActiveOnWriteHooks,\n} from \"../core/extensions/index.js\";\nimport { readLocatedItem } from \"../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../core/store/paths.js\";\nimport { readSettings } from \"../core/store/settings.js\";\nimport { resolveAuthor } from \"../core/shared/author.js\";\nimport type { HistoryEntry } from \"../types/index.js\";\nimport { resolveHistorySubject } from \"./history-redact.js\";\n\n/** Documents the history compact command options payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactCommandOptions {\n /** Value that configures or reports before for this contract. */\n before?: string;\n /** Value that configures or reports dry run for this contract. */\n dryRun?: boolean;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Human-readable explanation suitable for logs and agent-facing output. */\n message?: string;\n /** Value that configures or reports force for this contract. */\n force?: boolean;\n}\n\ntype HistoryCompactBoundaryKind = \"default\" | \"version\" | \"timestamp\";\n\ninterface HistoryCompactBoundary {\n kind: HistoryCompactBoundaryKind;\n raw: string | null;\n compactCount: number;\n retainedCount: number;\n}\n\ninterface HistoryCompactCurrentItem {\n loadedItem: Awaited<ReturnType<typeof readLocatedItem>> | null;\n currentItemRawBeforeLock: string | null;\n matchedChainBefore: boolean | null;\n}\n\n/** Documents the history compact result payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactResult {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports dry run for this contract. */\n dry_run: boolean;\n /** Value that configures or reports changed for this contract. */\n changed: boolean;\n /** Value that configures or reports compact boundary for this contract. */\n compact_boundary: {\n kind: HistoryCompactBoundaryKind;\n before: string | null;\n entries_compacted: number;\n entries_retained: number;\n first_retained_entry: number | null;\n };\n /** Value that configures or reports history for this contract. */\n history: {\n path: string;\n entries_scanned: number;\n entries_after: number;\n baseline_entry_added: boolean;\n audit_entry_added: boolean;\n verify_ok: boolean;\n verify_errors: string[];\n };\n /** Value that configures or reports item for this contract. */\n item: {\n exists: boolean;\n path: string | null;\n matched_chain_before: boolean | null;\n };\n /** Value that configures or reports warnings for this contract. */\n warnings: string[];\n /** ISO 8601 timestamp recording when generated occurred. */\n generated_at: string;\n}\n\nfunction parseBeforeBoundary(\n before: string | undefined,\n entries: HistoryEntry[],\n): HistoryCompactBoundary {\n if (before === undefined) {\n return {\n kind: \"default\",\n raw: null,\n compactCount: entries.length,\n retainedCount: 0,\n };\n }\n\n const raw = before.trim();\n if (raw.length === 0) {\n throw new PmCliError(\n \"history-compact --before requires a non-empty value.\",\n EXIT_CODE.USAGE,\n );\n }\n\n if (/^\\d+$/.test(raw)) {\n const version = Number.parseInt(raw, 10);\n if (\n !Number.isSafeInteger(version) ||\n version < 1 ||\n version > entries.length + 1\n ) {\n throw new PmCliError(\n `history-compact --before version must be between 1 and ${entries.length + 1}.`,\n EXIT_CODE.USAGE,\n );\n }\n const compactCount = Math.max(0, Math.min(entries.length, version - 1));\n return {\n kind: \"version\",\n raw,\n compactCount,\n retainedCount: entries.length - compactCount,\n };\n }\n\n const beforeTs = Date.parse(raw);\n if (!Number.isFinite(beforeTs)) {\n throw new PmCliError(\n `Invalid history-compact --before value \"${before}\". Use a version number or ISO timestamp.`,\n EXIT_CODE.USAGE,\n );\n }\n\n let compactCount = 0;\n for (const [index, entry] of entries.entries()) {\n const entryTs = Date.parse(entry.ts);\n if (!Number.isFinite(entryTs)) {\n throw new PmCliError(\n `History for this item contains invalid timestamp at entry ${index + 1}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n if (entryTs >= beforeTs) {\n break;\n }\n compactCount += 1;\n }\n\n return {\n kind: \"timestamp\",\n raw,\n compactCount,\n retainedCount: entries.length - compactCount,\n };\n}\n\nfunction replayHistoryAndResolveCheckpoint(\n entries: HistoryEntry[],\n compactCount: number,\n): {\n checkpoint: ReplayDocument;\n finalReplay: ReplayDocument;\n} {\n let replay = cloneEmptyReplayDocument();\n let checkpoint = cloneEmptyReplayDocument();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (replayHash(replay) !== entry.before_hash) {\n throw new PmCliError(\n `history-compact detected before-hash drift at entry ${index + 1}; run pm history-repair first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n replay = applyHistoryPatch(replay, entry.patch, index + 1, entry.op);\n if (replayHash(replay) !== entry.after_hash) {\n throw new PmCliError(\n `history-compact detected after-hash drift at entry ${index + 1}; run pm history-repair first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n if (index + 1 === compactCount) {\n checkpoint = structuredClone(replay);\n }\n }\n return {\n checkpoint,\n finalReplay: replay,\n };\n}\n\nfunction reanchorRetainedEntries(\n retainedEntries: HistoryEntry[],\n seed: ReplayDocument,\n retainedEntryOffset: number,\n): {\n entries: HistoryEntry[];\n finalReplay: ReplayDocument;\n} {\n let replay = structuredClone(seed);\n const rewritten: HistoryEntry[] = [];\n for (const [index, entry] of retainedEntries.entries()) {\n const beforeHash = replayHash(replay);\n replay = applyHistoryPatch(\n replay,\n entry.patch,\n retainedEntryOffset + index + 1,\n entry.op,\n );\n rewritten.push({\n ...entry,\n before_hash: beforeHash,\n after_hash: replayHash(replay),\n });\n }\n return {\n entries: rewritten,\n finalReplay: replay,\n };\n}\n\nasync function loadHistoryCompactCurrentItem(\n subject: Awaited<ReturnType<typeof resolveHistorySubject>>,\n settings: Awaited<ReturnType<typeof readSettings>>,\n historyEntries: HistoryEntry[],\n): Promise<HistoryCompactCurrentItem> {\n const loadedItem = subject.located\n ? await readLocatedItem(subject.located, { schema: settings.schema })\n : null;\n if (!loadedItem) {\n return {\n loadedItem: null,\n currentItemRawBeforeLock: null,\n matchedChainBefore: null,\n };\n }\n return {\n loadedItem,\n currentItemRawBeforeLock: loadedItem.raw,\n matchedChainBefore:\n replayHash(toReplayDocument(loadedItem.document)) ===\n historyEntries[historyEntries.length - 1]?.after_hash,\n };\n}\n\nfunction buildHistoryCompactMessage(\n options: HistoryCompactCommandOptions,\n boundary: HistoryCompactBoundary,\n): string {\n if (\n typeof options.message === \"string\" &&\n options.message.trim().length > 0\n ) {\n return options.message;\n }\n if (boundary.raw === null) {\n return `history-compact compacted full stream (${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n }).`;\n }\n return `history-compact compacted ${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n } before ${boundary.raw}.`;\n}\n\nfunction buildHistoryCompactBaselineMessage(\n boundary: HistoryCompactBoundary,\n): string {\n if (boundary.raw === null) {\n return `history-compact baseline snapshot after compacting ${boundary.compactCount} entr${\n boundary.compactCount === 1 ? \"y\" : \"ies\"\n }.`;\n }\n return `history-compact baseline snapshot before ${boundary.raw}.`;\n}\n\nfunction buildHistoryCompactEntries(params: {\n historyEntries: HistoryEntry[];\n boundary: HistoryCompactBoundary;\n changed: boolean;\n dryRun: boolean;\n author: string;\n options: HistoryCompactCommandOptions;\n}): {\n rewrittenEntries: HistoryEntry[];\n baselineEntryAdded: boolean;\n auditEntryAdded: boolean;\n} {\n if (!params.changed) {\n return {\n rewrittenEntries: params.historyEntries,\n baselineEntryAdded: false,\n auditEntryAdded: false,\n };\n }\n const { checkpoint, finalReplay } = replayHistoryAndResolveCheckpoint(\n params.historyEntries,\n params.boundary.compactCount,\n );\n const retained = params.historyEntries.slice(params.boundary.compactCount);\n const reanchored = reanchorRetainedEntries(\n retained,\n checkpoint,\n params.boundary.compactCount,\n );\n const baselineEntry = createHistoryEntry({\n nowIso: nowIso(),\n author: params.author,\n op: \"history_compact_baseline\",\n before: replayToItemDocument(cloneEmptyReplayDocument()),\n after: replayToItemDocument(checkpoint),\n message: buildHistoryCompactBaselineMessage(params.boundary),\n });\n const rewrittenEntries = [baselineEntry, ...reanchored.entries];\n if (!params.dryRun) {\n rewrittenEntries.push(\n createHistoryEntry({\n nowIso: nowIso(),\n author: params.author,\n op: \"history_compact\",\n before: replayToItemDocument(finalReplay),\n after: replayToItemDocument(finalReplay),\n message: buildHistoryCompactMessage(params.options, params.boundary),\n }),\n );\n }\n return {\n rewrittenEntries,\n baselineEntryAdded: true,\n auditEntryAdded: !params.dryRun,\n };\n}\n\nasync function applyHistoryCompactRewrite(params: {\n pmRoot: string;\n subject: Awaited<ReturnType<typeof resolveHistorySubject>>;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeRegistry: ReturnType<typeof resolveItemTypeRegistry>;\n historyRawBeforeLock: string;\n currentItemRawBeforeLock: string | null;\n author: string;\n force: boolean | undefined;\n loadedItem: Awaited<ReturnType<typeof readLocatedItem>> | null;\n historyPath: string;\n rewrittenEntries: HistoryEntry[];\n}): Promise<string[]> {\n return executeHistoryRewrite({\n pmRoot: params.pmRoot,\n subject: params.subject,\n settings: params.settings,\n typeRegistry: params.typeRegistry,\n historyRawBeforeLock: params.historyRawBeforeLock,\n currentItemRawBeforeLock: params.currentItemRawBeforeLock,\n operation: \"history-compact\",\n author: params.author,\n force: params.force,\n itemDocument: params.loadedItem?.document ?? null,\n applyRewrite: async ({ historyRawUnderLock }) =>\n writeHistoryRawWithRollback({\n historyPath: params.historyPath,\n nextHistoryRaw: historyEntriesToRaw(params.rewrittenEntries),\n historyRawUnderLock,\n }),\n applyPostRewrite: async () =>\n runActiveOnWriteHooks({\n path: params.historyPath,\n scope: \"project\",\n op: \"history_compact:history\",\n }),\n });\n}\n\n/** Implements run history compact for the public runtime surface of this module. */\nexport async function runHistoryCompact(\n id: string,\n options: HistoryCompactCommandOptions,\n global: GlobalOptions,\n): Promise<HistoryCompactResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const subject = await resolveHistorySubject(\n pmRoot,\n id,\n settings,\n typeRegistry.type_to_folder,\n );\n const historyPath = subject.historyPath;\n const historyRawBeforeLock = await readFileIfExists(historyPath);\n if (historyRawBeforeLock === null) {\n throw new PmCliError(\n `No history stream exists for ${subject.id}.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n const historyEntries = await readHistoryEntries(historyPath, subject.id);\n if (historyEntries.length === 0) {\n throw new PmCliError(\n `No history entries exist for ${subject.id}; nothing to compact.`,\n EXIT_CODE.USAGE,\n );\n }\n\n const chainVerification = verifyHistoryChain(historyEntries);\n if (!chainVerification.ok) {\n throw new PmCliError(\n `history-compact requires a valid history chain (${chainVerification.errors.join(\", \")}). Run pm history-repair ${subject.id} first.`,\n EXIT_CODE.CONFLICT,\n );\n }\n\n const boundary = parseBeforeBoundary(options.before, historyEntries);\n const changed = boundary.compactCount > 0;\n const dryRun = Boolean(options.dryRun);\n const author = resolveAuthor(options.author, settings.author_default);\n const warnings: string[] = [];\n if (!changed) {\n warnings.push(\"history_compact_noop_before_boundary\");\n }\n\n const currentItem = await loadHistoryCompactCurrentItem(\n subject,\n settings,\n historyEntries,\n );\n if (currentItem.matchedChainBefore === false) {\n warnings.push(\"history_compact_item_chain_mismatch\");\n }\n\n const { rewrittenEntries, baselineEntryAdded, auditEntryAdded } =\n buildHistoryCompactEntries({\n historyEntries,\n boundary,\n changed,\n dryRun,\n author,\n options,\n });\n\n const rewrittenVerify = verifyHistoryChain(rewrittenEntries);\n if (!rewrittenVerify.ok) {\n throw new PmCliError(\n `history-compact produced an invalid rewritten chain (${rewrittenVerify.errors.join(\", \")}).`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n\n if (changed && !dryRun) {\n warnings.push(\n ...(await applyHistoryCompactRewrite({\n pmRoot,\n subject,\n settings,\n typeRegistry,\n historyRawBeforeLock,\n currentItemRawBeforeLock: currentItem.currentItemRawBeforeLock,\n author,\n force: options.force,\n loadedItem: currentItem.loadedItem,\n historyPath,\n rewrittenEntries,\n })),\n );\n }\n\n const firstRetainedEntry =\n boundary.retainedCount > 0 ? boundary.compactCount + 1 : null;\n return {\n id: subject.id,\n dry_run: dryRun,\n changed,\n compact_boundary: {\n kind: boundary.kind,\n before: boundary.raw,\n entries_compacted: boundary.compactCount,\n entries_retained: boundary.retainedCount,\n first_retained_entry: firstRetainedEntry,\n },\n history: {\n path: historyPath,\n entries_scanned: historyEntries.length,\n entries_after: rewrittenEntries.length,\n baseline_entry_added: baselineEntryAdded,\n audit_entry_added: auditEntryAdded,\n verify_ok: rewrittenVerify.ok,\n verify_errors: rewrittenVerify.errors,\n },\n item: {\n exists: subject.located !== null,\n path: subject.located?.itemPath ?? null,\n matched_chain_before: currentItem.matchedChainBefore,\n },\n warnings: [...new Set(warnings)].sort((left, right) =>\n left.localeCompare(right),\n ),\n generated_at: nowIso(),\n };\n}\n\n/** Default entry floor below which a stream is treated as already compact. */\nexport const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES = 3;\n\n/** Documents the bulk history compact command options payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactBulkCommandOptions {\n /** Value that configures or reports ids for this contract. */\n ids?: string[];\n /** Value that configures or reports scope for this contract. */\n scope?: HistoryCompactScope;\n /** Value that configures or reports all over for this contract. */\n allOver?: number;\n /** Value that configures or reports min entries for this contract. */\n minEntries?: number;\n /** Value that configures or reports dry run for this contract. */\n dryRun?: boolean;\n /** Value that configures or reports author for this contract. */\n author?: string;\n /** Human-readable explanation suitable for logs and agent-facing output. */\n message?: string;\n /** Value that configures or reports force for this contract. */\n force?: boolean;\n}\n\n/** Per-item outcome row in a bulk compaction pass. */\nexport interface HistoryCompactBulkItemResult {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports outcome for this contract. */\n outcome: \"compacted\" | \"skipped\" | \"errored\";\n /** Value that configures or reports entries before for this contract. */\n entries_before: number;\n /** Value that configures or reports entries after for this contract. */\n entries_after: number | null;\n /** Value that configures or reports skip reason for this contract. */\n skip_reason: HistoryCompactBulkSkipReason | null;\n /** Value that configures or reports changed for this contract. */\n changed: boolean;\n /** Value that configures or reports error for this contract. */\n error: string | null;\n}\n\n/** Documents the bulk history compact result payload exchanged by command, SDK, and package integrations. */\nexport interface HistoryCompactBulkResult {\n /** Value that configures or reports bulk for this contract. */\n bulk: true;\n /** Value that configures or reports dry run for this contract. */\n dry_run: boolean;\n /** Value that configures or reports mode for this contract. */\n mode: \"ids\" | \"scan\";\n /** Value that configures or reports scope for this contract. */\n scope: HistoryCompactScope | null;\n /** Value that configures or reports criteria for this contract. */\n criteria: {\n min_entries: number;\n all_over: number | null;\n policy_threshold_applied: boolean;\n };\n /** Value that configures or reports totals for this contract. */\n totals: {\n streams_considered: number;\n selected: number;\n items_compacted: number;\n items_skipped: number;\n items_errored: number;\n };\n /** Value that configures or reports results for this contract. */\n results: HistoryCompactBulkItemResult[];\n /** ISO 8601 timestamp recording when generated occurred. */\n generated_at: string;\n}\n\n/** Enforce the `pm history-compact` target contract shared by the CLI and MCP surfaces: exactly one selection mode — a single item `<id>`, an explicit `--ids` list, or a scan selector (`--all-over` / `--closed` / `--all-streams`). */\nexport function assertHistoryCompactTarget(\n id: string | undefined,\n bulk: { ids?: string[]; allOver?: number; scope?: HistoryCompactScope },\n): void {\n const hasIds = bulk.ids !== undefined && bulk.ids.length > 0;\n const hasScan = bulk.allOver !== undefined || bulk.scope !== undefined;\n const selectorCount =\n (id !== undefined ? 1 : 0) + (hasIds ? 1 : 0) + (hasScan ? 1 : 0);\n if (selectorCount === 0) {\n throw new PmCliError(\n \"history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).\",\n EXIT_CODE.USAGE,\n );\n }\n if (id !== undefined && (hasIds || hasScan)) {\n throw new PmCliError(\n \"history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.\",\n EXIT_CODE.USAGE,\n );\n }\n if (hasIds && hasScan) {\n throw new PmCliError(\n \"history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.\",\n EXIT_CODE.USAGE,\n );\n }\n}\n\nfunction countHistoryStreamEntries(raw: string): number {\n let count = 0;\n for (const line of raw.split(/\\r?\\n/)) {\n if (line.trim().length > 0) {\n count += 1;\n }\n }\n return count;\n}\n\nasync function collectHistoryCompactBulkCandidates(params: {\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeToFolder: Record<string, string>;\n}): Promise<{\n candidates: HistoryCompactBulkCandidate[];\n preselectionErrors: HistoryCompactBulkItemResult[];\n}> {\n const statusRegistry = resolveRuntimeStatusRegistry(params.settings.schema);\n const classifier = lifecycleClassifierFromStatusRegistry(statusRegistry);\n const items = await listAllItemMetadataLight(\n params.pmRoot,\n params.settings.item_format,\n params.typeToFolder,\n undefined,\n params.settings.schema,\n );\n const bucketById = new Map(\n items.map((item) => [item.id, classifier.classify(item.status)] as const),\n );\n const historyDir = path.join(params.pmRoot, \"history\");\n const candidates: HistoryCompactBulkCandidate[] = [];\n const preselectionErrors: HistoryCompactBulkItemResult[] = [];\n if (!(await pathExists(historyDir))) {\n return { candidates, preselectionErrors };\n }\n const historyFiles = (await fs.readdir(historyDir))\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .sort((left, right) => left.localeCompare(right));\n for (const fileName of historyFiles) {\n const historyPath = path.join(historyDir, fileName);\n const id = fileName.slice(0, -\".jsonl\".length);\n try {\n const raw = await fs.readFile(historyPath, \"utf8\");\n await runActiveOnReadHooks({ path: historyPath, scope: \"project\" });\n candidates.push({\n id,\n entries: countHistoryStreamEntries(raw),\n bucket: bucketById.get(id) ?? null,\n });\n } catch (error) {\n preselectionErrors.push({\n id,\n outcome: \"errored\",\n entries_before: 0,\n entries_after: null,\n skip_reason: null,\n changed: false,\n /* c8 ignore next -- non-Error throws are normalized in defensive fallback. */\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return { candidates, preselectionErrors };\n}\n\nasync function runHistoryCompactBulkRow(params: {\n row: ReturnType<typeof selectHistoryCompactBulkTargets>[number];\n options: HistoryCompactBulkCommandOptions;\n dryRun: boolean;\n global: GlobalOptions;\n}): Promise<{\n result: HistoryCompactBulkItemResult;\n selected: boolean;\n compacted: boolean;\n errored: boolean;\n}> {\n if (!params.row.selected) {\n return {\n selected: false,\n compacted: false,\n errored: false,\n result: {\n id: params.row.id,\n outcome: \"skipped\",\n entries_before: params.row.entries,\n entries_after: null,\n skip_reason: params.row.skip_reason,\n changed: false,\n error: null,\n },\n };\n }\n try {\n const result = await runHistoryCompact(\n params.row.id,\n {\n dryRun: params.dryRun,\n author: params.options.author,\n message: params.options.message,\n force: params.options.force,\n },\n params.global,\n );\n return {\n selected: true,\n compacted: true,\n errored: false,\n result: {\n id: params.row.id,\n outcome: \"compacted\",\n entries_before: params.row.entries,\n entries_after: result.history.entries_after,\n skip_reason: null,\n changed: result.changed,\n error: null,\n },\n };\n } catch (error) {\n return {\n selected: true,\n compacted: false,\n errored: true,\n result: {\n id: params.row.id,\n outcome: \"errored\",\n entries_before: params.row.entries,\n entries_after: null,\n skip_reason: null,\n changed: false,\n /* c8 ignore next -- non-Error throws are normalized in defensive fallback. */\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n}\n\n/**\n * Bulk history compaction: compact every history stream matching the requested\n * selection (explicit `--ids`, a `--scope` lifecycle filter, and/or an\n * `--all-over <N>` entry threshold) in one audited pass. Each selected stream is\n * compacted with the same single-item logic ({@link runHistoryCompact}); one\n * failing stream never aborts the rest, and the caller decides the exit code\n * from `totals.items_errored`.\n *\n * When `history.compact_policy` is enabled and no explicit `--all-over` is\n * given, the policy's `max_entries` is used as the scan threshold so the\n * configured policy drives the sweep.\n */\nexport async function runHistoryCompactBulk(\n options: HistoryCompactBulkCommandOptions,\n global: GlobalOptions,\n): Promise<HistoryCompactBulkResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const { candidates, preselectionErrors } =\n await collectHistoryCompactBulkCandidates({\n pmRoot,\n settings,\n typeToFolder: typeRegistry.type_to_folder,\n });\n\n const mode: \"ids\" | \"scan\" =\n options.ids !== undefined && options.ids.length > 0 ? \"ids\" : \"scan\";\n const minEntries =\n options.minEntries ?? HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES;\n const policy = settings.history.compact_policy;\n const policyThresholdApplied =\n mode === \"scan\" && options.allOver === undefined && policy.enabled;\n const allOver =\n options.allOver ??\n (policyThresholdApplied ? policy.max_entries : undefined);\n\n const selection = selectHistoryCompactBulkTargets(candidates, {\n ids: options.ids,\n scope: options.scope,\n minEntries,\n allOver,\n });\n\n const dryRun = Boolean(options.dryRun);\n const results: HistoryCompactBulkItemResult[] = [...preselectionErrors];\n const totals = {\n streams_considered: candidates.length + preselectionErrors.length,\n selected: 0,\n items_compacted: 0,\n items_skipped: 0,\n items_errored: preselectionErrors.length,\n };\n for (const row of selection) {\n const outcome = await runHistoryCompactBulkRow({\n row,\n options,\n dryRun,\n global,\n });\n results.push(outcome.result);\n if (!outcome.selected) {\n totals.items_skipped += 1;\n continue;\n }\n totals.selected += 1;\n if (outcome.compacted) {\n totals.items_compacted += 1;\n }\n if (outcome.errored) {\n totals.items_errored += 1;\n }\n }\n\n return {\n bulk: true,\n dry_run: dryRun,\n mode,\n scope: options.scope ?? null,\n criteria: {\n min_entries: minEntries,\n all_over: allOver ?? null,\n policy_threshold_applied: policyThresholdApplied,\n },\n totals,\n results,\n generated_at: nowIso(),\n };\n}\n","/**\n * @module core/history/history-compact-bulk\n *\n * Pure selection logic for bulk history-stream compaction. Given a set of\n * history-stream candidates (id, entry count, and lifecycle bucket of the\n * owning item) plus the requested selection criteria, this module decides which\n * streams should be compacted and which are skipped (and why).\n *\n * The module performs no filesystem access and imports no heavy runtime\n * dependencies — the command layer reads streams and item statuses, hands the\n * resolved candidates here, then executes per-item compaction on the selection\n * this module returns. Keeping selection pure makes the matrix of scope /\n * threshold / explicit-id rules trivially testable without touching disk.\n */\n\nimport type { LifecycleBucket } from \"../governance/metadata-coverage.js\";\n\n/** Bulk-compaction scope: only closed items, or every history stream. */\nexport type HistoryCompactScope = \"closed\" | \"all-streams\";\n\n/** Why a candidate stream was not selected for compaction. */\nexport type HistoryCompactBulkSkipReason =\n | \"no_stream\"\n | \"already_compact\"\n | \"scope_mismatch\"\n | \"below_threshold\";\n\n/**\n * One history stream considered for bulk compaction.\n *\n * `bucket` is the lifecycle bucket of the owning item, or `null` when no item\n * matches the stream (an orphan history file). Orphan streams never satisfy a\n * `closed` scope filter but are eligible under `all-streams`.\n */\nexport interface HistoryCompactBulkCandidate {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports entries for this contract. */\n entries: number;\n /** Value that configures or reports bucket for this contract. */\n bucket: LifecycleBucket | null;\n}\n\n/** Selection criteria resolved from the command flags + policy defaults. */\nexport interface HistoryCompactBulkCriteria {\n /** Explicit, ordered list of item ids to compact. When non-empty the selection runs in \"ids\" mode: scope/allOver are ignored and only the `minEntries` floor applies. Duplicates are collapsed, preserving first-seen order. */\n ids?: string[];\n /** Lifecycle scope filter for scan mode (ignored in ids mode). */\n scope?: HistoryCompactScope;\n /** Streams with at most this many entries are skipped as `already_compact` (compaction collapses a stream to a 2-entry baseline+audit pair, so smaller streams gain nothing). Applies in both modes. */\n minEntries: number;\n /** Scan mode only: when set, only streams with strictly more entries than this are selected. Streams above `minEntries` but at/below `allOver` are skipped as `below_threshold`. */\n allOver?: number;\n}\n\n/** Per-candidate selection outcome. */\nexport interface HistoryCompactBulkSelectionRow {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports entries for this contract. */\n entries: number;\n /** Value that configures or reports selected for this contract. */\n selected: boolean;\n /** Value that configures or reports skip reason for this contract. */\n skip_reason: HistoryCompactBulkSkipReason | null;\n}\n\nfunction selectIdsMode(\n ids: string[],\n byId: ReadonlyMap<string, HistoryCompactBulkCandidate>,\n minEntries: number,\n): HistoryCompactBulkSelectionRow[] {\n const seen = new Set<string>();\n const rows: HistoryCompactBulkSelectionRow[] = [];\n for (const rawId of ids) {\n const id = rawId.trim();\n if (id.length === 0 || seen.has(id)) {\n continue;\n }\n seen.add(id);\n const candidate = byId.get(id);\n if (candidate === undefined) {\n rows.push({ id, entries: 0, selected: false, skip_reason: \"no_stream\" });\n continue;\n }\n if (candidate.entries <= minEntries) {\n rows.push({\n id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"already_compact\",\n });\n continue;\n }\n rows.push({\n id,\n entries: candidate.entries,\n selected: true,\n skip_reason: null,\n });\n }\n return rows;\n}\n\nfunction selectScanMode(\n candidates: HistoryCompactBulkCandidate[],\n criteria: HistoryCompactBulkCriteria,\n): HistoryCompactBulkSelectionRow[] {\n const ordered = [...candidates].sort(\n (a, b) => b.entries - a.entries || a.id.localeCompare(b.id),\n );\n const rows: HistoryCompactBulkSelectionRow[] = [];\n for (const candidate of ordered) {\n if (criteria.scope === \"closed\" && candidate.bucket !== \"closed\") {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"scope_mismatch\",\n });\n continue;\n }\n if (candidate.entries <= criteria.minEntries) {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"already_compact\",\n });\n continue;\n }\n if (\n criteria.allOver !== undefined &&\n candidate.entries <= criteria.allOver\n ) {\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: false,\n skip_reason: \"below_threshold\",\n });\n continue;\n }\n rows.push({\n id: candidate.id,\n entries: candidate.entries,\n selected: true,\n skip_reason: null,\n });\n }\n return rows;\n}\n\n/**\n * Decide which history streams to compact.\n *\n * Runs in \"ids\" mode when `criteria.ids` is non-empty (exact, ordered set,\n * honouring only the `minEntries` floor) and \"scan\" mode otherwise (every\n * candidate, filtered by scope and entry thresholds, ordered deepest-first).\n */\nexport function selectHistoryCompactBulkTargets(\n candidates: HistoryCompactBulkCandidate[],\n criteria: HistoryCompactBulkCriteria,\n): HistoryCompactBulkSelectionRow[] {\n if (criteria.ids !== undefined && criteria.ids.length > 0) {\n const byId = new Map(\n candidates.map((candidate) => [candidate.id, candidate]),\n );\n return selectIdsMode(criteria.ids, byId, criteria.minEntries);\n }\n return selectScanMode(candidates, criteria);\n}\n"],"names":["compactCount"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;;;AC6DjB,SAAS,cACP,KACA,MACA,YAAkB;AAElB,QAAM,OAAO,oBAAI,IAAG;AACpB,QAAM,OAAyC,CAAA;AAC/C,aAAW,SAAS,KAAK;AACvB,UAAM,KAAK,MAAM,KAAI;AACrB,QAAI,GAAG,WAAW,KAAK,KAAK,IAAI,EAAE,GAAG;AACnC;IACF;AACA,SAAK,IAAI,EAAE;AACX,UAAM,YAAY,KAAK,IAAI,EAAE;AAC7B,QAAI,cAAc,QAAW;AAC3B,WAAK,KAAK,EAAE,IAAI,SAAS,GAAG,UAAU,OAAO,aAAa,YAAW,CAAE;AACvE;IACF;AACA,QAAI,UAAU,WAAW,YAAY;AACnC,WAAK,KAAK;QACR;QACA,SAAS,UAAU;QACnB,UAAU;QACV,aAAa;OACd;AACD;IACF;AACA,SAAK,KAAK;MACR;MACA,SAAS,UAAU;MACnB,UAAU;MACV,aAAa;KACd;EACH;AACA,SAAO;AACT;AAEA,SAAS,eACP,YACA,UAAoC;AAEpC,QAAM,UAAU,CAAC,GAAG,UAAU,EAAE,KAC9B,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;AAE7D,QAAM,OAAyC,CAAA;AAC/C,aAAW,aAAa,SAAS;AAC/B,QAAI,SAAS,UAAU,YAAY,UAAU,WAAW,UAAU;AAChE,WAAK,KAAK;QACR,IAAI,UAAU;QACd,SAAS,UAAU;QACnB,UAAU;QACV,aAAa;OACd;AACD;IACF;AACA,QAAI,UAAU,WAAW,SAAS,YAAY;AAC5C,WAAK,KAAK;QACR,IAAI,UAAU;QACd,SAAS,UAAU;QACnB,UAAU;QACV,aAAa;OACd;AAC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WM6CEN.js";
4
+ } from "./chunk-P7MTHPJQ.js";
5
5
  import {
6
6
  writeStdout
7
- } from "./chunk-3VY6MIEO.js";
7
+ } from "./chunk-LZYP423P.js";
8
8
  import {
9
9
  EXIT_CODE,
10
10
  PmCliError,
@@ -20,11 +20,54 @@ import {
20
20
  }
21
21
  })();
22
22
 
23
+ // dist/sdk/error-runtime.js
24
+ !(function() {
25
+ try {
26
+ var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
27
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "812be476-6902-5602-8bae-93d64e0aa11c");
28
+ } catch (e2) {
29
+ }
30
+ })();
31
+ function describeUnknownError(error) {
32
+ if (error instanceof PmCliError) {
33
+ return error.message;
34
+ }
35
+ if (error instanceof Error) {
36
+ return error.message;
37
+ }
38
+ return "Unknown failure";
39
+ }
40
+ function readThrownExitCode(error) {
41
+ if (typeof error !== "object" || error === null || !("exitCode" in error)) {
42
+ return void 0;
43
+ }
44
+ const exitCode = error.exitCode;
45
+ return typeof exitCode === "number" && Number.isFinite(exitCode) ? exitCode : void 0;
46
+ }
47
+ function normalizeThrownExitCode(exitCode) {
48
+ const normalized = Math.trunc(exitCode);
49
+ return normalized > EXIT_CODE.SUCCESS ? normalized : EXIT_CODE.GENERIC_FAILURE;
50
+ }
51
+ function isCommanderError(error) {
52
+ return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" && error.code.startsWith("commander.");
53
+ }
54
+ function wrapThrownErrorForSentry(error, message) {
55
+ if (error instanceof Error) {
56
+ return error;
57
+ }
58
+ const wrapped = new Error(message);
59
+ const exitCode = readThrownExitCode(error);
60
+ if (exitCode !== void 0) {
61
+ wrapped.exitCode = normalizeThrownExitCode(exitCode);
62
+ }
63
+ return wrapped;
64
+ }
65
+
23
66
  // dist/sdk/cli-bootstrap.js
24
67
  !(function() {
25
68
  try {
26
69
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
27
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "bcccd920-dfec-51d8-8a76-f4d5c6499057");
70
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "13c76bef-728a-5eba-84d2-712c8b45bdd0");
28
71
  } catch (e2) {
29
72
  }
30
73
  })();
@@ -71,13 +114,17 @@ function parseBootstrapPathToken(token, next) {
71
114
  preferred: inlinePrefix === "--pm-path="
72
115
  };
73
116
  }
117
+ var BOOTSTRAP_BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
118
+ "--no-extensions",
119
+ "--no-pager",
120
+ "--json",
121
+ "--quiet",
122
+ "--lean"
123
+ ]);
74
124
  function parseBootstrapGlobalOptions(argv) {
75
125
  let legacyPathValue;
76
126
  let pmPathValue;
77
- let noExtensions = false;
78
- let noPager = false;
79
- let json = false;
80
- let quiet = false;
127
+ const booleanFlags = /* @__PURE__ */ new Set();
81
128
  let author;
82
129
  let index = 0;
83
130
  while (index < argv.length) {
@@ -85,23 +132,8 @@ function parseBootstrapGlobalOptions(argv) {
85
132
  if (token === "--") {
86
133
  break;
87
134
  }
88
- if (token === "--no-extensions") {
89
- noExtensions = true;
90
- index += 1;
91
- continue;
92
- }
93
- if (token === "--no-pager") {
94
- noPager = true;
95
- index += 1;
96
- continue;
97
- }
98
- if (token === "--json") {
99
- json = true;
100
- index += 1;
101
- continue;
102
- }
103
- if (token === "--quiet") {
104
- quiet = true;
135
+ if (BOOTSTRAP_BOOLEAN_FLAGS.has(token)) {
136
+ booleanFlags.add(token);
105
137
  index += 1;
106
138
  continue;
107
139
  }
@@ -136,10 +168,11 @@ function parseBootstrapGlobalOptions(argv) {
136
168
  }
137
169
  return {
138
170
  path: pmPathValue ?? legacyPathValue,
139
- noExtensions,
140
- noPager,
141
- json,
142
- quiet,
171
+ noExtensions: booleanFlags.has("--no-extensions"),
172
+ noPager: booleanFlags.has("--no-pager"),
173
+ json: booleanFlags.has("--json"),
174
+ quiet: booleanFlags.has("--quiet"),
175
+ lean: booleanFlags.has("--lean"),
143
176
  ...author === "" ? { authorMissingValue: true } : author !== void 0 ? { author } : {}
144
177
  };
145
178
  }
@@ -151,7 +184,7 @@ function stripGlobalBootstrapTokens(argv) {
151
184
  if (token === "--") {
152
185
  break;
153
186
  }
154
- if (token === "--json" || token === "--quiet" || token === "--no-extensions" || token === "--no-pager" || token === "--profile" || token === "--id-only" || token === "--explain") {
187
+ if (token === "--json" || token === "--quiet" || token === "--lean" || token === "--no-extensions" || token === "--no-pager" || token === "--profile" || token === "--id-only" || token === "--full-changed-fields" || token === "--explain") {
155
188
  index += 1;
156
189
  continue;
157
190
  }
@@ -222,7 +255,7 @@ function findCommandTokenIndex(argv) {
222
255
  index += 1;
223
256
  continue;
224
257
  }
225
- if (isInlineGlobalValueToken(token) || token === "--json" || token === "--quiet" || token === "--no-extensions" || token === "--no-pager" || token === "--profile" || token === "--id-only" || token === "--explain") {
258
+ if (isInlineGlobalValueToken(token) || token === "--json" || token === "--quiet" || token === "--lean" || token === "--no-extensions" || token === "--no-pager" || token === "--profile" || token === "--id-only" || token === "--explain") {
226
259
  continue;
227
260
  }
228
261
  if (token.startsWith("-")) {
@@ -828,7 +861,7 @@ import { Command } from "commander";
828
861
  !(function() {
829
862
  try {
830
863
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
831
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "91531f42-f413-5b2b-8366-76068aade412");
864
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "50998353-b5d9-5695-851c-c238c28471d6");
832
865
  } catch (e2) {
833
866
  }
834
867
  })();
@@ -839,10 +872,15 @@ function createPmCliProgram(version) {
839
872
  },
840
873
  writeErr: () => {
841
874
  }
842
- }).option("--json", "Output JSON instead of TOON").option("--quiet", "Suppress stdout output").option("--no-changed-fields", "Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--id-only", "Print only id and status for single-item mutation output").option("--pm-path <dir>", "Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>", "Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions", "Disable extension loading").option("--no-pager", "Disable pager integration for help and long output").option("--explain", "Render extended rationale and examples in help output").option("--profile", "Print deterministic timing diagnostics").option("--author <id>", "Override mutation author for this invocation").exitOverride();
875
+ }).option("--json", "Output JSON instead of TOON").option("--lean", "Omit null and empty containers from JSON output").option("--quiet", "Suppress stdout output").option("--no-changed-fields", "Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields", "Restore the legacy full mutation envelope and changed_fields array").option("--id-only", "Print only id and status for single-item mutation output").option("--pm-path <dir>", "Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>", "Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions", "Disable extension loading").option("--no-pager", "Disable pager integration for help and long output").option("--explain", "Render extended rationale and examples in help output").option("--profile", "Print deterministic timing diagnostics").option("--author <id>", "Override mutation author for this invocation").exitOverride();
843
876
  }
844
877
 
845
878
  export {
879
+ describeUnknownError,
880
+ readThrownExitCode,
881
+ normalizeThrownExitCode,
882
+ isCommanderError,
883
+ wrapThrownErrorForSentry,
846
884
  parseBootstrapGlobalOptions,
847
885
  stripGlobalBootstrapTokens,
848
886
  parseBootstrapHelpRequest,
@@ -857,4 +895,4 @@ export {
857
895
  applyInvocationAuthorOverride,
858
896
  createPmCliProgram
859
897
  };
860
- //# sourceMappingURL=chunk-WVA4DVNV.js.map
898
+ //# sourceMappingURL=chunk-ADBTSVGK.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../../sdk/error-runtime.ts", "../../../../../../../../sdk/cli-bootstrap.ts", "../../../../../../../../sdk/invocation-author.ts", "../../../../../../../../sdk/cli-program.ts"],
4
+ "sourcesContent": ["/**\n * @module sdk/error-runtime\n *\n * Provides presentation-independent normalization for values thrown through CLI and SDK runtimes.\n */\nimport { EXIT_CODE } from \"../core/shared/constants.js\";\nimport { PmCliError } from \"../core/shared/errors.js\";\n\n/** Returns a stable message for errors and unknown thrown values. */\nexport function describeUnknownError(error: unknown): string {\n if (error instanceof PmCliError) {\n return error.message;\n }\n if (error instanceof Error) {\n return error.message;\n }\n return \"Unknown failure\";\n}\n\n/** Reads a finite numeric exit code from an arbitrary thrown value. */\nexport function readThrownExitCode(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || !(\"exitCode\" in error)) {\n return undefined;\n }\n const exitCode = (error as { exitCode?: unknown }).exitCode;\n return typeof exitCode === \"number\" && Number.isFinite(exitCode)\n ? exitCode\n : undefined;\n}\n\n/** Normalizes thrown exit codes to a positive integer failure status. */\nexport function normalizeThrownExitCode(exitCode: number): number {\n const normalized = Math.trunc(exitCode);\n return normalized > EXIT_CODE.SUCCESS\n ? normalized\n : EXIT_CODE.GENERIC_FAILURE;\n}\n\n/** Identifies errors emitted by Commander without importing its private classes. */\nexport function isCommanderError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n typeof (error as { code?: unknown }).code === \"string\" &&\n (error as { code: string }).code.startsWith(\"commander.\")\n );\n}\n\n/** Converts non-Error thrown values into errors suitable for Sentry capture. */\nexport function wrapThrownErrorForSentry(\n error: unknown,\n message: string,\n): Error {\n if (error instanceof Error) {\n return error;\n }\n const wrapped = new Error(message) as Error & { exitCode?: number };\n const exitCode = readThrownExitCode(error);\n /* c8 ignore next */\n if (exitCode !== undefined) {\n wrapped.exitCode = normalizeThrownExitCode(exitCode);\n }\n return wrapped;\n}\n", "/**\n * @module sdk/cli-bootstrap\n *\n * Provides public bootstrap argument normalization for embedded CLI hosts.\n */\nimport {\n EXECUTABLE_COMMAND_ALIASES,\n resolveSubcommandFlagContractsForCommand,\n type CliFlagContract,\n} from \"./cli-contracts.js\";\nexport { EXECUTABLE_COMMAND_ALIASES };\nimport { levenshteinDistanceWithinLimit } from \"../core/shared/levenshtein.js\";\n\nconst GLOBAL_VALUE_CONSUMING_FLAGS = new Set<string>([\n \"--pm-path\",\n \"--path\",\n \"--author\",\n]);\n\n/** Whether a global value-consuming flag uses its inline `--flag=value` form. */\nconst isInlineGlobalValueToken = (token: string): boolean => {\n const equalsIndex = token.indexOf(\"=\");\n return (\n equalsIndex > 0 &&\n GLOBAL_VALUE_CONSUMING_FLAGS.has(token.slice(0, equalsIndex))\n );\n};\n\n/** Whether optional bootstrap author syntax consumes the following token. */\nconst consumesBootstrapAuthorValue = (next: string | undefined): boolean => {\n return typeof next === \"string\" && !next.startsWith(\"-\");\n};\n\nfunction parseBootstrapPathToken(\n token: string,\n next: string | undefined,\n): { consumed: number; pathValue?: string; preferred: boolean } | null {\n if (token === \"--path\" || token === \"--pm-path\") {\n if (typeof next === \"string\" && next.length > 0) {\n return {\n consumed: 2,\n pathValue: next,\n preferred: token === \"--pm-path\",\n };\n }\n return {\n consumed: 1,\n preferred: token === \"--pm-path\",\n };\n }\n\n const inlinePrefix = token.startsWith(\"--path=\")\n ? \"--path=\"\n : token.startsWith(\"--pm-path=\")\n ? \"--pm-path=\"\n : undefined;\n if (!inlinePrefix) {\n return null;\n }\n\n const value = token.slice(inlinePrefix.length);\n if (value.length > 0) {\n return {\n consumed: 1,\n pathValue: value,\n preferred: inlinePrefix === \"--pm-path=\",\n };\n }\n return {\n consumed: 1,\n preferred: inlinePrefix === \"--pm-path=\",\n };\n}\n\n/** Documents the bootstrap global options payload exchanged by command, SDK, and package integrations. */\nexport interface BootstrapGlobalOptions {\n /** Filesystem path used for path resolution. */\n path?: string;\n /** Value that configures or reports no extensions for this contract. */\n noExtensions: boolean;\n /** Value that configures or reports no pager for this contract. */\n noPager: boolean;\n /** Value that configures or reports json for this contract. */\n json: boolean;\n /** Value that configures or reports quiet for this contract. */\n quiet: boolean;\n /** Whether compact JSON projection is requested. */\n lean: boolean;\n /** Invocation-wide mutation author override. */\n author?: string;\n /** Whether `--author` was present without its required value. */\n authorMissingValue?: true;\n}\n\nconst BOOTSTRAP_BOOLEAN_FLAGS = new Set([\n \"--no-extensions\",\n \"--no-pager\",\n \"--json\",\n \"--quiet\",\n \"--lean\",\n]);\n\n/** Implements parse bootstrap global options for the public runtime surface of this module. */\nexport function parseBootstrapGlobalOptions(\n argv: string[],\n): BootstrapGlobalOptions {\n let legacyPathValue: string | undefined;\n let pmPathValue: string | undefined;\n const booleanFlags = new Set<string>();\n let author: string | undefined;\n let index = 0;\n while (index < argv.length) {\n const token = argv[index];\n if (token === \"--\") {\n break;\n }\n if (BOOTSTRAP_BOOLEAN_FLAGS.has(token)) {\n booleanFlags.add(token);\n index += 1;\n continue;\n }\n const parsedPath = parseBootstrapPathToken(token, argv[index + 1]);\n if (parsedPath) {\n if (parsedPath.pathValue !== undefined) {\n if (parsedPath.preferred) {\n pmPathValue = parsedPath.pathValue;\n } else {\n legacyPathValue = parsedPath.pathValue;\n }\n }\n index += parsedPath.consumed;\n continue;\n }\n if (token === \"--author\") {\n if (consumesBootstrapAuthorValue(argv[index + 1])) {\n author = argv[index + 1];\n index += 2;\n } else {\n author = \"\";\n index += 1;\n }\n continue;\n }\n if (token.startsWith(\"--author=\")) {\n author = token.slice(\"--author=\".length);\n index += 1;\n continue;\n }\n index += 1;\n }\n return {\n path: pmPathValue ?? legacyPathValue,\n noExtensions: booleanFlags.has(\"--no-extensions\"),\n noPager: booleanFlags.has(\"--no-pager\"),\n json: booleanFlags.has(\"--json\"),\n quiet: booleanFlags.has(\"--quiet\"),\n lean: booleanFlags.has(\"--lean\"),\n ...(author === \"\"\n ? { authorMissingValue: true }\n : author !== undefined\n ? { author }\n : {}),\n };\n}\n\n/** Implements strip global bootstrap tokens for the public runtime surface of this module. */\nexport function stripGlobalBootstrapTokens(argv: string[]): string[] {\n const remaining: string[] = [];\n let index = 0;\n while (index < argv.length) {\n const token = argv[index];\n if (token === \"--\") {\n break;\n }\n if (\n token === \"--json\" ||\n token === \"--quiet\" ||\n token === \"--lean\" ||\n token === \"--no-extensions\" ||\n token === \"--no-pager\" ||\n token === \"--profile\" ||\n token === \"--id-only\" ||\n token === \"--full-changed-fields\" ||\n token === \"--explain\"\n ) {\n index += 1;\n continue;\n }\n if (token === \"--author\") {\n index += consumesBootstrapAuthorValue(argv[index + 1]) ? 2 : 1;\n continue;\n }\n if (GLOBAL_VALUE_CONSUMING_FLAGS.has(token)) {\n index += 2;\n continue;\n }\n if (isInlineGlobalValueToken(token)) {\n index += 1;\n continue;\n }\n remaining.push(token);\n index += 1;\n }\n return remaining;\n}\n\n/** Documents the bootstrap help request payload exchanged by command, SDK, and package integrations. */\nexport interface BootstrapHelpRequest {\n /** Value that configures or reports requested for this contract. */\n requested: boolean;\n /** Value that configures or reports command path tokens for this contract. */\n commandPathTokens: string[];\n}\n\n/** Implements parse bootstrap help request for the public runtime surface of this module. */\nexport function parseBootstrapHelpRequest(\n argv: string[],\n): BootstrapHelpRequest {\n const stripped = stripGlobalBootstrapTokens(argv);\n const first = stripped[0]?.trim().toLowerCase();\n if (first === \"help\") {\n const commandPathTokens: string[] = [];\n for (let index = 1; index < stripped.length; index += 1) {\n const token = stripped[index];\n if (token.startsWith(\"-\")) {\n break;\n }\n commandPathTokens.push(token.trim().toLowerCase());\n }\n return {\n requested: true,\n commandPathTokens,\n };\n }\n\n const helpFlagIndex = stripped.findIndex(\n (token) => token === \"--help\" || token === \"-h\",\n );\n if (helpFlagIndex < 0) {\n return {\n requested: false,\n commandPathTokens: [],\n };\n }\n\n const commandPathTokens: string[] = [];\n for (const token of stripped) {\n if (token.startsWith(\"-\")) {\n break;\n }\n commandPathTokens.push(token.trim().toLowerCase());\n }\n return {\n requested: true,\n commandPathTokens,\n };\n}\n\n/**\n * Index of the command token in argv — the first non-flag token, skipping the\n * value-consuming/global bootstrap flags. Returns undefined when there is none\n * (bare invocation, only global flags, or a leading `--`). Single source of truth\n * for command-position scanning shared by {@link parseBootstrapCommandName} and the\n * command-alias rewrite so their precedence rules can never drift apart.\n */\nfunction findCommandTokenIndex(argv: string[]): number | undefined {\n for (let index = 0; index < argv.length; index += 1) {\n const token = argv[index];\n if (token === \"--\") {\n return undefined;\n }\n if (token === \"--author\") {\n index += consumesBootstrapAuthorValue(argv[index + 1]) ? 1 : 0;\n continue;\n }\n if (GLOBAL_VALUE_CONSUMING_FLAGS.has(token)) {\n index += 1;\n continue;\n }\n if (\n isInlineGlobalValueToken(token) ||\n token === \"--json\" ||\n token === \"--quiet\" ||\n token === \"--lean\" ||\n token === \"--no-extensions\" ||\n token === \"--no-pager\" ||\n token === \"--profile\" ||\n token === \"--id-only\" ||\n token === \"--explain\"\n ) {\n continue;\n }\n if (token.startsWith(\"-\")) {\n continue;\n }\n return index;\n }\n return undefined;\n}\n\n/** Implements parse bootstrap command name for the public runtime surface of this module. */\nexport function parseBootstrapCommandName(argv: string[]): string | undefined {\n const index = findCommandTokenIndex(argv);\n return index === undefined ? undefined : argv[index].trim().toLowerCase();\n}\n\nfunction shouldDisablePagerForInvocation(\n argv: string[],\n bootstrapGlobal: BootstrapGlobalOptions,\n): boolean {\n if (bootstrapGlobal.noPager) {\n return true;\n }\n if (process.stdout.isTTY === true) {\n return false;\n }\n const helpRequest = parseBootstrapHelpRequest(argv);\n return helpRequest.requested;\n}\n\n/** Implements apply bootstrap pager policy for the public runtime surface of this module. */\nexport function applyBootstrapPagerPolicy(argv: string[]): () => void {\n const pagerEnvironmentKeys = [\n \"PAGER\",\n \"MANPAGER\",\n \"GIT_PAGER\",\n \"LESS\",\n ] as const;\n const previousValues = pagerEnvironmentKeys.map((key) => process.env[key]);\n const restore = (): void => {\n for (const [index, key] of pagerEnvironmentKeys.entries()) {\n const value = previousValues[index];\n if (value === undefined) {\n delete process.env[key];\n } else {\n process.env[key] = value;\n }\n }\n };\n const bootstrapGlobal = parseBootstrapGlobalOptions(argv);\n if (!shouldDisablePagerForInvocation(argv, bootstrapGlobal)) {\n return restore;\n }\n process.env.PAGER = \"cat\";\n process.env.MANPAGER = \"cat\";\n process.env.GIT_PAGER = \"cat\";\n if (\n typeof process.env.LESS !== \"string\" ||\n process.env.LESS.trim().length === 0\n ) {\n process.env.LESS = \"FRX\";\n }\n return restore;\n}\n\ntype ExtensionSubcommandAction =\n | \"init\"\n | \"install\"\n | \"uninstall\"\n | \"explore\"\n | \"manage\"\n | \"doctor\"\n | \"adopt\"\n | \"adopt-all\"\n | \"activate\"\n | \"deactivate\";\n\nconst EXTENSION_ACTION_SYNTAX_TOKENS = new Set<ExtensionSubcommandAction>([\n \"install\",\n \"uninstall\",\n \"explore\",\n \"manage\",\n \"doctor\",\n \"adopt\",\n \"adopt-all\",\n \"activate\",\n \"deactivate\",\n]);\n\n/** Implements normalize legacy extension action syntax for the public runtime surface of this module. */\nexport function normalizeLegacyExtensionActionSyntax(argv: string[]): string[] {\n const extensionIndex = findCommandTokenIndex(argv);\n if (extensionIndex === undefined || argv[extensionIndex] !== \"extension\") {\n return [...argv];\n }\n const actionToken = argv[extensionIndex + 1];\n if (!actionToken || actionToken.startsWith(\"-\")) {\n return [...argv];\n }\n if (\n !EXTENSION_ACTION_SYNTAX_TOKENS.has(\n actionToken as ExtensionSubcommandAction,\n )\n ) {\n return [...argv];\n }\n if (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n return [...argv];\n }\n const forcedActionFlag = `--${actionToken}`;\n if (argv.includes(forcedActionFlag)) {\n return [...argv];\n }\n return [\n ...argv.slice(0, extensionIndex + 1),\n forcedActionFlag,\n ...argv.slice(extensionIndex + 2),\n ];\n}\n\ntype BootstrapNormalizationReason =\n | \"legacy_extension_action\"\n | \"command_alias\"\n | \"flag_alias\"\n | \"flag_typo\"\n | \"bare_key_value\"\n | \"list_merge\";\ntype BootstrapNormalizationConfidence = \"high\" | \"medium\";\n\n/** Executable command aliases: a leading command token here is rewritten to its canonical command BEFORE commander parses, so the alias actually runs instead of merely being suggested. These are the highest-frequency aliases real agents type (telemetry: `pm show <id>` alone is the single most common unknown-command) and each target takes the same positional/flags as the alias (with `--comment`/ `--note`/`--learning` flag-aliased to `--add` on the target command). Keeping this in one place means the alias is consistent across registration, commander dispatch, telemetry, and error handling — all of which read the normalized argv. */\n/**\n * Rewrite a leading command-alias token (e.g. `show` -> `get`) in place. Only the\n * command position is considered — the same token appearing later as an argument\n * (`pm get show`) is left untouched — and only when it is not preceded by `--` or a\n * value-consuming global flag, mirroring {@link parseBootstrapCommandName}.\n */\nfunction rewriteCommandAlias(\n argv: string[],\n trace: BootstrapNormalizationEvent[],\n): string[] {\n const index = findCommandTokenIndex(argv);\n if (index === undefined) {\n return argv;\n }\n const token = argv[index];\n const canonical = EXECUTABLE_COMMAND_ALIASES[token.trim().toLowerCase()];\n if (!canonical) {\n return argv;\n }\n const rewritten = [...argv];\n rewritten[index] = canonical;\n trace.push({\n from: token,\n to: [canonical],\n reason: \"command_alias\",\n confidence: \"high\",\n });\n return rewritten;\n}\n\n/** Documents the bootstrap normalization event payload exchanged by command, SDK, and package integrations. */\nexport interface BootstrapNormalizationEvent {\n /** Value that configures or reports from for this contract. */\n from: string;\n /** Value that configures or reports to for this contract. */\n to: string[];\n /** Value that configures or reports reason for this contract. */\n reason: BootstrapNormalizationReason;\n /** Value that configures or reports confidence for this contract. */\n confidence: BootstrapNormalizationConfidence;\n}\n\n/** Documents the bootstrap invocation normalization result payload exchanged by command, SDK, and package integrations. */\nexport interface BootstrapInvocationNormalizationResult {\n /** Value that configures or reports argv for this contract. */\n argv: string[];\n /** Value that configures or reports command name for this contract. */\n commandName: string | undefined;\n /** Value that configures or reports trace for this contract. */\n trace: BootstrapNormalizationEvent[];\n}\n\ninterface FlagLookup {\n canonicalByNormalized: Map<string, string | null>;\n canonicalByCompact: Map<string, string | null>;\n canonicalComparables: Array<{ canonicalFlag: string; comparable: string }>;\n listCanonicalFlags: Set<string>;\n}\n\nfunction normalizeFlagKeyToken(raw: string): string {\n const withoutPrefix = raw.replace(/^--?/, \"\");\n return withoutPrefix\n .replace(/_/g, \"-\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .toLowerCase();\n}\n\nfunction toComparableFlagKey(raw: string): string {\n return normalizeFlagKeyToken(raw).replace(/-/g, \"\");\n}\n\nfunction markUnambiguousFlag(\n map: Map<string, string | null>,\n key: string,\n canonicalFlag: string,\n): void {\n const existing = map.get(key);\n if (existing === undefined) {\n map.set(key, canonicalFlag);\n return;\n }\n if (existing !== canonicalFlag) {\n map.set(key, null);\n }\n}\n\nfunction collectLongFlagCandidates(contract: CliFlagContract): string[] {\n const candidates: string[] = [];\n const pushLongFlag = (value: string | undefined): void => {\n if (typeof value !== \"string\") {\n return;\n }\n if (!value.startsWith(\"--\")) {\n return;\n }\n candidates.push(value);\n };\n pushLongFlag(contract.flag);\n for (const alias of contract.aliases ?? []) {\n pushLongFlag(alias);\n }\n return candidates;\n}\n\nfunction buildFlagLookup(\n commandName: string | undefined,\n contractsOverride?: CliFlagContract[],\n): FlagLookup {\n const contracts =\n contractsOverride ?? resolveSubcommandFlagContractsForCommand(commandName);\n const canonicalByNormalized = new Map<string, string | null>();\n const canonicalByCompact = new Map<string, string | null>();\n const canonicalComparablesMap = new Map<string, string>();\n const listCanonicalFlags = new Set<string>();\n for (const contract of contracts) {\n const longCandidates = collectLongFlagCandidates(contract);\n if (longCandidates.length === 0) {\n continue;\n }\n const canonicalFlag = `--${normalizeFlagKeyToken(longCandidates[0])}`;\n for (const candidate of longCandidates) {\n markUnambiguousFlag(\n canonicalByNormalized,\n normalizeFlagKeyToken(candidate),\n canonicalFlag,\n );\n markUnambiguousFlag(\n canonicalByCompact,\n toComparableFlagKey(candidate),\n canonicalFlag,\n );\n }\n const comparable = toComparableFlagKey(canonicalFlag);\n if (!canonicalComparablesMap.has(canonicalFlag)) {\n canonicalComparablesMap.set(canonicalFlag, comparable);\n }\n if (contract.list === true) {\n listCanonicalFlags.add(canonicalFlag);\n }\n }\n return {\n canonicalByNormalized,\n canonicalByCompact,\n canonicalComparables: [...canonicalComparablesMap.entries()].map(\n ([canonicalFlag, comparable]) => ({\n canonicalFlag,\n comparable,\n }),\n ),\n listCanonicalFlags,\n };\n}\n\nfunction resolveCanonicalFlag(\n rawKey: string,\n lookup: FlagLookup,\n): {\n flag: string;\n reason: \"flag_alias\" | \"flag_typo\";\n confidence: BootstrapNormalizationConfidence;\n} | null {\n const normalizedKey = normalizeFlagKeyToken(rawKey);\n const direct = lookup.canonicalByNormalized.get(normalizedKey);\n if (typeof direct === \"string\") {\n return {\n flag: direct,\n reason: \"flag_alias\",\n confidence: \"high\",\n };\n }\n const comparableKey = normalizedKey.replace(/-/g, \"\");\n const compactMatch = lookup.canonicalByCompact.get(comparableKey);\n if (typeof compactMatch === \"string\") {\n return {\n flag: compactMatch,\n reason: \"flag_alias\",\n confidence: \"high\",\n };\n }\n const maxDistance = comparableKey.length >= 8 ? 2 : 1;\n let bestDistance = Number.POSITIVE_INFINITY;\n let bestFlag: string | undefined;\n let tied = false;\n for (const candidate of lookup.canonicalComparables) {\n const distance = levenshteinDistanceWithinLimit(\n comparableKey,\n candidate.comparable,\n maxDistance,\n );\n if (distance === null) {\n continue;\n }\n if (distance < bestDistance) {\n bestDistance = distance;\n bestFlag = candidate.canonicalFlag;\n tied = false;\n continue;\n }\n if (distance === bestDistance && bestFlag !== candidate.canonicalFlag) {\n tied = true;\n }\n }\n if (\n !bestFlag ||\n tied ||\n !Number.isFinite(bestDistance) ||\n bestDistance <= 0\n ) {\n return null;\n }\n return {\n flag: bestFlag,\n reason: \"flag_typo\",\n confidence: bestDistance >= 2 ? \"medium\" : \"high\",\n };\n}\n\n/** Implements list alias plural keys for the public runtime surface of this module. */\nexport function listAliasPluralKeys(normalizedKey: string): string[] {\n const candidates = [`${normalizedKey}s`];\n if (normalizedKey.endsWith(\"y\") && normalizedKey.length > 1) {\n candidates.push(`${normalizedKey.slice(0, -1)}ies`);\n }\n return candidates;\n}\n\nfunction parseBareKeyValueToken(\n token: string,\n preserve = false,\n): { key: string; value: string } | null {\n if (preserve || token.includes(\"://\")) {\n return null;\n }\n const match = token.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);\n if (!match) {\n return null;\n }\n const key = match[1];\n const value = match[3];\n if (value.length === 0) {\n return null;\n }\n return {\n key,\n value,\n };\n}\n\nfunction normalizeLongOptionToken(\n token: string,\n lookup: FlagLookup,\n preserve = false,\n): { tokens: string[]; event?: BootstrapNormalizationEvent } {\n if (preserve || !token.startsWith(\"--\")) {\n return { tokens: [token] };\n }\n const equalsIndex = token.indexOf(\"=\");\n const key = equalsIndex >= 0 ? token.slice(0, equalsIndex) : token;\n const inlineValue =\n equalsIndex >= 0 ? token.slice(equalsIndex + 1) : undefined;\n const resolution = resolveCanonicalFlag(key, lookup);\n if (!resolution) {\n return { tokens: [token] };\n }\n const normalizedToken =\n inlineValue === undefined\n ? resolution.flag\n : `${resolution.flag}=${inlineValue}`;\n if (normalizedToken === token) {\n return { tokens: [token] };\n }\n return {\n tokens: [normalizedToken],\n event: {\n from: token,\n to: [normalizedToken],\n reason: resolution.reason,\n confidence: resolution.confidence,\n },\n };\n}\n\n/** Locate global path-value tokens that normalization must preserve literally. */\nfunction collectBootstrapPathValueIndices(argv: string[]): Set<number> {\n const indices = new Set<number>();\n let expectsValue = false;\n for (let index = 0; index < argv.length; index += 1) {\n if (expectsValue) {\n indices.add(index);\n expectsValue = false;\n continue;\n }\n const token = argv[index];\n expectsValue = token === \"--path\" || token === \"--pm-path\";\n }\n return indices;\n}\n\n// Global option flags whose value may legitimately begin with \"--\" (commander\n// accepts such values). Their value token must not be reinterpreted as a list\n// flag during coalescing. `--pm-path <dir>` and its legacy `--path <dir>`\n// alias are the documented cases; other globals\n// (--json/--quiet/--no-extensions/--no-pager/--profile) are boolean.\nfunction splitCanonicalListToken(\n token: string,\n): { flag: string; inlineValue?: string } | null {\n if (!token.startsWith(\"--\")) {\n return null;\n }\n const equalsIndex = token.indexOf(\"=\");\n if (equalsIndex < 0) {\n return { flag: token };\n }\n return {\n flag: token.slice(0, equalsIndex),\n inlineValue: token.slice(equalsIndex + 1),\n };\n}\n\ninterface ListFlagSlot {\n outputIndex: number;\n originalTokens: string[];\n values: string[];\n occurrences: number;\n}\n\ninterface ListFlagOccurrence {\n originalTokens: string[];\n value: string | undefined;\n consumed: number;\n}\n\ninterface ValuedListFlagOccurrence {\n originalTokens: string[];\n value: string;\n}\n\nfunction copyValueConsumingFlag(\n argv: string[],\n index: number,\n result: (string | null)[],\n): number {\n result.push(argv[index]);\n const next = argv[index + 1];\n if (typeof next === \"string\" && next !== \"--\") {\n result.push(next);\n return index + 2;\n }\n return index + 1;\n}\n\nfunction readListFlagOccurrence(\n argv: string[],\n index: number,\n parsed: { flag: string; inlineValue?: string },\n multiValueListFlags: Set<string>,\n): ListFlagOccurrence {\n if (parsed.inlineValue !== undefined) {\n return {\n originalTokens: [argv[index]],\n value: parsed.inlineValue,\n consumed: 1,\n };\n }\n\n const values: string[] = [];\n let valueIndex = index + 1;\n while (\n valueIndex < argv.length &&\n argv[valueIndex] !== \"--\" &&\n !argv[valueIndex].startsWith(\"-\") &&\n (values.length === 0 || multiValueListFlags.has(parsed.flag))\n ) {\n values.push(argv[valueIndex]);\n valueIndex += 1;\n }\n\n const consumed = values.length === 0 ? 1 : 1 + values.length;\n return {\n originalTokens: argv.slice(index, index + consumed),\n value: values.length === 0 ? undefined : values.join(\",\"),\n consumed,\n };\n}\n\nfunction recordListFlagOccurrence(\n slots: Map<string, ListFlagSlot>,\n result: (string | null)[],\n flag: string,\n occurrence: ValuedListFlagOccurrence,\n): void {\n const existing = slots.get(flag);\n if (existing) {\n existing.values.push(occurrence.value);\n existing.occurrences += 1;\n return;\n }\n\n slots.set(flag, {\n outputIndex: result.length,\n originalTokens: occurrence.originalTokens,\n values: [occurrence.value],\n occurrences: 1,\n });\n // Reserve the anchor position; finalized after the walk so we know the full\n // merged value or can restore the original token form for single uses.\n result.push(null);\n}\n\nfunction buildListFlagCoalescingSplices(\n slots: Map<string, ListFlagSlot>,\n multiValueListFlags: Set<string>,\n): {\n events: BootstrapNormalizationEvent[];\n splices: Array<{ outputIndex: number; tokens: string[] }>;\n} {\n const events: BootstrapNormalizationEvent[] = [];\n const splices: Array<{ outputIndex: number; tokens: string[] }> = [];\n for (const [flag, slot] of slots) {\n const shouldMerge =\n slot.occurrences >= 2 ||\n (multiValueListFlags.has(flag) && slot.originalTokens.length > 2);\n if (!shouldMerge) {\n splices.push({\n outputIndex: slot.outputIndex,\n tokens: slot.originalTokens,\n });\n continue;\n }\n const mergedToken = `${flag}=${slot.values.join(\",\")}`;\n splices.push({ outputIndex: slot.outputIndex, tokens: [mergedToken] });\n events.push({\n from: `${flag} (x${slot.occurrences})`,\n to: [mergedToken],\n reason: \"list_merge\",\n confidence: \"high\",\n });\n }\n return { events, splices };\n}\n\nfunction applyListFlagSplices(\n result: (string | null)[],\n splices: Array<{ outputIndex: number; tokens: string[] }>,\n): void {\n splices.sort((a, b) => b.outputIndex - a.outputIndex);\n for (const splice of splices) {\n result.splice(splice.outputIndex, 1, ...splice.tokens);\n }\n}\n\n/**\n * Coalesce repeated occurrences of comma-separated list flags into a single\n * `--flag=v1,v2,v3` token anchored at the FIRST occurrence. Without this,\n * Commander treats these flags as scalars and silently keeps only the last\n * value (data loss). Both `--flag value` and `--flag=value` forms are merged;\n * a value-less occurrence is preserved untouched, and a `--` terminator stops\n * coalescing (remainder is passed through verbatim).\n *\n * `valueConsumingFlags` lists option flags (e.g. global `--pm-path`) whose value\n * may itself begin with `--`. Their value token is emitted verbatim so a\n * list-flag-looking value (`--path --tags`) is never reinterpreted as a flag\n * nor allowed to swallow the following command/positional token.\n */\nexport function coalesceRepeatedListFlags(\n argv: string[],\n listFlags: Set<string>,\n valueConsumingFlags: Set<string> = new Set(),\n multiValueListFlags: Set<string> = new Set(),\n): { argv: string[]; events: BootstrapNormalizationEvent[] } {\n if (listFlags.size === 0) {\n return { argv: [...argv], events: [] };\n }\n\n const result: (string | null)[] = [];\n const slots = new Map<string, ListFlagSlot>();\n let index = 0;\n while (index < argv.length) {\n const token = argv[index];\n if (token === \"--\") {\n result.push(...argv.slice(index));\n break;\n }\n // A value-consuming option in space form owns the next token as its value,\n // even when that value begins with \"--\". Emit both verbatim so the value is\n // never misread as a list-flag occurrence.\n if (valueConsumingFlags.has(token)) {\n index = copyValueConsumingFlag(argv, index, result);\n continue;\n }\n const parsed = splitCanonicalListToken(token);\n if (!parsed || !listFlags.has(parsed.flag)) {\n result.push(token);\n index += 1;\n continue;\n }\n\n const occurrence = readListFlagOccurrence(\n argv,\n index,\n parsed,\n multiValueListFlags,\n );\n if (occurrence.value === undefined) {\n // Value-less occurrence: leave untouched, do not coalesce.\n result.push(token);\n index += occurrence.consumed;\n continue;\n }\n\n recordListFlagOccurrence(slots, result, parsed.flag, {\n originalTokens: occurrence.originalTokens,\n value: occurrence.value,\n });\n index += occurrence.consumed;\n }\n\n // Apply anchor splices from the end so earlier indices stay valid when a\n // single-occurrence anchor expands back into two tokens.\n const { events, splices } = buildListFlagCoalescingSplices(\n slots,\n multiValueListFlags,\n );\n applyListFlagSplices(result, splices);\n\n return { argv: result as string[], events };\n}\n\n/** Linked-test entry keys accepted in the two-token form `pm test <id> --add command \"npm test -- parser\"` (GH-191). Only entry-identity keys are merged: `command`/`cmd` name the shell command and `path` names the test file, so a single key=value entry is meaningful for them. Other structured keys (scope, env_set, assertions, ...) cannot form a valid standalone entry and are left for the normal parser to reject. `--remove` matches existing entries by `command=`/`path=` only, so `cmd` is excluded there. Key names mirror STRUCTURED_LINKED_TEST_KEYS in src/cli/commands/linked-test-entry.ts. */\nconst LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG: ReadonlyMap<\n string,\n ReadonlySet<string>\n> = new Map([\n [\"--add\", new Set([\"command\", \"cmd\", \"path\"])],\n [\"--remove\", new Set([\"command\", \"path\"])],\n]);\n\n/** Sandbox-safe linked-test commands legitimately start with env assignments (`PM_PATH=... PM_GLOBAL_PATH=... vitest run -- parser`), which look like bare key=value settings tokens. When the two preceding tokens are a linked-test flag plus a bare two-token key (`--add command <value>`), the value must be left intact for mergeLinkedTestTwoTokenEntries instead of being rewritten into a canonical flag (e.g. PM_PATH= -> --pm-path), which would silently corrupt the command into `--add command --pm-path ...`. */\nfunction isLinkedTestTwoTokenValuePosition(\n commandName: string | undefined,\n emittedTokens: readonly string[],\n): boolean {\n if (commandName !== \"test\" || emittedTokens.length < 2) {\n return false;\n }\n const key = emittedTokens[emittedTokens.length - 1];\n const flag = emittedTokens[emittedTokens.length - 2];\n const keys = LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(flag);\n return keys !== undefined && keys.has(key);\n}\n\nfunction shouldPreserveBareKeyValueToken(\n commandName: string | undefined,\n emittedTokens: readonly string[],\n): boolean {\n return (\n commandName === \"search\" ||\n isLinkedTestTwoTokenValuePosition(commandName, emittedTokens)\n );\n}\n\n/** Accept the two-token linked-test form `pm test <id> --add command \"npm test -- parser\"` by merging the bare key token and its single quoted value into the documented `--add command=...` shape. Without this merge Commander binds the bare key as the option value and treats the quoted command as an excess positional, failing with \"too many arguments\" (GH-191). The merge only fires when EXACTLY ONE non-flag token follows the bare key, i.e. the value was quoted into one shell token — an unquoted multi-token value stays ambiguous (it may swallow the item id), still fails fast, and is routed to targeted quoting guidance by the commander error classifier instead. */\nexport function mergeLinkedTestTwoTokenEntries(\n argv: string[],\n commandName: string | undefined,\n trace: BootstrapNormalizationEvent[],\n): string[] {\n if (commandName !== \"test\") {\n return argv;\n }\n const result: string[] = [];\n let index = 0;\n while (index < argv.length) {\n const token = argv[index];\n if (token === \"--\") {\n result.push(...argv.slice(index));\n return result;\n }\n const keys = LINKED_TEST_TWO_TOKEN_KEYS_BY_FLAG.get(token);\n const key = keys ? argv[index + 1] : undefined;\n if (!keys || typeof key !== \"string\" || !keys.has(key)) {\n result.push(token);\n index += 1;\n continue;\n }\n let runEnd = index + 2;\n while (runEnd < argv.length && !argv[runEnd].startsWith(\"-\")) {\n runEnd += 1;\n }\n if (runEnd - (index + 2) !== 1) {\n result.push(token);\n index += 1;\n continue;\n }\n const value = argv[index + 2];\n const mergedValue = `${key}=${value}`;\n result.push(token, mergedValue);\n trace.push({\n from: `${token} ${key} ${value}`,\n to: [token, mergedValue],\n reason: \"bare_key_value\",\n confidence: \"high\",\n });\n index += 3;\n }\n return result;\n}\n\n/** Implements normalize bootstrap invocation for the public runtime surface of this module. */\nexport function normalizeBootstrapInvocation(\n argv: string[],\n): BootstrapInvocationNormalizationResult {\n const trace: BootstrapNormalizationEvent[] = [];\n const legacyNormalized = normalizeLegacyExtensionActionSyntax(argv);\n if (\n legacyNormalized.length !== argv.length ||\n legacyNormalized.some((token, index) => token !== argv[index])\n ) {\n trace.push({\n from: argv.join(\" \"),\n to: [...legacyNormalized],\n reason: \"legacy_extension_action\",\n confidence: \"high\",\n });\n }\n const aliasNormalized = rewriteCommandAlias(legacyNormalized, trace);\n const commandName = parseBootstrapCommandName(aliasNormalized);\n const commandPathName = parseBootstrapCommandPathName(aliasNormalized);\n const lookup = buildFlagLookup(commandPathName ?? commandName);\n const normalizedArgv: string[] = [];\n const pathValueIndices = collectBootstrapPathValueIndices(aliasNormalized);\n for (let index = 0; index < aliasNormalized.length; index += 1) {\n const token = aliasNormalized[index];\n if (token === \"--\") {\n normalizedArgv.push(...aliasNormalized.slice(index));\n break;\n }\n const preserveCurrentToken = pathValueIndices.has(index);\n const previous = normalizedArgv[normalizedArgv.length - 1];\n if (token.startsWith(\"--\")) {\n const normalizedToken = normalizeLongOptionToken(\n token,\n lookup,\n preserveCurrentToken,\n );\n normalizedArgv.push(...normalizedToken.tokens);\n if (normalizedToken.event) {\n trace.push(normalizedToken.event);\n }\n continue;\n }\n const bareKeyValue = parseBareKeyValueToken(token, preserveCurrentToken);\n if (\n bareKeyValue &&\n !(typeof previous === \"string\" && previous.startsWith(\"-\")) &&\n !shouldPreserveBareKeyValueToken(commandName, normalizedArgv)\n ) {\n const resolution = resolveCanonicalFlag(bareKeyValue.key, lookup);\n if (resolution) {\n const replacement = [resolution.flag, bareKeyValue.value];\n normalizedArgv.push(...replacement);\n trace.push({\n from: token,\n to: replacement,\n reason: \"bare_key_value\",\n confidence: resolution.confidence,\n });\n continue;\n }\n }\n normalizedArgv.push(token);\n }\n const linkedTestNormalized = mergeLinkedTestTwoTokenEntries(\n normalizedArgv,\n commandName,\n trace,\n );\n const coalesced = coalesceRepeatedListFlags(\n linkedTestNormalized,\n lookup.listCanonicalFlags,\n GLOBAL_VALUE_CONSUMING_FLAGS,\n commandName === \"create\" ? new Set([\"--tags\"]) : new Set(),\n );\n for (const event of coalesced.events) {\n trace.push(event);\n }\n return {\n argv: coalesced.argv,\n commandName,\n trace,\n };\n}\n\nfunction parseBootstrapCommandPathName(argv: string[]): string | undefined {\n const stripped = stripGlobalBootstrapTokens(argv);\n const first = stripped[0]?.trim().toLowerCase();\n const second = stripped[1]?.trim().toLowerCase();\n if (\n (first === \"extension\" || first === \"package\" || first === \"packages\") &&\n typeof second === \"string\" &&\n second.length > 0 &&\n !second.startsWith(\"-\")\n ) {\n return `${first} ${second}`;\n }\n return first;\n}\n\n/** Implements parse bootstrap type value for the public runtime surface of this module. */\nexport function parseBootstrapTypeValue(argv: string[]): string | undefined {\n for (let index = 0; index < argv.length; index += 1) {\n const token = argv[index];\n if (token === \"--\") {\n break;\n }\n if (token === \"--type\") {\n const candidate = argv[index + 1];\n if (typeof candidate === \"string\" && candidate.trim().length > 0) {\n return candidate.trim();\n }\n continue;\n }\n if (token.startsWith(\"--type=\")) {\n const candidate = token.slice(\"--type=\".length).trim();\n if (candidate.length > 0) {\n return candidate;\n }\n }\n }\n return undefined;\n}\n\n/** Public contract for test only, shared by SDK and presentation-layer consumers. */\nexport const _testOnly = {\n buildFlagLookup,\n collectBootstrapPathValueIndices,\n collectLongFlagCandidates,\n markUnambiguousFlag,\n normalizeLongOptionToken,\n resolveCanonicalFlag,\n};\n", "/**\n * @module sdk/invocation-author\n *\n * Safely scopes invocation-wide mutation authors for one-shot and embedded CLI hosts.\n */\nimport { EXIT_CODE } from \"../core/shared/constants.js\";\nimport { PmCliError } from \"../core/shared/errors.js\";\n\n/** Apply an optional author override and return an idempotent environment restorer. */\nexport function applyInvocationAuthorOverride(\n author: string | undefined,\n): () => void {\n if (author === undefined) {\n return () => {};\n }\n const normalizedAuthor = author.trim();\n if (normalizedAuthor.length === 0) {\n throw new PmCliError(\n \"--author requires a non-empty value.\",\n EXIT_CODE.USAGE,\n {\n code: \"missing_required_argument\",\n nextSteps: [\"Pass an explicit author identifier with --author <id>.\"],\n },\n );\n }\n const previousAuthor = process.env.PM_AUTHOR;\n process.env.PM_AUTHOR = normalizedAuthor;\n let restored = false;\n return () => {\n if (restored) {\n return;\n }\n restored = true;\n if (previousAuthor === undefined) {\n delete process.env.PM_AUTHOR;\n } else {\n process.env.PM_AUTHOR = previousAuthor;\n }\n };\n}\n", "/**\n * @module sdk/cli-program\n *\n * Builds the reusable Commander root that embeds pm's universal global contracts.\n */\nimport { Command } from \"commander\";\nimport { writeStdout } from \"../core/output/output.js\";\n\n/** Create a fresh pm root program suitable for one-shot CLI or embedded hosts. */\nexport function createPmCliProgram(version: string): Command {\n return new Command()\n .name(\"pm\")\n .description(\n \"Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.\",\n )\n .version(version)\n .showHelpAfterError(false)\n .allowExcessArguments(false)\n .allowUnknownOption(false)\n .configureOutput({\n writeOut: (value) => {\n writeStdout(value);\n },\n writeErr: () => {},\n })\n .option(\"--json\", \"Output JSON instead of TOON\")\n .option(\"--lean\", \"Omit null and empty containers from JSON output\")\n .option(\"--quiet\", \"Suppress stdout output\")\n .option(\n \"--no-changed-fields\",\n \"Omit the changed_fields array from mutation output (keeps changed_field_count)\",\n )\n .option(\n \"--full-changed-fields\",\n \"Restore the legacy full mutation envelope and changed_fields array\",\n )\n .option(\n \"--id-only\",\n \"Print only id and status for single-item mutation output\",\n )\n .option(\n \"--pm-path <dir>\",\n \"Explicit tracker storage path for this command (preferred over --path)\",\n )\n .option(\n \"--path <dir>\",\n \"Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd\",\n )\n .option(\"--no-extensions\", \"Disable extension loading\")\n .option(\"--no-pager\", \"Disable pager integration for help and long output\")\n .option(\n \"--explain\",\n \"Render extended rationale and examples in help output\",\n )\n .option(\"--profile\", \"Print deterministic timing diagnostics\")\n .option(\"--author <id>\", \"Override mutation author for this invocation\")\n .exitOverride();\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASM,SAAU,qBAAqB,OAAc;AACjD,MAAI,iBAAiB,YAAY;AAC/B,WAAO,MAAM;EACf;AACA,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM;EACf;AACA,SAAO;AACT;AAGM,SAAU,mBAAmB,OAAc;AAC/C,MAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,cAAc,QAAQ;AACzE,WAAO;EACT;AACA,QAAM,WAAY,MAAiC;AACnD,SAAO,OAAO,aAAa,YAAY,OAAO,SAAS,QAAQ,IAC3D,WACA;AACN;AAGM,SAAU,wBAAwB,UAAgB;AACtD,QAAM,aAAa,KAAK,MAAM,QAAQ;AACtC,SAAO,aAAa,UAAU,UAC1B,aACA,UAAU;AAChB;AAGM,SAAU,iBAAiB,OAAc;AAC7C,SACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,OAAQ,MAA6B,SAAS,YAC7C,MAA2B,KAAK,WAAW,YAAY;AAE5D;AAGM,SAAU,yBACd,OACA,SAAe;AAEf,MAAI,iBAAiB,OAAO;AAC1B,WAAO;EACT;AACA,QAAM,UAAU,IAAI,MAAM,OAAO;AACjC,QAAM,WAAW,mBAAmB,KAAK;AAEzC,MAAI,aAAa,QAAW;AAC1B,YAAQ,WAAW,wBAAwB,QAAQ;EACrD;AAC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;EAEL;AACA,QAAM,iBAAiB,QAAQ,IAAI;AACnC,UAAQ,IAAI,YAAY;AACxB,MAAI,WAAW;AACf,SAAO,MAAK;AACV,QAAI,UAAU;AACZ;IACF;AACA,eAAW;AACX,QAAI,mBAAmB,QAAW;AAChC,aAAO,QAAQ,IAAI;IACrB,OAAO;AACL,cAAQ,IAAI,YAAY;IAC1B;EACF;AACF;;;ACnCA,SAAS,eAAe;;;;;;;;AAIlB,SAAU,mBAAmB,SAAe;AAChD,SAAO,IAAI,QAAO,EACf,KAAK,IAAI,EACT,YACC,kHAAkH,EAEnH,QAAQ,OAAO,EACf,mBAAmB,KAAK,EACxB,qBAAqB,KAAK,EAC1B,mBAAmB,KAAK,EACxB,gBAAgB;IACf,UAAU,CAAC,UAAS;AAClB,kBAAY,KAAK;IACnB;IACA,UAAU,MAAK;IAAE;GAClB,EACA,OAAO,UAAU,6BAA6B,EAC9C,OAAO,UAAU,iDAAiD,EAClE,OAAO,WAAW,wBAAwB,EAC1C,OACC,uBACA,gFAAgF,EAEjF,OACC,yBACA,oEAAoE,EAErE,OACC,aACA,0DAA0D,EAE3D,OACC,mBACA,wEAAwE,EAEzE,OACC,gBACA,gGAAgG,EAEjG,OAAO,mBAAmB,2BAA2B,EACrD,OAAO,cAAc,oDAAoD,EACzE,OACC,aACA,uDAAuD,EAExD,OAAO,aAAa,wCAAwC,EAC5D,OAAO,iBAAiB,8CAA8C,EACtE,aAAY;AACjB;",
6
+ "names": ["commandPathTokens"]
7
+ }
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2ee716ac-cc07-5826-bc55-11be6f5e5e96")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8775ca3f-019e-55ea-aff0-8921293fb8dc")}catch(e){}}();
3
3
  import {
4
4
  EXIT_CODE,
5
5
  PmCliError
@@ -34,8 +34,8 @@ function parseTags(raw) {
34
34
  if (trimmed === "") {
35
35
  return [];
36
36
  }
37
- const source = coerceJsonTagArray(trimmed) ?? trimmed;
38
- const tags = source.split(",").map((tag) => tag.trim()).filter(Boolean).map((tag) => tag.toLowerCase());
37
+ const source = coerceJsonTagArray(trimmed) ?? trimmed.split(",");
38
+ const tags = source.map((tag) => tag.trim()).filter(Boolean).map((tag) => tag.toLowerCase());
39
39
  return Array.from(new Set(tags)).sort((a, b) => a.localeCompare(b));
40
40
  }
41
41
  function collectTagFlagValues(values) {
@@ -131,7 +131,7 @@ function coerceJsonTagArray(trimmed) {
131
131
  return null;
132
132
  }
133
133
  const parsedArray = parsed;
134
- return parsedArray.map((entry) => typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean" ? String(entry).replace(/,/g, " ") : "").filter((entry) => entry.length > 0).join(",");
134
+ return parsedArray.map((entry) => typeof entry === "string" || typeof entry === "number" || typeof entry === "boolean" ? String(entry) : "").filter((entry) => entry.length > 0);
135
135
  }
136
136
  function normalizeLineEndings(value) {
137
137
  return value.replace(/\r\n/g, "\n");
@@ -186,6 +186,12 @@ function splitCsvSegments(raw) {
186
186
  function unquoteValue(value) {
187
187
  const trimmed = value.trim();
188
188
  if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
189
+ try {
190
+ const parsed = JSON.parse(trimmed);
191
+ if (typeof parsed === "string")
192
+ return parsed;
193
+ } catch {
194
+ }
189
195
  return trimmed.slice(1, -1).replace(/\\"/g, '"');
190
196
  }
191
197
  return value;
@@ -401,6 +407,6 @@ export {
401
407
  parseOptionalNumber,
402
408
  parseOptionalNonNegativeInteger
403
409
  };
404
- //# sourceMappingURL=chunk-J4FBIFU6.js.map
410
+ //# sourceMappingURL=chunk-AELMUANP.js.map
405
411
 
406
- //# debugId=2ee716ac-cc07-5826-bc55-11be6f5e5e96
412
+ //# debugId=8775ca3f-019e-55ea-aff0-8921293fb8dc