@unbrained/pm-cli 2026.8.4 → 2026.8.6

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 (253) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +53 -13
  3. package/dist/cli/error-guidance.js +4 -4
  4. package/dist/cli/main.js +12 -37
  5. package/dist/cli/register-setup.d.ts +1 -1
  6. package/dist/cli/register-setup.js +46 -20
  7. package/dist/cli/register-structured-mutation.d.ts +2 -0
  8. package/dist/cli/register-structured-mutation.js +124 -12
  9. package/dist/cli-bundle/bundle-manifest.json +397 -397
  10. package/dist/cli-bundle/chunks/append-XAJ5Z4XS.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-QVO3VTA4.js → chunk-343QETLI.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-Q5F6OI7C.js → chunk-3KFVGGRE.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-6S7I3UKV.js → chunk-3ZJRFYY2.js} +19 -19
  14. package/dist/cli-bundle/chunks/{chunk-NFF3JAQR.js → chunk-4AVFKHHC.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-5H47J5FG.js → chunk-4OVGQW22.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-D2MBVMVE.js → chunk-5PBP2ZP3.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-5ZKQPA44.js +2 -0
  18. package/dist/cli-bundle/chunks/chunk-A3XQ7VPU.js +2 -0
  19. package/dist/cli-bundle/chunks/chunk-AJE3AHPD.js +8 -0
  20. package/dist/cli-bundle/chunks/{chunk-2POYGY53.js → chunk-AOBDLU4T.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-PYYPQLHC.js → chunk-AYRUGRNS.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-QMWUL66F.js → chunk-BP6EMEDP.js} +5 -5
  23. package/dist/cli-bundle/chunks/{chunk-UVZREFZU.js → chunk-C3YABSJK.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-RB65T4RX.js → chunk-CA3BURYF.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-KIKLF2W4.js → chunk-D7I3TUGV.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-PQXEB7W4.js → chunk-DQGJ2RWT.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-OB7TRZ2G.js → chunk-DWOAOZHZ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-SVDH5CHC.js → chunk-E7BFPLUZ.js} +4 -4
  29. package/dist/cli-bundle/chunks/{chunk-CGY5I2GO.js → chunk-F4NREH3G.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-DCJ6CM6F.js → chunk-FDBRXV25.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-NM5G7RLU.js → chunk-GU3TSEHD.js} +2 -2
  32. package/dist/cli-bundle/chunks/chunk-HS7OVAUN.js +164 -0
  33. package/dist/cli-bundle/chunks/{chunk-CU5ENFNP.js → chunk-JFZIS6JF.js} +2 -2
  34. package/dist/cli-bundle/chunks/{chunk-GOICHIX4.js → chunk-JQ4NZ5EB.js} +2 -2
  35. package/dist/cli-bundle/chunks/{chunk-HE3DZFN4.js → chunk-L6LGKJX3.js} +2 -2
  36. package/dist/cli-bundle/chunks/{chunk-BLINBTMX.js → chunk-M357ZCOR.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-NRDKVOUE.js → chunk-M4VEE3FK.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-HTYC76A4.js → chunk-MCS73BKB.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-BKMZTZYL.js → chunk-MDTH7SAE.js} +2 -2
  40. package/dist/cli-bundle/chunks/{chunk-H6FITE7D.js → chunk-NE5VRDAI.js} +2 -2
  41. package/dist/cli-bundle/chunks/{chunk-NPUJ7OLK.js → chunk-OXY3SJ3N.js} +2 -2
  42. package/dist/cli-bundle/chunks/chunk-PECV7L5T.js +2 -0
  43. package/dist/cli-bundle/chunks/{chunk-KH4GVBMC.js → chunk-Q3VOP62W.js} +2 -2
  44. package/dist/cli-bundle/chunks/{chunk-FQ4EFFDU.js → chunk-QJ7C3JIW.js} +2 -2
  45. package/dist/cli-bundle/chunks/{chunk-VH2EAGUG.js → chunk-R6LSRGPS.js} +2 -2
  46. package/dist/cli-bundle/chunks/{chunk-HQ2WU7OY.js → chunk-R6RKEYYW.js} +2 -2
  47. package/dist/cli-bundle/chunks/{chunk-PA5XRN2A.js → chunk-RAFUN7IX.js} +4 -4
  48. package/dist/cli-bundle/chunks/chunk-RUAU5OSH.js +2 -0
  49. package/dist/cli-bundle/chunks/chunk-SD3YXU2U.js +56 -0
  50. package/dist/cli-bundle/chunks/{chunk-JMKVCQSE.js → chunk-SV3YQ4RY.js} +2 -2
  51. package/dist/cli-bundle/chunks/{chunk-B5ZLCD5Z.js → chunk-SVV3DQES.js} +2 -2
  52. package/dist/cli-bundle/chunks/{chunk-J4EPW4GT.js → chunk-SXECIECW.js} +2 -2
  53. package/dist/cli-bundle/chunks/chunk-T45OHXDW.js +8 -0
  54. package/dist/cli-bundle/chunks/{chunk-NH35JNK5.js → chunk-TPKDJ5WL.js} +2 -2
  55. package/dist/cli-bundle/chunks/{chunk-ZSH4GNBH.js → chunk-UVVXHGYS.js} +2 -2
  56. package/dist/cli-bundle/chunks/chunk-V663653R.js +20 -0
  57. package/dist/cli-bundle/chunks/{chunk-5PZGZMPG.js → chunk-WSI5KZQJ.js} +2 -2
  58. package/dist/cli-bundle/chunks/{chunk-3XZYTRPC.js → chunk-XPOQQJTX.js} +2 -2
  59. package/dist/cli-bundle/chunks/{chunk-UJHUR3LZ.js → chunk-YCCDXBNU.js} +2 -2
  60. package/dist/cli-bundle/chunks/chunk-ZFBWCKYF.js +2 -0
  61. package/dist/cli-bundle/chunks/close-DI66JMSB.js +2 -0
  62. package/dist/cli-bundle/chunks/close-many-VFKT6U3O.js +2 -0
  63. package/dist/cli-bundle/chunks/comments-E73HIEZJ.js +2 -0
  64. package/dist/cli-bundle/chunks/copy-WBYVLCPC.js +2 -0
  65. package/dist/cli-bundle/chunks/{create-RLLCBCXM.js → create-TG67IVFI.js} +2 -2
  66. package/dist/cli-bundle/chunks/delete-6XKUVVQN.js +2 -0
  67. package/dist/cli-bundle/chunks/{deps-J4ONTF4X.js → deps-AJUGP2OH.js} +2 -2
  68. package/dist/cli-bundle/chunks/{docs-YL2DJ4WD.js → docs-QOCLDRKJ.js} +2 -2
  69. package/dist/cli-bundle/chunks/{files-NGNAIYKK.js → files-3ST5TY64.js} +2 -2
  70. package/dist/cli-bundle/chunks/focus-R2AWS63Y.js +2 -0
  71. package/dist/cli-bundle/chunks/{history-compact-HW62K5XP.js → history-compact-7BJFML4S.js} +2 -2
  72. package/dist/cli-bundle/chunks/{history-redact-HVBKUJOW.js → history-redact-WJN3HYXR.js} +2 -2
  73. package/dist/cli-bundle/chunks/{history-repair-OPNBH5JJ.js → history-repair-XDNZUB7F.js} +2 -2
  74. package/dist/cli-bundle/chunks/{learnings-F36PZXT6.js → learnings-SZMUPVNA.js} +2 -2
  75. package/dist/cli-bundle/chunks/{profile-N3XMWBM7.js → profile-KL53JIAC.js} +2 -2
  76. package/dist/cli-bundle/chunks/{register-list-query-BKGHBI7Y.js → register-list-query-QH7ONPKU.js} +2 -2
  77. package/dist/cli-bundle/chunks/register-mutation-OCRQNZK4.js +20 -0
  78. package/dist/cli-bundle/chunks/register-operations-HIBJXRGB.js +2 -0
  79. package/dist/cli-bundle/chunks/register-setup-QWBQ6HBS.js +2 -0
  80. package/dist/cli-bundle/chunks/restore-FXA5QPM7.js +2 -0
  81. package/dist/cli-bundle/chunks/{schema-4PJQMGUY.js → schema-QJ27OTRV.js} +2 -2
  82. package/dist/cli-bundle/chunks/update-7GBO4SXG.js +2 -0
  83. package/dist/cli-bundle/chunks/update-many-VF6ZKQUO.js +2 -0
  84. package/dist/cli-bundle/focused-chunks/chunk-27DK4A5O.js +2 -0
  85. package/dist/cli-bundle/focused-chunks/chunk-4JC3AOGS.js +8 -0
  86. package/dist/cli-bundle/focused-chunks/chunk-6KDHXURF.js +2 -0
  87. package/dist/cli-bundle/focused-chunks/chunk-74CWP3A4.js +2 -0
  88. package/dist/cli-bundle/focused-chunks/chunk-7AZDTGPA.js +2 -0
  89. package/dist/cli-bundle/focused-chunks/chunk-7YTZ7A4E.js +2 -0
  90. package/dist/cli-bundle/focused-chunks/{chunk-ONIX2KKW.js → chunk-CL3NB7VW.js} +2 -2
  91. package/dist/cli-bundle/focused-chunks/chunk-EAXXF2HW.js +4 -0
  92. package/dist/cli-bundle/focused-chunks/{chunk-L6A4NVQC.js → chunk-EYO4F74Z.js} +2 -2
  93. package/dist/cli-bundle/focused-chunks/chunk-GEYU23YS.js +153 -0
  94. package/dist/cli-bundle/focused-chunks/{chunk-DQ4PLKEE.js → chunk-GIERI4YU.js} +2 -2
  95. package/dist/cli-bundle/focused-chunks/chunk-GSW2Y7VZ.js +5 -0
  96. package/dist/cli-bundle/focused-chunks/{chunk-WVGJAD7L.js → chunk-LKQXXO62.js} +2 -2
  97. package/dist/cli-bundle/focused-chunks/{chunk-UFCPSWIL.js → chunk-MBBMTDD3.js} +2 -2
  98. package/dist/cli-bundle/focused-chunks/{chunk-OYTK4VNH.js → chunk-ME4XVOBJ.js} +2 -2
  99. package/dist/cli-bundle/focused-chunks/{chunk-RO5BQFG3.js → chunk-N7QN3NE6.js} +2 -2
  100. package/dist/cli-bundle/focused-chunks/chunk-QL5H3AQH.js +2 -0
  101. package/dist/cli-bundle/focused-chunks/chunk-TQMFQYXR.js +29 -0
  102. package/dist/cli-bundle/focused-chunks/{chunk-SQXVGHMH.js → chunk-XNVXIQ4B.js} +2 -2
  103. package/dist/cli-bundle/focused-chunks/{chunk-BOGRY7M6.js → chunk-YHDCGUIW.js} +10 -10
  104. package/dist/cli-bundle/focused-chunks/{chunk-K37BB4JL.js → chunk-YLPZHWX7.js} +2 -2
  105. package/dist/cli-bundle/main.js +13 -13
  106. package/dist/cli-bundle/sdk-authoring.js +1 -1
  107. package/dist/cli-bundle/sdk-contracts.js +1 -1
  108. package/dist/cli-bundle/sdk-core.js +28 -28
  109. package/dist/cli-bundle/sdk-governance.js +1 -1
  110. package/dist/cli-bundle/sdk-graph.js +1 -1
  111. package/dist/cli-bundle/sdk-merge.js +1 -1
  112. package/dist/cli-bundle/sdk-query.js +1 -1
  113. package/dist/cli-bundle/sdk-runtime.js +1 -1
  114. package/dist/cli-bundle/sdk-testing.js +1 -1
  115. package/dist/cli-bundle/sdk.js +1 -1
  116. package/dist/core/extensions/activation-summary.d.ts +4 -0
  117. package/dist/core/extensions/activation-summary.js +5 -2
  118. package/dist/core/extensions/contribution-inventory.d.ts +1 -0
  119. package/dist/core/extensions/contribution-inventory.js +35 -2
  120. package/dist/core/extensions/extension-hook-runtime.js +5 -3
  121. package/dist/core/extensions/extension-types.d.ts +18 -1
  122. package/dist/core/extensions/extension-types.js +2 -2
  123. package/dist/core/extensions/loader.js +8 -13
  124. package/dist/core/extensions/preflight-ownership.d.ts +5 -0
  125. package/dist/core/extensions/preflight-ownership.js +42 -0
  126. package/dist/core/item/item-format.js +14 -20
  127. package/dist/core/shared/constants.js +3 -2
  128. package/dist/core/store/item-store.js +2 -2
  129. package/dist/core/store/settings.js +2 -2
  130. package/dist/mcp/server.js +12 -6
  131. package/dist/mcp/tool-definitions.js +14 -7
  132. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +18 -18
  133. package/dist/sdk/cli-contracts/agent-output-contracts.js +51 -23
  134. package/dist/sdk/cli-contracts/commander-mutation-options.js +26 -2
  135. package/dist/sdk/cli-contracts/flag-contracts.d.ts +4 -0
  136. package/dist/sdk/cli-contracts/flag-contracts.js +34 -2
  137. package/dist/sdk/cli-contracts/registration-helpers.js +4 -2
  138. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +10 -2
  139. package/dist/sdk/cli-contracts/runtime-contracts.js +21 -5
  140. package/dist/sdk/cli-contracts/tool-schema.js +4 -2
  141. package/dist/sdk/cli-contracts.d.ts +2 -2
  142. package/dist/sdk/cli-contracts.js +4 -4
  143. package/dist/sdk/cli-program.js +3 -3
  144. package/dist/sdk/compose.d.ts +2 -2
  145. package/dist/sdk/compose.js +7 -2
  146. package/dist/sdk/contracts.d.ts +1 -0
  147. package/dist/sdk/contracts.js +3 -2
  148. package/dist/sdk/define.d.ts +3 -1
  149. package/dist/sdk/define.js +3 -8
  150. package/dist/sdk/dependency-provenance.d.ts +2 -0
  151. package/dist/sdk/dependency-provenance.js +7 -3
  152. package/dist/sdk/error-code-catalog.d.ts +23 -0
  153. package/dist/sdk/error-code-catalog.js +25 -5
  154. package/dist/sdk/extension/install-sources.d.ts +43 -5
  155. package/dist/sdk/extension/install-sources.js +36 -2
  156. package/dist/sdk/extension/migrations.d.ts +114 -0
  157. package/dist/sdk/extension/migrations.js +175 -0
  158. package/dist/sdk/extension/scaffold.js +14 -9
  159. package/dist/sdk/extension/source-resolution.d.ts +50 -0
  160. package/dist/sdk/extension/source-resolution.js +66 -0
  161. package/dist/sdk/extension.d.ts +5 -1
  162. package/dist/sdk/extension.js +24 -26
  163. package/dist/sdk/generated-error-code-catalog.js +499 -3
  164. package/dist/sdk/governance/health.js +11 -2
  165. package/dist/sdk/graph/governance.js +3 -3
  166. package/dist/sdk/graph/remediation.js +3 -3
  167. package/dist/sdk/graph/run.js +4 -8
  168. package/dist/sdk/index.d.ts +7 -2
  169. package/dist/sdk/index.js +9 -4
  170. package/dist/sdk/item-transaction.d.ts +51 -6
  171. package/dist/sdk/item-transaction.js +132 -22
  172. package/dist/sdk/lifecycle/create.d.ts +4 -0
  173. package/dist/sdk/lifecycle/create.js +26 -10
  174. package/dist/sdk/lifecycle-policy.d.ts +9 -0
  175. package/dist/sdk/lifecycle-policy.js +22 -9
  176. package/dist/sdk/merge/driver.js +6 -3
  177. package/dist/sdk/output-contracts.d.ts +67 -0
  178. package/dist/sdk/output-contracts.js +173 -0
  179. package/dist/sdk/package-import-adapters.js +2 -2
  180. package/dist/sdk/package-migrations.d.ts +10 -0
  181. package/dist/sdk/package-migrations.js +21 -0
  182. package/dist/sdk/runtime.d.ts +2 -0
  183. package/dist/sdk/runtime.js +6 -2
  184. package/dist/sdk/structured-mutations.d.ts +23 -0
  185. package/dist/sdk/structured-mutations.js +219 -10
  186. package/dist/sdk/workspace-snapshot.js +58 -12
  187. package/dist/sdk/workspace.js +30 -4
  188. package/docs/COMMANDS.md +49 -10
  189. package/docs/EXTENSIONS.md +3 -3
  190. package/docs/EXTENSION_LIFECYCLE.md +46 -0
  191. package/docs/MERGE_SAFETY.md +2 -0
  192. package/docs/PR_REVIEW_LOOP.md +10 -4
  193. package/docs/README.md +23 -22
  194. package/docs/RELEASING.md +36 -23
  195. package/docs/SCRIPTING.md +32 -9
  196. package/docs/SDK.md +122 -14
  197. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
  198. package/docs/TESTING.md +25 -0
  199. package/docs/examples/sdk-contract-consumer/README.md +11 -1
  200. package/docs/examples/sdk-contract-consumer/package.json +2 -1
  201. package/docs/examples/sdk-contract-consumer/parse-receipt.mjs +22 -0
  202. package/marketplace.json +2 -2
  203. package/package.json +5 -4
  204. package/packages/pm-beads/package.json +1 -1
  205. package/packages/pm-calendar/package.json +1 -1
  206. package/packages/pm-command-kit/package.json +1 -1
  207. package/packages/pm-digital-twin/package.json +1 -1
  208. package/packages/pm-governance-audit/package.json +1 -1
  209. package/packages/pm-guide-shell/package.json +1 -1
  210. package/packages/pm-kanban/package.json +1 -1
  211. package/packages/pm-lifecycle-hooks/package.json +1 -1
  212. package/packages/pm-linked-test-adapters/package.json +1 -1
  213. package/packages/pm-search-advanced/package.json +1 -1
  214. package/packages/pm-templates/package.json +1 -1
  215. package/packages/pm-todos/package.json +1 -1
  216. package/packages/pm-vcs/package.json +1 -1
  217. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  218. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  219. package/sdk/public-surface.json +508 -32
  220. package/dist/cli-bundle/chunks/append-DHBRLHHS.js +0 -2
  221. package/dist/cli-bundle/chunks/chunk-2INN52SU.js +0 -8
  222. package/dist/cli-bundle/chunks/chunk-377OOXUF.js +0 -55
  223. package/dist/cli-bundle/chunks/chunk-6RSK4IFN.js +0 -20
  224. package/dist/cli-bundle/chunks/chunk-ASJJKA57.js +0 -2
  225. package/dist/cli-bundle/chunks/chunk-IYAVULRN.js +0 -2
  226. package/dist/cli-bundle/chunks/chunk-JDPKBV5P.js +0 -2
  227. package/dist/cli-bundle/chunks/chunk-RRQBHQOV.js +0 -2
  228. package/dist/cli-bundle/chunks/chunk-SULWTPQO.js +0 -8
  229. package/dist/cli-bundle/chunks/chunk-V5K52PYW.js +0 -164
  230. package/dist/cli-bundle/chunks/chunk-XBLOD5TZ.js +0 -2
  231. package/dist/cli-bundle/chunks/close-VLHNN6YB.js +0 -2
  232. package/dist/cli-bundle/chunks/close-many-LSJNZKU6.js +0 -2
  233. package/dist/cli-bundle/chunks/comments-AAIA6A6X.js +0 -2
  234. package/dist/cli-bundle/chunks/copy-Z7YMLEHN.js +0 -2
  235. package/dist/cli-bundle/chunks/delete-KNOHHQJM.js +0 -2
  236. package/dist/cli-bundle/chunks/focus-LFRCGALV.js +0 -2
  237. package/dist/cli-bundle/chunks/register-mutation-GU3DCECN.js +0 -20
  238. package/dist/cli-bundle/chunks/register-operations-PTWH727R.js +0 -2
  239. package/dist/cli-bundle/chunks/register-setup-KWV6UD77.js +0 -2
  240. package/dist/cli-bundle/chunks/restore-4HZSLILR.js +0 -2
  241. package/dist/cli-bundle/chunks/update-E6LPS5IV.js +0 -2
  242. package/dist/cli-bundle/chunks/update-many-OSIC6KRO.js +0 -2
  243. package/dist/cli-bundle/focused-chunks/chunk-2VIIXOAD.js +0 -2
  244. package/dist/cli-bundle/focused-chunks/chunk-5MTKO7TV.js +0 -153
  245. package/dist/cli-bundle/focused-chunks/chunk-6GIZK7VQ.js +0 -2
  246. package/dist/cli-bundle/focused-chunks/chunk-AOP2WIZZ.js +0 -2
  247. package/dist/cli-bundle/focused-chunks/chunk-C2QSL62X.js +0 -28
  248. package/dist/cli-bundle/focused-chunks/chunk-CL75YW32.js +0 -2
  249. package/dist/cli-bundle/focused-chunks/chunk-E7OFMWGT.js +0 -8
  250. package/dist/cli-bundle/focused-chunks/chunk-I5F5UK3Q.js +0 -2
  251. package/dist/cli-bundle/focused-chunks/chunk-QM2BIVK7.js +0 -4
  252. package/dist/cli-bundle/focused-chunks/chunk-T5TSY36R.js +0 -5
  253. package/dist/cli-bundle/focused-chunks/chunk-VT6BF2IX.js +0 -2
@@ -1,14 +1,14 @@
1
- import{f as Jt}from"./chunk-I5F5UK3Q.js";import{h as de,i as Kt,j as ue,k as Vt,n as Yt}from"./chunk-OYTK4VNH.js";import{$a as ke,Ca as ie,Da as jt,Fa as Ut,Ha as Bt,Ia as zt,K as ne,Ka as $,L as V,P as Pt,Ta as Gt,V as Ft,W as Lt,Ya as Wt,Z as $t,_ as Dt,ab as ve,ba as Be,bb as qt,da as Mt,db as Ht,gb as be,k as W,na as Ot,q as Tt,za as Nt}from"./chunk-5MTKO7TV.js";import{D as B,I as It,J as z,K as le,Ka as Ct,M as O,P as Rt,T as P,aa as Ne,h as vt,o as bt,p as L,q as Et,r as ce,u as Oe,v as St}from"./chunk-QM2BIVK7.js";import{g as At}from"./chunk-6GIZK7VQ.js";import{N as wt,U as kt,V as we,Y as w,Z as k,aa as je,ba as xt,ca as Ue,t as Me}from"./chunk-CL75YW32.js";import{readFile as Ee,realpath as qe,writeFile as qi}from"node:fs/promises";import{execFile as Hi}from"node:child_process";import x from"node:path";import{promisify as Ki}from"node:util";import{readFile as Bi,writeFile as zi}from"node:fs/promises";import me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="786d5cc6-521d-521e-9e91-95d82551c279")}catch{}})();var Xt="# pm-cli:runtime-cache:start",ze="# pm-cli:runtime-cache:end",Zt=".agents/pm",Ge=["runtime/","search/","locks/","transactions/","checkpoints/"],Gi=["search/eval-queries.json"];function Qt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function We(e){let t=e.replaceAll("\\","/");return me.isAbsolute(e)||t===".."||t.startsWith("../")}function Wi(e=Zt){let t=Qt(e);return[Xt,...Ge.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Gi.map(n=>`!${t}/${n}`),ze].join(`
2
- `)}async function To(e,t={}){let n=me.join(e,".gitignore"),i=Zt;if(t.pmRoot!==void 0){let d=Qt(me.relative(me.resolve(e),me.resolve(t.pmRoot)));if(We(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Bi(n,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let s=r.indexOf(Xt),o=r.indexOf(ze),c=(s>=0&&o>=s?`${r.slice(0,s)}${r.slice(o+ze.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
1
+ import{f as Jt}from"./chunk-6KDHXURF.js";import{h as de,i as Kt,j as ue,k as Vt,n as Yt}from"./chunk-ME4XVOBJ.js";import{$a as ke,Ca as ie,Da as jt,Fa as Ut,Ha as zt,Ia as Bt,K as ne,Ka as $,L as V,P as Pt,Ta as Gt,V as Ft,W as Lt,Ya as Wt,Z as $t,_ as Dt,ab as ve,ba as ze,bb as qt,da as Mt,db as Ht,gb as be,k as W,na as Ot,q as Tt,za as Nt}from"./chunk-GEYU23YS.js";import{D as z,I as It,J as B,K as le,Ka as Ct,M as O,P as Rt,T as P,aa as Ne,h as vt,o as bt,p as L,q as Et,r as ce,u as Oe,v as St}from"./chunk-EAXXF2HW.js";import{i as At}from"./chunk-27DK4A5O.js";import{N as wt,U as kt,V as we,Y as g,Z as y,aa as je,ba as xt,ca as Ue,t as Me}from"./chunk-7AZDTGPA.js";import{readFile as Ee,realpath as qe,writeFile as Hi}from"node:fs/promises";import{execFile as Ki}from"node:child_process";import x from"node:path";import{promisify as Vi}from"node:util";import{readFile as Bi,writeFile as Gi}from"node:fs/promises";import me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var Zt="# pm-cli:runtime-cache:start",Be="# pm-cli:runtime-cache:end",Qt=".agents/pm",Ge=["runtime/","search/","locks/","transactions/","checkpoints/"],Wi=["search/eval-queries.json"];async function Xt(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new y("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function en(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function We(e){let t=e.replaceAll("\\","/");return me.isAbsolute(e)||t===".."||t.startsWith("../")}function qi(e=Qt){let t=en(e);return[Zt,...Ge.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Wi.map(n=>`!${t}/${n}`),Be].join(`
2
+ `)}async function Lo(e,t={}){let n=me.join(e,".gitignore"),i=Qt;if(t.pmRoot!==void 0){let d=en(me.relative(me.resolve(e),me.resolve(t.pmRoot)));if(We(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Xt(()=>Bi(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let s=r.indexOf(Zt),o=r.indexOf(Be),c=(s>=0&&o>=s?`${r.slice(0,s)}${r.slice(o+Be.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
3
3
 
4
- `:""}${Wi(i)}
5
- `;return l===r?{path:n,changed:!1}:(await zi(n,l,"utf8"),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1729579e-ef08-55c3-914f-c025ba3033e4")}catch{}})();var He=Ki(Hi),Q="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",Vi="merge-fence";function en(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function nn(){let e=St(import.meta.url,["../../.."]);return`${en(process.execPath)} ${en(x.join(e,"dist","cli.js"))}`}var rn=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];async function pe(e){try{let{stdout:t}=await He("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await qe(t.trim())}catch{return null}}async function sn(e){let t=await pe(e);if(t===null)throw new k("pm merge install requires a git repository (merge drivers are git configuration).",w.USAGE);return t}function Ke(e,t){return x.relative(e,t).replaceAll("\\","/")}function Y(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function tn(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function Yi(e,t){let n=tn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=tn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(x.basename(n.value))||x.basename(i.value)!=="cli.js"||x.basename(x.dirname(i.value))!=="dist"||!await L(n.value)||!await L(i.value))return!1;try{let r=x.dirname(x.dirname(i.value)),s=JSON.parse(await Ee(x.join(r,"package.json"),"utf8")),o=typeof s.bin=="object"&&s.bin!==null&&"pm"in s.bin?s.bin.pm:void 0;return s.name==="@unbrained/pm-cli"&&(s.bin==="dist/cli.js"||o==="dist/cli.js")}catch{return!1}}function Ve(e,t){let n=e.length>0?`${e}/`:"",i=[`${Y(`${n}**/*.toon`)} merge=pm-item-toon`,`${Y(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${Y(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${Y(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${Y(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${Y(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${Y(`${n}settings.json`)} merge=pm-json`),i.push(`${Y(`${n}**/*.json`)} merge=pm-json`),i}async function on(e,t,n){let i=x.join(e,".gitattributes"),r="";try{r=await Ee(i,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let s=[Q,...t,fe].join(`
4
+ `:""}${qi(i)}
5
+ `;return l===r?{path:n,changed:!1}:(await Xt(()=>Gi(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1729579e-ef08-55c3-914f-c025ba3033e4")}catch{}})();var He=Vi(Ki),Q="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",Yi="merge-fence";function tn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function rn(){let e=St(import.meta.url,["../../.."]);return`${tn(process.execPath)} ${tn(x.join(e,"dist","cli.js"))}`}var sn=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];async function pe(e){try{let{stdout:t}=await He("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await qe(t.trim())}catch{return null}}async function on(e){let t=await pe(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Ke(e,t){return x.relative(e,t).replaceAll("\\","/")}function Y(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function nn(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function Ji(e,t){let n=nn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=nn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(x.basename(n.value))||x.basename(i.value)!=="cli.js"||x.basename(x.dirname(i.value))!=="dist"||!await L(n.value)||!await L(i.value))return!1;try{let r=x.dirname(x.dirname(i.value)),s=JSON.parse(await Ee(x.join(r,"package.json"),"utf8")),o=typeof s.bin=="object"&&s.bin!==null&&"pm"in s.bin?s.bin.pm:void 0;return s.name==="@unbrained/pm-cli"&&(s.bin==="dist/cli.js"||o==="dist/cli.js")}catch{return!1}}function Ve(e,t){let n=e.length>0?`${e}/`:"",i=[`${Y(`${n}**/*.toon`)} merge=pm-item-toon`,`${Y(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${Y(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${Y(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${Y(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${Y(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${Y(`${n}settings.json`)} merge=pm-json`),i.push(`${Y(`${n}**/*.json`)} merge=pm-json`),i}async function an(e,t,n){let i=x.join(e,".gitattributes"),r="";try{r=await Ee(i,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let s=[Q,...t,fe].join(`
6
6
  `),o=r.indexOf(Q),a=r.indexOf(fe),l=(o>=0&&a>o?`${r.slice(0,o)}${r.slice(a+fe.length)}`:r.replace(Q,"").replace(fe,"")).trimEnd(),d=`${l.length>0?`${l}
7
7
 
8
8
  `:""}${s}
9
- `;return d===r?{path:i,changed:!1}:(n||await qi(i,d,"utf8"),{path:i,changed:!0})}function Se(e){let t=B(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function an(e,t){let n=x.resolve(e),i=null,r="",s=n;for(let p=0;p<8;p+=1){let _=x.join(s,".gitattributes");try{let v=await Ee(_,"utf8");if(v.includes(Q)){i=s,r=v;break}}catch{}let h=x.dirname(s);if(h===s)break;s=h}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=x.join(i,".gitattributes"),a=r.indexOf(Q),c=r.indexOf(fe),l=c>a?r.slice(a+Q.length,c).split(`
10
- `).map(p=>p.trim()).filter(p=>p.length>0):[],d=Ve(Ke(i,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),g=l.filter(p=>!m.has(p));return{status:f.length>0||g.length>0?"drift":"ok",path:o,missing_patterns:f,stale_patterns:g,schema_scope:"project"}}async function cn(e){let t=nn(),n=[],i=[];for(let r of rn){let s=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${o}`;try{let{stdout:c}=await He("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Yi(l,o)&&i.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function Ko(e){let t;try{t=await sn(x.resolve(e))}catch{return{status:"no_git"}}let n=Ke(t,x.resolve(e)),i=await $(e),r=ne(void 0,i.author_default),s=await Pt(e,Vi,i.locks.ttl_seconds,r,!1,zt(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=x.join(t,".gitattributes"),a;try{a=await Ee(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:o};throw u}if(!a.includes(Q))return{status:"not_installed",path:o};let c=await $(e),l=Se(c),d=await on(t,Ve(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Vo(e,t){let n=t.path?.trim(),i=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),s=n===void 0&&i!==void 0&&i.length>0&&r!==void 0&&r.length>0,o=n!==void 0?z(process.cwd(),n):s?x.resolve(r):z(process.cwd());if(!await L(O(o)))throw new k(`Tracker is not initialized at ${o}. Run pm init first.`,w.NOT_FOUND);let a=await sn(n!==void 0?o:s?x.resolve(i):process.cwd());return Ji({pmRoot:o,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Ji(e){let t=x.resolve(e.pmRoot),n=x.resolve(e.workspaceRoot),i=e.dryRun===!0,r,s;try{[r,s]=await Promise.all([qe(t),qe(n)])}catch(f){throw new k(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,w.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Ke(s,r);if(We(o))throw new k(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,w.USAGE);let a=await $(r),c=Se(a),l=Ve(o,c),d=[],u=nn();for(let f of rn)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!i)try{for(let f of d)await He("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new k(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,w.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await on(s,l,i);return{ok:!0,dry_run:i,workspace_root:s,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"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."],generated_at:V()}}import Ie from"node:fs/promises";import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="364a8999-58e2-58c9-bfa6-acd8c42ec471")}catch{}})();var Xi="2026-07-15T06:22:12.276Z",Zi=Date.parse(Xi),Qi=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],ln=e=>typeof e=="string"?e:"",dn=e=>{let t=e??{},n=ln(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(ln(t.ts))>=Zi);return Qi[i][r]};function un(e,t,n=20,i=new Set,r=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let g;try{g=JSON.parse(f)}catch{continue}l+=1;let p=dn(g);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var ea=(e,t,n=20,i=new Set)=>un(e,t,n,i);function er(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Ye=async(e,t=20,n=!1)=>{let i=Re.join(e,"history"),r;try{r=(await Ie.readdir(i)).filter(h=>h.endsWith(".jsonl")).sort((h,v)=>h.localeCompare(v))}catch{r=[]}let s=new Set,o=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,g="_workspace.jsonl",p=new Set;if(r.includes(g))try{p=er(await Ie.readFile(Re.join(i,g),"utf8"))}catch{p=new Set}for(let h of r){let v;try{v=await Ie.readFile(Re.join(i,h),"utf8")}catch{continue}let E=h.slice(0,-6),S=un(E,v,t-o.length,p,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...s].sort((h,v)=>h.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:a}:{}}};async function ta(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),s=t.events??[];if(+(t.all_actionable===!0)+ +(s.length>0)>1)throw new TypeError("Author acknowledgment accepts either explicit events or all_actionable, not both.");let a=t.all_actionable===!0?(await Ye(e,0,!0)).actionable_events:s;if([a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1))throw new TypeError("Author acknowledgment requires events, reviewer, attributed_author, and reason.");let l=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){if([/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1))throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`);let g;try{let _=(await Ie.readFile(Re.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];g=JSON.parse(_??"")}catch{throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`)}if(dn(g)!=="actionable_unknown")throw new TypeError(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`)}let d=await $(e),u=await Ut({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:i}},message:r,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as tr}from"node:child_process";import{randomUUID as nr}from"node:crypto";import{readdir as ir,readFile as rr}from"node:fs/promises";import _e from"node:path";import{promisify as sr}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var or=sr(tr);async function Je(e){try{let{stdout:t}=await or("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}function mn(e){return`${e}.json`}function ua(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Ue(je(t.retained)),discarded_hash:Ue(je(t.discarded))}))}}async function ma(e){let t=await Je(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=_e.basename(i,_e.extname(i)),s={version:1,id:nr(),item_path:i.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:V()};return await bt(t),await ce(_e.join(t,mn(s.id)),`${JSON.stringify(s,null,2)}
11
- `),s}async function Xe(e,t={}){let n=await Je(e);if(n===null||!await L(n))return[];let i=[],r;try{r=await ir(n)}catch{return[]}for(let s of r.sort((o,a)=>o.localeCompare(a)))if(s.endsWith(".json"))try{let o=JSON.parse(await rr(_e.join(n,s),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&i.push(o)}catch{}return i.sort((s,o)=>s.created_at.localeCompare(o.created_at))}async function fa(e,t){let n=await Je(e);n!==null&&await ce(_e.join(n,mn(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:V()},null,2)}
12
- `)}async function pa(e){let t=await Xe(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:V()}}import re from"node:fs/promises";import se from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function ar(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await re.readdir(se.join(e,r))}catch{return}for(let o of s)for(let a of It)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function cr(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=Be(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{s.unparseable.push({id:n,path:i,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function Ze(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function lr(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await re.readdir(se.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await re.readFile(se.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ze("history stream",o)});continue}cr({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function fn(e){let t=Be(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function dr(e){let t=[],n=0,i=null;try{i=await Et(O(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Ze("configuration file",s)})}if(i!==null){n+=1;let s=fn(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await re.readdir(se.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await re.readFile(se.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Ze("configuration file",c)});continue}let a=fn(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function pn(e,t,n,i={}){let r=await ar(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,g)=>f.localeCompare(g))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=se.join(e,u.relativePath);return Mt(await re.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await lr(e,s),d=await dr(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import ft from"node:fs/promises";import{realpathSync as xs}from"node:fs";import{execFile as Cs}from"node:child_process";import F from"node:path";import{promisify as As}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var ur=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:"pm validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function mr(e){if(typeof e!="string")return;let t=e.trim();for(let n of ur)if(t===n.code||t.startsWith(`${n.code}:`))return n}function fr(e){let t={};for(let n of e){let i=mr(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function _n(e){return Object.values(fr(e))}import oe from"node:fs/promises";import{createHash as pr}from"node:crypto";import gn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var yn=3,_r="history-drift-cache.json";function wn(e){return gn.join(e,"runtime",_r)}async function hr(e){try{let t=await oe.readFile(wn(e),"utf8"),n=JSON.parse(t);return n.version!==yn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function kn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function gr(e,t,n,i,r){let s=jt(e),o;try{o=await oe.stat(s)}catch(l){return kn(l,"ENOENT")||r.unreadableStreams.push(ie),!1}let a=r.missingStreams.length,c=await bn({itemId:ie,historyPath:s,stat:o,cached:t[ie],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(ie),n[ie]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function vn(e){return pr("sha256").update(e).digest("hex")}async function yr(e){let t=await oe.readFile(e,"utf8");return vn(t)}async function wr(e){let t=await oe.readFile(e,"utf8"),n=vn(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let o=s.trim();if(o.length===0)continue;let a=JSON.parse(o);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:Nt(i).ok,contentHash:n}:null}function kr(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function hn(e,t,n){try{let i=await wr(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function bn(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(kr(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await hn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await yr(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else i=t;return!e.verifyCacheHitByContent||i===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:i},cacheDirty:!1}:{verification:await hn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function En(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await hr(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Rt(e,u.id),f;try{f=await oe.stat(m)}catch(E){kn(E,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let g=s[u.id],p=await bn({itemId:u.id,historyPath:m,stat:f,cached:g,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),o[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:p.verification.contentHash,latest_after_hash:p.verification.latestAfterHash,chain_ok:p.verification.chainOk};let{body:_,...h}=u;Ot({metadata:h,body:_})!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await gr(e,s,o,c,i);if(a||=l,a||Object.keys(s).length!==Object.keys(o).length){let u=wn(e);try{await oe.mkdir(gn.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:yn,entries:o}))}catch{}}let d=[...new Set([...i.missingStreams,...i.unreadableStreams,...i.hashMismatches,...i.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...i,driftedItems:d}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var vr=["metadata","resolution"],Qe=["metadata","resolution","estimates","lifecycle"],br="completed";function et(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Sn(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function In(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=Sn(n.close_reason)??br;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${et(i)}`,gate:"resolution"})}return t}function Rn(e){let t=[];for(let n of e){let i=Sn(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${et(i)}`,gate:"metadata"})}return t}function xn(e,t){return e.map(n=>{let i=Bt(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function Cn(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function An(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${et(n.path)}`})}return t}function Tn(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new k(`--fix-scope values must not be empty. Supported values: ${Qe.join(", ")}.`,w.USAGE);return new Set(vr)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(Qe.includes(r)){n.add(r);continue}throw new k(`Unknown --fix-scope value "${i}". Supported values: ${Qe.join(", ")}.`,w.USAGE)}return n}function Pn(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function he(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var Er=/^([A-Z][A-Z0-9]*-\d+)\b/;function Sr(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Er.exec(t);return n?n[1]:null}function Fn(e){return typeof e=="string"&&e.trim().length>0}function Ln(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||Fn(i.duplicate_of))continue;let r=Sr(i.title);if(r===null)continue;let s=t.get(r);s||(s=[],t.set(r,s)),s.some(o=>o.id===i.id)||s.push({id:i.id,title:i.title,parent:Fn(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let s=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((i,r)=>i.code.localeCompare(r.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function $n(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var Dn=3;function Mn(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function On(e,t,n=Dn){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Dn,r=new Map;for(let s of t){let o=Mn(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{let o=(r.get(Mn(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Nn(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var Ir=/^[a-z][a-z0-9+.-]+:\/\//i;function ge(e){return Ir.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function Rr(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function jn(e){return`${e.item_id} ${e.link_kind}`}function Un(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Rr(r.classification,i.classification),r.owners.set(jn(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[jn(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function xr(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Bn(e){let t=[];for(let n of e)for(let i of n.items)t.push(`${n.path}:${n.classification} owner=${i.id} status=${i.status} field=${i.field} title="${xr(i.title)}"`);return t}import{execFile as Cr}from"node:child_process";import{realpath as Ar}from"node:fs/promises";import zn from"node:path";import{promisify as Tr}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Pr=Tr(Cr),Fr=32*1024*1024,Lr=1e4,$r=["search/eval-queries.json"];function tt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Dr(e){return`'${e.replaceAll("'","'\\''")}'`}async function Mr(e,t=Ar){return t(e).catch(()=>zn.resolve(e))}async function Gn(e){let t=await pe(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await Mr(e),i=tt(zn.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Ge.map(s=>`${i}/${tt(s)}`);try{let{stdout:s}=await Pr("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Fr,windowsHide:!0,timeout:Lr}),o=new Set($r.map(l=>`${i}/${l}`)),a=[...new Set(s.split("\0").filter(l=>l.length>0&&!o.has(tt(l))))].sort((l,d)=>l.localeCompare(d)),c=r.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Dr(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Or from"node:fs/promises";import D from"node:path";import Nr from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var jr=["path","scope","note"],Ur=["pattern","glob","path","scope","note"],Br=["path"],zr=["from","to"],Gr=new Set(["note","scope"]);function qn(e){let t=e??"project";if(!Me.includes(t))throw new k(`Invalid scope "${e}". Valid scopes: ${Me.join(", ")} (default: project).`,w.USAGE);return t}function Hn(e){return e.startsWith("```")||e.includes(`
13
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Kt(e)}function Wr(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Hn(n)||!n.includes(",")?[t]:Yt(n)})}function qr(e,t){return e?Wr(e).map(n=>{let i=n.trim(),r=Hn(i)?de(n,"--add"):{path:i};if(ue(r,"--add",jr),!r.path)throw new k(`--add requires path=<value> or a bare ${t} path`,w.USAGE);return{path:r.path,scope:qn(r.scope),note:r.note?.trim()||void 0}}):[]}function Hr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new k("--add-glob requires a glob pattern value",w.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--add-glob");ue(i,"--add-glob",Ur);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new k("--add-glob key/value form requires pattern=<glob>",w.USAGE);return{pattern:r,scope:qn(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Kr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new k("--remove requires a path value",w.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--remove"),r=Object.keys(i).filter(s=>Gr.has(s.toLowerCase()));if(r.length>0)throw new k(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,w.USAGE);if(ue(i,"--remove",Br),!i.path)throw new k("--remove key/value form requires path=<value>",w.USAGE);return i.path}return n}):[]}function Vr(e){return e?e.map(t=>{let n=de(t,"--migrate");ue(n,"--migrate",zr);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new k("--migrate requires from=<value> and to=<value>",w.USAGE);return{from:i,to:r}}):[]}function nt(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function q(e){return e.split(D.sep).join("/")}function it(e,t,n=process.cwd()){let i=e.trim();if(ge(i))return i;if(D.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return q(i.replaceAll("\\",D.sep));let r=D.relative(t,n);return r.startsWith(`..${D.sep}`)||r===".."||D.isAbsolute(r)?q(D.normalize(i)):q(D.relative(t,D.resolve(n,i)))}async function Yr(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=D.isAbsolute(r.pattern),o=await Nr(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>it(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function Jr(e,t,n){if(t===void 0)return e;if(!n)throw new k("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",w.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Xr(e){return`${e.path}::${e.scope}`}function rt(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function st(e){return[...new Map(e.map(t=>[Xr(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Zr(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ge(a)){o.push(a.trim());continue}let c=D.isAbsolute(a)?a:D.resolve(t,a);try{(await Or.stat(c)).isFile()?i.push(a):s.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function Qr(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=nt(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=nt(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>nt(o,i)),count:r}}function es(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=st(e);return i?r:rt(r)}async function Wn(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await Zr(t,e.workspaceRoot):void 0}}async function xe(e,t,n,i){let{metadataKey:r}=i,s=Vt(),o=z(process.cwd(),n.path),a=le(o),c=process.cwd();if(!await L(O(o)))throw new k(`Tracker is not initialized at ${o}. Run pm init first.`,w.NOT_FOUND);let l=await $(o),d=B(l,W()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),g=await s.resolveList(t.migrate,"--migrate"),p=qr(u,i.bareNoun).map(T=>({...T,path:it(T.path,a,c)})),_=Hr(m),h=await Yr(_,a,c),v=Jr([...p,...h],t.note,p.length>0||_.length>0),E=Kr(f).map(T=>it(T,a,c)),S=Vr(g);if(!(v.length>0||E.length>0||S.length>0)){let T=await ke(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!T)throw new k(`Item ${e} not found`,w.NOT_FOUND);let R=(await ve(T,{schema:l.schema})).document.metadata[r]??[];return Wn({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:a})}let G=ne(t.author,l.author_default),j=await be({pmRoot:o,settings:l,id:e,op:i.op,author:G,message:t.message,force:t.force,skipNoop:!0,mutate(T){let y=T.metadata,R=y[r]??[],te=[...R],Z=Qr(te,v,E,S),De=es(te,Z.adds,Z.removes,i.supportsAppendStable&&t.appendStable===!0);De.length>0?y[r]=De:delete y[r];let yt=!xt(R,De);return{changedFields:yt?[r]:[],warnings:yt&&Z.count>0?[`path_migrations_applied:${Z.count}`]:[]}}}),b=j.item[r]??[],A=j.warnings.find(T=>T.startsWith("path_migrations_applied:")),U=A?Number(A.slice(24)):0;return Wn({id:j.item.id,artifacts:b,changed:j.changedFields.includes(r),migrationsApplied:U,options:t,workspaceRoot:a})}function Ce(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Kn(e,t,n){let i=await xe(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ce(i,"docs")}import Vn from"node:fs/promises";import M from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var ts=32768;function ot(e){return q(M.normalize(e))}async function Ae(e){try{return await Vn.realpath(e)}catch{return M.resolve(e)}}function ae(e,t){let n=M.isAbsolute(e.path)?M.resolve(e.path):M.resolve(t,e.path);return`${ot(n)}::${e.scope}`}function Te(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Te(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Te(r,t?`${t}.${i}`:i,n)}function ns(e){let t=[];return Te(e.metadata,"metadata",t),Te(e.body,"body",t),t}function is(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function rs(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let s=new Set,o=r.value.slice(0,ts);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=is(l[0]);!d||s.has(d)||(s.add(d),t.push({field:r.field,value:d}))}}}return t}async function ss(e,t,n=t){let i=M.isAbsolute(e)?M.resolve(e):M.resolve(n,e),r;try{r=await Vn.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Ae(t),Ae(i)]);if(Oe(s,o)){let a=M.relative(s,o);return!a||a.startsWith("..")||M.isAbsolute(a)?void 0:{path:ot(a),scope:"project"}}return{path:ot(i),scope:"global"}}async function os(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>ae(c,t))),r=new Map,s=rs(ns(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await ss(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=ae(l,t),u=r.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(d,u)}return[...r.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:i.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function Yn(e,t,n){let i=await xe(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ce(i,"files")}async function as(e,t){let n=await Ae(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new k("Files lookup paths must not be empty.",w.USAGE);if(!M.isAbsolute(o))return q(o);let a=await Ae(o);return Oe(n,a)?q(M.relative(n,a)):q(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new k("Files lookup requires at least one path.",w.USAGE);return r}function cs(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new k(`Files lookup ${i} must be a non-negative integer.`,w.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Jn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function ls(e){if([e.strictRead,e.noTruncate,Tt()].includes(!0))return null;let t=await Wt(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Gt({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function ds(e){let t=[],i=(await qt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(o=>({item:o,files:(o.files??[]).filter(a=>e.paths.includes(q(a.path))&&(e.scope===void 0||a.scope===e.scope)).sort((a,c)=>{let l=a.path.localeCompare(c.path);return l===0?a.scope.localeCompare(c.scope):l})})).filter(o=>o.files.length>0).sort((o,a)=>{let c=o.item.priority-a.item.priority;if(c!==0)return c;let l=a.item.updated_at.localeCompare(o.item.updated_at);return l===0?o.item.id.localeCompare(a.item.id):l}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new k(`Files lookup could not read every item: ${r.join("; ")}`,w.GENERIC_FAILURE);let s=i.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<i.length,truncated:e.offset+s.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(o=>({item:Jn(o.item),files:o.files}))}}async function Tc(e,t){let n=z(process.cwd(),t.path),i=le(n);if(!await L(O(n)))throw new k(`Tracker is not initialized at ${n}. Run pm init first.`,w.NOT_FOUND);let r=await as(e.paths,i),s=await $(n),o=B(s,W()),{offset:a,limit:c}=cs(e),l=await ls({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:r,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Jn(d.item),files:d.files}))}:ds({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0})}async function Pc(e,t,n){let i=z(process.cwd(),n.path),r=le(i);if(!await L(O(i)))throw new k(`Tracker is not initialized at ${i}. Run pm init first.`,w.NOT_FOUND);let s=await $(i),o=B(s,W()),a=await ke(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new k(`Item ${e} not found`,w.NOT_FOUND);let c=await ve(a,{schema:s.schema}),l=await os(c.document,r,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let g=ne(t.author,s.author_default),p=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],h=new Set,v=await be({pmRoot:i,settings:s,id:e,op:"files_discover",author:g,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let A=[...b.metadata.files??[]],U=new Set(A.map(R=>ae(R,r)));_=[],h.clear();for(let[R,te]of p.entries()){let Z=ae(te,r);U.has(Z)||(A.push(te),U.add(Z),_.push(te),h.add(R))}let T=st(A),y=t.appendStable?T:rt(T);return y.length>0?b.metadata.files=y:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==p.length?[`files_discover_skipped_existing:${p.length-_.length}`]:[]}}}),E=v.item.files??[],S=new Set(_.map(b=>ae(b,r))),I=E.filter(b=>S.has(ae(b,r))),G=d.filter((b,A)=>!h.has(A)),j=[...u,...G];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:I.length,skipped_existing_count:j.length,candidates:l,added:I,skipped_existing:j}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var us=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),at=new Set(["--pm-path","--path","--author"]),ms={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},fs=new Set(["-p","--package"]),ps=new Set(["-c","--call"]),_s=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),hs=new Set(["-C","--prefix","--userconfig","--cache"]),Lc=new Set(["--cwd"]),$c=new Set(["--cwd"]),gs=new Set(["exec","x"]),Dc=new Set(["run","run-script"]),Mc=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function ys(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ws(e){let t=ks(e.split(" ").filter(s=>s.length>0));if(t.length===0)return null;let[n,...i]=t;if(Xn(n)||Zn(n))return i;if(n==="node"&&i[0]&&Zn(i[0]))return i.slice(1);let r=n==="npx"||n==="bunx"?ct(i):n==="pnpm"?Es(i):n==="npm"?Ss(i):null;return r&&(Xn(r.command)||bs(r.command))?r.args:null}var Qn=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of ys(s)){let c=ws(a),l=c?Is(c):null,d=l&&us.has(l.subcommand)?Rs(l.remaining,ms[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(d)}return[...o].sort((a,c)=>a.localeCompare(c))};function ks(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Oc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return n}}function Xn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function vs(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function bs(e){let t=vs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Zn(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function ct(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(ps.has(i)){t+=1;break}t+=fs.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ei(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Es(e){let t=ei(e,_s);return t?.subcommand!=="dlx"?null:ct(t.args)}function Ss(e){let t=ei(e,hs);return!t||!gs.has(t.subcommand)?null:ct(t.args)}function Is(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Rs(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(at.has(i)||t.has(i))&&(n+=1)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Ts=["src","tests","docs"],Ps=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Fs=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Ls=["resolution","expected_result","actual_result"],$s=["default","tracked-all","tracked-all-strict"],ti=["core","strict","custom"],Fe=["off","warn","error"];var dt=["author","acceptance_criteria","estimated_minutes","close_reason"],oi=[...dt,"reviewer","risk","confidence","sprint","release"],pt=Array.from(new Set(oi)),Ds={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},Ms={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},Os={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},Ns={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},js={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},Us=32*1024*1024,Bs=1e4,ai=40,K=5,zs=4096,Gs=255,Ws=As(Cs);function ci(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?ci(i):i);return t}function qs(e){return{...e,checks:e.checks.map(t=>({...t,details:ci(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function ee(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ni(e){return ee(e).replace(/\/+$/,"")}function N(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function $e(e,t){return Dt(e,t)??e}function ye(e,t){return t.terminal_statuses.has($e(e,t))}function J(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Pe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function Hs(e){let t=J(kt),n={blocked_reason:J(we.blocked_reason),resolution:J(we.resolution),actual_result:J(we.actual_result)},i=J(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:J(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:J(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:J(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:Pe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Pe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Pe(r.resolution,n.resolution)?"default":"settings",actual_result:Pe(r.actual_result,n.actual_result)?"default":"settings"}}}function li(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ti.includes(t))return t;throw new k(`Unknown --metadata-profile value "${e}". Supported values: ${ti.join(", ")}.`,w.USAGE)}function di(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new k(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,w.USAGE)}function ui(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new k(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,w.USAGE)}function Ks(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Ds[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function Vs(e,t,n){let i=Ks(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...dt],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...oi],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...dt],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Ys=new Set(["acceptance_criteria","estimated_minutes"]);function mi(e,t,n,i){return!i&&Ys.has(t)&&ye(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?$e(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function fi(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new k(`Unknown --scan-mode value "${e}". Supported values: ${$s.join(", ")}.`,w.USAGE)}function pi(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return F.resolve(t);let n=F.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return F.dirname(F.dirname(n));let r=F.resolve(process.cwd()),s=ii(n),o=ii(r),a=F.relative(s,o);return a.length===0||!a.startsWith("..")&&!F.isAbsolute(a)?n:r}function ii(e){try{return xs.native(e)}catch{return F.resolve(e)}}function _i(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function _t(e,t,n){let i=t.length>0?F.join(e,t):e,r;try{r=await ft.readdir(i,{withFileTypes:!0})}catch(s){if(_i(s,["ENOENT"]))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?F.join(t,s.name):s.name;if(s.isDirectory()){if(Fs.has(s.name))continue;await _t(e,o,n);continue}s.isFile()&&n.push(ee(o))}}async function ut(e){let t=[];for(let n of Ts)await _t(e,n,t);for(let n of Ps){let i=F.join(e,n);try{(await ft.stat(i)).isFile()&&t.push(ee(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function hi(e){try{let{stdout:t}=await Ws("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Us,windowsHide:!0,timeout:Bs}),n=t.split("\0").map(i=>ee(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function Js(e,t){let n=new Set,i=ni(wt);i.length>0&&n.add(i);let r=ni(F.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function ri(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Xs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await hi(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await ut(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await ut(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function C(e,t=K){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function X(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=C(e,ai);return{values:n.values,truncated:n.truncated,total:e.length}}var Zs={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},Qs={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function eo(e){let t=e.missing_fields.map(n=>`${Zs[n]} "${Qs[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function gi(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):_n(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function yi(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var to="validate_metadata_duplicate_issue_codes";function wi(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:K,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${to}:${e.length}`]}}function no(){return Object.fromEntries(pt.map(e=>[e,[]]))}function io(e,t,n){let i=no();for(let r of e)for(let s of pt)mi(r,s,t,n)&&i[s].push(r.id);return i}function ro(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${Ms[r]}:${s.length}`)}return i.push(...n),i}function ki(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=Os[i];s>0&&o&&(n[o]=s)}return n}function vi(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function so(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=Ns[r],a=js[r];if(!o||!a)continue;let c=C(s,i?s.length:K);e[o]=c.values,e[a]=c.truncated}}function bi(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Ei(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function oo(e,t,n,i){let r=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",o=io(e,n,s),a=Ln(e),c=wi(a,i),l=ro(t,o,c.warnings),d=ki(t,o),u=vi(t,o,r),m=$n(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...pt],counts:d,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),so(f,t,o,i);let g=bi(t,o,r),p=Ei(t,o,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:g,estimateBackfillRows:p}}function ao(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has($e(m.status,t))),s=[],o=[];for(let m of r){let f=Ls.filter(g=>!P(m[g]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:P(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:K,l=C(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>eo(m)),u=C(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Si(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ii(e,t="pm",n=Ne()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=N(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(l=>{let d=N(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>N(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>o.add(l));let c=N(s.definition_of_ready);return xi(c??"",t).filter(l=>i.has(l)).forEach(l=>o.add(l)),[s.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function Ri(e,t,n){let i=Jt(e,n?d=>ye(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:K,a=C(r,o),c=C(s,o),l=C(i.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function xi(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Si(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function ht(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.has(m)&&i.set(d,Math.min(i.get(d),n.get(m))):(a(m),i.set(d,Math.min(i.get(d),i.get(m))));if(i.get(d)!==n.get(d))return;let u=[];for(;r.length>0;){let m=r.pop();if(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return o.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function gt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(l=>i.has(l));for(let l of c){if(l===n&&r.length>1)return r.push(n),!0;if(!s.has(l)){if(s.add(l),r.push(l),o(l))return!0;r.pop(),s.delete(l)}}return!1};return o(n)?[...r]:[...e,n]}function Ci(e,t="pm"){let n=Ii(e,t),i=ht(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>gt(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Ai(e,t=Ne()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),i=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,o)=>s.id.localeCompare(o.id)).forEach(s=>{let o=i.get(s.id),a=N(s.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(s.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?i.get(u).push(s.id):o.push(u))})}),i.forEach((s,o)=>{i.set(o,[...new Set(s)].sort((a,c)=>a.localeCompare(c)))}),i}function Ti(e){let t=Ai(e),n=ht(t),i=[...new Set(n.flat())].sort((s,o)=>s.localeCompare(o)),r=n.map(s=>gt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function Pi(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Le(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Fi(e,t){let n=Le(e).split("/").filter(Boolean),i=Le(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function co(e,t){let n=Le(t),i=Le(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=Fi(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function lo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function uo(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=ee(o.path);if(a.length===0||a===e)return;let c=co(e,a);c!==null&&lo(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Li(e,t){return e.map(n=>{let i=Pi(n),r=i==="docs_unowned"?"docs":"files",s=uo(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function $i(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function mo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=N(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function fo(e,t,n,i,r){let s=N(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!ye(o.status,r)}}function po(e,t,n,i){let r=N(e.blocked_by),s=N(e.blocked_reason),o=s?.toLowerCase(),a=$e(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function _o(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!ye(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=mo(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=N(c.parent),u=d?r.get(s.get(d.toLowerCase())??d):void 0;if(u&&ye(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(fo(c,u,r,s,n))),t){let m=po(c,o,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,g)=>f.localeCompare(g))})}}return a}function ho(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function si(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function go(e,t,n,i,r,s){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=si("validate_lifecycle_dependency_cycles",n,r),c=si("validate_hierarchy_parent_cycle",i,s);return[...o,...a?[a]:[],...c?[c]:[]]}function Di(e){let t=ee(e);return t.length>zs||t.split(/[\\/]/).some(n=>n.length>Gs)}async function yo(e,t){let n=F.isAbsolute(t)?t:F.resolve(e,t);if(Di(n))return!1;try{let i=await ft.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return _i(i,["ENOENT","ENOTDIR"])}}async function wo(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ge(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=ee(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await yo(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function ko(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,l=c?[]:Js(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>ri(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!ri(f,l)),m={};if(d.length>0){let f=X(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Mi(e,t,n,i,r,s,o,a="pm"){let c=_o(e,t,r,s);ho(c);let l=Ci(c.activeItems,a),d=Ti(e),u=go(c,t,n,i,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:K,f=C(c.closureLikeRows.map(I=>`${I.id}:${I.fields.join(",")}`),m),g=C(c.terminalParentRows.map(I=>`${I.id}:${I.parent_id}:${I.parent_status}`),m),p=C(c.staleBlockerRows.map(I=>`${I.id}:${I.status}:${I.reasons.join(",")}`),m),_=C(l.cycle_item_ids,m),h=C(l.cycle_sample_paths,m),v=C(d.cycle_item_ids,m),E=C(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:g.values,active_terminal_parent_rows_truncated:g.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:p.values,stale_blocker_rows_truncated:p.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:h.values,dependency_cycle_sample_paths_truncated:h.truncated,parent_cycle_severity_policy:i,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Oi(e,t,n,i,r,s){let o=await wo(e,t),a=new Map(e.map(y=>[y.id,y])),c=[...new Set(o.missingLinkedPaths)].sort((y,R)=>y.localeCompare(R)),l=await Xs(t,i),d=ko(l,n,t,i,r,s),u=d.candidateFiles.filter(y=>!o.linkedProjectPaths.has(y)),m=Li(u,e),f=On(c,d.candidateFiles),g=new Map(f.map(y=>[y.path,y.classification])),p=f.filter(y=>y.classification==="moved").length,_=o.staleLinkRows.map(y=>({...y,classification:g.get(y.path)??"deleted"})).sort((y,R)=>y.item_id.localeCompare(R.item_id)||y.path.localeCompare(R.path)||y.link_kind.localeCompare(R.link_kind)),h=[];d.strictModeForcesPmInternals&&h.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&h.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&h.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((y,R)=>y.localeCompare(R)),E=X(v,s),S=X(c,s),I=X(u,s),G=X(m.map(y=>`${y.path}:${y.classification}:owner_candidate=${y.owner_candidate?.id??"unowned"}`),s),j=s?m:X($i(m),!1).values,b=X(Nn(f),s),A=_.map(y=>({item_id:y.item_id,path:y.path,link_kind:y.link_kind,classification:y.classification})),U=Un(A,y=>{let R=a.get(y);return R?{type:R.type,title:R.title,status:R.status}:void 0}),T=s?U:X(Bn(U),!1).values;return{check:{name:"files",status:h.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:ai,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:b.values,missing_linked_path_classifications_truncated:b.truncated,missing_linked_path_rows_count:U.length,missing_linked_path_rows:T,orphaned_paths_count:u.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:G.values,orphaned_path_classifications_truncated:G.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:j}},warnings:h,staleLinkPruneRows:_}}async function vo(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:s,chainMismatches:o,driftedItems:a}=await En(e,t),c=[];i.length>0&&c.push(`validate_history_drift_missing_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let l=n?Number.POSITIVE_INFINITY:K,d=C(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:i.length,unreadable_streams:r.length,hash_mismatches:s.length,chain_mismatches:o.length}}},warnings:c}}function bo(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function Ni(e,t,n){let i=new Set(e.map(_=>_.id.toLowerCase())),r=0,s=0,o=new Set,a=[],c=e.flatMap(_=>(_.tests??[]).map(h=>({item:_,linkedTest:h})));for(let{item:_,linkedTest:h}of c){if(typeof h.command!="string"||h.command.trim().length===0)continue;r+=1;let v=Qn(h.command,t);if(v.length!==0){s+=v.length;for(let E of v)o.add(E),i.has(E.toLowerCase())||a.push(bo(_.id,E,h.command))}}let l=[...new Set(a)].sort((_,h)=>_.localeCompare(h)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,h)=>_.localeCompare(h)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:K,f=C(l,m),g=C(d,m),p=C([...o].sort((_,h)=>_.localeCompare(h)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:p.values,unique_referenced_pm_ids_truncated:p.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:g.values,stale_pm_ids_truncated:g.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function Eo(e,t){let n=$t(e.map(c=>({ref:c.id,version:Lt(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:K,s=C(n.outdated,r),o=C(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:Ft,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var mt="pm validate auto-fix";async function ji(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:mt};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new k("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",w.USAGE);await n.runUpdate(e.item_id,i,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function lt(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Ui(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>lt(a)===null))try{await ji(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>lt(a)!==null)){let a=lt(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Yn(a.item_id,{remove:c,message:mt},t):await Kn(a.item_id,{remove:c,message:mt},t),i.push(...o)}catch(l){r.push(...o.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var El={applyValidateFix:ji,applyValidateFixes:Ui,attachValidateFixHints:gi,buildCommandReferencesCheck:Ni,buildDependencyReferencesCheck:Ri,buildCloseReasonBackfillRows:bi,buildFilesCheck:Oi,buildLifecycleCheck:Mi,buildLifecycleDependencyGraph:Ii,buildLifecycleParentGraph:Ai,buildEstimateBackfillRows:Ei,buildMetadataCounts:ki,buildMissingFieldOccurrences:vi,buildOrphanedPathRows:Li,classifyOrphanedPath:Pi,collectDefaultProjectFileCandidates:ut,collectTrackedGitFileCandidates:hi,detectLifecycleDependencyCycles:Ci,detectLifecycleParentCycles:Ti,escapeRegExp:Si,extractItemIds:xi,findLifecycleDependencyCycleComponents:ht,isMetadataFieldMissing:mi,linkedArtifactPathExceedsFilesystemLimits:Di,listFilesRecursive:_t,resolveDependencyCycleSeverity:di,resolveParentCycleSeverity:ui,resolveFileScanMode:fi,resolveLifecycleDependencyCycleSamplePath:gt,resolveRequestedChecks:yi,resolveValidateMetadataProfile:li,resolveWorkspaceRoot:pi,sharedDirectoryPrefixLength:Fi,summarizeOrphanedPathRows:$i,summarizeDuplicateIssueCodes:wi,toMeaningfulString:N};async function So(e,t,n,i){let r=await pn(e,new Set(t.map(m=>m.id)),n,{schema:i.schema,extensionFieldNames:vt(W())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await Gn(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await an(e,Se(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await pe(e),d=l===null?null:await cn(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await Xe(l);return u.length>0&&s.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":s.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function H(e,t,n){n&&gi(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Io(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=oo(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,H(t,r,n)}if(e.requestedChecks.has("resolution")){let r=ao(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,H(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Mi(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,H(t,r,n),H(t,Ri(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Oi(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,H(t,r,n)}return e.requestedChecks.has("command_references")&&H(t,Ni(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&H(t,await vo(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&H(t,Eo(e.items,i),n),e.requestedChecks.has("storage_integrity")&&H(t,await So(e.pmRoot,e.items,B(e.settings,W()).type_to_folder,e.settings),n),t}function Ro(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...Rn(t.closeReasonBackfillRows)),i.push(...In(t.resolutionBackfillRows)),i.push(...xn(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Cn(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...An(t.staleLinkPruneRows)),i}async function xo(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=Ro(e,t,n),{applicable:a,gated:c}=Pn(o,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Ui(a,r,s);d.push(...m.applied.map(he)),u.push(...m.failed.map(({fix:f,error:g})=>({...he(f),error:g instanceof Error?g.message:String(g)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(he),applied_fixes:d,gated_fixes:c.map(m=>({...he(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Sl(e,t,n={}){At(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new k("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",w.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new k("--fix-scope requires --auto-fix.",w.USAGE);let r=Tn(e.fixScope),s=z(process.cwd(),t.path);if(!await L(O(s)))throw new k(`Tracker is not initialized at ${s}. Run pm init first.`,w.NOT_FOUND);let o=await $(s),a=Ct(o.schema),c=B(o,W()),l=[],d=await Ht(s,o.item_format,c.type_to_folder,l,o.schema),u=yi(e);if(u.has("history_drift")){let A=await Ye(s);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=li(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),g=Vs(f,m,o.validation.metadata_required_fields),p=Hs(o),_=di(e.dependencyCycleSeverity),h=ui(e.parentCycleSeverity),v=fi(e.scanMode),E=pi(s),S=await Io({requestedChecks:u,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:d,statusRegistry:a,metadataPolicy:g,lifecyclePatternPolicy:p,dependencyCycleSeverity:_,parentCycleSeverity:h,fileScanMode:v,initialWarnings:[...new Set(l)]}),I=i?await xo(e,S,o,r,t,n):void 0,G=[...new Set(S.warnings)].sort((A,U)=>A.localeCompare(U)),b={ok:!S.checks.some(A=>A.status==="error"),has_warnings:G.length>0,checks:S.checks,warnings:G,...I!==void 0?{fixes:I}:{},generated_at:V(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...qs(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{To as a,Q as b,fe as c,pe as d,Ve as e,Se as f,an as g,cn as h,Ko as i,Vo as j,Ji as k,En as l,fr as m,Xi as n,dn as o,ea as p,Ye as q,ta as r,Gn as s,ua as t,ma as u,Xe as v,fa as w,pa as x,pn as y,Kn as z,Yn as A,Tc as B,Pc as C,_s as D,hs as E,Lc as F,$c as G,Dc as H,Mc as I,ys as J,ws as K,ks as L,Oc as M,Xn as N,bs as O,Zn as P,ct as Q,ei as R,Es as S,Ss as T,Is as U,qs as V,El as W,Sl as X};
14
- //# sourceMappingURL=chunk-BOGRY7M6.js.map
9
+ `;return d===r?{path:i,changed:!1}:(n||await Hi(i,d,"utf8"),{path:i,changed:!0})}function Se(e){let t=z(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function cn(e,t){let n=x.resolve(e),i=null,r="",s=n;for(let p=0;p<8;p+=1){let _=x.join(s,".gitattributes");try{let v=await Ee(_,"utf8");if(v.includes(Q)){i=s,r=v;break}}catch{}let h=x.dirname(s);if(h===s)break;s=h}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=x.join(i,".gitattributes"),a=r.indexOf(Q),c=r.indexOf(fe),l=c>a?r.slice(a+Q.length,c).split(`
10
+ `).map(p=>p.trim()).filter(p=>p.length>0):[],d=Ve(Ke(i,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),w=l.filter(p=>!m.has(p));return{status:f.length>0||w.length>0?"drift":"ok",path:o,missing_patterns:f,stale_patterns:w,schema_scope:"project"}}async function ln(e){let t=rn(),n=[],i=[];for(let r of sn){let s=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${o}`;try{let{stdout:c}=await He("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Ji(l,o)&&i.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function Jo(e){let t;try{t=await on(x.resolve(e))}catch{return{status:"no_git"}}let n=Ke(t,x.resolve(e)),i=await $(e),r=ne(void 0,i.author_default),s=await Pt(e,Yi,i.locks.ttl_seconds,r,!1,Bt(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=x.join(t,".gitattributes"),a;try{a=await Ee(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:o};throw u}if(!a.includes(Q))return{status:"not_installed",path:o};let c=await $(e),l=Se(c),d=await an(t,Ve(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Xo(e,t){let n=t.path?.trim(),i=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),s=n===void 0&&i!==void 0&&i.length>0&&r!==void 0&&r.length>0,o=n!==void 0?B(process.cwd(),n):s?x.resolve(r):B(process.cwd());if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let a=await on(n!==void 0?o:s?x.resolve(i):process.cwd());return Xi({pmRoot:o,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Xi(e){let t=x.resolve(e.pmRoot),n=x.resolve(e.workspaceRoot),i=e.dryRun===!0,r,s;try{[r,s]=await Promise.all([qe(t),qe(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Ke(s,r);if(We(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await $(r),c=Se(a),l=Ve(o,c),d=[],u=rn();for(let f of sn)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!i)try{for(let f of d)await He("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await an(s,l,i);return{ok:!0,dry_run:i,workspace_root:s,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"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."],generated_at:V()}}import Ie from"node:fs/promises";import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="364a8999-58e2-58c9-bfa6-acd8c42ec471")}catch{}})();var Zi="2026-07-15T06:22:12.276Z",Qi=Date.parse(Zi),er=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],dn=e=>typeof e=="string"?e:"",un=e=>{let t=e??{},n=dn(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(dn(t.ts))>=Qi);return er[i][r]};function mn(e,t,n=20,i=new Set,r=!1){let s=[],o=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let w;try{w=JSON.parse(f)}catch{continue}l+=1;let p=un(w);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var ia=(e,t,n=20,i=new Set)=>mn(e,t,n,i);function tr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Ye=async(e,t=20,n=!1)=>{let i=Re.join(e,"history"),r;try{r=(await Ie.readdir(i)).filter(h=>h.endsWith(".jsonl")).sort((h,v)=>h.localeCompare(v))}catch{r=[]}let s=new Set,o=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,w="_workspace.jsonl",p=new Set;if(r.includes(w))try{p=tr(await Ie.readFile(Re.join(i,w),"utf8"))}catch{p=new Set}for(let h of r){let v;try{v=await Ie.readFile(Re.join(i,h),"utf8")}catch{continue}let E=h.slice(0,-6),S=mn(E,v,t-o.length,p,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...s].sort((h,v)=>h.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:a}:{}}};async function ra(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),s=t.events??[];if(+(t.all_actionable===!0)+ +(s.length>0)>1)throw new TypeError("Author acknowledgment accepts either explicit events or all_actionable, not both.");let a=t.all_actionable===!0?(await Ye(e,0,!0)).actionable_events:s;if([a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1))throw new TypeError("Author acknowledgment requires events, reviewer, attributed_author, and reason.");let l=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){if([/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1))throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`);let w;try{let _=(await Ie.readFile(Re.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];w=JSON.parse(_??"")}catch{throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`)}if(un(w)!=="actionable_unknown")throw new TypeError(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`)}let d=await $(e),u=await Ut({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:i}},message:r,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as nr}from"node:child_process";import{randomUUID as ir}from"node:crypto";import{readdir as rr,readFile as sr}from"node:fs/promises";import _e from"node:path";import{promisify as or}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var ar=or(nr);async function Je(e){try{let{stdout:t}=await ar("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}function fn(e){return`${e}.json`}function pa(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Ue(je(t.retained)),discarded_hash:Ue(je(t.discarded))}))}}async function _a(e){let t=await Je(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=_e.basename(i,_e.extname(i)),s={version:1,id:ir(),item_path:i.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:V()};return await bt(t),await ce(_e.join(t,fn(s.id)),`${JSON.stringify(s,null,2)}
11
+ `),s}async function Xe(e,t={}){let n=await Je(e);if(n===null||!await L(n))return[];let i=[],r;try{r=await rr(n)}catch{return[]}for(let s of r.sort((o,a)=>o.localeCompare(a)))if(s.endsWith(".json"))try{let o=JSON.parse(await sr(_e.join(n,s),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&i.push(o)}catch{}return i.sort((s,o)=>s.created_at.localeCompare(o.created_at))}async function ha(e,t){let n=await Je(e);n!==null&&await ce(_e.join(n,fn(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:V()},null,2)}
12
+ `)}async function ga(e){let t=await Xe(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:V()}}import re from"node:fs/promises";import se from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function cr(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await re.readdir(se.join(e,r))}catch{return}for(let o of s)for(let a of It)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function lr(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=ze(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{s.unparseable.push({id:n,path:i,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&s.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(s.repairReconciliations+=1))}function Ze(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function dr(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await re.readdir(se.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await re.readFile(se.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ze("history stream",o)});continue}lr({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function pn(e){let t=ze(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function ur(e){let t=[],n=0,i=null;try{i=await Et(O(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Ze("configuration file",s)})}if(i!==null){n+=1;let s=pn(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await re.readdir(se.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await re.readFile(se.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Ze("configuration file",c)});continue}let a=pn(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function _n(e,t,n,i={}){let r=await cr(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,w)=>f.localeCompare(w))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=se.join(e,u.relativePath);return Mt(await re.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await dr(e,s),d=await ur(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import ft from"node:fs/promises";import{realpathSync as Cs}from"node:fs";import{execFile as As}from"node:child_process";import F from"node:path";import{promisify as Ts}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var mr=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:"pm validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function fr(e){if(typeof e!="string")return;let t=e.trim();for(let n of mr)if(t===n.code||t.startsWith(`${n.code}:`))return n}function pr(e){let t={};for(let n of e){let i=fr(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function hn(e){return Object.values(pr(e))}import oe from"node:fs/promises";import{createHash as _r}from"node:crypto";import yn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var wn=3,hr="history-drift-cache.json";function kn(e){return yn.join(e,"runtime",hr)}async function gr(e){try{let t=await oe.readFile(kn(e),"utf8"),n=JSON.parse(t);return n.version!==wn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function vn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function yr(e,t,n,i,r){let s=jt(e),o;try{o=await oe.stat(s)}catch(l){return vn(l,"ENOENT")||r.unreadableStreams.push(ie),!1}let a=r.missingStreams.length,c=await En({itemId:ie,historyPath:s,stat:o,cached:t[ie],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(ie),n[ie]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function bn(e){return _r("sha256").update(e).digest("hex")}async function wr(e){let t=await oe.readFile(e,"utf8");return bn(t)}async function kr(e){let t=await oe.readFile(e,"utf8"),n=bn(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let o=s.trim();if(o.length===0)continue;let a=JSON.parse(o);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:Nt(i).ok,contentHash:n}:null}function vr(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function gn(e,t,n){try{let i=await kr(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function En(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(vr(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await gn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await wr(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else i=t;return!e.verifyCacheHitByContent||i===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:i},cacheDirty:!1}:{verification:await gn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Sn(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await gr(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Rt(e,u.id),f;try{f=await oe.stat(m)}catch(E){vn(E,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let w=s[u.id],p=await En({itemId:u.id,historyPath:m,stat:f,cached:w,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),o[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:p.verification.contentHash,latest_after_hash:p.verification.latestAfterHash,chain_ok:p.verification.chainOk};let{body:_,...h}=u;Ot({metadata:h,body:_})!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await yr(e,s,o,c,i);if(a||=l,a||Object.keys(s).length!==Object.keys(o).length){let u=kn(e);try{await oe.mkdir(yn.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:wn,entries:o}))}catch{}}let d=[...new Set([...i.missingStreams,...i.unreadableStreams,...i.hashMismatches,...i.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...i,driftedItems:d}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var br=["metadata","resolution"],Qe=["metadata","resolution","estimates","lifecycle"],Er="completed";function et(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function In(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Rn(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=In(n.close_reason)??Er;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${et(i)}`,gate:"resolution"})}return t}function xn(e){let t=[];for(let n of e){let i=In(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${et(i)}`,gate:"metadata"})}return t}function Cn(e,t){return e.map(n=>{let i=zt(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function An(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function Tn(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${et(n.path)}`})}return t}function Pn(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${Qe.join(", ")}.`,g.USAGE);return new Set(br)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(Qe.includes(r)){n.add(r);continue}throw new y(`Unknown --fix-scope value "${i}". Supported values: ${Qe.join(", ")}.`,g.USAGE)}return n}function Fn(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function he(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var Sr=/^([A-Z][A-Z0-9]*-\d+)\b/;function Ir(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Sr.exec(t);return n?n[1]:null}function Ln(e){return typeof e=="string"&&e.trim().length>0}function $n(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||Ln(i.duplicate_of))continue;let r=Ir(i.title);if(r===null)continue;let s=t.get(r);s||(s=[],t.set(r,s)),s.some(o=>o.id===i.id)||s.push({id:i.id,title:i.title,parent:Ln(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let s=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((i,r)=>i.code.localeCompare(r.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function Dn(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var Mn=3;function On(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Nn(e,t,n=Mn){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Mn,r=new Map;for(let s of t){let o=On(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{let o=(r.get(On(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function jn(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var Rr=/^[a-z][a-z0-9+.-]+:\/\//i;function ge(e){return Rr.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function xr(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Un(e){return`${e.item_id} ${e.link_kind}`}function zn(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=xr(r.classification,i.classification),r.owners.set(Un(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Un(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function Cr(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Bn(e){let t=[];for(let n of e)for(let i of n.items)t.push(`${n.path}:${n.classification} owner=${i.id} status=${i.status} field=${i.field} title="${Cr(i.title)}"`);return t}import{execFile as Ar}from"node:child_process";import{realpath as Tr}from"node:fs/promises";import Gn from"node:path";import{promisify as Pr}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Fr=Pr(Ar),Lr=32*1024*1024,$r=1e4,Dr=["search/eval-queries.json"];function tt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Mr(e){return`'${e.replaceAll("'","'\\''")}'`}async function Or(e,t=Tr){return t(e).catch(()=>Gn.resolve(e))}async function Wn(e){let t=await pe(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await Or(e),i=tt(Gn.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Ge.map(s=>`${i}/${tt(s)}`);try{let{stdout:s}=await Fr("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Lr,windowsHide:!0,timeout:$r}),o=new Set(Dr.map(l=>`${i}/${l}`)),a=[...new Set(s.split("\0").filter(l=>l.length>0&&!o.has(tt(l))))].sort((l,d)=>l.localeCompare(d)),c=r.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Mr(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Nr from"node:fs/promises";import D from"node:path";import jr from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var Ur=["path","scope","note"],zr=["pattern","glob","path","scope","note"],Br=["path"],Gr=["from","to"],Wr=new Set(["note","scope"]);function Hn(e){let t=e??"project";if(!Me.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Me.join(", ")} (default: project).`,g.USAGE);return t}function Kn(e){return e.startsWith("```")||e.includes(`
13
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Kt(e)}function qr(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Kn(n)||!n.includes(",")?[t]:Yt(n)})}function Hr(e,t){return e?qr(e).map(n=>{let i=n.trim(),r=Kn(i)?de(n,"--add"):{path:i};if(ue(r,"--add",Ur),!r.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return{path:r.path,scope:Hn(r.scope),note:r.note?.trim()||void 0}}):[]}function Kr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--add-glob");ue(i,"--add-glob",zr);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:r,scope:Hn(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Vr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--remove"),r=Object.keys(i).filter(s=>Wr.has(s.toLowerCase()));if(r.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(ue(i,"--remove",Br),!i.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return i.path}return n}):[]}function Yr(e){return e?e.map(t=>{let n=de(t,"--migrate");ue(n,"--migrate",Gr);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:i,to:r}}):[]}function nt(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function q(e){return e.split(D.sep).join("/")}function it(e,t,n=process.cwd()){let i=e.trim();if(ge(i))return i;if(D.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return q(i.replaceAll("\\",D.sep));let r=D.relative(t,n);return r.startsWith(`..${D.sep}`)||r===".."||D.isAbsolute(r)?q(D.normalize(i)):q(D.relative(t,D.resolve(n,i)))}async function Jr(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=D.isAbsolute(r.pattern),o=await jr(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>it(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function Xr(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Zr(e){return`${e.path}::${e.scope}`}function rt(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function st(e){return[...new Map(e.map(t=>[Zr(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Qr(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ge(a)){o.push(a.trim());continue}let c=D.isAbsolute(a)?a:D.resolve(t,a);try{(await Nr.stat(c)).isFile()?i.push(a):s.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function es(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=nt(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=nt(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>nt(o,i)),count:r}}function ts(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=st(e);return i?r:rt(r)}async function qn(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await Qr(t,e.workspaceRoot):void 0}}async function xe(e,t,n,i){let{metadataKey:r}=i,s=Vt(),o=B(process.cwd(),n.path),a=le(o),c=process.cwd();if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let l=await $(o),d=z(l,W()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),w=await s.resolveList(t.migrate,"--migrate"),p=Hr(u,i.bareNoun).map(T=>({...T,path:it(T.path,a,c)})),_=Kr(m),h=await Jr(_,a,c),v=Xr([...p,...h],t.note,p.length>0||_.length>0),E=Vr(f).map(T=>it(T,a,c)),S=Yr(w);if(!(v.length>0||E.length>0||S.length>0)){let T=await ke(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!T)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await ve(T,{schema:l.schema})).document.metadata[r]??[];return qn({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:a})}let G=ne(t.author,l.author_default),j=await be({pmRoot:o,settings:l,id:e,op:i.op,author:G,message:t.message,force:t.force,skipNoop:!0,mutate(T){let k=T.metadata,R=k[r]??[],te=[...R],Z=es(te,v,E,S),De=ts(te,Z.adds,Z.removes,i.supportsAppendStable&&t.appendStable===!0);De.length>0?k[r]=De:delete k[r];let yt=!xt(R,De);return{changedFields:yt?[r]:[],warnings:yt&&Z.count>0?[`path_migrations_applied:${Z.count}`]:[]}}}),b=j.item[r]??[],A=j.warnings.find(T=>T.startsWith("path_migrations_applied:")),U=A?Number(A.slice(24)):0;return qn({id:j.item.id,artifacts:b,changed:j.changedFields.includes(r),migrationsApplied:U,options:t,workspaceRoot:a})}function Ce(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Vn(e,t,n){let i=await xe(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ce(i,"docs")}import Yn from"node:fs/promises";import M from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var ns=32768;function ot(e){return q(M.normalize(e))}async function Ae(e){try{return await Yn.realpath(e)}catch{return M.resolve(e)}}function ae(e,t){let n=M.isAbsolute(e.path)?M.resolve(e.path):M.resolve(t,e.path);return`${ot(n)}::${e.scope}`}function Te(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Te(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Te(r,t?`${t}.${i}`:i,n)}function is(e){let t=[];return Te(e.metadata,"metadata",t),Te(e.body,"body",t),t}function rs(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function ss(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let s=new Set,o=r.value.slice(0,ns);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=rs(l[0]);!d||s.has(d)||(s.add(d),t.push({field:r.field,value:d}))}}}return t}async function os(e,t,n=t){let i=M.isAbsolute(e)?M.resolve(e):M.resolve(n,e),r;try{r=await Yn.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Ae(t),Ae(i)]);if(Oe(s,o)){let a=M.relative(s,o);return!a||a.startsWith("..")||M.isAbsolute(a)?void 0:{path:ot(a),scope:"project"}}return{path:ot(i),scope:"global"}}async function as(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>ae(c,t))),r=new Map,s=ss(is(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await os(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=ae(l,t),u=r.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(d,u)}return[...r.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:i.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function Jn(e,t,n){let i=await xe(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ce(i,"files")}async function cs(e,t){let n=await Ae(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!M.isAbsolute(o))return q(o);let a=await Ae(o);return Oe(n,a)?q(M.relative(n,a)):q(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return r}function ls(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new y(`Files lookup ${i} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Xn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function ds(e){if([e.strictRead,e.noTruncate,Tt()].includes(!0))return null;let t=await Wt(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Gt({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function us(e){let t=[],i=(await qt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(o=>({item:o,files:(o.files??[]).filter(a=>e.paths.includes(q(a.path))&&(e.scope===void 0||a.scope===e.scope)).sort((a,c)=>{let l=a.path.localeCompare(c.path);return l===0?a.scope.localeCompare(c.scope):l})})).filter(o=>o.files.length>0).sort((o,a)=>{let c=o.item.priority-a.item.priority;if(c!==0)return c;let l=a.item.updated_at.localeCompare(o.item.updated_at);return l===0?o.item.id.localeCompare(a.item.id):l}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new y(`Files lookup could not read every item: ${r.join("; ")}`,g.GENERIC_FAILURE);let s=i.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<i.length,truncated:e.offset+s.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(o=>({item:Xn(o.item),files:o.files}))}}async function Lc(e,t){let n=B(process.cwd(),t.path),i=le(n);if(!await L(O(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let r=await cs(e.paths,i),s=await $(n),o=z(s,W()),{offset:a,limit:c}=ls(e),l=await ds({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:r,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Xn(d.item),files:d.files}))}:us({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0})}async function $c(e,t,n){let i=B(process.cwd(),n.path),r=le(i);if(!await L(O(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let s=await $(i),o=z(s,W()),a=await ke(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await ve(a,{schema:s.schema}),l=await as(c.document,r,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let w=ne(t.author,s.author_default),p=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],h=new Set,v=await be({pmRoot:i,settings:s,id:e,op:"files_discover",author:w,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let A=[...b.metadata.files??[]],U=new Set(A.map(R=>ae(R,r)));_=[],h.clear();for(let[R,te]of p.entries()){let Z=ae(te,r);U.has(Z)||(A.push(te),U.add(Z),_.push(te),h.add(R))}let T=st(A),k=t.appendStable?T:rt(T);return k.length>0?b.metadata.files=k:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==p.length?[`files_discover_skipped_existing:${p.length-_.length}`]:[]}}}),E=v.item.files??[],S=new Set(_.map(b=>ae(b,r))),I=E.filter(b=>S.has(ae(b,r))),G=d.filter((b,A)=>!h.has(A)),j=[...u,...G];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:I.length,skipped_existing_count:j.length,candidates:l,added:I,skipped_existing:j}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var ms=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),at=new Set(["--pm-path","--path","--author"]),fs={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},ps=new Set(["-p","--package"]),_s=new Set(["-c","--call"]),hs=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),gs=new Set(["-C","--prefix","--userconfig","--cache"]),Mc=new Set(["--cwd"]),Oc=new Set(["--cwd"]),ys=new Set(["exec","x"]),Nc=new Set(["run","run-script"]),jc=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function ws(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ks(e){let t=vs(e.split(" ").filter(s=>s.length>0));if(t.length===0)return null;let[n,...i]=t;if(Zn(n)||Qn(n))return i;if(n==="node"&&i[0]&&Qn(i[0]))return i.slice(1);let r=n==="npx"||n==="bunx"?ct(i):n==="pnpm"?Ss(i):n==="npm"?Is(i):null;return r&&(Zn(r.command)||Es(r.command))?r.args:null}var ei=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of ws(s)){let c=ks(a),l=c?Rs(c):null,d=l&&ms.has(l.subcommand)?xs(l.remaining,fs[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(d)}return[...o].sort((a,c)=>a.localeCompare(c))};function vs(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Uc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return n}}function Zn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function bs(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function Es(e){let t=bs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Qn(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function ct(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(_s.has(i)){t+=1;break}t+=ps.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ti(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Ss(e){let t=ti(e,hs);return t?.subcommand!=="dlx"?null:ct(t.args)}function Is(e){let t=ti(e,gs);return!t||!ys.has(t.subcommand)?null:ct(t.args)}function Rs(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function xs(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(at.has(i)||t.has(i))&&(n+=1)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Ps=["src","tests","docs"],Fs=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Ls=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),$s=["resolution","expected_result","actual_result"],Ds=["default","tracked-all","tracked-all-strict"],ni=["core","strict","custom"],Fe=["off","warn","error"];var dt=["author","acceptance_criteria","estimated_minutes","close_reason"],ai=[...dt,"reviewer","risk","confidence","sprint","release"],pt=Array.from(new Set(ai)),Ms={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},Os={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},Ns={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},js={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},Us={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},zs=32*1024*1024,Bs=1e4,ci=40,K=5,Gs=4096,Ws=255,qs=Ts(As);function li(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?li(i):i);return t}function Hs(e){return{...e,checks:e.checks.map(t=>({...t,details:li(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function ee(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ii(e){return ee(e).replace(/\/+$/,"")}function N(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function $e(e,t){return Dt(e,t)??e}function ye(e,t){return t.terminal_statuses.has($e(e,t))}function J(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Pe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function Ks(e){let t=J(kt),n={blocked_reason:J(we.blocked_reason),resolution:J(we.resolution),actual_result:J(we.actual_result)},i=J(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:J(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:J(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:J(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:Pe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Pe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Pe(r.resolution,n.resolution)?"default":"settings",actual_result:Pe(r.actual_result,n.actual_result)?"default":"settings"}}}function di(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ni.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${ni.join(", ")}.`,g.USAGE)}function ui(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,g.USAGE)}function mi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,g.USAGE)}function Vs(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Ms[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function Ys(e,t,n){let i=Vs(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...dt],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...ai],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...dt],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Js=new Set(["acceptance_criteria","estimated_minutes"]);function fi(e,t,n,i){return!i&&Js.has(t)&&ye(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?$e(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function pi(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new y(`Unknown --scan-mode value "${e}". Supported values: ${Ds.join(", ")}.`,g.USAGE)}function _i(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return F.resolve(t);let n=F.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return F.dirname(F.dirname(n));let r=F.resolve(process.cwd()),s=ri(n),o=ri(r),a=F.relative(s,o);return a.length===0||!a.startsWith("..")&&!F.isAbsolute(a)?n:r}function ri(e){try{return Cs.native(e)}catch{return F.resolve(e)}}function hi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function _t(e,t,n){let i=t.length>0?F.join(e,t):e,r;try{r=await ft.readdir(i,{withFileTypes:!0})}catch(s){if(hi(s,["ENOENT"]))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?F.join(t,s.name):s.name;if(s.isDirectory()){if(Ls.has(s.name))continue;await _t(e,o,n);continue}s.isFile()&&n.push(ee(o))}}async function ut(e){let t=[];for(let n of Ps)await _t(e,n,t);for(let n of Fs){let i=F.join(e,n);try{(await ft.stat(i)).isFile()&&t.push(ee(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function gi(e){try{let{stdout:t}=await qs("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:zs,windowsHide:!0,timeout:Bs}),n=t.split("\0").map(i=>ee(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function Xs(e,t){let n=new Set,i=ii(wt);i.length>0&&n.add(i);let r=ii(F.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function si(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Zs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await gi(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await ut(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await ut(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function C(e,t=K){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function X(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=C(e,ci);return{values:n.values,truncated:n.truncated,total:e.length}}var Qs={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},eo={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function to(e){let t=e.missing_fields.map(n=>`${Qs[n]} "${eo[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function yi(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):hn(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function wi(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var no="validate_metadata_duplicate_issue_codes";function ki(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:K,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${no}:${e.length}`]}}function io(){return Object.fromEntries(pt.map(e=>[e,[]]))}function ro(e,t,n){let i=io();for(let r of e)for(let s of pt)fi(r,s,t,n)&&i[s].push(r.id);return i}function so(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${Os[r]}:${s.length}`)}return i.push(...n),i}function vi(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=Ns[i];s>0&&o&&(n[o]=s)}return n}function bi(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function oo(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=js[r],a=Us[r];if(!o||!a)continue;let c=C(s,i?s.length:K);e[o]=c.values,e[a]=c.truncated}}function Ei(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Si(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function ao(e,t,n,i){let r=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",o=ro(e,n,s),a=$n(e),c=ki(a,i),l=so(t,o,c.warnings),d=vi(t,o),u=bi(t,o,r),m=Dn(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...pt],counts:d,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),oo(f,t,o,i);let w=Ei(t,o,r),p=Si(t,o,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:w,estimateBackfillRows:p}}function co(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has($e(m.status,t))),s=[],o=[];for(let m of r){let f=$s.filter(w=>!P(m[w]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:P(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:K,l=C(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>to(m)),u=C(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:o}}function Ii(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ri(e,t="pm",n=Ne()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=N(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(l=>{let d=N(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>N(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>o.add(l));let c=N(s.definition_of_ready);return Ci(c??"",t).filter(l=>i.has(l)).forEach(l=>o.add(l)),[s.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function xi(e,t,n){let i=Jt(e,n?d=>ye(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:K,a=C(r,o),c=C(s,o),l=C(i.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function Ci(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Ii(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function ht(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.has(m)&&i.set(d,Math.min(i.get(d),n.get(m))):(a(m),i.set(d,Math.min(i.get(d),i.get(m))));if(i.get(d)!==n.get(d))return;let u=[];for(;r.length>0;){let m=r.pop();if(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return o.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function gt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=a=>{let c=(t.get(a)??[]).filter(l=>i.has(l));for(let l of c){if(l===n&&r.length>1)return r.push(n),!0;if(!s.has(l)){if(s.add(l),r.push(l),o(l))return!0;r.pop(),s.delete(l)}}return!1};return o(n)?[...r]:[...e,n]}function Ai(e,t="pm"){let n=Ri(e,t),i=ht(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>gt(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Ti(e,t=Ne()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),i=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,o)=>s.id.localeCompare(o.id)).forEach(s=>{let o=i.get(s.id),a=N(s.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(s.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?i.get(u).push(s.id):o.push(u))})}),i.forEach((s,o)=>{i.set(o,[...new Set(s)].sort((a,c)=>a.localeCompare(c)))}),i}function Pi(e){let t=Ti(e),n=ht(t),i=[...new Set(n.flat())].sort((s,o)=>s.localeCompare(o)),r=n.map(s=>gt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function Fi(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Le(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Li(e,t){let n=Le(e).split("/").filter(Boolean),i=Le(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function lo(e,t){let n=Le(t),i=Le(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=Li(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function uo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function mo(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=ee(o.path);if(a.length===0||a===e)return;let c=lo(e,a);c!==null&&uo(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function $i(e,t){return e.map(n=>{let i=Fi(n),r=i==="docs_unowned"?"docs":"files",s=mo(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Di(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function fo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=N(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function po(e,t,n,i,r){let s=N(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!ye(o.status,r)}}function _o(e,t,n,i){let r=N(e.blocked_by),s=N(e.blocked_reason),o=s?.toLowerCase(),a=$e(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function ho(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!ye(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=fo(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=N(c.parent),u=d?r.get(s.get(d.toLowerCase())??d):void 0;if(u&&ye(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(po(c,u,r,s,n))),t){let m=_o(c,o,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,w)=>f.localeCompare(w))})}}return a}function go(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function oi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function yo(e,t,n,i,r,s){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=oi("validate_lifecycle_dependency_cycles",n,r),c=oi("validate_hierarchy_parent_cycle",i,s);return[...o,...a?[a]:[],...c?[c]:[]]}function Mi(e){let t=ee(e);return t.length>Gs||t.split(/[\\/]/).some(n=>n.length>Ws)}async function wo(e,t){let n=F.isAbsolute(t)?t:F.resolve(e,t);if(Mi(n))return!1;try{let i=await ft.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return hi(i,["ENOENT","ENOTDIR"])}}async function ko(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ge(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=ee(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await wo(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function vo(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,l=c?[]:Xs(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>si(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!si(f,l)),m={};if(d.length>0){let f=X(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Oi(e,t,n,i,r,s,o,a="pm"){let c=ho(e,t,r,s);go(c);let l=Ai(c.activeItems,a),d=Pi(e),u=yo(c,t,n,i,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:K,f=C(c.closureLikeRows.map(I=>`${I.id}:${I.fields.join(",")}`),m),w=C(c.terminalParentRows.map(I=>`${I.id}:${I.parent_id}:${I.parent_status}`),m),p=C(c.staleBlockerRows.map(I=>`${I.id}:${I.status}:${I.reasons.join(",")}`),m),_=C(l.cycle_item_ids,m),h=C(l.cycle_sample_paths,m),v=C(d.cycle_item_ids,m),E=C(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:w.values,active_terminal_parent_rows_truncated:w.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:p.values,stale_blocker_rows_truncated:p.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:h.values,dependency_cycle_sample_paths_truncated:h.truncated,parent_cycle_severity_policy:i,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Ni(e,t,n,i,r,s){let o=await ko(e,t),a=new Map(e.map(k=>[k.id,k])),c=[...new Set(o.missingLinkedPaths)].sort((k,R)=>k.localeCompare(R)),l=await Zs(t,i),d=vo(l,n,t,i,r,s),u=d.candidateFiles.filter(k=>!o.linkedProjectPaths.has(k)),m=$i(u,e),f=Nn(c,d.candidateFiles),w=new Map(f.map(k=>[k.path,k.classification])),p=f.filter(k=>k.classification==="moved").length,_=o.staleLinkRows.map(k=>({...k,classification:w.get(k.path)??"deleted"})).sort((k,R)=>k.item_id.localeCompare(R.item_id)||k.path.localeCompare(R.path)||k.link_kind.localeCompare(R.link_kind)),h=[];d.strictModeForcesPmInternals&&h.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&h.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&h.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((k,R)=>k.localeCompare(R)),E=X(v,s),S=X(c,s),I=X(u,s),G=X(m.map(k=>`${k.path}:${k.classification}:owner_candidate=${k.owner_candidate?.id??"unowned"}`),s),j=s?m:X(Di(m),!1).values,b=X(jn(f),s),A=_.map(k=>({item_id:k.item_id,path:k.path,link_kind:k.link_kind,classification:k.classification})),U=zn(A,k=>{let R=a.get(k);return R?{type:R.type,title:R.title,status:R.status}:void 0}),T=s?U:X(Bn(U),!1).values;return{check:{name:"files",status:h.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:ci,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:b.values,missing_linked_path_classifications_truncated:b.truncated,missing_linked_path_rows_count:U.length,missing_linked_path_rows:T,orphaned_paths_count:u.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:G.values,orphaned_path_classifications_truncated:G.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:j}},warnings:h,staleLinkPruneRows:_}}async function bo(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:s,chainMismatches:o,driftedItems:a}=await Sn(e,t),c=[];i.length>0&&c.push(`validate_history_drift_missing_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let l=n?Number.POSITIVE_INFINITY:K,d=C(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:i.length,unreadable_streams:r.length,hash_mismatches:s.length,chain_mismatches:o.length}}},warnings:c}}function Eo(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function ji(e,t,n){let i=new Set(e.map(_=>_.id.toLowerCase())),r=0,s=0,o=new Set,a=[],c=e.flatMap(_=>(_.tests??[]).map(h=>({item:_,linkedTest:h})));for(let{item:_,linkedTest:h}of c){if(typeof h.command!="string"||h.command.trim().length===0)continue;r+=1;let v=ei(h.command,t);if(v.length!==0){s+=v.length;for(let E of v)o.add(E),i.has(E.toLowerCase())||a.push(Eo(_.id,E,h.command))}}let l=[...new Set(a)].sort((_,h)=>_.localeCompare(h)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,h)=>_.localeCompare(h)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:K,f=C(l,m),w=C(d,m),p=C([...o].sort((_,h)=>_.localeCompare(h)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:p.values,unique_referenced_pm_ids_truncated:p.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function So(e,t){let n=$t(e.map(c=>({ref:c.id,version:Lt(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:K,s=C(n.outdated,r),o=C(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:Ft,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var mt="pm validate auto-fix";async function Ui(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:mt};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,i,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function lt(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function zi(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>lt(a)===null))try{await Ui(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>lt(a)!==null)){let a=lt(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Jn(a.item_id,{remove:c,message:mt},t):await Vn(a.item_id,{remove:c,message:mt},t),i.push(...o)}catch(l){r.push(...o.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Rl={applyValidateFix:Ui,applyValidateFixes:zi,attachValidateFixHints:yi,buildCommandReferencesCheck:ji,buildDependencyReferencesCheck:xi,buildCloseReasonBackfillRows:Ei,buildFilesCheck:Ni,buildLifecycleCheck:Oi,buildLifecycleDependencyGraph:Ri,buildLifecycleParentGraph:Ti,buildEstimateBackfillRows:Si,buildMetadataCounts:vi,buildMissingFieldOccurrences:bi,buildOrphanedPathRows:$i,classifyOrphanedPath:Fi,collectDefaultProjectFileCandidates:ut,collectTrackedGitFileCandidates:gi,detectLifecycleDependencyCycles:Ai,detectLifecycleParentCycles:Pi,escapeRegExp:Ii,extractItemIds:Ci,findLifecycleDependencyCycleComponents:ht,isMetadataFieldMissing:fi,linkedArtifactPathExceedsFilesystemLimits:Mi,listFilesRecursive:_t,resolveDependencyCycleSeverity:ui,resolveParentCycleSeverity:mi,resolveFileScanMode:pi,resolveLifecycleDependencyCycleSamplePath:gt,resolveRequestedChecks:wi,resolveValidateMetadataProfile:di,resolveWorkspaceRoot:_i,sharedDirectoryPrefixLength:Li,summarizeOrphanedPathRows:Di,summarizeDuplicateIssueCodes:ki,toMeaningfulString:N};async function Io(e,t,n,i){let r=await _n(e,new Set(t.map(m=>m.id)),n,{schema:i.schema,extensionFieldNames:vt(W())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await Wn(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await cn(e,Se(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await pe(e),d=l===null?null:await ln(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await Xe(l);return u.length>0&&s.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":s.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:s}}function H(e,t,n){n&&yi(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Ro(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=ao(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,H(t,r,n)}if(e.requestedChecks.has("resolution")){let r=co(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,H(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Oi(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,H(t,r,n),H(t,xi(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Ni(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,H(t,r,n)}return e.requestedChecks.has("command_references")&&H(t,ji(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&H(t,await bo(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&H(t,So(e.items,i),n),e.requestedChecks.has("storage_integrity")&&H(t,await Io(e.pmRoot,e.items,z(e.settings,W()).type_to_folder,e.settings),n),t}function xo(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...xn(t.closeReasonBackfillRows)),i.push(...Rn(t.resolutionBackfillRows)),i.push(...Cn(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...An(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Tn(t.staleLinkPruneRows)),i}async function Co(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=xo(e,t,n),{applicable:a,gated:c}=Fn(o,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await zi(a,r,s);d.push(...m.applied.map(he)),u.push(...m.failed.map(({fix:f,error:w})=>({...he(f),error:w instanceof Error?w.message:String(w)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(he),applied_fixes:d,gated_fixes:c.map(m=>({...he(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function xl(e,t,n={}){At(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let r=Pn(e.fixScope),s=B(process.cwd(),t.path);if(!await L(O(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,g.NOT_FOUND);let o=await $(s),a=Ct(o.schema),c=z(o,W()),l=[],d=await Ht(s,o.item_format,c.type_to_folder,l,o.schema),u=wi(e);if(u.has("history_drift")){let A=await Ye(s);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=di(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),w=Ys(f,m,o.validation.metadata_required_fields),p=Ks(o),_=ui(e.dependencyCycleSeverity),h=mi(e.parentCycleSeverity),v=pi(e.scanMode),E=_i(s),S=await Ro({requestedChecks:u,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:d,statusRegistry:a,metadataPolicy:w,lifecyclePatternPolicy:p,dependencyCycleSeverity:_,parentCycleSeverity:h,fileScanMode:v,initialWarnings:[...new Set(l)]}),I=i?await Co(e,S,o,r,t,n):void 0,G=[...new Set(S.warnings)].sort((A,U)=>A.localeCompare(U)),b={ok:!S.checks.some(A=>A.status==="error"),has_warnings:G.length>0,checks:S.checks,warnings:G,...I!==void 0?{fixes:I}:{},generated_at:V(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...Hs(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Lo as a,Q as b,fe as c,pe as d,Ve as e,Se as f,cn as g,ln as h,Jo as i,Xo as j,Xi as k,Sn as l,pr as m,Zi as n,un as o,ia as p,Ye as q,ra as r,Wn as s,pa as t,_a as u,Xe as v,ha as w,ga as x,_n as y,Vn as z,Jn as A,Lc as B,$c as C,hs as D,gs as E,Mc as F,Oc as G,Nc as H,jc as I,ws as J,ks as K,vs as L,Uc as M,Zn as N,Es as O,Qn as P,ct as Q,ti as R,Ss as S,Is as T,Rs as U,Hs as V,Rl as W,xl as X};
14
+ //# sourceMappingURL=chunk-YHDCGUIW.js.map