@unbrained/pm-cli 2026.7.1 → 2026.7.3

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 (625) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/CHANGELOG.md +25 -0
  3. package/CONTRIBUTING.md +2 -2
  4. package/README.md +1 -1
  5. package/dist/cli/commander-usage.d.ts +2 -0
  6. package/dist/cli/commander-usage.js +110 -86
  7. package/dist/cli/commander-usage.js.map +1 -1
  8. package/dist/cli/commands/activity.js +79 -57
  9. package/dist/cli/commands/activity.js.map +1 -1
  10. package/dist/cli/commands/aggregate.js +102 -79
  11. package/dist/cli/commands/aggregate.js.map +1 -1
  12. package/dist/cli/commands/calendar.js +278 -243
  13. package/dist/cli/commands/calendar.js.map +1 -1
  14. package/dist/cli/commands/close-many.js +176 -114
  15. package/dist/cli/commands/close-many.js.map +1 -1
  16. package/dist/cli/commands/close.js +157 -129
  17. package/dist/cli/commands/close.js.map +1 -1
  18. package/dist/cli/commands/comments-audit.js +50 -42
  19. package/dist/cli/commands/comments-audit.js.map +1 -1
  20. package/dist/cli/commands/config.d.ts +2 -0
  21. package/dist/cli/commands/config.js +443 -879
  22. package/dist/cli/commands/config.js.map +1 -1
  23. package/dist/cli/commands/context.js +365 -287
  24. package/dist/cli/commands/context.js.map +1 -1
  25. package/dist/cli/commands/contracts.js +352 -238
  26. package/dist/cli/commands/contracts.js.map +1 -1
  27. package/dist/cli/commands/create.js +32 -17
  28. package/dist/cli/commands/create.js.map +1 -1
  29. package/dist/cli/commands/dedupe-audit.js +46 -39
  30. package/dist/cli/commands/dedupe-audit.js.map +1 -1
  31. package/dist/cli/commands/dedupe-merge.js +88 -69
  32. package/dist/cli/commands/dedupe-merge.js.map +1 -1
  33. package/dist/cli/commands/extension/doctor.js +56 -67
  34. package/dist/cli/commands/extension/doctor.js.map +1 -1
  35. package/dist/cli/commands/extension/shared.js +21 -15
  36. package/dist/cli/commands/extension/shared.js.map +1 -1
  37. package/dist/cli/commands/get.js +114 -81
  38. package/dist/cli/commands/get.js.map +1 -1
  39. package/dist/cli/commands/health.d.ts +17 -0
  40. package/dist/cli/commands/health.js +545 -417
  41. package/dist/cli/commands/health.js.map +1 -1
  42. package/dist/cli/commands/history-compact.js +209 -140
  43. package/dist/cli/commands/history-compact.js.map +1 -1
  44. package/dist/cli/commands/history-redact.js +162 -119
  45. package/dist/cli/commands/history-redact.js.map +1 -1
  46. package/dist/cli/commands/history-repair.js +120 -85
  47. package/dist/cli/commands/history-repair.js.map +1 -1
  48. package/dist/cli/commands/init-agent-guidance.js +32 -19
  49. package/dist/cli/commands/init-agent-guidance.js.map +1 -1
  50. package/dist/cli/commands/init.d.ts +8 -2
  51. package/dist/cli/commands/init.js +263 -162
  52. package/dist/cli/commands/init.js.map +1 -1
  53. package/dist/cli/commands/list.js +152 -102
  54. package/dist/cli/commands/list.js.map +1 -1
  55. package/dist/cli/commands/next.js +60 -40
  56. package/dist/cli/commands/next.js.map +1 -1
  57. package/dist/cli/commands/plan.js +373 -298
  58. package/dist/cli/commands/plan.js.map +1 -1
  59. package/dist/cli/commands/profile.js +23 -15
  60. package/dist/cli/commands/profile.js.map +1 -1
  61. package/dist/cli/commands/recurrence-parsers.js +43 -25
  62. package/dist/cli/commands/recurrence-parsers.js.map +1 -1
  63. package/dist/cli/commands/reindex.d.ts +21 -5
  64. package/dist/cli/commands/reindex.js +345 -205
  65. package/dist/cli/commands/reindex.js.map +1 -1
  66. package/dist/cli/commands/restore.d.ts +8 -7
  67. package/dist/cli/commands/restore.js +105 -69
  68. package/dist/cli/commands/restore.js.map +1 -1
  69. package/dist/cli/commands/schema.js +33 -30
  70. package/dist/cli/commands/schema.js.map +1 -1
  71. package/dist/cli/commands/search.d.ts +10 -2
  72. package/dist/cli/commands/search.js +503 -470
  73. package/dist/cli/commands/search.js.map +1 -1
  74. package/dist/cli/commands/telemetry.js +98 -87
  75. package/dist/cli/commands/telemetry.js.map +1 -1
  76. package/dist/cli/commands/test-all.js +237 -168
  77. package/dist/cli/commands/test-all.js.map +1 -1
  78. package/dist/cli/commands/test.d.ts +6 -5
  79. package/dist/cli/commands/test.js +424 -344
  80. package/dist/cli/commands/test.js.map +1 -1
  81. package/dist/cli/commands/update-many.js +57 -42
  82. package/dist/cli/commands/update-many.js.map +1 -1
  83. package/dist/cli/commands/update.d.ts +1 -1
  84. package/dist/cli/commands/update.js +738 -671
  85. package/dist/cli/commands/update.js.map +1 -1
  86. package/dist/cli/commands/validate.d.ts +20 -1
  87. package/dist/cli/commands/validate.js +478 -343
  88. package/dist/cli/commands/validate.js.map +1 -1
  89. package/dist/cli/error-guidance.js +406 -361
  90. package/dist/cli/error-guidance.js.map +1 -1
  91. package/dist/cli/extension-command-help.js +27 -19
  92. package/dist/cli/extension-command-help.js.map +1 -1
  93. package/dist/cli/help-json-payload.js +57 -49
  94. package/dist/cli/help-json-payload.js.map +1 -1
  95. package/dist/cli/main.d.ts +47 -0
  96. package/dist/cli/main.js +474 -371
  97. package/dist/cli/main.js.map +1 -1
  98. package/dist/cli/migration-gates.js +22 -45
  99. package/dist/cli/migration-gates.js.map +1 -1
  100. package/dist/cli/register-list-query.js +299 -310
  101. package/dist/cli/register-list-query.js.map +1 -1
  102. package/dist/cli/register-mutation.js +763 -779
  103. package/dist/cli/register-mutation.js.map +1 -1
  104. package/dist/cli/register-operations.js +386 -362
  105. package/dist/cli/register-operations.js.map +1 -1
  106. package/dist/cli/register-setup.js +120 -101
  107. package/dist/cli/register-setup.js.map +1 -1
  108. package/dist/cli/registration-helpers.d.ts +4 -0
  109. package/dist/cli/registration-helpers.js +45 -56
  110. package/dist/cli/registration-helpers.js.map +1 -1
  111. package/dist/cli-bundle/chunks/{activity-DBLQVIP6.js → activity-5YWLSPGE.js} +9 -9
  112. package/dist/cli-bundle/chunks/activity-BIML7K2D.js +16 -0
  113. package/dist/cli-bundle/chunks/{aggregate-SDF7DUOD.js → aggregate-2V2M3JZU.js} +107 -83
  114. package/dist/cli-bundle/chunks/{aggregate-SDF7DUOD.js.map → aggregate-2V2M3JZU.js.map} +2 -2
  115. package/dist/cli-bundle/chunks/{aggregate-JTEF4BP7.js → aggregate-EK7DXML7.js} +108 -84
  116. package/dist/cli-bundle/chunks/aggregate-EK7DXML7.js.map +1 -0
  117. package/dist/cli-bundle/chunks/{append-LOVPGVPT.js → append-EZESUVJT.js} +8 -8
  118. package/dist/cli-bundle/chunks/{append-QCFJSDFL.js → append-JFG4WQMG.js} +8 -8
  119. package/dist/cli-bundle/chunks/{chunk-TP5Q5ZD3.js → chunk-32IUNTG4.js} +158 -119
  120. package/dist/cli-bundle/chunks/chunk-32IUNTG4.js.map +1 -0
  121. package/dist/cli-bundle/chunks/{chunk-BHO33VBQ.js → chunk-3W2HJKJX.js} +3 -3
  122. package/dist/cli-bundle/chunks/{chunk-VARHOHYV.js → chunk-4EXFFP7T.js} +86 -52
  123. package/dist/cli-bundle/chunks/chunk-4EXFFP7T.js.map +7 -0
  124. package/dist/cli-bundle/chunks/{chunk-4DUVCVLZ.js → chunk-4PFVUUYV.js} +2 -2
  125. package/dist/cli-bundle/chunks/{chunk-JSU5P7VS.js → chunk-4WB6S4YX.js} +308 -184
  126. package/dist/cli-bundle/chunks/chunk-4WB6S4YX.js.map +1 -0
  127. package/dist/cli-bundle/chunks/{chunk-HXTQJXWT.js → chunk-572FKBRL.js} +61 -102
  128. package/dist/cli-bundle/chunks/chunk-572FKBRL.js.map +1 -0
  129. package/dist/cli-bundle/chunks/{chunk-IJYK2T43.js → chunk-5E7N4T2Z.js} +2 -2
  130. package/dist/cli-bundle/chunks/{chunk-NKZAN7BD.js → chunk-5IZUBZBR.js} +3 -3
  131. package/dist/cli-bundle/chunks/{chunk-NOLPZMSV.js → chunk-5JIWFWOZ.js} +2 -2
  132. package/dist/cli-bundle/chunks/{chunk-FFMQB7WR.js → chunk-67LARBDL.js} +493 -404
  133. package/dist/cli-bundle/chunks/chunk-67LARBDL.js.map +1 -0
  134. package/dist/cli-bundle/chunks/{chunk-6AQZPVHQ.js → chunk-6CDCWKSX.js} +4 -4
  135. package/dist/cli-bundle/chunks/{chunk-3K2M5OYU.js → chunk-6KRFL33E.js} +308 -184
  136. package/dist/cli-bundle/chunks/chunk-6KRFL33E.js.map +7 -0
  137. package/dist/cli-bundle/chunks/{chunk-LB6TP6MC.js → chunk-6NYJGMTY.js} +2 -2
  138. package/dist/cli-bundle/chunks/{chunk-SLMUGTK3.js → chunk-7CLLC75T.js} +4 -4
  139. package/dist/cli-bundle/chunks/{chunk-2466X6E4.js → chunk-7LYO6S5A.js} +8 -8
  140. package/dist/cli-bundle/chunks/{chunk-W4ULYO7Z.js → chunk-A3OQ7TFW.js} +8 -8
  141. package/dist/cli-bundle/chunks/{chunk-5CGRF3L5.js → chunk-AIKU3IIL.js} +153 -90
  142. package/dist/cli-bundle/chunks/chunk-AIKU3IIL.js.map +1 -0
  143. package/dist/cli-bundle/chunks/{chunk-WYDHYJPO.js → chunk-AJHYQCBJ.js} +39 -5
  144. package/dist/cli-bundle/chunks/chunk-AJHYQCBJ.js.map +7 -0
  145. package/dist/cli-bundle/chunks/{chunk-VZDBVEZR.js → chunk-B4O5S7I3.js} +79 -57
  146. package/dist/cli-bundle/chunks/{chunk-VZDBVEZR.js.map → chunk-B4O5S7I3.js.map} +2 -2
  147. package/dist/cli-bundle/chunks/{chunk-OTUHB4HS.js → chunk-BE2SR6QL.js} +92 -77
  148. package/dist/cli-bundle/chunks/chunk-BE2SR6QL.js.map +1 -0
  149. package/dist/cli-bundle/chunks/{chunk-JLM7BHI7.js → chunk-BI4R7HI2.js} +75 -53
  150. package/dist/cli-bundle/chunks/chunk-BI4R7HI2.js.map +7 -0
  151. package/dist/cli-bundle/chunks/{chunk-AXIDKKAT.js → chunk-CXR3CMBQ.js} +33 -6
  152. package/dist/cli-bundle/chunks/chunk-CXR3CMBQ.js.map +1 -0
  153. package/dist/cli-bundle/chunks/{chunk-ZETXE4SE.js → chunk-ECU6MMTQ.js} +713 -613
  154. package/dist/cli-bundle/chunks/chunk-ECU6MMTQ.js.map +1 -0
  155. package/dist/cli-bundle/chunks/{chunk-2D4HATP2.js → chunk-EJ2OCBHF.js} +54 -30
  156. package/dist/cli-bundle/chunks/chunk-EJ2OCBHF.js.map +1 -0
  157. package/dist/cli-bundle/chunks/{chunk-BDTISOSD.js → chunk-EQURFOMH.js} +41 -26
  158. package/dist/cli-bundle/chunks/chunk-EQURFOMH.js.map +7 -0
  159. package/dist/cli-bundle/chunks/{chunk-GJ326ZKX.js → chunk-ER4ME5U2.js} +3 -3
  160. package/dist/cli-bundle/chunks/{chunk-HZZEHPRG.js → chunk-ERG65A2L.js} +2 -2
  161. package/dist/cli-bundle/chunks/{chunk-IZBR4NRW.js → chunk-F6WNBITZ.js} +157 -113
  162. package/dist/cli-bundle/chunks/chunk-F6WNBITZ.js.map +7 -0
  163. package/dist/cli-bundle/chunks/{chunk-L5OEFZQG.js → chunk-FH2H3CBD.js} +3 -3
  164. package/dist/cli-bundle/chunks/{chunk-JPECA746.js → chunk-FUFFPIYA.js} +2 -2
  165. package/dist/cli-bundle/chunks/{chunk-CF7RL6FR.js → chunk-FZJM2TXF.js} +110 -73
  166. package/dist/cli-bundle/chunks/chunk-FZJM2TXF.js.map +1 -0
  167. package/dist/cli-bundle/chunks/{chunk-27BXPBAY.js → chunk-GUYNUXQT.js} +3 -3
  168. package/dist/cli-bundle/chunks/{chunk-MAUKX7JC.js → chunk-GVJE5T7Q.js} +2 -2
  169. package/dist/cli-bundle/chunks/{chunk-3J6JRJ3I.js → chunk-HB4FAT3O.js} +42 -60
  170. package/dist/cli-bundle/chunks/chunk-HB4FAT3O.js.map +7 -0
  171. package/dist/cli-bundle/chunks/{chunk-55SNVXRQ.js → chunk-HQAF23Q2.js} +626 -484
  172. package/dist/cli-bundle/chunks/chunk-HQAF23Q2.js.map +7 -0
  173. package/dist/cli-bundle/chunks/{chunk-ZRP4VG5U.js → chunk-JBZ2NTKX.js} +2 -2
  174. package/dist/cli-bundle/chunks/{chunk-RMMQ74TG.js → chunk-JPATY4SE.js} +54 -30
  175. package/dist/cli-bundle/chunks/chunk-JPATY4SE.js.map +7 -0
  176. package/dist/cli-bundle/chunks/{chunk-IPYBJWTE.js → chunk-K5DT2YKM.js} +109 -72
  177. package/dist/cli-bundle/chunks/chunk-K5DT2YKM.js.map +7 -0
  178. package/dist/cli-bundle/chunks/{chunk-EJUDVUYZ.js → chunk-KEZOIPCR.js} +3 -3
  179. package/dist/cli-bundle/chunks/{chunk-RVUALSJF.js → chunk-KHVGM5CS.js} +466 -365
  180. package/dist/cli-bundle/chunks/chunk-KHVGM5CS.js.map +7 -0
  181. package/dist/cli-bundle/chunks/{chunk-YITK2PJ6.js → chunk-KS6ATO47.js} +288 -175
  182. package/dist/cli-bundle/chunks/chunk-KS6ATO47.js.map +7 -0
  183. package/dist/cli-bundle/chunks/{chunk-7R4QEMZZ.js → chunk-L4SLHV6G.js} +463 -362
  184. package/dist/cli-bundle/chunks/chunk-L4SLHV6G.js.map +1 -0
  185. package/dist/cli-bundle/chunks/{chunk-RLDHZHQS.js → chunk-LBE5QFMZ.js} +158 -114
  186. package/dist/cli-bundle/chunks/chunk-LBE5QFMZ.js.map +1 -0
  187. package/dist/cli-bundle/chunks/{chunk-22WKIL3H.js → chunk-LCWQP6NM.js} +76 -54
  188. package/dist/cli-bundle/chunks/chunk-LCWQP6NM.js.map +1 -0
  189. package/dist/cli-bundle/chunks/{chunk-KNPEF7QG.js → chunk-LOWVNZBZ.js} +91 -76
  190. package/dist/cli-bundle/chunks/chunk-LOWVNZBZ.js.map +7 -0
  191. package/dist/cli-bundle/chunks/{chunk-HYTGA6GI.js → chunk-MDHWWBNZ.js} +3 -3
  192. package/dist/cli-bundle/chunks/{chunk-N74UMG5H.js → chunk-MEZZZBYX.js} +2 -2
  193. package/dist/cli-bundle/chunks/{chunk-V3NOKJF2.js → chunk-MHRS5FUX.js} +288 -175
  194. package/dist/cli-bundle/chunks/chunk-MHRS5FUX.js.map +1 -0
  195. package/dist/cli-bundle/chunks/{chunk-3XZCOZ5J.js → chunk-NOIEVOK5.js} +391 -313
  196. package/dist/cli-bundle/chunks/chunk-NOIEVOK5.js.map +1 -0
  197. package/dist/cli-bundle/chunks/{chunk-SDR5J34Q.js → chunk-NZ7QIUP5.js} +4 -4
  198. package/dist/cli-bundle/chunks/{chunk-UYUYDGIB.js → chunk-OGLGI22K.js} +115 -67
  199. package/dist/cli-bundle/chunks/{chunk-UYUYDGIB.js.map → chunk-OGLGI22K.js.map} +1 -1
  200. package/dist/cli-bundle/chunks/{chunk-DDPTYJIM.js → chunk-P5L7Z2O6.js} +2 -2
  201. package/dist/cli-bundle/chunks/{chunk-BZCEN4JA.js → chunk-PULUSQAV.js} +492 -403
  202. package/dist/cli-bundle/chunks/chunk-PULUSQAV.js.map +7 -0
  203. package/dist/cli-bundle/chunks/{chunk-3VGN2UWE.js → chunk-QCDTQCMW.js} +22 -30
  204. package/dist/cli-bundle/chunks/chunk-QCDTQCMW.js.map +1 -0
  205. package/dist/cli-bundle/chunks/{chunk-4A3BJ675.js → chunk-QNNQAAZ5.js} +24 -18
  206. package/dist/cli-bundle/chunks/{chunk-4A3BJ675.js.map → chunk-QNNQAAZ5.js.map} +1 -1
  207. package/dist/cli-bundle/chunks/{chunk-MDPEOIGN.js → chunk-RAHINBVP.js} +60 -101
  208. package/dist/cli-bundle/chunks/chunk-RAHINBVP.js.map +7 -0
  209. package/dist/cli-bundle/chunks/{chunk-CWFNTKQJ.js → chunk-RJH5VQHW.js} +43 -61
  210. package/dist/cli-bundle/chunks/chunk-RJH5VQHW.js.map +1 -0
  211. package/dist/cli-bundle/chunks/{chunk-OGXLACHC.js → chunk-SU2E4AWU.js} +6 -6
  212. package/dist/cli-bundle/chunks/{chunk-HPPFYYOV.js → chunk-SU3TB4NS.js} +2 -2
  213. package/dist/cli-bundle/chunks/{chunk-JWXRETDF.js → chunk-SYE6WMV6.js} +626 -484
  214. package/dist/cli-bundle/chunks/chunk-SYE6WMV6.js.map +1 -0
  215. package/dist/cli-bundle/chunks/{chunk-NWMZWYYB.js → chunk-T3P7PMZP.js} +42 -27
  216. package/dist/cli-bundle/chunks/chunk-T3P7PMZP.js.map +1 -0
  217. package/dist/cli-bundle/chunks/{chunk-G7I7DEZA.js → chunk-T4XBKJ3F.js} +4 -4
  218. package/dist/cli-bundle/chunks/{chunk-RH5ZBYFD.js → chunk-T6AXEBOP.js} +23 -17
  219. package/dist/cli-bundle/chunks/{chunk-RH5ZBYFD.js.map → chunk-T6AXEBOP.js.map} +2 -2
  220. package/dist/cli-bundle/chunks/{chunk-5QFDBI4F.js → chunk-TQ6AX5SQ.js} +58 -69
  221. package/dist/cli-bundle/chunks/{chunk-5QFDBI4F.js.map → chunk-TQ6AX5SQ.js.map} +2 -2
  222. package/dist/cli-bundle/chunks/{chunk-4XOIEKSD.js → chunk-U3S2B7TA.js} +86 -52
  223. package/dist/cli-bundle/chunks/chunk-U3S2B7TA.js.map +1 -0
  224. package/dist/cli-bundle/chunks/{chunk-VICZWYGZ.js → chunk-U5TR4N7J.js} +7 -7
  225. package/dist/cli-bundle/chunks/{chunk-EVMTBV6V.js → chunk-UMNQZS4H.js} +3 -3
  226. package/dist/cli-bundle/chunks/{chunk-A7FPBAQS.js → chunk-WJA3PXW7.js} +7 -7
  227. package/dist/cli-bundle/chunks/{chunk-RGEMWD6Q.js → chunk-WRYERRZX.js} +157 -118
  228. package/dist/cli-bundle/chunks/chunk-WRYERRZX.js.map +7 -0
  229. package/dist/cli-bundle/chunks/{chunk-NUHHPVVS.js → chunk-WYOIIFSE.js} +712 -612
  230. package/dist/cli-bundle/chunks/chunk-WYOIIFSE.js.map +7 -0
  231. package/dist/cli-bundle/chunks/{chunk-4DSGXSBL.js → chunk-XRYSCRZR.js} +116 -68
  232. package/dist/cli-bundle/chunks/{chunk-4DSGXSBL.js.map → chunk-XRYSCRZR.js.map} +3 -3
  233. package/dist/cli-bundle/chunks/{chunk-NU2UEROZ.js → chunk-YF746GTH.js} +59 -70
  234. package/dist/cli-bundle/chunks/{chunk-NU2UEROZ.js.map → chunk-YF746GTH.js.map} +1 -1
  235. package/dist/cli-bundle/chunks/{chunk-JMP4E6D7.js → chunk-YPWUSH72.js} +390 -312
  236. package/dist/cli-bundle/chunks/{chunk-JMP4E6D7.js.map → chunk-YPWUSH72.js.map} +2 -2
  237. package/dist/cli-bundle/chunks/{chunk-QCWF6IYD.js → chunk-YSDFIY7N.js} +3 -3
  238. package/dist/cli-bundle/chunks/{chunk-UZIWVBE6.js → chunk-YSGTMDWC.js} +2 -2
  239. package/dist/cli-bundle/chunks/{chunk-NFDPYAIP.js → chunk-YVKZ3ANP.js} +21 -29
  240. package/dist/cli-bundle/chunks/chunk-YVKZ3ANP.js.map +7 -0
  241. package/dist/cli-bundle/chunks/{chunk-OKQ22KTH.js → chunk-Z4DGFQDH.js} +80 -58
  242. package/dist/cli-bundle/chunks/{chunk-OKQ22KTH.js.map → chunk-Z4DGFQDH.js.map} +1 -1
  243. package/dist/cli-bundle/chunks/{chunk-64HNBBFQ.js → chunk-Z5F6XZXE.js} +6 -6
  244. package/dist/cli-bundle/chunks/{chunk-AVEE5EHK.js → chunk-Z7RPDF2Y.js} +3 -3
  245. package/dist/cli-bundle/chunks/{chunk-3S2KT7NG.js → chunk-ZFTKYWIF.js} +152 -89
  246. package/dist/cli-bundle/chunks/chunk-ZFTKYWIF.js.map +7 -0
  247. package/dist/cli-bundle/chunks/{claim-T3GCKV7C.js → claim-2BGBGSVI.js} +8 -8
  248. package/dist/cli-bundle/chunks/{claim-EMQLYPRW.js → claim-5GU7OE67.js} +8 -8
  249. package/dist/cli-bundle/chunks/close-6YODBUIV.js +14 -0
  250. package/dist/cli-bundle/chunks/{close-TQYAAFJP.js → close-AFVKPR57.js} +7 -7
  251. package/dist/cli-bundle/chunks/{close-many-BG5QQIDQ.js → close-many-7KLOSYLP.js} +186 -122
  252. package/dist/cli-bundle/chunks/close-many-7KLOSYLP.js.map +7 -0
  253. package/dist/cli-bundle/chunks/{close-many-LDRVEQY2.js → close-many-JKUJMHLG.js} +187 -123
  254. package/dist/cli-bundle/chunks/close-many-JKUJMHLG.js.map +1 -0
  255. package/dist/cli-bundle/chunks/{comments-YUXJRZPQ.js → comments-DNWHEBOS.js} +9 -9
  256. package/dist/cli-bundle/chunks/{comments-QCKR2YY2.js → comments-RW23R3VE.js} +9 -9
  257. package/dist/cli-bundle/chunks/config-AUM5WBYA.js +1072 -0
  258. package/dist/cli-bundle/chunks/config-AUM5WBYA.js.map +7 -0
  259. package/dist/cli-bundle/chunks/config-OZWSA2NP.js +1062 -0
  260. package/dist/cli-bundle/chunks/config-OZWSA2NP.js.map +1 -0
  261. package/dist/cli-bundle/chunks/{context-B6275WPX.js → context-OYXRGY7S.js} +12 -12
  262. package/dist/cli-bundle/chunks/{context-OCZ3FJ4Z.js → context-PKCEHQY3.js} +12 -12
  263. package/dist/cli-bundle/chunks/{contracts-HN7ABKLP.js → contracts-L6ODXNUM.js} +320 -199
  264. package/dist/cli-bundle/chunks/contracts-L6ODXNUM.js.map +7 -0
  265. package/dist/cli-bundle/chunks/{contracts-W4FZVVD6.js → contracts-X74F2GSM.js} +321 -200
  266. package/dist/cli-bundle/chunks/contracts-X74F2GSM.js.map +1 -0
  267. package/dist/cli-bundle/chunks/{copy-DEM4DATS.js → copy-6XOR3HKN.js} +5 -5
  268. package/dist/cli-bundle/chunks/{copy-BTJOSKKT.js → copy-I4NCLBR4.js} +5 -5
  269. package/dist/cli-bundle/chunks/{create-RLRJMRTM.js → create-PM45M6PE.js} +12 -12
  270. package/dist/cli-bundle/chunks/create-Z7YCH3BE.js +28 -0
  271. package/dist/cli-bundle/chunks/{delete-BHK7VB2Z.js → delete-7YXHYG67.js} +5 -5
  272. package/dist/cli-bundle/chunks/{delete-LSVHAB4Y.js → delete-LPISP43T.js} +5 -5
  273. package/dist/cli-bundle/chunks/{deps-XHYXWEPT.js → deps-N2T26FME.js} +5 -5
  274. package/dist/cli-bundle/chunks/{deps-4UDFJRUA.js → deps-WATKQDE3.js} +5 -5
  275. package/dist/cli-bundle/chunks/{docs-GYZNVS26.js → docs-6LQ3GLM7.js} +7 -7
  276. package/dist/cli-bundle/chunks/{docs-26S44RXU.js → docs-Z3X6JZLT.js} +7 -7
  277. package/dist/cli-bundle/chunks/{eval-UYF3ZPVO.js → eval-6DCLG52D.js} +10 -10
  278. package/dist/cli-bundle/chunks/{eval-PGRVIJQU.js → eval-Y3ZCUTHK.js} +10 -10
  279. package/dist/cli-bundle/chunks/{extension-CPSLJQVE.js → extension-BNINIMT7.js} +11 -11
  280. package/dist/cli-bundle/chunks/{extension-CXJ6RELI.js → extension-QWE4YYK5.js} +11 -11
  281. package/dist/cli-bundle/chunks/{files-NQHEXUZD.js → files-6SGKHS6O.js} +7 -7
  282. package/dist/cli-bundle/chunks/{files-MBNICQFM.js → files-FUYPSOFJ.js} +7 -7
  283. package/dist/cli-bundle/chunks/{focus-DWYIG7GU.js → focus-2Q3K76G2.js} +6 -6
  284. package/dist/cli-bundle/chunks/{focus-XZW5423D.js → focus-ATLBWXXD.js} +6 -6
  285. package/dist/cli-bundle/chunks/{gc-LPVMKJQJ.js → gc-RUYEMNRF.js} +3 -3
  286. package/dist/cli-bundle/chunks/{gc-7GQYOS2G.js → gc-TDWSDR66.js} +3 -3
  287. package/dist/cli-bundle/chunks/{get-A7MAOHCU.js → get-2WGLX74N.js} +120 -80
  288. package/dist/cli-bundle/chunks/get-2WGLX74N.js.map +7 -0
  289. package/dist/cli-bundle/chunks/{get-DSDEKJ3L.js → get-LY6M2JIM.js} +121 -81
  290. package/dist/cli-bundle/chunks/get-LY6M2JIM.js.map +1 -0
  291. package/dist/cli-bundle/chunks/{health-3IPFLKXB.js → health-4RKHYS3T.js} +535 -371
  292. package/dist/cli-bundle/chunks/health-4RKHYS3T.js.map +1 -0
  293. package/dist/cli-bundle/chunks/{health-GZXGBZ36.js → health-TMFVNYRA.js} +534 -370
  294. package/dist/cli-bundle/chunks/health-TMFVNYRA.js.map +7 -0
  295. package/dist/cli-bundle/chunks/history-CGNQJXFE.js +18 -0
  296. package/dist/cli-bundle/chunks/{history-NERDJNUB.js → history-SGRRS72R.js} +8 -8
  297. package/dist/cli-bundle/chunks/{history-compact-2WRZ2WK4.js → history-compact-LOED43R3.js} +213 -134
  298. package/dist/cli-bundle/chunks/history-compact-LOED43R3.js.map +7 -0
  299. package/dist/cli-bundle/chunks/{history-compact-HR7BB4LR.js → history-compact-V5DNAQHH.js} +214 -135
  300. package/dist/cli-bundle/chunks/history-compact-V5DNAQHH.js.map +1 -0
  301. package/dist/cli-bundle/chunks/{history-redact-O3NBCNWC.js → history-redact-IRL7WJ3E.js} +9 -9
  302. package/dist/cli-bundle/chunks/history-redact-N3JK7VBW.js +19 -0
  303. package/dist/cli-bundle/chunks/{history-repair-XA3LC4GA.js → history-repair-4WVBVHFR.js} +124 -84
  304. package/dist/cli-bundle/chunks/history-repair-4WVBVHFR.js.map +1 -0
  305. package/dist/cli-bundle/chunks/{history-repair-LCMOS45X.js → history-repair-PGYQJMGD.js} +123 -83
  306. package/dist/cli-bundle/chunks/history-repair-PGYQJMGD.js.map +7 -0
  307. package/dist/cli-bundle/chunks/{init-64XDLQJB.js → init-4GESW7RM.js} +12 -12
  308. package/dist/cli-bundle/chunks/init-XIDPABA4.js +22 -0
  309. package/dist/cli-bundle/chunks/{learnings-LPKCSJX7.js → learnings-4BHWFFUV.js} +9 -9
  310. package/dist/cli-bundle/chunks/{learnings-JR6MA5TI.js → learnings-4FJY7WIW.js} +9 -9
  311. package/dist/cli-bundle/chunks/{list-G5Y65VF6.js → list-472TIOVK.js} +8 -8
  312. package/dist/cli-bundle/chunks/{list-DNBJVO3E.js → list-D7BF5CL2.js} +8 -8
  313. package/dist/cli-bundle/chunks/{next-FYTQF6HG.js → next-D5STGWI2.js} +71 -46
  314. package/dist/cli-bundle/chunks/next-D5STGWI2.js.map +1 -0
  315. package/dist/cli-bundle/chunks/{next-BCERKDUR.js → next-SFQZVX2B.js} +70 -45
  316. package/dist/cli-bundle/chunks/next-SFQZVX2B.js.map +7 -0
  317. package/dist/cli-bundle/chunks/{notes-2BMU3VVQ.js → notes-6KNOSLIT.js} +9 -9
  318. package/dist/cli-bundle/chunks/{notes-6KTGO2OJ.js → notes-W4UEICGF.js} +9 -9
  319. package/dist/cli-bundle/chunks/{plan-RKZHQVXR.js → plan-JO6V7BXO.js} +373 -279
  320. package/dist/cli-bundle/chunks/plan-JO6V7BXO.js.map +1 -0
  321. package/dist/cli-bundle/chunks/{plan-4WXEQCTN.js → plan-MJQW5XK3.js} +372 -278
  322. package/dist/cli-bundle/chunks/plan-MJQW5XK3.js.map +7 -0
  323. package/dist/cli-bundle/chunks/{profile-4OMM32CD.js → profile-3TOTMUR4.js} +27 -19
  324. package/dist/cli-bundle/chunks/profile-3TOTMUR4.js.map +7 -0
  325. package/dist/cli-bundle/chunks/{profile-QLER5ENE.js → profile-WIQY2KCV.js} +28 -20
  326. package/dist/cli-bundle/chunks/profile-WIQY2KCV.js.map +1 -0
  327. package/dist/cli-bundle/chunks/register-list-query-ELBHCCFI.js +416 -0
  328. package/dist/cli-bundle/chunks/register-list-query-ELBHCCFI.js.map +7 -0
  329. package/dist/cli-bundle/chunks/register-list-query-GAPQ6DM3.js +406 -0
  330. package/dist/cli-bundle/chunks/register-list-query-GAPQ6DM3.js.map +1 -0
  331. package/dist/cli-bundle/chunks/{register-mutation-KK7PHYYU.js → register-mutation-ROFE2YPC.js} +729 -702
  332. package/dist/cli-bundle/chunks/register-mutation-ROFE2YPC.js.map +7 -0
  333. package/dist/cli-bundle/chunks/{register-mutation-ENNDUAZG.js → register-mutation-SJWMVIJ2.js} +730 -703
  334. package/dist/cli-bundle/chunks/register-mutation-SJWMVIJ2.js.map +1 -0
  335. package/dist/cli-bundle/chunks/{register-operations-HZ6XERQG.js → register-operations-IADFVH53.js} +389 -365
  336. package/dist/cli-bundle/chunks/register-operations-IADFVH53.js.map +7 -0
  337. package/dist/cli-bundle/chunks/register-operations-MEKU3AKC.js +510 -0
  338. package/dist/cli-bundle/chunks/register-operations-MEKU3AKC.js.map +1 -0
  339. package/dist/cli-bundle/chunks/{register-setup-ZKJ53RS7.js → register-setup-3QJY43CY.js} +128 -103
  340. package/dist/cli-bundle/chunks/register-setup-3QJY43CY.js.map +7 -0
  341. package/dist/cli-bundle/chunks/{register-setup-P67EMBDJ.js → register-setup-AJWUSSQX.js} +129 -104
  342. package/dist/cli-bundle/chunks/register-setup-AJWUSSQX.js.map +1 -0
  343. package/dist/cli-bundle/chunks/{restore-4MHZFJ2E.js → restore-44IHMMZZ.js} +9 -9
  344. package/dist/cli-bundle/chunks/restore-EXHU34EU.js +17 -0
  345. package/dist/cli-bundle/chunks/{scheduling-shortcuts-LB6DOLRL.js → scheduling-shortcuts-OLHNLAZY.js} +12 -12
  346. package/dist/cli-bundle/chunks/{scheduling-shortcuts-UTOYKLXQ.js → scheduling-shortcuts-TSBK4AY5.js} +12 -12
  347. package/dist/cli-bundle/chunks/{schema-73HR2OJW.js → schema-IB2NZZWD.js} +7 -7
  348. package/dist/cli-bundle/chunks/{schema-U6LJKSIR.js → schema-VBCELP5G.js} +7 -7
  349. package/dist/cli-bundle/chunks/{search-AXPXKZER.js → search-7UBETML4.js} +10 -10
  350. package/dist/cli-bundle/chunks/{search-KILGT37L.js → search-R227JOL6.js} +10 -10
  351. package/dist/cli-bundle/chunks/{stats-W5KNVJWQ.js → stats-FAG7COEH.js} +6 -6
  352. package/dist/cli-bundle/chunks/{stats-PSYVVTNZ.js → stats-MCK7PLYS.js} +6 -6
  353. package/dist/cli-bundle/chunks/{telemetry-GAHHQTOS.js → telemetry-DRPDZMAO.js} +84 -70
  354. package/dist/cli-bundle/chunks/telemetry-DRPDZMAO.js.map +7 -0
  355. package/dist/cli-bundle/chunks/{telemetry-BZUF6H7G.js → telemetry-GVVUQSJQ.js} +85 -71
  356. package/dist/cli-bundle/chunks/telemetry-GVVUQSJQ.js.map +1 -0
  357. package/dist/cli-bundle/chunks/{test-PWDIZ255.js → test-QY44WAMR.js} +15 -15
  358. package/dist/cli-bundle/chunks/{test-ACD52Z3S.js → test-SY76DZTO.js} +15 -15
  359. package/dist/cli-bundle/chunks/test-all-QD6QAEG7.js +430 -0
  360. package/dist/cli-bundle/chunks/test-all-QD6QAEG7.js.map +7 -0
  361. package/dist/cli-bundle/chunks/test-all-USPJHXFR.js +427 -0
  362. package/dist/cli-bundle/chunks/test-all-USPJHXFR.js.map +1 -0
  363. package/dist/cli-bundle/chunks/{test-runs-UXIXPDKU.js → test-runs-MG5VIGSK.js} +185 -147
  364. package/dist/cli-bundle/chunks/test-runs-MG5VIGSK.js.map +1 -0
  365. package/dist/cli-bundle/chunks/{test-runs-PLRAZEFW.js → test-runs-QIR5MJPL.js} +184 -146
  366. package/dist/cli-bundle/chunks/test-runs-QIR5MJPL.js.map +7 -0
  367. package/dist/cli-bundle/chunks/update-A7EICML6.js +24 -0
  368. package/dist/cli-bundle/chunks/{update-KFX2SIAC.js → update-IKJZWLQC.js} +15 -15
  369. package/dist/cli-bundle/chunks/{update-many-RNSBX2TA.js → update-many-BEMTDA2X.js} +84 -69
  370. package/dist/cli-bundle/chunks/{update-many-RNSBX2TA.js.map → update-many-BEMTDA2X.js.map} +1 -1
  371. package/dist/cli-bundle/chunks/{update-many-Z5GJS5LC.js → update-many-RATAARHU.js} +83 -68
  372. package/dist/cli-bundle/chunks/{update-many-Z5GJS5LC.js.map → update-many-RATAARHU.js.map} +2 -2
  373. package/dist/cli-bundle/chunks/{upgrade-BRL6KCOJ.js → upgrade-NWMR3VQL.js} +11 -11
  374. package/dist/cli-bundle/chunks/{upgrade-HAK6JG2O.js → upgrade-VU46BLJZ.js} +11 -11
  375. package/dist/cli-bundle/chunks/{validate-X5W76YJL.js → validate-GAJ6FUSI.js} +451 -321
  376. package/dist/cli-bundle/chunks/validate-GAJ6FUSI.js.map +1 -0
  377. package/dist/cli-bundle/chunks/{validate-MTUVL5VC.js → validate-NRY6MFXN.js} +450 -320
  378. package/dist/cli-bundle/chunks/validate-NRY6MFXN.js.map +7 -0
  379. package/dist/cli-bundle/main.js +1107 -916
  380. package/dist/cli-bundle/main.js.map +3 -3
  381. package/dist/core/config/nested-settings.js +89 -67
  382. package/dist/core/config/nested-settings.js.map +1 -1
  383. package/dist/core/governance/metadata-coverage.js +20 -28
  384. package/dist/core/governance/metadata-coverage.js.map +1 -1
  385. package/dist/core/history/drift-scan.js +93 -81
  386. package/dist/core/history/drift-scan.js.map +1 -1
  387. package/dist/core/item/item-type-definition.js +14 -14
  388. package/dist/core/item/item-type-definition.js.map +1 -1
  389. package/dist/core/item/type-registry.js +114 -99
  390. package/dist/core/item/type-registry.js.map +1 -1
  391. package/dist/core/output/mutation-projection.js +42 -26
  392. package/dist/core/output/mutation-projection.js.map +1 -1
  393. package/dist/core/schema/runtime-schema.js +97 -80
  394. package/dist/core/schema/runtime-schema.js.map +1 -1
  395. package/dist/core/schema/status-defs-file.js +26 -3
  396. package/dist/core/schema/status-defs-file.js.map +1 -1
  397. package/dist/core/search/corpus.js +25 -19
  398. package/dist/core/search/corpus.js.map +1 -1
  399. package/dist/core/search/semantic-defaults.js +64 -37
  400. package/dist/core/search/semantic-defaults.js.map +1 -1
  401. package/dist/core/search/vector-stores.js +32 -17
  402. package/dist/core/search/vector-stores.js.map +1 -1
  403. package/dist/core/sentry/helpers.js +31 -28
  404. package/dist/core/sentry/helpers.js.map +1 -1
  405. package/dist/core/sentry/instrument.js +54 -43
  406. package/dist/core/sentry/instrument.js.map +1 -1
  407. package/dist/core/shared/memo.d.ts +12 -0
  408. package/dist/core/shared/memo.js +25 -0
  409. package/dist/core/shared/memo.js.map +1 -0
  410. package/dist/core/shared/serialization.js +24 -14
  411. package/dist/core/shared/serialization.js.map +1 -1
  412. package/dist/core/shared/time.js +26 -4
  413. package/dist/core/shared/time.js.map +1 -1
  414. package/dist/core/store/front-matter-cache.d.ts +5 -0
  415. package/dist/core/store/front-matter-cache.js +316 -171
  416. package/dist/core/store/front-matter-cache.js.map +1 -1
  417. package/dist/core/store/item-store.js +33 -26
  418. package/dist/core/store/item-store.js.map +1 -1
  419. package/dist/core/store/settings.js +247 -203
  420. package/dist/core/store/settings.js.map +1 -1
  421. package/dist/core/test/background-runs.js +189 -160
  422. package/dist/core/test/background-runs.js.map +1 -1
  423. package/dist/sdk/cli-contracts/flag-contracts.js +71 -99
  424. package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
  425. package/dist/sdk/compose.js +51 -42
  426. package/dist/sdk/compose.js.map +1 -1
  427. package/docs/AGENT_GUIDE.md +2 -2
  428. package/docs/ARCHITECTURE.md +2 -2
  429. package/docs/COMMANDS.md +8 -4
  430. package/docs/CONFIGURATION.md +1 -1
  431. package/docs/EXTENSIONS.md +12 -12
  432. package/docs/ONBOARDING.md +4 -2
  433. package/docs/README.md +2 -0
  434. package/docs/examples/starter-extension/README.md +11 -10
  435. package/marketplace.json +3 -3
  436. package/package.json +2 -2
  437. package/packages/pm-beads/extensions/beads/runtime.ts +240 -167
  438. package/packages/pm-guide-shell/extensions/guide-shell/runtime.ts +65 -58
  439. package/packages/pm-todos/extensions/todos/runtime.ts +65 -42
  440. package/plugins/pm-claude/.claude-plugin/plugin.json +2 -2
  441. package/plugins/pm-claude/README.md +6 -3
  442. package/plugins/pm-claude/commands/pm-init.md +1 -1
  443. package/dist/cli-bundle/chunks/activity-AW6XVFH6.js +0 -16
  444. package/dist/cli-bundle/chunks/aggregate-JTEF4BP7.js.map +0 -1
  445. package/dist/cli-bundle/chunks/chunk-22WKIL3H.js.map +0 -1
  446. package/dist/cli-bundle/chunks/chunk-2D4HATP2.js.map +0 -1
  447. package/dist/cli-bundle/chunks/chunk-3J6JRJ3I.js.map +0 -7
  448. package/dist/cli-bundle/chunks/chunk-3K2M5OYU.js.map +0 -7
  449. package/dist/cli-bundle/chunks/chunk-3S2KT7NG.js.map +0 -7
  450. package/dist/cli-bundle/chunks/chunk-3VGN2UWE.js.map +0 -1
  451. package/dist/cli-bundle/chunks/chunk-3XZCOZ5J.js.map +0 -1
  452. package/dist/cli-bundle/chunks/chunk-4XOIEKSD.js.map +0 -1
  453. package/dist/cli-bundle/chunks/chunk-55SNVXRQ.js.map +0 -7
  454. package/dist/cli-bundle/chunks/chunk-5CGRF3L5.js.map +0 -1
  455. package/dist/cli-bundle/chunks/chunk-7R4QEMZZ.js.map +0 -1
  456. package/dist/cli-bundle/chunks/chunk-AXIDKKAT.js.map +0 -1
  457. package/dist/cli-bundle/chunks/chunk-BDTISOSD.js.map +0 -7
  458. package/dist/cli-bundle/chunks/chunk-BZCEN4JA.js.map +0 -7
  459. package/dist/cli-bundle/chunks/chunk-CF7RL6FR.js.map +0 -1
  460. package/dist/cli-bundle/chunks/chunk-CWFNTKQJ.js.map +0 -1
  461. package/dist/cli-bundle/chunks/chunk-FFMQB7WR.js.map +0 -1
  462. package/dist/cli-bundle/chunks/chunk-HXTQJXWT.js.map +0 -1
  463. package/dist/cli-bundle/chunks/chunk-IPYBJWTE.js.map +0 -7
  464. package/dist/cli-bundle/chunks/chunk-IZBR4NRW.js.map +0 -7
  465. package/dist/cli-bundle/chunks/chunk-JLM7BHI7.js.map +0 -7
  466. package/dist/cli-bundle/chunks/chunk-JSU5P7VS.js.map +0 -1
  467. package/dist/cli-bundle/chunks/chunk-JWXRETDF.js.map +0 -1
  468. package/dist/cli-bundle/chunks/chunk-KNPEF7QG.js.map +0 -7
  469. package/dist/cli-bundle/chunks/chunk-MDPEOIGN.js.map +0 -7
  470. package/dist/cli-bundle/chunks/chunk-NFDPYAIP.js.map +0 -7
  471. package/dist/cli-bundle/chunks/chunk-NUHHPVVS.js.map +0 -7
  472. package/dist/cli-bundle/chunks/chunk-NWMZWYYB.js.map +0 -1
  473. package/dist/cli-bundle/chunks/chunk-OTUHB4HS.js.map +0 -1
  474. package/dist/cli-bundle/chunks/chunk-RGEMWD6Q.js.map +0 -7
  475. package/dist/cli-bundle/chunks/chunk-RLDHZHQS.js.map +0 -1
  476. package/dist/cli-bundle/chunks/chunk-RMMQ74TG.js.map +0 -7
  477. package/dist/cli-bundle/chunks/chunk-RVUALSJF.js.map +0 -7
  478. package/dist/cli-bundle/chunks/chunk-TP5Q5ZD3.js.map +0 -1
  479. package/dist/cli-bundle/chunks/chunk-V3NOKJF2.js.map +0 -1
  480. package/dist/cli-bundle/chunks/chunk-VARHOHYV.js.map +0 -7
  481. package/dist/cli-bundle/chunks/chunk-WYDHYJPO.js.map +0 -7
  482. package/dist/cli-bundle/chunks/chunk-YITK2PJ6.js.map +0 -7
  483. package/dist/cli-bundle/chunks/chunk-ZETXE4SE.js.map +0 -1
  484. package/dist/cli-bundle/chunks/close-E6ZZGCJY.js +0 -14
  485. package/dist/cli-bundle/chunks/close-many-BG5QQIDQ.js.map +0 -7
  486. package/dist/cli-bundle/chunks/close-many-LDRVEQY2.js.map +0 -1
  487. package/dist/cli-bundle/chunks/config-DMSU64QO.js +0 -1541
  488. package/dist/cli-bundle/chunks/config-DMSU64QO.js.map +0 -7
  489. package/dist/cli-bundle/chunks/config-QH2DICD6.js +0 -1531
  490. package/dist/cli-bundle/chunks/config-QH2DICD6.js.map +0 -1
  491. package/dist/cli-bundle/chunks/contracts-HN7ABKLP.js.map +0 -7
  492. package/dist/cli-bundle/chunks/contracts-W4FZVVD6.js.map +0 -1
  493. package/dist/cli-bundle/chunks/create-OH3BDGBB.js +0 -28
  494. package/dist/cli-bundle/chunks/get-A7MAOHCU.js.map +0 -7
  495. package/dist/cli-bundle/chunks/get-DSDEKJ3L.js.map +0 -1
  496. package/dist/cli-bundle/chunks/health-3IPFLKXB.js.map +0 -1
  497. package/dist/cli-bundle/chunks/health-GZXGBZ36.js.map +0 -7
  498. package/dist/cli-bundle/chunks/history-WSZHY3PN.js +0 -18
  499. package/dist/cli-bundle/chunks/history-compact-2WRZ2WK4.js.map +0 -7
  500. package/dist/cli-bundle/chunks/history-compact-HR7BB4LR.js.map +0 -1
  501. package/dist/cli-bundle/chunks/history-redact-MP6CH7U5.js +0 -19
  502. package/dist/cli-bundle/chunks/history-repair-LCMOS45X.js.map +0 -7
  503. package/dist/cli-bundle/chunks/history-repair-XA3LC4GA.js.map +0 -1
  504. package/dist/cli-bundle/chunks/init-PAX32BJA.js +0 -22
  505. package/dist/cli-bundle/chunks/next-BCERKDUR.js.map +0 -7
  506. package/dist/cli-bundle/chunks/next-FYTQF6HG.js.map +0 -1
  507. package/dist/cli-bundle/chunks/plan-4WXEQCTN.js.map +0 -7
  508. package/dist/cli-bundle/chunks/plan-RKZHQVXR.js.map +0 -1
  509. package/dist/cli-bundle/chunks/profile-4OMM32CD.js.map +0 -7
  510. package/dist/cli-bundle/chunks/profile-QLER5ENE.js.map +0 -1
  511. package/dist/cli-bundle/chunks/register-list-query-7LV46VAU.js +0 -400
  512. package/dist/cli-bundle/chunks/register-list-query-7LV46VAU.js.map +0 -1
  513. package/dist/cli-bundle/chunks/register-list-query-SNG5PGA4.js +0 -410
  514. package/dist/cli-bundle/chunks/register-list-query-SNG5PGA4.js.map +0 -7
  515. package/dist/cli-bundle/chunks/register-mutation-ENNDUAZG.js.map +0 -1
  516. package/dist/cli-bundle/chunks/register-mutation-KK7PHYYU.js.map +0 -7
  517. package/dist/cli-bundle/chunks/register-operations-C6OWLDSH.js +0 -486
  518. package/dist/cli-bundle/chunks/register-operations-C6OWLDSH.js.map +0 -1
  519. package/dist/cli-bundle/chunks/register-operations-HZ6XERQG.js.map +0 -7
  520. package/dist/cli-bundle/chunks/register-setup-P67EMBDJ.js.map +0 -1
  521. package/dist/cli-bundle/chunks/register-setup-ZKJ53RS7.js.map +0 -7
  522. package/dist/cli-bundle/chunks/restore-YALDGTQR.js +0 -17
  523. package/dist/cli-bundle/chunks/telemetry-BZUF6H7G.js.map +0 -1
  524. package/dist/cli-bundle/chunks/telemetry-GAHHQTOS.js.map +0 -7
  525. package/dist/cli-bundle/chunks/test-all-L2MDDUCA.js +0 -358
  526. package/dist/cli-bundle/chunks/test-all-L2MDDUCA.js.map +0 -1
  527. package/dist/cli-bundle/chunks/test-all-RBZ6DLU2.js +0 -361
  528. package/dist/cli-bundle/chunks/test-all-RBZ6DLU2.js.map +0 -7
  529. package/dist/cli-bundle/chunks/test-runs-PLRAZEFW.js.map +0 -7
  530. package/dist/cli-bundle/chunks/test-runs-UXIXPDKU.js.map +0 -1
  531. package/dist/cli-bundle/chunks/update-AMRSOIWP.js +0 -24
  532. package/dist/cli-bundle/chunks/validate-MTUVL5VC.js.map +0 -7
  533. package/dist/cli-bundle/chunks/validate-X5W76YJL.js.map +0 -1
  534. /package/dist/cli-bundle/chunks/{activity-DBLQVIP6.js.map → activity-5YWLSPGE.js.map} +0 -0
  535. /package/dist/cli-bundle/chunks/{activity-AW6XVFH6.js.map → activity-BIML7K2D.js.map} +0 -0
  536. /package/dist/cli-bundle/chunks/{append-LOVPGVPT.js.map → append-EZESUVJT.js.map} +0 -0
  537. /package/dist/cli-bundle/chunks/{append-QCFJSDFL.js.map → append-JFG4WQMG.js.map} +0 -0
  538. /package/dist/cli-bundle/chunks/{chunk-BHO33VBQ.js.map → chunk-3W2HJKJX.js.map} +0 -0
  539. /package/dist/cli-bundle/chunks/{chunk-4DUVCVLZ.js.map → chunk-4PFVUUYV.js.map} +0 -0
  540. /package/dist/cli-bundle/chunks/{chunk-IJYK2T43.js.map → chunk-5E7N4T2Z.js.map} +0 -0
  541. /package/dist/cli-bundle/chunks/{chunk-NKZAN7BD.js.map → chunk-5IZUBZBR.js.map} +0 -0
  542. /package/dist/cli-bundle/chunks/{chunk-NOLPZMSV.js.map → chunk-5JIWFWOZ.js.map} +0 -0
  543. /package/dist/cli-bundle/chunks/{chunk-6AQZPVHQ.js.map → chunk-6CDCWKSX.js.map} +0 -0
  544. /package/dist/cli-bundle/chunks/{chunk-LB6TP6MC.js.map → chunk-6NYJGMTY.js.map} +0 -0
  545. /package/dist/cli-bundle/chunks/{chunk-SLMUGTK3.js.map → chunk-7CLLC75T.js.map} +0 -0
  546. /package/dist/cli-bundle/chunks/{chunk-2466X6E4.js.map → chunk-7LYO6S5A.js.map} +0 -0
  547. /package/dist/cli-bundle/chunks/{chunk-W4ULYO7Z.js.map → chunk-A3OQ7TFW.js.map} +0 -0
  548. /package/dist/cli-bundle/chunks/{chunk-GJ326ZKX.js.map → chunk-ER4ME5U2.js.map} +0 -0
  549. /package/dist/cli-bundle/chunks/{chunk-HZZEHPRG.js.map → chunk-ERG65A2L.js.map} +0 -0
  550. /package/dist/cli-bundle/chunks/{chunk-L5OEFZQG.js.map → chunk-FH2H3CBD.js.map} +0 -0
  551. /package/dist/cli-bundle/chunks/{chunk-JPECA746.js.map → chunk-FUFFPIYA.js.map} +0 -0
  552. /package/dist/cli-bundle/chunks/{chunk-27BXPBAY.js.map → chunk-GUYNUXQT.js.map} +0 -0
  553. /package/dist/cli-bundle/chunks/{chunk-MAUKX7JC.js.map → chunk-GVJE5T7Q.js.map} +0 -0
  554. /package/dist/cli-bundle/chunks/{chunk-ZRP4VG5U.js.map → chunk-JBZ2NTKX.js.map} +0 -0
  555. /package/dist/cli-bundle/chunks/{chunk-EJUDVUYZ.js.map → chunk-KEZOIPCR.js.map} +0 -0
  556. /package/dist/cli-bundle/chunks/{chunk-HYTGA6GI.js.map → chunk-MDHWWBNZ.js.map} +0 -0
  557. /package/dist/cli-bundle/chunks/{chunk-N74UMG5H.js.map → chunk-MEZZZBYX.js.map} +0 -0
  558. /package/dist/cli-bundle/chunks/{chunk-SDR5J34Q.js.map → chunk-NZ7QIUP5.js.map} +0 -0
  559. /package/dist/cli-bundle/chunks/{chunk-DDPTYJIM.js.map → chunk-P5L7Z2O6.js.map} +0 -0
  560. /package/dist/cli-bundle/chunks/{chunk-OGXLACHC.js.map → chunk-SU2E4AWU.js.map} +0 -0
  561. /package/dist/cli-bundle/chunks/{chunk-HPPFYYOV.js.map → chunk-SU3TB4NS.js.map} +0 -0
  562. /package/dist/cli-bundle/chunks/{chunk-G7I7DEZA.js.map → chunk-T4XBKJ3F.js.map} +0 -0
  563. /package/dist/cli-bundle/chunks/{chunk-VICZWYGZ.js.map → chunk-U5TR4N7J.js.map} +0 -0
  564. /package/dist/cli-bundle/chunks/{chunk-EVMTBV6V.js.map → chunk-UMNQZS4H.js.map} +0 -0
  565. /package/dist/cli-bundle/chunks/{chunk-A7FPBAQS.js.map → chunk-WJA3PXW7.js.map} +0 -0
  566. /package/dist/cli-bundle/chunks/{chunk-QCWF6IYD.js.map → chunk-YSDFIY7N.js.map} +0 -0
  567. /package/dist/cli-bundle/chunks/{chunk-UZIWVBE6.js.map → chunk-YSGTMDWC.js.map} +0 -0
  568. /package/dist/cli-bundle/chunks/{chunk-64HNBBFQ.js.map → chunk-Z5F6XZXE.js.map} +0 -0
  569. /package/dist/cli-bundle/chunks/{chunk-AVEE5EHK.js.map → chunk-Z7RPDF2Y.js.map} +0 -0
  570. /package/dist/cli-bundle/chunks/{claim-T3GCKV7C.js.map → claim-2BGBGSVI.js.map} +0 -0
  571. /package/dist/cli-bundle/chunks/{claim-EMQLYPRW.js.map → claim-5GU7OE67.js.map} +0 -0
  572. /package/dist/cli-bundle/chunks/{close-E6ZZGCJY.js.map → close-6YODBUIV.js.map} +0 -0
  573. /package/dist/cli-bundle/chunks/{close-TQYAAFJP.js.map → close-AFVKPR57.js.map} +0 -0
  574. /package/dist/cli-bundle/chunks/{comments-YUXJRZPQ.js.map → comments-DNWHEBOS.js.map} +0 -0
  575. /package/dist/cli-bundle/chunks/{comments-QCKR2YY2.js.map → comments-RW23R3VE.js.map} +0 -0
  576. /package/dist/cli-bundle/chunks/{context-B6275WPX.js.map → context-OYXRGY7S.js.map} +0 -0
  577. /package/dist/cli-bundle/chunks/{context-OCZ3FJ4Z.js.map → context-PKCEHQY3.js.map} +0 -0
  578. /package/dist/cli-bundle/chunks/{copy-DEM4DATS.js.map → copy-6XOR3HKN.js.map} +0 -0
  579. /package/dist/cli-bundle/chunks/{copy-BTJOSKKT.js.map → copy-I4NCLBR4.js.map} +0 -0
  580. /package/dist/cli-bundle/chunks/{create-RLRJMRTM.js.map → create-PM45M6PE.js.map} +0 -0
  581. /package/dist/cli-bundle/chunks/{create-OH3BDGBB.js.map → create-Z7YCH3BE.js.map} +0 -0
  582. /package/dist/cli-bundle/chunks/{delete-BHK7VB2Z.js.map → delete-7YXHYG67.js.map} +0 -0
  583. /package/dist/cli-bundle/chunks/{delete-LSVHAB4Y.js.map → delete-LPISP43T.js.map} +0 -0
  584. /package/dist/cli-bundle/chunks/{deps-XHYXWEPT.js.map → deps-N2T26FME.js.map} +0 -0
  585. /package/dist/cli-bundle/chunks/{deps-4UDFJRUA.js.map → deps-WATKQDE3.js.map} +0 -0
  586. /package/dist/cli-bundle/chunks/{docs-GYZNVS26.js.map → docs-6LQ3GLM7.js.map} +0 -0
  587. /package/dist/cli-bundle/chunks/{docs-26S44RXU.js.map → docs-Z3X6JZLT.js.map} +0 -0
  588. /package/dist/cli-bundle/chunks/{eval-UYF3ZPVO.js.map → eval-6DCLG52D.js.map} +0 -0
  589. /package/dist/cli-bundle/chunks/{eval-PGRVIJQU.js.map → eval-Y3ZCUTHK.js.map} +0 -0
  590. /package/dist/cli-bundle/chunks/{extension-CPSLJQVE.js.map → extension-BNINIMT7.js.map} +0 -0
  591. /package/dist/cli-bundle/chunks/{extension-CXJ6RELI.js.map → extension-QWE4YYK5.js.map} +0 -0
  592. /package/dist/cli-bundle/chunks/{files-NQHEXUZD.js.map → files-6SGKHS6O.js.map} +0 -0
  593. /package/dist/cli-bundle/chunks/{files-MBNICQFM.js.map → files-FUYPSOFJ.js.map} +0 -0
  594. /package/dist/cli-bundle/chunks/{focus-DWYIG7GU.js.map → focus-2Q3K76G2.js.map} +0 -0
  595. /package/dist/cli-bundle/chunks/{focus-XZW5423D.js.map → focus-ATLBWXXD.js.map} +0 -0
  596. /package/dist/cli-bundle/chunks/{gc-LPVMKJQJ.js.map → gc-RUYEMNRF.js.map} +0 -0
  597. /package/dist/cli-bundle/chunks/{gc-7GQYOS2G.js.map → gc-TDWSDR66.js.map} +0 -0
  598. /package/dist/cli-bundle/chunks/{history-WSZHY3PN.js.map → history-CGNQJXFE.js.map} +0 -0
  599. /package/dist/cli-bundle/chunks/{history-NERDJNUB.js.map → history-SGRRS72R.js.map} +0 -0
  600. /package/dist/cli-bundle/chunks/{history-redact-O3NBCNWC.js.map → history-redact-IRL7WJ3E.js.map} +0 -0
  601. /package/dist/cli-bundle/chunks/{history-redact-MP6CH7U5.js.map → history-redact-N3JK7VBW.js.map} +0 -0
  602. /package/dist/cli-bundle/chunks/{init-64XDLQJB.js.map → init-4GESW7RM.js.map} +0 -0
  603. /package/dist/cli-bundle/chunks/{init-PAX32BJA.js.map → init-XIDPABA4.js.map} +0 -0
  604. /package/dist/cli-bundle/chunks/{learnings-LPKCSJX7.js.map → learnings-4BHWFFUV.js.map} +0 -0
  605. /package/dist/cli-bundle/chunks/{learnings-JR6MA5TI.js.map → learnings-4FJY7WIW.js.map} +0 -0
  606. /package/dist/cli-bundle/chunks/{list-G5Y65VF6.js.map → list-472TIOVK.js.map} +0 -0
  607. /package/dist/cli-bundle/chunks/{list-DNBJVO3E.js.map → list-D7BF5CL2.js.map} +0 -0
  608. /package/dist/cli-bundle/chunks/{notes-2BMU3VVQ.js.map → notes-6KNOSLIT.js.map} +0 -0
  609. /package/dist/cli-bundle/chunks/{notes-6KTGO2OJ.js.map → notes-W4UEICGF.js.map} +0 -0
  610. /package/dist/cli-bundle/chunks/{restore-4MHZFJ2E.js.map → restore-44IHMMZZ.js.map} +0 -0
  611. /package/dist/cli-bundle/chunks/{restore-YALDGTQR.js.map → restore-EXHU34EU.js.map} +0 -0
  612. /package/dist/cli-bundle/chunks/{scheduling-shortcuts-LB6DOLRL.js.map → scheduling-shortcuts-OLHNLAZY.js.map} +0 -0
  613. /package/dist/cli-bundle/chunks/{scheduling-shortcuts-UTOYKLXQ.js.map → scheduling-shortcuts-TSBK4AY5.js.map} +0 -0
  614. /package/dist/cli-bundle/chunks/{schema-73HR2OJW.js.map → schema-IB2NZZWD.js.map} +0 -0
  615. /package/dist/cli-bundle/chunks/{schema-U6LJKSIR.js.map → schema-VBCELP5G.js.map} +0 -0
  616. /package/dist/cli-bundle/chunks/{search-AXPXKZER.js.map → search-7UBETML4.js.map} +0 -0
  617. /package/dist/cli-bundle/chunks/{search-KILGT37L.js.map → search-R227JOL6.js.map} +0 -0
  618. /package/dist/cli-bundle/chunks/{stats-W5KNVJWQ.js.map → stats-FAG7COEH.js.map} +0 -0
  619. /package/dist/cli-bundle/chunks/{stats-PSYVVTNZ.js.map → stats-MCK7PLYS.js.map} +0 -0
  620. /package/dist/cli-bundle/chunks/{test-PWDIZ255.js.map → test-QY44WAMR.js.map} +0 -0
  621. /package/dist/cli-bundle/chunks/{test-ACD52Z3S.js.map → test-SY76DZTO.js.map} +0 -0
  622. /package/dist/cli-bundle/chunks/{update-AMRSOIWP.js.map → update-A7EICML6.js.map} +0 -0
  623. /package/dist/cli-bundle/chunks/{update-KFX2SIAC.js.map → update-IKJZWLQC.js.map} +0 -0
  624. /package/dist/cli-bundle/chunks/{upgrade-BRL6KCOJ.js.map → upgrade-NWMR3VQL.js.map} +0 -0
  625. /package/dist/cli-bundle/chunks/{upgrade-HAK6JG2O.js.map → upgrade-VU46BLJZ.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../../../../../cli/commands/restore.ts"],
4
- "sourcesContent": ["/**\n * @module cli/commands/restore\n *\n * Implements the pm restore command surface and its agent-facing runtime behavior.\n */\nimport jsonPatch from \"fast-json-patch\";\nimport fs from \"node:fs/promises\";\nimport { pathExists, readFileIfExists, writeFileAtomic } from \"../../core/fs/fs-utils.js\";\nimport { appendHistoryEntry, createHistoryEntry } from \"../../core/history/history.js\";\nimport {\n EMPTY_REPLAY_DOCUMENT,\n normalizeReplayPatchOps,\n replayHash,\n replayToCanonicalItemDocument,\n replayToItemDocument,\n toReplayDocument,\n type ReplayDocument as CanonicalReplayDocument,\n} from \"../../core/history/replay.js\";\nimport { enforceHistoryStreamPolicyForItem } from \"../../core/history/history-stream-policy.js\";\nimport { normalizeItemId, normalizeRawItemId } from \"../../core/item/id.js\";\nimport { canonicalDocument, serializeItemDocument } from \"../../core/item/item-format.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { acquireLock } from \"../../core/lock/lock.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 projectAfterCommandItemSnapshot,\n recordAfterCommandAffectedItem,\n runActiveOnWriteHooks,\n} from \"../../core/extensions/index.js\";\nimport { locateItem, readLocatedItem } from \"../../core/store/item-store.js\";\nimport { getHistoryPath, getItemPath, getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { resolveAuthor } from \"../../core/shared/author.js\";\nimport type { HistoryEntry, HistoryPatchOp, ItemDocument, ItemMetadata } from \"../../types/index.js\";\nimport { readHistoryEntries } from \"./history.js\";\n\ninterface ResolvedRestoreTarget {\n kind: \"version\" | \"timestamp\";\n raw: string;\n historyIndex: number;\n}\n\ninterface ResolvedRestoreSubject {\n id: string;\n historyPath: string;\n located: Awaited<ReturnType<typeof locateItem>>;\n historyPolicyWarnings: string[];\n}\n\n/**\n * Documents the restore command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface RestoreCommandOptions {\n author?: string;\n message?: string;\n force?: boolean;\n}\n\n/**\n * Documents the restore result payload exchanged by command, SDK, and package integrations.\n */\nexport interface RestoreResult {\n item: ItemMetadata;\n restored_from: {\n kind: \"version\" | \"timestamp\";\n target: string;\n history_index: number;\n entry_ts: string;\n entry_op: string;\n };\n changed_fields: string[];\n warnings: string[];\n}\n\nfunction ensureReplayTarget(target: string, history: HistoryEntry[]): ResolvedRestoreTarget {\n const trimmed = target.trim();\n if (!trimmed) {\n throw new PmCliError(\"Missing restore target. Use a timestamp or version number.\", EXIT_CODE.USAGE);\n }\n\n if (/^\\d+$/.test(trimmed)) {\n const version = Number(trimmed);\n if (!Number.isSafeInteger(version) || version < 1 || version > history.length) {\n throw new PmCliError(\n `Restore version must be between 1 and ${history.length} for this item.`,\n EXIT_CODE.USAGE,\n );\n }\n return {\n kind: \"version\",\n raw: trimmed,\n historyIndex: version - 1,\n };\n }\n\n const parsedTarget = Date.parse(trimmed);\n if (!Number.isFinite(parsedTarget)) {\n throw new PmCliError(\n `Invalid restore target \"${target}\". Use a positive version number or ISO timestamp.`,\n EXIT_CODE.USAGE,\n );\n }\n\n let index = -1;\n for (let i = 0; i < history.length; i += 1) {\n const entryTimestamp = Date.parse(history[i].ts);\n if (!Number.isFinite(entryTimestamp)) {\n throw new PmCliError(\n `History for this item contains invalid timestamp at entry ${i + 1}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n if (entryTimestamp <= parsedTarget) {\n index = i;\n }\n }\n\n if (index < 0) {\n throw new PmCliError(`No history entries exist at or before timestamp ${trimmed}.`, EXIT_CODE.USAGE);\n }\n\n return {\n kind: \"timestamp\",\n raw: trimmed,\n historyIndex: index,\n };\n}\n\nfunction extractPatchFailureContext(\n patch: HistoryPatchOp[],\n error: unknown,\n): { patchIndex?: number; op?: string; path?: string; from?: string; reason?: string } {\n const context: { patchIndex?: number; op?: string; path?: string; from?: string; reason?: string } = {};\n if (error instanceof Error && error.message.trim().length > 0) {\n context.reason = error.message.trim();\n }\n if (typeof error !== \"object\" || error === null) {\n return context;\n }\n const candidate = error as {\n index?: unknown;\n operation?: unknown;\n };\n /* c8 ignore start -- parser-generated patch errors may omit index metadata in current fixtures. */\n if (typeof candidate.index === \"number\" && Number.isInteger(candidate.index) && candidate.index >= 0) {\n context.patchIndex = candidate.index;\n }\n /* c8 ignore stop */\n /* c8 ignore start -- operation payload metadata is optional in upstream json-patch failures. */\n const operationRecord =\n typeof candidate.operation === \"object\" && candidate.operation !== null\n ? (candidate.operation as { op?: unknown; path?: unknown; from?: unknown })\n : null;\n /* c8 ignore stop */\n if (operationRecord && typeof operationRecord.op === \"string\") {\n context.op = operationRecord.op;\n }\n if (operationRecord && typeof operationRecord.path === \"string\") {\n context.path = operationRecord.path;\n }\n if (operationRecord && typeof operationRecord.from === \"string\") {\n context.from = operationRecord.from;\n }\n if ((context.op === undefined || context.path === undefined) && context.patchIndex !== undefined) {\n const fallback = patch[context.patchIndex];\n /* c8 ignore start -- fallback enrichment paths are only exercised by malformed patch telemetry payloads. */\n if (fallback) {\n context.op = context.op ?? fallback.op;\n context.path = context.path ?? fallback.path;\n context.from = context.from ?? fallback.from;\n }\n /* c8 ignore stop */\n }\n return context;\n}\n\nfunction applyHistoryPatch(\n current: CanonicalReplayDocument,\n patch: HistoryPatchOp[],\n entryNumber: number,\n entryOp: string,\n): CanonicalReplayDocument {\n try {\n const normalizedPatch = normalizeReplayPatchOps(patch);\n const applied = jsonPatch.applyPatch(\n structuredClone(current),\n normalizedPatch as jsonPatch.Operation[],\n true,\n false,\n ).newDocument as unknown;\n if (\n typeof applied !== \"object\" ||\n applied === null ||\n !(\"metadata\" in applied) ||\n !(\"body\" in applied) ||\n typeof (applied as { body: unknown }).body !== \"string\" ||\n typeof (applied as { metadata: unknown }).metadata !== \"object\" ||\n (applied as { metadata: unknown }).metadata === null\n ) {\n throw new PmCliError(\n `History replay produced an invalid document shape at entry ${entryNumber}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n const replay = applied as { metadata: Record<string, unknown>; body: string };\n return {\n metadata: replay.metadata,\n body: replay.body,\n };\n } catch (error: unknown) {\n if (error instanceof PmCliError) {\n throw error;\n }\n const failureContext = extractPatchFailureContext(patch, error);\n const contextTokens = [\n `history_op=${entryOp}`,\n /* c8 ignore next -- contextual fields are best-effort and may be absent depending on patch failure shape. */\n failureContext.patchIndex !== undefined ? `patch_index=${failureContext.patchIndex}` : null,\n /* c8 ignore next -- contextual fields are best-effort and may be absent depending on patch failure shape. */\n failureContext.op ? `op=${failureContext.op}` : null,\n /* c8 ignore next -- contextual fields are best-effort and may be absent depending on patch failure shape. */\n failureContext.path ? `path=${failureContext.path}` : null,\n /* c8 ignore next -- contextual fields are best-effort and may be absent depending on patch failure shape. */\n failureContext.from ? `from=${failureContext.from}` : null,\n ].filter((token): token is string => token !== null);\n /* c8 ignore start -- jsonPatch/structuredClone/normalizeReplayPatchOps always throw Error instances with non-empty messages here, so extractPatchFailureContext always sets reason; the empty-suffix fallback is unreachable through applyHistoryPatch. */\n const reasonSuffix = failureContext.reason ? ` ${failureContext.reason}` : \"\";\n /* c8 ignore stop */\n throw new PmCliError(\n `Failed to apply history patch at entry ${entryNumber} (${contextTokens.join(\", \")}).${reasonSuffix}`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n}\n\nfunction replayToTarget(history: HistoryEntry[], targetIndex: number): CanonicalReplayDocument {\n let document: CanonicalReplayDocument = structuredClone(EMPTY_REPLAY_DOCUMENT);\n\n for (let i = 0; i <= targetIndex; i += 1) {\n const entry = history[i];\n const beforeHash = replayHash(document);\n if (beforeHash !== entry.before_hash) {\n throw new PmCliError(\n `History hash mismatch before replay at entry ${i + 1}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n\n document = applyHistoryPatch(document, entry.patch, i + 1, entry.op);\n\n const afterHash = replayHash(document);\n if (afterHash !== entry.after_hash) {\n throw new PmCliError(\n `History hash mismatch after replay at entry ${i + 1}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n }\n\n return document;\n}\n\nfunction ensureMaterializedRestoreTarget(\n replayDocument: CanonicalReplayDocument,\n target: ResolvedRestoreTarget,\n): CanonicalReplayDocument {\n if (Object.keys(replayDocument.metadata).length > 0) {\n return replayDocument;\n }\n throw new PmCliError(\n `Restore target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction replayCurrentDocument(history: HistoryEntry[]): ItemDocument {\n const currentReplay = replayToTarget(history, history.length - 1);\n if (Object.keys(currentReplay.metadata).length === 0) {\n return {\n metadata: {} as ItemMetadata,\n body: currentReplay.body,\n };\n }\n return canonicalDocument(replayToItemDocument(currentReplay));\n}\n\nasync function resolveRestoreSubject(\n pmRoot: string,\n id: string,\n settings: Awaited<ReturnType<typeof readSettings>>,\n typeToFolder: Record<string, string>,\n): Promise<ResolvedRestoreSubject> {\n const located = await locateItem(pmRoot, id, settings.id_prefix, settings.item_format, typeToFolder);\n if (located) {\n const historyPath = getHistoryPath(pmRoot, located.id);\n const historyPolicy = await enforceHistoryStreamPolicyForItem({\n pmRoot,\n settings,\n itemId: located.id,\n commandLabel: \"restore\",\n });\n return {\n id: located.id,\n historyPath,\n located,\n historyPolicyWarnings: historyPolicy.warnings,\n };\n }\n\n const normalizedId = normalizeItemId(id, settings.id_prefix);\n const rawNormalizedId = normalizeRawItemId(id);\n /* c8 ignore start -- raw-id fallback is covered by normalize-item-id utility tests. */\n const candidateIds = normalizedId === rawNormalizedId ? [normalizedId] : [normalizedId, rawNormalizedId];\n /* c8 ignore stop */\n for (const candidateId of candidateIds) {\n const historyPath = getHistoryPath(pmRoot, candidateId);\n if (await pathExists(historyPath)) {\n return {\n id: candidateId,\n historyPath,\n located: null,\n historyPolicyWarnings: [],\n };\n }\n }\n\n throw new PmCliError(`Item ${id} not found`, EXIT_CODE.NOT_FOUND);\n}\n\nfunction changedFields(beforeDocument: ItemDocument, afterDocument: ItemDocument): string[] {\n const beforeReplay = toReplayDocument(beforeDocument);\n const afterReplay = toReplayDocument(afterDocument);\n const patch = jsonPatch.compare(beforeReplay, afterReplay) as HistoryPatchOp[];\n const fields = new Set<string>();\n\n for (const op of patch) {\n if (op.path === \"/body\" || op.path.startsWith(\"/body/\")) {\n fields.add(\"body\");\n continue;\n }\n const segment = op.path.replace(/^\\/(?:metadata|front_matter)\\/?/, \"\").split(\"/\")[0];\n fields.add(segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n }\n\n return Array.from(fields).sort((a, b) => a.localeCompare(b));\n}\n\n/**\n * Implements run restore for the public runtime surface of this module.\n */\nexport async function runRestore(\n id: string,\n target: string,\n options: RestoreCommandOptions,\n global: GlobalOptions,\n): Promise<RestoreResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const subject = await resolveRestoreSubject(pmRoot, id, settings, typeRegistry.type_to_folder);\n const resolvedId = subject.id;\n const historyRawBeforeLock = await readFileIfExists(subject.historyPath);\n const history = await readHistoryEntries(subject.historyPath, resolvedId);\n if (history.length === 0) {\n throw new PmCliError(`No history exists for ${resolvedId}; restore is unavailable.`, EXIT_CODE.NOT_FOUND);\n }\n\n const resolvedTarget = ensureReplayTarget(target, history);\n const replayDocument = ensureMaterializedRestoreTarget(replayToTarget(history, resolvedTarget.historyIndex), resolvedTarget);\n const restoredDocument = replayToCanonicalItemDocument(replayDocument, { schema: settings.schema });\n\n if (restoredDocument.metadata.id !== resolvedId) {\n throw new PmCliError(\n `Restore target resolved to item ${restoredDocument.metadata.id}, expected ${resolvedId}.`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n const loadedItemBeforeLock = subject.located ? await readLocatedItem(subject.located, { schema: settings.schema }) : null;\n const currentItemRawBeforeLock = loadedItemBeforeLock?.raw ?? null;\n\n const author = resolveAuthor(options.author, settings.author_default);\n const releaseLock = await acquireLock(\n pmRoot,\n resolvedId,\n settings.locks.ttl_seconds,\n author,\n Boolean(options.force),\n settings.governance.force_required_for_stale_lock,\n );\n\n try {\n const historyRawUnderLock = await readFileIfExists(subject.historyPath);\n if (historyRawUnderLock !== historyRawBeforeLock) {\n throw new PmCliError(\n `History for ${resolvedId} changed while waiting for lock; retry restore.`,\n EXIT_CODE.CONFLICT,\n );\n }\n const locatedUnderLock = await locateItem(\n pmRoot,\n resolvedId,\n settings.id_prefix,\n settings.item_format,\n typeRegistry.type_to_folder,\n );\n const loadedItemUnderLock = locatedUnderLock ? await readLocatedItem(locatedUnderLock, { schema: settings.schema }) : null;\n if ((loadedItemUnderLock?.raw ?? null) !== currentItemRawBeforeLock) {\n throw new PmCliError(`Item ${resolvedId} changed while waiting for lock; retry restore.`, EXIT_CODE.CONFLICT);\n }\n\n const existingItemPath = locatedUnderLock?.itemPath ?? null;\n const itemFormat = \"toon\";\n let resolvedCurrentDocument: ItemDocument;\n let resolvedOriginalRaw: string | null = null;\n if (loadedItemUnderLock) {\n resolvedCurrentDocument = loadedItemUnderLock.document;\n resolvedOriginalRaw = loadedItemUnderLock.raw;\n } else {\n resolvedCurrentDocument = replayCurrentDocument(history);\n }\n const assigned = resolvedCurrentDocument.metadata.assignee?.trim();\n const ownershipWarnings: string[] = [];\n const hasOwnershipConflict = assigned && assigned !== author && !options.force;\n if (hasOwnershipConflict) {\n if (settings.governance.ownership_enforcement === \"strict\") {\n throw new PmCliError(\n `Item ${resolvedId} is assigned to ${assigned}. Use --force to override.`,\n EXIT_CODE.CONFLICT,\n );\n }\n if (settings.governance.ownership_enforcement === \"warn\") {\n ownershipWarnings.push(`ownership_warning:assignee_conflict:${resolvedId}:${assigned}`);\n }\n }\n\n const serializedRestore = serializeItemDocument(restoredDocument, { format: itemFormat, schema: settings.schema });\n /* c8 ignore next -- restored item path typing is exercised in restore integration workflows. */\n const restoredItemPath = getItemPath(\n pmRoot,\n restoredDocument.metadata.type,\n resolvedId,\n itemFormat,\n typeRegistry.type_to_folder,\n );\n await writeFileAtomic(restoredItemPath, serializedRestore);\n if (existingItemPath && restoredItemPath !== existingItemPath) {\n await fs.rm(existingItemPath);\n }\n\n const historyEntry = createHistoryEntry({\n nowIso: nowIso(),\n author,\n op: \"restore\",\n before: resolvedCurrentDocument,\n after: restoredDocument,\n message: options.message,\n });\n\n try {\n await appendHistoryEntry(subject.historyPath, historyEntry);\n } catch (error: unknown) {\n if (existingItemPath && resolvedOriginalRaw !== null && restoredItemPath !== existingItemPath) {\n await writeFileAtomic(existingItemPath, resolvedOriginalRaw);\n await fs.rm(restoredItemPath, { force: true });\n } else if (existingItemPath && resolvedOriginalRaw !== null) {\n await writeFileAtomic(existingItemPath, resolvedOriginalRaw);\n } else {\n await fs.rm(restoredItemPath, { force: true });\n }\n throw error;\n }\n const restoreChangedFields = changedFields(resolvedCurrentDocument, restoredDocument);\n const hookWarnings = [\n ...(await runActiveOnWriteHooks({\n path: restoredItemPath,\n scope: \"project\",\n op: \"restore\",\n item_id: restoredDocument.metadata.id,\n item_type: restoredDocument.metadata.type,\n before: resolvedCurrentDocument,\n after: restoredDocument,\n changed_fields: [\"restored\"],\n })),\n ...(await runActiveOnWriteHooks({\n path: subject.historyPath,\n scope: \"project\",\n op: \"restore:history\",\n item_id: restoredDocument.metadata.id,\n item_type: restoredDocument.metadata.type,\n before: resolvedCurrentDocument,\n after: restoredDocument,\n changed_fields: [\"restored\"],\n })),\n ];\n recordAfterCommandAffectedItem({\n id: restoredDocument.metadata.id,\n op: \"restore\",\n item_type: restoredDocument.metadata.type,\n previous_status: resolvedCurrentDocument.metadata.status,\n status: restoredDocument.metadata.status,\n previous: projectAfterCommandItemSnapshot(resolvedCurrentDocument.metadata, restoreChangedFields),\n current: projectAfterCommandItemSnapshot(restoredDocument.metadata, restoreChangedFields),\n changed_fields: restoreChangedFields,\n });\n\n const targetEntry = history[resolvedTarget.historyIndex];\n return {\n item: restoredDocument.metadata,\n restored_from: {\n kind: resolvedTarget.kind,\n target: resolvedTarget.raw,\n history_index: resolvedTarget.historyIndex + 1,\n entry_ts: targetEntry.ts,\n entry_op: targetEntry.op,\n },\n changed_fields: restoreChangedFields,\n warnings: [...subject.historyPolicyWarnings, ...ownershipWarnings, ...hookWarnings],\n };\n } finally {\n await releaseLock();\n }\n}\n\nexport const _testOnlyRestoreCommand = {\n applyHistoryPatch,\n changedFields,\n ensureMaterializedRestoreTarget,\n ensureReplayTarget,\n extractPatchFailureContext,\n replayCurrentDocument,\n replayToTarget,\n resolveRestoreSubject,\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,eAAe;AACtB,OAAO,QAAQ;;;;;;;;AAwEf,SAAS,mBAAmB,QAAgB,SAAuB;AACjE,QAAM,UAAU,OAAO,KAAI;AAC3B,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,WAAW,8DAA8D,UAAU,KAAK;EACpG;AAEA,MAAI,QAAQ,KAAK,OAAO,GAAG;AACzB,UAAM,UAAU,OAAO,OAAO;AAC9B,QAAI,CAAC,OAAO,cAAc,OAAO,KAAK,UAAU,KAAK,UAAU,QAAQ,QAAQ;AAC7E,YAAM,IAAI,WACR,yCAAyC,QAAQ,MAAM,mBACvD,UAAU,KAAK;IAEnB;AACA,WAAO;MACL,MAAM;MACN,KAAK;MACL,cAAc,UAAU;;EAE5B;AAEA,QAAM,eAAe,KAAK,MAAM,OAAO;AACvC,MAAI,CAAC,OAAO,SAAS,YAAY,GAAG;AAClC,UAAM,IAAI,WACR,2BAA2B,MAAM,sDACjC,UAAU,KAAK;EAEnB;AAEA,MAAI,QAAQ;AACZ,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,GAAG;AAC1C,UAAM,iBAAiB,KAAK,MAAM,QAAQ,CAAC,EAAE,EAAE;AAC/C,QAAI,CAAC,OAAO,SAAS,cAAc,GAAG;AACpC,YAAM,IAAI,WACR,6DAA6D,IAAI,CAAC,KAClE,UAAU,eAAe;IAE7B;AACA,QAAI,kBAAkB,cAAc;AAClC,cAAQ;IACV;EACF;AAEA,MAAI,QAAQ,GAAG;AACb,UAAM,IAAI,WAAW,mDAAmD,OAAO,KAAK,UAAU,KAAK;EACrG;AAEA,SAAO;IACL,MAAM;IACN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B,SAAS;QACrC,QAAQ;QACR,OAAO;QACP,gBAAgB,CAAC,UAAU;OAC5B;;AAEH,mCAA+B;MAC7B,IAAI,iBAAiB,SAAS;MAC9B,IAAI;MACJ,WAAW,iBAAiB,SAAS;MACrC,iBAAiB,wBAAwB,SAAS;MAClD,QAAQ,iBAAiB,SAAS;MAClC,UAAU,gCAAgC,wBAAwB,UAAU,oBAAoB;MAChG,SAAS,gCAAgC,iBAAiB,UAAU,oBAAoB;MACxF,gBAAgB;KACjB;AAED,UAAM,cAAc,QAAQ,eAAe,YAAY;AACvD,WAAO;MACL,MAAM,iBAAiB;MACvB,eAAe;QACb,MAAM,eAAe;QACrB,QAAQ,eAAe;QACvB,eAAe,eAAe,eAAe;QAC7C,UAAU,YAAY;QACtB,UAAU,YAAY;;MAExB,gBAAgB;MAChB,UAAU,CAAC,GAAG,QAAQ,uBAAuB,GAAG,mBAAmB,GAAG,YAAY;;EAEtF;AACE,UAAM,YAAW;EACnB;AACF;AAEO,IAAM,0BAA0B;EACrC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;",
6
- "names": ["global"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../../../../../cli/commands/history-redact.ts", "../../../../../../../../core/history/history-rewrite.ts"],
4
- "sourcesContent": ["/**\n * @module cli/commands/history-redact\n *\n * Implements the pm history redact command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport { pathExists, readFileIfExists, writeFileAtomic } from \"../../core/fs/fs-utils.js\";\nimport { createHistoryEntry } from \"../../core/history/history.js\";\nimport { executeHistoryRewrite } from \"../../core/history/history-rewrite.js\";\nimport {\n EMPTY_REPLAY_DOCUMENT,\n historyEntriesToRaw,\n replayHash,\n replayToItemDocument,\n tryApplyReplayPatch,\n verifyHistoryChain,\n type ReplayDocument,\n} from \"../../core/history/replay.js\";\nimport { normalizeItemId, normalizeRawItemId } from \"../../core/item/id.js\";\nimport { canonicalDocument, serializeItemDocument } from \"../../core/item/item-format.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.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 { getActiveExtensionRegistrations, runActiveOnWriteHooks } from \"../../core/extensions/index.js\";\nimport { locateItem, readLocatedItem } from \"../../core/store/item-store.js\";\nimport { getHistoryPath, getItemPath, getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { resolveAuthor } from \"../../core/shared/author.js\";\nimport type { HistoryEntry, HistoryPatchOp, ItemDocument } from \"../../types/index.js\";\nimport { readHistoryEntries } from \"./history.js\";\n\n/**\n * Documents the history redact command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryRedactCommandOptions {\n literal?: string[] | string;\n regex?: string[] | string;\n replacement?: string;\n dryRun?: boolean;\n author?: string;\n message?: string;\n force?: boolean;\n}\n\ninterface RegexRule {\n kind: \"regex\";\n source: string;\n flags: string;\n label: string;\n}\n\ninterface LiteralRule {\n kind: \"literal\";\n value: string;\n label: string;\n}\n\ntype RedactionRule = RegexRule | LiteralRule;\n\ninterface RedactionRewriteResult {\n entries: HistoryEntry[];\n finalDocument: ReplayDocument;\n entriesChanged: number;\n replacements: number;\n}\n\ninterface HistoryIntegritySnapshot {\n hashMismatchesBefore: number;\n hashMismatchesAfter: number;\n finalDocument: ReplayDocument;\n}\n\n/**\n * Documents the history subject payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistorySubject {\n id: string;\n historyPath: string;\n located: Awaited<ReturnType<typeof locateItem>>;\n}\n\n/**\n * Documents the history redact result payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryRedactResult {\n id: string;\n dry_run: boolean;\n changed: boolean;\n patterns: {\n literals: string[];\n regex: string[];\n replacement: string;\n };\n history: {\n path: string;\n entries_scanned: number;\n entries_changed: number;\n replacements: number;\n hash_mismatches_before: number;\n hash_mismatches_after: number;\n preexisting_hash_mismatches: number;\n audit_entry_added: boolean;\n verify_ok: boolean;\n verify_errors: string[];\n };\n item: {\n existed_before: boolean;\n exists_after: boolean;\n path_before: string | null;\n path_after: string | null;\n changed: boolean;\n };\n warnings: string[];\n generated_at: string;\n}\n\nfunction normalizeStringArrayInput(value: string[] | string | undefined): string[] {\n if (Array.isArray(value)) {\n return value;\n }\n if (typeof value === \"string\") {\n return [value];\n }\n return [];\n}\n\nfunction normalizeRegexFlags(flags: string): string {\n const unique: string[] = [];\n for (const token of flags) {\n if (!unique.includes(token)) {\n unique.push(token);\n }\n }\n if (!unique.includes(\"g\")) {\n unique.push(\"g\");\n }\n return unique.join(\"\");\n}\n\nfunction parseRegexRule(spec: string): RegexRule {\n const trimmed = spec.trim();\n if (trimmed.length === 0) {\n throw new PmCliError(\"history-redact --regex requires a non-empty pattern.\", EXIT_CODE.USAGE);\n }\n\n let source = trimmed;\n let flags = \"g\";\n if (trimmed.startsWith(\"/\") && trimmed.length > 1) {\n /* c8 ignore start -- bare-slash regex literals are rejected earlier in argument validation. */\n const slashIndex = trimmed.lastIndexOf(\"/\");\n if (slashIndex > 0) {\n source = trimmed.slice(1, slashIndex);\n flags = normalizeRegexFlags(trimmed.slice(slashIndex + 1));\n }\n /* c8 ignore stop */\n }\n if (source.length === 0) {\n throw new PmCliError(\"history-redact --regex cannot use an empty pattern.\", EXIT_CODE.USAGE);\n }\n try {\n new RegExp(source, flags);\n } catch (error) {\n /* c8 ignore start -- RegExp constructor failures are normalized in higher-level parser tests. */\n throw new PmCliError(\n `Invalid --regex value \"${spec}\": ${error instanceof Error ? error.message : String(error)}`,\n EXIT_CODE.USAGE,\n );\n /* c8 ignore stop */\n }\n\n return {\n kind: \"regex\",\n source,\n flags,\n label: `/${source}/${flags}`,\n };\n}\n\nfunction buildRedactionRules(\n literalInput: string[] | string | undefined,\n regexInput: string[] | string | undefined,\n): RedactionRule[] {\n const literalRules = [...new Set(normalizeStringArrayInput(literalInput).map((entry) => entry.trim()))]\n .filter((entry) => entry.length > 0)\n .map<LiteralRule>((entry) => ({\n kind: \"literal\",\n value: entry,\n label: entry,\n }));\n const regexRules = [...new Set(normalizeStringArrayInput(regexInput).map((entry) => entry.trim()))]\n .filter((entry) => entry.length > 0)\n .map(parseRegexRule);\n\n const rules = [...literalRules, ...regexRules];\n if (rules.length === 0) {\n throw new PmCliError(\n \"history-redact requires at least one matcher via --literal or --regex.\",\n EXIT_CODE.USAGE,\n {\n code: \"missing_required_argument\",\n required: \"Provide --literal <value> and/or --regex <pattern>.\",\n examples: [\n 'pm history-redact pm-a1b2 --literal \"[redacted_path_prefix]/private\"',\n 'pm history-redact pm-a1b2 --regex \"/192\\\\\\\\.168\\\\\\\\.[0-9.]+/g\" --replacement \"[scrubbed_ip]\"',\n ],\n },\n );\n }\n return rules;\n}\n\nfunction applyLiteralRule(value: string, literal: string, replacement: string): { value: string; replacements: number } {\n if (literal.length === 0) {\n return { value, replacements: 0 };\n }\n let cursor = 0;\n let replacements = 0;\n while (cursor <= value.length) {\n const index = value.indexOf(literal, cursor);\n if (index === -1) {\n break;\n }\n replacements += 1;\n cursor = index + Math.max(1, literal.length);\n }\n if (replacements === 0) {\n return { value, replacements: 0 };\n }\n return {\n value: value.split(literal).join(replacement),\n replacements,\n };\n}\n\nfunction applyRegexRule(value: string, rule: RegexRule, replacement: string): { value: string; replacements: number } {\n const regex = new RegExp(rule.source, rule.flags);\n const matches = [...value.matchAll(regex)];\n if (matches.length === 0) {\n return { value, replacements: 0 };\n }\n return {\n value: value.replace(regex, replacement),\n replacements: matches.length,\n };\n}\n\nfunction redactStringValue(value: string, rules: RedactionRule[], replacement: string): { value: string; replacements: number } {\n let next = value;\n let replacements = 0;\n for (const rule of rules) {\n const result =\n rule.kind === \"literal\"\n ? applyLiteralRule(next, rule.value, replacement)\n : applyRegexRule(next, rule, replacement);\n next = result.value;\n replacements += result.replacements;\n }\n return {\n value: next,\n replacements,\n };\n}\n\nfunction redactUnknownValue(value: unknown, rules: RedactionRule[], replacement: string): { value: unknown; replacements: number } {\n if (typeof value === \"string\") {\n return redactStringValue(value, rules, replacement);\n }\n if (Array.isArray(value)) {\n let replacements = 0;\n const nextValues = value.map((entry) => {\n const redacted = redactUnknownValue(entry, rules, replacement);\n replacements += redacted.replacements;\n return redacted.value;\n });\n return {\n value: nextValues,\n replacements,\n };\n }\n if (typeof value === \"object\" && value !== null) {\n let replacements = 0;\n const nextRecord: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const redacted = redactUnknownValue(entry, rules, replacement);\n replacements += redacted.replacements;\n nextRecord[key] = redacted.value;\n }\n return {\n value: nextRecord,\n replacements,\n };\n }\n return {\n value,\n replacements: 0,\n };\n}\n\nfunction applyHistoryPatch(current: ReplayDocument, patch: HistoryPatchOp[], entryNumber: number, op: string): ReplayDocument {\n const result = tryApplyReplayPatch(current, patch);\n /* c8 ignore start -- invalid patch replay paths are covered by replay helper tests. */\n if (!result.ok) {\n throw new PmCliError(\n `history-redact failed to apply patch at entry ${entryNumber} (op=${op}): ${\n result.error instanceof Error ? result.error.message : String(result.error)\n }`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n /* c8 ignore stop */\n return result.document;\n}\n\nfunction inspectHistoryIntegrity(entries: HistoryEntry[]): HistoryIntegritySnapshot {\n let replay = structuredClone(EMPTY_REPLAY_DOCUMENT);\n let hashMismatchesBefore = 0;\n let hashMismatchesAfter = 0;\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (replayHash(replay) !== entry.before_hash) {\n hashMismatchesBefore += 1;\n }\n replay = applyHistoryPatch(replay, entry.patch, index + 1, entry.op);\n /* c8 ignore start -- after-hash mismatch branch is exercised in dedicated history integrity tests. */\n if (replayHash(replay) !== entry.after_hash) {\n hashMismatchesAfter += 1;\n }\n /* c8 ignore stop */\n }\n return {\n hashMismatchesBefore,\n hashMismatchesAfter,\n finalDocument: replay,\n };\n}\n\nfunction redactHistoryEntry(entry: HistoryEntry, rules: RedactionRule[], replacement: string): {\n entry: HistoryEntry;\n replacements: number;\n changed: boolean;\n} {\n let replacements = 0;\n let changed = false;\n let nextMessage = entry.message;\n\n if (typeof entry.message === \"string\") {\n const redactedMessage = redactStringValue(entry.message, rules, replacement);\n nextMessage = redactedMessage.value;\n replacements += redactedMessage.replacements;\n if (redactedMessage.replacements > 0) {\n changed = true;\n }\n }\n\n const nextPatch = entry.patch.map((operation) => {\n /* c8 ignore start -- patch operations without `value` are covered in lower-level patch adapters. */\n if (!Object.prototype.hasOwnProperty.call(operation, \"value\")) {\n return operation;\n }\n /* c8 ignore stop */\n const redactedValue = redactUnknownValue(operation.value, rules, replacement);\n replacements += redactedValue.replacements;\n if (redactedValue.replacements > 0) {\n changed = true;\n return {\n ...operation,\n value: redactedValue.value,\n };\n }\n return operation;\n });\n\n return {\n entry: {\n ...entry,\n message: nextMessage,\n patch: nextPatch,\n },\n replacements,\n changed,\n };\n}\n\nfunction rewriteHistoryEntries(entries: HistoryEntry[], rules: RedactionRule[], replacement: string): RedactionRewriteResult {\n let replay = structuredClone(EMPTY_REPLAY_DOCUMENT);\n let entriesChanged = 0;\n let replacements = 0;\n const rewrittenEntries: HistoryEntry[] = [];\n\n for (let index = 0; index < entries.length; index += 1) {\n const redacted = redactHistoryEntry(entries[index], rules, replacement);\n replacements += redacted.replacements;\n if (redacted.changed) {\n entriesChanged += 1;\n }\n const beforeHash = replayHash(replay);\n replay = applyHistoryPatch(replay, redacted.entry.patch, index + 1, redacted.entry.op);\n const afterHash = replayHash(replay);\n rewrittenEntries.push({\n ...redacted.entry,\n before_hash: beforeHash,\n after_hash: afterHash,\n });\n }\n\n return {\n entries: rewrittenEntries,\n finalDocument: replay,\n entriesChanged,\n replacements,\n };\n}\n\nfunction hasItemMetadata(replay: ReplayDocument): boolean {\n return Object.keys(replay.metadata).length > 0;\n}\n\n/**\n * Implements resolve history subject for the public runtime surface of this module.\n */\nexport async function resolveHistorySubject(\n pmRoot: string,\n id: string,\n settings: Awaited<ReturnType<typeof readSettings>>,\n typeToFolder: Record<string, string>,\n): Promise<HistorySubject> {\n const located = await locateItem(pmRoot, id, settings.id_prefix, settings.item_format, typeToFolder);\n if (located) {\n return {\n id: located.id,\n historyPath: getHistoryPath(pmRoot, located.id),\n located,\n };\n }\n\n const normalizedId = normalizeItemId(id, settings.id_prefix);\n const rawNormalizedId = normalizeRawItemId(id);\n const candidateIds = normalizedId === rawNormalizedId ? [normalizedId] : [normalizedId, rawNormalizedId];\n for (const candidateId of candidateIds) {\n const historyPath = getHistoryPath(pmRoot, candidateId);\n if (await pathExists(historyPath)) {\n return {\n id: candidateId,\n historyPath,\n located: null,\n };\n }\n }\n throw new PmCliError(`Item ${id} not found`, EXIT_CODE.NOT_FOUND);\n}\n\n/**\n * Implements run history redact for the public runtime surface of this module.\n */\nexport async function runHistoryRedact(\n id: string,\n options: HistoryRedactCommandOptions,\n global: GlobalOptions,\n): Promise<HistoryRedactResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const replacement = typeof options.replacement === \"string\" && options.replacement.length > 0 ? options.replacement : \"[redacted]\";\n const rules = buildRedactionRules(options.literal, options.regex);\n const subject = await resolveHistorySubject(pmRoot, id, settings, typeRegistry.type_to_folder);\n\n if (!(await pathExists(subject.historyPath))) {\n throw new PmCliError(`No history stream exists for ${subject.id}.`, EXIT_CODE.NOT_FOUND);\n }\n const historyRawBeforeLock = await readFileIfExists(subject.historyPath);\n const historyEntries = await readHistoryEntries(subject.historyPath, subject.id);\n if (historyEntries.length === 0) {\n throw new PmCliError(`No history entries exist for ${subject.id}; nothing to redact.`, EXIT_CODE.USAGE);\n }\n\n const integritySnapshot = inspectHistoryIntegrity(historyEntries);\n const rewritten = rewriteHistoryEntries(historyEntries, rules, replacement);\n const preexistingHashMismatches = integritySnapshot.hashMismatchesBefore + integritySnapshot.hashMismatchesAfter;\n const dryRun = Boolean(options.dryRun);\n const changed = rewritten.replacements > 0;\n const warnings: string[] = [];\n if (preexistingHashMismatches > 0) {\n warnings.push(`history_redact_preexisting_hash_mismatches:${preexistingHashMismatches}`);\n }\n if (!changed) {\n warnings.push(\"history_redact_no_matches\");\n }\n\n let currentItemRaw: string | null = null;\n /* c8 ignore next -- located subject null-path branch is covered in restore/history-repair integration suites. */\n let currentItemPath: string | null = subject.located?.itemPath ?? null;\n let currentItemDocument: ItemDocument | null = null;\n if (subject.located) {\n const loaded = await readLocatedItem(subject.located, { schema: settings.schema });\n currentItemRaw = loaded.raw;\n currentItemDocument = loaded.document;\n }\n\n let nextItemPath: string | null = null;\n let nextItemRaw: string | null = null;\n let nextItemDocument: ItemDocument | null = null;\n /* c8 ignore next -- delete-state replay branches are covered by history rewrite integration tests. */\n if (hasItemMetadata(rewritten.finalDocument)) {\n const canonical = canonicalDocument(replayToItemDocument(rewritten.finalDocument), { schema: settings.schema });\n if (canonical.metadata.id !== subject.id) {\n throw new PmCliError(\n `history-redact would change item id from ${subject.id} to ${canonical.metadata.id}; narrow your patterns.`,\n EXIT_CODE.USAGE,\n );\n }\n nextItemDocument = canonical;\n nextItemPath = getItemPath(pmRoot, canonical.metadata.type, subject.id, \"toon\", typeRegistry.type_to_folder);\n nextItemRaw = serializeItemDocument(canonical, {\n format: \"toon\",\n schema: settings.schema,\n });\n }\n\n const itemChanged =\n /* c8 ignore next -- null-coalescing item-path comparison branch is exercised in broader command integration coverage. */\n (currentItemPath ?? null) !== (nextItemPath ?? null) ||\n /* c8 ignore next -- null-coalescing item-content comparison branch is exercised in broader command integration coverage. */\n (currentItemRaw ?? null) !== (nextItemRaw ?? null);\n\n const author = resolveAuthor(options.author, settings.author_default);\n const redactionMessage =\n /* c8 ignore next -- custom-message branch is validated by command wrapper tests. */\n typeof options.message === \"string\" && options.message.trim().length > 0\n ? options.message\n : `history-redact replaced ${rewritten.replacements} match(es) across ${rewritten.entriesChanged} entr${\n rewritten.entriesChanged === 1 ? \"y\" : \"ies\"\n }.`;\n\n const rewrittenEntries = [...rewritten.entries];\n let auditEntryAdded = false;\n if (!dryRun && changed) {\n /* c8 ignore next -- fallback replay-to-item conversion runs only when rewritten final metadata is absent. */\n const finalDocument = nextItemDocument ?? replayToItemDocument(rewritten.finalDocument);\n rewrittenEntries.push(\n createHistoryEntry({\n nowIso: nowIso(),\n author,\n op: \"history_redact\",\n before: finalDocument,\n after: finalDocument,\n message: redactionMessage,\n }),\n );\n auditEntryAdded = true;\n }\n const historyVerify = verifyHistoryChain(rewrittenEntries);\n /* c8 ignore start -- invalid rewritten chains are covered by history verification unit tests. */\n if (!historyVerify.ok) {\n throw new PmCliError(\n `history-redact produced an invalid rewritten chain (${historyVerify.errors.join(\", \")}).`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n /* c8 ignore stop */\n\n if (!dryRun && changed) {\n warnings.push(\n ...(await executeHistoryRewrite({\n pmRoot,\n subject,\n settings,\n typeRegistry,\n historyRawBeforeLock,\n currentItemRawBeforeLock: currentItemRaw,\n operation: \"history-redact\",\n author,\n force: options.force,\n itemDocument: currentItemDocument,\n applyRewrite: async ({ historyRawUnderLock }) => {\n const affectedItemPaths = new Set<string>();\n if (currentItemPath) {\n affectedItemPaths.add(currentItemPath);\n }\n if (nextItemPath) {\n affectedItemPaths.add(nextItemPath);\n }\n const itemSnapshots = new Map<string, string>();\n if (currentItemPath && currentItemRaw !== null) {\n itemSnapshots.set(currentItemPath, currentItemRaw);\n }\n\n try {\n /* c8 ignore next -- item-write diff branch requires path and content divergence under lock races. */\n if (nextItemPath && nextItemRaw !== null && nextItemRaw !== currentItemRaw) {\n await writeFileAtomic(nextItemPath, nextItemRaw);\n }\n if (currentItemPath && (!nextItemPath || nextItemPath !== currentItemPath)) {\n await fs.rm(currentItemPath, { force: true });\n }\n await writeFileAtomic(subject.historyPath, historyEntriesToRaw(rewrittenEntries));\n } catch (error) {\n /* c8 ignore start -- no-history-under-lock rollback path is exercised in lock-race integration tests. */\n if (historyRawUnderLock === null) {\n await fs.rm(subject.historyPath, { force: true });\n } else {\n await writeFileAtomic(subject.historyPath, historyRawUnderLock);\n }\n /* c8 ignore stop */\n for (const itemPath of affectedItemPaths) {\n const snapshot = itemSnapshots.get(itemPath);\n /* c8 ignore start -- missing snapshot rollback occurs only for create/delete race permutations. */\n if (snapshot === undefined) {\n await fs.rm(itemPath, { force: true });\n } else {\n await writeFileAtomic(itemPath, snapshot);\n }\n /* c8 ignore stop */\n }\n throw error;\n }\n },\n applyPostRewrite: async () => {\n const hookWarnings: string[] = [];\n const itemHookPath = nextItemPath ?? currentItemPath;\n if (itemHookPath) {\n hookWarnings.push(\n ...(await runActiveOnWriteHooks({\n path: itemHookPath,\n scope: \"project\",\n op: \"history_redact\",\n })),\n );\n }\n hookWarnings.push(\n ...(await runActiveOnWriteHooks({\n path: subject.historyPath,\n scope: \"project\",\n op: \"history_redact:history\",\n })),\n );\n return hookWarnings;\n },\n })),\n );\n }\n\n return {\n id: subject.id,\n dry_run: dryRun,\n changed,\n patterns: {\n literals: rules.filter((rule): rule is LiteralRule => rule.kind === \"literal\").map((rule) => rule.value),\n regex: rules.filter((rule): rule is RegexRule => rule.kind === \"regex\").map((rule) => `/${rule.source}/${rule.flags}`),\n replacement,\n },\n history: {\n path: subject.historyPath,\n entries_scanned: historyEntries.length,\n entries_changed: rewritten.entriesChanged,\n replacements: rewritten.replacements,\n hash_mismatches_before: integritySnapshot.hashMismatchesBefore,\n hash_mismatches_after: integritySnapshot.hashMismatchesAfter,\n preexisting_hash_mismatches: preexistingHashMismatches,\n audit_entry_added: auditEntryAdded,\n verify_ok: historyVerify.ok,\n verify_errors: historyVerify.errors,\n },\n item: {\n existed_before: currentItemPath !== null,\n exists_after: nextItemPath !== null,\n path_before: currentItemPath,\n path_after: nextItemPath,\n changed: itemChanged,\n },\n /* c8 ignore next -- warning dedupe ordering is covered indirectly by command-level smoke tests. */\n warnings: [...new Set(warnings)].sort((left, right) => left.localeCompare(right)),\n generated_at: nowIso(),\n };\n}\n\nexport const _testOnly = {\n applyLiteralRule,\n applyRegexRule,\n buildRedactionRules,\n hasItemMetadata,\n normalizeRegexFlags,\n normalizeStringArrayInput,\n parseRegexRule,\n redactStringValue,\n redactUnknownValue,\n};\n", "/**\n * @module core/history/history-rewrite\n *\n * Implements append-only history and replay behavior for History Rewrite.\n */\nimport { readFileIfExists } from \"../fs/fs-utils.js\";\nimport type { ItemTypeRegistry } from \"../item/type-registry.js\";\nimport { acquireLock } from \"../lock/lock.js\";\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { locateItem, readLocatedItem } from \"../store/item-store.js\";\nimport { resolveGovernanceKnobs } from \"../store/settings.js\";\nimport type { ItemDocument, PmSettings } from \"../../types/index.js\";\n\ntype LoadedItem = Awaited<ReturnType<typeof readLocatedItem>>;\n\n/**\n * Documents the history rewrite subject payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryRewriteSubject {\n id: string;\n historyPath: string;\n}\n\n/**\n * Documents the history rewrite ownership params payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryRewriteOwnershipParams {\n itemDocument: ItemDocument | null;\n subjectId: string;\n author: string;\n force: boolean | undefined;\n settings: PmSettings;\n}\n\n/**\n * Apply ownership_enforcement governance to a history-rewriting operation.\n * Returns the warning(s) the caller should append (empty when no conflict or strict-throws).\n * Throws PmCliError(CONFLICT) in strict mode when the assignee conflicts and --force is not set.\n */\nexport function checkHistoryRewriteOwnership(params: HistoryRewriteOwnershipParams): string[] {\n if (!params.itemDocument) return [];\n const assigned = params.itemDocument.metadata?.assignee?.trim();\n if (!assigned || assigned === params.author || params.force) return [];\n\n const governance = resolveGovernanceKnobs(params.settings);\n if (governance.ownership_enforcement === \"strict\") {\n throw new PmCliError(\n `Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,\n EXIT_CODE.CONFLICT,\n );\n }\n if (governance.ownership_enforcement === \"warn\") {\n return [`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`];\n }\n return [];\n}\n\n/**\n * Documents the verify history rewrite drift params payload exchanged by command, SDK, and package integrations.\n */\nexport interface VerifyHistoryRewriteDriftParams {\n pmRoot: string;\n subject: HistoryRewriteSubject;\n settings: PmSettings;\n typeRegistry: ItemTypeRegistry;\n historyRawBeforeLock: string | null;\n currentItemRawBeforeLock: string | null;\n /** Short operation name used in the conflict message (e.g. \"history-redact\"). */\n operation: string;\n}\n\n/**\n * Documents the verified history rewrite state payload exchanged by command, SDK, and package integrations.\n */\nexport interface VerifiedHistoryRewriteState {\n historyRawUnderLock: string | null;\n locatedUnderLock: Awaited<ReturnType<typeof locateItem>>;\n loadedItemUnderLock: LoadedItem | null;\n}\n\n/**\n * Re-read the history stream and the located item document under the acquired lock and\n * compare both with the pre-lock raw snapshots. Throws PmCliError(CONFLICT) if either\n * diverged while waiting for the lock so the caller surfaces an actionable retry.\n */\nexport async function verifyHistoryRewriteNoDrift(\n params: VerifyHistoryRewriteDriftParams,\n): Promise<VerifiedHistoryRewriteState> {\n const historyRawUnderLock = await readFileIfExists(params.subject.historyPath);\n if (historyRawUnderLock !== params.historyRawBeforeLock) {\n throw new PmCliError(\n `History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,\n EXIT_CODE.CONFLICT,\n );\n }\n const locatedUnderLock = await locateItem(\n params.pmRoot,\n params.subject.id,\n params.settings.id_prefix,\n params.settings.item_format,\n params.typeRegistry.type_to_folder,\n );\n const loadedItemUnderLock = locatedUnderLock\n ? await readLocatedItem(locatedUnderLock, { schema: params.settings.schema })\n : null;\n if ((loadedItemUnderLock?.raw ?? null) !== (params.currentItemRawBeforeLock ?? null)) {\n throw new PmCliError(\n `Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,\n EXIT_CODE.CONFLICT,\n );\n }\n return { historyRawUnderLock, locatedUnderLock, loadedItemUnderLock };\n}\n\n/**\n * Documents the execute history rewrite params payload exchanged by command, SDK, and package integrations.\n */\nexport interface ExecuteHistoryRewriteParams {\n pmRoot: string;\n subject: HistoryRewriteSubject;\n settings: PmSettings;\n typeRegistry: ItemTypeRegistry;\n historyRawBeforeLock: string | null;\n currentItemRawBeforeLock: string | null;\n /** Short operation name used in conflict guidance (e.g. \"history-redact\"). */\n operation: string;\n author: string;\n force: boolean | undefined;\n itemDocument: ItemDocument | null;\n applyRewrite: (verified: VerifiedHistoryRewriteState) => Promise<void>;\n applyPostRewrite?: (verified: VerifiedHistoryRewriteState) => Promise<string[]>;\n}\n\n/**\n * Shared lock/verify/ownership orchestration for history-rewrite commands.\n * Callers provide the operation-specific write/rollback logic and optional\n * post-write hook execution while this helper enforces the common governance +\n * lock sequencing contract.\n */\nexport async function executeHistoryRewrite(params: ExecuteHistoryRewriteParams): Promise<string[]> {\n const warnings = [...checkHistoryRewriteOwnership({\n itemDocument: params.itemDocument,\n subjectId: params.subject.id,\n author: params.author,\n force: params.force,\n settings: params.settings,\n })];\n const releaseLock = await acquireLock(\n params.pmRoot,\n params.subject.id,\n params.settings.locks.ttl_seconds,\n params.author,\n Boolean(params.force),\n params.settings.governance.force_required_for_stale_lock,\n );\n try {\n const verified = await verifyHistoryRewriteNoDrift({\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: params.operation,\n });\n await params.applyRewrite(verified);\n if (params.applyPostRewrite) {\n warnings.push(...(await params.applyPostRewrite(verified)));\n }\n return warnings;\n } finally {\n await releaseLock();\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA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B,eAAe;MAChC,iBAAiB,UAAU;MAC3B,cAAc,UAAU;MACxB,wBAAwB,kBAAkB;MAC1C,uBAAuB,kBAAkB;MACzC,6BAA6B;MAC7B,mBAAmB;MACnB,WAAW,cAAc;MACzB,eAAe,cAAc;;IAE/B,MAAM;MACJ,gBAAgB,oBAAoB;MACpC,cAAc,iBAAiB;MAC/B,aAAa;MACb,YAAY;MACZ,SAAS;;;IAGX,UAAU,CAAC,GAAG,IAAI,IAAI,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,UAAU,KAAK,cAAc,KAAK,CAAC;IAChF,cAAc,OAAM;;AAExB;AAEO,IAAM,YAAY;EACvB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;",
6
- "names": ["global"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../../../../../cli/commands/activity.ts"],
4
- "sourcesContent": ["/**\n * @module cli/commands/activity\n *\n * Implements the pm activity command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getActiveExtensionRegistrations, runActiveOnReadHooks } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { enforceHistoryStreamPolicyForItems } from \"../../core/history/history-stream-policy.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.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 { compareTimestampStrings, nowIso, resolveIsoOrRelative } from \"../../core/shared/time.js\";\nimport { listAllFrontMatterLight } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { readHistoryEntries } from \"./history.js\";\nimport { parseLimit } from \"../shared-parsers.js\";\nimport type { HistoryEntry } from \"../../types/index.js\";\n\n/**\n * Documents the activity command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ActivityCommandOptions {\n id?: string;\n op?: string;\n author?: string;\n from?: string;\n to?: string;\n limit?: string;\n compact?: boolean;\n}\n\n/**\n * Documents the activity entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface ActivityEntry extends HistoryEntry {\n id: string;\n}\n\n/**\n * Documents the compact activity entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface CompactActivityEntry {\n id: string;\n op: string;\n ts: string;\n author: string;\n msg?: string;\n}\n\n/**\n * Documents the activity result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ActivityResult {\n activity: ActivityEntry[];\n compact_activity?: CompactActivityEntry[];\n compact: boolean;\n count: number;\n limit: number | null;\n}\n\nfunction parseNonEmptyFilter(raw: string | undefined, flagLabel: string): string | undefined {\n if (raw === undefined) return undefined;\n const normalized = raw.trim();\n if (normalized.length === 0) {\n throw new PmCliError(`${flagLabel} must not be empty`, EXIT_CODE.USAGE);\n }\n return normalized;\n}\n\nfunction parseRangeBound(raw: string | undefined, nowValue: string, fieldLabel: string): string | undefined {\n if (raw === undefined) return undefined;\n const normalized = raw.trim();\n if (normalized.length === 0) {\n throw new PmCliError(\"Activity time bounds must not be empty\", EXIT_CODE.USAGE);\n }\n return resolveIsoOrRelative(normalized, new Date(nowValue), fieldLabel);\n}\n\nfunction includeByTimeWindow(entry: ActivityEntry, from: string | undefined, to: string | undefined): boolean {\n if (entry.ts.length === 0 && (from || to)) {\n return false;\n }\n if (from && compareTimestampStrings(entry.ts, from) < 0) {\n return false;\n }\n if (to && compareTimestampStrings(entry.ts, to) >= 0) {\n return false;\n }\n return true;\n}\n\nfunction limitEntries<T>(values: T[], limit: number | undefined): T[] {\n if (limit === undefined) return values;\n return values.slice(0, limit);\n}\n\nfunction readActivityString(value: unknown, fallback = \"\"): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\nfunction normalizeActivityEntry(id: string, entry: HistoryEntry): ActivityEntry {\n return {\n ...entry,\n id,\n ts: readActivityString(entry.ts),\n author: readActivityString(entry.author, \"unknown\"),\n op: readActivityString(entry.op, \"unknown\"),\n patch: Array.isArray(entry.patch) ? entry.patch : [],\n before_hash: readActivityString(entry.before_hash),\n after_hash: readActivityString(entry.after_hash),\n };\n}\n\nfunction sortActivity(entries: ActivityEntry[]): ActivityEntry[] {\n return [...entries].sort((a, b) => {\n const byTimestamp = b.ts.localeCompare(a.ts);\n if (byTimestamp !== 0) return byTimestamp;\n const byId = a.id.localeCompare(b.id);\n if (byId !== 0) return byId;\n return a.op.localeCompare(b.op);\n });\n}\n\nasync function listHistoryFiles(historyDir: string): Promise<string[]> {\n try {\n return (await fs.readdir(historyDir))\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .sort((a, b) => a.localeCompare(b));\n } catch (error: unknown) {\n // Activity should degrade gracefully when optional history storage is absent.\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw error;\n }\n}\n\nexport const _testOnly = {\n parseNonEmptyFilter,\n parseRangeBound,\n includeByTimeWindow,\n limitEntries,\n readActivityString,\n normalizeActivityEntry,\n sortActivity,\n listHistoryFiles,\n};\n\n/**\n * Implements run activity for the public runtime surface of this module.\n */\nexport async function runActivity(options: ActivityCommandOptions, global: GlobalOptions): Promise<ActivityResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const nowValue = nowIso();\n const idFilter = parseNonEmptyFilter(options.id, \"Activity --id\");\n const opFilter = parseNonEmptyFilter(options.op, \"Activity --op\");\n const authorFilter = parseNonEmptyFilter(options.author, \"Activity --author\");\n const fromBound = parseRangeBound(options.from, nowValue, \"--from\");\n const toBound = parseRangeBound(options.to, nowValue, \"--to\");\n if (fromBound && toBound && compareTimestampStrings(fromBound, toBound) >= 0) {\n throw new PmCliError(\"Activity --from must be before --to\", EXIT_CODE.USAGE);\n }\n const limit = parseLimit(options.limit);\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const items = await listAllFrontMatterLight(pmRoot, settings.item_format, typeRegistry.type_to_folder, undefined, settings.schema);\n await enforceHistoryStreamPolicyForItems({\n pmRoot,\n settings,\n itemIds: items.map((item) => item.id),\n commandLabel: \"activity\",\n });\n const historyDir = path.join(pmRoot, \"history\");\n await runActiveOnReadHooks({\n path: historyDir,\n scope: \"project\",\n });\n const historyFiles = await listHistoryFiles(historyDir);\n\n const combined: ActivityEntry[] = [];\n for (const file of historyFiles) {\n const id = file.slice(0, -\".jsonl\".length);\n if (idFilter && id !== idFilter) {\n continue;\n }\n const entries = await readHistoryEntries(path.join(historyDir, file), id);\n for (const entry of entries) {\n if (opFilter && entry.op !== opFilter) {\n continue;\n }\n if (authorFilter && entry.author !== authorFilter) {\n continue;\n }\n const candidate = normalizeActivityEntry(id, entry);\n if (!includeByTimeWindow(candidate, fromBound, toBound)) {\n continue;\n }\n combined.push({\n ...candidate,\n });\n }\n }\n\n const activity = limitEntries(sortActivity(combined), limit);\n const compact = options.compact === true;\n const compactActivity = compact\n ? activity.map((entry): CompactActivityEntry => ({\n id: entry.id,\n op: entry.op,\n ts: entry.ts,\n author: entry.author,\n ...(entry.message ? { msg: entry.message } : {}),\n }))\n : undefined;\n return {\n activity: compact ? [] : activity,\n compact_activity: compactActivity,\n compact,\n count: activity.length,\n limit: limit ?? null,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,QAAQ;AACf,OAAO,UAAU;;;;;;;;AA0DjB,SAAS,oBAAoB,KAAyB,WAAiB;AACrE,MAAI,QAAQ;AAAW,WAAO;AAC9B,QAAM,aAAa,IAAI,KAAI;AAC3B,MAAI,WAAW,WAAW,GAAG;AAC3B,UAAM,IAAI,WAAW,GAAG,SAAS,sBAAsB,UAAU,KAAK;EACxE;AACA,SAAO;AAC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AAM;AACjI,QAAM,mCAAmC;IACvC;IACA;IACA,SAAS,MAAM,IAAI,CAAC,SAAS,KAAK,EAAE;IACpC,cAAc;GACf;AACD,QAAM,aAAa,KAAK,KAAK,QAAQ,SAAS;AAC9C,QAAM,qBAAqB;IACzB,MAAM;IACN,OAAO;GACR;AACD,QAAM,eAAe,MAAM,iBAAiB,UAAU;AAEtD,QAAM,WAA4B,CAAA;AAClC,aAAW,QAAQ,cAAc;AAC/B,UAAM,KAAK,KAAK,MAAM,GAAG,CAAC,SAAS,MAAM;AACzC,QAAI,YAAY,OAAO,UAAU;AAC/B;IACF;AACA,UAAM,UAAU,MAAM,mBAAmB,KAAK,KAAK,YAAY,IAAI,GAAG,EAAE;AACxE,eAAW,SAAS,SAAS;AAC3B,UAAI,YAAY,MAAM,OAAO,UAAU;AACrC;MACF;AACA,UAAI,gBAAgB,MAAM,WAAW,cAAc;AACjD;MACF;AACA,YAAM,YAAY,uBAAuB,IAAI,KAAK;AAClD,UAAI,CAAC,oBAAoB,WAAW,WAAW,OAAO,GAAG;AACvD;MACF;AACA,eAAS,KAAK;QACZ,GAAG;OACJ;IACH;EACF;AAEA,QAAM,WAAW,aAAa,aAAa,QAAQ,GAAG,KAAK;AAC3D,QAAM,UAAU,QAAQ,YAAY;AACpC,QAAM,kBAAkB,UACpB,SAAS,IAAI,CAAC,WAAiC;IAC7C,IAAI,MAAM;IACV,IAAI,MAAM;IACV,IAAI,MAAM;IACV,QAAQ,MAAM;IACd,GAAI,MAAM,UAAU,EAAE,KAAK,MAAM,QAAO,IAAK,CAAA;IAC7C,IACF;AACJ,SAAO;IACL,UAAU,UAAU,CAAA,IAAK;IACzB,kBAAkB;IAClB;IACA,OAAO,SAAS;IAChB,OAAO,SAAS;;AAEpB;",
6
- "names": ["global"]
7
- }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../../core/extensions/item-fields.ts","../../../../../../../../core/item/item-record.ts","../../../../../../../../core/history/history.ts","../../../../../../../../core/history/history-stream-policy.ts","../../../../../../../../core/lock/lock.ts","../../../../../../../../core/item/id.ts","../../../../../../../../core/store/front-matter-cache.ts","../../../../../../../../core/store/item-store.ts"],"sourcesContent":["/**\n * @module core/extensions/item-fields\n *\n * Implements extension runtime contracts and governance for Item Fields.\n */\nimport type { ExtensionRegistrationRegistry } from \"./loader.js\";\nimport { normalizeItemFieldType, type KnownItemFieldType } from \"./item-field-types.js\";\nimport { EXIT_CODE, FRONT_MATTER_KEY_ORDER } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\n\nconst RESERVED_ITEM_FIELD_NAMES = new Set(FRONT_MATTER_KEY_ORDER);\n\nfunction normalizeFieldName(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeFieldType(value: unknown): KnownItemFieldType | null {\n if (typeof value !== \"string\") {\n return null;\n }\n return normalizeItemFieldType(value);\n}\n\nfunction cloneFieldValue<T>(value: T): T {\n try {\n return structuredClone(value);\n } catch {\n return value;\n }\n}\n\nfunction parseFieldAssignment(raw: string): { key: string; value: string } {\n const trimmed = raw.trim();\n const separatorIndex = trimmed.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new PmCliError(`--field entries must use name=value syntax, received: ${raw}`, EXIT_CODE.USAGE);\n }\n // `separatorIndex > 0` guarantees a non-`=` first character on the already\n // trimmed string, so the trimmed key is always non-empty here.\n const key = trimmed.slice(0, separatorIndex).trim();\n const value = trimmed.slice(separatorIndex + 1);\n return { key, value };\n}\n\nfunction parseJsonFieldValue(raw: string, fieldName: string, expectedType: \"array\" | \"object\"): unknown {\n try {\n const parsed = JSON.parse(raw);\n if (expectedType === \"array\" && Array.isArray(parsed)) {\n return parsed;\n }\n if (expectedType === \"object\" && typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed;\n }\n } catch {\n // Fall through to the typed usage error below.\n }\n throw new PmCliError(`--field ${fieldName}=... must be valid JSON ${expectedType}`, EXIT_CODE.USAGE);\n}\n\nfunction coerceRegisteredFieldValue(fieldName: string, fieldType: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\", raw: string): unknown {\n if (fieldType === \"string\") {\n return raw;\n }\n if (fieldType === \"number\") {\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new PmCliError(`--field ${fieldName}=... must be a number`, EXIT_CODE.USAGE);\n }\n const parsed = Number(trimmed);\n if (!Number.isFinite(parsed)) {\n throw new PmCliError(`--field ${fieldName}=... must be a number`, EXIT_CODE.USAGE);\n }\n return parsed;\n }\n if (fieldType === \"boolean\") {\n const normalized = raw.trim().toLowerCase();\n if (normalized === \"true\" || normalized === \"1\" || normalized === \"yes\") {\n return true;\n }\n if (normalized === \"false\" || normalized === \"0\" || normalized === \"no\") {\n return false;\n }\n throw new PmCliError(`--field ${fieldName}=... must be one of true|false|1|0|yes|no`, EXIT_CODE.USAGE);\n }\n return parseJsonFieldValue(raw, fieldName, fieldType);\n}\n\nfunction collectRegisteredFieldDefinitions(\n registrations: ExtensionRegistrationRegistry | null,\n): Map<string, { name: string; type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" }> {\n const definitions = new Map<string, { name: string; type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\" }>();\n if (!registrations) {\n return definitions;\n }\n for (const registration of registrations.item_fields) {\n for (const definition of registration.fields) {\n const fieldName = normalizeFieldName(definition.name);\n const fieldType = normalizeFieldType(definition.type);\n if (!fieldName || !fieldType) {\n continue;\n }\n const existing = definitions.get(fieldName);\n if (existing && existing.type !== fieldType) {\n throw new PmCliError(\n `Extension item field \"${fieldName}\" is declared with conflicting types: ${existing.type}, ${fieldType}`,\n EXIT_CODE.USAGE,\n {\n code: \"extension_item_field_type_conflict\",\n nextSteps: [\"Make every active extension declaration for this field use the same type.\"],\n },\n );\n }\n definitions.set(fieldName, { name: fieldName, type: fieldType });\n }\n }\n return definitions;\n}\n\nfunction assertNotReservedItemFieldName(fieldName: string): void {\n if (!RESERVED_ITEM_FIELD_NAMES.has(fieldName)) {\n return;\n }\n throw new PmCliError(`Extension item field \"${fieldName}\" collides with reserved item metadata`, EXIT_CODE.USAGE, {\n code: \"extension_item_field_reserved\",\n nextSteps: [\"Rename the extension item field, preferably with an extension-specific prefix.\"],\n });\n}\n\n/**\n * Implements collect registered item field names for the public runtime surface of this module.\n */\nexport function collectRegisteredItemFieldNames(registrations: ExtensionRegistrationRegistry | null): string[] {\n return [...collectRegisteredFieldDefinitions(registrations).keys()].sort((left, right) => left.localeCompare(right));\n}\n\n/**\n * Implements parse registered item field assignments for the public runtime surface of this module.\n */\nexport function parseRegisteredItemFieldAssignments(\n rawFields: string[] | undefined,\n registrations: ExtensionRegistrationRegistry | null,\n): Record<string, unknown> {\n if (!rawFields || rawFields.length === 0) {\n return {};\n }\n const definitions = collectRegisteredFieldDefinitions(registrations);\n const values: Record<string, unknown> = {};\n for (const raw of rawFields) {\n const { key, value } = parseFieldAssignment(raw);\n const definition = definitions.get(key);\n if (!definition) {\n const known = [...definitions.keys()].sort((left, right) => left.localeCompare(right));\n throw new PmCliError(`--field ${key} is not declared by an active extension item-field registration`, EXIT_CODE.USAGE, {\n code: \"extension_item_field_unknown\",\n recovery: { provided_fields: known },\n nextSteps: known.length > 0\n ? [`Use one of the declared fields: ${known.join(\", \")}`]\n : [\"Activate an extension that calls registerItemFields before setting extension fields.\"],\n });\n }\n assertNotReservedItemFieldName(definition.name);\n values[definition.name] = coerceRegisteredFieldValue(definition.name, definition.type, value);\n }\n return values;\n}\n\nfunction isValidFieldType(value: unknown, expectedType: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\"): boolean {\n if (expectedType === \"string\") {\n return typeof value === \"string\";\n }\n if (expectedType === \"number\") {\n return typeof value === \"number\" && Number.isFinite(value);\n }\n if (expectedType === \"boolean\") {\n return typeof value === \"boolean\";\n }\n if (expectedType === \"array\") {\n return Array.isArray(value);\n }\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isAllowedFieldValue(value: unknown, allowed: unknown[] | undefined): boolean {\n if (!allowed || allowed.length === 0) {\n return true;\n }\n return allowed.some((candidate) => Object.is(candidate, value));\n}\n\n/**\n * Implements apply registered item field defaults and validation for the public runtime surface of this module.\n */\nexport function applyRegisteredItemFieldDefaultsAndValidation(\n frontMatter: Record<string, unknown>,\n registrations: ExtensionRegistrationRegistry | null,\n options: { skipDefaultFields?: ReadonlySet<string> } = {},\n): void {\n if (!registrations) {\n return;\n }\n collectRegisteredFieldDefinitions(registrations);\n for (const registration of registrations.item_fields) {\n for (const definition of registration.fields) {\n const fieldName = normalizeFieldName(definition.name);\n if (!fieldName) {\n continue;\n }\n assertNotReservedItemFieldName(fieldName);\n if (\n !(fieldName in frontMatter) &&\n !options.skipDefaultFields?.has(fieldName) &&\n Object.prototype.hasOwnProperty.call(definition, \"default\")\n ) {\n frontMatter[fieldName] = cloneFieldValue(definition.default);\n }\n\n const currentValue = frontMatter[fieldName];\n if (currentValue === undefined) {\n continue;\n }\n const expectedType = normalizeFieldType(definition.type);\n if (expectedType && !isValidFieldType(currentValue, expectedType)) {\n throw new TypeError(`Item field \"${fieldName}\" must be of type ${expectedType}`);\n }\n\n const allowedValues = Array.isArray(definition.values) ? definition.values : undefined;\n if (!isAllowedFieldValue(currentValue, allowedValues)) {\n throw new TypeError(`Item field \"${fieldName}\" must match one of the configured allowed values`);\n }\n }\n }\n}\n","/**\n * @module core/item/item-record\n *\n * Defines item parsing, formatting, and lifecycle helpers for Item Record.\n */\nimport type { ItemMetadata } from \"../../types/index.js\";\n\n/**\n * Bridge a typed item record into the generic `Record<string, unknown>` shape\n * consumed by formatters, field projections, history canonicalization, and\n * JSON output paths.\n *\n * `ItemMetadata` carries an index signature, but the structural mismatch on its\n * concretely-typed fields means TypeScript still requires a double cast to widen\n * it. Centralizing that `as unknown as Record<string, unknown>` widening here\n * gives the type bridge a single, named, documented home instead of scattering\n * the cast across command and core modules.\n *\n * This is a compile-time-only widening: the returned value is the very same\n * object reference, with no runtime transformation. (It is intentionally\n * distinct from the runtime `asRecord*` guards in `core/shared/primitives.ts`,\n * which validate `typeof` at runtime.) `ItemFrontMatter` is an alias of\n * `ItemMetadata`, so front-matter values are accepted as-is.\n */\nexport function toItemRecord(item: ItemMetadata): Record<string, unknown> {\n return item as unknown as Record<string, unknown>;\n}\n","/**\n * @module core/history/history\n *\n * Implements append-only history and replay behavior for History.\n */\nimport jsonPatch from \"fast-json-patch\";\nimport { FRONT_MATTER_KEY_ORDER } from \"../shared/constants.js\";\nimport { runActiveServiceOverride } from \"../extensions/index.js\";\nimport { appendLineAtomic } from \"../fs/fs-utils.js\";\nimport { canonicalDocument } from \"../item/item-format.js\";\nimport { toItemRecord } from \"../item/item-record.js\";\nimport { orderObject, sha256Hex, stableStringify } from \"../shared/serialization.js\";\nimport { nowIso } from \"../shared/time.js\";\nimport type { HistoryEntry, HistoryPatchOp, ItemDocument } from \"../../types/index.js\";\n\nconst EMPTY_LEGACY_HASH_DOCUMENT = {\n front_matter: {},\n body: \"\",\n};\n\nfunction decodeJsonPointer(path: string): string[] {\n if (!path || path === \"/\") {\n return [];\n }\n if (!path.startsWith(\"/\")) {\n return [];\n }\n return path\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n}\n\nfunction isDefinedPointerPath(document: unknown, path: string): boolean {\n const segments = decodeJsonPointer(path);\n if (segments.length === 0) {\n return true;\n }\n let cursor: unknown = document;\n for (const segment of segments) {\n if (Array.isArray(cursor)) {\n if (segment === \"-\" || !/^(0|[1-9]\\d*)$/.test(segment)) {\n return false;\n }\n const index = Number(segment);\n if (!Number.isInteger(index) || index < 0 || index >= cursor.length) {\n return false;\n }\n const next = cursor[index];\n if (next === undefined) {\n return false;\n }\n cursor = next;\n continue;\n }\n if (typeof cursor !== \"object\" || cursor === null) {\n return false;\n }\n if (!Object.prototype.hasOwnProperty.call(cursor, segment)) {\n return false;\n }\n const next = (cursor as Record<string, unknown>)[segment];\n if (next === undefined) {\n return false;\n }\n cursor = next;\n }\n return true;\n}\n\nfunction normalizeHistoryPatchOps(\n beforeDocument: { metadata: Record<string, unknown>; body: string },\n patch: HistoryPatchOp[],\n): HistoryPatchOp[] {\n const normalized: HistoryPatchOp[] = [];\n let replayCursor: unknown = structuredClone(beforeDocument);\n for (const operation of patch) {\n const normalizedOperation =\n operation.op === \"replace\" && !isDefinedPointerPath(replayCursor, operation.path)\n ? ({ ...operation, op: \"add\" } as HistoryPatchOp)\n : operation;\n normalized.push(normalizedOperation);\n replayCursor = jsonPatch.applyPatch(\n replayCursor,\n [normalizedOperation as jsonPatch.Operation],\n true,\n true,\n ).newDocument as unknown;\n }\n return normalized;\n}\n\nfunction canonicalHashDocument(document: ItemDocument): { front_matter: Record<string, unknown>; body: string } {\n const hasMetadata = document.metadata && Object.keys(document.metadata).length > 0;\n if (!hasMetadata) {\n return {\n front_matter: {},\n body: document.body ?? \"\",\n };\n }\n const canonical = canonicalDocument(document);\n const orderedFrontMatter = orderObject(toItemRecord(canonical.metadata), FRONT_MATTER_KEY_ORDER);\n return {\n front_matter: orderedFrontMatter,\n body: canonical.body,\n };\n}\n\nfunction canonicalPatchDocument(document: ItemDocument): { metadata: Record<string, unknown>; body: string } {\n const hasMetadata = document.metadata && Object.keys(document.metadata).length > 0;\n if (!hasMetadata) {\n return {\n metadata: {},\n body: document.body ?? \"\",\n };\n }\n const canonical = canonicalDocument(document);\n const orderedMetadata = orderObject(toItemRecord(canonical.metadata), FRONT_MATTER_KEY_ORDER);\n return {\n metadata: orderedMetadata,\n body: canonical.body,\n };\n}\n\n/**\n * Implements hash document for the public runtime surface of this module.\n */\nexport function hashDocument(document: ItemDocument): string {\n return sha256Hex(stableStringify(canonicalHashDocument(document)));\n}\n\n/**\n * Implements hash empty document for the public runtime surface of this module.\n */\nexport function hashEmptyDocument(): string {\n return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT));\n}\n\n/**\n * Implements create history entry for the public runtime surface of this module.\n */\nexport function createHistoryEntry(params: {\n nowIso: string;\n author: string;\n op: string;\n before: ItemDocument;\n after: ItemDocument;\n message?: string;\n}): HistoryEntry {\n const beforeHashCanonical = canonicalHashDocument(params.before);\n const afterHashCanonical = canonicalHashDocument(params.after);\n const beforePatchCanonical = canonicalPatchDocument(params.before);\n const afterPatchCanonical = canonicalPatchDocument(params.after);\n const rawPatch = jsonPatch.compare(beforePatchCanonical, afterPatchCanonical) as HistoryPatchOp[];\n const patch = normalizeHistoryPatchOps(beforePatchCanonical, rawPatch);\n\n return {\n ts: params.nowIso,\n author: params.author,\n op: params.op,\n patch,\n before_hash: sha256Hex(stableStringify(beforeHashCanonical)),\n after_hash: sha256Hex(stableStringify(afterHashCanonical)),\n message: params.message === undefined ? undefined : params.message,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction fallbackHistoryTimestamp(entry: Pick<HistoryEntry, \"ts\">): string {\n const ts = entry.ts.trim();\n return ts.length > 0 ? ts : nowIso();\n}\n\nfunction withHistoryTimestamp(value: Record<string, unknown>, fallbackTs: string): Record<string, unknown> {\n const ts = value.ts;\n if (typeof ts === \"string\" && ts.trim().length > 0) {\n return value;\n }\n return { ...value, ts: fallbackTs };\n}\n\nfunction serializeHistoryLine(value: unknown, fallbackEntry: Pick<HistoryEntry, \"ts\">): string {\n const fallbackTs = fallbackHistoryTimestamp(fallbackEntry);\n if (typeof value === \"string\") {\n try {\n const parsed = JSON.parse(value) as unknown;\n if (isRecord(parsed)) {\n return JSON.stringify(withHistoryTimestamp(parsed, fallbackTs));\n }\n } catch {\n // Non-JSON extension lines are preserved for compatibility.\n }\n return value;\n }\n if (isRecord(value)) {\n return JSON.stringify(withHistoryTimestamp(value, fallbackTs));\n }\n return JSON.stringify(value);\n}\n\n/**\n * Implements append history entry for the public runtime surface of this module.\n */\nexport async function appendHistoryEntry(historyPath: string, entry: HistoryEntry): Promise<void> {\n const override = await runActiveServiceOverride(\"history_append\", {\n history_path: historyPath,\n entry,\n });\n if (override.handled) {\n if (override.result === false) {\n return;\n }\n if (typeof override.result === \"string\") {\n await appendLineAtomic(historyPath, serializeHistoryLine(override.result, entry));\n return;\n }\n if (typeof override.result === \"object\" && override.result !== null) {\n const record = override.result as {\n history_path?: unknown;\n entry?: unknown;\n line?: unknown;\n skip?: unknown;\n };\n if (record.skip === true) {\n return;\n }\n const nextHistoryPath = typeof record.history_path === \"string\" ? record.history_path : historyPath;\n if (typeof record.line === \"string\") {\n await appendLineAtomic(nextHistoryPath, serializeHistoryLine(record.line, entry));\n return;\n }\n await appendLineAtomic(nextHistoryPath, serializeHistoryLine(record.entry ?? entry, entry));\n return;\n }\n }\n await appendLineAtomic(historyPath, serializeHistoryLine(entry, entry));\n}\n\nexport const _testOnly = {\n decodeJsonPointer,\n isDefinedPointerPath,\n};\n","/**\n * @module core/history/history-stream-policy\n *\n * Implements append-only history and replay behavior for History Stream Policy.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { runActiveOnWriteHooks } from \"../extensions/index.js\";\nimport { ensureDir, pathExists } from \"../fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { getHistoryPath } from \"../store/paths.js\";\nimport type { PmSettings } from \"../../types/index.js\";\n\ninterface HistoryStreamPolicyParams {\n pmRoot: string;\n settings: PmSettings;\n itemId: string;\n commandLabel: string;\n}\n\ninterface HistoryStreamPolicyManyParams {\n pmRoot: string;\n settings: PmSettings;\n itemIds: string[];\n commandLabel: string;\n}\n\n/**\n * Documents the history stream policy result payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryStreamPolicyResult {\n auto_created_ids: string[];\n warnings: string[];\n}\n\nfunction toSortedUniqueItemIds(itemIds: string[]): string[] {\n return [...new Set(itemIds.filter((value) => value.trim().length > 0))].sort((left, right) => left.localeCompare(right));\n}\n\nfunction strictMissingStreamError(itemId: string, commandLabel: string): PmCliError {\n return new PmCliError(\n `Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,\n EXIT_CODE.NOT_FOUND,\n );\n}\n\nasync function createStream(historyPath: string, commandLabel: string): Promise<string[]> {\n await ensureDir(path.dirname(historyPath));\n const handle = await fs.open(historyPath, \"a\");\n await handle.close();\n return runActiveOnWriteHooks({\n path: historyPath,\n scope: \"project\",\n op: `${commandLabel}:history:auto_create`,\n });\n}\n\n/**\n * Implements enforce history stream policy for item for the public runtime surface of this module.\n */\nexport async function enforceHistoryStreamPolicyForItem(params: HistoryStreamPolicyParams): Promise<HistoryStreamPolicyResult> {\n return enforceHistoryStreamPolicyForItems({\n pmRoot: params.pmRoot,\n settings: params.settings,\n itemIds: [params.itemId],\n commandLabel: params.commandLabel,\n });\n}\n\n/**\n * Implements enforce history stream policy for items for the public runtime surface of this module.\n */\nexport async function enforceHistoryStreamPolicyForItems(\n params: HistoryStreamPolicyManyParams,\n): Promise<HistoryStreamPolicyResult> {\n const ids = toSortedUniqueItemIds(params.itemIds);\n const autoCreated: string[] = [];\n const warnings: string[] = [];\n\n for (const itemId of ids) {\n const historyPath = getHistoryPath(params.pmRoot, itemId);\n if (await pathExists(historyPath)) {\n continue;\n }\n if (params.settings.history.missing_stream === \"strict_error\") {\n throw strictMissingStreamError(itemId, params.commandLabel);\n }\n warnings.push(...(await createStream(historyPath, params.commandLabel)));\n warnings.push(`history_stream_auto_created:${itemId}`);\n autoCreated.push(itemId);\n }\n\n return {\n auto_created_ids: autoCreated,\n warnings,\n };\n}\n","/**\n * @module core/lock/lock\n *\n * Coordinates tracker lock ownership and cleanup for Lock.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { runActiveOnReadHooks, runActiveOnWriteHooks, runActiveServiceOverride } from \"../extensions/index.js\";\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { toErrorMessage } from \"../shared/primitives.js\";\nimport { getLockPath } from \"../store/paths.js\";\nimport { nowIso } from \"../shared/time.js\";\n\ninterface LockInfo {\n id: string;\n pid: number;\n owner: string;\n created_at: string;\n ttl_seconds: number;\n}\n\ntype LockWriteOp = \"lock:create\" | \"lock:release\" | \"lock:stale_remove\";\n\ninterface LockReadResult {\n info: LockInfo | null;\n warnings: string[];\n}\n\nfunction parseLockInfo(raw: string): LockReadResult {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n return {\n info: null,\n warnings: [\"lock_info_invalid_json\"],\n };\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return {\n info: null,\n warnings: [\"lock_info_invalid_shape\"],\n };\n }\n const candidate = parsed as Record<string, unknown>;\n const id = candidate.id;\n const pid = candidate.pid;\n const owner = candidate.owner;\n const createdAt = candidate.created_at;\n const ttlSeconds = candidate.ttl_seconds;\n if (\n typeof id !== \"string\" ||\n typeof pid !== \"number\" ||\n !Number.isFinite(pid) ||\n typeof owner !== \"string\" ||\n typeof createdAt !== \"string\" ||\n typeof ttlSeconds !== \"number\" ||\n !Number.isFinite(ttlSeconds)\n ) {\n return {\n info: null,\n warnings: [\"lock_info_invalid_shape\"],\n };\n }\n return {\n info: {\n id,\n pid,\n owner,\n created_at: createdAt,\n ttl_seconds: ttlSeconds,\n },\n warnings: [],\n };\n}\n\nasync function readLockInfo(lockPath: string): Promise<LockReadResult> {\n try {\n const raw = await fs.readFile(lockPath, \"utf8\");\n await runActiveOnReadHooks({\n path: lockPath,\n scope: \"project\",\n });\n return parseLockInfo(raw);\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return {\n info: null,\n warnings: [],\n };\n }\n return {\n info: null,\n warnings: [\"lock_info_read_failed\"],\n };\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === code;\n}\n\nasync function emitLockWriteHook(lockPath: string, op: LockWriteOp): Promise<void> {\n await runActiveOnWriteHooks({\n path: lockPath,\n scope: \"project\",\n op,\n });\n}\n\nfunction buildLockPayload(id: string, owner: string, ttlSeconds: number): LockInfo {\n return {\n id,\n pid: process.pid,\n owner,\n created_at: nowIso(),\n ttl_seconds: ttlSeconds,\n };\n}\n\nasync function createLockFile(lockPath: string, id: string, owner: string, ttlSeconds: number): Promise<void> {\n await fs.mkdir(path.dirname(lockPath), { recursive: true });\n const handle = await fs.open(lockPath, \"wx\");\n try {\n await handle.writeFile(`${JSON.stringify(buildLockPayload(id, owner, ttlSeconds), null, 2)}\\n`, \"utf8\");\n } finally {\n await handle.close();\n }\n await emitLockWriteHook(lockPath, \"lock:create\");\n}\n\nasync function unlinkLockWithHook(lockPath: string, op: \"lock:release\" | \"lock:stale_remove\"): Promise<void> {\n try {\n await fs.unlink(lockPath);\n await emitLockWriteHook(lockPath, op);\n } catch {\n // Lock cleanup is best-effort.\n }\n}\n\nfunction isStaleLock(info: LockInfo | null, ttlSeconds: number): boolean {\n const createdAtMs = info?.created_at ? Date.parse(info.created_at) : Number.NaN;\n const ageMs = Number.isFinite(createdAtMs) ? Date.now() - createdAtMs : Number.POSITIVE_INFINITY;\n return ageMs > ttlSeconds * 1000;\n}\n\nfunction lockOwnerSuffix(info: LockInfo | null): string {\n return info?.owner ? ` (owner ${info.owner})` : \"\";\n}\n\nasync function handleExistingLock(\n lockPath: string,\n id: string,\n ttlSeconds: number,\n force: boolean,\n forceRequiredForStaleLock: boolean,\n): Promise<void> {\n const lockInfo = await readLockInfo(lockPath);\n if (!isStaleLock(lockInfo.info, ttlSeconds)) {\n throw new PmCliError(`Item ${id} is locked${lockOwnerSuffix(lockInfo.info)}`, EXIT_CODE.CONFLICT);\n }\n\n if (!force && forceRequiredForStaleLock) {\n const warningSuffix = lockInfo.warnings.length > 0 ? ` (${lockInfo.warnings.join(\",\")})` : \"\";\n throw new PmCliError(\n `Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,\n EXIT_CODE.CONFLICT,\n );\n }\n\n await unlinkLockWithHook(lockPath, \"lock:stale_remove\");\n}\n\nexport const _testOnly = {\n parseLockInfo,\n readLockInfo,\n isErrno,\n buildLockPayload,\n isStaleLock,\n lockOwnerSuffix,\n};\n\n\n/**\n * Implements acquire lock for the public runtime surface of this module.\n */\nexport async function acquireLock(\n pmRoot: string,\n id: string,\n ttlSeconds: number,\n owner: string,\n force = false,\n forceRequiredForStaleLock = true,\n): Promise<() => Promise<void>> {\n const lockOverride = await runActiveServiceOverride(\"lock_acquire\", {\n pm_root: pmRoot,\n id,\n ttl_seconds: ttlSeconds,\n owner,\n force,\n force_required_for_stale_lock: forceRequiredForStaleLock,\n });\n if (lockOverride.handled) {\n const releaseFromFunction = typeof lockOverride.result === \"function\" ? lockOverride.result : null;\n const releaseFromObject =\n typeof lockOverride.result === \"object\" &&\n lockOverride.result !== null &&\n \"release\" in lockOverride.result &&\n typeof (lockOverride.result as { release?: unknown }).release === \"function\"\n ? ((lockOverride.result as { release: () => Promise<void> | void }).release as () => Promise<void> | void)\n : null;\n const release = releaseFromFunction ?? releaseFromObject;\n if (release) {\n return async () => {\n await Promise.resolve(release());\n await runActiveServiceOverride(\"lock_release\", {\n pm_root: pmRoot,\n id,\n owner,\n });\n };\n }\n }\n\n const lockPath = getLockPath(pmRoot, id);\n\n for (let attempt = 0; attempt < 3; attempt += 1) {\n try {\n await createLockFile(lockPath, id, owner, ttlSeconds);\n return async () => {\n await unlinkLockWithHook(lockPath, \"lock:release\");\n await runActiveServiceOverride(\"lock_release\", {\n pm_root: pmRoot,\n id,\n owner,\n });\n };\n } catch (error: unknown) {\n if (!isErrno(error, \"EEXIST\")) {\n throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`, EXIT_CODE.GENERIC_FAILURE);\n }\n await handleExistingLock(lockPath, id, ttlSeconds, force, forceRequiredForStaleLock);\n }\n }\n\n throw new PmCliError(`Failed to acquire lock for ${id}`, EXIT_CODE.CONFLICT);\n}\n","/**\n * @module core/item/id\n *\n * Defines item parsing, formatting, and lifecycle helpers for Id.\n */\nimport crypto from \"node:crypto\";\nimport path from \"node:path\";\nimport { TYPE_TO_FOLDER } from \"../shared/constants.js\";\nimport { pathExists } from \"../fs/fs-utils.js\";\n\n/**\n * Implements normalize prefix for the public runtime surface of this module.\n */\nexport function normalizePrefix(input: string | undefined): string {\n const normalized = (input ?? \"\").trim().toLowerCase();\n if (!normalized) return \"pm-\";\n return normalized.endsWith(\"-\") ? normalized : `${normalized}-`;\n}\n\n/**\n * Implements normalize raw item id for the public runtime surface of this module.\n */\nexport function normalizeRawItemId(input: string): string {\n let normalized = input.trim().toLowerCase();\n if (normalized.startsWith(\"#\")) {\n normalized = normalized.slice(1);\n }\n return normalized;\n}\n\n/**\n * Implements normalize item id for the public runtime surface of this module.\n */\nexport function normalizeItemId(input: string, prefix: string): string {\n const canonicalPrefix = normalizePrefix(prefix);\n const normalized = normalizeRawItemId(input);\n if (normalized.startsWith(canonicalPrefix)) {\n return normalized;\n }\n return `${canonicalPrefix}${normalized}`;\n}\n\nfunction randomToken(length: number): string {\n let token = \"\";\n for (let index = 0; index < length; index += 1) {\n token += crypto.randomInt(0, 36).toString(36);\n }\n return token;\n}\n\nasync function idExists(pmRoot: string, id: string): Promise<boolean> {\n const checks = Object.values(TYPE_TO_FOLDER).flatMap((folder) => [\n path.join(pmRoot, folder, `${id}.md`),\n path.join(pmRoot, folder, `${id}.toon`),\n ]);\n for (const target of checks) {\n if (await pathExists(target)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Implements generate item id for the public runtime surface of this module.\n */\nexport async function generateItemId(pmRoot: string, prefix: string): Promise<string> {\n let tokenLength = 4;\n let attempts = 0;\n\n while (tokenLength <= 10) {\n for (let i = 0; i < 32; i += 1) {\n const id = `${normalizePrefix(prefix)}${randomToken(tokenLength)}`;\n if (!(await idExists(pmRoot, id))) {\n return id;\n }\n attempts += 1;\n }\n tokenLength += 1;\n }\n\n throw new Error(`Unable to generate unique id after ${attempts} attempts`);\n}\n","/**\n * @module core/store/front-matter-cache\n *\n * Reads and writes tracker storage with format-aware helpers for Front Matter Cache.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport { getActiveExtensionRegistrations, hasActiveOnReadHooks, runActiveOnReadHooks } from \"../extensions/index.js\";\nimport { collectRegisteredItemFieldNames } from \"../extensions/item-fields.js\";\nimport { parseItemDocument } from \"../item/item-format.js\";\nimport { writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { ITEM_FILE_EXTENSIONS, getItemFormatFromPath } from \"./paths.js\";\nimport type { ItemDocument, ItemFormat, ItemMetadata, ItemType, RuntimeSchemaSettings } from \"../../types/index.js\";\n\nconst CACHE_VERSION = 6;\nconst CACHE_FILENAME = \"metadata-cache.json\";\nconst BODY_CACHE_FILENAME = \"metadata-cache-bodies.json\";\nconst COLLECTIONS_CACHE_FILENAME = \"metadata-cache-collections.json\";\n\n/**\n * Heavy \"collection\" front-matter fields. These arrays dominate the on-disk cache\n * (e.g. a single item's comment thread can be hundreds of KB) yet the hot list path\n * (`pm list`, stats, deps, activity, calendar, close) never reads them. They are\n * stored in a separate collections cache that is parsed only when a caller opts in\n * (`includeCollections`), keeping the always-loaded light cache an order of magnitude\n * smaller and its JSON.parse correspondingly cheaper.\n */\nexport const HEAVY_METADATA_KEYS = [\n \"comments\",\n \"notes\",\n \"learnings\",\n \"files\",\n \"tests\",\n \"test_runs\",\n \"docs\",\n] as const;\n\nfunction resolveActiveExtensionFieldNames(): readonly string[] {\n return collectRegisteredItemFieldNames(getActiveExtensionRegistrations());\n}\n\ninterface StatSignature {\n mtime_ms: number;\n ctime_ms: number;\n size: number;\n}\n\ninterface CachedEntry extends StatSignature {\n metadata: ItemMetadata;\n body_length: number;\n}\n\ninterface CachedBody extends StatSignature {\n body: string;\n}\n\ninterface CachedCollections extends StatSignature {\n collections: Record<string, unknown>;\n}\n\ninterface CacheEnvelope {\n version: number;\n context_fingerprint: string;\n entries: Record<string, CachedEntry>;\n}\n\ninterface BodyCacheEnvelope {\n version: number;\n context_fingerprint: string;\n bodies: Record<string, CachedBody>;\n}\n\ninterface CollectionsCacheEnvelope {\n version: number;\n context_fingerprint: string;\n collections: Record<string, CachedCollections>;\n}\n\n/**\n * Split parsed front-matter into the light scalar/small fields (everything except the\n * heavy collection arrays) and the heavy collection fields. Only keys that are actually\n * present are moved, so an item without comments stays without comments in both tiers.\n */\nfunction splitHeavyMetadata(metadata: ItemMetadata): {\n light: ItemMetadata;\n heavy: Record<string, unknown>;\n} {\n const light = { ...metadata } as Record<string, unknown>;\n const heavy: Record<string, unknown> = {};\n for (const key of HEAVY_METADATA_KEYS) {\n if (key in light) {\n heavy[key] = light[key];\n delete light[key];\n }\n }\n return { light: light as ItemMetadata, heavy };\n}\n\n/**\n * Recombine light metadata with cached heavy collection fields. Key order differs from\n * the on-disk document, but every downstream hash/serialization canonicalizes and\n * sorts keys (`stableStringify`), so the merged record is byte-identical once hashed.\n */\nfunction mergeHeavyMetadata(light: ItemMetadata, heavy: Record<string, unknown> | undefined): ItemMetadata {\n if (!heavy || Object.keys(heavy).length === 0) {\n return light;\n }\n return { ...light, ...heavy } as ItemMetadata;\n}\n\n/**\n * Documents the cached document candidate payload exchanged by command, SDK, and package integrations.\n */\nexport interface CachedDocumentCandidate {\n metadata: ItemMetadata;\n body?: string;\n item_format: ItemFormat;\n item_path: string;\n}\n\nfunction computeContextFingerprint(\n preferredFormat: ItemFormat | undefined,\n typeToFolder: Record<string, string>,\n schema: RuntimeSchemaSettings | undefined,\n extensionFieldNames: readonly string[],\n): string {\n const hash = createHash(\"sha256\");\n hash.update(`format:${preferredFormat ?? \"default\"}`);\n const sortedTypes = Object.entries(typeToFolder)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([type, folder]) => `${type}=${folder}`)\n .join(\",\");\n hash.update(`|types:${sortedTypes}`);\n if (schema) {\n hash.update(`|schema:${JSON.stringify(schema)}`);\n }\n if (extensionFieldNames.length > 0) {\n hash.update(`|extension_fields:${extensionFieldNames.join(\",\")}`);\n }\n return hash.digest(\"hex\").slice(0, 16);\n}\n\nfunction getCachePath(pmRoot: string): string {\n return path.join(pmRoot, \"runtime\", CACHE_FILENAME);\n}\n\nfunction getBodyCachePath(pmRoot: string): string {\n return path.join(pmRoot, \"runtime\", BODY_CACHE_FILENAME);\n}\n\nfunction getCollectionsCachePath(pmRoot: string): string {\n return path.join(pmRoot, \"runtime\", COLLECTIONS_CACHE_FILENAME);\n}\n\nasync function loadCache(pmRoot: string): Promise<CacheEnvelope | null> {\n try {\n const raw = await fs.readFile(getCachePath(pmRoot), \"utf8\");\n const parsed = JSON.parse(raw) as CacheEnvelope;\n if (parsed.version !== CACHE_VERSION || typeof parsed.entries !== \"object\" || parsed.entries === null) {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\nasync function loadBodyCache(pmRoot: string): Promise<BodyCacheEnvelope | null> {\n try {\n const raw = await fs.readFile(getBodyCachePath(pmRoot), \"utf8\");\n const parsed = JSON.parse(raw) as BodyCacheEnvelope;\n if (parsed.version !== CACHE_VERSION || typeof parsed.bodies !== \"object\" || parsed.bodies === null) {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\nasync function loadCollectionsCache(pmRoot: string): Promise<CollectionsCacheEnvelope | null> {\n try {\n const raw = await fs.readFile(getCollectionsCachePath(pmRoot), \"utf8\");\n const parsed = JSON.parse(raw) as CollectionsCacheEnvelope;\n if (parsed.version !== CACHE_VERSION || typeof parsed.collections !== \"object\" || parsed.collections === null) {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\nasync function persistCache(\n cachePath: string,\n envelope: CacheEnvelope | BodyCacheEnvelope | CollectionsCacheEnvelope,\n): Promise<void> {\n await fs.mkdir(path.dirname(cachePath), { recursive: true });\n await writeFileAtomic(cachePath, JSON.stringify(envelope));\n}\n\n/**\n * Decide whether a freshly parsed document candidate should replace the one\n * already recorded for the same item id when both an explicit-format file and a\n * fallback-format file exist (e.g. `pm-x.toon` and `pm-x.md`). An explicit\n * `preferredFormat` wins; otherwise `toon` wins over any non-toon format.\n *\n * This is a pure decision so the winner is fully deterministic regardless of the\n * order in which the concurrent per-file reads resolve — the inline call site\n * populates the map as each async read completes, so without a pure rule the\n * branch taken (and thus its coverage) would race. Keep this exported and\n * unit-tested across every format combination.\n */\nexport function shouldReplaceCachedDocumentCandidate(\n existingFormat: ItemFormat,\n candidateFormat: ItemFormat,\n preferredFormat: ItemFormat | undefined,\n): boolean {\n if (preferredFormat) {\n return candidateFormat === preferredFormat && existingFormat !== preferredFormat;\n }\n return candidateFormat === \"toon\" && existingFormat !== \"toon\";\n}\n\nfunction appendWarning(warnings: string[] | undefined, warning: string): void {\n if (warnings && !warnings.includes(warning)) {\n warnings.push(warning);\n }\n}\n\nfunction statMatches(signature: StatSignature, mtimeMs: number, ctimeMs: number, size: number): boolean {\n return signature.mtime_ms === mtimeMs && signature.ctime_ms === ctimeMs && signature.size === size;\n}\n\n/**\n * Documents the list cache options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ListCacheOptions {\n /**\n * When false, item bodies are neither loaded from nor written to the separate\n * body cache. Metadata-only callers (`pm list`, stats, deps, activity, …) skip\n * the large body cache entirely; only body consumers (search/reindex) pay for it.\n */\n includeBody?: boolean;\n /**\n * When false, heavy collection fields (comments/notes/learnings/files/tests/\n * test_runs/docs) are neither loaded from nor written to the separate collections\n * cache, and are absent from the returned metadata. Light-only callers (`pm list`\n * compact, stats, deps, activity, calendar, close) skip the large collections cache\n * entirely. Defaults to true so any caller that does read those fields stays correct.\n */\n includeCollections?: boolean;\n}\n\n/**\n * List all item documents using a persistent on-disk metadata cache.\n *\n * Metadata and bodies are stored in two separate cache files so the hot path\n * (`pm list` and friends, which discard bodies) never loads or rewrites the much\n * larger body payload. Each file is rewritten only when its contents actually\n * change, and per-file onRead hooks are dispatched only when an extension\n * registers one. Only files whose mtime/ctime/size changed since the last run are\n * re-parsed.\n */\nexport async function listAllDocumentCandidatesCached(\n pmRoot: string,\n preferredFormat: ItemFormat | undefined,\n typeToFolder: Record<string, string>,\n warnings: string[] | undefined,\n schema: RuntimeSchemaSettings | undefined,\n options: ListCacheOptions = {},\n): Promise<CachedDocumentCandidate[]> {\n const includeBody = options.includeBody !== false;\n const includeCollections = options.includeCollections !== false;\n const extensionFieldNames = resolveActiveExtensionFieldNames();\n const contextFingerprint = computeContextFingerprint(preferredFormat, typeToFolder, schema, extensionFieldNames);\n\n const existingCache = await loadCache(pmRoot);\n const previousEntries: Record<string, CachedEntry> =\n existingCache && existingCache.context_fingerprint === contextFingerprint ? existingCache.entries : {};\n\n const existingBodyCache = includeBody ? await loadBodyCache(pmRoot) : null;\n const previousBodies: Record<string, CachedBody> =\n existingBodyCache && existingBodyCache.context_fingerprint === contextFingerprint ? existingBodyCache.bodies : {};\n\n const existingCollectionsCache = includeCollections ? await loadCollectionsCache(pmRoot) : null;\n const previousCollections: Record<string, CachedCollections> =\n existingCollectionsCache && existingCollectionsCache.context_fingerprint === contextFingerprint\n ? existingCollectionsCache.collections\n : {};\n\n const entries = Object.entries(typeToFolder) as Array<[ItemType, string]>;\n const dirResults = await Promise.all(\n entries.map(async ([, folder]) => {\n const dirPath = path.join(pmRoot, folder);\n try {\n const files = await fs.readdir(dirPath);\n return { folder, dirPath, files };\n } catch (error: unknown) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code !== \"ENOENT\") {\n appendWarning(warnings, `item_list_directory_read_failed:${folder}`);\n }\n return { folder, dirPath, files: [] as string[] };\n }\n }),\n );\n\n const dispatchReadHooks = hasActiveOnReadHooks();\n const newEntries: Record<string, CachedEntry> = {};\n const newBodies: Record<string, CachedBody> = {};\n const newCollections: Record<string, CachedCollections> = {};\n const documentsById = new Map<string, { candidate: CachedDocumentCandidate; itemFormat: ItemFormat }>();\n let metadataMiss = false;\n let bodyMiss = false;\n let collectionsMiss = false;\n\n const parseTasks: Array<Promise<void>> = [];\n\n for (const { folder, dirPath, files } of dirResults) {\n for (const file of files) {\n if (!ITEM_FILE_EXTENSIONS.some((ext) => file.toLowerCase().endsWith(ext))) {\n continue;\n }\n const filePath = path.join(dirPath, file);\n const relativePath = path.relative(pmRoot, filePath);\n\n parseTasks.push(\n (async () => {\n try {\n const stat = await fs.stat(filePath);\n const mtimeMs = stat.mtimeMs;\n const ctimeMs = stat.ctimeMs;\n const { size } = stat;\n const itemFormat = getItemFormatFromPath(filePath) as ItemFormat;\n\n // Preserve onRead hook semantics even when served from cache, but only\n // when an extension actually observes reads. Surface hook warnings so\n // read-hook failures are not silently hidden.\n if (dispatchReadHooks) {\n for (const warning of await runActiveOnReadHooks({ path: filePath, scope: \"project\" })) {\n appendWarning(warnings, warning);\n }\n }\n\n const cachedEntry = previousEntries[relativePath];\n const metadataCached = cachedEntry !== undefined && statMatches(cachedEntry, mtimeMs, ctimeMs, size);\n const cachedBody = previousBodies[relativePath];\n const bodyCached = cachedBody !== undefined && statMatches(cachedBody, mtimeMs, ctimeMs, size);\n const cachedCollections = previousCollections[relativePath];\n const collectionsCached =\n cachedCollections !== undefined && statMatches(cachedCollections, mtimeMs, ctimeMs, size);\n\n const needRead =\n !metadataCached || (includeBody && !bodyCached) || (includeCollections && !collectionsCached);\n let lightMetadata: ItemMetadata;\n let heavyMetadata: Record<string, unknown> | undefined;\n let bodyLength: number;\n let body: string | undefined;\n\n if (needRead) {\n const raw = await fs.readFile(filePath, \"utf8\");\n const parsed = parseItemDocument(raw, {\n format: itemFormat,\n schema,\n extensionFieldNames,\n onWarning: (w) => appendWarning(warnings, w),\n });\n const split = splitHeavyMetadata(parsed.metadata);\n lightMetadata = metadataCached ? cachedEntry.metadata : split.light;\n bodyLength = metadataCached ? cachedEntry.body_length : parsed.body.length;\n body = includeBody ? parsed.body : undefined;\n if (includeCollections) {\n heavyMetadata = collectionsCached ? cachedCollections.collections : split.heavy;\n }\n if (!metadataCached) {\n metadataMiss = true;\n }\n if (includeBody && !bodyCached) {\n bodyMiss = true;\n }\n if (includeCollections && !collectionsCached) {\n collectionsMiss = true;\n }\n } else {\n lightMetadata = cachedEntry.metadata;\n bodyLength = cachedEntry.body_length;\n body = includeBody ? cachedBody.body : undefined;\n heavyMetadata = includeCollections && cachedCollections ? cachedCollections.collections : undefined;\n }\n\n newEntries[relativePath] = {\n mtime_ms: mtimeMs,\n ctime_ms: ctimeMs,\n size,\n metadata: lightMetadata,\n body_length: bodyLength,\n };\n if (includeBody && body !== undefined) {\n newBodies[relativePath] = { mtime_ms: mtimeMs, ctime_ms: ctimeMs, size, body };\n }\n if (includeCollections && heavyMetadata !== undefined) {\n newCollections[relativePath] = { mtime_ms: mtimeMs, ctime_ms: ctimeMs, size, collections: heavyMetadata };\n }\n\n const metadata = includeCollections ? mergeHeavyMetadata(lightMetadata, heavyMetadata) : lightMetadata;\n const existing = documentsById.get(metadata.id);\n const candidate: CachedDocumentCandidate = {\n metadata,\n body,\n item_format: itemFormat,\n item_path: filePath,\n };\n if (!existing || shouldReplaceCachedDocumentCandidate(existing.itemFormat, itemFormat, preferredFormat)) {\n documentsById.set(metadata.id, { candidate, itemFormat });\n }\n } catch {\n appendWarning(warnings, `item_list_item_read_failed:${folder}/${file}`);\n }\n })(),\n );\n }\n }\n\n await Promise.all(parseTasks);\n\n // Rewrite a cache file only when its contents changed: any re-parsed (missing or\n // stale) entry, or a different set of keys (additions/deletions).\n const metadataDirty = metadataMiss || Object.keys(previousEntries).length !== Object.keys(newEntries).length;\n if (metadataDirty || existingCache === null || existingCache.context_fingerprint !== contextFingerprint) {\n await persistCache(getCachePath(pmRoot), {\n version: CACHE_VERSION,\n context_fingerprint: contextFingerprint,\n entries: newEntries,\n }).catch(() => {});\n }\n\n if (includeBody) {\n const bodyDirty = bodyMiss || Object.keys(previousBodies).length !== Object.keys(newBodies).length;\n if (bodyDirty || existingBodyCache === null || existingBodyCache.context_fingerprint !== contextFingerprint) {\n await persistCache(getBodyCachePath(pmRoot), {\n version: CACHE_VERSION,\n context_fingerprint: contextFingerprint,\n bodies: newBodies,\n }).catch(() => {});\n }\n }\n\n if (includeCollections) {\n const collectionsDirty =\n collectionsMiss || Object.keys(previousCollections).length !== Object.keys(newCollections).length;\n if (\n collectionsDirty ||\n existingCollectionsCache === null ||\n existingCollectionsCache.context_fingerprint !== contextFingerprint\n ) {\n await persistCache(getCollectionsCachePath(pmRoot), {\n version: CACHE_VERSION,\n context_fingerprint: contextFingerprint,\n collections: newCollections,\n }).catch(() => {});\n }\n }\n\n return [...documentsById.values()]\n .sort((left, right) => left.candidate.metadata.id.localeCompare(right.candidate.metadata.id))\n .map((entry) => entry.candidate);\n}\n\n/**\n * Implements list all documents cached for the public runtime surface of this module.\n */\nexport async function listAllDocumentsCached(\n pmRoot: string,\n preferredFormat: ItemFormat | undefined,\n typeToFolder: Record<string, string>,\n warnings: string[] | undefined,\n schema: RuntimeSchemaSettings | undefined,\n): Promise<ItemDocument[]> {\n const candidates = await listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, {\n includeBody: false,\n });\n return candidates.map((candidate) => ({\n metadata: candidate.metadata,\n body: candidate.body ?? \"\",\n }));\n}\n\n/**\n * Light variant of {@link listAllDocumentsCached}: returns metadata WITHOUT the heavy\n * collection fields (comments/notes/learnings/files/tests/test_runs/docs), skipping the\n * large collections cache entirely. Only safe for callers that read just the light\n * scalar/small fields (id/title/status/type/priority/parent/tags/dates/dependencies/…).\n */\nexport async function listAllDocumentsCachedLight(\n pmRoot: string,\n preferredFormat: ItemFormat | undefined,\n typeToFolder: Record<string, string>,\n warnings: string[] | undefined,\n schema: RuntimeSchemaSettings | undefined,\n): Promise<ItemDocument[]> {\n const candidates = await listAllDocumentCandidatesCached(pmRoot, preferredFormat, typeToFolder, warnings, schema, {\n includeBody: false,\n includeCollections: false,\n });\n return candidates.map((candidate) => ({\n metadata: candidate.metadata,\n body: candidate.body ?? \"\",\n }));\n}\n","/**\n * @module core/store/item-store\n *\n * Reads and writes tracker storage with format-aware helpers for Item Store.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n getActiveExtensionRegistrations,\n projectAfterCommandItemSnapshot,\n recordAfterCommandAffectedItem,\n runActiveOnReadHooks,\n runActiveOnWriteHooks,\n runActiveServiceOverride,\n} from \"../extensions/index.js\";\nimport { collectRegisteredItemFieldNames } from \"../extensions/item-fields.js\";\nimport { EMPTY_CANONICAL_DOCUMENT, EXIT_CODE, TYPE_TO_FOLDER } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { levenshteinDistanceWithinLimit } from \"../shared/levenshtein.js\";\nimport { appendHistoryEntry, createHistoryEntry } from \"../history/history.js\";\nimport { enforceHistoryStreamPolicyForItem } from \"../history/history-stream-policy.js\";\nimport { canonicalDocument, parseItemDocument, serializeItemDocument } from \"../item/item-format.js\";\nimport { resolveItemTypeRegistry } from \"../item/type-registry.js\";\nimport { acquireLock } from \"../lock/lock.js\";\nimport { writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { normalizeItemId, normalizeRawItemId } from \"../item/id.js\";\nimport { listAllDocumentCandidatesCached, listAllDocumentsCached, listAllDocumentsCachedLight } from \"./front-matter-cache.js\";\nimport { getHistoryPath, getItemFormatFromPath, getItemPath, ITEM_FILE_EXTENSIONS } from \"./paths.js\";\nimport { resolveGovernanceKnobs } from \"./settings.js\";\nimport { nowIso } from \"../shared/time.js\";\nimport type { ItemDocument, ItemFormat, ItemFrontMatter, ItemType, PmSettings, RuntimeSchemaSettings } from \"../../types/index.js\";\n\n/**\n * Documents the located item payload exchanged by command, SDK, and package integrations.\n */\nexport interface LocatedItem {\n id: string;\n type: ItemType;\n itemPath: string;\n item_format: ItemFormat;\n}\n\nasync function fileExists(targetPath: string): Promise<boolean> {\n try {\n await fs.access(targetPath);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === code;\n}\n\nfunction appendWarning(warnings: string[] | undefined, warning: string): void {\n if (!warnings) {\n return;\n }\n if (!warnings.includes(warning)) {\n warnings.push(warning);\n }\n}\n\nfunction resolveActiveExtensionFieldNames(explicit: readonly string[] | undefined): readonly string[] {\n return explicit ?? collectRegisteredItemFieldNames(getActiveExtensionRegistrations());\n}\n\nfunction resolveItemFormatSearchOrder(preferredFormat?: ItemFormat): ItemFormat[] {\n if (preferredFormat === \"toon\") {\n return [\"toon\", \"json_markdown\"];\n }\n if (preferredFormat === \"json_markdown\") {\n return [\"json_markdown\", \"toon\"];\n }\n return [\"toon\", \"json_markdown\"];\n}\n\n/**\n * Implements locate item for the public runtime surface of this module.\n */\nexport async function locateItem(\n pmRoot: string,\n rawId: string,\n idPrefix = \"pm-\",\n preferredFormat?: ItemFormat,\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n): Promise<LocatedItem | null> {\n const normalizedId = normalizeItemId(rawId, idPrefix);\n const rawNormalizedId = normalizeRawItemId(rawId);\n const candidateIds = normalizedId === rawNormalizedId ? [normalizedId] : [normalizedId, rawNormalizedId];\n const entries = Object.entries(typeToFolder) as Array<[ItemType, string]>;\n const searchOrder = resolveItemFormatSearchOrder(preferredFormat);\n for (const candidateId of candidateIds) {\n for (const [type] of entries) {\n for (const itemFormat of searchOrder) {\n const itemPath = getItemPath(pmRoot, type, candidateId, itemFormat, typeToFolder);\n if (await fileExists(itemPath)) {\n return {\n id: candidateId,\n type,\n itemPath,\n item_format: itemFormat,\n };\n }\n }\n }\n }\n return null;\n}\n\n/**\n * Implements read located item for the public runtime surface of this module.\n */\nexport async function readLocatedItem(\n item: LocatedItem,\n options: { schema?: RuntimeSchemaSettings; extensionFieldNames?: readonly string[]; warnings?: string[] } = {},\n): Promise<{ raw: string; document: ItemDocument }> {\n const raw = await fs.readFile(item.itemPath, \"utf8\");\n await runActiveOnReadHooks({\n path: item.itemPath,\n scope: \"project\",\n });\n const document = parseItemDocument(raw, {\n format: item.item_format,\n schema: options.schema,\n extensionFieldNames: resolveActiveExtensionFieldNames(options.extensionFieldNames),\n onWarning: (warning) => appendWarning(options.warnings, warning),\n });\n return { raw, document };\n}\n\n/**\n * Implements list all front matter for the public runtime surface of this module.\n */\nexport async function listAllFrontMatter(\n pmRoot: string,\n preferredFormat?: ItemFormat,\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n warnings?: string[],\n schema?: RuntimeSchemaSettings,\n): Promise<ItemFrontMatter[]> {\n const documents = await listAllDocumentsCached(pmRoot, preferredFormat, typeToFolder, warnings, schema);\n return documents.map((document) => document.metadata);\n}\n\n/**\n * Light variant of {@link listAllFrontMatter}: returns front-matter WITHOUT the heavy\n * collection fields (comments/notes/learnings/files/tests/test_runs/docs). Skips the\n * large collections cache so the hot list path stays cheap. Only use for callers that\n * read just the light scalar/small fields — see {@link listAllDocumentsCachedLight}.\n */\nexport async function listAllFrontMatterLight(\n pmRoot: string,\n preferredFormat?: ItemFormat,\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n warnings?: string[],\n schema?: RuntimeSchemaSettings,\n): Promise<ItemFrontMatter[]> {\n const documents = await listAllDocumentsCachedLight(pmRoot, preferredFormat, typeToFolder, warnings, schema);\n return documents.map((document) => document.metadata);\n}\n\n/**\n * Implements list all front matter with body for the public runtime surface of this module.\n */\nexport async function listAllFrontMatterWithBody(\n pmRoot: string,\n preferredFormat?: ItemFormat,\n typeToFolder: Record<string, string> = TYPE_TO_FOLDER,\n warnings?: string[],\n schema?: RuntimeSchemaSettings,\n): Promise<Array<ItemFrontMatter & { body: string }>> {\n const candidates = await listAllDocumentCandidatesCached(\n pmRoot,\n preferredFormat,\n typeToFolder,\n warnings,\n schema,\n { includeBody: true },\n );\n return candidates.map((candidate) => ({\n ...candidate.metadata,\n // includeBody:true guarantees candidate bodies are materialized.\n body: candidate.body!,\n }));\n}\n\nasync function listKnownItemIds(\n pmRoot: string,\n typeToFolder: Record<string, string>,\n): Promise<string[]> {\n const folders = new Set(Object.values(typeToFolder));\n const allIds: string[] = [];\n await Promise.all(\n [...folders].map(async (folder) => {\n try {\n const entries = await fs.readdir(path.join(pmRoot, folder));\n for (const entry of entries) {\n for (const ext of ITEM_FILE_EXTENSIONS) {\n if (entry.toLowerCase().endsWith(ext)) {\n allIds.push(entry.slice(0, -ext.length));\n break;\n }\n }\n }\n } catch {\n // ignore missing folders\n }\n }),\n );\n return allIds;\n}\n\nasync function buildDidYouMeanSuggestions(\n pmRoot: string,\n badId: string,\n idPrefix: string,\n typeToFolder: Record<string, string>,\n): Promise<string[]> {\n const normalized = normalizeItemId(badId, idPrefix);\n const ids = await listKnownItemIds(pmRoot, typeToFolder);\n if (ids.length === 0) return [];\n const limit = Math.max(3, Math.floor(normalized.length / 2));\n const scored = ids\n .map((id) => ({ id, distance: levenshteinDistanceWithinLimit(id, normalized, limit) }))\n .filter((entry): entry is { id: string; distance: number } => entry.distance !== null)\n .sort((left, right) => left.distance - right.distance)\n .slice(0, 3)\n .map((entry) => entry.id);\n return scored;\n}\n\n/**\n * Implements build item not found error for the public runtime surface of this module.\n */\nexport async function buildItemNotFoundError(\n pmRoot: string,\n badId: string,\n idPrefix: string,\n typeToFolder: Record<string, string>,\n): Promise<PmCliError> {\n const suggestions = await buildDidYouMeanSuggestions(pmRoot, badId, idPrefix, typeToFolder);\n const nextSteps: string[] = [\"Confirm the active --path/PM_PATH scope, then retry with a valid id.\"];\n if (suggestions.length > 0) {\n nextSteps.unshift(`Did you mean one of: ${suggestions.join(\", \")}?`);\n }\n return new PmCliError(`Item ${badId} not found`, EXIT_CODE.NOT_FOUND, { nextSteps });\n}\n\nfunction bypassesAssigneeConflict(\n op: string,\n bypassAssigneeConflict?: boolean,\n): boolean {\n return (\n op === \"claim\" ||\n (bypassAssigneeConflict === true &&\n (op === \"comment_add\" ||\n op === \"comment_edit\" ||\n op === \"comment_delete\" ||\n op === \"note_add\" ||\n op === \"learning_add\" ||\n op === \"release\" ||\n op === \"update\" ||\n op === \"update_audit\"))\n );\n}\n\nasync function prepareLockedItem(params: {\n pmRoot: string;\n settings: PmSettings;\n id: string;\n op: string;\n author: string;\n force?: boolean;\n bypassAssigneeConflict?: boolean;\n extensionFieldNames?: readonly string[];\n typeToFolder?: Record<string, string>;\n}): Promise<{\n typeToFolder: Record<string, string>;\n located: LocatedItem;\n originalRaw: string;\n document: ItemDocument;\n warnings: string[];\n releaseLock: () => Promise<void>;\n}> {\n const typeToFolder =\n params.typeToFolder ??\n resolveItemTypeRegistry(params.settings, getActiveExtensionRegistrations())\n .type_to_folder;\n const located = await locateItem(\n params.pmRoot,\n params.id,\n params.settings.id_prefix,\n params.settings.item_format,\n typeToFolder,\n );\n if (!located) {\n throw await buildItemNotFoundError(\n params.pmRoot,\n params.id,\n params.settings.id_prefix,\n typeToFolder,\n );\n }\n\n const releaseLock = await acquireLock(\n params.pmRoot,\n located.id,\n params.settings.locks.ttl_seconds,\n params.author,\n Boolean(params.force),\n params.settings.governance.force_required_for_stale_lock,\n );\n\n try {\n const warnings: string[] = [];\n const { raw: originalRaw, document } = await readLocatedItem(located, {\n schema: params.settings.schema,\n extensionFieldNames: params.extensionFieldNames,\n warnings,\n });\n\n const assigned = document.metadata.assignee?.trim();\n const governance = resolveGovernanceKnobs(params.settings);\n const hasOwnershipConflict =\n assigned &&\n assigned !== params.author &&\n !params.force &&\n !bypassesAssigneeConflict(params.op, params.bypassAssigneeConflict);\n if (hasOwnershipConflict) {\n if (governance.ownership_enforcement === \"strict\") {\n throw new PmCliError(\n `Item ${located.id} is assigned to ${assigned}. Use --force to override.`,\n EXIT_CODE.CONFLICT,\n );\n }\n if (governance.ownership_enforcement === \"warn\") {\n warnings.push(\n `ownership_warning:assignee_conflict:${located.id}:${assigned}`,\n );\n }\n }\n\n return {\n typeToFolder,\n located,\n originalRaw,\n document,\n warnings,\n releaseLock,\n };\n } catch (error: unknown) {\n await releaseLock();\n throw error;\n }\n}\n\n/**\n * Implements mutate item for the public runtime surface of this module.\n */\nexport async function mutateItem(params: {\n pmRoot: string;\n settings: PmSettings;\n id: string;\n op: string;\n author: string;\n message?: string;\n force?: boolean;\n bypassAssigneeConflict?: boolean;\n skipNoop?: boolean;\n extensionFieldNames?: readonly string[];\n typeToFolder?: Record<string, string>;\n mutate: (document: ItemDocument) => {\n changedFields: string[];\n warnings?: string[];\n };\n}): Promise<{\n item: ItemFrontMatter;\n body: string;\n changedFields: string[];\n warnings: string[];\n}> {\n const prepared = await prepareLockedItem({\n pmRoot: params.pmRoot,\n settings: params.settings,\n id: params.id,\n op: params.op,\n author: params.author,\n force: params.force,\n bypassAssigneeConflict: params.bypassAssigneeConflict,\n extensionFieldNames: params.extensionFieldNames,\n typeToFolder: params.typeToFolder,\n });\n const {\n typeToFolder,\n located,\n originalRaw,\n document,\n warnings: parseWarnings,\n releaseLock,\n } = prepared;\n\n try {\n const beforeDocument = canonicalDocument(document, {\n schema: params.settings.schema,\n extensionFieldNames: params.extensionFieldNames,\n });\n const mutableDocument = canonicalDocument(structuredClone(document), {\n schema: params.settings.schema,\n extensionFieldNames: params.extensionFieldNames,\n });\n const mutation = params.mutate(mutableDocument);\n if (params.skipNoop === true && mutation.changedFields.length === 0) {\n return {\n item: beforeDocument.metadata,\n body: beforeDocument.body,\n changedFields: [],\n warnings: [...parseWarnings, ...(mutation.warnings ?? [])],\n };\n }\n const historyPolicy = await enforceHistoryStreamPolicyForItem({\n pmRoot: params.pmRoot,\n settings: params.settings,\n itemId: located.id,\n commandLabel: params.op,\n });\n mutableDocument.metadata.updated_at = nowIso();\n const afterDocument = canonicalDocument(mutableDocument, {\n schema: params.settings.schema,\n extensionFieldNames: params.extensionFieldNames,\n });\n const targetItemFormat: ItemFormat = \"toon\";\n const serializedAfter = serializeItemDocument(afterDocument, {\n format: targetItemFormat,\n schema: params.settings.schema,\n extensionFieldNames: params.extensionFieldNames,\n });\n const targetItemPath = getItemPath(\n params.pmRoot,\n afterDocument.metadata.type,\n located.id,\n targetItemFormat,\n typeToFolder,\n );\n const historyPath = getHistoryPath(params.pmRoot, located.id);\n const serviceWriteOverride = await runActiveServiceOverride(\"item_store_write\", {\n op: params.op,\n pm_root: params.pmRoot,\n item_id: located.id,\n source_item_path: located.itemPath,\n target_item_path: targetItemPath,\n history_path: historyPath,\n item_format: targetItemFormat,\n before: beforeDocument,\n after: afterDocument,\n contents: serializedAfter,\n });\n let effectiveTargetItemPath = targetItemPath;\n let effectiveSerializedAfter = serializedAfter;\n let skipItemWrite = false;\n if (\n serviceWriteOverride.handled &&\n typeof serviceWriteOverride.result === \"object\" &&\n serviceWriteOverride.result !== null\n ) {\n const overrideRecord = serviceWriteOverride.result as {\n target_item_path?: unknown;\n contents?: unknown;\n skip_write?: unknown;\n };\n if (typeof overrideRecord.target_item_path === \"string\" && overrideRecord.target_item_path.trim().length > 0) {\n effectiveTargetItemPath = overrideRecord.target_item_path;\n }\n if (typeof overrideRecord.contents === \"string\") {\n effectiveSerializedAfter = overrideRecord.contents;\n }\n if (overrideRecord.skip_write === true) {\n skipItemWrite = true;\n }\n }\n\n if (!skipItemWrite) {\n await writeFileAtomic(effectiveTargetItemPath, effectiveSerializedAfter);\n }\n if (!skipItemWrite && effectiveTargetItemPath !== located.itemPath) {\n await fs.rm(located.itemPath);\n }\n const entry = createHistoryEntry({\n nowIso: afterDocument.metadata.updated_at,\n author: params.author,\n op: params.op,\n before: beforeDocument,\n after: afterDocument,\n message: params.message,\n });\n\n try {\n await appendHistoryEntry(historyPath, entry);\n } catch (error: unknown) {\n if (!skipItemWrite && effectiveTargetItemPath !== located.itemPath) {\n await writeFileAtomic(located.itemPath, originalRaw);\n await fs.rm(effectiveTargetItemPath, { force: true });\n } else if (!skipItemWrite) {\n await writeFileAtomic(located.itemPath, originalRaw);\n }\n throw error;\n }\n const hookWarnings = [\n ...(await runActiveOnWriteHooks({\n path: effectiveTargetItemPath,\n scope: \"project\",\n op: params.op,\n item_id: afterDocument.metadata.id,\n item_type: afterDocument.metadata.type,\n before: beforeDocument,\n after: afterDocument,\n changed_fields: mutation.changedFields,\n })),\n ...(await runActiveOnWriteHooks({\n path: historyPath,\n scope: \"project\",\n op: `${params.op}:history`,\n item_id: afterDocument.metadata.id,\n item_type: afterDocument.metadata.type,\n before: beforeDocument,\n after: afterDocument,\n changed_fields: mutation.changedFields,\n })),\n ];\n\n recordAfterCommandAffectedItem({\n id: afterDocument.metadata.id,\n op: params.op,\n item_type: afterDocument.metadata.type,\n previous_status: beforeDocument.metadata.status,\n status: afterDocument.metadata.status,\n previous: projectAfterCommandItemSnapshot(beforeDocument.metadata, mutation.changedFields),\n current: projectAfterCommandItemSnapshot(afterDocument.metadata, mutation.changedFields),\n changed_fields: mutation.changedFields,\n });\n\n return {\n item: afterDocument.metadata,\n body: afterDocument.body,\n changedFields: mutation.changedFields,\n warnings: [\n ...parseWarnings,\n ...(mutation.warnings ?? []),\n ...historyPolicy.warnings,\n ...serviceWriteOverride.warnings,\n ...hookWarnings,\n ],\n };\n } finally {\n await releaseLock();\n }\n}\n\nexport const itemStoreTestOnly = {\n appendWarning,\n bypassesAssigneeConflict,\n buildDidYouMeanSuggestions,\n isErrno,\n};\n\n/**\n * Implements delete item for the public runtime surface of this module.\n */\nexport async function deleteItem(params: {\n pmRoot: string;\n settings: PmSettings;\n id: string;\n author: string;\n message?: string;\n force?: boolean;\n dryRun?: boolean;\n}): Promise<{ item: ItemFrontMatter; changedFields: string[]; warnings: string[]; targetPath?: string }> {\n const prepared = await prepareLockedItem({\n pmRoot: params.pmRoot,\n settings: params.settings,\n id: params.id,\n op: \"delete\",\n author: params.author,\n force: params.force,\n });\n const { located, originalRaw, document, warnings: parseWarnings, releaseLock } = prepared;\n\n try {\n const historyPolicy = await enforceHistoryStreamPolicyForItem({\n pmRoot: params.pmRoot,\n settings: params.settings,\n itemId: located.id,\n commandLabel: \"delete\",\n });\n\n const beforeDocument = canonicalDocument(document, { schema: params.settings.schema });\n const deletionTimestamp = nowIso();\n const tombstoneDocument = EMPTY_CANONICAL_DOCUMENT as unknown as ItemDocument;\n const historyEntry = createHistoryEntry({\n nowIso: deletionTimestamp,\n author: params.author,\n op: \"delete\",\n before: beforeDocument,\n after: tombstoneDocument,\n message: params.message,\n });\n const historyPath = getHistoryPath(params.pmRoot, located.id);\n const serviceDeleteOverride = await runActiveServiceOverride(\"item_store_delete\", {\n op: \"delete\",\n pm_root: params.pmRoot,\n item_id: located.id,\n item_path: located.itemPath,\n history_path: historyPath,\n before: beforeDocument,\n });\n let effectiveItemPath = located.itemPath;\n let skipDelete = false;\n if (\n serviceDeleteOverride.handled &&\n typeof serviceDeleteOverride.result === \"object\" &&\n serviceDeleteOverride.result !== null\n ) {\n const overrideRecord = serviceDeleteOverride.result as {\n item_path?: unknown;\n skip_delete?: unknown;\n };\n if (typeof overrideRecord.item_path === \"string\" && overrideRecord.item_path.trim().length > 0) {\n effectiveItemPath = overrideRecord.item_path;\n }\n if (overrideRecord.skip_delete === true) {\n skipDelete = true;\n }\n }\n\n if (params.dryRun === true) {\n return {\n item: beforeDocument.metadata,\n changedFields: [\"deleted\"],\n targetPath: effectiveItemPath,\n warnings: [...parseWarnings, ...historyPolicy.warnings, ...serviceDeleteOverride.warnings],\n };\n }\n\n if (!skipDelete) {\n await fs.rm(effectiveItemPath);\n }\n try {\n await appendHistoryEntry(historyPath, historyEntry);\n } catch (error: unknown) {\n if (!skipDelete) {\n await writeFileAtomic(effectiveItemPath, originalRaw);\n }\n throw error;\n }\n\n const hookWarnings = [\n ...(await runActiveOnWriteHooks({\n path: effectiveItemPath,\n scope: \"project\",\n op: \"delete\",\n item_id: beforeDocument.metadata.id,\n item_type: beforeDocument.metadata.type,\n before: beforeDocument,\n after: tombstoneDocument,\n changed_fields: [\"deleted\"],\n })),\n ...(await runActiveOnWriteHooks({\n path: historyPath,\n scope: \"project\",\n op: \"delete:history\",\n item_id: beforeDocument.metadata.id,\n item_type: beforeDocument.metadata.type,\n before: beforeDocument,\n after: tombstoneDocument,\n changed_fields: [\"deleted\"],\n })),\n ];\n\n recordAfterCommandAffectedItem({\n id: beforeDocument.metadata.id,\n op: \"delete\",\n item_type: beforeDocument.metadata.type,\n previous_status: beforeDocument.metadata.status,\n previous: projectAfterCommandItemSnapshot(beforeDocument.metadata, Object.keys(beforeDocument.metadata)),\n changed_fields: [\"deleted\"],\n });\n\n return {\n item: beforeDocument.metadata,\n changedFields: [\"deleted\"],\n warnings: [...parseWarnings, ...historyPolicy.warnings, ...serviceDeleteOverride.warnings, ...hookWarnings],\n };\n } finally {\n await releaseLock();\n }\n}\n"],"names":["path","next","fs","path","fs","path","path","path","fs","path","path","fs","fs","path","fs","appendWarning","resolveActiveExtensionFieldNames","fs","path","fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAM,4BAA4B,IAAI,IAAI,sBAAsB;AAEhE,SAAS,mBAAmB,OAAc;AACxC,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;EACT;AACA,QAAM,aAAa,MAAM,KAAI;AAC7B,SAAO,WAAW,SAAS,IAAI,aAAa;AAC9C;AAEA,SAAS,mBAAmB,OAAc;AACxC,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;EACT;AACA,SAAO,uBAAuB,KAAK;AACrC;AAEA,SAAS,gBAAmB,OAAQ;AAClC,MAAI;AACF,WAAO,gBAAgB,KAAK;EAC9B,QAAQ;AACN,WAAO;EACT;AACF;AAEA,SAAS,qBAAqB,KAAW;AACvC,QAAM,UAAU,IAAI,KAAI;AACxB,QAAM,iBAAiB,QAAQ,QAAQ,GAAG;AAC1C,MAAI,kBAAkB,GAAG;AACvB,UAAM,IAAI,WAAW,yDAAyD,GAAG,IAAI,UAAU,KAAK;EACtG;AAGA,QAAM,MAAM,QAAQ,MAAM,GAAG,cAAc,EAAE,KAAI;AACjD,QAAM,QAAQ,QAAQ,MAAM,iBAAiB,CAAC;AAC9C,SAAO,EAAE,KAAK,MAAK;AACrB;AAEA,SAAS,oBAAoB,KAAa,WAAmB,cAAgC;AAC3F,M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