@unbrained/pm-cli 2026.7.20 → 2026.7.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (421) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +11 -0
  3. package/dist/cli/commander-usage.d.ts +1 -1
  4. package/dist/cli/commander-usage.js +5 -5
  5. package/dist/cli/commander-usage.js.map +1 -1
  6. package/dist/cli/commands/completion.js +13 -5
  7. package/dist/cli/commands/completion.js.map +1 -1
  8. package/dist/cli/commands/contracts.js +4 -3
  9. package/dist/cli/commands/contracts.js.map +1 -1
  10. package/dist/cli/error-guidance.d.ts +2 -0
  11. package/dist/cli/error-guidance.js +7 -2
  12. package/dist/cli/error-guidance.js.map +1 -1
  13. package/dist/cli/main.d.ts +1 -5
  14. package/dist/cli/main.js +12 -50
  15. package/dist/cli/main.js.map +1 -1
  16. package/dist/cli/register-list-query.js +13 -3
  17. package/dist/cli/register-list-query.js.map +1 -1
  18. package/dist/cli/register-mutation.js +45 -3
  19. package/dist/cli/register-mutation.js.map +1 -1
  20. package/dist/cli/register-structured-mutation.d.ts +14 -0
  21. package/dist/cli/register-structured-mutation.js +62 -0
  22. package/dist/cli/register-structured-mutation.js.map +1 -0
  23. package/dist/cli/registration-helpers.js +5 -3
  24. package/dist/cli/registration-helpers.js.map +1 -1
  25. package/dist/cli-bundle/bundle-manifest.json +280 -296
  26. package/dist/cli-bundle/chunks/{append-E6V54WOQ.js → append-7OVFYR3C.js} +3 -3
  27. package/dist/cli-bundle/chunks/{append-NNJ3EFIT.js → append-DFETHAZL.js} +3 -3
  28. package/dist/cli-bundle/chunks/{chunk-C3KD7U3T.js → chunk-2L6ZP22J.js} +241 -10
  29. package/dist/cli-bundle/chunks/chunk-2L6ZP22J.js.map +7 -0
  30. package/dist/cli-bundle/chunks/{chunk-KZEANWJS.js → chunk-4PUUNQDV.js} +98 -30
  31. package/dist/cli-bundle/chunks/chunk-4PUUNQDV.js.map +7 -0
  32. package/dist/cli-bundle/chunks/{chunk-RDV4ZFYS.js → chunk-4QOB7L7I.js} +7 -9
  33. package/dist/cli-bundle/chunks/{chunk-RDV4ZFYS.js.map → chunk-4QOB7L7I.js.map} +1 -1
  34. package/dist/cli-bundle/chunks/{chunk-3LPFHE3P.js → chunk-4QSQ6XDK.js} +62 -20
  35. package/dist/cli-bundle/chunks/chunk-4QSQ6XDK.js.map +1 -0
  36. package/dist/cli-bundle/chunks/{chunk-QJKL5PHS.js → chunk-7656MAUL.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-3AO5VSDR.js → chunk-7RW4JCU2.js} +328 -6
  38. package/dist/cli-bundle/chunks/chunk-7RW4JCU2.js.map +7 -0
  39. package/dist/cli-bundle/chunks/{chunk-X6K5XTTN.js → chunk-7W2UAXXT.js} +5 -5
  40. package/dist/cli-bundle/chunks/{chunk-SSKOQNMS.js → chunk-ABWCF646.js} +9 -11
  41. package/dist/cli-bundle/chunks/{chunk-SSKOQNMS.js.map → chunk-ABWCF646.js.map} +1 -1
  42. package/dist/cli-bundle/chunks/{chunk-WVA4DVNV.js → chunk-ADBTSVGK.js} +71 -33
  43. package/dist/cli-bundle/chunks/chunk-ADBTSVGK.js.map +7 -0
  44. package/dist/cli-bundle/chunks/{chunk-J4FBIFU6.js → chunk-AELMUANP.js} +12 -6
  45. package/dist/cli-bundle/chunks/chunk-AELMUANP.js.map +1 -0
  46. package/dist/cli-bundle/chunks/{chunk-4F6BWJ4J.js → chunk-AMJPSANK.js} +57 -36
  47. package/dist/cli-bundle/chunks/chunk-AMJPSANK.js.map +7 -0
  48. package/dist/cli-bundle/chunks/{chunk-6VIJ7UA5.js → chunk-AS4SAZ5R.js} +850 -819
  49. package/dist/cli-bundle/chunks/chunk-AS4SAZ5R.js.map +7 -0
  50. package/dist/cli-bundle/chunks/{chunk-SG74J6MV.js → chunk-ATBCUC7Y.js} +574 -5
  51. package/dist/cli-bundle/chunks/chunk-ATBCUC7Y.js.map +1 -0
  52. package/dist/cli-bundle/chunks/{chunk-5OK4UGFV.js → chunk-BXNDKOR2.js} +3 -3
  53. package/dist/cli-bundle/chunks/{chunk-KSPWRNVP.js → chunk-CPX275C6.js} +2 -2
  54. package/dist/cli-bundle/chunks/{chunk-JH2ZSLO3.js → chunk-DZRV2OPA.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-L7BH7IWU.js → chunk-E5XMKOSB.js} +2 -2
  56. package/dist/cli-bundle/chunks/{chunk-CQTQKUUV.js → chunk-EWJWSNRU.js} +3 -3
  57. package/dist/cli-bundle/chunks/{chunk-DAQ45GCS.js → chunk-F2LBF7XJ.js} +22 -15
  58. package/dist/cli-bundle/chunks/chunk-F2LBF7XJ.js.map +7 -0
  59. package/dist/cli-bundle/chunks/{chunk-6XMUURSS.js → chunk-FJIFFBJX.js} +64 -33
  60. package/dist/cli-bundle/chunks/chunk-FJIFFBJX.js.map +1 -0
  61. package/dist/cli-bundle/chunks/{chunk-E7ICD63T.js → chunk-FO6OSVEN.js} +4 -6
  62. package/dist/cli-bundle/chunks/{chunk-E7ICD63T.js.map → chunk-FO6OSVEN.js.map} +1 -1
  63. package/dist/cli-bundle/chunks/{chunk-3MCTMJXI.js → chunk-FPBMLYPI.js} +2 -2
  64. package/dist/cli-bundle/chunks/{chunk-UZDQXNUB.js → chunk-FSE2IKJQ.js} +46 -5
  65. package/dist/cli-bundle/chunks/chunk-FSE2IKJQ.js.map +1 -0
  66. package/dist/cli-bundle/chunks/{chunk-IX677TRO.js → chunk-GKX4NJ7U.js} +8 -10
  67. package/dist/cli-bundle/chunks/{chunk-IX677TRO.js.map → chunk-GKX4NJ7U.js.map} +1 -1
  68. package/dist/cli-bundle/chunks/{chunk-DVDBQA3B.js → chunk-GTK4DTEW.js} +5 -5
  69. package/dist/cli-bundle/chunks/chunk-H7EAER5L.js +974 -0
  70. package/dist/cli-bundle/chunks/chunk-H7EAER5L.js.map +1 -0
  71. package/dist/cli-bundle/chunks/{chunk-5UX66S6U.js → chunk-ICDAQ4TD.js} +316 -8
  72. package/dist/cli-bundle/chunks/chunk-ICDAQ4TD.js.map +1 -0
  73. package/dist/cli-bundle/chunks/{chunk-YQQNAKW3.js → chunk-JFD5LPMI.js} +6 -8
  74. package/dist/cli-bundle/chunks/{chunk-YQQNAKW3.js.map → chunk-JFD5LPMI.js.map} +1 -1
  75. package/dist/cli-bundle/chunks/{chunk-QANSTTC7.js → chunk-JXCW2TI2.js} +6 -8
  76. package/dist/cli-bundle/chunks/{chunk-QANSTTC7.js.map → chunk-JXCW2TI2.js.map} +1 -1
  77. package/dist/cli-bundle/chunks/{chunk-GSJSM5BJ.js → chunk-K36WV5J6.js} +76 -13
  78. package/dist/cli-bundle/chunks/chunk-K36WV5J6.js.map +1 -0
  79. package/dist/cli-bundle/chunks/{chunk-GVI6FAFG.js → chunk-K55VMLSS.js} +7 -5
  80. package/dist/cli-bundle/chunks/chunk-K55VMLSS.js.map +7 -0
  81. package/dist/cli-bundle/chunks/{chunk-GIQSU6S2.js → chunk-KBLZ3AA5.js} +2 -2
  82. package/dist/cli-bundle/chunks/{chunk-XJF7CDNH.js → chunk-KH44WBAT.js} +2 -2
  83. package/dist/cli-bundle/chunks/{chunk-GV2262OF.js → chunk-LAV26CQG.js} +2 -2
  84. package/dist/cli-bundle/chunks/{chunk-VDO2JMD4.js → chunk-LVC72YRD.js} +2 -2
  85. package/dist/cli-bundle/chunks/{chunk-3VY6MIEO.js → chunk-LZYP423P.js} +35 -6
  86. package/dist/cli-bundle/chunks/chunk-LZYP423P.js.map +7 -0
  87. package/dist/cli-bundle/chunks/{chunk-ZYPFOO3L.js → chunk-MATHDCGG.js} +3 -3
  88. package/dist/cli-bundle/chunks/{chunk-OV7MSW3I.js → chunk-MWQ2HC2A.js} +99 -31
  89. package/dist/cli-bundle/chunks/chunk-MWQ2HC2A.js.map +1 -0
  90. package/dist/cli-bundle/chunks/{chunk-NHT3F4WZ.js → chunk-NUF7ROFH.js} +840 -816
  91. package/dist/cli-bundle/chunks/chunk-NUF7ROFH.js.map +1 -0
  92. package/dist/cli-bundle/chunks/{chunk-AOEOYL3S.js → chunk-O4BCOJTZ.js} +3 -3
  93. package/dist/cli-bundle/chunks/{chunk-RJO3YAFM.js → chunk-OCUBRA6D.js} +2 -2
  94. package/dist/cli-bundle/chunks/{chunk-5IZJWSDB.js → chunk-OG5DVFMA.js} +22 -15
  95. package/dist/cli-bundle/chunks/chunk-OG5DVFMA.js.map +1 -0
  96. package/dist/cli-bundle/chunks/{chunk-I577UHC7.js → chunk-OR42SO64.js} +2 -2
  97. package/dist/cli-bundle/chunks/{chunk-ZOJ3LR7O.js → chunk-OY7DMU5P.js} +2 -2
  98. package/dist/cli-bundle/chunks/{chunk-HEWM6CEN.js → chunk-P7MTHPJQ.js} +50 -9
  99. package/dist/cli-bundle/chunks/chunk-P7MTHPJQ.js.map +7 -0
  100. package/dist/cli-bundle/chunks/{chunk-2BO4CA46.js → chunk-PFNHX655.js} +236 -12
  101. package/dist/cli-bundle/chunks/{chunk-2BO4CA46.js.map → chunk-PFNHX655.js.map} +1 -1
  102. package/dist/cli-bundle/chunks/{chunk-ZV2NTVMJ.js → chunk-PONKZPCJ.js} +2 -2
  103. package/dist/cli-bundle/chunks/{chunk-THAOZG4U.js → chunk-PQSEQD6E.js} +8 -6
  104. package/dist/cli-bundle/chunks/chunk-PQSEQD6E.js.map +1 -0
  105. package/dist/cli-bundle/chunks/chunk-PWDEHT3L.js +991 -0
  106. package/dist/cli-bundle/chunks/chunk-PWDEHT3L.js.map +7 -0
  107. package/dist/cli-bundle/chunks/{chunk-UX6SSO2I.js → chunk-PZC2FUOQ.js} +2 -2
  108. package/dist/cli-bundle/chunks/{chunk-WUVEBQW6.js → chunk-QG4GFLQ6.js} +3 -5
  109. package/dist/cli-bundle/chunks/{chunk-WUVEBQW6.js.map → chunk-QG4GFLQ6.js.map} +1 -1
  110. package/dist/cli-bundle/chunks/{chunk-VQIHNHMJ.js → chunk-QIH77CAG.js} +2 -2
  111. package/dist/cli-bundle/chunks/{chunk-R3EWPG4A.js → chunk-QJIKE24M.js} +2 -2
  112. package/dist/cli-bundle/chunks/{chunk-QLZ643FM.js → chunk-QOOTOD3W.js} +10 -12
  113. package/dist/cli-bundle/chunks/{chunk-QLZ643FM.js.map → chunk-QOOTOD3W.js.map} +1 -1
  114. package/dist/cli-bundle/chunks/{chunk-MYSS5H2A.js → chunk-R3P6FZJW.js} +5 -7
  115. package/dist/cli-bundle/chunks/{chunk-MYSS5H2A.js.map → chunk-R3P6FZJW.js.map} +1 -1
  116. package/dist/cli-bundle/chunks/{chunk-G3COA6GS.js → chunk-RNPZYNHS.js} +56 -35
  117. package/dist/cli-bundle/chunks/chunk-RNPZYNHS.js.map +1 -0
  118. package/dist/cli-bundle/chunks/{chunk-T44FMVRL.js → chunk-RPESLSO5.js} +62 -20
  119. package/dist/cli-bundle/chunks/chunk-RPESLSO5.js.map +7 -0
  120. package/dist/cli-bundle/chunks/{chunk-INSTSQNZ.js → chunk-SY4SFZSD.js} +595 -3
  121. package/dist/cli-bundle/chunks/chunk-SY4SFZSD.js.map +7 -0
  122. package/dist/cli-bundle/chunks/{chunk-HB3P4M52.js → chunk-TRSHFPRZ.js} +2 -2
  123. package/dist/cli-bundle/chunks/{chunk-HRW7GF6T.js → chunk-UCBDQI5E.js} +2 -2
  124. package/dist/cli-bundle/chunks/{chunk-4U4Z6AHI.js → chunk-V22ZPOKN.js} +2 -2
  125. package/dist/cli-bundle/chunks/{chunk-JM6YAXTR.js → chunk-VHXHVTUU.js} +2 -2
  126. package/dist/cli-bundle/chunks/{chunk-LPEYZRUR.js → chunk-VJQG4BIM.js} +35 -6
  127. package/dist/cli-bundle/chunks/chunk-VJQG4BIM.js.map +1 -0
  128. package/dist/cli-bundle/chunks/{chunk-D6NXDNP3.js → chunk-VLRGDBLY.js} +2 -2
  129. package/dist/cli-bundle/chunks/{chunk-JAPE62Y5.js → chunk-VNTCM3VW.js} +3 -3
  130. package/dist/cli-bundle/chunks/{chunk-FDHPAVVB.js → chunk-VXOOB6YX.js} +2 -2
  131. package/dist/cli-bundle/chunks/{chunk-GFQP7HAZ.js → chunk-VZIZB6QH.js} +3 -5
  132. package/dist/cli-bundle/chunks/{chunk-GFQP7HAZ.js.map → chunk-VZIZB6QH.js.map} +1 -1
  133. package/dist/cli-bundle/chunks/{chunk-HQ3SB4CN.js → chunk-X3W65QK3.js} +2 -2
  134. package/dist/cli-bundle/chunks/{chunk-RZJLNXFG.js → chunk-XJTABV3X.js} +3 -3
  135. package/dist/cli-bundle/chunks/{chunk-GVT754PX.js → chunk-YCIUJJOD.js} +11 -5
  136. package/dist/cli-bundle/chunks/chunk-YCIUJJOD.js.map +7 -0
  137. package/dist/cli-bundle/chunks/{chunk-IJNK6WW2.js → chunk-Z75ONV25.js} +75 -12
  138. package/dist/cli-bundle/chunks/chunk-Z75ONV25.js.map +7 -0
  139. package/dist/cli-bundle/chunks/{chunk-4L23AGQ7.js → chunk-Z7VWXXJM.js} +5 -7
  140. package/dist/cli-bundle/chunks/{chunk-4L23AGQ7.js.map → chunk-Z7VWXXJM.js.map} +1 -1
  141. package/dist/cli-bundle/chunks/{chunk-YBT7O4KT.js → chunk-ZTVA4KLN.js} +4 -6
  142. package/dist/cli-bundle/chunks/{chunk-YBT7O4KT.js.map → chunk-ZTVA4KLN.js.map} +1 -1
  143. package/dist/cli-bundle/chunks/{chunk-TYHJDFYW.js → chunk-ZVZGXPQ5.js} +2 -2
  144. package/dist/cli-bundle/chunks/{close-many-SDA426VT.js → close-many-5RZXVN4J.js} +5 -6
  145. package/dist/cli-bundle/chunks/{close-many-UTZANOCQ.js → close-many-RZVTUGBG.js} +5 -6
  146. package/dist/cli-bundle/chunks/{comments-LZN6FXXC.js → comments-TPU7QRBL.js} +4 -4
  147. package/dist/cli-bundle/chunks/{comments-VBQ345ND.js → comments-Z4KV6FU3.js} +4 -4
  148. package/dist/cli-bundle/chunks/{create-GG4RBCGC.js → create-EIFBIVNQ.js} +6 -6
  149. package/dist/cli-bundle/chunks/{create-JBC5KUW6.js → create-RGSPN5GD.js} +6 -6
  150. package/dist/cli-bundle/chunks/{deps-FI4O6NQS.js → deps-UH5EQQUY.js} +3 -3
  151. package/dist/cli-bundle/chunks/{deps-DELOO4TL.js → deps-YG7UF3VR.js} +3 -3
  152. package/dist/cli-bundle/chunks/{docs-6Z2MP526.js → docs-G32TK6XS.js} +4 -4
  153. package/dist/cli-bundle/chunks/{docs-2UYBP5D6.js → docs-JWWNRC27.js} +4 -4
  154. package/dist/cli-bundle/chunks/{files-HKEAN5MA.js → files-3H32UQ4K.js} +4 -4
  155. package/dist/cli-bundle/chunks/{files-HEUGSJZL.js → files-4ALMCSKB.js} +4 -4
  156. package/dist/cli-bundle/chunks/{history-compact-7NDVP3PT.js → history-compact-77BT2LUB.js} +3 -4
  157. package/dist/cli-bundle/chunks/{history-compact-65YVN5DB.js → history-compact-VCKGTX64.js} +3 -4
  158. package/dist/cli-bundle/chunks/{history-redact-7YBL4XSG.js → history-redact-LJPZPNFA.js} +2 -3
  159. package/dist/cli-bundle/chunks/{history-redact-IZGNJBU4.js → history-redact-PWTTJ3XS.js} +2 -3
  160. package/dist/cli-bundle/chunks/{history-repair-7M4PYQUH.js → history-repair-I7CBNCV3.js} +5 -6
  161. package/dist/cli-bundle/chunks/{history-repair-GNGETJLI.js → history-repair-YTDZRK5E.js} +5 -6
  162. package/dist/cli-bundle/chunks/{learnings-3YXDRWFT.js → learnings-CYNOICKR.js} +4 -4
  163. package/dist/cli-bundle/chunks/{learnings-ALC6IMNL.js → learnings-KTYW3AL7.js} +4 -4
  164. package/dist/cli-bundle/chunks/{notes-7JMLQ447.js → notes-FGO63FXL.js} +4 -4
  165. package/dist/cli-bundle/chunks/{notes-JFCLTC5C.js → notes-ZERD3KB2.js} +4 -4
  166. package/dist/cli-bundle/chunks/{plan-T3XB3WTK.js → plan-OFJUBIM5.js} +7 -7
  167. package/dist/cli-bundle/chunks/{plan-KOIPWVOZ.js → plan-SGCDDTYR.js} +7 -7
  168. package/dist/cli-bundle/chunks/{profile-OILJHKUW.js → profile-3THJPIQY.js} +4 -5
  169. package/dist/cli-bundle/chunks/{profile-RJXA7PGS.js → profile-XEZAMMBW.js} +4 -5
  170. package/dist/cli-bundle/chunks/{register-list-query-CFVG75P3.js → register-list-query-BR435Q2H.js} +19 -16
  171. package/dist/cli-bundle/chunks/register-list-query-BR435Q2H.js.map +1 -0
  172. package/dist/cli-bundle/chunks/{register-list-query-E7UVY4TN.js → register-list-query-RWTWLOBE.js} +18 -15
  173. package/dist/cli-bundle/chunks/register-list-query-RWTWLOBE.js.map +7 -0
  174. package/dist/cli-bundle/chunks/{register-mutation-IQ55E25C.js → register-mutation-HLWC2WNP.js} +167 -31
  175. package/dist/cli-bundle/chunks/register-mutation-HLWC2WNP.js.map +1 -0
  176. package/dist/cli-bundle/chunks/{register-mutation-4VJTXBZW.js → register-mutation-ZJX5AZM5.js} +173 -30
  177. package/dist/cli-bundle/chunks/register-mutation-ZJX5AZM5.js.map +7 -0
  178. package/dist/cli-bundle/chunks/{register-operations-AR7RMX4W.js → register-operations-744YBJMV.js} +23 -25
  179. package/dist/cli-bundle/chunks/{register-operations-AR7RMX4W.js.map → register-operations-744YBJMV.js.map} +1 -1
  180. package/dist/cli-bundle/chunks/{register-operations-NOLZGORC.js → register-operations-UEBJH6AN.js} +21 -23
  181. package/dist/cli-bundle/chunks/{register-operations-NOLZGORC.js.map → register-operations-UEBJH6AN.js.map} +1 -1
  182. package/dist/cli-bundle/chunks/{register-setup-EYZ7VTPZ.js → register-setup-5DA4UZXI.js} +7 -8
  183. package/dist/cli-bundle/chunks/{register-setup-EYZ7VTPZ.js.map → register-setup-5DA4UZXI.js.map} +1 -1
  184. package/dist/cli-bundle/chunks/{register-setup-BB77VUEE.js → register-setup-6H25M3BH.js} +9 -10
  185. package/dist/cli-bundle/chunks/{register-setup-BB77VUEE.js.map → register-setup-6H25M3BH.js.map} +1 -1
  186. package/dist/cli-bundle/chunks/{restore-ZH65GZFB.js → restore-6TDVSATY.js} +4 -5
  187. package/dist/cli-bundle/chunks/{restore-L6IAGOD7.js → restore-RSL7C7LO.js} +4 -5
  188. package/dist/cli-bundle/chunks/{schema-4ERWM5QJ.js → schema-HFXFSGPG.js} +2 -3
  189. package/dist/cli-bundle/chunks/{schema-55DL3Q52.js → schema-TPVTIJPO.js} +2 -3
  190. package/dist/cli-bundle/chunks/{update-FW6FKDOP.js → update-LJZCL5SI.js} +7 -7
  191. package/dist/cli-bundle/chunks/{update-TJHSPRPT.js → update-SIA7LH5Y.js} +7 -7
  192. package/dist/cli-bundle/chunks/{update-many-PWXX5WHO.js → update-many-BDBZVGQL.js} +11 -12
  193. package/dist/cli-bundle/chunks/{update-many-NNALYQCN.js → update-many-MOY3A5B3.js} +11 -12
  194. package/dist/cli-bundle/main.js +60 -85
  195. package/dist/cli-bundle/main.js.map +2 -2
  196. package/dist/cli-bundle/sdk-runtime.js +37 -37
  197. package/dist/cli-bundle/sdk.js +126 -291
  198. package/dist/cli-bundle/sdk.js.map +4 -4
  199. package/dist/core/item/parse.d.ts +1 -1
  200. package/dist/core/item/parse.js +13 -7
  201. package/dist/core/item/parse.js.map +1 -1
  202. package/dist/core/output/mutation-projection.d.ts +2 -0
  203. package/dist/core/output/mutation-projection.js +33 -2
  204. package/dist/core/output/mutation-projection.js.map +1 -1
  205. package/dist/core/output/output.d.ts +4 -0
  206. package/dist/core/output/output.js +18 -13
  207. package/dist/core/output/output.js.map +1 -1
  208. package/dist/core/shared/command-types.d.ts +4 -0
  209. package/dist/core/shared/command-types.js +2 -2
  210. package/dist/core/shared/command-types.js.map +1 -1
  211. package/dist/mcp/server.js +39 -4
  212. package/dist/mcp/server.js.map +1 -1
  213. package/dist/mcp/tool-definitions.js +45 -4
  214. package/dist/mcp/tool-definitions.js.map +1 -1
  215. package/dist/sdk/cli-bootstrap.d.ts +2 -0
  216. package/dist/sdk/cli-bootstrap.js +20 -27
  217. package/dist/sdk/cli-bootstrap.js.map +1 -1
  218. package/dist/sdk/cli-contracts/enum-contracts.d.ts +2 -2
  219. package/dist/sdk/cli-contracts/enum-contracts.js +7 -2
  220. package/dist/sdk/cli-contracts/enum-contracts.js.map +1 -1
  221. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  222. package/dist/sdk/cli-contracts/flag-contracts.js +21 -2
  223. package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
  224. package/dist/sdk/cli-contracts/tool-option-contracts.js +10 -2
  225. package/dist/sdk/cli-contracts/tool-option-contracts.js.map +1 -1
  226. package/dist/sdk/cli-contracts/tool-parameter-tables.js +16 -3
  227. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  228. package/dist/sdk/cli-contracts/tool-schema.js +6 -2
  229. package/dist/sdk/cli-contracts/tool-schema.js.map +1 -1
  230. package/dist/sdk/cli-contracts.d.ts +1 -1
  231. package/dist/sdk/cli-contracts.js +3 -3
  232. package/dist/sdk/cli-contracts.js.map +1 -1
  233. package/dist/sdk/cli-program.js +4 -2
  234. package/dist/sdk/cli-program.js.map +1 -1
  235. package/dist/sdk/dependencies.d.ts +3 -2
  236. package/dist/sdk/dependencies.js +13 -12
  237. package/dist/sdk/dependencies.js.map +1 -1
  238. package/dist/sdk/error-runtime.d.ts +10 -0
  239. package/dist/sdk/error-runtime.js +59 -0
  240. package/dist/sdk/error-runtime.js.map +1 -0
  241. package/dist/sdk/graph/analytics.d.ts +9 -0
  242. package/dist/sdk/graph/analytics.js +24 -13
  243. package/dist/sdk/graph/analytics.js.map +1 -1
  244. package/dist/sdk/graph/assembly.d.ts +39 -0
  245. package/dist/sdk/graph/assembly.js +92 -12
  246. package/dist/sdk/graph/assembly.js.map +1 -1
  247. package/dist/sdk/graph/cache.d.ts +4 -1
  248. package/dist/sdk/graph/cache.js +17 -4
  249. package/dist/sdk/graph/cache.js.map +1 -1
  250. package/dist/sdk/graph/centrality.d.ts +82 -0
  251. package/dist/sdk/graph/centrality.js +259 -0
  252. package/dist/sdk/graph/centrality.js.map +1 -0
  253. package/dist/sdk/graph/durable-cache.d.ts +71 -0
  254. package/dist/sdk/graph/durable-cache.js +205 -0
  255. package/dist/sdk/graph/durable-cache.js.map +1 -0
  256. package/dist/sdk/graph/governance.d.ts +69 -1
  257. package/dist/sdk/graph/governance.js +143 -35
  258. package/dist/sdk/graph/governance.js.map +1 -1
  259. package/dist/sdk/graph/index.d.ts +7 -4
  260. package/dist/sdk/graph/index.js +8 -5
  261. package/dist/sdk/graph/index.js.map +1 -1
  262. package/dist/sdk/graph/mutation-advisory.d.ts +35 -4
  263. package/dist/sdk/graph/mutation-advisory.js +124 -35
  264. package/dist/sdk/graph/mutation-advisory.js.map +1 -1
  265. package/dist/sdk/graph/remediation.js +12 -2
  266. package/dist/sdk/graph/remediation.js.map +1 -1
  267. package/dist/sdk/graph/run.d.ts +133 -2
  268. package/dist/sdk/graph/run.js +217 -8
  269. package/dist/sdk/graph/run.js.map +1 -1
  270. package/dist/sdk/graph/scheduling.d.ts +59 -0
  271. package/dist/sdk/graph/scheduling.js +125 -0
  272. package/dist/sdk/graph/scheduling.js.map +1 -0
  273. package/dist/sdk/graph/traversal.d.ts +11 -0
  274. package/dist/sdk/graph/traversal.js +16 -2
  275. package/dist/sdk/graph/traversal.js.map +1 -1
  276. package/dist/sdk/index.d.ts +4 -0
  277. package/dist/sdk/index.js +6 -2
  278. package/dist/sdk/index.js.map +1 -1
  279. package/dist/sdk/runtime-input.js +7 -2
  280. package/dist/sdk/runtime-input.js.map +1 -1
  281. package/dist/sdk/runtime-primitives.d.ts +10 -0
  282. package/dist/sdk/runtime-primitives.js +14 -0
  283. package/dist/sdk/runtime-primitives.js.map +1 -0
  284. package/dist/sdk/runtime.d.ts +15 -0
  285. package/dist/sdk/runtime.js +16 -3
  286. package/dist/sdk/runtime.js.map +1 -1
  287. package/dist/sdk/structured-mutations.d.ts +21 -0
  288. package/dist/sdk/structured-mutations.js +375 -0
  289. package/dist/sdk/structured-mutations.js.map +1 -0
  290. package/docs/COMMANDS.md +85 -5
  291. package/docs/RELATIONSHIP_GRAPH.md +48 -7
  292. package/docs/SDK.md +78 -3
  293. package/marketplace.json +2 -2
  294. package/package.json +1 -1
  295. package/packages/pm-beads/package.json +1 -1
  296. package/packages/pm-calendar/package.json +1 -1
  297. package/packages/pm-command-kit/package.json +1 -1
  298. package/packages/pm-governance-audit/package.json +1 -1
  299. package/packages/pm-guide-shell/package.json +1 -1
  300. package/packages/pm-kanban/package.json +1 -1
  301. package/packages/pm-lifecycle-hooks/package.json +1 -1
  302. package/packages/pm-linked-test-adapters/package.json +1 -1
  303. package/packages/pm-search-advanced/package.json +1 -1
  304. package/packages/pm-templates/package.json +1 -1
  305. package/packages/pm-todos/package.json +1 -1
  306. package/packages/pm-vcs/package.json +1 -1
  307. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  308. package/plugins/pm-claude/README.md +5 -3
  309. package/plugins/pm-claude/commands/pm-init.md +1 -1
  310. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  311. package/dist/cli-bundle/chunks/chunk-3AO5VSDR.js.map +0 -7
  312. package/dist/cli-bundle/chunks/chunk-3LPFHE3P.js.map +0 -1
  313. package/dist/cli-bundle/chunks/chunk-3VY6MIEO.js.map +0 -7
  314. package/dist/cli-bundle/chunks/chunk-4F6BWJ4J.js.map +0 -7
  315. package/dist/cli-bundle/chunks/chunk-5IZJWSDB.js.map +0 -1
  316. package/dist/cli-bundle/chunks/chunk-5UX66S6U.js.map +0 -1
  317. package/dist/cli-bundle/chunks/chunk-6C2ZZX5Z.js +0 -286
  318. package/dist/cli-bundle/chunks/chunk-6C2ZZX5Z.js.map +0 -1
  319. package/dist/cli-bundle/chunks/chunk-6VIJ7UA5.js.map +0 -7
  320. package/dist/cli-bundle/chunks/chunk-6XMUURSS.js.map +0 -1
  321. package/dist/cli-bundle/chunks/chunk-C3KD7U3T.js.map +0 -7
  322. package/dist/cli-bundle/chunks/chunk-CFHAODHQ.js +0 -334
  323. package/dist/cli-bundle/chunks/chunk-CFHAODHQ.js.map +0 -1
  324. package/dist/cli-bundle/chunks/chunk-DAQ45GCS.js.map +0 -7
  325. package/dist/cli-bundle/chunks/chunk-E6LEMURX.js +0 -249
  326. package/dist/cli-bundle/chunks/chunk-E6LEMURX.js.map +0 -7
  327. package/dist/cli-bundle/chunks/chunk-G3COA6GS.js.map +0 -1
  328. package/dist/cli-bundle/chunks/chunk-GSJSM5BJ.js.map +0 -1
  329. package/dist/cli-bundle/chunks/chunk-GVI6FAFG.js.map +0 -7
  330. package/dist/cli-bundle/chunks/chunk-GVT754PX.js.map +0 -7
  331. package/dist/cli-bundle/chunks/chunk-HEWM6CEN.js.map +0 -7
  332. package/dist/cli-bundle/chunks/chunk-IJNK6WW2.js.map +0 -7
  333. package/dist/cli-bundle/chunks/chunk-INSTSQNZ.js.map +0 -7
  334. package/dist/cli-bundle/chunks/chunk-J4FBIFU6.js.map +0 -1
  335. package/dist/cli-bundle/chunks/chunk-KZEANWJS.js.map +0 -7
  336. package/dist/cli-bundle/chunks/chunk-LPEYZRUR.js.map +0 -1
  337. package/dist/cli-bundle/chunks/chunk-NHT3F4WZ.js.map +0 -1
  338. package/dist/cli-bundle/chunks/chunk-OV7MSW3I.js.map +0 -1
  339. package/dist/cli-bundle/chunks/chunk-P7JTWYLH.js +0 -246
  340. package/dist/cli-bundle/chunks/chunk-P7JTWYLH.js.map +0 -1
  341. package/dist/cli-bundle/chunks/chunk-R5U2VZ3K.js +0 -344
  342. package/dist/cli-bundle/chunks/chunk-R5U2VZ3K.js.map +0 -7
  343. package/dist/cli-bundle/chunks/chunk-SG74J6MV.js.map +0 -1
  344. package/dist/cli-bundle/chunks/chunk-T44FMVRL.js.map +0 -7
  345. package/dist/cli-bundle/chunks/chunk-THAOZG4U.js.map +0 -1
  346. package/dist/cli-bundle/chunks/chunk-UQLXSG72.js +0 -289
  347. package/dist/cli-bundle/chunks/chunk-UQLXSG72.js.map +0 -7
  348. package/dist/cli-bundle/chunks/chunk-UZDQXNUB.js.map +0 -1
  349. package/dist/cli-bundle/chunks/chunk-WVA4DVNV.js.map +0 -7
  350. package/dist/cli-bundle/chunks/register-list-query-CFVG75P3.js.map +0 -1
  351. package/dist/cli-bundle/chunks/register-list-query-E7UVY4TN.js.map +0 -7
  352. package/dist/cli-bundle/chunks/register-mutation-4VJTXBZW.js.map +0 -7
  353. package/dist/cli-bundle/chunks/register-mutation-IQ55E25C.js.map +0 -1
  354. /package/dist/cli-bundle/chunks/{append-E6V54WOQ.js.map → append-7OVFYR3C.js.map} +0 -0
  355. /package/dist/cli-bundle/chunks/{append-NNJ3EFIT.js.map → append-DFETHAZL.js.map} +0 -0
  356. /package/dist/cli-bundle/chunks/{chunk-QJKL5PHS.js.map → chunk-7656MAUL.js.map} +0 -0
  357. /package/dist/cli-bundle/chunks/{chunk-X6K5XTTN.js.map → chunk-7W2UAXXT.js.map} +0 -0
  358. /package/dist/cli-bundle/chunks/{chunk-5OK4UGFV.js.map → chunk-BXNDKOR2.js.map} +0 -0
  359. /package/dist/cli-bundle/chunks/{chunk-KSPWRNVP.js.map → chunk-CPX275C6.js.map} +0 -0
  360. /package/dist/cli-bundle/chunks/{chunk-JH2ZSLO3.js.map → chunk-DZRV2OPA.js.map} +0 -0
  361. /package/dist/cli-bundle/chunks/{chunk-L7BH7IWU.js.map → chunk-E5XMKOSB.js.map} +0 -0
  362. /package/dist/cli-bundle/chunks/{chunk-CQTQKUUV.js.map → chunk-EWJWSNRU.js.map} +0 -0
  363. /package/dist/cli-bundle/chunks/{chunk-3MCTMJXI.js.map → chunk-FPBMLYPI.js.map} +0 -0
  364. /package/dist/cli-bundle/chunks/{chunk-DVDBQA3B.js.map → chunk-GTK4DTEW.js.map} +0 -0
  365. /package/dist/cli-bundle/chunks/{chunk-GIQSU6S2.js.map → chunk-KBLZ3AA5.js.map} +0 -0
  366. /package/dist/cli-bundle/chunks/{chunk-XJF7CDNH.js.map → chunk-KH44WBAT.js.map} +0 -0
  367. /package/dist/cli-bundle/chunks/{chunk-GV2262OF.js.map → chunk-LAV26CQG.js.map} +0 -0
  368. /package/dist/cli-bundle/chunks/{chunk-VDO2JMD4.js.map → chunk-LVC72YRD.js.map} +0 -0
  369. /package/dist/cli-bundle/chunks/{chunk-ZYPFOO3L.js.map → chunk-MATHDCGG.js.map} +0 -0
  370. /package/dist/cli-bundle/chunks/{chunk-AOEOYL3S.js.map → chunk-O4BCOJTZ.js.map} +0 -0
  371. /package/dist/cli-bundle/chunks/{chunk-RJO3YAFM.js.map → chunk-OCUBRA6D.js.map} +0 -0
  372. /package/dist/cli-bundle/chunks/{chunk-I577UHC7.js.map → chunk-OR42SO64.js.map} +0 -0
  373. /package/dist/cli-bundle/chunks/{chunk-ZOJ3LR7O.js.map → chunk-OY7DMU5P.js.map} +0 -0
  374. /package/dist/cli-bundle/chunks/{chunk-ZV2NTVMJ.js.map → chunk-PONKZPCJ.js.map} +0 -0
  375. /package/dist/cli-bundle/chunks/{chunk-UX6SSO2I.js.map → chunk-PZC2FUOQ.js.map} +0 -0
  376. /package/dist/cli-bundle/chunks/{chunk-VQIHNHMJ.js.map → chunk-QIH77CAG.js.map} +0 -0
  377. /package/dist/cli-bundle/chunks/{chunk-R3EWPG4A.js.map → chunk-QJIKE24M.js.map} +0 -0
  378. /package/dist/cli-bundle/chunks/{chunk-HB3P4M52.js.map → chunk-TRSHFPRZ.js.map} +0 -0
  379. /package/dist/cli-bundle/chunks/{chunk-HRW7GF6T.js.map → chunk-UCBDQI5E.js.map} +0 -0
  380. /package/dist/cli-bundle/chunks/{chunk-4U4Z6AHI.js.map → chunk-V22ZPOKN.js.map} +0 -0
  381. /package/dist/cli-bundle/chunks/{chunk-JM6YAXTR.js.map → chunk-VHXHVTUU.js.map} +0 -0
  382. /package/dist/cli-bundle/chunks/{chunk-D6NXDNP3.js.map → chunk-VLRGDBLY.js.map} +0 -0
  383. /package/dist/cli-bundle/chunks/{chunk-JAPE62Y5.js.map → chunk-VNTCM3VW.js.map} +0 -0
  384. /package/dist/cli-bundle/chunks/{chunk-FDHPAVVB.js.map → chunk-VXOOB6YX.js.map} +0 -0
  385. /package/dist/cli-bundle/chunks/{chunk-HQ3SB4CN.js.map → chunk-X3W65QK3.js.map} +0 -0
  386. /package/dist/cli-bundle/chunks/{chunk-RZJLNXFG.js.map → chunk-XJTABV3X.js.map} +0 -0
  387. /package/dist/cli-bundle/chunks/{chunk-TYHJDFYW.js.map → chunk-ZVZGXPQ5.js.map} +0 -0
  388. /package/dist/cli-bundle/chunks/{close-many-SDA426VT.js.map → close-many-5RZXVN4J.js.map} +0 -0
  389. /package/dist/cli-bundle/chunks/{close-many-UTZANOCQ.js.map → close-many-RZVTUGBG.js.map} +0 -0
  390. /package/dist/cli-bundle/chunks/{comments-LZN6FXXC.js.map → comments-TPU7QRBL.js.map} +0 -0
  391. /package/dist/cli-bundle/chunks/{comments-VBQ345ND.js.map → comments-Z4KV6FU3.js.map} +0 -0
  392. /package/dist/cli-bundle/chunks/{create-GG4RBCGC.js.map → create-EIFBIVNQ.js.map} +0 -0
  393. /package/dist/cli-bundle/chunks/{create-JBC5KUW6.js.map → create-RGSPN5GD.js.map} +0 -0
  394. /package/dist/cli-bundle/chunks/{deps-FI4O6NQS.js.map → deps-UH5EQQUY.js.map} +0 -0
  395. /package/dist/cli-bundle/chunks/{deps-DELOO4TL.js.map → deps-YG7UF3VR.js.map} +0 -0
  396. /package/dist/cli-bundle/chunks/{docs-6Z2MP526.js.map → docs-G32TK6XS.js.map} +0 -0
  397. /package/dist/cli-bundle/chunks/{docs-2UYBP5D6.js.map → docs-JWWNRC27.js.map} +0 -0
  398. /package/dist/cli-bundle/chunks/{files-HKEAN5MA.js.map → files-3H32UQ4K.js.map} +0 -0
  399. /package/dist/cli-bundle/chunks/{files-HEUGSJZL.js.map → files-4ALMCSKB.js.map} +0 -0
  400. /package/dist/cli-bundle/chunks/{history-compact-7NDVP3PT.js.map → history-compact-77BT2LUB.js.map} +0 -0
  401. /package/dist/cli-bundle/chunks/{history-compact-65YVN5DB.js.map → history-compact-VCKGTX64.js.map} +0 -0
  402. /package/dist/cli-bundle/chunks/{history-redact-7YBL4XSG.js.map → history-redact-LJPZPNFA.js.map} +0 -0
  403. /package/dist/cli-bundle/chunks/{history-redact-IZGNJBU4.js.map → history-redact-PWTTJ3XS.js.map} +0 -0
  404. /package/dist/cli-bundle/chunks/{history-repair-7M4PYQUH.js.map → history-repair-I7CBNCV3.js.map} +0 -0
  405. /package/dist/cli-bundle/chunks/{history-repair-GNGETJLI.js.map → history-repair-YTDZRK5E.js.map} +0 -0
  406. /package/dist/cli-bundle/chunks/{learnings-3YXDRWFT.js.map → learnings-CYNOICKR.js.map} +0 -0
  407. /package/dist/cli-bundle/chunks/{learnings-ALC6IMNL.js.map → learnings-KTYW3AL7.js.map} +0 -0
  408. /package/dist/cli-bundle/chunks/{notes-7JMLQ447.js.map → notes-FGO63FXL.js.map} +0 -0
  409. /package/dist/cli-bundle/chunks/{notes-JFCLTC5C.js.map → notes-ZERD3KB2.js.map} +0 -0
  410. /package/dist/cli-bundle/chunks/{plan-T3XB3WTK.js.map → plan-OFJUBIM5.js.map} +0 -0
  411. /package/dist/cli-bundle/chunks/{plan-KOIPWVOZ.js.map → plan-SGCDDTYR.js.map} +0 -0
  412. /package/dist/cli-bundle/chunks/{profile-OILJHKUW.js.map → profile-3THJPIQY.js.map} +0 -0
  413. /package/dist/cli-bundle/chunks/{profile-RJXA7PGS.js.map → profile-XEZAMMBW.js.map} +0 -0
  414. /package/dist/cli-bundle/chunks/{restore-ZH65GZFB.js.map → restore-6TDVSATY.js.map} +0 -0
  415. /package/dist/cli-bundle/chunks/{restore-L6IAGOD7.js.map → restore-RSL7C7LO.js.map} +0 -0
  416. /package/dist/cli-bundle/chunks/{schema-4ERWM5QJ.js.map → schema-HFXFSGPG.js.map} +0 -0
  417. /package/dist/cli-bundle/chunks/{schema-55DL3Q52.js.map → schema-TPVTIJPO.js.map} +0 -0
  418. /package/dist/cli-bundle/chunks/{update-FW6FKDOP.js.map → update-LJZCL5SI.js.map} +0 -0
  419. /package/dist/cli-bundle/chunks/{update-TJHSPRPT.js.map → update-SIA7LH5Y.js.map} +0 -0
  420. /package/dist/cli-bundle/chunks/{update-many-PWXX5WHO.js.map → update-many-BDBZVGQL.js.map} +0 -0
  421. /package/dist/cli-bundle/chunks/{update-many-NNALYQCN.js.map → update-many-MOY3A5B3.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../../sdk/workspace.ts","../../../../../../../../sdk/merge/install.ts"],"sourcesContent":["/**\n * @module sdk/workspace\n *\n * Maintains repository-scaffold contracts shared by the public SDK and CLI.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Opening marker for the init-owned ignore block. */\nexport const PM_GITIGNORE_START = \"# pm-cli:runtime-cache:start\";\n/** Closing marker for the init-owned ignore block. */\nexport const PM_GITIGNORE_END = \"# pm-cli:runtime-cache:end\";\n\n/** Default workspace-relative tracker root used when no custom root is resolved. */\nexport const PM_GITIGNORE_DEFAULT_TRACKER_ROOT = \".agents/pm\";\n\n/**\n * Tracker-relative directories that hold per-clone runtime state (caches,\n * search indexes, locks, crash-recovery receipts). They must never be\n * committed: they churn on every command and conflict on every concurrent\n * branch merge. `transactions/` (SDK workspace-transaction journals) and\n * `checkpoints/` (bulk-mutation rollback receipts) are per-branch recovery\n * state with their own GC (`pm gc --scope transactions|checkpoints`), so\n * keeping them untracked is the recorded merge-safety disposition.\n */\nexport const PM_GITIGNORE_RUNTIME_DIRECTORIES = [\n \"runtime/\",\n \"search/\",\n \"locks/\",\n \"transactions/\",\n \"checkpoints/\",\n] as const;\n\n/** Result of reconciling the init-owned repository ignore block. */\nexport interface EnsurePmGitignoreResult {\n /** Absolute path to the reconciled file. */\n path: string;\n /** Whether the file content changed. */\n changed: boolean;\n}\n\nfunction normalizeTrackerRelativeRoot(trackerRelativeRoot: string): string {\n return trackerRelativeRoot\n .replaceAll(\"\\\\\", \"/\")\n .replace(/^\\.\\/+/, \"\")\n .replace(/\\/+$/, \"\");\n}\n\n/** Return whether a relative path escapes its owning root, without rejecting valid names such as `..pm`. */\nexport function isPathOutsideRoot(relativePath: string): boolean {\n const normalized = relativePath.replaceAll(\"\\\\\", \"/\");\n return (\n path.isAbsolute(relativePath) ||\n normalized === \"..\" ||\n normalized.startsWith(\"../\")\n );\n}\n\n/** Return the canonical pm ignore block rendered for the given workspace-relative tracker root (defaults to `.agents/pm`), primarily for documentation and tests. */\nexport function getPmGitignoreBlock(\n trackerRelativeRoot: string = PM_GITIGNORE_DEFAULT_TRACKER_ROOT,\n): string {\n const root = normalizeTrackerRelativeRoot(trackerRelativeRoot);\n return [\n PM_GITIGNORE_START,\n ...PM_GITIGNORE_RUNTIME_DIRECTORIES.map(\n (directory) => `${root}/${directory}`,\n ),\n PM_GITIGNORE_END,\n ].join(\"\\n\");\n}\n\n/**\n * Idempotently create or replace the fenced pm cache block in a workspace\n * `.gitignore`. When `pmRoot` is provided the ignored runtime directories are\n * rendered under the resolved workspace-relative tracker root, so custom-root\n * workspaces (`--pm-path`/`PM_PATH`) stop committing runtime caches (GH-598).\n * A tracker root outside the workspace needs no ignore rules here, so the\n * file is left untouched.\n */\nexport async function ensurePmGitignore(\n workspaceRoot: string,\n options: {\n /** Absolute tracker root; rendered relative to the workspace root. */\n pmRoot?: string;\n } = {},\n): Promise<EnsurePmGitignoreResult> {\n const gitignorePath = path.join(workspaceRoot, \".gitignore\");\n let trackerRelativeRoot = PM_GITIGNORE_DEFAULT_TRACKER_ROOT;\n if (options.pmRoot !== undefined) {\n const relative = normalizeTrackerRelativeRoot(\n path.relative(path.resolve(workspaceRoot), path.resolve(options.pmRoot)),\n );\n if (isPathOutsideRoot(relative)) {\n return { path: gitignorePath, changed: false };\n }\n if (relative.length > 0) {\n trackerRelativeRoot = relative;\n }\n }\n let current = \"\";\n try {\n current = await readFile(gitignorePath, \"utf8\");\n } catch (error: unknown) {\n if (\n !(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n ) {\n throw error;\n }\n }\n const start = current.indexOf(PM_GITIGNORE_START);\n const end = current.indexOf(PM_GITIGNORE_END);\n const withoutManagedBlock =\n start >= 0 && end >= start\n ? `${current.slice(0, start)}${current.slice(end + PM_GITIGNORE_END.length)}`\n : current;\n const prefix = withoutManagedBlock.trimEnd();\n const next = `${prefix.length > 0 ? `${prefix}\\n\\n` : \"\"}${getPmGitignoreBlock(trackerRelativeRoot)}\\n`;\n if (next === current) {\n return { path: gitignorePath, changed: false };\n }\n await writeFile(gitignorePath, next, \"utf8\");\n return { path: gitignorePath, changed: true };\n}\n","/**\n * @module sdk/merge/install\n *\n * Installs the tracker's git merge configuration into a repository: a fenced\n * `.gitattributes` block mapping every mergeable tracker artifact class to a\n * pm merge driver, plus the local `git config` driver definitions that make\n * those attributes effective. Idempotent and re-runnable; schema type\n * mutations refresh the fenced block automatically once it is installed.\n */\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { execFile } from \"node:child_process\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.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 { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport {\n readSettings,\n resolveGovernanceKnobs,\n} from \"../../core/store/settings.js\";\nimport { isPathOutsideRoot } from \"../workspace.js\";\n\nconst execFileAsync = promisify(execFile);\n\n/** Opening marker for the pm-owned merge-driver `.gitattributes` block. */\nexport const PM_GITATTRIBUTES_START = \"# pm-cli:merge-drivers:start\";\n/** Closing marker for the pm-owned merge-driver `.gitattributes` block. */\nexport const PM_GITATTRIBUTES_END = \"# pm-cli:merge-drivers:end\";\n\nconst MERGE_FENCE_LOCK_ID = \"merge-fence\";\n\nconst MERGE_DRIVER_DEFINITIONS = [\n {\n key: \"pm-item-toon\",\n name: \"pm field-aware TOON item document merge\",\n artifact: \"item\",\n itemPath: \"item.toon\",\n },\n {\n key: \"pm-item-markdown\",\n name: \"pm field-aware JSON-markdown item document merge\",\n artifact: \"item\",\n itemPath: \"item.md\",\n },\n {\n key: \"pm-history\",\n name: \"pm append-only history stream merge\",\n artifact: \"history\",\n itemPath: undefined,\n },\n {\n key: \"pm-relationship\",\n name: \"pm append-only relationship event store merge\",\n artifact: \"relationship\",\n itemPath: undefined,\n },\n {\n key: \"pm-json\",\n name: \"pm key-level JSON config merge\",\n artifact: \"json\",\n itemPath: undefined,\n },\n] as const;\n\n/** Documents the merge install options payload exchanged by command, SDK, and package integrations. */\nexport interface MergeInstallOptions {\n /** Preview the `.gitattributes` and `git config` changes without writing anything. */\n dryRun?: boolean;\n}\n\n/** Documents the merge install result payload exchanged by command, SDK, and package integrations. */\nexport interface MergeInstallResult {\n /** Whether the installation completed (or, for dry runs, would complete) without errors. */\n ok: boolean;\n /** Whether this run was a preview only. */\n dry_run: boolean;\n /** Repository root the merge configuration was installed into. */\n workspace_root: string;\n /** `.gitattributes` reconciliation outcome. */\n gitattributes: {\n path: string;\n changed: boolean;\n patterns: string[];\n };\n /** Local `git config` merge-driver definitions applied (or previewed). */\n git_config: Array<{ key: string; value: string }>;\n /** Guidance for completing the multi-branch workflow setup. */\n guidance: string[];\n /** ISO 8601 timestamp recording when generated occurred. */\n generated_at: string;\n}\n\nasync function resolveGitWorkspaceRoot(cwd: string): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\n \"git\",\n [\"rev-parse\", \"--show-toplevel\"],\n { cwd, encoding: \"utf8\", windowsHide: true, timeout: 10_000 },\n );\n return stdout.trim();\n } catch {\n throw new PmCliError(\n \"pm merge install requires a git repository (merge drivers are git configuration).\",\n EXIT_CODE.USAGE,\n );\n }\n}\n\nfunction toPosixRelative(fromPath: string, toPath: string): string {\n return path.relative(fromPath, toPath).replaceAll(\"\\\\\", \"/\");\n}\n\n/** Encode one Git attributes pattern with C-style quoting so whitespace, backslashes, and quotation marks remain part of the repository path instead of being parsed as attribute separators. */\nfunction quoteGitAttributePattern(value: string): string {\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\n/**\n * Build the complete fenced `.gitattributes` pattern list for a tracker rooted\n * at `trackerRelativeRoot` (git-root-relative POSIX path, empty when the\n * tracker root IS the git root). This is the single coverage contract shared\n * by `pm merge install` (which writes the fence) and the validate\n * merge-fence-drift detection (which compares the committed fence against the\n * active schema's type folders), so schema-added custom types can never\n * silently diverge from the installed fence without a warning.\n */\nexport function buildMergeAttributePatterns(\n trackerRelativeRoot: string,\n typeFolders: string[],\n): string[] {\n const prefix =\n trackerRelativeRoot.length > 0 ? `${trackerRelativeRoot}/` : \"\";\n const patterns: string[] = [];\n for (const folder of typeFolders) {\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}${folder}/*.toon`)} merge=pm-item-toon`,\n );\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}${folder}/*.md`)} merge=pm-item-markdown`,\n );\n }\n // RelationshipEventStore deliberately accepts a caller-chosen relativePath\n // anywhere below the tracker root. Cover all tracker JSONL first, then let\n // the more-specific history rule below override it. This keeps custom event\n // stores protected without guessing package-owned paths.\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}**/*.jsonl`)} merge=pm-relationship`,\n );\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}history/*.jsonl`)} merge=pm-history`,\n );\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}settings.json`)} merge=pm-json`,\n );\n patterns.push(\n `${quoteGitAttributePattern(`${prefix}schema/*.json`)} merge=pm-json`,\n );\n return patterns;\n}\n\nasync function reconcileGitattributesBlock(\n workspaceRoot: string,\n patterns: string[],\n dryRun: boolean,\n): Promise<{ path: string; changed: boolean }> {\n const gitattributesPath = path.join(workspaceRoot, \".gitattributes\");\n let current = \"\";\n try {\n current = await readFile(gitattributesPath, \"utf8\");\n } catch (error: unknown) {\n if (\n !(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n ) {\n throw error;\n }\n }\n const block = [\n PM_GITATTRIBUTES_START,\n ...patterns,\n PM_GITATTRIBUTES_END,\n ].join(\"\\n\");\n const start = current.indexOf(PM_GITATTRIBUTES_START);\n const end = current.indexOf(PM_GITATTRIBUTES_END);\n const withoutManagedBlock =\n start >= 0 && end > start\n ? `${current.slice(0, start)}${current.slice(end + PM_GITATTRIBUTES_END.length)}`\n : current\n .replace(PM_GITATTRIBUTES_START, \"\")\n .replace(PM_GITATTRIBUTES_END, \"\");\n const prefix = withoutManagedBlock.trimEnd();\n const next = `${prefix.length > 0 ? `${prefix}\\n\\n` : \"\"}${block}\\n`;\n if (next === current) {\n return { path: gitattributesPath, changed: false };\n }\n if (!dryRun) {\n await writeFile(gitattributesPath, next, \"utf8\");\n }\n return { path: gitattributesPath, changed: true };\n}\n\n/** Result of comparing the committed merge-fence block against the coverage the active schema requires. */\nexport interface MergeFenceAuditResult {\n /** Audit outcome: no fence installed (nothing to audit), fence matches, or fence drifted from the active schema/type folders. */\n status: \"not_installed\" | \"ok\" | \"drift\";\n /** `.gitattributes` file containing the fence, when one was found. */\n path?: string;\n /** Expected attribute lines absent from the committed fence (for example a schema-added type folder). */\n missing_patterns: string[];\n /** Committed fence lines no longer produced by the coverage contract (for example a removed type folder). */\n stale_patterns: string[];\n}\n\n/**\n * Audit the committed `.gitattributes` merge fence against the coverage the\n * active schema requires, without touching git configuration. The fence file\n * is discovered by walking up from the tracker root (bounded), so the audit\n * stays filesystem-only and safe to run inside `pm validate`. A `drift`\n * result means items of some type folder (or a tracker JSONL store) would\n * merge under git's default text driver despite the fence being installed.\n */\nexport async function auditMergeAttributeFence(\n pmRoot: string,\n typeFolders: string[],\n): Promise<MergeFenceAuditResult> {\n const resolvedRoot = path.resolve(pmRoot);\n let fenceDirectory: string | null = null;\n let fenceContent = \"\";\n let directory = resolvedRoot;\n for (let depth = 0; depth < 8; depth += 1) {\n const candidate = path.join(directory, \".gitattributes\");\n try {\n const raw = await readFile(candidate, \"utf8\");\n if (raw.includes(PM_GITATTRIBUTES_START)) {\n fenceDirectory = directory;\n fenceContent = raw;\n break;\n }\n } catch {\n // No .gitattributes at this level; keep walking up.\n }\n const parent = path.dirname(directory);\n if (parent === directory) {\n break;\n }\n directory = parent;\n }\n if (fenceDirectory === null) {\n return { status: \"not_installed\", missing_patterns: [], stale_patterns: [] };\n }\n const fencePath = path.join(fenceDirectory, \".gitattributes\");\n const start = fenceContent.indexOf(PM_GITATTRIBUTES_START);\n const end = fenceContent.indexOf(PM_GITATTRIBUTES_END);\n const committed =\n end > start\n ? fenceContent\n .slice(start + PM_GITATTRIBUTES_START.length, end)\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n : [];\n const expected = buildMergeAttributePatterns(\n toPosixRelative(fenceDirectory, resolvedRoot),\n typeFolders,\n );\n const committedSet = new Set(committed);\n const expectedSet = new Set(expected);\n const missing = expected.filter((line) => !committedSet.has(line));\n const stale = committed.filter((line) => !expectedSet.has(line));\n return {\n status: missing.length > 0 || stale.length > 0 ? \"drift\" : \"ok\",\n path: fencePath,\n missing_patterns: missing,\n stale_patterns: stale,\n };\n}\n\n/** Outcome of an automatic merge-fence refresh attempted after a schema type mutation. */\nexport interface MergeFenceRefreshOutcome {\n /** What happened: the fence was rewritten, already matched, was never installed (actionable hint), or there is no git repository to configure. */\n status: \"refreshed\" | \"unchanged\" | \"not_installed\" | \"no_git\";\n /** `.gitattributes` path examined, when a git repository was found. */\n path?: string;\n}\n\n/**\n * Refresh the fenced `.gitattributes` merge-driver block after a schema type\n * mutation, but only when `pm merge install` already ran (the fence markers\n * are present). Without this, custom item types registered after install\n * would write items into folders with no merge attribute — silently\n * reintroducing the whole-file conflict class for exactly those items. Repos\n * that never installed the fence get a `not_installed` outcome so callers can\n * surface an actionable hint instead of mutating git configuration nobody\n * asked for.\n */\nexport async function refreshMergeAttributeFenceIfInstalled(\n pmRoot: string,\n): Promise<MergeFenceRefreshOutcome> {\n let workspaceRoot: string;\n try {\n workspaceRoot = await resolveGitWorkspaceRoot(path.resolve(pmRoot));\n } catch {\n return { status: \"no_git\" };\n }\n const trackerRelativeRoot = toPosixRelative(\n workspaceRoot,\n path.resolve(pmRoot),\n );\n const lockSettings = await readSettings(pmRoot);\n const owner = (process.env.PM_AUTHOR ?? lockSettings.author_default).trim();\n const releaseLock = await acquireLock(\n pmRoot,\n MERGE_FENCE_LOCK_ID,\n lockSettings.locks.ttl_seconds,\n owner.length > 0 ? owner : \"unknown\",\n false,\n resolveGovernanceKnobs(lockSettings).force_required_for_stale_lock,\n lockSettings.locks.wait_ms,\n );\n try {\n const gitattributesPath = path.join(workspaceRoot, \".gitattributes\");\n let current: string;\n try {\n current = await readFile(gitattributesPath, \"utf8\");\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\n return { status: \"not_installed\", path: gitattributesPath };\n }\n throw error;\n }\n if (!current.includes(PM_GITATTRIBUTES_START)) {\n return { status: \"not_installed\", path: gitattributesPath };\n }\n // Re-read after acquiring the dedicated fence lock so every concurrent\n // refresher computes from the latest committed type registry.\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const typeFolders = [\n ...new Set(Object.values(typeRegistry.type_to_folder)),\n ].sort((left, right) => left.localeCompare(right));\n const outcome = await reconcileGitattributesBlock(\n workspaceRoot,\n buildMergeAttributePatterns(trackerRelativeRoot, typeFolders),\n false,\n );\n return {\n status: outcome.changed ? \"refreshed\" : \"unchanged\",\n path: outcome.path,\n };\n } finally {\n await releaseLock();\n }\n}\n\n/**\n * Install (or preview) the repository merge configuration for tracker data:\n * writes the fenced merge-driver block into `.gitattributes` (committed and\n * shared with every branch) and defines the `merge.pm-*.driver` entries in the\n * repository-local git config (per-clone, so every collaborator runs this once\n * per checkout). Requires an initialized tracker and a git repository.\n */\nexport async function runMergeInstall(\n options: MergeInstallOptions,\n global: GlobalOptions,\n): Promise<MergeInstallResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n const dryRun = options.dryRun === true;\n const workspaceRoot = await resolveGitWorkspaceRoot(process.cwd());\n const trackerRelativeRoot = toPosixRelative(\n workspaceRoot,\n path.resolve(pmRoot),\n );\n if (isPathOutsideRoot(trackerRelativeRoot)) {\n throw new PmCliError(\n `Tracker root ${pmRoot} is outside the git repository ${workspaceRoot}; there is nothing to configure for this repository.`,\n EXIT_CODE.USAGE,\n );\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const typeFolders = [\n ...new Set(Object.values(typeRegistry.type_to_folder)),\n ].sort((left, right) => left.localeCompare(right));\n const patterns = buildMergeAttributePatterns(\n trackerRelativeRoot,\n typeFolders,\n );\n const gitattributes = await reconcileGitattributesBlock(\n workspaceRoot,\n patterns,\n dryRun,\n );\n\n const gitConfigEntries: Array<{ key: string; value: string }> = [];\n for (const definition of MERGE_DRIVER_DEFINITIONS) {\n gitConfigEntries.push({\n key: `merge.${definition.key}.name`,\n value: definition.name,\n });\n gitConfigEntries.push({\n key: `merge.${definition.key}.driver`,\n value: `pm merge driver ${definition.artifact} \"%O\" \"%A\" \"%B\"${definition.itemPath === undefined ? \"\" : ` --item-path ${definition.itemPath}`}`,\n });\n }\n if (!dryRun) {\n for (const entry of gitConfigEntries) {\n await execFileAsync(\"git\", [\"config\", entry.key, entry.value], {\n cwd: workspaceRoot,\n encoding: \"utf8\",\n windowsHide: true,\n timeout: 10_000,\n });\n }\n }\n\n return {\n ok: true,\n dry_run: dryRun,\n workspace_root: workspaceRoot,\n gitattributes: {\n path: gitattributes.path,\n changed: gitattributes.changed,\n patterns,\n },\n git_config: gitConfigEntries,\n guidance: [\n \"Commit .gitattributes so every branch and collaborator shares the merge mapping.\",\n 'git config is per-clone: each collaborator (and each fresh worktree/clone) runs \"pm merge install\" once.',\n 'After merging branches, run \"pm validate\" and, if history drift is reported, \"pm history-repair --all\" to reconcile item state with merged history.',\n \"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits.\",\n ],\n generated_at: nowIso(),\n };\n}\n"],"names":["readFile","writeFile","path","path","readFile","writeFile"],"mappings":";;;;;;;;;;;;;;;;;;;AAKA,SAAS,UAAU,iBAAiB;AACpC,OAAO,UAAU;AAGV,IAAM,qBAAqB;AAE3B,IAAM,mBAAmB;AAGzB,IAAM,oCAAoC;AAW1C,IAAM,mCAAmC;EAC9C;EACA;EACA;EACA;EACA;;AAWF,SAAS,6BAA6B,qBAA2B;AAC/D,SAAO,oBACJ,WAAW,MAAM,GAAG,EACpB,QAAQ,UAAU,EAAE,EACpB,QAAQ,QAAQ,EAAE;AACvB;AAGM,SAAU,kBAAkB,cAAoB;AACpD,QAAM,aAAa,aAAa,WAAW,MAAM,GAAG;AACpD,SACE,KAAK,WAAW,YAAY,KAC5B,eAAe,QACf,WAAW,WAAW,KAAK;AAE/B;AAGM,SAAU,oBACd,sBAA8B,mCAAiC;AAE/D,QAAM,OAAO,6BAA6B,mBAAmB;AAC7D,SAAO;IACL;IACA,GAAG,iCAAiC,IAClC,CAAC,cAAc,GAAG,IAAI,IAAI,SAAS,EAAE;IAEvC;IACA,KAAK,IAAI;AACb;AAUA,eAAsB,kBACpB,eACA,UAGI,CAAA,GAAE;AAEN,QAAM,gBAAgB,KAAK,KAAK,eAAe,YAAY;AAC3D,MAAI,sBAAs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AD,MAAK,QAAQ,MAAM,CAAC;AAEtB,MAAI,kBAAkB,mBAAmB,GAAG;AAC1C,UAAM,IAAI,WACR,gBAAgB,MAAM,kCAAkC,aAAa,wDACrE,UAAU,KAAK;EAEnB;AAEA,QAAM,WAAW,MAAM,aAAa,MAAM;AAC1C,QAAM,eAAe,wBACnB,UACA,gCAA+B,CAAE;AAEnC,QAAM,cAAc;IAClB,GAAG,IAAI,IAAI,OAAO,OAAO,aAAa,cAAc,CAAC;IACrD,KAAK,CAAC,MAAM,UAAU,KAAK,cAAc,KAAK,CAAC;AACjD,QAAM,WAAW,4BACf,qBACA,WAAW;AAEb,QAAM,gBAAgB,MAAM,4BAC1B,eACA,UACA,MAAM;AAGR,QAAM,mBAA0D,CAAA;AAChE,aAAW,cAAc,0BAA0B;AACjD,qBAAiB,KAAK;MACpB,KAAK,SAAS,WAAW,GAAG;MAC5B,OAAO,WAAW;KACnB;AACD,qBAAiB,KAAK;MACpB,KAAK,SAAS,WAAW,GAAG;MAC5B,OAAO,mBAAmB,WAAW,QAAQ,kBAAkB,WAAW,aAAa,SAAY,KAAK,gBAAgB,WAAW,QAAQ,EAAE;KAC9I;EACH;AACA,MAAI,CAAC,QAAQ;AACX,eAAW,SAAS,kBAAkB;AACpC,YAAM,cAAc,OAAO,CAAC,UAAU,MAAM,KAAK,MAAM,KAAK,GAAG;QAC7D,KAAK;QACL,UAAU;QACV,aAAa;QACb,SAAS;OACV;IACH;EACF;AAEA,SAAO;IACL,IAAI;IACJ,SAAS;IACT,gBAAgB;IAChB,eAAe;MACb,MAAM,cAAc;MACpB,SAAS,cAAc;MACvB;;IAEF,YAAY;IACZ,UAAU;MACR;MACA;MACA;MACA;;IAEF,cAAc,OAAM;;AAExB","debugId":"85f534fd-62b4-5641-8729-6dcd58b50e94"}
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../../../../../sdk/graph/cache.ts", "../../../../../../../../sdk/relationship-context.ts", "../../../../../../../../sdk/dependencies.ts"],
4
- "sourcesContent": ["/**\n * @module sdk/graph/cache\n *\n * Incremental workspace graph cache: fingerprint-keyed reuse of the assembled\n * relationship graph plus memoized analytics results, so long-lived processes\n * (the MCP server, SDK consumers, packages) stop paying the full-workspace\n * assembly and analysis cost on every bounded query. The fingerprint is a\n * deterministic digest of every relationship-relevant item field — id, title,\n * lifecycle status and its terminal classification, hierarchy parent, legacy\n * blocker, and structured dependency edges — so any mutation that could change\n * the graph or its projections invalidates the entry, while unrelated payload\n * churn (bodies, comments) does not enter the digest at all. Every lookup\n * reports hit/miss observability so envelopes can explain their freshness.\n */\nimport { createHash } from \"node:crypto\";\nimport type { Dependency, ItemStatus } from \"../../types/index.js\";\nimport type {\n WorkspaceRelationshipAssembly,\n WorkspaceRelationshipItem,\n} from \"./assembly.js\";\n\n/** Default memoized query results retained per workspace entry. */\nconst DEFAULT_MAX_RESULTS_PER_WORKSPACE = 64;\n/** Default workspace entries retained by one cache instance. */\nconst DEFAULT_MAX_WORKSPACES = 8;\n\n/** Cache observability attached to graph result envelopes. */\nexport interface GraphCacheMetadata {\n /** Truncated workspace graph fingerprint identifying the snapshot answered from. */\n fingerprint: string;\n /** Whether the workspace assembly was reused from cache. */\n assembly: \"hit\" | \"miss\";\n /** Whether the full query result was reused from cache. */\n result: \"hit\" | \"miss\";\n}\n\n/** Digest one item's relationship-relevant fields into a deterministic line. */\nfunction fingerprintLine(\n item: WorkspaceRelationshipItem,\n isTerminal: (status: ItemStatus) => boolean,\n): string {\n const dependencies = (item.dependencies ?? [])\n .map((rawDependency) => {\n // Public SDK callers may supply legacy or JSON-decoded payloads; mirror\n // assembly's defensive normalization so the digest tracks what assembly\n // would actually index.\n if (typeof rawDependency !== \"object\" || rawDependency === null)\n return \"\";\n const dependency = rawDependency as Partial<Dependency>;\n return `${typeof dependency.kind === \"string\" ? dependency.kind : \"related\"}:${\n typeof dependency.id === \"string\" ? dependency.id : \"\"\n }`;\n })\n .sort()\n .join(\",\");\n return [\n item.id,\n item.title,\n item.status,\n isTerminal(item.status) ? \"1\" : \"0\",\n item.parent ?? \"\",\n item.blocked_by ?? \"\",\n dependencies,\n ].join(\"\\u0000\");\n}\n\n/**\n * Compute the deterministic workspace graph fingerprint for one item snapshot.\n * Items are digested in sorted order so storage enumeration order never\n * changes the fingerprint, and the terminal classification of each status is\n * folded in so schema changes to lifecycle semantics invalidate cached\n * assemblies even when raw statuses are unchanged.\n */\nexport function computeWorkspaceGraphFingerprint(\n items: readonly WorkspaceRelationshipItem[],\n isTerminal: (status: ItemStatus) => boolean = (status) =>\n status === \"closed\" || status === \"canceled\",\n): string {\n const lines = items\n .filter((item) => typeof item?.id === \"string\" && item.id.trim().length > 0)\n .map((item) => fingerprintLine(item, isTerminal))\n .sort();\n // Separate fields and records with control characters no stored field can\n // contain unescaped, so adjacent free-text fields can never collide.\n return createHash(\"sha256\").update(lines.join(\"\\u0001\")).digest(\"hex\");\n}\n\n/** One cached workspace snapshot: its assembly plus memoized query results. */\ninterface WorkspaceGraphCacheEntry {\n /** Fingerprint of the item snapshot this entry answers for. */\n fingerprint: string;\n /** Assembled relationship graph reused across queries. */\n assembly: WorkspaceRelationshipAssembly;\n /** Bounded insertion-ordered memo of deterministic query results. */\n results: Map<string, unknown>;\n}\n\n/** One resolved cache lookup bound to a workspace snapshot. */\nexport interface WorkspaceGraphCacheLookup {\n /** The (possibly reused) workspace assembly. */\n assembly: WorkspaceRelationshipAssembly;\n /** Whether the assembly came from cache instead of being rebuilt. */\n assemblyReused: boolean;\n /** Full fingerprint of the snapshot this lookup is bound to. */\n fingerprint: string;\n /**\n * Memoize one deterministic query result under this snapshot. On a miss the\n * freshly computed value is returned as-is while an independent clone is\n * stored, so mutating a miss result never corrupts the cache; every hit\n * returns a fresh clone of the stored entry. Callers must not rely on the\n * miss and hit paths returning the same object identity.\n */\n memoize<T>(queryKey: string, compute: () => T): { value: T; reused: boolean };\n}\n\n/** Validate one optional positive-integer cache bound, applying its default. */\nfunction requirePositiveCacheBound(\n name: string,\n value: number | undefined,\n fallback: number,\n): number {\n const bound = value ?? fallback;\n if (!Number.isInteger(bound) || bound < 1)\n throw new TypeError(`Invalid ${name} bound: ${String(value)}`);\n return bound;\n}\n\n/**\n * Fingerprint-keyed cache of workspace relationship assemblies and memoized\n * deterministic query results. One entry is retained per workspace key; a\n * changed fingerprint atomically replaces the entry and drops its memoized\n * results. Memoized values are structured-cloned on store and on read so\n * neither the producer nor any consumer can mutate cached state.\n */\nexport class WorkspaceGraphCache {\n readonly #entries = new Map<string, WorkspaceGraphCacheEntry>();\n readonly #maxResultsPerWorkspace: number;\n readonly #maxWorkspaces: number;\n\n /** Create a cache, optionally bounding workspaces and memoized results. */\n public constructor(\n options: { maxResultsPerWorkspace?: number; maxWorkspaces?: number } = {},\n ) {\n this.#maxResultsPerWorkspace = requirePositiveCacheBound(\n \"maxResultsPerWorkspace\",\n options.maxResultsPerWorkspace,\n DEFAULT_MAX_RESULTS_PER_WORKSPACE,\n );\n this.#maxWorkspaces = requirePositiveCacheBound(\n \"maxWorkspaces\",\n options.maxWorkspaces,\n DEFAULT_MAX_WORKSPACES,\n );\n }\n\n /**\n * Resolve the cached assembly for one workspace key and fingerprint,\n * building and storing it on miss. The returned lookup exposes snapshot-\n * scoped memoization for query results derived from the same assembly.\n */\n public lookup(\n key: string,\n fingerprint: string,\n build: () => WorkspaceRelationshipAssembly,\n ): WorkspaceGraphCacheLookup {\n let entry = this.#entries.get(key);\n let assemblyReused = true;\n if (entry === undefined || entry.fingerprint !== fingerprint) {\n entry = { fingerprint, assembly: build(), results: new Map() };\n assemblyReused = false;\n if (\n !this.#entries.has(key) &&\n this.#entries.size >= this.#maxWorkspaces\n ) {\n // Evict the least recently used workspace; every lookup refreshes\n // recency below, so insertion order tracks use order.\n this.#entries.delete(this.#entries.keys().next().value!);\n }\n }\n // Delete-and-reinsert keeps Map insertion order equal to recency order,\n // making workspace eviction genuinely least-recently-used.\n this.#entries.delete(key);\n this.#entries.set(key, entry);\n const resolved = entry;\n const maxResults = this.#maxResultsPerWorkspace;\n return {\n assembly: resolved.assembly,\n assemblyReused,\n fingerprint,\n memoize<T>(\n queryKey: string,\n compute: () => T,\n ): { value: T; reused: boolean } {\n const cached = resolved.results.get(queryKey);\n if (cached !== undefined || resolved.results.has(queryKey)) {\n // Refresh recency so eviction below is least-recently-used rather\n // than first-inserted.\n resolved.results.delete(queryKey);\n resolved.results.set(queryKey, cached);\n return { value: structuredClone(cached) as T, reused: true };\n }\n const value = compute();\n if (resolved.results.size >= maxResults) {\n // Evict the oldest memoized result; Map preserves insertion order.\n resolved.results.delete(resolved.results.keys().next().value!);\n }\n resolved.results.set(queryKey, structuredClone(value));\n return { value, reused: false };\n },\n };\n }\n\n /** Drop every cached workspace entry and memoized result. */\n public clear(): void {\n this.#entries.clear();\n }\n}\n\n/** Process-wide shared cache used by the CLI/MCP graph and deps adapters. */\nconst sharedCache = new WorkspaceGraphCache();\n\n/** Return the process-wide shared workspace graph cache. */\nexport function workspaceGraphCache(): WorkspaceGraphCache {\n return sharedCache;\n}\n\n/** Reset the process-wide shared workspace graph cache (tests and long-lived hosts). */\nexport function resetWorkspaceGraphCache(): void {\n sharedCache.clear();\n}\n", "/**\n * @module sdk/relationship-context\n *\n * Assembles one explainable, cursorable, token-bounded relationship context\n * packet for agents, custom tools, and presentation-layer adapters.\n */\nimport {\n createQueryFingerprint,\n encodeQueryCursor,\n resolveQueryCursorStart,\n} from \"./pagination.js\";\nimport {\n RelationshipGraph,\n RelationshipKindRegistry,\n createRelationshipKindRegistry,\n type RelationshipEdge,\n type RelationshipTraversalDirection,\n} from \"./relationships.js\";\n\n/** Semantic family explaining why a node or edge participates in graph context. */\nexport type RelationshipContextRole =\n | \"prerequisite\"\n | \"dependent\"\n | \"ancestor\"\n | \"descendant\"\n | \"provenance\"\n | \"related\";\n\n/**\n * Completeness marker for one graph-context packet.\n *\n * The exact in-memory kernel only produces \"complete\" and \"truncated\" today;\n * the remaining values are reserved so index-backed, sampled, or policy-redacted\n * providers can report their result quality through the same contract.\n */\nexport type RelationshipContextCompleteness =\n | \"complete\"\n | \"truncated\"\n | \"sampled\"\n | \"approximate\"\n | \"stale_index\"\n | \"redacted\";\n\n/** Caller-owned compact node details joined into graph context. */\nexport interface RelationshipContextNodeDetails {\n /** Stable graph node identifier. */\n id: string;\n /** Optional display title. */\n title?: string;\n /** Optional lifecycle status. */\n status?: string;\n /** Optional evidence pointers such as files, tests, or history ids. */\n evidence?: readonly string[];\n}\n\n/** One selected graph-context node with explainable inclusion. */\nexport interface RelationshipContextNode extends RelationshipContextNodeDetails {\n /** Shortest bounded distance from the root. */\n distance: number;\n /** Semantic family of this node relative to its discovery counterpart. */\n role: RelationshipContextRole;\n /** Node through which bounded traversal first discovered this node. */\n via: string;\n /** Concise deterministic reasons the node was selected. */\n reasons: string[];\n}\n\n/** Counts-first packet overview served before any row payload. */\nexport interface RelationshipContextSummary {\n /** Root node identifier. */\n rootId: string;\n /** Root lifecycle status when the caller supplied node details. */\n rootStatus?: string;\n /** Root-incident edge counts per semantic family under the active filters. */\n directEdges: Record<RelationshipContextRole, number>;\n /** Total root-incident edges under the active filters. */\n directTotal: number;\n /** Nodes discovered by the bounded traversal, excluding the root. */\n discoveredNodes: number;\n /** Nodes returned in this page. */\n returnedNodes: number;\n /** Edges returned in this page. */\n returnedEdges: number;\n /** Discovered nodes omitted by pagination, node, or token bounds. */\n omittedNodes: number;\n /** Qualifying edges omitted by edge or token bounds. */\n omittedEdges: number;\n /** Root evidence pointers promoted into the packet. */\n evidenceCount: number;\n /** Whether a continuation cursor is available. */\n hasMore: boolean;\n}\n\n/** Controls for bounded graph-context assembly. */\nexport interface RelationshipContextOptions {\n /** Traversal direction relative to each visited node. */\n direction?: RelationshipTraversalDirection;\n /** Optional registered kind filter. */\n kinds?: readonly string[];\n /** Maximum traversal depth. */\n maxDepth?: number;\n /** Maximum nodes returned in this page. */\n nodeLimit?: number;\n /** Maximum edges returned in this page. */\n edgeLimit?: number;\n /** Maximum estimated output tokens charged to rows and edges. */\n tokenBudget?: number;\n /** Opaque continuation from an equivalent query. */\n cursor?: string;\n /** Registry used to explain custom relationship semantics. */\n registry?: RelationshipKindRegistry;\n /** Abort signal checked during traversal. */\n signal?: AbortSignal;\n}\n\n/** Explainable graph context packet. */\nexport interface RelationshipContextResult {\n /** Root node details. */\n root: RelationshipContextNodeDetails;\n /** Counts-first overview of the packet. */\n summary: RelationshipContextSummary;\n /** Bounded related-node page. */\n nodes: RelationshipContextNode[];\n /** Bounded edges whose endpoints are present in the packet. */\n edges: RelationshipEdge[];\n /** Root evidence pointers promoted for immediate consumption. */\n evidence: string[];\n /** Completeness, continuation, and cost envelope. */\n meta: {\n exact: true;\n truncated: boolean;\n completeness: RelationshipContextCompleteness;\n nodeLimit: number;\n edgeLimit: number;\n tokenBudget: number;\n usedTokens: number;\n visitedNodes: number;\n inspectedEdges: number;\n omittedNodes: number;\n omittedEdges: number;\n nextCursor?: string;\n };\n}\n\ninterface DiscoveredNode {\n id: string;\n distance: number;\n via: string;\n role: RelationshipContextRole;\n}\n\n/** Deterministic priority used when one node matches several semantic families. */\nconst RELATIONSHIP_CONTEXT_ROLE_PRIORITY: readonly RelationshipContextRole[] = [\n \"prerequisite\",\n \"dependent\",\n \"ancestor\",\n \"descendant\",\n \"provenance\",\n \"related\",\n];\n\nconst tokenEncoder = new TextEncoder();\n\nfunction positiveInteger(\n value: number | undefined,\n fallback: number,\n field: string,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isInteger(resolved) || resolved < 1)\n throw new TypeError(`Relationship context ${field} must be positive`);\n return resolved;\n}\n\nfunction estimateTokens(value: unknown): number {\n return Math.max(\n 1,\n Math.ceil(tokenEncoder.encode(JSON.stringify(value)).byteLength / 4),\n );\n}\n\nfunction explainDirectEdge(\n edge: RelationshipEdge,\n node: string,\n registry: RelationshipKindRegistry,\n): RelationshipContextRole {\n const definition = registry.resolve(edge.kind);\n if (definition?.ordering) {\n // Legacy and JSON-parsed definitions may predate explicit precedence.\n const sourceFirst =\n (definition.precedence ?? \"source_before_target\") ===\n \"source_before_target\";\n const before = sourceFirst ? edge.source : edge.target;\n return node === before ? \"prerequisite\" : \"dependent\";\n }\n if (definition?.hierarchy) {\n // Legacy and JSON-parsed definitions may predate explicit hierarchy direction.\n const sourceIsParent =\n (definition.hierarchyDirection ?? \"source_parent\") === \"source_parent\";\n const parent = sourceIsParent ? edge.source : edge.target;\n return node === parent ? \"ancestor\" : \"descendant\";\n }\n if (edge.kind === \"discovered_from\" || edge.kind === \"incident_from\")\n return \"provenance\";\n return \"related\";\n}\n\nfunction directReasons(\n rootEdges: readonly RelationshipEdge[],\n root: string,\n node: string,\n registry: RelationshipKindRegistry,\n): RelationshipContextRole[] {\n const reasons = rootEdges\n .filter(\n (edge) =>\n (edge.source === root && edge.target === node) ||\n (edge.target === root && edge.source === node),\n )\n .map((edge) => explainDirectEdge(edge, node, registry));\n return [...new Set(reasons)].sort();\n}\n\n/** Pick the deterministic primary family when a node matches several. */\nfunction primaryRole(\n roles: readonly RelationshipContextRole[],\n): RelationshipContextRole {\n // Callers only pass non-empty classification sets drawn from the fixed\n // family list, so a priority match always exists.\n return RELATIONSHIP_CONTEXT_ROLE_PRIORITY.find((role) =>\n roles.includes(role),\n )!;\n}\n\nfunction discoverNodes(\n graph: RelationshipGraph,\n root: string,\n registry: RelationshipKindRegistry,\n options: RelationshipContextOptions,\n): {\n rows: DiscoveredNode[];\n visitedNodes: number;\n inspectedEdges: number;\n depthTruncated: boolean;\n} {\n const direction = options.direction ?? \"both\";\n const maxDepth = options.maxDepth ?? 3;\n if (!Number.isInteger(maxDepth) || maxDepth < 0)\n throw new TypeError(\"Relationship context maxDepth must be non-negative\");\n const seen = new Set([root]);\n const queue: { id: string; distance: number }[] = [\n { id: root, distance: 0 },\n ];\n const rows: DiscoveredNode[] = [];\n let inspectedEdges = 0;\n let depthTruncated = false;\n for (let index = 0; index < queue.length; index += 1) {\n options.signal?.throwIfAborted();\n const current = queue[index]!;\n if (current.distance >= maxDepth && depthTruncated) continue;\n const adjacent = graph.neighborEdges(current.id, {\n direction,\n kinds: options.kinds,\n signal: options.signal,\n });\n inspectedEdges += adjacent.meta.inspectedEdges;\n if (current.distance >= maxDepth) {\n if (adjacent.value.some((row) => !seen.has(row.id))) depthTruncated = true;\n continue;\n }\n for (const { id, edge } of adjacent.value) {\n if (seen.has(id)) continue;\n seen.add(id);\n const row = {\n id,\n distance: current.distance + 1,\n via: current.id,\n role: explainDirectEdge(edge, id, registry),\n };\n rows.push(row);\n queue.push(row);\n }\n }\n rows.sort(\n (left, right) =>\n left.distance - right.distance || left.id.localeCompare(right.id),\n );\n return {\n rows,\n visitedNodes: queue.length,\n inspectedEdges,\n depthTruncated,\n };\n}\n\n/** Count root-incident edges per semantic family under the active filters. */\nfunction summarizeDirectEdges(\n graph: RelationshipGraph,\n root: string,\n registry: RelationshipKindRegistry,\n options: RelationshipContextOptions,\n): {\n directEdges: Record<RelationshipContextRole, number>;\n directTotal: number;\n rootEdges: RelationshipEdge[];\n} {\n const directEdges: Record<RelationshipContextRole, number> = {\n prerequisite: 0,\n dependent: 0,\n ancestor: 0,\n descendant: 0,\n provenance: 0,\n related: 0,\n };\n const rows = graph.neighborEdges(root, {\n direction: options.direction ?? \"both\",\n kinds: options.kinds,\n signal: options.signal,\n }).value;\n for (const { id, edge } of rows)\n directEdges[explainDirectEdge(edge, id, registry)] += 1;\n return {\n directEdges,\n directTotal: rows.length,\n rootEdges: rows.map(({ edge }) => edge),\n };\n}\n\nfunction selectContextNodes(params: {\n candidates: readonly DiscoveredNode[];\n details: ReadonlyMap<string, RelationshipContextNodeDetails>;\n rootEdges: readonly RelationshipEdge[];\n rootId: string;\n registry: RelationshipKindRegistry;\n nodeLimit: number;\n tokenBudget: number;\n initialTokens: number;\n}): { nodes: RelationshipContextNode[]; usedTokens: number } {\n const nodes: RelationshipContextNode[] = [];\n let usedTokens = params.initialTokens;\n for (const candidate of params.candidates) {\n if (nodes.length >= params.nodeLimit) break;\n const direct =\n candidate.distance === 1\n ? directReasons(\n params.rootEdges,\n params.rootId,\n candidate.id,\n params.registry,\n )\n : [];\n const node: RelationshipContextNode = {\n ...(params.details.get(candidate.id) ?? { id: candidate.id }),\n distance: candidate.distance,\n role: direct.length > 0 ? primaryRole(direct) : candidate.role,\n via: candidate.via,\n reasons:\n direct.length > 0\n ? direct\n : [\n `${candidate.role} via ${candidate.via} (depth ${candidate.distance})`,\n ],\n };\n const cost = estimateTokens(node);\n if (usedTokens + cost > params.tokenBudget) break;\n nodes.push(node);\n usedTokens += cost;\n }\n if (params.candidates.length > 0 && nodes.length === 0)\n throw new TypeError(\"Relationship context tokenBudget cannot fit one node\");\n return { nodes, usedTokens };\n}\n\nfunction selectContextEdges(params: {\n graph: RelationshipGraph;\n included: ReadonlySet<string>;\n options: RelationshipContextOptions;\n registry: RelationshipKindRegistry;\n edgeLimit: number;\n tokenBudget: number;\n initialTokens: number;\n}): {\n edges: RelationshipEdge[];\n usedTokens: number;\n candidateCount: number;\n} {\n const kinds = params.options.kinds\n ? new Set(\n params.options.kinds.map((kind) => params.registry.require(kind).kind),\n )\n : undefined;\n const candidates = params.graph\n .edges()\n .filter(\n (edge) => {\n if (\n !params.included.has(edge.source) ||\n !params.included.has(edge.target)\n )\n return false;\n if (kinds === undefined || kinds.has(edge.kind)) return true;\n const inverse = params.registry.resolve(edge.kind)?.inverse;\n return inverse !== undefined && kinds.has(inverse);\n },\n );\n const edges: RelationshipEdge[] = [];\n let usedTokens = params.initialTokens;\n for (const edge of candidates) {\n if (edges.length >= params.edgeLimit) break;\n const cost = estimateTokens(edge);\n if (usedTokens + cost > params.tokenBudget) break;\n edges.push(edge);\n usedTokens += cost;\n }\n return { edges, usedTokens, candidateCount: candidates.length };\n}\n\n/** Build one deterministic bounded graph-context packet with continuation. */\nexport function buildRelationshipContext(\n graph: RelationshipGraph,\n rootId: string,\n details: readonly RelationshipContextNodeDetails[],\n options: RelationshipContextOptions = {},\n): RelationshipContextResult {\n if (!graph.nodes().includes(rootId))\n throw new TypeError(`Relationship node not found: ${rootId}`);\n const nodeLimit = positiveInteger(options.nodeLimit, 20, \"nodeLimit\");\n const edgeLimit = positiveInteger(options.edgeLimit, 40, \"edgeLimit\");\n const tokenBudget = positiveInteger(options.tokenBudget, 1200, \"tokenBudget\");\n const registry = options.registry ?? createRelationshipKindRegistry();\n const byId = new Map(details.map((detail) => [detail.id, detail]));\n const rootDetails: RelationshipContextNodeDetails = byId.get(rootId) ?? {\n id: rootId,\n };\n const { evidence: rootEvidence = [], ...root } = rootDetails;\n const evidence = [...rootEvidence];\n const discovery = discoverNodes(graph, rootId, registry, options);\n const { rootEdges, ...directSummary } = summarizeDirectEdges(\n graph,\n rootId,\n registry,\n options,\n );\n const fingerprint = createQueryFingerprint(\"relationship-context\", {\n rootId,\n direction: options.direction ?? \"both\",\n kinds: [...(options.kinds ?? [])].sort(),\n maxDepth: options.maxDepth ?? 3,\n });\n const pageStart = resolveQueryCursorStart(\n discovery.rows,\n options.cursor,\n fingerprint,\n ({ id }) => id,\n );\n const candidates = discovery.rows.slice(pageStart);\n const initialTokens = estimateTokens(root) + estimateTokens(evidence);\n if (initialTokens > tokenBudget)\n throw new TypeError(\n \"Relationship context tokenBudget cannot fit root and evidence\",\n );\n const nodeSelection = selectContextNodes({\n candidates,\n details: byId,\n rootEdges,\n rootId,\n registry,\n nodeLimit,\n tokenBudget,\n initialTokens,\n });\n const { nodes } = nodeSelection;\n\n const included = new Set([rootId, ...nodes.map(({ id }) => id)]);\n const edgeSelection = selectContextEdges({\n graph,\n included,\n options,\n registry,\n edgeLimit,\n tokenBudget,\n initialTokens: nodeSelection.usedTokens,\n });\n const { edges, usedTokens } = edgeSelection;\n\n const consumed = pageStart + nodes.length;\n const hasMoreNodes = consumed < discovery.rows.length;\n const lastNode = nodes.at(-1);\n const omittedEdges = edgeSelection.candidateCount - edges.length;\n const truncated =\n discovery.depthTruncated || hasMoreNodes || omittedEdges > 0;\n const summary: RelationshipContextSummary = {\n rootId,\n ...(root.status === undefined ? {} : { rootStatus: root.status }),\n ...directSummary,\n discoveredNodes: discovery.rows.length,\n returnedNodes: nodes.length,\n returnedEdges: edges.length,\n omittedNodes: discovery.rows.length - consumed,\n omittedEdges,\n evidenceCount: evidence.length,\n hasMore: hasMoreNodes,\n };\n return {\n root,\n summary,\n nodes,\n edges,\n evidence,\n meta: {\n exact: true,\n truncated,\n completeness: truncated ? \"truncated\" : \"complete\",\n nodeLimit,\n edgeLimit,\n tokenBudget,\n usedTokens,\n visitedNodes: discovery.visitedNodes,\n inspectedEdges: discovery.inspectedEdges,\n omittedNodes: discovery.rows.length - consumed,\n omittedEdges,\n ...(hasMoreNodes && lastNode\n ? {\n nextCursor: encodeQueryCursor(\n fingerprint,\n lastNode.id,\n consumed - 1,\n ),\n }\n : {}),\n },\n };\n}\n", "/**\n * @module sdk/dependencies\n *\n * Implements the pm deps command surface and its agent-facing runtime behavior.\n */\nimport { getActiveExtensionRegistrations } from \"../core/extensions/index.js\";\nimport { pathExists } from \"../core/fs/fs-utils.js\";\nimport { resolveItemTypeRegistry } from \"../core/item/type-registry.js\";\nimport { isTerminalStatus } from \"../core/item/status.js\";\nimport { resolveRuntimeStatusRegistry } from \"../core/schema/runtime-schema.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 {\n listAllItemMetadataLight,\n locateItem,\n readLocatedItem,\n} from \"../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../core/store/paths.js\";\nimport { readSettings } from \"../core/store/settings.js\";\nimport type {\n Dependency,\n ItemMetadata,\n ItemStatus,\n ItemType,\n} from \"../types/index.js\";\nimport {\n assembleWorkspaceRelationshipGraph,\n collectDanglingDependencyReferences,\n type DanglingDependencyReference,\n type WorkspaceRelationshipAssembly,\n} from \"./graph/assembly.js\";\nimport {\n computeWorkspaceGraphFingerprint,\n workspaceGraphCache,\n} from \"./graph/cache.js\";\nimport {\n buildRelationshipContext,\n type RelationshipContextOptions,\n type RelationshipContextResult,\n} from \"./relationship-context.js\";\nimport { createRelationshipKindRegistry } from \"./relationships.js\";\n\n/** Supported values accepted by the deps format contract. */\nexport const DEPS_FORMAT_VALUES = [\"tree\", \"graph\", \"context\"] as const;\n/** Restricts deps format values accepted by command, SDK, and storage contracts. */\nexport type DepsFormat = (typeof DEPS_FORMAT_VALUES)[number];\n/** Supported values accepted by the deps collapse contract. */\nexport const DEPS_COLLAPSE_VALUES = [\"none\", \"repeated\"] as const;\n/** Restricts deps collapse mode values accepted by command, SDK, and storage contracts. */\nexport type DepsCollapseMode = (typeof DEPS_COLLAPSE_VALUES)[number];\n/** Supported values accepted by the deps graph-context direction contract. */\nexport const DEPS_DIRECTION_VALUES = [\"outgoing\", \"incoming\", \"both\"] as const;\n/** Restricts deps traversal-direction values accepted by command, SDK, and storage contracts. */\nexport type DepsDirection = (typeof DEPS_DIRECTION_VALUES)[number];\n\n/** Documents the deps command options payload exchanged by command, SDK, and package integrations. */\nexport interface DepsCommandOptions {\n /** Value that configures or reports format for this contract. */\n format?: string;\n /** Value that configures or reports max depth for this contract. */\n maxDepth?: string | number;\n /** Value that configures or reports collapse for this contract. */\n collapse?: string;\n /** Value that configures or reports summary for this contract. */\n summary?: boolean;\n /** Maximum graph-context nodes returned. */\n nodeLimit?: string | number;\n /** Maximum graph-context edges and enumerated missing-reference rows returned. */\n edgeLimit?: string | number;\n /** Maximum estimated graph-context output tokens. */\n tokenBudget?: string | number;\n /** Opaque continuation cursor for graph-context output. */\n cursor?: string;\n /** Graph-context traversal direction relative to each visited node. */\n direction?: string;\n /** Registered relationship kinds narrowing graph-context traversal. */\n kind?: string | string[];\n}\n\ninterface IndexedItem {\n id: string;\n title: string;\n type: ItemType;\n status: ItemStatus;\n dependencies: IndexedDependency[];\n}\n\ninterface IndexedDependency {\n id: string;\n kind: string;\n}\n\n/** Documents the deps tree node payload exchanged by command, SDK, and package integrations. */\nexport interface DepsTreeNode {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports title for this contract. */\n title?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type?: ItemType;\n /** Lifecycle state reported for status. */\n status?: ItemStatus;\n /** Value that configures or reports via for this contract. */\n via?: string;\n /** Value that configures or reports missing for this contract. */\n missing: boolean;\n /** Value that configures or reports cycle for this contract. */\n cycle: boolean;\n /** Value that configures or reports truncated for this contract. */\n truncated?: boolean;\n /** Value that configures or reports collapsed for this contract. */\n collapsed?: boolean;\n /** Value that configures or reports dependencies for this contract. */\n dependencies: DepsTreeNode[];\n}\n\n/** Documents the deps graph node payload exchanged by command, SDK, and package integrations. */\nexport interface DepsGraphNode {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports title for this contract. */\n title?: string;\n /** Schema type that determines the shape and validation rules for this value. */\n type?: ItemType;\n /** Lifecycle state reported for status. */\n status?: ItemStatus;\n /** Value that configures or reports missing for this contract. */\n missing: boolean;\n}\n\n/** Documents the deps graph edge payload exchanged by command, SDK, and package integrations. */\nexport interface DepsGraphEdge {\n /** Value that configures or reports from for this contract. */\n from: string;\n /** Value that configures or reports to for this contract. */\n to: string;\n /** Value that configures or reports kind for this contract. */\n kind: string;\n}\n\n/** Documents the deps graph result payload exchanged by command, SDK, and package integrations. */\nexport interface DepsGraphResult {\n /** Value that configures or reports root id for this contract. */\n root_id: string;\n /** Value that configures or reports nodes for this contract. */\n nodes: DepsGraphNode[];\n /** Value that configures or reports edges for this contract. */\n edges: DepsGraphEdge[];\n /** Value that configures or reports missing ids for this contract. */\n missing_ids: string[];\n}\n\n/** Documents the deps result payload exchanged by command, SDK, and package integrations. */\nexport interface DepsResult {\n /** Stable identifier used to reference this record across commands and storage. */\n id: string;\n /** Value that configures or reports format for this contract. */\n format: DepsFormat;\n /** Number of node entries represented by this result. */\n node_count: number;\n /** Number of edge entries represented by this result. */\n edge_count: number;\n /**\n * Number of missing entries represented by this result.\n *\n * Tree and graph formats count missing nodes encountered while walking\n * dependency edges; context format counts missing nodes reachable within the\n * same bounded traversal (direction, kinds, and depth) that produced the\n * packet, independent of node or token pagination, so the two formats agree\n * for equal traversal parameters over the dependency edge family.\n */\n missing_count: number;\n /** Traversal scope documenting the missing_count semantics for context format. */\n missing_scope?: \"traversal\";\n /** Total dangling references declared into the traversed missing nodes. */\n missing_reference_count?: number;\n /** Bounded enumeration of dangling references, capped by the context edge limit. */\n missing_references?: DanglingDependencyReference[];\n /** Value that configures or reports tree for this contract. */\n tree?: DepsTreeNode;\n /** Value that configures or reports graph for this contract. */\n graph?: DepsGraphResult;\n /** Explainable bounded graph-context projection. */\n context?: RelationshipContextResult;\n}\n\nfunction parseFormat(raw: string | undefined): DepsFormat {\n const candidate = raw?.trim().toLowerCase() ?? \"tree\";\n if ((DEPS_FORMAT_VALUES as readonly string[]).includes(candidate)) {\n return candidate as DepsFormat;\n }\n throw new PmCliError(\n `Invalid --format value \"${raw}\". Use \"tree\", \"graph\", or \"context\".`,\n EXIT_CODE.USAGE,\n );\n}\n\n/** Parse one positive-integer graph bound, failing fast with the offending flag name. */\nexport function parsePositiveInteger(raw: string | number | undefined, flag: string): number | undefined {\n if (raw === undefined) return undefined;\n const value = typeof raw === \"number\" ? raw : Number(raw.trim());\n if (!Number.isInteger(value) || value < 1)\n throw new PmCliError(`Invalid --${flag} value \"${raw}\". Use a positive integer.`, EXIT_CODE.USAGE);\n return value;\n}\n\n/** Parse the shared non-negative --max-depth traversal bound. */\nexport function parseMaxDepth(raw: string | number | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const normalized = typeof raw === \"number\" ? raw : Number(raw.trim());\n if (!Number.isInteger(normalized) || normalized < 0) {\n throw new PmCliError(\n `Invalid --max-depth value \"${raw}\". Use a non-negative integer.`,\n EXIT_CODE.USAGE,\n );\n }\n return normalized;\n}\n\nfunction parseCollapse(raw: string | undefined): DepsCollapseMode {\n const candidate = raw?.trim().toLowerCase() ?? \"none\";\n if ((DEPS_COLLAPSE_VALUES as readonly string[]).includes(candidate)) {\n return candidate as DepsCollapseMode;\n }\n throw new PmCliError(\n `Invalid --collapse value \"${raw}\". Use \"none\" or \"repeated\".`,\n EXIT_CODE.USAGE,\n );\n}\n\n/** Parse the shared graph traversal --direction value, defaulting to \"both\". */\nexport function parseDirection(raw: string | undefined): DepsDirection {\n const candidate = raw?.trim().toLowerCase() ?? \"both\";\n if ((DEPS_DIRECTION_VALUES as readonly string[]).includes(candidate)) {\n return candidate as DepsDirection;\n }\n throw new PmCliError(\n `Invalid --direction value \"${raw}\". Use \"outgoing\", \"incoming\", or \"both\".`,\n EXIT_CODE.USAGE,\n );\n}\n\n/**\n * Normalize repeatable and comma-separated --kind values against the built-in\n * relationship ontology, failing fast on unknown kinds instead of silently\n * matching nothing (the multi-value filter-grammar trap tracked by pm-gknu).\n */\nexport function parseKinds(raw: string | string[] | undefined): string[] | undefined {\n if (raw === undefined) return undefined;\n const registry = createRelationshipKindRegistry();\n const values = (Array.isArray(raw) ? raw : [raw])\n .flatMap((value) => value.split(\",\"))\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n if (values.length === 0) return undefined;\n const kinds = new Set<string>();\n for (const value of values) {\n const definition = registry.resolve(value);\n if (!definition) {\n const known = registry\n .list()\n .map((entry) => entry.kind)\n .join(\", \");\n throw new PmCliError(\n `Invalid --kind value \"${value}\". Registered kinds: ${known}.`,\n EXIT_CODE.USAGE,\n );\n }\n kinds.add(definition.kind);\n }\n return [...kinds].sort();\n}\n\nfunction normalizeDependencies(\n dependencies: Dependency[] | undefined,\n): IndexedDependency[] {\n if (!dependencies || dependencies.length === 0) {\n return [];\n }\n const sorted = dependencies.map(({ id, kind }) => ({\n id: id.trim(),\n kind: kind.trim().toLowerCase(),\n })).sort((left, right) => {\n const byKind = left.kind.localeCompare(right.kind);\n if (byKind !== 0) return byKind;\n return left.id.localeCompare(right.id);\n });\n const deduped = new Map<string, IndexedDependency>();\n for (const dependency of sorted) {\n const key = `${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;\n if (!deduped.has(key)) {\n deduped.set(key, { id: dependency.id, kind: dependency.kind });\n }\n }\n return [...deduped.values()];\n}\n\nfunction toIndexedItem(item: ItemMetadata): IndexedItem {\n return {\n id: item.id,\n title: item.title,\n type: item.type,\n status: item.status,\n dependencies: normalizeDependencies(item.dependencies),\n };\n}\n\nfunction toTreeNode(\n id: string,\n index: Map<string, IndexedItem>,\n lineage: Set<string>,\n maxDepth: number | undefined,\n collapse: DepsCollapseMode,\n expanded: Set<string>,\n depth = 0,\n via?: string,\n): DepsTreeNode {\n const lookupId = id.trim().toLowerCase();\n const item = index.get(lookupId);\n const baseNode: DepsTreeNode = {\n id: item?.id ?? id,\n title: item?.title,\n type: item?.type,\n status: item?.status,\n via,\n missing: !item,\n cycle: lineage.has(lookupId),\n dependencies: [],\n };\n if (!item || baseNode.cycle) {\n return baseNode;\n }\n if (maxDepth !== undefined && depth >= maxDepth) {\n if (item.dependencies.length > 0) {\n baseNode.truncated = true;\n }\n return baseNode;\n }\n if (collapse === \"repeated\" && expanded.has(lookupId)) {\n baseNode.collapsed = true;\n return baseNode;\n }\n if (collapse === \"repeated\") {\n expanded.add(lookupId);\n }\n const nextLineage = new Set(lineage);\n nextLineage.add(lookupId);\n baseNode.dependencies = item.dependencies.map((dependency) =>\n toTreeNode(\n dependency.id,\n index,\n nextLineage,\n maxDepth,\n collapse,\n expanded,\n depth + 1,\n dependency.kind,\n ),\n );\n return baseNode;\n}\n\nfunction mergeGraphNode(\n existing: DepsGraphNode | undefined,\n candidate: DepsGraphNode,\n): DepsGraphNode {\n if (!existing) {\n return candidate;\n }\n /* c8 ignore start -- defensive: mixed missing/non-missing duplicates only occur in malformed synthetic trees. */\n if (existing.missing && !candidate.missing) return candidate;\n /* c8 ignore stop */\n return {\n ...existing,\n title: existing.title ?? candidate.title,\n type: existing.type ?? candidate.type,\n status: existing.status ?? candidate.status,\n };\n}\n\nfunction toGraph(root: DepsTreeNode): DepsGraphResult {\n const nodesById = new Map<string, DepsGraphNode>();\n const edgesByKey = new Map<string, DepsGraphEdge>();\n\n const visit = (node: DepsTreeNode): void => {\n nodesById.set(\n node.id,\n mergeGraphNode(nodesById.get(node.id), {\n id: node.id,\n title: node.title,\n type: node.type,\n status: node.status,\n missing: node.missing,\n }),\n );\n for (const child of node.dependencies) {\n nodesById.set(\n child.id,\n mergeGraphNode(nodesById.get(child.id), {\n id: child.id,\n title: child.title,\n type: child.type,\n status: child.status,\n missing: child.missing,\n }),\n );\n /* c8 ignore start -- legacy malformed dependency payloads may omit kind/via. */\n const relationKind = child.via ?? \"related\";\n const edgeKey = `${node.id}::${child.id}::${relationKind}`;\n if (!edgesByKey.has(edgeKey)) {\n edgesByKey.set(edgeKey, {\n from: node.id,\n to: child.id,\n kind: relationKind,\n });\n }\n /* c8 ignore stop */\n if (!child.cycle) {\n visit(child);\n }\n }\n };\n\n visit(root);\n\n const nodes = [...nodesById.values()].sort((left, right) =>\n left.id.localeCompare(right.id),\n );\n const edges = [...edgesByKey.values()].sort((left, right) => {\n const byFrom = left.from.localeCompare(right.from);\n if (byFrom !== 0) return byFrom;\n const byTo = left.to.localeCompare(right.to);\n if (byTo !== 0) return byTo;\n return left.kind.localeCompare(right.kind);\n });\n const missingIds = nodes\n .filter((node) => node.missing)\n .map((node) => node.id);\n return {\n root_id: root.id,\n nodes,\n edges,\n missing_ids: missingIds,\n };\n}\n\n/** Count a dependency result without allocating its potentially exponential tree payload. */\nfunction countDependencyGraph(\n rootId: string,\n index: Map<string, IndexedItem>,\n maxDepth: number | undefined,\n): Pick<DepsResult, \"node_count\" | \"edge_count\" | \"missing_count\"> {\n const nodeIds = new Set<string>();\n const edgeKeys = new Set<string>();\n const missingIds = new Set<string>();\n const expanded = new Set<string>();\n const pending = [{ id: rootId, depth: 0 }];\n let pendingIndex = 0;\n while (pendingIndex < pending.length) {\n const current = pending[pendingIndex++]!;\n const lookupId = current.id.trim().toLowerCase();\n nodeIds.add(lookupId);\n const item = index.get(lookupId);\n if (!item) {\n missingIds.add(lookupId);\n continue;\n }\n if (maxDepth !== undefined && current.depth >= maxDepth) {\n continue;\n }\n if (expanded.has(lookupId)) {\n continue;\n }\n expanded.add(lookupId);\n for (const dependency of item.dependencies) {\n edgeKeys.add(\n `${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`,\n );\n pending.push({ id: dependency.id, depth: current.depth + 1 });\n }\n }\n return {\n node_count: nodeIds.size,\n edge_count: edgeKeys.size,\n missing_count: missingIds.size,\n };\n}\n\n/** Options subset consumed by the deps graph-context projection. */\ntype DepsContextOptions = Pick<\n DepsCommandOptions,\n | \"maxDepth\"\n | \"nodeLimit\"\n | \"edgeLimit\"\n | \"tokenBudget\"\n | \"cursor\"\n | \"direction\"\n | \"kind\"\n>;\n\n/** Parse CLI-compatible deps context options once for packet and closure parity. */\nfunction parseDepsContextOptions(\n options: DepsContextOptions,\n): RelationshipContextOptions {\n const maxDepth = parseMaxDepth(options.maxDepth);\n const nodeLimit = parsePositiveInteger(options.nodeLimit, \"node-limit\");\n const edgeLimit = parsePositiveInteger(options.edgeLimit, \"edge-limit\");\n const tokenBudget = parsePositiveInteger(options.tokenBudget, \"token-budget\");\n const kinds = parseKinds(options.kind);\n return {\n direction: parseDirection(options.direction),\n ...(kinds === undefined ? {} : { kinds }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(nodeLimit === undefined ? {} : { nodeLimit }),\n ...(edgeLimit === undefined ? {} : { edgeLimit }),\n ...(tokenBudget === undefined ? {} : { tokenBudget }),\n ...(options.cursor?.trim() ? { cursor: options.cursor.trim() } : {}),\n };\n}\n\n/** Build one bounded context packet from an assembled deps relationship graph. */\nfunction buildContextFromAssembly(\n assembly: WorkspaceRelationshipAssembly,\n rootId: string,\n options: RelationshipContextOptions,\n rootEvidence: readonly string[],\n): RelationshipContextResult {\n return buildRelationshipContext(\n assembly.graph,\n rootId,\n assembly.details.map((detail) =>\n detail.id === rootId && rootEvidence.length > 0\n ? { ...detail, evidence: rootEvidence }\n : detail,\n ),\n options,\n );\n}\n\n/** Build the SDK-backed bounded relationship-context projection for deps. */\nexport function buildDepsRelationshipContext(\n rootId: string,\n items: readonly ItemMetadata[],\n options: DepsContextOptions,\n rootEvidence: readonly string[] = [],\n): RelationshipContextResult {\n return buildContextFromAssembly(\n assembleWorkspaceRelationshipGraph(items),\n rootId,\n parseDepsContextOptions(options),\n rootEvidence,\n );\n}\n\n/** Append up to `limit` labeled pointers from one linked collection. */\nfunction appendEvidencePointers(\n evidence: string[],\n label: string,\n values: readonly (string | undefined)[],\n limit: number,\n): void {\n for (const value of values.slice(0, limit)) {\n const trimmed = value?.trim();\n if (trimmed) evidence.push(`${label}:${trimmed}`);\n }\n}\n\n/**\n * Load bounded root evidence pointers (linked files, tests, docs, and\n * annotation counts) so the context packet answers \"where is the proof\"\n * without a follow-up item read.\n */\nasync function collectRootEvidence(\n pmRoot: string,\n id: string,\n settings: Awaited<ReturnType<typeof readSettings>>,\n typeToFolder: Record<string, string>,\n): Promise<string[]> {\n const located = await locateItem(\n pmRoot,\n id,\n settings.id_prefix,\n settings.item_format,\n typeToFolder,\n );\n // The caller already resolved the root against the light index, so a miss\n // can only happen when storage mutates mid-read; degrade to no evidence.\n /* c8 ignore start -- defensive: unreachable without a concurrent delete between the index scan and this read. */\n if (!located) return [];\n /* c8 ignore stop */\n const { document } = await readLocatedItem(located, {\n schema: settings.schema,\n });\n const metadata = document.metadata;\n const files = metadata.files ?? [];\n const tests = metadata.tests ?? [];\n const docs = metadata.docs ?? [];\n const counts = [\n [\"files\", files.length],\n [\"tests\", tests.length],\n [\"docs\", docs.length],\n [\"comments\", (metadata.comments ?? []).length],\n [\"notes\", (metadata.notes ?? []).length],\n [\"learnings\", (metadata.learnings ?? []).length],\n ] as const;\n if (counts.every(([, count]) => count === 0)) return [];\n const evidence = [\n `linked:${counts.map(([key, count]) => `${key}=${count}`).join(\",\")}`,\n ];\n appendEvidencePointers(evidence, \"file\", files.map((file) => file.path), 3);\n appendEvidencePointers(\n evidence,\n \"test\",\n tests.map((test) => test.command ?? test.path),\n 2,\n );\n appendEvidencePointers(evidence, \"doc\", docs.map((doc) => doc.path), 2);\n return evidence;\n}\n\n/** Assemble the context-format deps result with traversal-scoped missing enumeration. */\nfunction buildContextDepsResult(params: {\n assembly: WorkspaceRelationshipAssembly;\n canonicalId: string;\n options: DepsCommandOptions;\n rootEvidence: readonly string[];\n summaryOnly: boolean;\n}): DepsResult {\n const { assembly, canonicalId, options, rootEvidence, summaryOnly } = params;\n const contextOptions = parseDepsContextOptions(options);\n const context = buildContextFromAssembly(\n assembly,\n canonicalId,\n contextOptions,\n rootEvidence,\n );\n const reachable = assembly.graph.closure(canonicalId, {\n direction: contextOptions.direction,\n ...(contextOptions.kinds === undefined\n ? {}\n : { kinds: contextOptions.kinds }),\n maxDepth: contextOptions.maxDepth ?? 3,\n });\n const missingReachable = reachable.value.filter((nodeId) =>\n assembly.missingIdSet.has(nodeId.toLowerCase()),\n );\n const missingReachableSet = new Set(\n missingReachable.map((nodeId) => nodeId.toLowerCase()),\n );\n const relationshipRegistry = assembly.graph.registry();\n const filteredKinds = contextOptions.kinds\n ? new Set(\n contextOptions.kinds.map(\n (kind) => relationshipRegistry.require(kind).kind,\n ),\n )\n : undefined;\n const packetIds = new Set([canonicalId, ...reachable.value]);\n const missingReferences = [\n ...assembly.dangling.active,\n ...assembly.dangling.legacy_terminal,\n ].filter((row) => {\n if (\n row.no_active_blocker_sentinel ||\n !missingReachableSet.has(row.target_id.trim().toLowerCase()) ||\n !packetIds.has(row.holder_id)\n )\n return false;\n if (filteredKinds === undefined) return true;\n const definition = relationshipRegistry.resolve(row.kind);\n return (\n definition !== undefined &&\n (filteredKinds.has(definition.kind) ||\n (definition.inverse !== undefined &&\n filteredKinds.has(definition.inverse)))\n );\n });\n const referenceLimit = contextOptions.edgeLimit ?? 40;\n return {\n id: canonicalId,\n format: \"context\",\n node_count: context.nodes.length + 1,\n edge_count: context.edges.length,\n missing_count: missingReachable.length,\n missing_scope: \"traversal\",\n missing_reference_count: missingReferences.length,\n ...(summaryOnly\n ? {}\n : {\n missing_references: missingReferences.slice(0, referenceLimit),\n context,\n }),\n };\n}\n\n/** Implements run deps for the public runtime surface of this module. */\nexport async function runDeps(\n id: string,\n options: DepsCommandOptions,\n global: GlobalOptions,\n): Promise<DepsResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(\n `Tracker is not initialized at ${pmRoot}. Run pm init first.`,\n EXIT_CODE.NOT_FOUND,\n );\n }\n const format = parseFormat(options.format);\n const maxDepth = parseMaxDepth(options.maxDepth);\n const collapse = parseCollapse(options.collapse);\n const summaryOnly = options.summary === true;\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n getActiveExtensionRegistrations(),\n );\n const items = await listAllItemMetadataLight(\n pmRoot,\n settings.item_format,\n typeRegistry.type_to_folder,\n undefined,\n settings.schema,\n );\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const index = new Map(\n items.map((item) => [item.id.trim().toLowerCase(), toIndexedItem(item)]),\n );\n const dangling = collectDanglingDependencyReferences(\n items,\n (status) => isTerminalStatus(status, statusRegistry),\n );\n for (const reference of [...dangling.active, ...dangling.legacy_terminal]) {\n const holder = index.get(reference.holder_id.trim().toLowerCase());\n const referenceKind = reference.kind.trim().toLowerCase();\n if (\n holder &&\n !holder.dependencies.some(\n (dependency) =>\n dependency.id.trim().toLowerCase() === reference.target_id.trim().toLowerCase() &&\n dependency.kind === referenceKind,\n )\n ) {\n holder.dependencies.push({ id: reference.target_id, kind: referenceKind });\n }\n }\n if (!index.has(id.trim().toLowerCase())) {\n throw new PmCliError(`Item ${id} not found`, EXIT_CODE.NOT_FOUND);\n }\n\n if (format === \"context\") {\n const canonicalId = index.get(id.trim().toLowerCase())!.id;\n const rootEvidence = summaryOnly\n ? []\n : await collectRootEvidence(\n pmRoot,\n canonicalId,\n settings,\n typeRegistry.type_to_folder,\n );\n const isTerminal = (status: ItemStatus): boolean =>\n isTerminalStatus(status, statusRegistry);\n // Reuse the fingerprint-keyed shared cache so bounded context packets in\n // long-lived hosts stop paying full-workspace assembly on every call.\n const lookup = workspaceGraphCache().lookup(\n pmRoot,\n computeWorkspaceGraphFingerprint(items, isTerminal),\n () => assembleWorkspaceRelationshipGraph(items, isTerminal),\n );\n return buildContextDepsResult({\n assembly: lookup.assembly,\n canonicalId,\n options,\n rootEvidence,\n summaryOnly,\n });\n }\n\n if (summaryOnly) {\n return {\n id,\n format,\n ...countDependencyGraph(id, index, maxDepth),\n };\n }\n\n const tree = toTreeNode(\n id,\n index,\n new Set<string>(),\n maxDepth,\n collapse,\n new Set<string>(),\n );\n const graph = toGraph(tree);\n const baseResult = {\n id,\n format,\n node_count: graph.nodes.length,\n edge_count: graph.edges.length,\n missing_count: graph.missing_ids.length,\n };\n if (format === \"tree\") {\n return {\n ...baseResult,\n tree,\n };\n }\n return {\n ...baseResult,\n graph,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;;;;;;;;AAQ3B,IAAM,oCAAoC;AAE1C,IAAM,yBAAyB;AAa/B,SAAS,gBACP,MACA,YAA2C;AAE3C,QAAM,gBAAgB,KAAK,gBAAgB,CAAA,GACxC,IAAI,CAAC,kBAAiB;AAIrB,QAAI,OAAO,kBAAkB,YAAY,kBAAkB;AACzD,aAAO;AACT,UAAM,aAAa;AACnB,WAAO,GAAG,OAAO,WAAW,SAAS,WAAW,WAAW,OAAO,SAAS,IACzE,OAAO,WAAW,OAAO,WAAW,WAAW,KAAK,EACtD;EACF,CAAC,EACA,KAAI,EACJ,KAAK,GAAG;AACX,SAAO;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,WAAW,KAAK,MAAM,IAAI,MAAM;IAChC,KAAK,UAAU;IACf,KAAK,cAAc;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nC,QACA,iCAAiC,OAAO,UAAU,GAClD,MAAM,mCAAmC,OAAO,UAAU,CAAC;AAE7D,WAAO,uBAAuB;MAC5B,UAAU,OAAO;MACjB;MACA;MACA;MACA;KACD;EACH;AAEA,MAAI,aAAa;AACf,WAAO;MACL;MACA;MACA,GAAG,qBAAqB,IAAI,OAAO,QAAQ;;EAE/C;AAEA,QAAM,OAAO,WACX,IACA,OACA,oBAAI,IAAG,GACP,UACA,UACA,oBAAI,IAAG,CAAU;AAEnB,QAAM,QAAQ,QAAQ,IAAI;AAC1B,QAAM,aAAa;IACjB;IACA;IACA,YAAY,MAAM,MAAM;IACxB,YAAY,MAAM,MAAM;IACxB,eAAe,MAAM,YAAY;;AAEnC,MAAI,WAAW,QAAQ;AACrB,WAAO;MACL,GAAG;MACH;;EAEJ;AACA,SAAO;IACL,GAAG;IACH;;AAEJ;",
6
- "names": ["global"]
7
- }
@@ -1,249 +0,0 @@
1
- import {
2
- canonicalDocument,
3
- hashDocument,
4
- orderObject,
5
- sha256Hex,
6
- stableStringify,
7
- toItemRecord
8
- } from "./chunk-IY6VZ3IW.js";
9
- import {
10
- ITEM_METADATA_KEY_ORDER
11
- } from "./chunk-7AVEY74G.js";
12
-
13
- // dist/core/history/replay.js
14
- import jsonPatch from "fast-json-patch";
15
- !(function() {
16
- try {
17
- var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
18
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "870cc300-69e5-5207-a84a-9dc346628044");
19
- } catch (e2) {
20
- }
21
- })();
22
- var EMPTY_REPLAY_DOCUMENT = {
23
- metadata: {},
24
- body: ""
25
- };
26
- function cloneEmptyReplayDocument() {
27
- return structuredClone(EMPTY_REPLAY_DOCUMENT);
28
- }
29
- function replayHash(document) {
30
- try {
31
- return hashDocument(replayToItemDocument(document));
32
- } catch {
33
- return sha256Hex(stableStringify({
34
- replay_fallback: true,
35
- metadata: document.metadata,
36
- body: document.body
37
- }));
38
- }
39
- }
40
- function replayToItemDocument(document) {
41
- return {
42
- metadata: document.metadata,
43
- body: document.body
44
- };
45
- }
46
- function replayToCanonicalItemDocument(document, options = {}) {
47
- return canonicalDocument(replayToItemDocument(document), options);
48
- }
49
- function toReplayDocument(document) {
50
- if (!document.metadata || Object.keys(document.metadata).length === 0) {
51
- return {
52
- metadata: {},
53
- body: document.body ?? ""
54
- };
55
- }
56
- const canonical = canonicalDocument(document);
57
- return {
58
- metadata: orderObject(toItemRecord(canonical.metadata), ITEM_METADATA_KEY_ORDER),
59
- body: canonical.body
60
- };
61
- }
62
- function normalizeReplayPatchPath(path) {
63
- if (path === "/front_matter") {
64
- return "/metadata";
65
- }
66
- if (path.startsWith("/front_matter/")) {
67
- return `/metadata/${path.slice("/front_matter/".length)}`;
68
- }
69
- return path;
70
- }
71
- function isHistoryPatchOp(value) {
72
- return typeof value === "object" && value !== null && typeof value.op === "string" && typeof value.path === "string";
73
- }
74
- function normalizeReplayPatchOps(patch) {
75
- if (!Array.isArray(patch)) {
76
- return [];
77
- }
78
- return patch.filter(isHistoryPatchOp).map((operation) => ({
79
- ...operation,
80
- path: normalizeReplayPatchPath(operation.path),
81
- from: typeof operation.from === "string" ? normalizeReplayPatchPath(operation.from) : void 0
82
- }));
83
- }
84
- function isReplayDocumentShape(value) {
85
- return typeof value === "object" && value !== null && "metadata" in value && "body" in value && typeof value.body === "string" && typeof value.metadata === "object" && value.metadata !== null;
86
- }
87
- function tryApplyReplayPatch(current, patch) {
88
- try {
89
- const normalizedPatch = normalizeReplayPatchOps(patch);
90
- const applied = jsonPatch.applyPatch(structuredClone(current), normalizedPatch, true, false).newDocument;
91
- if (!isReplayDocumentShape(applied)) {
92
- return {
93
- ok: false,
94
- error: new Error("history_replay_invalid_document_shape")
95
- };
96
- }
97
- return {
98
- ok: true,
99
- document: { metadata: applied.metadata, body: applied.body }
100
- };
101
- } catch (error) {
102
- return { ok: false, error };
103
- }
104
- }
105
- function verifyHistoryChain(entries) {
106
- let replay = cloneEmptyReplayDocument();
107
- for (let index = 0; index < entries.length; index += 1) {
108
- const entry = entries[index];
109
- if (replayHash(replay) !== entry.before_hash) {
110
- return {
111
- ok: false,
112
- errors: [`verify_failed:before_hash_mismatch:entry_${index + 1}`]
113
- };
114
- }
115
- const applied = tryApplyReplayPatch(replay, entry.patch);
116
- if (!applied.ok) {
117
- return {
118
- ok: false,
119
- errors: [`verify_failed:patch_apply_failed:entry_${index + 1}`]
120
- };
121
- }
122
- replay = applied.document;
123
- if (replayHash(replay) !== entry.after_hash) {
124
- return {
125
- ok: false,
126
- errors: [`verify_failed:after_hash_mismatch:entry_${index + 1}`]
127
- };
128
- }
129
- }
130
- return { ok: true, errors: [] };
131
- }
132
- function tryApplySingleOp(document, op) {
133
- try {
134
- const applied = jsonPatch.applyPatch(structuredClone(document), [op], true, false).newDocument;
135
- return { ok: true, document: applied };
136
- } catch {
137
- return { ok: false };
138
- }
139
- }
140
- function lenientApplyReplayPatch(current, patch) {
141
- let working = structuredClone(current);
142
- let convertedReplaceToAdd = 0;
143
- let skippedOps = 0;
144
- for (const op of normalizeReplayPatchOps(patch)) {
145
- const direct = tryApplySingleOp(working, op);
146
- if (direct.ok) {
147
- working = direct.document;
148
- continue;
149
- }
150
- if (op.op === "replace") {
151
- const asAdd = tryApplySingleOp(working, { ...op, op: "add" });
152
- if (asAdd.ok) {
153
- working = asAdd.document;
154
- convertedReplaceToAdd += 1;
155
- continue;
156
- }
157
- }
158
- skippedOps += 1;
159
- }
160
- const candidate = working;
161
- const document = {
162
- metadata: typeof candidate.metadata === "object" && candidate.metadata !== null ? candidate.metadata : {},
163
- body: typeof candidate.body === "string" ? candidate.body : current.body
164
- };
165
- return { document, convertedReplaceToAdd, skippedOps };
166
- }
167
- function reanchorHistoryEntries(entries) {
168
- let replay = cloneEmptyReplayDocument();
169
- const rewritten = [];
170
- const details = [];
171
- let entriesRehashed = 0;
172
- let entriesPatchRepaired = 0;
173
- let convertedReplaceToAdd = 0;
174
- let skippedOps = 0;
175
- for (let index = 0; index < entries.length; index += 1) {
176
- const entry = entries[index];
177
- const beforeHash = replayHash(replay);
178
- const strict = tryApplyReplayPatch(replay, entry.patch);
179
- let next;
180
- let outPatch;
181
- let patchRepaired = false;
182
- let entryConverted = 0;
183
- let entrySkipped = 0;
184
- if (strict.ok) {
185
- next = strict.document;
186
- outPatch = entry.patch;
187
- } else {
188
- const lenient = lenientApplyReplayPatch(replay, entry.patch);
189
- next = lenient.document;
190
- outPatch = jsonPatch.compare(replay, next);
191
- patchRepaired = true;
192
- entryConverted = lenient.convertedReplaceToAdd;
193
- entrySkipped = lenient.skippedOps;
194
- convertedReplaceToAdd += entryConverted;
195
- skippedOps += entrySkipped;
196
- entriesPatchRepaired += 1;
197
- }
198
- const afterHash = replayHash(next);
199
- const rehashed = beforeHash !== entry.before_hash || afterHash !== entry.after_hash;
200
- if (rehashed) {
201
- entriesRehashed += 1;
202
- }
203
- rewritten.push({
204
- ...entry,
205
- patch: outPatch,
206
- before_hash: beforeHash,
207
- after_hash: afterHash
208
- });
209
- details.push({
210
- index: index + 1,
211
- rehashed,
212
- patch_repaired: patchRepaired,
213
- converted_replace_to_add: entryConverted,
214
- skipped_ops: entrySkipped
215
- });
216
- replay = next;
217
- }
218
- return {
219
- entries: rewritten,
220
- finalDocument: replay,
221
- entriesRehashed,
222
- entriesPatchRepaired,
223
- convertedReplaceToAdd,
224
- skippedOps,
225
- details
226
- };
227
- }
228
- function historyEntriesToRaw(entries) {
229
- if (entries.length === 0) {
230
- return "";
231
- }
232
- return `${entries.map((entry) => JSON.stringify(entry)).join("\n")}
233
- `;
234
- }
235
-
236
- export {
237
- EMPTY_REPLAY_DOCUMENT,
238
- cloneEmptyReplayDocument,
239
- replayHash,
240
- replayToItemDocument,
241
- replayToCanonicalItemDocument,
242
- toReplayDocument,
243
- normalizeReplayPatchOps,
244
- tryApplyReplayPatch,
245
- verifyHistoryChain,
246
- reanchorHistoryEntries,
247
- historyEntriesToRaw
248
- };
249
- //# sourceMappingURL=chunk-E6LEMURX.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../../../../../core/history/replay.ts"],
4
- "sourcesContent": ["/**\n * @module core/history/replay\n *\n * Implements append-only history and replay behavior for Replay.\n */\nimport jsonPatch from \"fast-json-patch\";\nimport { ITEM_METADATA_KEY_ORDER } from \"../shared/constants.js\";\nimport { canonicalDocument } from \"../item/item-format.js\";\nimport { toItemRecord } from \"../item/item-record.js\";\nimport {\n orderObject,\n sha256Hex,\n stableStringify,\n} from \"../shared/serialization.js\";\nimport { hashDocument } from \"./history.js\";\nimport type {\n HistoryEntry,\n HistoryPatchOp,\n ItemDocument,\n ItemMetadata,\n} from \"../../types/index.js\";\n\n/**\n * Shared history replay/patch mechanics single-sourced for the history, restore,\n * history-redact, and history-repair commands plus the health/validate drift checks.\n *\n * Each command keeps its own thin error-formatting wrapper so the exact CLI error\n * contracts (restore's rich patch-failure context, redact's op tag, history's\n * generic message) are preserved; only the underlying replay/patch logic is shared.\n */\n\nexport interface ReplayDocument {\n /** Value that configures or reports metadata for this contract. */\n metadata: Record<string, unknown>;\n /** Value that configures or reports body for this contract. */\n body: string;\n}\n\n/** Public contract for empty replay document, shared by SDK and presentation-layer consumers. */\nexport const EMPTY_REPLAY_DOCUMENT: ReplayDocument = {\n metadata: {},\n body: \"\",\n};\n\n/** Implements clone empty replay document for the public runtime surface of this module. */\nexport function cloneEmptyReplayDocument(): ReplayDocument {\n return structuredClone(EMPTY_REPLAY_DOCUMENT);\n}\n\n/** Implements replay hash for the public runtime surface of this module. */\nexport function replayHash(document: ReplayDocument): string {\n try {\n return hashDocument(replayToItemDocument(document));\n } catch {\n // Legacy/malformed replay states (for example a stream whose first entry never\n // established a full `create` document, so the canonicalizer cannot normalize it)\n // cannot be canonically hashed. Fall back to a deterministic structural hash so\n // re-anchor and verification stay internally consistent for these streams. Fully\n // formed documents always take the canonical path above, so valid streams are\n // unaffected.\n return sha256Hex(\n stableStringify({\n replay_fallback: true,\n metadata: document.metadata,\n body: document.body,\n }),\n );\n }\n}\n\n/** Implements replay to item document for the public runtime surface of this module. */\nexport function replayToItemDocument(document: ReplayDocument): ItemDocument {\n return {\n metadata: document.metadata as ItemMetadata,\n body: document.body,\n };\n}\n\n/** Converts a materialized replay document into a canonical item document. Use this when callers have already rejected the empty/deleted replay state and need restored metadata validated through the normal item-metadata rules. */\nexport function replayToCanonicalItemDocument(\n document: ReplayDocument,\n options: Parameters<typeof canonicalDocument>[1] = {},\n): ItemDocument {\n return canonicalDocument(replayToItemDocument(document), options);\n}\n\n/** Canonicalize an item document into the ordered replay form used when comparing a replayed chain against the on-disk item (restore + history-repair reconciliation). */\nexport function toReplayDocument(document: ItemDocument): ReplayDocument {\n if (!document.metadata || Object.keys(document.metadata).length === 0) {\n return {\n metadata: {},\n body: document.body ?? \"\",\n };\n }\n const canonical = canonicalDocument(document);\n return {\n metadata: orderObject(\n toItemRecord(canonical.metadata),\n ITEM_METADATA_KEY_ORDER,\n ),\n body: canonical.body,\n };\n}\n\n/** Implements normalize replay patch path for the public runtime surface of this module. */\nexport function normalizeReplayPatchPath(path: string): string {\n if (path === \"/front_matter\") {\n return \"/metadata\";\n }\n if (path.startsWith(\"/front_matter/\")) {\n return `/metadata/${path.slice(\"/front_matter/\".length)}`;\n }\n return path;\n}\n\nfunction isHistoryPatchOp(value: unknown): value is HistoryPatchOp {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { op?: unknown }).op === \"string\" &&\n typeof (value as { path?: unknown }).path === \"string\"\n );\n}\n\n/** Implements normalize replay patch ops for the public runtime surface of this module. */\nexport function normalizeReplayPatchOps(\n patch: HistoryPatchOp[] | unknown,\n): HistoryPatchOp[] {\n if (!Array.isArray(patch)) {\n return [];\n }\n return patch.filter(isHistoryPatchOp).map((operation) => ({\n ...operation,\n path: normalizeReplayPatchPath(operation.path),\n from:\n typeof operation.from === \"string\"\n ? normalizeReplayPatchPath(operation.from)\n : undefined,\n }));\n}\n\nfunction isReplayDocumentShape(\n value: unknown,\n): value is { metadata: Record<string, unknown>; body: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"metadata\" in value &&\n \"body\" in value &&\n typeof (value as { body: unknown }).body === \"string\" &&\n typeof (value as { metadata: unknown }).metadata === \"object\" &&\n (value as { metadata: unknown }).metadata !== null\n );\n}\n\n/** Restricts replay apply result values accepted by command, SDK, and storage contracts. */\nexport type ReplayApplyResult =\n | { ok: true; document: ReplayDocument }\n | { ok: false; error: unknown };\n\n/** Strictly apply a history patch (front_matter->metadata normalized) to a replay document. Returns a result envelope rather than throwing so each caller can format its own error contract. */\nexport function tryApplyReplayPatch(\n current: ReplayDocument,\n patch: HistoryPatchOp[],\n): ReplayApplyResult {\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 (!isReplayDocumentShape(applied)) {\n return {\n ok: false,\n error: new Error(\"history_replay_invalid_document_shape\"),\n };\n }\n return {\n ok: true,\n document: { metadata: applied.metadata, body: applied.body },\n };\n } catch (error) {\n return { ok: false, error };\n }\n}\n\n/** Deterministically verify a history chain: each entry's before_hash must equal the prior replayed after_hash, the patch must strictly apply, and the recorded after_hash must equal the replayed result. */\nexport function verifyHistoryChain(entries: HistoryEntry[]): {\n ok: boolean;\n errors: string[];\n} {\n let replay = cloneEmptyReplayDocument();\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n if (replayHash(replay) !== entry.before_hash) {\n return {\n ok: false,\n errors: [`verify_failed:before_hash_mismatch:entry_${index + 1}`],\n };\n }\n const applied = tryApplyReplayPatch(replay, entry.patch);\n if (!applied.ok) {\n return {\n ok: false,\n errors: [`verify_failed:patch_apply_failed:entry_${index + 1}`],\n };\n }\n replay = applied.document;\n if (replayHash(replay) !== entry.after_hash) {\n return {\n ok: false,\n errors: [`verify_failed:after_hash_mismatch:entry_${index + 1}`],\n };\n }\n }\n return { ok: true, errors: [] };\n}\n\n/** Documents the lenient apply result payload exchanged by command, SDK, and package integrations. */\nexport interface LenientApplyResult {\n /** Value that configures or reports document for this contract. */\n document: ReplayDocument;\n /** Value that configures or reports converted replace to add for this contract. */\n convertedReplaceToAdd: number;\n /** Value that configures or reports skipped ops for this contract. */\n skippedOps: number;\n}\n\nfunction tryApplySingleOp(\n document: unknown,\n op: HistoryPatchOp,\n): { ok: true; document: unknown } | { ok: false } {\n try {\n const applied = jsonPatch.applyPatch(\n structuredClone(document),\n [op as jsonPatch.Operation],\n true,\n false,\n ).newDocument as unknown;\n return { ok: true, document: applied };\n } catch {\n return { ok: false };\n }\n}\n\n/** Apply a legacy patch op-by-op, recovering from drift that strict replay rejects: a `replace` whose path no longer exists is retried as `add`, and any op that still cannot apply against the current replay state is skipped. The resulting document is what the repaired entry's recomputed patch should target. */\nexport function lenientApplyReplayPatch(\n current: ReplayDocument,\n patch: HistoryPatchOp[],\n): LenientApplyResult {\n let working: unknown = structuredClone(current);\n let convertedReplaceToAdd = 0;\n let skippedOps = 0;\n\n for (const op of normalizeReplayPatchOps(patch)) {\n const direct = tryApplySingleOp(working, op);\n if (direct.ok) {\n working = direct.document;\n continue;\n }\n if (op.op === \"replace\") {\n const asAdd = tryApplySingleOp(working, { ...op, op: \"add\" });\n if (asAdd.ok) {\n working = asAdd.document;\n convertedReplaceToAdd += 1;\n continue;\n }\n }\n skippedOps += 1;\n }\n\n const candidate = working as { metadata?: unknown; body?: unknown };\n const document: ReplayDocument = {\n metadata:\n typeof candidate.metadata === \"object\" && candidate.metadata !== null\n ? (candidate.metadata as Record<string, unknown>)\n : {},\n body: typeof candidate.body === \"string\" ? candidate.body : current.body,\n };\n return { document, convertedReplaceToAdd, skippedOps };\n}\n\n/** Documents the reanchor entry detail payload exchanged by command, SDK, and package integrations. */\nexport interface ReanchorEntryDetail {\n /** Value that configures or reports index for this contract. */\n index: number;\n /** Value that configures or reports rehashed for this contract. */\n rehashed: boolean;\n /** Value that configures or reports patch repaired for this contract. */\n patch_repaired: boolean;\n /** Value that configures or reports converted replace to add for this contract. */\n converted_replace_to_add: number;\n /** Value that configures or reports skipped ops for this contract. */\n skipped_ops: number;\n}\n\n/** Documents the reanchor result payload exchanged by command, SDK, and package integrations. */\nexport interface ReanchorResult {\n /** Value that configures or reports entries for this contract. */\n entries: HistoryEntry[];\n /** Value that configures or reports final document for this contract. */\n finalDocument: ReplayDocument;\n /** Value that configures or reports entries rehashed for this contract. */\n entriesRehashed: number;\n /** Value that configures or reports entries patch repaired for this contract. */\n entriesPatchRepaired: number;\n /** Value that configures or reports converted replace to add for this contract. */\n convertedReplaceToAdd: number;\n /** Value that configures or reports skipped ops for this contract. */\n skippedOps: number;\n /** Value that configures or reports details for this contract. */\n details: ReanchorEntryDetail[];\n}\n\n/** Re-anchor a drifted history chain: replay every entry from empty, recompute the before/after hashes, and only rewrite a patch when the original op set no longer strictly applies (legacy drift). Clean entries keep their patch verbatim so the on-disk diff stays minimal. The returned chain verifies via verifyHistoryChain. */\nexport function reanchorHistoryEntries(\n entries: HistoryEntry[],\n): ReanchorResult {\n let replay = cloneEmptyReplayDocument();\n const rewritten: HistoryEntry[] = [];\n const details: ReanchorEntryDetail[] = [];\n let entriesRehashed = 0;\n let entriesPatchRepaired = 0;\n let convertedReplaceToAdd = 0;\n let skippedOps = 0;\n\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index];\n const beforeHash = replayHash(replay);\n const strict = tryApplyReplayPatch(replay, entry.patch);\n\n let next: ReplayDocument;\n let outPatch: HistoryPatchOp[];\n let patchRepaired = false;\n let entryConverted = 0;\n let entrySkipped = 0;\n\n if (strict.ok) {\n next = strict.document;\n outPatch = entry.patch;\n } else {\n const lenient = lenientApplyReplayPatch(replay, entry.patch);\n next = lenient.document;\n outPatch = jsonPatch.compare(replay, next) as HistoryPatchOp[];\n patchRepaired = true;\n entryConverted = lenient.convertedReplaceToAdd;\n entrySkipped = lenient.skippedOps;\n convertedReplaceToAdd += entryConverted;\n skippedOps += entrySkipped;\n entriesPatchRepaired += 1;\n }\n\n const afterHash = replayHash(next);\n const rehashed =\n beforeHash !== entry.before_hash || afterHash !== entry.after_hash;\n if (rehashed) {\n entriesRehashed += 1;\n }\n\n rewritten.push({\n ...entry,\n patch: outPatch,\n before_hash: beforeHash,\n after_hash: afterHash,\n });\n details.push({\n index: index + 1,\n rehashed,\n patch_repaired: patchRepaired,\n converted_replace_to_add: entryConverted,\n skipped_ops: entrySkipped,\n });\n replay = next;\n }\n\n return {\n entries: rewritten,\n finalDocument: replay,\n entriesRehashed,\n entriesPatchRepaired,\n convertedReplaceToAdd,\n skippedOps,\n details,\n };\n}\n\n/** Implements history entries to raw for the public runtime surface of this module. */\nexport function historyEntriesToRaw(entries: HistoryEntry[]): string {\n if (entries.length === 0) {\n return \"\";\n }\n return `${entries.map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;AAKA,OAAO,eAAe;;;;;;;;AAkCf,IAAM,wBAAwC;EACnD,UAAU,CAAA;EACV,MAAM;;AAIF,SAAU,2BAAwB;AACtC,SAAO,gBAAgB,qBAAqB;AAC9C;AAGM,SAAU,WAAW,UAAwB;AACjD,MAAI;AACF,WAAO,aAAa,qBAAqB,QAAQ,CAAC;EACpD,QAAQ;AAON,WAAO,UACL,gBAAgB;MACd,iBAAiB;MACjB,UAAU,SAAS;MACnB,MAAM,SAAS;KAChB,CAAC;EAEN;AACF;AAGM,SAAU,qBAAqB,UAAwB;AAC3D,SAAO;IACL,UAAU,SAAS;IACnB,MAAM,SAAS;;AAEnB;AAGM,SAAU,8BACd,UACA,UAAmD,CAAA,GAAE;AAErD,SAAO,kBAAkB,qBAAqB,QAAQ,GAAG,OAAO;AAClE;AAGM,SAAU,iBAAiB,UAAsB;AACrD,MAAI,CAAC,SAAS,YAAY,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