@unbrained/pm-cli 2026.11.13 → 2026.11.15

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 (289) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/extension-command-help.js +2 -2
  4. package/dist/cli/register-mutation.js +2 -2
  5. package/dist/cli/register-operations.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/chunk-6UTBX62V.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-GWVP23RZ.js → chunk-7AODVNHX.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +9 -0
  10. package/dist/cli-bundle/chunks/{chunk-PUU5DXSV.js → chunk-DBUBX4DL.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-5LG5YZYF.js → chunk-E4B2HWH7.js} +13 -13
  12. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +6 -0
  13. package/dist/cli-bundle/chunks/chunk-FSE624WQ.js +2 -0
  14. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +20 -0
  15. package/dist/cli-bundle/chunks/chunk-GAFALSR2.js +8 -0
  16. package/dist/cli-bundle/chunks/{chunk-LKVFPQNY.js → chunk-GCSKHCYK.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-HMVZSXB4.js +8 -0
  18. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +31 -0
  19. package/dist/cli-bundle/chunks/chunk-J6L3Q5J4.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-KLWGIEDC.js +114 -0
  21. package/dist/cli-bundle/chunks/chunk-KSLPRST2.js +10 -0
  22. package/dist/cli-bundle/chunks/chunk-LC6DL446.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-UFZQPKQS.js → chunk-NAX554KY.js} +35 -35
  24. package/dist/cli-bundle/chunks/chunk-PMIGRSNZ.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-Q6GBRK27.js +3 -0
  26. package/dist/cli-bundle/chunks/chunk-QZNDEZYI.js +2 -0
  27. package/dist/cli-bundle/chunks/chunk-S5UXBECQ.js +2 -0
  28. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-TESRFVGF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-GXGMMIZN.js → chunk-VWKLTHYQ.js} +80 -70
  30. package/dist/cli-bundle/chunks/chunk-YJNY5MKP.js +2 -0
  31. package/dist/cli-bundle/chunks/chunk-YLPZE2TK.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-ZVDXGAYV.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-ZWUS65LN.js +2 -0
  34. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-42Y2CSEQ.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-revision-JCEDTAVX.js +2 -0
  36. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-IQHBRFAJ.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-DF6BFGG6.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-JNJY2D3N.js → register-list-query-DNKPQB76.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-mutation-WVTDFLEF.js +20 -0
  41. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-2RTG3LII.js +2 -0
  43. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-W5ULPKIE.js} +2 -2
  44. package/dist/cli-bundle/chunks/stage-YFNK7U26.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-Q3OA5OAK.js → chunk-2UQFFVQK.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/chunk-52H6AELE.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-J3LQQP3N.js → chunk-63FM3TIG.js} +7 -7
  48. package/dist/cli-bundle/focused-chunks/{chunk-VGFKTSGY.js → chunk-7GCAZJT4.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-BSY6FZ3Y.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-CZZKAGHE.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-DRBXOAGY.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-DXMQ32EH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-EALGFJRP.js +78 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +44 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-JE3MFEQZ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-JR75B6HU.js → chunk-JRRHN2PZ.js} +12 -12
  57. package/dist/cli-bundle/focused-chunks/chunk-JXA77YIV.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-LSWUTTE6.js +6 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-QXOFSZR6.js +3 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-RMCODWHZ.js +65 -0
  62. package/dist/cli-bundle/focused-chunks/chunk-S6GTALM4.js +24 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-UPUIDGNJ.js +2 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-TVJ2PHAK.js → chunk-W2KIQ7RF.js} +3 -3
  65. package/dist/cli-bundle/focused-chunks/chunk-WGYR3X6O.js +26 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-ZJF6ZA7B.js → chunk-XQZKGTZV.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-4LFE3FQL.js → chunk-YTNUUEY6.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-YZUBG4W2.js +6 -0
  70. package/dist/cli-bundle/focused-chunks/chunk-Z6HCQYSW.js +8 -0
  71. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-LSBWMXKS.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/item-revision-YO7YGQYE.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/item-transaction-7A3Q4CAJ.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/mutation-actor-UQHBNHOF.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/mutation-admission-G565NLPE.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-UXN76GMA.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/stage-F3YJGNRK.js +2 -0
  78. package/dist/cli-bundle/main.js +7 -7
  79. package/dist/cli-bundle/sdk-authoring.js +1 -1
  80. package/dist/cli-bundle/sdk-contracts.js +3 -3
  81. package/dist/cli-bundle/sdk-core.js +1 -1
  82. package/dist/cli-bundle/sdk-governance.js +1 -1
  83. package/dist/cli-bundle/sdk-graph.js +1 -1
  84. package/dist/cli-bundle/sdk-merge.js +57 -57
  85. package/dist/cli-bundle/sdk-query.js +1 -1
  86. package/dist/cli-bundle/sdk-runtime.js +1 -1
  87. package/dist/cli-bundle/sdk-testing.js +1 -1
  88. package/dist/cli-bundle/sdk.js +11 -11
  89. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  90. package/dist/core/extensions/extension-types.d.ts +30 -0
  91. package/dist/core/extensions/extension-types.js +1 -1
  92. package/dist/core/extensions/index.d.ts +21 -1
  93. package/dist/core/extensions/index.js +1 -1
  94. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  95. package/dist/core/extensions/mutation-actor.js +2 -0
  96. package/dist/core/item/deferred-fields.js +2 -0
  97. package/dist/core/item/item-format-version.d.ts +8 -6
  98. package/dist/core/item/item-format-version.js +1 -1
  99. package/dist/core/item/item-format.js +2 -2
  100. package/dist/core/lock/lock.js +3 -3
  101. package/dist/core/output/linked-test-projection.js +6 -0
  102. package/dist/core/output/output.d.ts +7 -0
  103. package/dist/core/output/output.js +9 -7
  104. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  105. package/dist/core/schema/runtime-field-values.js +1 -1
  106. package/dist/core/session/session-state.js +1 -1
  107. package/dist/core/shared/item-metadata-contract.js +1 -1
  108. package/dist/core/shared/text-normalization.d.ts +24 -0
  109. package/dist/core/shared/text-normalization.js +1 -1
  110. package/dist/core/shared/url-credentials.js +1 -1
  111. package/dist/core/store/item-store.js +1 -1
  112. package/dist/core/test/run-selectors.d.ts +3 -1
  113. package/dist/core/test/run-selectors.js +1 -1
  114. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  115. package/dist/sdk/annotations.js +1 -1
  116. package/dist/sdk/authoring.d.ts +1 -1
  117. package/dist/sdk/authoring.js +1 -1
  118. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  119. package/dist/sdk/cli-contracts/completeness.js +1 -1
  120. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  121. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  122. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  123. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  124. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  125. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  126. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  127. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  128. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  129. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  130. package/dist/sdk/completion/bash.js +1 -1
  131. package/dist/sdk/completion/fish.js +6 -1
  132. package/dist/sdk/completion/zsh.js +6 -1
  133. package/dist/sdk/context-intent-contracts.js +1 -1
  134. package/dist/sdk/docs.d.ts +3 -1
  135. package/dist/sdk/docs.js +1 -1
  136. package/dist/sdk/environment/project-runtime-compatibility.d.ts +8 -1
  137. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  138. package/dist/sdk/extension/command-options.d.ts +23 -4
  139. package/dist/sdk/extension/command-options.js +1 -1
  140. package/dist/sdk/extension/native-command-options.js +2 -0
  141. package/dist/sdk/files.d.ts +3 -1
  142. package/dist/sdk/files.js +1 -1
  143. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  144. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  145. package/dist/sdk/governance/health.js +1 -1
  146. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  147. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  148. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  149. package/dist/sdk/governance/validate.d.ts +2 -2
  150. package/dist/sdk/governance/validate.js +1 -1
  151. package/dist/sdk/guide-topics.js +1 -1
  152. package/dist/sdk/index.d.ts +1 -1
  153. package/dist/sdk/index.js +1 -1
  154. package/dist/sdk/item-transaction.d.ts +2 -2
  155. package/dist/sdk/item-transaction.js +1 -1
  156. package/dist/sdk/lifecycle/claim.d.ts +5 -1
  157. package/dist/sdk/lifecycle/claim.js +1 -1
  158. package/dist/sdk/lifecycle/close.js +1 -1
  159. package/dist/sdk/lifecycle/copy.js +1 -1
  160. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  161. package/dist/sdk/lifecycle/create.d.ts +6 -2
  162. package/dist/sdk/lifecycle/create.js +1 -1
  163. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  164. package/dist/sdk/lifecycle/plan.js +1 -1
  165. package/dist/sdk/lifecycle/restore.js +1 -1
  166. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  167. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  168. package/dist/sdk/linked-artifacts.d.ts +45 -3
  169. package/dist/sdk/linked-artifacts.js +2 -2
  170. package/dist/sdk/merge/three-way.d.ts +1 -1
  171. package/dist/sdk/merge/three-way.js +2 -2
  172. package/dist/sdk/output/table-rows.d.ts +28 -4
  173. package/dist/sdk/output/table-rows.js +1 -1
  174. package/dist/sdk/output.d.ts +1 -1
  175. package/dist/sdk/output.js +1 -1
  176. package/dist/sdk/package-import-adapters.d.ts +9 -1
  177. package/dist/sdk/package-import-adapters.js +1 -1
  178. package/dist/sdk/pagination.js +1 -1
  179. package/dist/sdk/public-surface.json +1 -1
  180. package/dist/sdk/query/complete-list.d.ts +14 -5
  181. package/dist/sdk/query/complete-list.js +1 -1
  182. package/dist/sdk/query/list.js +1 -1
  183. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  184. package/dist/sdk/query/projection-contracts.js +1 -1
  185. package/dist/sdk/read-output/continuation.js +1 -1
  186. package/dist/sdk/read-output/extension.js +1 -1
  187. package/dist/sdk/read-output-budget.js +1 -1
  188. package/dist/sdk/runtime-input.d.ts +6 -2
  189. package/dist/sdk/runtime-input.js +1 -1
  190. package/dist/sdk/runtime-primitives.d.ts +1 -1
  191. package/dist/sdk/runtime-primitives.js +1 -1
  192. package/dist/sdk/runtime.d.ts +2 -2
  193. package/dist/sdk/runtime.js +1 -1
  194. package/dist/sdk/structured-mutations.js +1 -1
  195. package/dist/sdk/test/batch.d.ts +5 -2
  196. package/dist/sdk/test/batch.js +2 -2
  197. package/dist/sdk/test/command-args.js +1 -1
  198. package/dist/sdk/test/entry.js +2 -2
  199. package/dist/sdk/test/execution.d.ts +10 -7
  200. package/dist/sdk/test/execution.js +2 -2
  201. package/dist/sdk/test/parsers.js +1 -1
  202. package/dist/sdk/test/prerequisites.d.ts +1 -1
  203. package/dist/sdk/test/prerequisites.js +1 -1
  204. package/dist/sdk/test/run-phases.d.ts +44 -0
  205. package/dist/sdk/test/run-phases.js +2 -0
  206. package/dist/sdk/testing.d.ts +15 -2
  207. package/dist/sdk/testing.js +1 -1
  208. package/dist/types.d.ts +11 -1
  209. package/dist/types.js +1 -1
  210. package/docs/AGENT_OUTPUT_ENCODINGS.md +16 -4
  211. package/docs/COMMANDS.md +31 -4
  212. package/docs/EXTENSIONS.md +1 -1
  213. package/docs/LINKED_TEST_EDITS.md +2 -1
  214. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +6 -3
  215. package/docs/README.md +2 -2
  216. package/docs/READ_OUTPUT_CONTRACTS.md +23 -2
  217. package/docs/SDK.md +129 -6
  218. package/docs/TESTING.md +64 -1
  219. package/docs/WORKSPACE_CONCURRENCY.md +5 -1
  220. package/docs/generated/FLAG_LEXICON_BUDGETS.md +9 -9
  221. package/marketplace.json +1 -1
  222. package/package.json +6 -4
  223. package/packages/pm-beads/package.json +1 -1
  224. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  225. package/packages/pm-calendar/package.json +1 -1
  226. package/packages/pm-command-kit/package.json +1 -1
  227. package/packages/pm-digital-twin/package.json +1 -1
  228. package/packages/pm-governance-audit/package.json +1 -1
  229. package/packages/pm-guide-shell/package.json +1 -1
  230. package/packages/pm-kanban/package.json +1 -1
  231. package/packages/pm-lifecycle-hooks/package.json +1 -1
  232. package/packages/pm-linked-test-adapters/package.json +1 -1
  233. package/packages/pm-search-advanced/package.json +1 -1
  234. package/packages/pm-templates/package.json +1 -1
  235. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  236. package/packages/pm-todos/package.json +1 -1
  237. package/packages/pm-vcs/package.json +1 -1
  238. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  239. package/plugins/pm-claude/package.json +1 -1
  240. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  241. package/plugins/pm-codex/package.json +1 -1
  242. package/plugins/pm-codex/plugin.json +1 -1
  243. package/runtime-dependencies.json +1 -1
  244. package/CHANGELOG.md +0 -4793
  245. package/dist/cli-bundle/chunks/chunk-36E4L2R4.js +0 -2
  246. package/dist/cli-bundle/chunks/chunk-4WD4CHVH.js +0 -8
  247. package/dist/cli-bundle/chunks/chunk-6UXBWMEM.js +0 -2
  248. package/dist/cli-bundle/chunks/chunk-CO7RWLCM.js +0 -2
  249. package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +0 -6
  250. package/dist/cli-bundle/chunks/chunk-FAYX6C7H.js +0 -2
  251. package/dist/cli-bundle/chunks/chunk-GIAJX2QJ.js +0 -9
  252. package/dist/cli-bundle/chunks/chunk-HQINCDF6.js +0 -116
  253. package/dist/cli-bundle/chunks/chunk-IYDIPXBO.js +0 -2
  254. package/dist/cli-bundle/chunks/chunk-L4F4ZHGR.js +0 -2
  255. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  256. package/dist/cli-bundle/chunks/chunk-O6PBQMD7.js +0 -2
  257. package/dist/cli-bundle/chunks/chunk-O6T24Z3M.js +0 -2
  258. package/dist/cli-bundle/chunks/chunk-OQCVU2SG.js +0 -8
  259. package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +0 -20
  260. package/dist/cli-bundle/chunks/chunk-TCYIGAQG.js +0 -31
  261. package/dist/cli-bundle/chunks/chunk-URWNUZQZ.js +0 -3
  262. package/dist/cli-bundle/chunks/chunk-UYARS5XF.js +0 -3
  263. package/dist/cli-bundle/chunks/item-revision-G5OVYGZ5.js +0 -2
  264. package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +0 -2
  265. package/dist/cli-bundle/chunks/mutation-admission-SET4KY73.js +0 -2
  266. package/dist/cli-bundle/chunks/register-mutation-WTHZHPOP.js +0 -20
  267. package/dist/cli-bundle/chunks/register-operations-EZP3EG6A.js +0 -2
  268. package/dist/cli-bundle/chunks/register-setup-THFZP23A.js +0 -2
  269. package/dist/cli-bundle/chunks/stage-JXJILTYE.js +0 -2
  270. package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +0 -2
  271. package/dist/cli-bundle/focused-chunks/chunk-3MB47JLT.js +0 -2
  272. package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +0 -44
  273. package/dist/cli-bundle/focused-chunks/chunk-5NTLNE54.js +0 -26
  274. package/dist/cli-bundle/focused-chunks/chunk-ADBFVDTG.js +0 -8
  275. package/dist/cli-bundle/focused-chunks/chunk-CSKDIMQP.js +0 -2
  276. package/dist/cli-bundle/focused-chunks/chunk-FNIX62V6.js +0 -3
  277. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  278. package/dist/cli-bundle/focused-chunks/chunk-IYV3IPRF.js +0 -65
  279. package/dist/cli-bundle/focused-chunks/chunk-QGQJBQCH.js +0 -2
  280. package/dist/cli-bundle/focused-chunks/chunk-RIMNSVFA.js +0 -26
  281. package/dist/cli-bundle/focused-chunks/chunk-VGJDKDKA.js +0 -2
  282. package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +0 -82
  283. package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +0 -91
  284. package/dist/cli-bundle/focused-chunks/chunk-WFVZ7GGR.js +0 -2
  285. package/dist/cli-bundle/focused-chunks/chunk-ZOGEQFGH.js +0 -2
  286. package/dist/cli-bundle/focused-chunks/item-revision-IF7E7BVY.js +0 -2
  287. package/dist/cli-bundle/focused-chunks/item-transaction-5TFWIOXI.js +0 -2
  288. package/dist/cli-bundle/focused-chunks/mutation-admission-KELM46JF.js +0 -2
  289. package/dist/cli-bundle/focused-chunks/stage-UAKMQTCI.js +0 -2
@@ -0,0 +1,44 @@
1
+ import{A as vl,B as nh,C as rh,n as uf,o as $i,p as yf,q as wf,r as Li,s as zr,t as Pc,u as Lc,v as Ni,y as Vf,z as Yf}from"./chunk-WGYR3X6O.js";import{a as oh,f as ih,h as gn,m as ah,o as ao,r as fa,s as sh,t as ch,x as lh}from"./chunk-WVYXR3YX.js";import{$ as mg,Ab as Xg,Ca as wg,Da as vg,Db as $a,Ea as bg,Fa as kg,Ga as Sg,H as Bh,Ha as Eg,I as Wh,Ia as Ag,J as Vh,Ja as wn,K as Yh,Ka as Tg,Kb as Qg,L as Jh,La as Cg,Lb as Zg,M as Xh,Ma as Ig,Mb as ey,N as Qh,Na as Ca,O as Zh,Oa as Rg,P as eg,Pa as Og,Q as tg,Qa as xg,Qb as ty,R as ng,Ra as $g,Rb as uy,S as rg,Sa as Ng,T as og,Ta as Ia,U as ig,Ua as Xt,V as ag,Va as Fg,W as sg,Wa as Ra,X as cg,Y as lg,Z as lr,Za as go,_ as dg,eb as Mg,fb as Dg,g as $h,gb as Ug,h as Ph,ha as pg,hb as jg,ib as Gg,ja as fg,jb as qg,ka as Rl,kb as Oa,la as Ol,lb as Ll,ma as _g,mb as Kg,na as $l,nb as Nl,ob as mr,pa as hg,pb as zg,qa as gg,qb as Hg,ra as Pl,rb as Bg,sb as Wg,tb as Vg,ub as yo,vb as xa,wb as Yg,xb as Jg,yb as pr,z as jh,zb as Fl}from"./chunk-RMCODWHZ.js";import{h as wt,i as vn,m as Lg}from"./chunk-YTNUUEY6.js";import{a as ho,b as Gh,c as Aa,h as zh,i as Hh}from"./chunk-W2KIQ7RF.js";import{c as Tl}from"./chunk-JE3MFEQZ.js";import{A as bh,B as wa,C as kh,D as Sh,E as Sl,F as mo,G as va,H as sr,I as Eh,J as El,K as ke,L as Al,M as we,N as Ah,O as Th,P as ba,Q as Ch,R as ka,S as Ih,a as _a,b as so,c as ha,d as Fe,e as ga,f as dh,g as mh,h as ya,i as co,j as ph,k as uh,l as bl,m as kl,n as gt,o as fh,p as _h,q as hh,r as lo,s as gh,t as yh,u as yt,v as b,w as wh,x as vh,z as ze}from"./chunk-BSY6FZ3Y.js";import{e as df,g as mf,h as pf,k as _f,q as gf}from"./chunk-7GCAZJT4.js";import{S as Kf,T as Bc,U as zf,V as qi,W as Wc,X as Hf,Y as Bf,a as Jp,b as Xp,c as Qp,d as Zp,da as Vc,f as eu,ha as Wf}from"./chunk-LQZ5F6LE.js";import{a as Mh,b as Dh,c as Pa,d as La,e as Na}from"./chunk-Z6HCQYSW.js";import{K as yg,b as Uh}from"./chunk-DXMQ32EH.js";import{A as ly,Ea as jl,Ga as dy,Va as bo,Xa as my,Ya as py,b as Fh,e as Cl,g as Il,i as xl,j as wo,l as ny,m as ry,n as Ml,sa as Dl,v as oy,w as iy,x as ay,xa as vo,y as sy,z as cy,za as Ul}from"./chunk-JRRHN2PZ.js";import{A as Ta,F as dr,h as Sa,k as Oh,l as po,o as xh,w as Pt,y as Lh,z as Nh}from"./chunk-UPUIDGNJ.js";import{a as _o,b as yn,d as Pg}from"./chunk-2UQFFVQK.js";import{$ as r_,$a as Y_,A as fe,B as Hi,C as Jc,D as tt,E as Qf,F as Xc,G as Zf,H as le,J as Rt,K as e_,L as Bi,M as Ht,N as ge,O as tr,P as Qc,Q as Vr,R as Zc,S as Yr,T as Ot,U as t_,V as Wi,W as Vi,X as Yi,Y as Ji,Ya as oo,Z as Xi,_ as n_,_a as V_,aa as o_,ab as pa,bb as ua,c as sf,cb as J_,ea as Qi,f as cf,fa as Zi,g as lf,i as xi,ia,j as qt,ja as aa,k as Hn,ka as I_,l as vf,la as sa,m as bf,ma as ca,n as Jf,na as Vt,p as pt,pa as ul,q as ut,qa as la,qb as ar,r as Qn,rb as X_,s as Yc,sa as R_,sb as yl,t as Xf,ta as O_,tb as Q_,u as zt,ua as to,ub as Z_,v as Zn,vb as eh,w as Ki,x as er,y as zi,yb as wl,zb as th}from"./chunk-63FM3TIG.js";import{$ as jr,$a as Ei,Aa as zu,B as xc,Ba as Hu,C as $c,D as au,Da as Bu,E as Kn,Ea as Wu,F as ii,Fa as Vu,G as ai,Ga as Yu,H as su,Ha as Ju,I as cu,Ia as Xu,J as lu,Ja as fi,K as du,Ka as _i,L as mu,La as hi,M as si,Ma as Qu,N as pu,Na as Zu,O as uu,Oa as gi,P as fu,Pa as ef,Q as ci,Qa as tf,R as _u,Ra as nf,S as hu,Sa as yi,T as gu,Ta as wi,U as yu,Ua as vi,V as li,Va as bi,W as di,Wa as qr,X as wu,Xa as rf,Y as mi,Ya as ki,Za as Kr,_ as vu,_a as Si,aa as bu,ab as Ai,b as tu,ba as ku,bb as Ti,c as nu,ca as Su,cb as of,d as ru,da as Eu,db as Gt,ea as Au,eb as Ci,fa as Tu,fb as Ii,ga as Cu,gb as Ri,ha as Iu,hb as Oi,i as Ic,ia as Ru,ja as Ou,ka as xu,kb as af,la as $u,ma as Pu,mb as qe,na as Lu,nb as M,o as Rc,oa as Nu,p as ou,pa as Gr,qa as Fu,ra as Mu,s as oi,sa as pi,t as Oc,ta as ui,u as pn,ua as Du,va as Uu,w as iu,wa as ju,xa as Gu,ya as qu,za as Ku}from"./chunk-52H6AELE.js";import{A as ug,a as uo,b as fo,c as cr,d as ot,i as Ea}from"./chunk-DRBXOAGY.js";import{d as Rh}from"./chunk-XQZKGTZV.js";import{C as M_,E as D_,H as U_,M as j_,N as G_,O as ma,U as Yt,W as Jt,Y as K,Z as ne,_ as z_,aa as ye,b as et,ba as H_,c as Zo,ca as hn,d as ei,da as rt,e as Le,ea as B_,f as A_,fa as ir,g as T_,ga as _e,h as Wt,ha as W_,ia as gl,j as Ne,k as eo,l as nr,m as L_,n as rr,na as io,o as or,p as N_,v as ro,x as F_}from"./chunk-CZZKAGHE.js";import{$ as ft,$a as P_,Aa as ht,B as c_,Ba as Qr,C as l_,Ca as Zr,D as ta,G as na,I as nl,Ja as E_,L as ae,La as pl,M as _n,N as se,O as rl,Oa as C_,P as ol,Pa as oa,Q as il,Qa as nt,S as d_,Sa as da,U as al,Ua as x_,Va as no,W as m_,X as p_,Xa as $_,Y as u_,Ya as $t,Z as sl,Za as fl,_ as f_,_a as _l,a as ff,aa as _t,ab as E,ba as h_,bb as Re,c as Tt,ca as ra,db as q_,e as Pi,eb as hl,f as Ct,fa as g_,fb as K_,g as Kt,ga as y_,gb as O,h as hf,ha as cl,j as D,k as It,ka as ll,l as Qe,ma as w_,n as zn,na as v_,oa as b_,pa as k_,qa as S_,r as xt,u as i_,ua as Ke,v as el,va as Bt,w as a_,wa as dl,x as tl,xa as Jr,y as s_,ya as Xr,z as ea,za as ml}from"./chunk-EALGFJRP.js";import{a as Gi,b as qf}from"./chunk-C3O6JJPO.js";import{$a as __,Ca as Xn,Ga as jf,M as $f,N as Pf,Oa as Gf,Q as Lf,R as Nf,T as Ff,a as Ie,e as ji,h as Rf,i as Pe,j as Of,n as xf,qa as Mf,s as Hc,ya as Df,za as Uf}from"./chunk-S6GTALM4.js";import{E as Vn,F as I,k as Mi,l as Af,m as Tf,n as Wr,o as Di,y as Fc}from"./chunk-LSWUTTE6.js";import{$a as Ce,$c as Kc,A as _c,Aa as ni,Ac as te,B as hc,Ba as $e,C as gc,Ca as oe,D as yc,Da as Et,E as wc,F as vc,Fa as Xe,Ga as ri,Gc as Ef,Ia as At,Ja as ie,Jc as mt,K as kp,Kb as jp,Kc as Hr,Lb as Gp,Ma as qn,Mb as qp,Nb as Kp,Nc as Bn,Ob as zp,Oc as Nc,Pb as Hp,Pc as Cf,Qb as Bp,Qc as Wn,R as Sp,Rc as If,Sb as Mr,Sc as Br,T as Ep,Ub as Wp,Uc as Mc,V as Ap,Wc as Dc,X as Tp,Xb as Vp,Xc as Uc,Y as Cp,Yc as jc,Zc as Gc,_b as Yp,_c as qc,a as up,ad as zc,bb as W,bd as R,db as mn,dd as Yn,ed as un,fa as dt,fd as X,g as mc,ha as Ip,hb as Op,hc as Dr,i as pc,ib as xp,ic as Cc,id as fn,j as uc,ja as kc,jb as $p,jc as Ur,jd as Jn,ka as Lr,kb as Pp,lb as Lp,lc as kf,mb as Np,md as Ui,n as Xo,na as Sc,nb as Ec,o as kt,oa as Nr,ob as Fp,p as $r,pa as xe,q as Pr,qb as Mp,r as fc,rb as Dp,rc as Sf,sa as $,sc as L,t as fp,ta as Te,u as _p,ua as ti,ub as Ac,uc as A,v as hp,va as Gn,vb as Up,w as gp,wa as Fr,wb as Tc,xa as Rp,y as yp,yc as Fi,z as wp,za as T}from"./chunk-YZUBG4W2.js";import{a as Kh}from"./chunk-EGN2HFRU.js";import{b as qh}from"./chunk-FOA7XKWP.js";import{A as d,C as B,D as St,E as Ge,F as ee,I as re,K as jn,m as Qo,s as bc,u as vp,x as dn,y as bp,z as m}from"./chunk-QXOFSZR6.js";import{readFile as cA}from"node:fs/promises";import lA 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]="20a3a324-d176-5918-8167-5e548be4abc9")}catch{}})();var Gl="context-intents.json";function Fa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function dA(e,t,n){if(!Fa(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let r=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(r)||!r.every(o=>typeof o=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:r,token_budget:e.token_budget}}function fy(e,t){let n=Array.isArray(e)?e:Fa(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((r,o)=>dA(r,t,o))}async function mA(e){let t=lA.join(e,Gl),n;try{n=await cA(t,"utf8")}catch(o){if(St(o))return[];throw await K_(e),o}let r;try{r=JSON.parse(n)}catch(o){let i=o instanceof Error?o.message:String(o);throw new TypeError(`Invalid ${Gl}: ${i}`,{cause:o})}return fy(r,Gl)}function pA(e){if(!Fa(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Fa(n)?n.contextIntents??n.context_intents:void 0}function uA(e){return e.flatMap(t=>{let n=pA(t.module);return n===void 0?[]:fy(n,`package ${t.name}`)})}async function fA(e){let t=await mA(e.pmRoot),n=uA(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Ma(e,t){let n=await fA(e);return await Uf(n,t)}import{readFile as _A}from"node:fs/promises";(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]="59163d45-c136-5ead-adf1-b08ebb9c27ae")}catch{}})();function kn(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,le(e,t)}function wy(e){return Object.prototype.toString.call(e)==="[object Object]"}function hA(e,t,n,r){let o=A();if(!wy(e))return{...r({created_at:o,author:n,text:t}),text:t,edited_at:o};let i=a=>typeof a=="string"&&a!=="";return{...e,...i(e.created_at)?{}:{created_at:o},...i(e.author)?{}:{author:n},text:t,edited_at:o}}function _y(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new d(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function ql(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function bn(e,t){let n=e[t];return Array.isArray(n)?n:[]}function ur(e,t={}){let n=e.trim();if(!n)return"";let r=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&r&&!n.startsWith("```"))return n.slice(r[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let o=fe(n,"--add");return Object.keys(o).map(i=>i.trim().toLowerCase()).some(i=>i!=="text")?n:o.text?.trim()||n}catch{return n}}function Kl(e){return typeof e=="object"&&e!==null&&"code"in e}function So(e,t){if(!Rt(e))throw new d(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function gA(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new d(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=Ht(),r=Rt(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",r)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return So(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let o=e.file.trim();if(!o)throw new d("--file path cannot be empty",m.USAGE);if(o==="-")return So(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await _A(o,"utf8"),emptyFlag:"--file"}}catch(i){if(Kl(i)&&St(i))throw new d(`--file path not found: ${o}. Use --file - to read stdin.`,m.USAGE);let a=i instanceof Error?i.message:String(i);throw new d(`Failed to read --file path "${o}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function Ua(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new d("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new d("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new d("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new d("--edit must be a positive integer",m.USAGE);let n=await gA(e,t);if(e.edit!==void 0){if(!n)throw new d("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ko(e,t){throw e instanceof d&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new d(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function vy(e){return e==="comments"?"--stdin":"--add -"}function yA(e){return/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(e.trim())}function wA(e){return e==="--file"?"--file <path>":e.startsWith("--file=")?e:e==="--stdin"?"--stdin":void 0}function vA(e){let t=e.value.trim(),n=e.collectionKey.replace(/s$/,""),r=wA(t),o=vy(e.collectionKey),i=e.retryArgs===void 0?{}:{field:e.textFlag,recovery:{suggested_flags:[t],suggested_retry:L(e.retryArgs),suggested_retry_args:[...e.retryArgs]}};if(r!==void 0){let a=r.split(/[ =]/,1)[0],s=a==="--file"?"that file":"stdin",c=e.conflictingOperand===void 0?"":` "${e.conflictingOperand}" was read as positional text, which ${a} cannot be combined with: drop it, or pass it as the text without ${a}.`;return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text: ${e.textFlag} took ${a} as its value. Drop ${e.textFlag} and pass ${r} on its own.${c}`,m.USAGE,{code:"annotation_flag_like_value",required:`Drop ${e.textFlag}: ${r} reads the ${n} text from ${s} by itself. Use ${e.textFlag} text=${t} only when the text really is "${t}".`,examples:[`${e.commandPrefix} ${r}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}return new d(`${e.textFlag} value "${t}" looks like an option, not annotation text. Use ${o} to read stdin, or use text=${t} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${o} for stdin input, pass plain text, or use text=${t} when the text really starts with "-".`,examples:[`${e.commandPrefix} ${o}`,`${e.commandPrefix} ${e.textFlag} text=${t}`],...i})}function bA(e,t){if(!((t.input.emptyFlag??"--add")!=="--add"||!yA(e)))throw vA({collectionKey:t.collectionKey,textFlag:"--add",value:e,commandPrefix:t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`})}function kA(e,t,n,r,o){if(n.input.mode!=="edit")return;let i=Yp(t);if(i===void 0)return;let a=n.collectionKey.replace(/s$/,""),s=n.input.index,c=Pe(r)[0]==="--pm-path"?["--pm-path",o]:[];throw new d(`Replacement text for ${a} ${s} on ${e} ends with the read-output compaction marker, so it was copied from a compacted read that left out ${i} characters. Nothing was written.`,m.USAGE,{code:"annotation_text_compacted",item_id:e,details:{collection:n.collectionKey,entry_index:s,omitted_characters:i},required:`Read the whole ${a} with --output-budget unbounded, apply the change to the full text, and retry the edit without the trailing marker.`,why:"A budgeted read shortens long entries to a prefix plus a marker naming how many characters it left out; editing from that text would replace the stored entry with the shortened prefix.",examples:[L([...c,n.collectionKey,e,"--output-budget","unbounded","--json"]),`${L([...c,n.collectionKey,e,"--edit",String(s),"--file"])} <full-text-file>`]})}function SA(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new d(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(EA(e,t),e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new d(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${vy(e.collectionKey)}`]})}function EA(e,t){if(t.expectAt!==void 0){if(e.input.mode!=="edit"&&e.input.mode!=="delete")throw new d(`--expect-at guards an --edit or --delete of one ${e.collectionKey.replace(/s$/,"")}`,m.USAGE,{code:"annotation_expectation_without_target",required:"Combine --expect-at with --edit <index> or --delete <index>; omit it for list and append operations.",examples:[`pm ${e.collectionKey} <id> --edit <index> --expect-at <created_at> --add "<text>"`,`pm ${e.collectionKey} <id> --delete <index> --expect-at <created_at>`]});if(typeof t.expectAt!="string"||t.expectAt.trim().length===0)throw new d("--expect-at must be the non-empty created_at timestamp of the entry you read",m.USAGE,{code:"annotation_expectation_invalid",required:"Pass the created_at value of the row you read at that index, as a string."})}}function hy(e,t,n,r,o){if(o===void 0)return;let i=t[n]?.created_at,a=typeof i=="string"?i:null;if(a===o)return;let s=t.flatMap((f,h)=>f?.created_at===o?[h+1]:[]),c=r.collectionKey.replace(/s$/,""),l=r.input.mode==="delete"?"--delete":"--edit",p=n+1,u=s.length===1?` The ${c} created at ${o} is at index ${s[0]}.`:s.length>1?` ${s.length} ${r.collectionKey} were created at ${o}: indexes ${s.join(", ")}.`:` No ${c} on ${e} was created at ${o}.`;throw new d(`${c.charAt(0).toUpperCase()}${c.slice(1)} ${p} on ${e} was created at ${a||"an unrecorded time (malformed entry)"}, not ${o}; refusing ${l} of an entry the caller did not read. Nothing was written.${u}`,m.CONFLICT,{code:"annotation_entry_mismatch",item_id:e,details:{collection:r.collectionKey,entry_index:p,expected_created_at:o,actual_created_at:a,matching_indexes:s},required:`Address the ${c} by the index its listing row reports and keep --expect-at set to that row's created_at. When several indexes share the timestamp, inspect those rows before retrying, because the guard compares timestamps, not entry identities.`,why:"A listing page's position or count is not an entry address; only the row's index is, and the expectation checks that the entry at that index still carries the created_at that was read.",examples:[`pm ${r.collectionKey} ${e} --limit 5`,`pm ${r.collectionKey} ${e} ${l} ${s.length===1?s[0]:"<index>"} --expect-at ${o}${l==="--edit"?' --add "<text>"':""}`]})}function AA(e,t,n,r,o,i){let a=bn(e.metadata,t),s=o?a.findIndex(c=>wy(c)&&c.author===n&&c.text===r):-1;return s>=0?{changedFields:[],written:a,position:s}:(a.push(i({created_at:A(),author:n,text:r})),e.metadata[t]=a,{changedFields:[t],written:a,position:a.length-1})}function gy(e,t,n){return m_.has(e)?t.map((r,o)=>o).sort((r,o)=>p_(t[r],t[o])||r-o).indexOf(n)+1:n+1}async function fr(e,t,n,r){SA(r,t);let o=T(process.cwd(),n.path);await O(o);let i=await E(o),a=$(i,R()),s=to(t.limit);if(r.input.mode==="list"){let _=await K(o,e,i.id_prefix,i.item_format,a.type_to_folder);if(!_)throw new d(`Item ${e} not found`,m.NOT_FOUND);let g=await ne(_,{schema:i.schema}),y=bn(g.document.metadata,r.collectionKey);return Da(_.id,r.collectionKey,y,s,t.includeMeta===!0)}let c=I(t.author,i.author_default);if(r.input.mode==="delete"){let _=r.deleteOp??r.op,g;try{g=await _e({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(w){let v=bn(w.metadata,r.collectionKey),k=yy(r.input.index,v.length,r.collectionKey);return hy(e,v,k,r,t.expectAt),_y(v[k],"deleted"),v.splice(k,1),w.metadata[r.collectionKey]=v,{changedFields:[r.collectionKey]}}})}catch(w){ko(w,r.conflictGuidance)}let y=bn(g.item,r.collectionKey);return Da(g.item.id,r.collectionKey,y,s,t.includeMeta===!0,{action:"delete",entryIndex:r.input.index},t.fullHistory===!0)}let l=r.input.rawValue??r.input.value??"";bA(l,r);let p=r.parseText(r.input.value??"");if(!p.trim())throw new d(`${r.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(kA(e,p,r,n,o),r.input.mode==="edit"){let _=r.editOp??r.op,g,y=0;try{g=await _e({pmRoot:o,settings:i,id:e,op:_,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,mutate(k){let C=bn(k.metadata,r.collectionKey),S=yy(r.input.index,C.length,r.collectionKey);hy(e,C,S,r,t.expectAt);let x=C[S];return _y(x,"edited"),C[S]=hA(x,p,c,r.createEntry),y=gy(r.collectionKey,C,S),k.metadata[r.collectionKey]=C,{changedFields:[r.collectionKey]}}})}catch(k){ko(k,r.conflictGuidance)}let w=bn(g.item,r.collectionKey),v=y;return Da(g.item.id,r.collectionKey,w,s,t.includeMeta===!0,{action:"edit",entryIndex:v,entry:w[v-1]},t.fullHistory===!0)}let u,f=0;try{u=await _e({pmRoot:o,settings:i,id:e,op:r.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:r.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(_){let g=AA(_,r.collectionKey,c,p,t.ifAbsent===!0,r.createEntry);return f=gy(r.collectionKey,g.written,g.position),{changedFields:g.changedFields}}})}catch(_){ko(_,r.conflictGuidance)}let h=bn(u.item,r.collectionKey);return Da(u.item.id,r.collectionKey,h,s,t.includeMeta===!0,{action:"add",entryIndex:f,entry:h[f-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function yy(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let r=n.replace(/s$/,""),o=`${r.charAt(0).toUpperCase()}${r.slice(1)}`,i=t===1?`1 ${r}`:`${t} ${n}`;throw new d(`${o} index ${e??"(missing)"} out of range (item has ${i})`,m.USAGE)}return e-1}function TA(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function by(e,t){if(Object.prototype.toString.call(e)!=="[object Object]")return e;let n={index:t,...e};return n.index=t,n}function CA(e,t){let n=e.length-t.length;return t.map((r,o)=>by(r,n+o+1))}function Da(e,t,n,r,o,i,a=!1){let s=i===void 0||a?CA(n,ql(n,i!==void 0&&a?void 0:r)):i.entry===void 0?[]:[by(i.entry,i.entryIndex)],c=i!==void 0&&s.length<n.length;return{id:e,[t]:s,count:s.length,...i?.changedCount===void 0?{}:{changed:i.changedCount===1},...[o,i!==void 0].includes(!0)?{total_count:n.length,returned_count:s.length,has_more:c||s.length<n.length,...r!==void 0?{limit:r}:{}}:{},...TA(t,i,c)}}(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]="6c6e6cae-87e6-58df-9f59-b9e74a80de38")}catch{}})();function IA(e){return e===void 0?"unknown":e==="claim"?"claim":"assignment"}async function ky(e,t,n){let r=[...await Promise.resolve().then(()=>ra(Xe(e,t),t)).catch(()=>[])].reverse().find(c=>c.patch.some(l=>l.path==="/metadata/assignee")),o=r?.patch.find(c=>c.path==="/metadata/assignee"),i=o!==void 0&&typeof o.value=="string"&&o.value.trim()===n.trim()?r:void 0,a=IA(i?.op),s=Bn(n);return{phrase:a==="claim"?`claimed by ${s}`:`assigned to ${s}`,holder:s,source:a,since:i?.ts??null}}(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]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function _r(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=vf({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=It(e.fromStatus,e.statusRegistry)??e.fromStatus,r=It(e.toStatus,e.statusRegistry)??e.toStatus,o=`Disallowed transition for type "${e.typeName}": ${n} -> ${r}. Allowed transitions: ${bf(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new d(o,m.USAGE);return`workflow_transition_not_allowed: ${o}`}(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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function ja(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new d("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?It(e.handoff,t):void 0;if(n===void 0||zn(n,t)||n===t.in_progress_status)throw new d("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new d("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function Sy(e,t,n,r,o){if(zn(e.status,r)||!e.assignee?.trim())throw new d("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let i=n.governance.workflow_enforcement??"off",a=_r({enforcement:i,typeWorkflows:i==="off"?[]:Hn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:t}),s={from_status:e.status,to_status:t,message:o},c=e.status===t?[]:["status"];return e.status=t,{receipt:s,warnings:a?[a]:[],changedFields:c}}import{AsyncLocalStorage as RA}from"node:async_hooks";(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]="f4c54507-c8b1-5f19-b58a-61186c79c8b0")}catch{}})();function Lt(e){return e.in_progress_status!==e.open_status&&e.by_id.has(e.in_progress_status)?e.in_progress_status:It("in_progress",e)??e.open_status}(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]="2d3aa974-e49d-50fc-9c29-01c0e694b4c4")}catch{}})();var OA="strict",qa="start_blocked_by_open_dependency";function Ey(e,t,n){if(t===void 0)return!1;let r=_n(Lt(n),n);return _n(t,n)===r&&_n(e??"",n)!==r}function Ga(e,t,n){let r=o=>Ne(o.trim(),n).toLowerCase();return r(e)===r(t)}var xA=new Set(["cli:create:blocked_by","cli:update:blocked_by"]);function zl(e,t,n){if(e.kind!=="blocked_by"||typeof t!="string"||t.trim().length===0)return!1;let r=e.id.trim().toLowerCase();return r===t.trim().toLowerCase()?!0:r===Ne(t.trim(),n).toLowerCase()&&xA.has(e.source_kind?.trim().toLowerCase()??"")}function $A(e,t,n){let r=e.dependencies??[],o=r.filter(i=>i.kind==="blocked_by");if(r.some(i=>i.kind!=="blocked_by"&&Ap(i.kind)==="blocked_by"&&Ga(i.id,t,n)))return L(["get",e.id,"--fields","blocked_by,dependencies"]);if(!(typeof e.blocked_by=="string"&&Ga(e.blocked_by,t,n))){let i=o.filter(a=>Ga(a.id,t,n));return i.length===1&&i.every(a=>a.id===cr(a.id,n,void 0))?L(["update",e.id,"--dep-remove",`id=${i[0].id},kind=blocked_by`]):L(["get",e.id,"--fields","blocked_by,dependencies"])}return o.filter(i=>Ga(i.id,t,n)).every(i=>zl(i,e.blocked_by,n))?L(["update",e.id,"--unset","blocked_by"]):L(["get",e.id,"--fields","blocked_by,dependencies"])}var PA=new Set(["item_document_invalid","item_document_encoding_invalid","item_format_version_unsupported","item_identity_ambiguous","item_identity_conflict"]);async function LA(e,t){try{return(await Pg(e)).filter(n=>!n.resolved)}catch(n){let r=io(n)?n.context.code:void 0;if(!t||typeof r!="string"||!PA.has(r))throw n;return r}}async function Ay(e){let t=e.settings.governance.start_blocker_enforcement??OA;if(t==="off")return[];let n=$(e.settings,R()).type_to_folder,r=e.metadata.id,o=await LA({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n,metadata:e.metadata},t==="warn"||e.force===!0);if(typeof o=="string")return[`start_blocker_unverifiable:${r}:${o}`];if(o.length===0)return[];let i=o.map(a=>a.id).join(",");if(t==="warn")return[`start_with_open_blockers:${r}:${i}`];if(e.force===!0)return[`start_blocker_override:${r}:${i}`];throw new d(`Cannot start ${r}: ${o.length===1?"its blocker":`${o.length} of its blockers`} ${i} ${o.length===1?"is":"are"} still open.`,m.CONFLICT,{code:"start_blocked_by_open_dependency",item_id:r,required:`Finish or close the open blocker${o.length===1?"":"s"} first, remove the blocked_by edge if it no longer applies, or start anyway with --force.`,why:"Starting work that a declared blocker still gates would leave an in-progress item that validate reports as non_blocked_status_has_blocked_by. governance.start_blocker_enforcement (strict by default) governs this check.",nextSteps:[...o.filter(a=>a.external!==!0).slice(0,3).map(a=>L(["get",a.id])),$A(e.metadata,o[0].id,e.settings.id_prefix),"pm next"],details:{enforcement:t,open_blockers:o.map(a=>({id:a.id,title:a.title,status:a.status,external:a.external===!0}))}})}async function Ka(e){if(e.requested===!1||!Ey(e.fromStatus,e.metadata.status,e.registry))return[];let t=await Ay(e),n=Hl.getStore()?.warnings??new Set;return t.filter(r=>!n.has(r))}var Hl=new RA;function Ty(e){return Hl.run({warnings:new Set},e)}async function Cy(e){let t=Hl.getStore();if(t===void 0)return[];let n=Ey(e.metadata.status,Lt(e.registry),e.registry)?await Ay(e):[];for(let r of n)t.warnings.add(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]="d2ca6888-c757-5be9-84ca-15c97998945e")}catch{}})();var Iy="no_available_next_item";function Ry(e){if(!(e instanceof Error)||e.name!=="PmCliError")return;let t=e.context;if(typeof t!="object"||t===null)return;let n=t.code;return typeof n=="string"?n:void 0}function Oy(e,t){return Ry(e)===t}function NA(e){return Oy(e,"already_claimed_by")}async function Eo(e,t,n,r={}){let o=T(process.cwd(),n.path);await O(o);let i=await E(o),a=D(i.schema),s=I(r.author,i.author_default),c=Vn(s),l=null,p=!1,u={},f=[],h=await _e({pmRoot:o,settings:i,id:e,op:"claim",author:s,message:r.message,force:t,skipNoop:!0,async mutate(g){let y=g.metadata.assignee??"",w=g.metadata.claim_principal?.trim()||y;if(l=y.trim().length>0?y:null,zn(g.metadata.status,a)&&!t)throw new d(`Cannot claim terminal item ${g.metadata.id} without --force`,m.CONFLICT);if(l!==null&&w!==c){if(r.ifAvailable===!0)return p=!0,f.push(`claim_skipped_held_by:${Br(l)}`),{changedFields:[]};if(!t){let P=await ky(o,g.metadata.id,y);throw new d(`Item ${g.metadata.id} is already ${P.phrase}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",item_id:g.metadata.id,claimed_by:P.holder,claimed_at:P.since,claim_source:P.source,why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}f.push(`claim_takeover:${Br(l)}->${s}`)}let v={assignee:s,claim_principal:c},k=["assignee","claim_principal"].filter(P=>g.metadata[P]!==v[P]);Object.assign(g.metadata,v);let C=g.metadata.status,{changedFields:S,warnings:x,...N}=UA(g.metadata,r.start===!0,i,a);return x.push(...await DA({pmRoot:o,settings:i,metadata:g.metadata,fromStatus:C,registry:a,force:t,start:r.start===!0})),u=N,f.push(...x),{changedFields:[...k,...S],warnings:f}}}),_=xy(await $y("claim",h.item.id,n,p,()=>ny({pmRoot:o,settings:i,principal:c,itemId:h.item.id})));return f.push(..._.warnings),{item:Nc(h.item),changed_fields:h.changedFields,claimed_by:p&&l!==null?Bn(l):s,previous_assignee:l===null?null:Bn(l),forced:t,...p?{skipped:!0}:{},...f.length>0?{warnings:f}:{},...Bl("suggestions",_.suggestions),...u}}var FA="claim_semantic_attribution_unrecorded";function xy(e){return e?{warnings:[e.warning],suggestions:[e.suggestion]}:{warnings:[],suggestions:[]}}function Bl(e,t){return t.length>0?{[e]:t}:{}}var MA="release_semantic_attribution_unrecorded";async function $y(e,t,n,r,o){if(!r)try{await o();return}catch(i){let a=Ry(i)??"unexpected_error",s=Pe(n);return{warning:e==="claim"?FA:MA,suggestion:`The ${e} of ${t} is saved, but the session attribution that names this agent's active work was not updated (${a}); nothing needs a retry. If ${L([...s,"health"])} reports a stale lock, remove it with ${L([...s,"gc","--scope","locks"])}.`}}}function Py(e,t,n=!1){let r=n?" --start":"";if(!t&&!e)throw new d(n?"pm claim --start needs an item id, or --next to start the next available item":"Specify an item id or pass --next",m.USAGE,{code:"missing_required_argument",field:"id",required:"Pass an item id, or --next to select the next available item.",nextSteps:[`Retry as pm claim <id>${r}, or pm claim --next${r}.`]});if(t&&e)throw new d("Specify either an item id or --next, not both",m.USAGE,{code:"ambiguous_option_combination",required:"Pass either an item id or --next.",nextSteps:[`Retry as pm claim ${e}${r} to claim that item, or drop the id to select with --next.`]})}async function DA(e){return e.start?Ka(e):Cy(e)}function UA(e,t,n,r){if(!t)return{changedFields:[],warnings:[]};if(zn(e.status,r))throw new d(`Cannot start terminal item ${e.id}; reopen it with pm item reopen before starting it`,m.CONFLICT,{code:"terminal_state_conflict",item_id:e.id,why:"Starting work moves an active item into progress; a terminal item must be reopened so its recurrence evidence is recorded.",nextSteps:[`Run pm item reopen ${e.id} "<reason>", then pm claim ${e.id} --start.`]});let o=Lt(r),i=n.governance.workflow_enforcement??"off",a=_r({enforcement:i,typeWorkflows:i==="off"?[]:Hn(n.schema),statusRegistry:r,typeName:e.type,fromStatus:e.status,toStatus:o}),s={from_status:e.status,to_status:o},c=e.status===o?[]:["status"];return e.status=o,{start:s,changedFields:c,warnings:a?[a]:[]}}async function Ly(e,t,n={},r={}){let o=jA(n.maxAttempts),i=await E(T(process.cwd(),t.path)),a={...n,author:I(n.author,i.author_default)},s=await vo({...r,callerAuthor:a.author,limit:String(o)},t),c=[s.recommended,...s.ready].filter(l=>l!==null).map(l=>({...l,reasons:"reasons"in l?l.reasons:["ranked ready candidate"]}));return GA(c.slice(0,o),e,t,a)}function jA(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new d("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function GA(e,t,n,r={},o=Eo){let i=0,a=[],s=()=>a.length>0?{start_refused:[...a]}:{};for(let c of e){i+=1;try{let l=await o(c.id,t,n,r),p={...l,recommendation:c,attempts:i,available:!0,...s()};if(!l.skipped)return p}catch(l){if(Oy(l,qa)){a.push(c.id);continue}if(!NA(l))throw l}}if(r.ifAvailable===!0)return{available:!1,item:null,claimed_by:I(r.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:i,...s(),warnings:[Iy]};throw qA(i,a,r.start===!0)}function qA(e,t,n){let r=e===0,o="Every ranked candidate was claimed by another agent before this atomic selection completed.";return r?o="No ready items matched the specified filters or selection criteria.":t.length>0&&(o=`${t.length} of ${e} attempted candidates refused their start because a declared blocker is open (${t.join(", ")}), and nothing was written to them; ${t.length===e?"no other candidate was attempted":"every other attempted candidate was claimed by another agent"}.`),new d(r?"No actionable items matched the selection filters":"No actionable item remained available to claim",r?m.NOT_FOUND:m.CONFLICT,{code:Iy,why:o,nextSteps:[r?"Verify the filters or run pm next to inspect all ready work.":`Run pm claim --next${n?" --start":""} again, with the same filters, to refresh the ranked candidate set.`],...t.length>0?{details:{start_refused:[...t]}}:{}})}async function gr(e,t,n,r={}){let o=T(process.cwd(),n.path);await O(o);let i=await E(o),a=I(r.author,i.author_default),s=Vn(a),c=r.ownershipReleaseBypass===!0,l=null,p=D(i.schema),u=ja(r,p);if(u!==void 0&&c)throw new d("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let f,h;try{h=await _e({pmRoot:o,settings:i,id:e,op:"release",author:a,message:r.message,force:t,bypassAssigneeConflict:c,mutate(y){l=y.metadata.assignee??null;let w=u===void 0?void 0:Sy(y.metadata,u,i,p,r.message);return f=w?.receipt,!l&&!y.metadata.claim_principal?{changedFields:[]}:(delete y.metadata.assignee,delete y.metadata.claim_principal,{changedFields:["assignee","claim_principal",...w?.changedFields??[]],warnings:w?.warnings})}})}catch(y){ko(y,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}let _=xy(await $y("release",h.item.id,n,!1,()=>ry({pmRoot:o,principal:s,itemId:h.item.id}))),g=KA(h.item,p);return{item:Nc(h.item),released_by:a,changed_fields:h.changedFields,previous_assignee:l===null?null:Bn(l),forced:t,...f===void 0?{}:{handoff:f},...Bl("warnings",[...h.warnings,...g.warnings,..._.warnings]),...Bl("suggestions",[...g.suggestions,..._.suggestions])}}function KA(e,t){return _n(e.status,t)===_n(t.in_progress_status,t)?{warnings:["released_unclaimed_in_progress"],suggestions:[`${e.id} remains ${e.status} and unclaimed. If work is paused, run pm release ${e.id} --pause to move it to ${t.open_status}.`]}:{warnings:[],suggestions:[]}}(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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function zA(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function HA(e,t,n){let r=t,o=new Set([e.id]);for(;r!==void 0&&!o.has(r.id);)o.add(r.id),r=r.parent_id?n.get(r.parent_id):void 0;return r===void 0}function BA(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((r,o)=>r.entries[0].ts.localeCompare(o.entries[0].ts)||r.id.localeCompare(o.id)),t.push(...n.map(r=>r.children))}}function Ny(e=Di,t=Wr){return t.map(n=>{let r=e.filter(o=>((n==="model"?o.model_environment_keys:o.provenance_environment_keys?.[n])?.length??0)>0||o.provenance_resolvers?.[n]!==void 0).map(o=>o.harness).sort();return{dimension:n,harnesses:r,covered:r.length>0}})}function x1(e,t=1){let n=new Map;for(let r of e){if(!r.agent_harness)continue;let o=n.get(r.agent_harness)??{harness:r.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1,r.agent_model||r.agent_provenance?.model&&r.agent_provenance.model.value.length>0?o.observed+=1:r.agent_provenance?.model===null?o.unavailable+=1:o.legacy_missing+=1,n.set(r.agent_harness,o)}return[...n.values()].map(r=>{let o=r.observed+r.unavailable;return{...r,coverage:o===0?null:r.observed/o,inert:o>=t&&r.observed===0}}).sort((r,o)=>r.harness.localeCompare(o.harness))}function Fy(e,t=Wr,n=1){let r=new Map;for(let o of e)if(o.agent_harness)for(let i of t){let a=`${o.agent_harness}\0${i}`,s=r.get(a)??{harness:o.agent_harness,dimension:i,entries:0,observed:0,unavailable:0,legacy_missing:0};s.entries+=1;let c=o.agent_provenance?.[i];c!=null&&c.value.length>0?s.observed+=1:c===null?s.unavailable+=1:s.legacy_missing+=1,r.set(a,s)}return[...r.values()].map(o=>{let i=o.observed+o.unavailable;return{...o,coverage:i===0?null:o.observed/i,inert:i>=n&&o.observed===0}}).sort((o,i)=>o.harness.localeCompare(i.harness)||o.dimension.localeCompare(i.dimension))}function $1(e,t={}){let n=t.minimumCoverage??.8,r=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(r),r>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let o=new Map;for(let c of e)if(c.agent_harness)for(let l of["role","topic"]){let p=`${c.agent_harness}\0${l}`,u=o.get(p)??{harness:c.agent_harness,dimension:l,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let f=c.agent_provenance?.[l];f?.value&&(u.observed+=1,u.by_source[f.source]=(u.by_source[f.source]??0)+1),o.set(p,u)}let i=[...o.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([l],[p])=>l.localeCompare(p)))})).sort((c,l)=>c.harness.localeCompare(l.harness)||c.dimension.localeCompare(l.dimension)),a=i.filter(c=>c.entries>=r),s=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&s.length===0,minimum_coverage:n,minimum_entries:r,rows:i,failures:s}}function P1(e){let t=[...e].sort((i,a)=>i.ts.localeCompare(a.ts)||i.author.localeCompare(a.author)||i.op.localeCompare(a.op)||i.before_hash.localeCompare(a.before_hash)||i.after_hash.localeCompare(a.after_hash)),n=new Map,r=new Map;for(let i of t){let a=i.agent_episode,s=zA(i),c=`${s.source}:${s.id}`,l=n.get(c);if(l){l.entries.push(i);continue}let p={id:s.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:s.source,entries:[i],children:[]};n.set(c,p),a!==void 0&&r.set(s.id,p)}let o=[];for(let i of n.values()){let a=i.parent_id?r.get(i.parent_id):void 0;a&&HA(i,a,r)?a.children.push(i):o.push(i)}return BA(o),o}(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]="7140bb24-7202-541a-bc13-6a67bac260a8")}catch{}})();var My=100;function yr(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new d(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function WA(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=My?t:`${t.slice(0,My-3)}...`}function Dy(e){return e.map((t,n)=>`${n+1}. ${WA(t)}`).join("; ")}function VA(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function YA(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Uy(e,t){let n=VA(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,i)=>i+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new d(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let r=n[0];if(e.length===0)throw new d(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new d("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let i=[],a=[];for(let s=0;s<e.length;s+=1)YA(e[s],o)&&(a.push(e[s]),i.push(s+1));if(a.length===0)throw new d(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Dy(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:i,selected_count:a.length,skipped_count:e.length-a.length}}if(r==="only-index"){let o=yr(t.onlyIndex);if(o>e.length)throw new d(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Dy(e)}`,m.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-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]="35d8018b-d17b-5d63-9d85-9db0b416326a")}catch{}})();var JA=["setup","test"];function Oe(e){return e.phase==="setup"}function wr(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new d(`${t} field "phase" must be one of: ${JA.join(", ")}`,m.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function za(e){return[...e.filter(Oe),...e.filter(t=>!Oe(t))]}function jy(e,t){if(!e.selected.some(i=>!Oe(i)))return e;let n=t.flatMap((i,a)=>Oe(i)?[a+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(i=>!Oe(t[i-1])),o=n.filter(i=>!e.selected_indexes.includes(i));return{...e,selected:[...n,...r].map(i=>t[i-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...o.length>0?{setup_indexes:o}:{}}}function Gy(e,t,n){if(!Oe(e))return;let r=[...n].filter(o=>o!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function Ao(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...Oe(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!Oe(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!Oe(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let r=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:r.failure_category??r.status},r}}}function XA(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function vr(e){let t=XA();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}(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]="ef8e6aec-bd75-5615-bcda-a51d055b65d7")}catch{}})();var An=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",ho,Gh,"FORCE_COLOR"]),Wa=/^[A-Za-z_][A-Za-z0-9_]*$/,En=["schema","tracker","auto","none"],qy=["source","isolated","snapshot"];function To(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1);if(!Wa.test(a))throw new d(`${t} env_set key "${a}" is invalid`,m.USAGE);if(An.has(a.toUpperCase()))throw new d(`${t} env_set key "${a}" is reserved for sandbox safety`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function Co(e,t){if(!e)return;let n=ar(e,{separators:/[;,\n]/});if(n.length===0)throw new d(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let r of n){if(!Wa.test(r))throw new d(`${t} env_clear key "${r}" is invalid`,m.USAGE);if(An.has(r.toUpperCase()))throw new d(`${t} env_clear key "${r}" is reserved for sandbox safety`,m.USAGE)}return n}function Va(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new d(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ya(e,t){if(!e)return;let n=e.trim().toLowerCase();if(En.includes(n))return n;throw new d(`${t} pm_context_mode must be one of: ${En.join(", ")}`,m.USAGE)}function Tn(e,t){if(!e)return;let n=e.trim().toLowerCase();if(qy.includes(n))return n;throw new d(`${t} workspace_context_mode must be one of: ${qy.join(", ")}`,m.USAGE)}function Cn(e){if(!e)return;let t=ar(e,{separators:/[;\n]/});return t.length>0?t:void 0}function br(e,t,n){let r=Cn(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(i){throw new d(`${t} ${n} includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`,m.USAGE)}return r}}function Ja(e,t){if(!e)return;let n=ge(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new d(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Xa(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);r[a]=s}return Object.keys(r).length>0?r:void 0}function Qa(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new d(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let r=Object.create(null);for(let o of n){let i=o.indexOf("=");if(i<=0)throw new d(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0||s.length===0)throw new d(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(s);if(!Number.isFinite(c))throw new d(`${t} assert_json_field_gte value for "${a}" must be numeric`,m.USAGE);r[a]=c}return Object.keys(r).length>0?r:void 0}var QA=new Set(Ot);function Za(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ZA(e,t){let n={},r=[];for(let[o,i]of Object.entries(e)){let a=o.toLowerCase();if(!QA.has(a)){r.push(o);continue}if(Object.hasOwn(n,a))throw t(`provides key "${o}" more than once after case normalization`);n[a]=i}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${Ot.join(", ")}.`);return n}function Sn(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function Ha(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let i=o.filter(a=>a.length>0);return i.length>0?i:void 0}function Ky(e,t,n){let r=Ha(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(i){throw n(`field "${t}" includes invalid regex "${o}": ${i instanceof Error?i.message:String(i)}`)}return r}}function Ba(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function eT(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Ba(n,"timeout_seconds",t),i=r===void 0?void 0:Ba(r,"timeout",t);if(o!==void 0&&i!==void 0&&o!==i)throw t("timeout and timeout_seconds must match when both are provided");let a=o??i;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function tT(e,t){let n=Sn(e,"scope",t);if(n===void 0)return"project";if(!kt.includes(n))throw t(`field "scope" must be one of: ${kt.join(", ")}`);return n}function nT(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Za(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(typeof i!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Wa.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(An.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=i}return Object.keys(r).length>0?r:void 0}function rT(e,t){let n=Ha(e,"env_clear",t);if(n){for(let r of n){if(!Wa.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(An.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function oT(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function iT(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Ba(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function aT(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Za(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof i!="string"&&typeof i!="number"&&typeof i!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(i)}return Object.keys(r).length>0?r:void 0}function sT(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Za(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,i]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Ba(i,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function cT(e,t,n){let r=f=>new d(`${n} ${t} ${f}`,m.USAGE);if(!Za(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${Ot.join(", ")}.`);let o=ZA(e,r),i=Sn(o,"command",r),a=Sn(o,"cmd",r);if(i!==void 0&&a!==void 0&&i!==a)throw r("command and cmd must match when both are provided");let s=i??a;if(s===void 0||s.trim().length===0)throw r('requires a non-empty "command" string');let c=Sn(o,"path",r),l=Sn(o,"pm_context_mode",r);if(l!==void 0&&!En.includes(l))throw r(`field "pm_context_mode" must be one of: ${En.join(", ")}`);let p=Tn(Sn(o,"workspace_context_mode",r),`${n} ${t}`),u=Sn(o,"note",r);return{command:s,path:c!==void 0&&c.length>0?c:void 0,scope:tT(o,r),timeout_seconds:eT(o,r),pm_context_mode:l,workspace_context_mode:p,env_set:nT(o,r),env_clear:rT(o,r),shared_host_safe:oT(o,"shared_host_safe",r),assert_stdout_contains:Ha(o,"assert_stdout_contains",r),assert_stdout_regex:Ky(o,"assert_stdout_regex",r),assert_stderr_contains:Ha(o,"assert_stderr_contains",r),assert_stderr_regex:Ky(o,"assert_stderr_regex",r),assert_stdout_min_lines:iT(o,r),assert_json_field_equals:aT(o,r),assert_json_field_gte:sT(o,r),note:u!==void 0&&u.trim().length>0?u.trim():void 0,phase:wr(o.phase,`${n} ${t}`)}}function Io(e,t){let n=e.trim();if(n.length===0)throw new d(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let r;try{r=JSON.parse(n)}catch(i){throw new d(`${t} value is not valid JSON: ${i instanceof Error?i.message:String(i)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new d(`${t} array must include at least one linked-test entry object`,m.USAGE);return o.map((i,a)=>cT(i,o.length>1?`entry ${a+1}`:"entry",t))}(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]="f75d72fe-b7f5-576d-b6c1-1cd94e3288b3")}catch{}})();var Wl=["command","cmd"],Ro=Object.freeze(Ot.filter(e=>!["command","cmd","timeout"].includes(e)));function zy(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new d("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new d("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:yr(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function Hy(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new d("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function lT(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new d("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let r=yr(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new d("Linked-test selector must be a non-empty command or path",m.USAGE);let i=e.flatMap((a,s)=>a[r]===o?[s]:[]);if(i.length===1)return i[0];if(i.length>1)throw new d(`Linked-test selector is ambiguous; matching indexes: ${i.map(a=>a+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new d("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function By(e,t){let n=Object.keys(e),r=n.filter(o=>!Ro.includes(o));if(n.length===0&&!t||r.length>0)throw new d("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${Ro.join(", ")}.`,recovery:{allowed_values:[...Ro]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new d("scope is required and cannot be cleared",m.USAGE)}function dT(e,t,n){let r={};for(let o of Ro){let i=t[o]!==void 0?t[o]:e[o];i!=null&&(r[o]=i)}return{command:n,...r}}function es(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function mT(e,t,n){let r=Wl.filter(i=>Object.hasOwn(e,i)).map(i=>e[i]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(i=>typeof i!="string"||i.trim()!==o))throw new d("--set-json sets command and cmd to different values; send one command",m.USAGE,{code:"linked_test_command_immutable",...es(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new d(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,m.USAGE,{code:"linked_test_command_immutable",...es(t),nextSteps:[`Patch only editable fields: ${Ro.join(", ")}.`]});return yo(o),o}function pT(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:i,requested:a,global:s}=e;By(i,!0);let c=dT(n[r],i,a),l=Io(JSON.stringify(c),"--add-json")[0];Zc(l);let p=n.findIndex((u,f)=>f!==r&&Yr(u,l));if(p>=0)throw new d(`--set-json cannot change ${o}: linked test ${p+1} already has the requested identity, so a replacement would merge into it`,m.USAGE,{code:"linked_test_command_immutable",...es(o),nextSteps:[`Edit linked test ${p+1} instead: ${L([...Pe(s),"test",t,"--update-index",String(p+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${L([...Pe(s),"test",t,"--remove-index",String(r+1)])}`]});return c}function uT(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function fT(e){let{id:t,tests:n,index:r,patch:o,global:i,controls:a}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let s=o,c=Wl.find(g=>Object.hasOwn(s,g));if(c===void 0)return;let l=n[r],p=mT(s,c,l),u=Object.fromEntries(Object.entries(s).filter(([g])=>!Wl.includes(g))),f=pT({id:t,tests:n,index:r,identityKey:c,otherFields:u,requested:p,global:i}),h=l.command!==void 0&&n.filter(g=>g.command===l.command).length===1?["--remove",`command=${l.command}`]:["--remove-index",String(r+1)],_=[...Pe(i),"test",t,...h,"--add-json",JSON.stringify(f),...uT(a)];throw new d(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,m.USAGE,{code:"linked_test_command_immutable",...es(c),recovery:{suggested_retry:L(_),suggested_retry_args:_},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${h[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function _T(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new d("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);By(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([s])=>Ot.includes(s))),o=u_(Io(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([s,c])=>[s,c===null?void 0:c]))}),"--set-json")[0]);Zc(o);let i=n.filter(s=>!ie(e[s],o[s])),a={...e};for(let s of i){let c=o[s];Object.assign(a,{[s]:c}),c===void 0&&delete a[s]}if(!a.command?.trim()&&!a.path?.trim())throw new d("Linked-test entry must retain a command or path",m.USAGE);return{test:a,fields:i}}async function Wy(e,t,n={}){let r=T(process.cwd(),n.path);await O(r);let o=await E(r),i=I(t.author,o.author_default),a=$(o,R()),s=0,c=[],l=await ir({pmRoot:r,settings:o,id:e,author:i,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:s,fields:c}}),mutate(u){let f=u.metadata.tests??[],h=lT(f,t.selector);fT({id:u.metadata.id,tests:f,index:h,patch:t.patch,global:n,controls:t});let _=_T(f[h],t.patch);return s=h+1,c=_.fields,_.fields.length===0?{changedFields:[]}:(u.metadata.tests=f.map((g,y)=>y===h?{..._.test,updated_by:i,updated_at:A()}:g),{changedFields:["tests"]})}}),p=l.item.tests;return{ok:!0,id:l.item.id,tests:p,count:p.length,changed:l.changedFields.length>0,updated_index:s,updated_fields:c}}(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]="67429334-089f-5cc0-9d73-533fed16b53a")}catch{}})();function hT(){return{metadata:{},body:""}}import{AsyncLocalStorage as iG}from"node:async_hooks";(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]="78b20f7a-4ae7-5811-9ab7-049a07d844e5")}catch{}})();var gT=Vc("list").properties.outputSession,yT={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...gT},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Vy={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},Yy={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},de={type:"string",description:"pm item id, for example pm-abc1."},wT=`Operation name (one of): ${Tc.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,vT={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},bT={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function G(e,t=[]){return{...Yy,properties:{...Yy.properties,...e},required:t}}var kT=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:G({action:{type:"string",enum:[...Tc],description:wT},id:de,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...yT},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:G({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:G({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:G({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({query:{type:"string"},options:{type:"object"},...bT},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:G({options:{type:"object"},...vT})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:G({id:de,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:G({verify:{type:"boolean",description:"Verify complete selected authoritative history chains."},since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:G({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:de,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:de,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:G({id:de,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:G({id:de,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:de,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:G({id:de,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:G({id:de,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:G({id:de,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:'List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls return the newest comments that fit the output budget, with total_count/has_more metadata and a next_cursor that pages back to older comments through outputCursor; without options.limit or outputLimit, outputBudget "unbounded" returns the complete listing at once. Pass options.limit=N for only the newest N comments (next_cursor pages within that window when the budget trims it; has_more reports older comments beyond it without a cursor) or options.limit=0 for summary-only metadata; options.full=true returns the complete history after a write. Rows carry their absolute index; pair edit/delete with options.expectAt to refuse a different entry.',inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings; rows carry their absolute index, and options.expectAt guards edit/delete.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:G({subcommand:{type:"string",enum:[...Fp]},id:de,target:de,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:G({id:de,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:G({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:G({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:G({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:G({...Vy,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...qn],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...uc]},description:`Lifecycle roles for add-status: ${uc.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:Vy}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:G({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:G({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:G({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],ST={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},ET=kT.map(e=>{let t=ST[e.name];if(!t)return e;let n=e.inputSchema.properties,r=e.inputSchema.required.map(String);return{...e,inputSchema:Vc(t,{properties:n,required:r})}});function Jy(){return ET.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(r=>String(r)).sort((r,o)=>r.localeCompare(o)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(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]="208db30b-9299-52bf-902b-14c6a63b08f5")}catch{}})();var Xy=new Map([["activity",["--limit","--after","--full"]],["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),AT=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],sw=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),ns=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),In=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),cw=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),lw=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),dw=new Map([...lw.entries()].flatMap(([e,t])=>Nt(t).map(n=>[n,e]))),mw=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Jl=new Map(mw.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),TT=10,CT=20,Qy=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),pw=[["init",vu],["install",ku],["uninstall",Su],["explore",Eu],["manage",Ou],["describe",Au],["reload",xu],["doctor",$u],["catalog",Pu],["adopt",Lu],["adopt-all",Tu],["activate",Cu],["deactivate",Iu],["migrate",Ru]],IT=[...pw.map(([e,t])=>e==="init"?[e,bu]:[e,t]),["upgrade",Gr]],RT=[...pw.map(([e,t])=>[`extension ${e}`,t]),...IT.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",di],["config",wu],["extension",mi],["package",jr],["packages",jr],["install",Nu],["create",gi],["item mutate",ef],["item complete",tf],["item reopen",nf],["copy",yi],["focus",wi],["update",vi],["update-many",bi],["upgrade",Gr],["calendar",qr],["cal",qr],["context",Kr],["ctx",Kr],["get",Si],["search",Ii],["eval",of],["events",ki],["workspace",Gt],["workspace position",[]],["workspace snapshot",Gt],["workspace snapshot create",Gt],["workspace snapshot list",Gt],["workspace snapshot inspect",Gt],["workspace snapshot restore",Gt],["workspace snapshot delete",Gt],["next",Ci],["aggregate",ai],["deps",Ai],["graph",Ti],["guide",Ei],["reindex",Fu],["history",si],["history-compact",_u],["history-attest",hu],["history-redact",uu],["history-repair",fu],["history-author-acknowledge",ci],["merge",pu],["schema",gu],["profile",yu],["plan",li],["restore",Uu],["delete",ju],["close",Mu],["close-many",pi],["append",ui],["claim",Du],["release",Gu],["start-task",qu],["pause-task",Ku],["close-task",zu],["comments",su],["notes",cu],["learnings",lu],["files",du],["docs",mu],["test",Wu],["test-runs-worker",[]],["test-all",Vu],["telemetry",Yu],["test-runs",Ju],["gc",Xu],["stats",fi],["ops",[]],["duplicates",_i],["validate",Qu],["health",hi],["assurance",Zu],...af,["contracts",Ri],["completion",Oi],["activity",rf],...[...sw].map(e=>[e,ii])],Oo=new Map(RT);for(let{alias:e,canonical:t}of Ce){let n=Oo.get(e);n!==void 0&&Oo.set(t,n)}function OT(e){return dw.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function Zy(e){let t=Ce.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Ec.includes(e)?Se(e):e.startsWith("extension-")?Se(`extension ${e.slice(10)}`):e.startsWith("package-")?Se(`package ${e.slice(8)}`):e.startsWith("item-")?Se(`item ${e.slice(5)}`):e.startsWith("test-runs-")?Se(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?Se(`templates ${e.slice(10)}`):ns.has(e)?lw.get(e)??Se(e):null}function xT(e,t){let n=W(t);return n!==t||Ce.some(r=>r.alias===t)?e.action===n:e.command_path===null?!1:Nt(e.command_path).some(r=>r===t?!0:r.startsWith(`${t} `)||t.startsWith(`${r} `))}function Nt(e){return e.split("|").map(t=>Se(t)).filter(t=>t.length>0)}function $T(e,t){let n=new Set(t),r=new Set;for(let o of e)if(o.command_path)for(let i of Nt(o.command_path)){let a=i.split(" ").filter(s=>s.length>0);if(a.length!==0)for(let s=a.length;s>0;s-=1){let c=a.slice(0,s).join(" ");if(n.has(c)){r.add(c);break}}}return[...r].sort((o,i)=>o.localeCompare(i))}function ts(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function xo(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function PT(e,t){if(!t)return{...e};let n=xo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;return typeof i!="object"||i===null?!1:i.const===t});return{...e,oneOf:n}}function Vl(e,t){let n=xo(e).filter(r=>{let o=r.properties;if(typeof o!="object"||o===null)return!1;let i=o.action;if(typeof i!="object"||i===null)return!1;let a=i.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function Se(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function uw(e){return e.replace(/\s+/g,"-")}function Qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ew(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=Qt(r);!o||n.has(o)||(n.add(o),t.push(o))}return t}function Yl(e,t,n){n&&(e[t]=!0)}function tw(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?kp(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function LT(e){let t=tw(e.long,"long"),n=tw(e.short,"short"),r=t??n;if(!r)return null;let o={flag:r};n&&t&&(o.short=n),Yl(o,"required",e.required===!0),Yl(o,"repeatable",e.repeatable===!0),Yl(o,"list",e.list===!0),e.default!==void 0&&(o.default=e.default);let i=Qt(e.description);i&&(o.description=i);let a=Wp(e);o.value_arity=a.value_arity;let s=Qt(e.value_name)??a.value_name;s&&(o.value_name=s);let c=a.value_type??(a.value_name?"string":null);return c&&(o.value_type=c),o}function fw(e){let t=new Map;for(let r of e){let o=Se(r.target_command);if(o.length===0)continue;let i=t.get(o)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${r.layer}:${r.name}`;i.sourceDedupe.has(a)||(i.sourceDedupe.add(a),i.sources.push({layer:r.layer,name:r.name}));for(let s of r.flags){let c=LT(s);if(!c)continue;let l=`${c.flag}|${c.short??""}`;i.dedupe.has(l)||(i.dedupe.add(l),i.flags.push(c))}t.set(o,i)}let n=new Map;for(let[r,o]of t.entries())n.set(r,{flags:o.flags,sources:o.sources.sort((i,a)=>{let s=i.layer.localeCompare(a.layer);return s!==0?s:(i.name??"").localeCompare(a.name??"")})});return n}function NT(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...$c.filter(({flag:n})=>n.startsWith("--output-"))]}}function FT(e){let t=fw(e.flagRegistrations),n=new Map;for(let i of e.commandDefinitions){let a=Se(i.command);if(a.length===0)continue;let s=Qt(i.action)??uw(a),c=Array.isArray(i.arguments)?i.arguments.map(l=>{let p=Qt(l.name);return p?{name:p,required:l.required===!0,variadic:l.variadic===!0,description:Qt(l.description)}:null}).filter(l=>l!==null):[];n.set(a,{...i.tier===void 0?{}:{tier:i.tier},...NT(i,t.get(a)?.flags??[]),command:a,action:s,source:{layer:i.layer,name:i.name},description:Qt(i.description),intent:Qt(i.intent),arguments:c,examples:ew(i.examples),failure_hints:ew(i.failure_hints)})}let r=new Set;for(let i of e.handlers)r.add(Se(i));for(let i of n.keys())r.add(i);for(let i of t.keys())r.add(i);let o=[];for(let i of[...r].sort((a,s)=>a.localeCompare(s))){let a=n.get(i);o.push(MT(i,a,t.get(i)?.flags??[]))}return o}function MT(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:uw(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function DT(e){let t=e.flag.startsWith("--")?e.flag:void 0,n=vl({long:t,short:t===void 0?e.flag:void 0});return n!==null&&/[a-z0-9]/iu.test(n)?n:null}function UT(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function jT(e,t){let n=e.value_type??"boolean",r=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",o=e.repeatable===!0||e.list===!0;return{type:o?"array":r,...o?{items:{type:r}}:{},...e.default!==void 0?{default:e.default}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function GT(e){let t=e.command.split("|").map(o=>o.trim()).filter(o=>o.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},r=["action"];for(let o of e.arguments)n[o.name]=UT(o,e.action),o.required&&r.push(o.name);for(let o of e.flags){let i=DT(o);!i||n[i]!==void 0||(n[i]=$c.some(a=>a.flag===o.flag&&a.flag.startsWith("--output-"))?Kf[i]:jT(o,e.action),o.required===!0&&r.push(i))}return{type:"object",properties:n,required:r,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function qT(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function KT(e){let t=new Map;for(let n of e){let r=t.get(n.action);if(!r){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}r.command=[...new Set([r.command,n.command])].sort((i,a)=>i.localeCompare(a)).join("|"),r.arguments=r.arguments.length>=n.arguments.length?r.arguments:n.arguments;let o=new Set(r.flags.map(i=>`${i.flag}|${i.short??""}`));for(let i of n.flags){let a=`${i.flag}|${i.short??""}`;if(!o.has(a))o.add(a),r.flags.push(i);else{let s=r.flags.find(c=>`${c.flag}|${c.short??""}`===a);s&&qT(s,i)}}r.examples=[...new Set([...r.examples,...n.examples])],r.failure_hints=[...new Set([...r.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,r)=>n.action.localeCompare(r.action))}async function zT(e,t=E){let n={mode:dn.extensions.policy.mode,trust_mode:dn.extensions.policy.trust_mode,default_sandbox_profile:dn.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let r=T(process.cwd(),e.path);if(!await B(oe(r)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let o=await t(r),i=await Dr({pmRoot:r,settings:o,cwd:process.cwd(),noExtensions:!1}),a=await Ur({...i,loaded:i.loaded});return{handlers:new Set(a.commands.handlers.map(s=>Se(s.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:i.policy.mode,trust_mode:i.policy.trust_mode,default_sandbox_profile:i.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function HT(e,t={}){let n=new Map;for(let r of Ac){let o=ns.has(r);if(o&&!t.includePackageOwnedActions)continue;let i=Zy(r);n.set(r,{action:r,provider:o?"extension":"core",requires_extension:o,command_path:i})}if(t.includePackageOwnedActions)for(let r of ns)n.has(r)||n.set(r,{action:r,provider:"extension",requires_extension:!0,command_path:Zy(r)});for(let r of e)n.has(r.action)||n.set(r.action,{action:r.action,provider:"extension",requires_extension:!0,command_path:Ce.find(o=>o.alias===r.command)?.canonical??Se(r.command)});return[...n.values()].sort((r,o)=>(r.action??"").localeCompare(o.action??""))}function BT(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!In.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?Nt(e.command_path):[],r=n.some(a=>t.handlers.has(a)||t.handlers.has(W(a))),o=n.map(a=>cw.get(W(a))).find(a=>typeof a=="string"),i=t.disabledReason===null&&r;return{action:e.action,invocable:i,available:i,requires_extension:!0,provider:"extension",disabled_reason:i?null:t.disabledReason??(o?`optional_package_not_installed:${o}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:r,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function _w(e){let t=Oo.get(e)??Kn,n=qe(e).find(r=>r.flag==="--output-format"&&r.aliases?.includes("--format"));return n?[...t,n]:t}function Xl(e){return In.has(W(e))?!1:Oo.has(e)}function WT(e){return sw.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function nw(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function VT(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function YT(e){let t=new Map;for(let r of e.definitions){let o=nw(r.cli_flag);if(!o)continue;let i=r.cli_aliases.map(s=>VT(s)).find(s=>s!==null),a=r.cli_aliases.map(s=>nw(s)).filter(s=>s!==null&&s!==o);for(let s of r.commands){let c=t.get(s)??{flags:[],seen:new Set},l=i?{flag:o,short:i}:{flag:o},p=`${l.flag}|${l.short??""}`;c.seen.has(p)||(c.seen.add(p),c.flags.push(l));for(let u of a){let f=`${u}|`;c.seen.has(f)||(c.seen.add(f),c.flags.push({flag:u}))}t.set(s,c)}}let n=new Map;for(let[r,o]of t.entries())n.set(r,xc(o.flags));return n}function rw(e,t){let n=[],r=new Set;for(let o of[...e,...t]){let i=`${o.flag}|${o.short??""}`;r.has(i)||(r.add(i),n.push(o))}return xc(n)}function JT(e){let t=vl(e.flag.startsWith("--")?{long:e.flag}:{short:e.flag});return{...e,owner:"extension",...t===null?{}:{sdk_option:t}}}function XT(e,t,n,r){let o=(n??[]).map(JT),i=t==="extension"&&(n!==void 0||QT(e,r));return{flags:o,inherited:i?{inherited_flags:au({readOutput:ZT(e,r)})}:{}}}function hw(e,t){let n=W(e);return t.find(r=>W(r.command)===n)}function QT(e,t){return hw(e,t)!==void 0}function ZT(e,t){return hw(e,t)?.read_output!==void 0}function eC(e,t,n,r,o){let i=new Map(t);for(let{alias:a,canonical:s}of Ce){let c=t.get(s)??t.get(a);c&&(i.set(a,c),i.set(s,c))}return e.map(a=>{let s=Xl(a),c=s?_w(a):[],l=n.get(WT(a))??[],p=i.get(a),u=rw(c,l),f=c.length>0&&(p?.flags.length??0)>0?"mixed":s?"core":"extension",h=XT(a,f,p?.flags,o),_=rw(u,h.flags);return{command:a,flags:_,...h.inherited,...r?{canonical_command:yw(a),visibility:gw(a,o),positionals:ou(a)?.slots??[],flag_invocations:ao(a,_)}:{},provider:f,extension_sources:p?.sources}}).sort((a,s)=>a.command.localeCompare(s.command))}function tC(e,t=mn){let n=new Set(e),r=new Map;for(let o of mw){let i=o.aliases.filter(a=>n.has(a));r.set(o.canonical,{canonical:o.canonical,aliases:i,contracts:[]})}for(let o of t){if(!n.has(o.canonical)||o.registration==="commander"&&!n.has(o.alias))continue;let i=r.get(o.canonical)??{canonical:o.canonical,aliases:[],contracts:[]};i.aliases.includes(o.alias)||i.aliases.push(o.alias),i.contracts.push(o),r.set(o.canonical,i)}return[...r.values()].map(({contracts:o,...i})=>o.length===0?i:{...i,contracts:o}).sort((o,i)=>o.canonical.localeCompare(i.canonical))}function nC(){return{create_string_options:zf,create_repeatable_options:qi,update_string_options:Hf,update_repeatable_options:Bf,list_string_options:Jp,search_string_options:Xp,calendar_string_options:Qp,context_string_options:Zp,activity_string_options:eu}}function ow(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let s of e.required_create_fields)n.add(s);for(let s of e.required_create_repeatables)n.add(s)}let r=Gn(e,"create",n),o=[...new Set(r.required)].sort((s,c)=>s.localeCompare(c)),i=[...new Set(o.map(s=>xe("create",s)))].sort((s,c)=>s.localeCompare(c)),a=[...new Set(e.options.filter(s=>s.required===!0).map(s=>s.key))].sort((s,c)=>s.localeCompare(c));return{required_option_keys:o,required_flags:i,required_type_options:a,policy_errors:[...new Set(r.errors)].sort((s,c)=>s.localeCompare(c))}}function rC(e){let t={},n={};for(let r of[...e.types].sort((o,i)=>o.localeCompare(i))){let o=e.by_type[r];t[r]=ow(o,"strict"),n[r]=ow(o,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function oC(e,t){let n=xo(e);if(n.length===0)return e;let r=!1,o=n.map(i=>{let a=i.properties;if(typeof a!="object"||a===null)return i;let s=a.action;return typeof s!="object"||s===null||s.const!=="create"?i:(r=!0,{...i,"x-create-required-options":t})});return r?{...e,oneOf:o}:e}function iC(e){let t=ts(e.action)!==void 0||ts(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,r=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,o=e.schemaOnly===!0,i=e.flagsOnly===!0,a=e.availabilityOnly===!0,s=e.runtimeOnly===!0,c=e.full===!0,l=ts(e.action),p=ts(e.command),u=!r&&!c&&!o&&!i&&!a&&!l&&!p;return{selectedAction:l,selectedCommand:p,summary:r,schemaOnly:o,flagsOnly:i,availabilityOnly:a,runtimeOnly:s,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||p!==void 0&&!c}}function aC(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new d("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function sC(e,t=E){try{return await t(e)}catch{return structuredClone(dn)}}async function cC(e,t,n){let r=await sC(t),o=await zT(e),i=$(r,o.registrations??R()),a=Qe(r.schema),s=FT(o);return{settings:r,runtimeProbe:o,typeRegistry:i,statusRegistry:D(r.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:YT(a),createRequiredOptionContracts:rC(i),extensionContracts:s,mergedExtensionContracts:KT(s.filter(c=>rs(n,c.command,s))),extensionFlagMap:fw(o.flagRegistrations)}}function iw(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&ns.has(e.selectedAction)||e.selectedCommand!==void 0&&In.has(W(e.selectedCommand)))}function lC(e,t){let n=HT(t,{includePackageOwnedActions:iw(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let r=new Set(Up);return n.filter(o=>!r.has(o.action)&&(e.fullOutput||(t.find(i=>i.action===o.action)?.tier??fa(o.action))!=="internal"))}return iw(e)&&e.selectedCommand!==void 0&&In.has(W(e.selectedCommand))&&!n.some(r=>r.command_path===e.selectedCommand)&&n.push({action:OT(W(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function dC(e,t){let n=new Set(t.map(r=>r.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new d(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function mC(e,t){return[...new Set([...Ec.filter(n=>!In.has(W(n))),...[...Oo.keys()].filter(n=>!In.has(W(n))),...e.flatMap(n=>n.command_path?Nt(n.command_path).filter(r=>n.provider==="extension"||!In.has(W(r))||t.some(o=>o.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(r=>{let o=Ce.find(i=>i.alias===r||i.canonical===r);return o===void 0?[r]:[o.alias,o.canonical]}))])].map(n=>Se(n)).filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r))}function pC(e,t){let n=t.slice(0,TT),r=t.length-n.length,o=r>0?`${n.join(", ")}, and ${r} more`:n.join(", "),i=t.slice(0,CT),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),s=t[0];return new d(`Command "${e}" is a command namespace. Choose a concrete child command: ${o}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${s}" --flags-only --json`,fallback_candidates:i.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function uC(e,t){return new d(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function fC(e){return new d(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function _C(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(o=>o.startsWith(`${e.selectedCommand} `));if(n.length>0)throw pC(e.selectedCommand,n);let r=cw.get(W(e.selectedCommand));throw r?uC(e.selectedCommand,r):fC(e.selectedCommand)}function hC(e,t){let n=lC(e,t.mergedExtensionContracts);dC(e,n);let r=mC(n,t.mergedExtensionContracts);_C(e,r);let o=e.selectedCommand?dw.get(W(e.selectedCommand)):void 0,i=e.selectedCommand?n.filter(l=>o?l.action===o:xT(l,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!i.some(l=>l.action===e.selectedAction))throw new d(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let a=e.selectedAction?i.filter(l=>l.action===e.selectedAction):i,s=[...new Map(a.map(l=>BT(l,t.runtimeProbe)).map(l=>[o?l.action:`${l.action}|${l.command_path??""}`,l])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?s.filter(l=>l.invocable):s;return{actionDescriptors:n,commandCatalog:r,commandScopedDescriptors:i,scopedActionDescriptors:a,selectedPackageOwnedAction:o,actionAvailability:c,actions:[...new Set(c.map(l=>l.action))]}}function gC(e){return new Set(xo(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let r=n.action;if(typeof r!="object"||r===null)return null;let o=r.const;return typeof o=="string"?o:null}).filter(t=>t!==null))}function yC(e){let t=Wf,n=xo(t),r=gC(t),o=e.filter(i=>!r.has(i.action)).map(i=>GT(i));return o.length>0?{...t,oneOf:[...n,...o]}:t}function aw(e,t,n){let r=new Set(t.actionDescriptors.map(i=>i.action)),o=e.selectedAction?PT(n,e.selectedAction):e.selectedCommand?Vl(n,new Set(t.scopedActionDescriptors.map(i=>i.action))):Vl(n,r);return e.runtimeOnly&&!e.selectedAction?Vl(o,new Set(t.actions)):o}function wC(e,t,n){let r=yC(t.mergedExtensionContracts),o=!e.flagsOnly&&!e.availabilityOnly?oC(aw(e,n,r),t.createRequiredOptionContracts):aw(e,n,r);return{mergedSchema:r,filteredSchema:o}}function vC(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?$T(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function gw(e,t){return t.find(n=>W(n.command)===W(e))?.tier??fa(e)}function rs(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||gw(t,n)!=="internal"}function bC(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let r=new Set(mn.filter(o=>o.hidden&&(o.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(o=>o.alias));if(e.summary&&!e.fullOutput)for(let o of Jl.keys())r.add(o);return t.filter(o=>!r.has(o)&&rs(e,o,n))}function yw(e){let t=Ce.find(r=>r.alias===e||r.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Jl.get(n)??n}var kC=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),SC=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function EC(e,t){let n=Qy.get(W(e))??(e.includes(" ")?void 0:Qy.get(yw(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let r=t.find(l=>Nt(l.command).some(p=>W(p)===W(e)));if(r?.intent!==null&&r?.intent!==void 0)return{intent:r.intent,intent_source:"command"};if(r?.description!==null&&r?.description!==void 0)return{intent:r.description,intent_source:"description"};let o=e.split(" "),i=o.at(-1),a=o.slice(0,-1).join(" "),s=kC.get(i),c=SC.get(e)??a;return{intent:s===void 0||a.length===0?`Run ${e}.`:`${s} ${c}.`,intent_source:"generated"}}function AC(e,t=[],n={}){let r=n.includeFormatBudgets??!0,o=n.includeIntentProvenance??!0;return[...new Set(e.map(Se))].filter(i=>i.length>0).sort((i,a)=>i.localeCompare(a)).map(i=>{let a=Hc(i,{generateFallback:!0}),s=i.split(" ")[0],c=Jl.get(s)??(s.startsWith("list-")?"list":s.startsWith("history-")?"history":s),l=new Set([..._w(i).map(f=>f.flag),...t.filter(f=>Nt(f.command).some(h=>W(h)===W(i))).flatMap(f=>f.flags.map(h=>h.flag))]),p=(Xy.get(W(i))??Xy.get(c)??AT).filter(f=>l.has(f)),u=EC(i,t);return{command:i,intent:u.intent,...o||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...p.length>0?{flags:p}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...r?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function TC(e){return e.map(t=>({budget:Hc(t,{generateFallback:!0}),envelope:lh(t)}))}function CC(e){let t=new Map;for(let n of e){let r=ih(n),o=r===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:r.exit_codes,i=o.join(","),a=t.get(i)??{commands:[],exit_codes:o};a.commands.push(n),t.set(i,a)}return[...t.values()]}function IC(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(r=>Nt(r.command).some(o=>W(o)===W(e.selectedCommand)));if(e.selectedAction){let r=new Set(n);return t.extensionContracts.filter(o=>Nt(o.command).some(i=>r.has(i)))}return t.extensionContracts.filter(r=>rs(e,r.command,t.extensionContracts))}function RC(e,t,n,r){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:r,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function OC(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=__);let r=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(o=>o.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([o])=>r===void 0||o===r).map(([o,i])=>[o,[...new Set(i.map(a=>`--${a.cli_flag}`))].sort((a,s)=>a.localeCompare(s))]))},!(r!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Op],services:[...xp],policy_modes:[...$p],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Np],trust_modes:[...Pp],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Lp],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...fp],create_modes:[..._p],close_validation_modes:[...hp],workflow_enforcement_modes:[...gp]},e.relationship_kind_contracts=[...Sp,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(o=>o.definitions)].sort((o,i)=>o.kind.localeCompare(i.kind)).map(o=>({canonical:o.kind,aliases:[...o.aliases??[]],...o.inverse===void 0?{}:{inverse:o.inverse},ordering:o.ordering,hierarchy:o.hierarchy})))}function xC(e,t,n,r){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=r;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=r}}function $C(e,t,n,r,o){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=eC(r,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let i=new Set(r);e.list_projections=Object.entries(ru).filter(([a])=>i.has(a)).map(([a,s])=>({command:a,default:s,brief_fields:[...nu,"priority"],compact_fields:[...tu]}))}e.command_aliases=t.fullOutput?o:o.map(({canonical:i,aliases:a})=>({canonical:i,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function PC(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=nC();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function LC(e,t,n,r){e.command_summaries=AC(t,n,{includeFormatBudgets:r.includeFormatBudgets,includeIntentProvenance:r.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Of],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...r.includeProjectionModeMatrix?{commands:[...new Set(t.map(Se))].filter(o=>Pf(o)!==void 0).sort((o,i)=>o.localeCompare(i)).map(o=>({command:o,modes:[...Nf(o).keys()]}))}:{}},e.grammar_contracts={nouns:pn.nouns,shared_verbs:pn.shared_verbs,scope_before_verb:pn.scope_before_verb,visible_top_level_ceiling:pn.visible_top_level_ceiling,ceiling_raise_requires_pm_item:pn.ceiling_raise_requires_pm_item,positional_shape_budget:pn.positional_shape_budget,positional_shape_count:new Set(Oc.map(({slots:o})=>iu(o))).size,positional_action_count:Rc.length,positional_action_parents:[...new Set(Rc.map(({parent:o})=>o))].sort((o,i)=>o.localeCompare(i)),...r.includePositionalSignatures?{positional_signatures:Oc}:{}}}async function Ql(e,t){let n=iC(e);aC(n);let r=T(process.cwd(),t.path),o=await cC(t,r,n),i=hC(n,o),a=wC(n,o,i),s=vC(n,i),c=bC(n,s,o.extensionContracts),l=RC(n,a,i,c),p=IC(n,o,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&LC(l,c,p,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return l;let f=tC(i.commandCatalog.filter(h=>rs(n,h,o.extensionContracts)));return n.flagsOnly&&!n.fullOutput||OC(l,o,n),xC(l,n,a,p),$C(l,n,o,c,f),PC(l,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(l.assurance_contracts={measurement_source_kinds:[...Ph],gate_triggers:[...$h]}),n.fullOutput&&l.grammar_contracts&&(l.grammar_contracts.destinations=oi.map(h=>({...h,reason:h.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(l.mcp_tools=Jy(),l.context_intents=Df(),l.read_output_dimensions=$f,l.error_codes=ah,l.command_output_contracts=TC(c),l.diagnostic_output_contracts=xf,l.command_exit_contracts={vocabulary:oh,command_sets:CC(c)}),l}(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]="0a4abc17-0fcb-573f-8f89-6e505e112261")}catch{}})();async function ww(e,t,n=Mf){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t,o=Array.isArray(r.warnings)?r.warnings.filter(i=>typeof i=="string"):[];r.warnings=[...new Set([...o,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as NC}from"node:crypto";(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]="971103f5-a101-5e45-a607-ebebbaafe7f5")}catch{}})();function Zl(e){let t=Ep();for(let n of e)t.register(n);return t}function FC(e,t,n=[]){if(n.length===0)return e;let r=JSON.parse(e),o=JSON.parse(_l(t));for(let i of n){let a=i.split("."),s=o;for(let p of a){let u=kc(s);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(p)||["constructor","prototype","__proto__"].includes(p)||u===null||!Object.hasOwn(u,p))throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);s=u[p]}if(kc(s)===null)throw new d(`Invalid owned settings subtree: ${i}. Select a declared inline object path.`,m.USAGE);let c=r,l=o;for(let p of a.slice(0,-1)){let u=c[p];l=l[p],u===void 0&&Object.defineProperty(c,p,{value:structuredClone(l),enumerable:!0,writable:!0,configurable:!0}),c=c[p]}Object.defineProperty(c,a.at(-1),{value:s,enumerable:!0,writable:!0,configurable:!0})}return ie(r,JSON.parse(e))?e:`${JSON.stringify(r,null,2)}
2
+ `}function vw(e,t,n,r){return{fitOutputEnvelope:Fh,client:t,isItemNotFoundError:o=>io(o)&&o.exitCode===m.NOT_FOUND,getItemAt:(o,i)=>Nh(o,i,{pmRoot:e}),readSettingsSection:(o,i)=>Z_(e,o,i),writeSettingsSection:(o,i,a)=>eh(e,o,i,{author:n,...a}),openRelationshipEventStore:o=>Dh.open({pmRoot:e,nodes:o.nodes,registry:Zl(o.definitions),...o.relativePath===void 0?{}:{relativePath:o.relativePath}}),createRelationshipGraph:o=>new Cp(o.nodes,o.edges,Zl(o.definitions)),analyzeRelationshipImpact:(o,i,a)=>Uh(o,i,a),validateRelationshipEvents:o=>{let i=new Mh(o.nodes,{registry:Zl(o.definitions)});return o.events.map(a=>i.append({...a,expectedVersion:i.version}))},commitWorkspaceTransaction:o=>jh({...o,pmRoot:e}),mutateWorkspaceSettings:async o=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(o.operationId))throw new d("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",m.USAGE);let i=o.dryRun===!0?await no(e,()=>E(e)):await E(e);try{let a=await oa({pmRoot:e,filePath:oe(e),op:"extension:pm:settings",idempotencyKey:r===void 0?o.operationId:`${NC("sha256").update(r).digest("hex").slice(0,16)}:${o.operationId}`,author:I(n,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!1,dryRun:o.dryRun===!0,mutate:async s=>{let c=s===null?null:JSON.parse(s),l=da(c);if(!l.success)throw new d("Workspace settings mutation requires a valid initialized settings.json.",m.USAGE);let p=fl(l.data),u=await o.mutate(structuredClone(p));if(!da(u).success)throw new d("Workspace settings mutation returned invalid settings.json.",m.USAGE);let f=ie(p,u)?s:_l(u,{source:{raw:c,validated:l.data}});f=FC(f,u,o.replaceSubtrees);let h=da(JSON.parse(f));if(!h.success)throw new d("Workspace settings mutation serialized invalid settings.json.",m.USAGE);return{raw:f,result:o.includePreview===!0?fl(h.data):void 0}}});return a.changed&&o.dryRun!==!0&&await X({path:oe(e),scope:"project",op:"extension:pm:settings"}),{changed:a.changed,dry_run:o.dryRun===!0,replayed:a.replayed===!0,...a.result===void 0?{}:{preview:a.result}}}finally{x_(e)}}}}(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]="1956081d-53b1-5f2c-887a-6aac3325b764")}catch{}})();function bw(e){return{undeclaredKeys:Xl(e)?"pass":"refuse"}}import MC from"node:fs/promises";import Q from"node:path";import DC from"node:readline/promises";import{stdin as UC,stdout as He}from"node:process";(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]="0bfdfae5-a153-5cc1-9946-aa2ef215aa85")}catch{}})();var td=Symbol.for("pm.sdk.init-invocation-cwd");var jC=()=>DC.createInterface({input:UC,output:He});function GC(){return structuredClone(dn)}var qC=["minimal","default","strict"];function Sw(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--preset must not be empty",m.USAGE);if(t==="minimal"||t==="default"||t==="strict")return t;if(t==="lite"||t==="minimum")return"minimal";throw new d(`Invalid --preset value "${e}". Allowed: ${qC.join(", ")}`,m.USAGE)}function KC(e){if(e!==void 0){if(e.trim().length===0)throw new d("--type-preset must not be empty",m.USAGE);try{return mf(e)}catch{throw new d(`Invalid --type-preset value "${e}". Allowed: ${df.join(", ")}`,m.USAGE)}}}function zC(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new d("--author must not be empty",m.USAGE);return t}function ed(e){if(e===void 0)return!1;let t=e.trim();return t.length===0?!1:Q.isAbsolute(t)||/^[a-z]:/iu.test(t)||t.startsWith(".")||t.includes("/")||t.includes("\\")}function HC(e,t,n,r){let o=r?.trim();if(r!==void 0&&o?.length===0)throw new d("--workspace must not be empty",m.USAGE);if(o!==void 0){if(t.path!==void 0||ed(n))throw new d("--workspace cannot be combined with --pm-path/--path or a path-like positional target.",m.USAGE);let l=Q.resolve(e,o),p=Q.join(l,".agents","pm");return{pmRoot:p,prefixArg:n,target:{mode:"workspace-path",tracker_root:p,workspace_root:l}}}if(t.path===void 0&&ed(n)){let l=Q.resolve(e,n.trim());return{pmRoot:l,prefixArg:void 0,target:{mode:"tracker-path",tracker_root:l}}}let i=T(e,t.path),a=Q.join(Q.resolve(e),".agents","pm"),s=Q.dirname(Q.dirname(i)),c=Q.resolve(i)===a?"current":"ancestor";return{pmRoot:i,prefixArg:n,target:t.path===void 0?{mode:"workspace-discovery",tracker_root:i,workspace_root:s,discovery:c,requested_cwd:Q.resolve(e),...c==="ancestor"?{suggested_current_tracker_root:a}:{}}:{mode:"tracker-path",tracker_root:i}}}function BC(e,t){if(t===void 0)return e;if(t.trim().length===0)throw new d("--id-prefix must not be empty",m.USAGE);if(ed(t))throw new d(`--id-prefix accepts an item ID prefix, not a tracker path: "${t}".`,m.USAGE,{code:"init_id_prefix_path_like",required:"Pass the tracker path positionally or with the global --path option.",examples:[`pm init ${t}`,`pm --path ${t} init`]});if(e!==void 0&&Wt(e)!==Wt(t))throw new d(`Conflicting id prefixes: positional "${e}" and --id-prefix "${t}".`,m.USAGE,{code:"init_id_prefix_conflict",required:"Use either the positional id prefix or --id-prefix with one value.",examples:[`pm init ${Wt(e)}`,`pm init --id-prefix ${Wt(t)}`]});return t}function WC(e){if(e===void 0)return"ask";let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new d("--agent-guidance must not be empty",m.USAGE);if(t==="ask"||t==="add"||t==="skip"||t==="status")return t;throw new d(`Invalid --agent-guidance value "${e}". Allowed: ${dg.join(", ")}`,m.USAGE)}function VC(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}function Ew(e,t){let n=vp[t];e.governance={preset:t,...n},e.validation.parent_reference=n.parent_reference,e.validation.metadata_profile=n.metadata_profile}function YC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function JC(e){let t=e.details;return{installed_all:t.installed_all===!0,installed_count:typeof t.installed_count=="number"?t.installed_count:0,packages:Array.isArray(t.packages)?t.packages.filter(YC).map(n=>({alias:typeof n.alias=="string"?n.alias:"",ok:n.ok===!0})):[]}}async function XC(e,t,n){let r=Pi(t.schema),o=Ct(e,r.files.types,Tt.types),i=cf(await ee(o)),a=[],s=[];for(let c of pf(n)){let l=lf(i,c);i=l.file,(l.replaced?s:a).push(l.definition.name)}return await nt({pmRoot:e,filePath:o,raw:xi(i),op:"init:type-preset",author:I(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms}),{name:n,registered:a,updated:s,file:o}}async function QC(e){let t=[".git","package.json","pnpm-workspace.yaml","AGENTS.md",Q.join(".agents","pm")];for(let n of t)if(await B(Q.join(e,n)))return!0;return!1}async function ZC(e,t,n){if(!t||n||await B(Q.join(e,"settings.json"))||!await QC(e))return;let r=Q.join(e,".agents","pm");throw new d(`Refusing to initialize tracker files directly in workspace root "${e}".`,m.USAGE,{code:"workspace_root_pm_path",type:"urn:pm-cli:error:workspace_root_pm_path",why:"Path-like init targets and --pm-path/--path point at the tracker storage directory itself, not the repository workspace. Point at .agents/pm, use --workspace, or pass --force if you intentionally want root-level tracker files.",examples:[`pm --pm-path ${r} init --yes`,"pm init --yes",`pm --pm-path ${e} init --yes --force`],nextSteps:["Use --pm-path <repo>/.agents/pm for repository-local tracker storage.","Use PM_PATH only for sandboxed tests or explicit tracker roots.","Pass --force only when root-level tracker files are intentional."],recovery:{next_best_command:`pm --pm-path ${r} init --yes`}})}async function Aw(e,t){let n=[],r=[];for(let o of t){let i=o?Q.join(e,o):e,a=await B(i);await MC.mkdir(i,{recursive:!0}),a?r.push(`already_exists:${i}`):n.push(i),r.push(...await X({path:i,scope:"project",op:"init:ensure_dir"}))}return{createdDirs:n,warnings:r}}async function e0(e,t){let n=jC(),r=t===void 0?2:3;try{He.write(`pm init setup wizard (agent-optimized)
3
+ `),He.write(`This walkthrough is non-destructive and each choice can be changed later with pm config.
4
+
5
+ `),He.write(`1/${r} Item ID prefix
6
+ `),He.write(`Prefix is prepended to generated IDs (for example pm-a1b2).
7
+ `);let o=await n.question(`Item ID prefix [${e}]: `),i=o.trim().length>0?Wt(o):e;He.write(`
8
+ 2/${r} Governance preset
9
+ `),He.write(`minimal: no ownership blocking, progressive create defaults, close validation off.
10
+ `),He.write(`default: ownership conflict warnings, progressive create defaults, close validation warn.
11
+ `),He.write(`strict: ownership blocking, strict create defaults, close validation strict.
12
+ `);let a=await n.question("Governance preset [minimal/default/strict] (default: minimal): "),s=a.trim().length>0?a.trim():"minimal",c="minimal";try{c=Sw(s)}catch{He.write(`Unrecognized governance preset "${s}"; using minimal.
13
+ `)}let l;if(t!==void 0){He.write(`
14
+ 3/3 Telemetry
15
+ `),He.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
16
+ `);let p=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);l=VC(p,t)}return He.write(`
17
+ `),{prefix:i,preset:c,telemetry_enabled:l}}finally{n.close()}}function t0(e){return{presetFromOption:Sw(e.preset),useDefaults:e.defaults===!0,authorFromOption:zC(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:WC(e.agentGuidance),typePreset:KC(e.typePreset)}}function n0(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function r0(e,t,n,r){if(t.length===0||n)return;let o=r.discovery==="ancestor";throw new d(`${o?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,m.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:o?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...o?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...o?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function o0(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(Ew(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function i0(e){let t=await E(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=n0({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return r0(e.settingsPath,n,e.options.force===!0,e.target),o0({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await Re(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function a0(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,o=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let l=await e0(t,await s0());t=l.prefix,n=l.preset,r=l.telemetry_enabled,o=!0}let i=n??"minimal",a=GC();a.id_prefix=t,Ew(a,i);let s=Fc()?.trim()||void 0;a.author_default=e.normalizedOptions.authorFromOption??s??"";let c=Tw(e.pmRoot);return r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await Re(e.pmRoot,a,void 0,c),r!==void 0&&c.omitSections&&await c0(r,e.warnings),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:o}}function Tw(e){return Q.resolve(e)===Q.resolve($e(process.cwd()))?{}:{omitSections:["telemetry"]}}async function s0(){let e=await E($e(process.cwd()));if(!(pa().telemetry_disabled||e.telemetry.first_run_prompt_completed||$t(e)))return e.telemetry.enabled}async function c0(e,t){let n=$e(process.cwd()),r=await E(n);if($t(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let o=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await Re(n,r,"telemetry:first_run_prompt",{skipIfStored:i=>o=i.telemetry?.first_run_prompt_completed===!0}),o&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function l0(e){let{telemetry:t}=await E($e(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function kw(e){return e.settingsExists?await i0(e):await a0({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function d0(e){let t=await mg({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await Re(e.pmRoot,e.settings,void 0,Tw(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function m0(e,t){let n=[],r=[],o=await hf(e,t.schema);for(let i of o.created_paths)n.push(i),r.push(...await X({path:i,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function p0(e){if(e.typePreset===void 0)return;let t=await XC(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await X({path:t.file,scope:"project",op:"init:type_preset"})),t}async function u0(e){let t=$(e.settings,R()).folders.filter(r=>!bc.includes(r)),n=await Aw(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function f0(e){let t=Q.resolve(e.tracker_root),n=Q.dirname(t);return Q.basename(t)==="pm"&&Q.basename(n)===".agents"?Q.dirname(n):e.workspace_root}async function _0(e,t,n,r){if(!e)return;let o=await lr("all",{install:!0,project:!0},{...t,path:n});r.push(...o.warnings);let i=JC(o),a=i.packages.filter(s=>!s.ok).map(s=>s.alias);if(!i.installed_all||a.length>0)throw new d(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,m.GENERIC_FAILURE);return i}function h0(e){let t=r=>L([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let o=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(o)||n.push(o)}return n}async function g0(e,t,n,r=Hh){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let o=await r({pmRoot:e,workspaceRoot:t});o.gitattributes.changed&&n.push(`updated:merge_fence:${o.gitattributes.path}`)}catch(o){if(!(o instanceof d))throw o;n.push(`merge_fence_skipped:install_failed:${o.context.code??"pm_error"}:${o.message}:run pm merge install after resolving the Git repository error`)}}async function y0(e,t,n,r){if(e==null||n==="status")return;let o=await Tl(e,{pmRoot:t});o.changed&&r.push(`updated:gitignore:${o.path}`)}async function $o(e,t,n={}){let r=t[td],o=typeof r=="string"?r:process.cwd(),i=HC(o,t,e,n.workspace),a=i.pmRoot;e=BC(i.prefixArg,n.idPrefix);let s=t0(n);await ZC(a,i.target.mode==="tracker-path",n.force===!0);let c=[],l=[],p=Q.join(a,"settings.json"),u=await B(p),f;u&&(f=await kw({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Wt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:i.target}));let h=await Aw(a,bc);c.push(...h.createdDirs),l.push(...h.warnings),f??=await kw({pmRoot:a,settingsPath:p,settingsExists:u,normalizedPrefix:Wt(e),prefixArg:e,options:n,normalizedOptions:s,warnings:l,target:i.target});let{settings:_}=f,g=f0(i.target),y=await Aa(g??Q.dirname(a)),w=g??y,v=await d0({pmRoot:a,cwd:w??o,agentGuidanceMode:s.agentGuidanceMode,settings:_,warnings:l}),k=await m0(a,_);c.push(...k.createdDirs),l.push(...k.warnings);let C=await p0({pmRoot:a,settings:_,typePreset:s.typePreset,warnings:l});C&&(_=await E(a)),await u0({pmRoot:a,settings:_,createdDirs:c,warnings:l}),await y0(w,a,s.agentGuidanceMode,l),!u&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await g0(a,y,l);let S=await _0(s.installBundledPackages,t,a,l),x=h0({installBundledPackages:s.installBundledPackages,registeredTypePreset:C,agentGuidanceNextSteps:v.next_steps,target:i.target});return{ok:!0,path:a,target:i.target,settings:await l0(_),created_dirs:c,warnings:l,governance_preset:_.governance.preset,wizard_used:f.wizardUsed,...C?{registered_type_preset:C}:{},...S?{installed_packages:S}:{},next_steps:x,agent_guidance:v}}(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]="08ad3dd1-a1ec-5ee8-9f0f-1350dd91f25e")}catch{}})();async function Cw(e,t){let n=T(t??process.cwd(),e),r=await E(n);return ye(n,r.item_format,$(r,null).type_to_folder,void 0,r.schema)}(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]="247354d6-fccb-58f8-b969-b1952abf181e")}catch{}})();var w0={"list-all":{action:"list",options:{excludeTerminal:!1}},"list-draft":{action:"list",options:{status:"draft",excludeTerminal:!1}},"list-open":{action:"list",options:{status:"open",excludeTerminal:!1}},"list-in-progress":{action:"list",options:{status:"in_progress",excludeTerminal:!1}},"list-blocked":{action:"list",options:{status:"blocked",excludeTerminal:!1}},"list-closed":{action:"list",options:{status:"closed",excludeTerminal:!1}},"list-canceled":{action:"list",options:{status:"canceled",excludeTerminal:!1}}};function Iw(e){return Object.fromEntries(Mp.map(t=>[`${e}-${t}`,{action:e,options:{[t==="adopt-all"?"adoptAll":t]:!0,...e==="package"?{vocabulary:"package"}:{}}}]))}var Rw={ctx:{action:"context"},...w0,...Iw("extension"),...Iw("package"),...Object.fromEntries(Dp.map(e=>[`package-${e}`,{action:e}]))};(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]="baa27a48-c538-574c-9d05-1f1c0f4f429c")}catch{}})();function Ow(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function v0(e){return e.brief===!0?"brief":typeof e.fields=="string"&&e.fields.trim().length>0||Array.isArray(e.fields)&&e.fields.length>0?"fields":e.compact===!0?"compact":"full"}function nd(e,t){let n=v0(t),r=n==="brief"?n:Ow(e.projection)&&typeof e.projection.mode=="string"?e.projection.mode:n;return{...e,query_summary:{filters:Ow(e.filters)?e.filters:{},projection:r}}}import{readFile as b0}from"node:fs/promises";(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]="b6e1bb2f-ac0f-500e-ba35-64f6a2f08868")}catch{}})();async function rd(e,t){let n=e.add!==void 0,r=e.stdin===!0,o=typeof e.file=="string",i=Number(n)+Number(r)+Number(o);if(i===0)return;if(i>1)throw new d("Specify comment text using only one input source: --add, --stdin, or --file",m.USAGE);if(n)return{value:await t.resolveValue(e.add,"--add",Rt(e))??"",emptyFlag:"--add"};if(r)return So(e,"--stdin"),{value:await t.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};let a=e.file.trim();if(!a)throw new d("--file path cannot be empty",m.USAGE);if(a==="-")return So(e,"--file -"),{value:await t.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await b0(a,"utf8"),emptyFlag:"--file"}}catch(s){if(Kl(s)&&St(s))throw new d(`--file path not found: ${a}. Use --file - to read stdin.`,m.USAGE);let c=s instanceof Error?s.message:String(s);throw new d(`Failed to read --file path "${a}": ${c}. Use --file - to read stdin.`,m.USAGE)}}async function k0(e,t){let n=e.edit,r=e.delete,o=n!==void 0,i=r!==void 0;if(o&&i)throw new d("Specify only one of --edit or --delete",m.USAGE);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new d("--edit must be a positive integer",m.USAGE);if(r!==void 0&&(!Number.isInteger(r)||r<1))throw new d("--delete must be a positive integer",m.USAGE);if(i){if(await rd(e,t)!==void 0)throw new d("--delete does not take comment text",m.USAGE);return{mode:"delete",index:r}}if(o){let s=await rd(e,t);if(s===void 0)throw new d("--edit requires replacement text via positional [text], --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:n,value:s.value,emptyFlag:s.emptyFlag}}let a=await rd(e,t);return a===void 0?{mode:"list"}:{mode:a.emptyFlag==="--add"?"add":a.emptyFlag==="--stdin"?"stdin":"file",value:a.value,emptyFlag:a.emptyFlag}}async function xw(e,t,n){let r=Ht(),o=await k0(t,r),i=o.mode==="add"||o.mode==="edit",a=o.value??"";return fr(e,t,n,{input:{...o,rawValue:t.add??a,value:i?ur(a,{stripPlainTextPrefix:!0}):a},collectionKey:"comments",op:"comment_add",editOp:"comment_edit",deleteOp:"comment_delete",parseText:s=>s,createEntry:s=>s,bypassOwnershipConflict:!!(o.mode==="add"&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm comments --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(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]="544840da-22f5-5734-81ec-e12c5612545c")}catch{}})();var S0=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function $w(e){let t=e?.trim();if(!t||t==="__proto__"||t.length>128)throw new Error("A legacy author must contain 1-128 characters.");return t}function E0(e){let t=e?.trim().toLowerCase();if(!t||!S0.test(t))throw new Error("A canonical harness must be a lowercase dash-separated namespace.");return t}function A0(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function T0(e,t){let n=new Set;for(let r of(e??[]).slice(0,1e4)){let o=r.trim().slice(0,128);o.length===0||o.startsWith("harness:")||Object.hasOwn(t,o)||n.add(o)}return n.size}function C0(e,t){let n=$w(t.legacy_author),r=E0(t.canonical_harness);if(n===r||n===`harness:${r}`||n.startsWith("harness:"))throw new Error(`The legacy author "${n}" is already canonical and must not be aliased.`);return e[n]===r?!1:(e[n]=r,!0)}function I0(e,t){if(t.operation==="add")return C0(e,t);if(t.operation==="remove"){let r=$w(t.legacy_author);return Object.hasOwn(e,r)?(delete e[r],!0):!1}if(t.operation==="clear"){let r=Object.keys(e).length>0;for(let o of Object.keys(e))delete e[o];return r}let n=t.operation;throw new Error(`Unsupported vocabulary operation: ${String(n)}`)}function od(e){return{version:e?.version??1,alias_count:Object.keys(e?.aliases??{}).length}}function Pw(e,t){let n=e?.version??1,r={...e?.aliases},o=I0(r,t),i={version:o?n+1:n,aliases:A0(r)};return{vocabulary:i,preview:{operation:t.operation,changed:o,version_before:n,version_after:i.version,alias_count:Object.keys(i.aliases).length,residual_author_count:T0(t.observed_authors,i.aliases)}}}(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]="19ca7be2-e710-50cc-8436-8ab1920f1bd6")}catch{}})();var Lw=["project","global"],Zt={definition_of_done:["definition-of-done","definition_of_done","workflow.definition_of_done"],item_format:["item-format","item_format"],history_missing_stream_policy:["history-missing-stream-policy","history_missing_stream_policy","history.missing_stream"],sprint_release_format_policy:["sprint-release-format-policy","sprint_release_format_policy","validation.sprint_release_format"],parent_reference_policy:["parent-reference-policy","parent_reference_policy","validation.parent_reference"],metadata_validation_profile:["metadata-validation-profile","metadata_validation_profile","validation.metadata_profile"],metadata_required_fields:["metadata-required-fields","metadata_required_fields","validation.metadata_required_fields"],lifecycle_stale_blocker_reason_patterns:["lifecycle-stale-blocker-reason-patterns","lifecycle_stale_blocker_reason_patterns","validation.lifecycle_stale_blocker_reason_patterns"],lifecycle_closure_like_blocked_reason_patterns:["lifecycle-closure-like-blocked-reason-patterns","lifecycle_closure_like_blocked_reason_patterns","validation.lifecycle_closure_like_blocked_reason_patterns"],lifecycle_closure_like_resolution_patterns:["lifecycle-closure-like-resolution-patterns","lifecycle_closure_like_resolution_patterns","validation.lifecycle_closure_like_resolution_patterns"],lifecycle_closure_like_actual_result_patterns:["lifecycle-closure-like-actual-result-patterns","lifecycle_closure_like_actual_result_patterns","validation.lifecycle_closure_like_actual_result_patterns"],governance_preset:["governance-preset","governance_preset","governance.preset"],governance_ownership_enforcement:["governance-ownership-enforcement","governance_ownership_enforcement","governance.ownership_enforcement"],governance_create_mode_default:["governance-create-mode-default","governance_create_mode_default","governance.create_mode_default"],governance_close_validation_default:["governance-close-validation-default","governance_close_validation_default","governance.close_validation_default"],governance_require_close_reason:["governance-require-close-reason","governance_require_close_reason","governance.require_close_reason"],governance_create_default_type:["governance-create-default-type","governance_create_default_type","governance.create_default_type"],governance_workflow_enforcement:["governance-workflow-enforcement","governance_workflow_enforcement","governance.workflow_enforcement"],governance_start_blocker_enforcement:["governance-start-blocker-enforcement","governance_start_blocker_enforcement","governance.start_blocker_enforcement"],governance_parent_reference_policy:["governance-parent-reference-policy","governance_parent_reference_policy","governance.parent_reference"],governance_metadata_validation_profile:["governance-metadata-validation-profile","governance_metadata_validation_profile","governance.metadata_profile"],governance_force_required_for_stale_lock:["governance-force-required-for-stale-lock","governance_force_required_for_stale_lock","governance.force_required_for_stale_lock"],test_result_tracking:["test-result-tracking","test_result_tracking","testing.record_results_to_items"],untrusted_linked_test_execution:["untrusted-linked-test-execution","untrusted_linked_test_execution","testing.allow_untrusted_linked_tests"],telemetry_tracking:["telemetry-tracking","telemetry_tracking","telemetry.enabled"],agent_identity_vocabulary:["agent-identity-vocabulary","agent_identity_vocabulary","agent_identity.identity_vocabulary"],context:["context"]},Nw=Object.fromEntries(Object.keys(Zt).flatMap(e=>Zt[e].map(t=>[t,e]))),R0={definition_of_done:"Definition of Done criteria list.",item_format:"Default item file format.",history_missing_stream_policy:"Missing history stream handling policy.",sprint_release_format_policy:"Sprint/release format validation policy.",parent_reference_policy:"Parent reference validation policy.",metadata_validation_profile:"Validate metadata profile policy (core|strict|custom).",metadata_required_fields:"Validate custom metadata required-fields list.",lifecycle_stale_blocker_reason_patterns:"Validate lifecycle stale-blocker reason substring patterns (criteria list).",lifecycle_closure_like_blocked_reason_patterns:"Validate lifecycle closure-like blocked_reason substring patterns (criteria list).",lifecycle_closure_like_resolution_patterns:"Validate lifecycle closure-like resolution substring patterns (criteria list).",lifecycle_closure_like_actual_result_patterns:"Validate lifecycle closure-like actual_result substring patterns (criteria list).",governance_preset:"Governance preset policy (minimal|default|strict|custom).",governance_ownership_enforcement:"Governance ownership enforcement policy (none|warn|strict).",governance_create_mode_default:"Governance default create mode (progressive|strict).",governance_close_validation_default:"Governance default close validation mode (off|warn|strict).",governance_require_close_reason:"Governance close-reason requirement policy (enabled|disabled).",governance_create_default_type:"Governance default item type for `pm create` when --type is omitted.",governance_workflow_enforcement:"Governance per-type transition enforcement mode (off|warn|strict).",governance_start_blocker_enforcement:"Governance admission for starting an item whose declared blocker is still open (off|warn|strict; strict by default).",governance_parent_reference_policy:"Governance parent reference policy (warn|strict_error).",governance_metadata_validation_profile:"Governance metadata validation profile (core|strict|custom).",governance_force_required_for_stale_lock:"Governance stale-lock force policy (enabled|disabled).",test_result_tracking:"Item-level linked test result persistence policy.",untrusted_linked_test_execution:"Permit an explicit per-run override for commands not trusted by this clone.",telemetry_tracking:"Telemetry usage reporting policy.",agent_identity_vocabulary:"Versioned exact legacy-author interpretation vocabulary (summary only).",context:"Context command settings (depth, section toggles, limits)."},O0=["lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns"],x0=new Set(["metadata_required_fields",...O0]),$0=new Set(["test_result_tracking","untrusted_linked_test_execution","telemetry_tracking"]),P0=new Set(["governance_require_close_reason","governance_force_required_for_stale_lock"]),L0=new Set(["governance_ownership_enforcement","governance_create_mode_default","governance_close_validation_default"]),N0=new Set(["governance_parent_reference_policy","governance_metadata_validation_profile","governance_workflow_enforcement","governance_start_blocker_enforcement"]),F0=new Set(["governance_preset","governance_create_default_type"]),Gw=e=>x0.has(e),M0=e=>L0.has(e),D0=e=>N0.has(e),U0=e=>F0.has(e);function id(e){return e==="definition_of_done"||Gw(e)}function j0(e){if(Lw.includes(e))return e;throw new d(`Invalid config scope "${e}". Allowed: ${Lw.join(", ")}`,m.USAGE)}function G0(e){if(e==="get"||e==="set"||e==="list"||e==="export")return e;throw Le({command_path:"config",token:e.trim()||"<empty>",allowed:["export","get","list","set"],token_kind:"action"})}function q0(e,t="global",n){let r=Object.hasOwn(Nw,e)?Nw[e]:void 0;if(r)return r;let o=[...Object.values(Zt),...Li.map(p=>[p.key.replaceAll("_","-"),p.path])],i=e.toLowerCase().replaceAll(/[_.]/gu,"-"),a=o.map(p=>({key:p[0],distance:Math.min(...p.map(u=>up(i,u.replaceAll(/[_.]/gu,"-"),3)??1/0))})).filter(({distance:p})=>Number.isFinite(p)).sort((p,u)=>p.distance-u.distance||p.key.localeCompare(u.key)).slice(0,3).map(({key:p})=>p),s=n?Pe(n):[],c=L([...s,"config",t,"list","--json"]),l=a.length>0?` Did you mean ${a.map(p=>p==="telemetry-tracking"&&t==="project"?`${p} (global only)`:p).join(", ")}?`:"";throw new d(`Invalid config key "${e}".${l} Inspect keys and aliases with ${c}.`,m.USAGE,{code:"config_key_unknown",changed:!1,required:`Use a key or settings path from ${c}.`,examples:[c],recovery:{allowed_values:[...new Set([...md(t).flatMap(p=>Zt[p]),...Li.flatMap(p=>[p.key,p.key.replaceAll("_","-"),p.path])])],candidate_commands:a.map(p=>L([...s,"config",p==="telemetry-tracking"?"global":t,"get",p,"--json"])),next_best_command:c}})}function K0(e,t){let n=[...new Set((e??[]).map(r=>r.trim()).filter(r=>r.length>0))].sort((r,o)=>r.localeCompare(o));if(t){if(n.length>0)throw new d("Config set definition-of-done cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new d("Config set definition-of-done requires at least one non-empty --criterion value (or --clear-criteria to clear)",m.USAGE);return n}function z0(e){let t=e?.trim().toLowerCase();if(t==="toon")return"toon";throw t==="json_markdown"?new d("Config set item-format no longer accepts json_markdown. Markdown item files are legacy read/migration input only.",m.USAGE):new d("Config set item-format requires --format toon",m.USAGE)}function qw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="auto_create"||t==="strict_error")return t;throw new d("Config set history-missing-stream-policy requires --policy with one of: auto_create, strict_error",m.USAGE)}function H0(e){return cd(e,"test-result-tracking")}function cd(e,t){let n=e?.trim().toLowerCase().replaceAll("-","_");if(n==="enabled"||n==="disabled")return n;throw new d(`Config set ${t} requires --policy with one of: enabled, disabled`,m.USAGE)}function Kw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set telemetry-tracking requires --policy with one of: enabled, disabled",m.USAGE)}function ld(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="core"||t==="strict"||t==="custom")return t;throw new d("Config set metadata-validation-profile requires --policy with one of: core, strict, custom",m.USAGE)}function zw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="minimal"||t==="default"||t==="strict"||t==="custom")return t;throw new d("Config set governance-preset requires --policy with one of: minimal, default, strict, custom",m.USAGE)}function Hw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="none"||t==="warn"||t==="strict")return t;throw new d("Config set governance-ownership-enforcement requires --policy with one of: none, warn, strict",m.USAGE)}function Bw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="progressive"||t==="strict")return t;throw new d("Config set governance-create-mode-default requires --policy with one of: progressive, strict",m.USAGE)}function Ww(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="off"||t==="warn"||t==="strict")return t;if(t==="none"||t==="disabled")return"off";throw new d("Config set governance-close-validation-default requires --policy with one of: off, warn, strict",m.USAGE)}function ad(e,t="governance-workflow-enforcement"){let n=typeof e=="string"?e.trim().toLowerCase().replaceAll("-","_"):void 0;if(n==="off"||n==="warn"||n==="strict")return n;if(n==="none"||n==="disabled")return"off";throw new d(`Config set ${t} requires one of: off, warn, strict`,m.USAGE)}function Vw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-force-required-for-stale-lock requires --policy with one of: enabled, disabled",m.USAGE)}function Yw(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="enabled"||t==="disabled")return t;throw new d("Config set governance-require-close-reason requires --policy with one of: enabled, disabled",m.USAGE)}var B0={test_result_tracking:"test-result-tracking",untrusted_linked_test_execution:"untrusted-linked-test-execution"},W0={governance_workflow_enforcement:"governance-workflow-enforcement",governance_start_blocker_enforcement:"governance-start-blocker-enforcement"};function Fw(e,t){let n=B0[e];if(n)return cd(t,n);let r=W0[e];if(r)return ad(t,r);switch(e){case"history_missing_stream_policy":return qw(t);case"sprint_release_format_policy":return ul(t);case"parent_reference_policy":case"governance_parent_reference_policy":return ia(t);case"metadata_validation_profile":case"governance_metadata_validation_profile":return ld(t);case"governance_preset":return zw(t);case"governance_ownership_enforcement":return Hw(t);case"governance_create_mode_default":return Bw(t);case"governance_close_validation_default":return Ww(t);case"governance_require_close_reason":return Yw(t);case"governance_force_required_for_stale_lock":return Vw(t);case"telemetry_tracking":return Kw(t);default:return t.trim().toLowerCase().replaceAll("-","_")}}var Mw={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"},V0=["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"];function Y0(e,t){let n=[...new Set((e??[]).map(i=>i.trim()).filter(i=>i.length>0))];if(t){if(n.length>0)throw new d("Config set metadata-required-fields cannot combine --clear-criteria with --criterion values",m.USAGE);return[]}if(n.length===0)throw new d("Config set metadata-required-fields requires at least one --criterion value (or --clear-criteria to clear)",m.USAGE);let r=n.map(i=>i.toLowerCase().replaceAll("-","_")),o=r.filter(i=>Mw[i]===void 0);if(o.length>0)throw new d(`Config set metadata-required-fields received unsupported values: ${o.join(", ")}. Supported values: ${V0.join(", ")}`,m.USAGE);return[...new Set(r.map(i=>Mw[i]))].sort((i,a)=>i.localeCompare(a))}function J0(e,t,n){let r=[...new Set((t??[]).map(o=>o.trim().toLowerCase()).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));if(n){if(r.length>0)throw new d(`Config set ${Zt[e][0]} cannot combine --clear-criteria with --criterion values`,m.USAGE);return[]}if(r.length===0)throw new d(`Config set ${Zt[e][0]} requires at least one --criterion value (or --clear-criteria to clear)`,m.USAGE);return r}function X0(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Q0(e,t,n,r){if(e==="list"||e==="export"){if(typeof t=="string"&&t.trim().length>0)throw new d(`Config action "${e}" does not accept <key>`,m.USAGE);return}if(typeof t!="string"||t.trim().length===0)throw new d(`Config action "${e}" requires <key>`,m.USAGE);return q0(t,n,r)}function Jw(e){if(!e)throw new d("Config action requires <key>",m.USAGE)}var Z0={definition_of_done:e=>[...e.workflow.definition_of_done],item_format:e=>e.item_format,history_missing_stream_policy:e=>e.history.missing_stream,sprint_release_format_policy:e=>e.validation.sprint_release_format,parent_reference_policy:e=>e.validation.parent_reference,metadata_validation_profile:e=>e.validation.metadata_profile,metadata_required_fields:e=>[...e.validation.metadata_required_fields],lifecycle_stale_blocker_reason_patterns:e=>[...e.validation.lifecycle_stale_blocker_reason_patterns],lifecycle_closure_like_blocked_reason_patterns:e=>[...e.validation.lifecycle_closure_like_blocked_reason_patterns],lifecycle_closure_like_resolution_patterns:e=>[...e.validation.lifecycle_closure_like_resolution_patterns],lifecycle_closure_like_actual_result_patterns:e=>[...e.validation.lifecycle_closure_like_actual_result_patterns],governance_preset:e=>e.governance.preset,governance_ownership_enforcement:e=>e.governance.ownership_enforcement,governance_create_mode_default:e=>e.governance.create_mode_default,governance_close_validation_default:e=>e.governance.close_validation_default,governance_require_close_reason:e=>e.governance.require_close_reason?"enabled":"disabled",governance_create_default_type:e=>e.governance.create_default_type??"",governance_workflow_enforcement:e=>e.governance.workflow_enforcement??"off",governance_start_blocker_enforcement:e=>e.governance.start_blocker_enforcement??"strict",governance_parent_reference_policy:e=>e.governance.parent_reference,governance_metadata_validation_profile:e=>e.governance.metadata_profile,governance_force_required_for_stale_lock:e=>e.governance.force_required_for_stale_lock?"enabled":"disabled",test_result_tracking:e=>e.testing.record_results_to_items?"enabled":"disabled",untrusted_linked_test_execution:e=>e.testing.allow_untrusted_linked_tests?"enabled":"disabled",telemetry_tracking:e=>e.telemetry.enabled?"enabled":"disabled",agent_identity_vocabulary:e=>od(e.agent_identity?.identity_vocabulary),context:e=>({default_depth:e.context.default_depth,activity_limit:e.context.activity_limit,stale_threshold_days:e.context.stale_threshold_days,next_ranking_policy:e.context.next_ranking_policy,sections:{...e.context.sections}})};function dd(e,t){return Z0[t](e)}function Me(e,t){return t.length===0?e:{...e,warnings:t}}async function eI(e,t){let n=process.cwd(),r=e==="project"?T(n,t.path):$e(n),o=oe(r);return e==="project"&&await O(r),{pmRoot:r,settingsPath:o}}function tI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="true"||t==="enabled"||t==="on"||t==="1")return!0;if(t==="false"||t==="disabled"||t==="off"||t==="0")return!1;throw new d(`Context section toggle must be true|false|enabled|disabled, got "${e}"`,m.USAGE)}function Dw(e,t){let n=zr(t==="--activity-limit"?"context_activity_limit":"context_stale_threshold_days"),r=Pc(n,e);if(r.ok)return r.parsed.value;throw new d(`Context ${t}: ${r.error.message}`,m.USAGE)}async function nI(e,t,n,r,o){let i=!1,a=e.context,s=[];if(t.defaultDepth!==void 0){let l=t.defaultDepth.trim().toLowerCase();if(!vc.includes(l))throw new d(`Context --default-depth must be one of ${vc.join("|")}`,m.USAGE);s.push("context.default_depth"),a.default_depth!==l&&(a.default_depth=l,i=!0)}if(t.activityLimit!==void 0){let l=Dw(t.activityLimit,"--activity-limit");s.push("context.activity_limit"),a.activity_limit!==l&&(a.activity_limit=l,i=!0)}if(t.staleThresholdDays!==void 0){let l=Dw(t.staleThresholdDays,"--stale-threshold-days");s.push("context.stale_threshold_days"),a.stale_threshold_days!==l&&(a.stale_threshold_days=l,i=!0)}let c=[["hierarchy",t.sectionHierarchy],["activity",t.sectionActivity],["progress",t.sectionProgress],["blockers",t.sectionBlockers],["files",t.sectionFiles],["workload",t.sectionWorkload],["staleness",t.sectionStaleness],["tests",t.sectionTests]];for(let[l,p]of c){let u=tI(p);if(u!==void 0){let f=l;s.push(`context.sections.${l}`),a.sections[f]!==u&&(a.sections[f]=u,i=!0)}}return(i||$t(e))&&(await Re(n.pmRoot,e,"config:set:context",{assignedPaths:s}),i=!0),Me({scope:r,key:"context",context_settings:{default_depth:a.default_depth,activity_limit:a.activity_limit,stale_threshold_days:a.stale_threshold_days,next_ranking_policy:a.next_ranking_policy,sections:{...a.sections}},settings_path:n.settingsPath,changed:i},o)}function rI(e,t,n){if(n.value!==void 0&&n.value!==t)throw new d(`Config set ${e} received both positional value "${t}" and --value "${n.value}". Pass only one.`,m.USAGE);return{...n,value:t}}function oI(e,t,n,r,o,i){if(o===void 0)return i;if(e!=="set")throw new d(`Config action "${e}" does not accept a positional value. Only "set" takes <value>.`,m.USAGE);if(typeof t!="string"||t.trim().length===0)throw new d('Config action "set" requires <key> before a positional <value>.',m.USAGE);if(r)return rI(t,o,i);Jw(n);let a=r_(n,o);if(!a.routable)throw new d(a.reason,m.USAGE);if(a.flag==="criterion"){if(i.criterion!==void 0&&i.criterion.length>0)throw new d(`Config set ${t} received both positional value "${o}" and --criterion. Pass criteria via --criterion only when supplying more than one value.`,m.USAGE);return{...i,criterion:a.values}}if(a.flag==="format")return{...i,format:a.value};if(i.policy!==void 0&&Fw(n,i.policy)!==Fw(n,a.value))throw new d(`Config set ${t} received both positional value "${o}" and --policy "${i.policy}". Pass only one.`,m.USAGE);return{...i,policy:a.value}}function Xw(e,t){let n=`pm config global ${e} telemetry-tracking${t}`;throw new d(`Config ${e} telemetry-tracking applies to this CLI install, not one project. Run: ${n}`,m.USAGE,{code:"invalid_argument_value",reason:"telemetry_consent_is_global",field:"scope",changed:!1,required:`Run: ${n}`,examples:[n]})}function md(e){return Object.keys(Zt).filter(t=>e==="global"||t!=="telemetry_tracking")}function iI(e){let t=md(e.scope).map(r=>({key:r,aliases:Zt[r],value_kind:r==="context"||r==="agent_identity_vocabulary"?"object":id(r)?"string_array":"enum",set_flags:r==="context"?["--default-depth","--activity-limit","--stale-threshold-days","--section-<name>"]:r==="agent_identity_vocabulary"?["--policy","--value","--criterion"]:id(r)?["--criterion","--clear-criteria"]:r==="item_format"?["--format"]:["--policy"],summary:R0[r],value:dd(e.settings,r)})),n=Li.map(r=>({key:r.key,canonical_key:r.key.replaceAll("_","-"),path:r.path,kind:r.kind,value:Lc(e.settings,r),summary:r.summary,...r.choices?{choices:[...r.choices]}:{},...r.min===void 0?{}:{min:r.min},...r.max===void 0?{}:{max:r.max}}));return Me({scope:e.scope,keys:t,nested_settings:n,count:t.length,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function aI(e){let t=Object.fromEntries(md(e.scope).map(n=>[n,dd(e.settings,n)]));return Me({scope:e.scope,values:t,settings_path:e.target.settingsPath,changed:!1},e.warnings)}function sI(e,t){let n=dd(e.settings,t),r={scope:e.scope,key:t,settings_path:e.target.settingsPath,changed:!1};return t==="item_format"?Me({...r,format:e.settings.item_format,has_explicit_item_format:e.metadata.has_explicit_item_format},e.warnings):t==="context"?Me({...r,context_settings:n},e.warnings):t==="agent_identity_vocabulary"?Me({...r,identity_vocabulary:n},e.warnings):Array.isArray(n)?Me({...r,criteria:n},e.warnings):Me({...r,policy:n},e.warnings)}async function cI(e,t,n,r){if(t==="get"){let s=Lc(e.settings,n);return Me({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:s},settings_path:e.target.settingsPath,changed:!1},e.warnings)}let o=r.value;if(typeof o!="string")throw new d(`Config set ${n.key} requires a value. Pass it positionally (\`pm config ${e.scope} set ${n.key} <value>\`) or via --value.`,m.USAGE);let i=Pc(n,o);if(!i.ok)throw new d(i.error.message,m.USAGE);let a=Ni(e.settings,n,i.parsed.value)||$t(e.settings);return a&&await Re(e.target.pmRoot,e.settings,`config:set:${n.path}`,{assignedPaths:[n.path]}),Me({scope:e.scope,key:n.key,nested_setting:{key:n.key,path:n.path,kind:n.kind,value:i.parsed.value},settings_path:e.target.settingsPath,changed:a},e.warnings)}async function Z(e,t,n,r=[]){(t||$t(e.settings))&&(await Re(e.target.pmRoot,e.settings,n,{assignedPaths:r}),$t(e.settings)&&(e.fallbackRepairWritten=!0))}function Uw(e,t,n){return e!==n||t!==n}function me(e,t,n,r){return Me({scope:e.scope,key:t,policy:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}function sd(e,t,n,r){return Me({scope:e.scope,key:t,criteria:n,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function jw(e,t,n){let r=$(t,R()),o=await X_(e,n,"config:set:item_format:migrate",r.type_to_folder,t.schema);return{target_format:o.target_format,scanned:o.scanned,migrated:o.migrated,removed:o.removed,warnings:o.warnings}}async function lI(e,t){let n=z0(t.format),r=e.settings.item_format!==n||!e.metadata.has_explicit_item_format,o;if(r){e.settings.item_format=n;let i={assignedPaths:["item_format"]};$t(e.settings)?(await Re(e.target.pmRoot,e.settings,"config:set:item_format",i),e.fallbackRepairWritten=!0,o=await jw(e.target.pmRoot,await E(e.target.pmRoot),n)):(o=await jw(e.target.pmRoot,e.settings,n),await Re(e.target.pmRoot,e.settings,"config:set:item_format",i))}return Me({scope:e.scope,key:"item_format",format:e.settings.item_format,has_explicit_item_format:!0,migration:o,settings_path:e.target.settingsPath,changed:r},e.warnings)}async function dI(e,t,n){if(t==="history_missing_stream_policy"){let i=qw(n.policy),a=e.settings.history.missing_stream!==i;return e.settings.history.missing_stream=i,await Z(e,a,"config:set:history_missing_stream_policy",["history.missing_stream"]),me(e,t,e.settings.history.missing_stream,a)}if(t==="sprint_release_format_policy"){let i=ul(n.policy),a=e.settings.validation.sprint_release_format!==i;return e.settings.validation.sprint_release_format=i,await Z(e,a,"config:set:sprint_release_format_policy",["validation.sprint_release_format"]),me(e,t,e.settings.validation.sprint_release_format,a)}if(t==="parent_reference_policy"){let i=ia(n.policy),a=e.settings.validation.parent_reference!==i||e.settings.governance.preset!=="custom"||e.settings.governance.parent_reference!==i;return e.settings.validation.parent_reference=i,e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,await Z(e,a,"config:set:parent_reference_policy",["validation.parent_reference","governance.preset","governance.parent_reference"]),me(e,t,e.settings.validation.parent_reference,a)}let r=ld(n.policy),o=e.settings.validation.metadata_profile!==r||e.settings.governance.preset!=="custom"||e.settings.governance.metadata_profile!==r;return e.settings.validation.metadata_profile=r,e.settings.governance.preset="custom",e.settings.governance.metadata_profile=r,await Z(e,o,"config:set:metadata_validation_profile",["validation.metadata_profile","governance.preset","governance.metadata_profile"]),me(e,t,e.settings.validation.metadata_profile,o)}async function mI(e,t,n){if(t==="metadata_required_fields"){let a=Y0(n.criterion,n.clearCriteria),s=a.length!==e.settings.validation.metadata_required_fields.length||a.some((c,l)=>c!==e.settings.validation.metadata_required_fields[l]);return e.settings.validation.metadata_required_fields=a,await Z(e,s,"config:set:metadata_required_fields",["validation.metadata_required_fields"]),sd(e,t,[...e.settings.validation.metadata_required_fields],s)}let r={lifecycle_stale_blocker_reason_patterns:e.settings.validation.lifecycle_stale_blocker_reason_patterns,lifecycle_closure_like_blocked_reason_patterns:e.settings.validation.lifecycle_closure_like_blocked_reason_patterns,lifecycle_closure_like_resolution_patterns:e.settings.validation.lifecycle_closure_like_resolution_patterns,lifecycle_closure_like_actual_result_patterns:e.settings.validation.lifecycle_closure_like_actual_result_patterns}[t],o=J0(t,n.criterion,n.clearCriteria),i=o.length!==r.length||o.some((a,s)=>a!==r[s]);return r.splice(0,r.length,...o),await Z(e,i,`config:set:${t}`,[`validation.${t}`]),sd(e,t,[...r],i)}async function pI(e,t,n){if(t==="governance_preset"){let c=zw(n.policy),l=e.settings.governance.preset!==c;return e.settings.governance.preset=c,await Z(e,l,"config:set:governance_preset",["governance.preset"]),me(e,t,e.settings.governance.preset,l)}let r=typeof n.policy=="string",o=r?n.policy.trim():"";if(r&&o.length===0){let c=e.settings.governance.create_default_type!==void 0;return delete e.settings.governance.create_default_type,await Z(e,c,"config:set:governance_create_default_type",["governance.create_default_type"]),me(e,t,e.settings.governance.create_default_type??"",c)}if(o.length===0)throw new d('Config set governance-create-default-type requires an item type value (or an empty value "" to clear it)',m.USAGE);let i=$(e.settings,R()),a=Te(o,i);if(!a)throw new d(qt(o,i.types,Kt(e.target.pmRoot,e.settings.schema)),m.USAGE);let s=e.settings.governance.create_default_type!==a;return e.settings.governance.create_default_type=a,await Z(e,s,"config:set:governance_create_default_type",["governance.create_default_type"]),me(e,t,e.settings.governance.create_default_type,s)}async function uI(e,t,n){if(t==="governance_ownership_enforcement"){let i=Hw(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.ownership_enforcement!==i;return e.settings.governance.preset="custom",e.settings.governance.ownership_enforcement=i,await Z(e,a,"config:set:governance_ownership_enforcement",["governance.preset","governance.ownership_enforcement"]),me(e,t,e.settings.governance.ownership_enforcement,a)}if(t==="governance_create_mode_default"){let i=Bw(n.policy),a=e.settings.governance.preset!=="custom"||e.settings.governance.create_mode_default!==i;return e.settings.governance.preset="custom",e.settings.governance.create_mode_default=i,await Z(e,a,"config:set:governance_create_mode_default",["governance.preset","governance.create_mode_default"]),me(e,t,e.settings.governance.create_mode_default,a)}let r=Ww(n.policy),o=e.settings.governance.preset!=="custom"||e.settings.governance.close_validation_default!==r;return e.settings.governance.preset="custom",e.settings.governance.close_validation_default=r,await Z(e,o,"config:set:governance_close_validation_default",["governance.preset","governance.close_validation_default"]),me(e,t,e.settings.governance.close_validation_default,o)}async function fI(e,t,n){if(t==="governance_parent_reference_policy"){let i=ia(n.policy),a=e.settings.governance.preset!=="custom"||Uw(e.settings.governance.parent_reference,e.settings.validation.parent_reference,i);return e.settings.governance.preset="custom",e.settings.governance.parent_reference=i,e.settings.validation.parent_reference=i,await Z(e,a,"config:set:governance_parent_reference_policy",["governance.preset","governance.parent_reference","validation.parent_reference"]),me(e,t,e.settings.governance.parent_reference,a)}if(t==="governance_metadata_validation_profile"){let i=ld(n.policy),a=e.settings.governance.preset!=="custom"||Uw(e.settings.governance.metadata_profile,e.settings.validation.metadata_profile,i);return e.settings.governance.preset="custom",e.settings.governance.metadata_profile=i,e.settings.validation.metadata_profile=i,await Z(e,a,"config:set:governance_metadata_validation_profile",["governance.preset","governance.metadata_profile","validation.metadata_profile"]),me(e,t,e.settings.governance.metadata_profile,a)}if(t==="governance_start_blocker_enforcement"){let i=ad(n.policy,"governance-start-blocker-enforcement"),a=(e.settings.governance.start_blocker_enforcement??"strict")!==i;return e.settings.governance.start_blocker_enforcement=i,await Z(e,a,"config:set:governance_start_blocker_enforcement",["governance.start_blocker_enforcement"]),me(e,t,i,a)}let r=ad(n.policy),o=(e.settings.governance.workflow_enforcement??"off")!==r;return e.settings.governance.workflow_enforcement=r,await Z(e,o,"config:set:governance_workflow_enforcement",["governance.workflow_enforcement"]),me(e,t,e.settings.governance.workflow_enforcement,o)}async function _I(e,t,n){if(t==="governance_require_close_reason"){let i=Yw(n.policy)==="enabled",a=e.settings.governance.require_close_reason!==i;return e.settings.governance.require_close_reason=i,await Z(e,a,"config:set:governance_require_close_reason",["governance.require_close_reason"]),me(e,t,e.settings.governance.require_close_reason?"enabled":"disabled",a)}let r=Vw(n.policy)==="enabled",o=e.settings.governance.preset!=="custom"||e.settings.governance.force_required_for_stale_lock!==r;return e.settings.governance.preset="custom",e.settings.governance.force_required_for_stale_lock=r,await Z(e,o,"config:set:governance_force_required_for_stale_lock",["governance.preset","governance.force_required_for_stale_lock"]),me(e,t,e.settings.governance.force_required_for_stale_lock?"enabled":"disabled",o)}async function hI(e,t,n){if(t==="test_result_tracking"){let a=H0(n.policy)==="enabled",s=e.settings.testing.record_results_to_items!==a;return e.settings.testing.record_results_to_items=a,await Z(e,s,"config:set:test_result_tracking",["testing.record_results_to_items"]),me(e,t,e.settings.testing.record_results_to_items?"enabled":"disabled",s)}if(t==="untrusted_linked_test_execution"){let a=cd(n.policy,"untrusted-linked-test-execution")==="enabled",s=e.settings.testing.allow_untrusted_linked_tests!==a;return e.settings.testing.allow_untrusted_linked_tests=a,await Z(e,s,"config:set:untrusted_linked_test_execution",["testing.allow_untrusted_linked_tests"]),me(e,t,e.settings.testing.allow_untrusted_linked_tests?"enabled":"disabled",s)}let r=Kw(n.policy);e.scope==="project"&&Xw("set",` --policy ${r}`);let o=r==="enabled",i=e.settings.telemetry.enabled!==o||!e.settings.telemetry.first_run_prompt_completed;return e.settings.telemetry.enabled=o,e.settings.telemetry.first_run_prompt_completed=!0,await Z(e,i,"config:set:telemetry_tracking",["telemetry.enabled","telemetry.first_run_prompt_completed"]),me(e,t,e.settings.telemetry.enabled?"enabled":"disabled",i)}async function gI(e,t,n){let r=K0(n.criterion,n.clearCriteria),o=r.length!==e.settings.workflow.definition_of_done.length||r.some((i,a)=>i!==e.settings.workflow.definition_of_done[a]);return e.settings.workflow.definition_of_done=r,await Z(e,o,"config:set:definition_of_done",["workflow.definition_of_done"]),sd(e,t,[...e.settings.workflow.definition_of_done],o)}function yI(e){let t=e?.trim().toLowerCase().replaceAll("_","-"),n=t?.startsWith("preview-")===!0,r=n?t.slice(8):t;if(r==="add"||r==="remove"||r==="clear")return{operation:r,dryRun:n};throw new d("Config set agent-identity-vocabulary requires --policy add|remove|clear|preview-add|preview-remove|preview-clear",m.USAGE)}function wI(e,t){if(e==="add"){let n=t?.lastIndexOf("=")??-1;if(n<=0||n===t.length-1)throw new d('Config set agent-identity-vocabulary --policy add requires --value "<legacy-author>=<canonical-harness>"',m.USAGE);return{legacy_author:t.slice(0,n),canonical_harness:t.slice(n+1)}}if(e==="remove"){if(t===void 0)throw new d("Config set agent-identity-vocabulary --policy remove requires --value <legacy-author>",m.USAGE);return{legacy_author:t}}if(t!==void 0)throw new d("Config set agent-identity-vocabulary --policy clear does not accept --value",m.USAGE);return{}}async function vI(e,t){let{operation:n,dryRun:r}=yI(t.policy),o=wI(n,t.value),i;try{i=Pw(e.settings.agent_identity?.identity_vocabulary,{operation:n,...o,observed_authors:t.criterion})}catch(a){throw new d(a.message,m.USAGE)}return i.preview.changed&&!r&&(e.settings.agent_identity={...e.settings.agent_identity,identity_vocabulary:i.vocabulary},await Z(e,!0,`config:set:agent_identity.identity_vocabulary:${n}:v${i.preview.version_after}`,["agent_identity"])),Me({scope:e.scope,key:"agent_identity_vocabulary",identity_vocabulary:od(r?e.settings.agent_identity?.identity_vocabulary:i.vocabulary),vocabulary_mutation:i.preview,settings_path:e.target.settingsPath,changed:i.preview.changed&&!r},e.warnings)}async function bI(e,t,n){let r=await kI(e,t,n);return e.fallbackRepairWritten===!0?{...r,changed:!0}:r}async function kI(e,t,n){if(n.clearCriteria===!0&&!id(t))throw new d("--clear-criteria is only supported with config set criteria-list keys",m.USAGE);return t==="item_format"?lI(e,n):t==="context"?nI(e.settings,n,e.target,e.scope,e.warnings):t==="agent_identity_vocabulary"?vI(e,n):t==="definition_of_done"?gI(e,t,n):Gw(t)?mI(e,t,n):$0.has(t)?hI(e,t,n):P0.has(t)?_I(e,t,n):M0(t)?uI(e,t,n):D0(t)?fI(e,t,n):U0(t)?pI(e,t,n):dI(e,t,n)}async function Qw(e,t,n,r,o,i){let a=j0(e),s=G0(t),c=s==="get"||s==="set"?zr(n):void 0,l=c?void 0:Q0(s,n,a,o),p=oI(s,n,l,c,i,r),u=await eI(a,o),{settings:f,metadata:h,warnings:_}=await P_(u.pmRoot),g={scope:a,target:u,settings:f,metadata:h,warnings:X0(_)};return c?cI(g,s,c,p):s==="list"?iI(g):s==="export"?aI(g):(Jw(l),s==="get"&&l==="telemetry_tracking"&&a==="project"&&Xw("get",""),s==="get"?sI(g,l):bI(g,l,p))}import ev from"node:fs/promises";import tv 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]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function SI(e,t,n){let r=new Set,o=[];for(let i of e){let a=i.trim();if(a.length===0||r.has(a))continue;r.add(a);let s=t.get(a);if(s===void 0){o.push({id:a,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(s.entries<=n){o.push({id:a,entries:s.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:a,entries:s.entries,selected:!0,skip_reason:null})}return o}function EI(e,t){let n=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),r=[];for(let o of n){if(t.scope==="closed"&&o.bucket!=="closed"){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){r.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}r.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return r}function Zw(e,t){if(t.ids!==void 0&&t.ids.length>0){let n=new Map(e.map(r=>[r.id,r]));return SI(t.ids,n,t.minEntries)}return EI(e,t)}(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]="8e3e7c46-1929-5ff4-84b0-d4c0605148c2")}catch{}})();function AI(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let n=e.trim();if(n.length===0)throw new d("history-compact --before requires a non-empty value.",m.USAGE);if(/^\d+$/.test(n)){let i=Number.parseInt(n,10),a=nr(t);if(!Number.isSafeInteger(i)||i<a+1||i>a+t.length+1)throw new d(`history-compact --before version must be between ${a+1} and ${a+t.length+1}.`,m.USAGE);let s=i-a-1;return{kind:"version",raw:n,compactCount:s,retainedCount:t.length-s}}let r=Date.parse(n);if(!Number.isFinite(r))throw new d(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,m.USAGE);let o=0;for(let[i,a]of t.entries()){let s=Date.parse(a.ts);if(!Number.isFinite(s))throw new d(`History for this item contains invalid timestamp at entry ${i+1}.`,m.GENERIC_FAILURE);if(s>=r)break;o+=1}return{kind:"timestamp",raw:n,compactCount:o,retainedCount:t.length-o}}function TI(e,t){let n=Jr(),r=Jr();for(let o=0;o<e.length;o+=1){let i=e[o];n=rr(n,i.patch,o+1,i.op),o+1===t&&(r=structuredClone(n))}return{checkpoint:r,finalReplay:n}}function CI(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let n=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:w_.some(r=>(n.item_hash_version===void 0||n.item_hash_version===r)&&ml(Zr(e.document),r,xt(n.hash_algorithm)).includes(n.after_hash))}}function II(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function RI(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function OI(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:n}=TI(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),o=nr(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],a=Ke({hashAlgorithm:xt(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:ht(Jr()),after:ht(t),message:RI(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:v_(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),s=[b_({...a,before_hash:ml(Jr(),i.item_hash_version??1,xt(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...r];return e.dryRun||s.push(Ke({nowIso:A(),author:e.author,op:"history_compact",before:ht(n),after:ht(n),message:II(e.options,e.boundary)})),{rewrittenEntries:s,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function pd(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await _o(n.path),a=await yn(r,e,o,i.type_to_folder);return Ia({pmRoot:r,subject:a,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:s=>xI(a,t,s)})}function xI(e,t,n){let r=e.historyPath,o=n.entries,i=n.verification;if(!i.ok)throw new d(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let a=AI(t.before,o),s=a.compactCount>0,c=!!t.dryRun,l=n.author,p=[];s||p.push("history_compact_noop_before_boundary");let u=CI(n.loadedItem,o);u.matchedChainBefore===!1&&p.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:h,auditEntryAdded:_}=OI({historyEntries:o,boundary:a,changed:s,dryRun:c,author:l,options:t}),g=nr(o,!0),y=a.retainedCount>0&&g!==null?g+a.compactCount+1:null;return{changed:s,rewrittenEntries:f,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:s,compact_boundary:{kind:a.kind,before:a.raw,entries_compacted:a.compactCount,entries_retained:a.retainedCount,first_retained_entry:y},history:{path:r,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:h,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...p,...v])].sort((k,C)=>k.localeCompare(C)),generated_at:A()})}}var $I=3;function PI(e){for(let n of["allOver","minEntries"]){let r=e[n];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new d(`history-compact ${n} must be a non-negative safe integer.`,m.USAGE)}let t=Zi(e.ids);if(e.ids!==void 0&&t==="")throw new d("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Qi(t)}}function nv(e,t){let n=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(n?1:0)+(r?1:0)==0)throw new d("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",m.USAGE);if(e!==void 0&&(n||r))throw new d("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",m.USAGE);if(n&&r)throw new d("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",m.USAGE)}function LI(e){let t=0;for(let n of e.split(/\r?\n/))n.trim().length>0&&(t+=1);return t}async function NI(e){let t=D(e.settings.schema),n=Sa(t),r=await ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(r.map(l=>[l.id,n.classify(l.status)])),i=tv.join(e.pmRoot,"history"),a=[],s=[];if(!await B(i))return{candidates:a,preselectionErrors:s};let c=(await ev.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,p)=>l.localeCompare(p));for(let l of c){let p=tv.join(i,l),u=l.slice(0,-6);try{let f=await ev.readFile(p,"utf8");await Jn({path:p,scope:"project"}),a.push({id:u,entries:LI(f),bucket:o.get(u)??null})}catch(f){s.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:a,preselectionErrors:s}}async function FI(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await pd(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await wt(t,e.pmRoot)}}}}async function rv(e,t){let n=PI(e),{pmRoot:r,settings:o,typeRegistry:i}=await _o(t.path),{candidates:a,preselectionErrors:s}=await NI({pmRoot:r,settings:o,typeToFolder:i.type_to_folder}),c=n.ids!==void 0&&n.ids.length>0?"ids":"scan",l=e.minEntries??$I,p=o.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&p.enabled,f=e.allOver??(u?p.max_entries:void 0),h=Zw(a,{ids:n.ids,scope:e.scope,minEntries:l,allOver:f}),_=!!e.dryRun,g=[...s],y={streams_considered:a.length+s.length,selected:0,items_compacted:0,items_skipped:0,items_errored:s.length};for(let w of h){let v=await FI({pmRoot:r,row:w,options:n,dryRun:_,global:t});if(g.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:_,mode:c,scope:e.scope??null,criteria:{min_entries:l,all_over:f??null,policy_threshold_applied:u},totals:y,results:g,generated_at:A()}}(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]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();function ov(e){let t=e.options.all===!0,n=e.id??b(e.options,"id");return Fg(n,t),t?Ra(e.options,e.global):Xt(n,e.options,e.global)}function iv(e){let t=e.options.ids,n=Zi(t);if(t!==void 0&&n==="")throw new d("history-compact ids requires at least one valid item ID.",m.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});let r=n===void 0?void 0:Qi(n),o=ze(e.options.allOver??e.options.all_over,"history-compact allOver"),i=ze(e.options.minEntries??e.options.min_entries,"history-compact minEntries"),a=b(e.options,"scope"),s=[];e.options.closed===!0&&s.push("closed"),(e.options.allStreams===!0||e.options.all_streams===!0)&&s.push("all-streams"),(a==="closed"||a==="all-streams")&&s.push(a);let c=[...new Set(s)];if(c.length>1)throw new d("history-compact: closed and all-streams scopes are mutually exclusive.",m.USAGE);let l=c[0];return nv(e.id,{ids:r,allOver:o,scope:l}),e.id!==void 0?pd(e.id,{before:b(e.options,"before"),dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global):rv({ids:r,scope:l,allOver:o,minEntries:i,dryRun:e.options.dryRun===!0||e.options.dry_run===!0,author:b(e.options,"author"),message:b(e.options,"message"),force:e.force},e.global)}import fd from"node:fs/promises";(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]="99336062-727a-5797-8586-117c3c106dcc")}catch{}})();function av(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function MI(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function ud(e,t){return new d(`Invalid --regex value at --regex #${e}: ${t}`,m.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function DI(e,t=1){let n=e.trim();if(n.length===0)throw ud(t,"provide a non-empty pattern.");let r=n,o="g";if(n.startsWith("/")&&n.length>1){let i=n.lastIndexOf("/"),a=0;for(let s=i-1;s>=0&&n[s]==="\\";s--)a++;i>0&&a%2===0&&/^[dgimsuvy]*$/u.test(n.slice(i+1))&&(r=n.slice(1,i),o=MI(n.slice(i+1)))}if(r.length===0)throw ud(t,"an empty pattern is not allowed.");try{new RegExp(r,o)}catch{throw ud(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:r,flags:o}}function UI(e,t){let n=[...new Set(av(e).map(a=>a.trim()))].filter(a=>a.length>0).map(a=>({kind:"literal",value:a})),r=new Set,o=av(t).flatMap((a,s)=>{let c=a.trim();return r.has(c)?[]:(r.add(c),[DI(c,s+1)])}),i=[...n,...o];if(i.length===0)throw new d("history-redact requires at least one matcher via --literal or --regex.",m.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function jI(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){let i=e.indexOf(t,r);if(i===-1)break;o+=1,r=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function GI(e,t,n){let r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function cv(e,t,n){let r=e,o=0;for(let i of t){let a=i.kind==="literal"?jI(r,i.value,n):GI(r,i,n);r=a.value,o+=a.replacements}return{value:r,replacements:o}}function os(e,t,n){if(typeof e=="string")return cv(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let i=os(o,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,o={};for(let[i,a]of Object.entries(e)){let s=os(a,t,n);r+=s.replacements,o[i]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function sv(e,t,n){let r=0;return{patch:e.map(o=>{if(!Object.prototype.hasOwnProperty.call(o,"value"))return o;let i=os(o.value,t,n);return r+=i.replacements,i.replacements>0?{...o,value:i.value}:o}),replacements:r}}function qI(e){let t=structuredClone(dl),n=0,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];Xr(t,void 0,xt(i.hash_algorithm))!==i.before_hash&&(n+=1),t=rr(t,i.patch,o+1,i.op),Xr(t,void 0,xt(i.hash_algorithm))!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function KI(e,t,n){let r=0,o=!1,i=!1,a=e.message;if(typeof e.message=="string"){let l=cv(e.message,t,n);a=l.value,r+=l.replacements,l.replacements>0&&(o=!0)}let s=sv(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;let c=e.reanchor_evidence?.map(l=>{let p=l.patch?sv(l.patch,t,n):{patch:void 0,replacements:0},u=l.record?os(l.record,t,n):{value:void 0,replacements:0};r+=p.replacements,r+=u.replacements;let f=p.replacements>0||u.replacements>0;if(o||=f,!f)return l;i=!0;let{patch:h,record:_,record_hash:g,record_hash_version:y,...w}=l;return p.replacements>0?w:{...w,patch:l.patch}});return{entry:{...e,message:a,patch:s.patch,...c?{reanchor_evidence:c}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:i}}function zI(e,t,n){let r=structuredClone(dl),o=0,i=0,a=[];for(let s=0;s<e.length;s+=1){let c=e[s],l=k_(c);if(!l.ok)throw new d(`history-redact refuses invalid immutable record ${s+1} (${l.error}).`,m.GENERIC_FAILURE);let p=KI(c,t,n);i+=p.replacements,p.changed&&(o+=1);let u=Xr(r,void 0,xt(c.hash_algorithm));r=rr(r,p.entry.patch,s+1,p.entry.op);let f=Xr(r,void 0,xt(c.hash_algorithm));a.push(S_(c,{...p.entry,before_hash:u,after_hash:f},{retainPriorRecord:p.changed,retainPriorRecordHash:!p.changed}))}return{entries:a,finalDocument:r,entriesChanged:o,replacements:i}}function HI(e){return Object.keys(e.metadata).length>0}function BI(e){if(!HI(e.finalDocument))return{raw:null,path:null,document:null};let t=_t(ht(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new d("history-redact would change the item id; narrow your patterns.",m.USAGE);return{document:t,path:Et(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:ft(t,{format:"toon",schema:e.settings.schema})}}function WI(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function VI(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??ht(e.rewritten.finalDocument);return t.push(Ke({nowIso:A(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function YI(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{let r=await Yt(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let a=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await re(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await fd.rm(e.currentItem.path,{force:!0}),await re(e.subject.historyPath,E_(e.rewrittenEntries))}catch(c){try{await JI(e.subject.historyPath,n,o,i)}finally{await ll(e.subject.historyPath)}throw c}await ll(e.subject.historyPath);let s=e.nextItem.path??e.currentItem.path;s&&(t=await Jt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{a=()=>{throw s}})}a()},afterWrite:async()=>[...t,...await XI(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function JI(e,t,n,r){t===null?await fd.rm(e,{force:!0}):await re(e,t);for(let o of n){let i=r.get(o);i===void 0?await fd.rm(o,{force:!0}):await re(o,i)}}async function XI(e,t){let n=[],r=new Set(t.filter(o=>o!==null));for(let o of r)n.push(...await X({path:o,scope:"project",op:"history_redact"}));return n.push(...await X({path:e,scope:"project",op:"history_redact:history"})),n}async function lv(e,t,n){let{pmRoot:r,settings:o,typeRegistry:i}=await _o(n.path),a=t.replacement??"",s=a.length===0,c=s?"[redacted]":a,l=UI(t.literal,t.regex),p=await yn(r,e,o,i.type_to_folder);return Ia({pmRoot:r,subject:p,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>QI({pmRoot:r,subject:p,settings:o,typeRegistry:i,options:t,rules:l,replacement:c,replacementIsDefault:s},u)})}function QI(e,t){let{pmRoot:n,subject:r,settings:o,typeRegistry:i,options:a,rules:s,replacement:c,replacementIsDefault:l}=e,p=t.entries,u=qI(p),f=zI(p,s,c),h=u.hashMismatchesBefore+u.hashMismatchesAfter,_=!!a.dryRun,g=f.replacements>0,y=[];h>0&&y.push(`history_redact_preexisting_hash_mismatches:${h}`),g||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},v=BI({pmRoot:n,subject:r,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),k=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),C=t.author,S=WI(a,f),{rewrittenEntries:x,auditEntryAdded:N}=VI({rewritten:f,dryRun:_,changed:g,nextItemDocument:v.document,author:C,message:S});return{changed:g,rewrittenEntries:x,...YI({pmRoot:n,subject:r,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:C,rewrittenEntries:x}),report:({verification:P,warnings:Y})=>({id:r.id,dry_run:_,changed:g,patterns:{literal_count:s.filter(j=>j.kind==="literal").length,regex_count:s.filter(j=>j.kind==="regex").length,total_count:s.length,replacement_is_default:l},history:{path:r.historyPath,entries_scanned:p.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:h,audit_entry_added:N,verify_ok:P.ok,verify_errors:P.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:k},warnings:[...new Set([...y,...Y])].sort((j,pe)=>j.localeCompare(pe)),generated_at:A()})}}(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]="61d1a8d4-3d60-5fa5-9f51-d0f14717fffa")}catch{}})();async function dv(e,t,n){return fr(e,t,n,{input:await Ua(t,"learning"),collectionKey:"learnings",op:"learning_add",editOp:"learning_edit",deleteOp:"learning_delete",parseText:r=>ur(r),createEntry:r=>r,bypassOwnershipConflict:!!(t.edit===void 0&&t.delete===void 0&&t.ownershipAppendBypass),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm learnings --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}})}(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]="28dd911b-487d-5ada-8fa5-527798ceb36e")}catch{}})();async function mv(e,t,n){if(_h(t),gt(e,"append","id"),t=Qf(t),t.body===void 0)throw new d("Missing required --body text",m.USAGE);let r=Ht(),o=T(process.cwd(),n.path);await O(o);let i=await E(o),a=I(t.author,i.author_default),s=(await r.resolveValue(t.body,"--body",e_(t,"body"))).trim();if(s.length===0)throw new d("--body text cannot be empty; append requires non-blank content and empty appends would only rewrite updated_at.",m.USAGE,{code:"append_empty_body",required:"Provide non-empty body text positionally, via --body, or with - for stdin.",examples:['pm append pm-a1b2 --body "Progress note"',"pm append pm-a1b2 --body -"]});let c=await _e({pmRoot:o,settings:i,id:e,op:"append",author:a,message:t.message,force:t.force,mutate(l){let p=l.body.trim().length>0?`
18
+
19
+ `:"";return l.body=`${l.body.trimEnd()}${p}${s}
20
+ `,{changedFields:["body"]}}});return{item:c.item,appended:s,changed_fields:c.changedFields}}(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]="1bb376cc-27bc-50d9-a856-76fafcfe6663")}catch{}})();function ZI(e,t,n){let r={...t.metadata,body:t.body},o={...n.metadata,body:n.body};for(let i of new Set([...Object.keys(r),...Object.keys(o)])){if(i==="updated_at"||i==="pm_format_version")continue;let a=r[i],s=o[i];if(ie(a,s))continue;let c=e.get(i);if(c&&!ie(c.after,a))throw new d(`Rollback conflict on ${i}: the batch effects contain an intervening edit. Inspect pm history before resolving it.`,m.CONFLICT);e.set(i,{field:i,before:c?c.before:a,after:s})}}function eR(e,t,n){let r=new Map;for(let[o,i]of e.entries()){if(i.context?.bulk_checkpoint!==t)continue;let a=Qr(or(e,o-1),{schema:n}),s=Qr(or(e,o),{schema:n});ZI(r,a,s)}return[...r.values()].filter(o=>!ie(o.before,o.after))}function tR(e,t){let n={...e.metadata,body:e.body},r=t.filter(o=>!ie(n[o.field],o.after));if(r.length>0)throw new d(`Rollback conflict on ${r.map(o=>o.field).join(", ")}: a later edit changed a batch field. Inspect pm get/history and reconcile it explicitly before retrying.`,m.CONFLICT);for(let o of t)o.field==="body"?e.body=o.before:o.before===void 0?delete e.metadata[o.field]:e.metadata[o.field]=structuredClone(o.before);return t.map(o=>o.field)}async function is(e,t,n){if(t.record.rollback_strategy!=="guarded_inverse")throw new d("This legacy checkpoint has no attributable inverse effects. Inspect pm history and use an explicit pm restore only after reviewing later edits.",m.CONFLICT);let r=await E(e),o=new Map,i=await n_(t.items,async s=>{try{return await nR(e,r,t,s,n)}catch(c){throw o.set(s,c),c}}),a=[];for(let s of i.rows)a.push(s.status==="failed"?{...s,...await wt(o.get(s.id),e)}:s);return{...i,rows:a}}async function nR(e,t,n,r,o){let i=await B_({pmRoot:e,settings:t,id:r,op:"restore",author:I(o.author,t.author_default),message:o.message,force:o.force,skipNoop:!0,historyContext:{bulk_rollback:n.id},async mutate(a){let s=await ra(Xe(e,r),r);if(!Lh(s,a).ok)throw new d(`Cannot safely roll back ${r}: item/history verification failed. Inspect pm history --verify before recovery.`,m.CONFLICT);return s.some(c=>c.context?.bulk_rollback===n.id)?{changedFields:[]}:{changedFields:tR(a,eR(s,n.id,t.schema))}}});return{changed_fields:i.changedFields,warnings:i.warnings,skipped:i.changedFields.length===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]="1430dcf8-9363-556d-aa33-184cea5421f9")}catch{}})();var rR=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function pv(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let r=n.value?.trim();if(r)return{closeReason:r,source:n.source}}return{source:"none"}}function Po(e,t){return _d(e,t,{operation:"close"})}function _d(e,t,n){let r=pv(e);if(!t||r.closeReason!==void 0)return r;let o=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new d("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:o,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function hd(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",r=e.blocked_by!==void 0,o=e.dependencies??[],i=o.filter(l=>l.kind==="blocked_by"),a=e.blocked_reason!==void 0,s=[];if(r&&(delete e.blocked_by,s.push("blocked_by")),a&&(delete e.blocked_reason,s.push("blocked_reason")),t.orderingEdges==="remove"&&i.length>0){let l=new Set(i),p=o.filter(u=>!l.has(u));p.length>0?e.dependencies=p:delete e.dependencies,s.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:s,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...i.length>0?[`closed_removed_predecessors:${e.id}:${i.map(l=>l.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${i.length}`]:[]]};let c=[...new Set([...n?[n]:[],...i.map(l=>l.id)])];return c.length===0?{changedFields:s,warnings:[]}:{changedFields:s,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(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]="94147426-41f3-5f24-b6e2-8653f5dde6d0")}catch{}})();var oR=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function iR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new d(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function fv(e){let t=[];for(let n of oR){let r=e[n.key];(typeof r!="string"||r.trim().length===0)&&t.push(n)}return t}function _v(e,t,n={}){let r=fv(e);if(r.length===0)return;let o={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},i=r.map(s=>`--${s.key.replaceAll("_","-")}`),a=[...t,"update",e.id,...r.flatMap((s,c)=>[i[c],o[s.key]?.trim()||"<value>"])];return{missing:i,suggested_retry:L(a),suggested_retry_args:a}}async function aR(e,t,n){let r=new Set,o=t;for(;typeof o=="string"&&o.trim().length>0;){let i=o.trim();if(i===n)return!0;if(r.has(i))return!1;r.add(i),o=(await e(i))?.duplicate_of}return!1}function sR(e){return typeof e!="string"||e.trim().length===0}async function cR(e,t,n,r){let o=n?.trim();if(!o)return;if(o===r)throw new d("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let i=$(t,R()),a=new Map,s=async l=>{if(a.has(l))return a.get(l)??null;let p=await K(e,l,t.id_prefix,t.item_format,i.type_to_folder);if(!p)return a.set(l,null),null;let{document:u}=await ne(p,{schema:t.schema});return a.set(l,u.metadata),u.metadata},c=await s(o);if(!c)throw new d(`Duplicate target "${o}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${r} "Duplicate of ${o}" --duplicate-of ${o}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await aR(s,c.duplicate_of,r))throw new d(`Circular duplicate reference detected. Target "${o}" points back to "${r}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new d(`Duplicate target "${o}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${r} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function lR(e,t,n){return e.filter(r=>r.parent===t&&!se(r.status,n)).map(r=>r.id).sort((r,o)=>r.localeCompare(o))}function dR(e,t,n){let r=new Map(e.map(s=>[s.id.trim().toLowerCase(),s])),o=Rh(e),i=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(s=>a.has(s.status)).map(s=>({item:s,blockerIds:o.get(s.id.trim().toLowerCase())})).filter(({blockerIds:s})=>s.includes(i)).filter(({blockerIds:s})=>s.every(c=>{if(c===i)return!0;let l=r.get(c);return l!==void 0&&se(l.status,n)})).map(({item:s,blockerIds:c})=>({id:s.id,blocker_ids:c})).sort((s,c)=>s.id.localeCompare(c.id))}async function mR(e,t,n,r,o,i,a){let s=dR(n,r,i),c=[],l=[],p=[],u=[],f;for(let h of s)try{let _=await _e({pmRoot:e,settings:t,id:h.id,op:"update",author:o,message:`Auto-unblocked after blocker ${r} closed`,mutate(g){let y=g.metadata.dependencies??[],w=y.filter(k=>{let C=k.id.trim().toLowerCase();return k.kind!=="blocked_by"||!h.blocker_ids.includes(C)});g.metadata.status=i.open_status,delete g.metadata.blocked_by,delete g.metadata.blocked_reason,g.metadata.unblock_note=`Auto-unblocked after blocker ${r} closed; all blockers resolved (${h.blocker_ids.join(", ")}).`,w.length>0?g.metadata.dependencies=w:delete g.metadata.dependencies;let v=["status","blocked_by","blocked_reason","unblock_note"];return w.length!==y.length&&v.push("dependencies"),{changedFields:v}}});c.push(`auto_unblocked:${_.item.id}:resolved_blockers=${h.blocker_ids.join(",")}`),l.push(_.item.id)}catch(_){let g=_ instanceof Error?_.message.replace(/\s+/g," ").trim():"unknown";vn(_)?(f??=_,p.push(h.id)):u.push({id:h.id,reason:g}),c.push(`auto_unblock_failed:${h.id}:${g}`)}if(f!==void 0){let h=await Lg(f,e),_=[...i.blocked_statuses].sort().join(",");throw _R(h,{closedId:r,unblockedIds:l,conflictIds:p,failed:u,openStatus:i.open_status,blockedStatuses:_,commandScope:a})}return c}var Ft=10,gd=20,pR=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function uR(e){for(let t of pR){let n=e[t.list];if(Array.isArray(n))for(;n.length>t.floor&&!gl(e);)n.pop(),Reflect.set(e,t.omitted,Number(e[t.omitted])+1)}return e}function uv(e){let t=e.length-Ft;return`${e.slice(0,Ft).join(", ")}${t>0?`, and ${t} more`:""}`}var fR="post_close_auto_unblock_refused";function _R(e,t){let{closedId:n,conflictIds:r,failed:o,commandScope:i}=t,a=String(e.context.item_id),s=_=>L([...i,"update",_,"--status",t.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${_}=<item_hash>`]),c=o.slice(0,Ft).map(_=>({id:_.id,reason:Vp(_.reason,160)})),l=o.length===0?"":` Auto-unblocking also failed for ${uv(o.map(_=>_.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,p=L([...i,"list","--status",t.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),u=[...r.slice(0,Ft).flatMap(_=>[L([...i,"get",_,"--json"]),s(_)]),...c.map(_=>L([...i,"get",_.id,"--json"]))],f=r.length>Ft||o.length>Ft||u.length>gd,h=u.slice(0,f?gd-1:gd);return new d(`${n} was closed, but auto-unblocking ${a} was refused. ${e.message}`,e.exitCode,{...e.context,reason:fR,examples:U_(a,!1,{scopeArgs:i}).examples,required:`The close of ${n} is complete; do not retry it. Only unblocking ${r.length===1?a:`the guarded dependents it refused (${uv(r)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${s(a)}${r.length===1?"":" for each id"}.${l}${f?` This refusal does not list a step for every dependent left blocked; list them with ${p}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:f?[...h,p]:h,details:uR({...structuredClone(e.context.details),pending_unblock:r.slice(0,Ft),pending_unblock_omitted:Math.max(0,r.length-Ft),auto_unblock_failed:c,auto_unblock_failed_omitted:Math.max(0,o.length-Ft)}),side_effects:[{path:`history/${n}.jsonl`,op:"close"},...t.unblockedIds.map(_=>({path:`history/${_}.jsonl`,op:"update"}))]})}async function as(e,t,n){if(!vn(e)||!e.context.side_effects?.some(o=>`${o.op}:${o.path}`==`close:history/${t}.jsonl`))return;let r=String(e.context.item_id);return{warnings:[...e.context.side_effects.filter(o=>o.op==="update").map(o=>o.path.slice(8,-6)).map(o=>`auto_unblocked:${o}`),`auto_unblock_refused:${r}:item_revision_conflict`],dependent_revision_conflict:{item_id:r,error:dt(e),...await wt(e,n)}}}function hR(e,t){let n=[],r=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:o,key:i}of r){if(typeof o!="string")continue;let a=o.trim();a.length!==0&&(e[i]=a,n.push(i))}return n}function gR(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],r=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:o,value:i}of r)sR(e[o])&&(e[o]=i,n.push(o));return n}function yR(e,t){let n=[["--resolution",e.resolution],["--expected-result",e.expectedResult],["--actual-result",e.actualResult],["--validate-close",e.validateClose],["--completed-at",e.completedAt],["--message",e.message],["--author",e.author]].flatMap(([r,o])=>t.has(r)||o===void 0||o.trim().length===0?[]:[`${r}=${o}`]);return e.force===!0?[...n,"--force"]:n}function wR(e,t,n){let r=t.map(y=>y.label),o=t.map(y=>`--${y.key.replaceAll("_","-")}`),i=o.flatMap(y=>[y,"<value>"]),a=[...n.commandScope,"update",e.id,...i],s=`Cannot close item ${e.id}: missing ${r.join(", ")}. Populate fields or use --validate-close warn.`,c="Use --validate-close warn only when governance permits an evidenced exception.",l=Object.entries(n.options.lifecyclePolicy??{}).filter(([,y])=>y!==void 0).map(([y])=>y),p=M_(n.pmRoot),u=typeof n.options.author=="string"&&n.options.author.trim().length===0,f=l.length>0?`its lifecyclePolicy override (${l.join(", ")}) has no CLI spelling`:u?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":p===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(f!==void 0)return new d(s,m.USAGE,{code:"close_validation_missing_fields",required:`Pass ${t.map(y=>y.key).join(", ")} on the same SDK close; ${f}, so no CLI retry reproduces it.`,recovery:{missing:o,next_best_command:L(a)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",c]});let h=n.closeReason===void 0?[]:[`--reason=${n.closeReason}`],_=p.map(y=>`--expect-hash=${y}`),g=[...n.commandScope,"close",e.id,...h,...yR(n.options,new Set(o)),..._,...i];return new d(s,m.USAGE,{code:"close_validation_missing_fields",required:`Supply ${o.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:o,suggested_retry:L(g),suggested_retry_args:g,next_best_command:L(a)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",c]})}function vR(e,t,n,r){let o=t.map(s=>il(s.field).flag),i=[...r.author?.trim()?[`--author=${r.author}`]:[],...r.force===!0?["--force"]:[]],a=[...n,"update",e.id,...i,...o.flatMap(s=>[s,"<value>"])];return new d(`Cannot close item ${e.id}: deferred fields still have no value (${t.map(s=>s.field).join(", ")}). Supply them or use --validate-close warn.`,m.USAGE,{code:"close_validation_deferred_fields",required:`Supply ${o.join(", ")}: each was deferred at create (${t.map(s=>`${s.field}: ${s.reason}`).join("; ")}).`,recovery:{missing:o,next_best_command:L(a)},nextSteps:["Record the now-known values with recovery.next_best_command; the update resolves each deferral, then repeat the close.","Use --validate-close warn only when governance permits closing with deferred values still unknown."]})}function bR(e,t,n){let r=d_(e);if(r.length===0)return[];if(t==="strict")throw vR(e,r,n.commandScope,n.options);return[`close_validation_deferred_fields:${e.id}:${r.map(o=>o.field).join(",")}`]}function kR(e,t,n,r){let o=[];if(t!=="off"){o.push(...bR(e,t,r));let i=fv(e);if(i.length>0){let a=i.map(s=>s.label);if(t==="strict")throw wR(e,i,r);o.push(`close_validation_missing_fields:${e.id}:${a.join(",")}`)}if(n.length>0){if(t==="strict")throw new d(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);o.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return o}return n.length>0&&o.push(`closed_with_active_children:${e.id}:${n.join(",")}`),o}function SR(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function ER(e){let t=["assignee","claim_principal"].filter(n=>e[n]!==void 0);for(let n of t)delete e[n];return[...t]}function AR(e,t){if(se(e.status,t.statusRegistry)&&!t.force)throw new d(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:_v(e,t.commandScope,t.options)});let n=hR(e,t.options),r=gR(e,t.duplicateOf),o=kR(e,t.validateCloseMode,t.activeChildIds,t);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let i=t.options.completedAt!==void 0||e.completed_at===void 0;i&&(e.completed_at=t.completedAt);let a=["status","closed_at",...i?["completed_at"]:[],...SR(e,t.closeReason),...n];if(Q_(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of r)a.includes(c)||a.push(c)}a.push(...ER(e));let s=hd(e,t.lifecyclePolicy);return a.push(...s.changedFields),o.push(...s.warnings),{changedFields:a,...o.length>0?{warnings:o}:{}}}async function hv(e,t,n,r){let o=T(process.cwd(),r.path),i=Pe(r);await O(o);let a=await E(o),s=D(a.schema),c=I(n.author,a.author_default),l=$(a,R()).type_to_folder,p=await K(o,e,a.id_prefix,a.item_format,l);if(!p)throw await rt(o,e,a.id_prefix,l);let u=await cR(o,a,n.duplicateOf,p.id),f={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??a.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},h=Po({explicit:t,duplicateOf:u,resolution:n.resolution,message:n.message},f.requireCloseReason).closeReason,_=iR(n.validateClose)??a.governance.close_validation_default,g=await ye(o,a.item_format,l,void 0,a.schema),y=lR(g,p.id,s),w=A(),v=n.completedAt===void 0?w:te(n.completedAt,new Date(w),"completed-at"),k={timestamp:v,source:n.completedAt===void 0?"close_time":"asserted",...n.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${L([...i,"update",p.id,"--completed-at","<ISO>"])}.`}:{}},C=await ir({pmRoot:o,settings:a,id:p.id,op:"close",author:c,message:n.message,force:n.force,resolveHistoryContext:()=>({completion:{timestamp:k.timestamp,source:k.source}}),mutate(x){return n.completedAt===void 0&&x.metadata.completed_at!==void 0&&(k={timestamp:x.metadata.completed_at,source:"existing"}),AR(x.metadata,{pmRoot:o,commandScope:i,statusRegistry:s,force:n.force,options:n,duplicateOf:u,validateCloseMode:_,activeChildIds:y,closeReason:h,closedAt:w,completedAt:v,lifecyclePolicy:f})}}),S=_==="warn"?_v(C.item,i):void 0;return{item:C.item,changed_fields:C.changedFields,...S?{follow_up:{kind:"complete_close_evidence",missing:S.missing,suggested_command:S.suggested_retry,suggested_command_args:S.suggested_retry_args}}:{},warnings:[...C.warnings,...await mR(o,a,g,p.id,c,s,i)],completion:k}}function Mt(e,t,n,r){return hv(e,t,n,r)}(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]="90dbc790-401a-5b74-90e2-143f65d32b9f")}catch{}})();var yv=2,yd="close-many",TR=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function CR(e,t){return wo(e,t,{includePagination:!1})}function IR(e,t){return wo(e,t)}function RR(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",m.USAGE)}function OR(e){let t={};if(!e)return t;for(let[n,r]of Object.entries(e))r==null||typeof r=="string"&&!r.split(",").some(o=>o.trim().length>0)||(t[n]=r);return t}function xR(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new d("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",m.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function $R(e,t){let n=D(t.schema),r=$(t,R()),o=await ye(e,t.item_format,r.type_to_folder,void 0,t.schema),i=new Map,a=new Map;for(let s of o){if(typeof s.parent!="string"||s.parent.length===0||(a.set(s.id,s.parent),se(s.status,n)))continue;let c=i.get(s.parent);c?c.push(s.id):i.set(s.parent,[s.id])}for(let s of i.values())s.sort((c,l)=>c.localeCompare(l));return{childrenByParent:i,parentByChild:a}}function gv(e,t,n){let r=n?.get(e);if(r!==void 0)return r;let o=0,i=t.get(e),a=[],s=new Set,c=!1;for(;i!==void 0&&!s.has(i);){let l=n?.get(i);if(l!==void 0){o+=l+1;break}s.add(i),a.push(i),o+=1,i=t.get(i)}if(i!==void 0&&s.has(i)&&(c=!0),!c){n?.set(e,o);for(let[l,p]of a.entries())n?.set(p,o-l-1)}return o}async function PR(e){let t=await Xi(e.pmRoot,yd,e.rollbackId,yv),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,r=await is(e.pmRoot,t,{author:e.options.author,message:n,force:e.options.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...gn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}}function LR(e,t,n,r,o){return e.map(i=>{let a=(t.get(i.id)??[]).filter(c=>!n.has(c)),s=!wv(i,r,o);return{id:i.id,title:typeof i.title=="string"?i.title:"",status:i.status,action:s?"skip":"close",...s?{skip_reason:"already_terminal"}:{},...a.length>0?{active_child_ids:a}:{}}})}async function NR(e){let t=await Ji(e.pmRoot,yd,e.checkpointId,{schema_version:yv,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:I(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function FR(e){let t=[],n=[];for(let r of e.matched){if(!e.closableIds.has(r.id)){t.push({id:r.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let o=await ma({pmRoot:e.pmRoot,itemId:r.id,checkpointId:e.checkpointId},()=>Mt(r.id,e.reason,e.closeOptions,e.global));t.push({id:r.id,status:"closed",completion:o.completion,changed_fields:o.changed_fields,...o.warnings&&o.warnings.length>0?{warnings:o.warnings}:{}}),n.push(r.id)}catch(o){let i=await as(o,r.id,e.pmRoot);if(i!==void 0){t.push({id:r.id,status:"closed",...i}),n.push(r.id);continue}t.push({id:r.id,status:"failed",error:dt(o),...await wt(o,e.pmRoot)})}}return{rows:t,closedIds:n}}function MR(e){return Vi(e.rollback)}function DR(e){if(e.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",m.USAGE);if(IR(e.list,e.status))throw new d("Rollback mode does not accept filter options",m.USAGE)}function UR(e){if(!CR(e.list,e.status))throw new d(`close-many requires at least one filter to scope the close (for example: ${TR}). Refusing to match every item.`,m.USAGE)}function jR(e,t){let n=new Map;return[...e].sort((r,o)=>{let i=gv(o.id,t,n)-gv(r.id,t,n);return i!==0?i:r.id.localeCompare(o.id)})}function wv(e,t,n){return n||!se(e.status,t)}function GR(e,t,n){return new Set(e.filter(r=>wv(r,t,n)).map(r=>r.id))}async function qR(e){UR(e.options);let t=D(e.settings.schema),n=xR(e.options.reason,e.settings.governance.require_close_reason),r=e.options.force===!0,o=await Pt(e.options.status,OR(e.options.list),e.global),{childrenByParent:i,parentByChild:a}=await $R(e.pmRoot,e.settings),s=jR(o.items,a),c=[...new Set(String(e.options.list?.ids??"").split(",").map(f=>f.trim()).filter(f=>f.length>0))],l=c.length===0?[]:(await Pt(void 0,{ids:c.join(","),noTruncate:!0,full:!0},e.global)).items,p=new Set(l.map(f=>f.id)),u=GR(s,t,r);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:r,listed:o,matched:s,unmatchedIds:c.length===0?void 0:c.filter(f=>!p.has(f)),planRows:LR(s,i,u,t,r)}}function KR(e){return{outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[],...e.unmatchedIds!==void 0?{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length}:{}}}async function zR(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return NR({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function vv(e,t){let n=MR(e),r=T(process.cwd(),t.path);await O(r);let o=await E(r),i=e.dryRun===!0;if(RR(e.list),n!==void 0)return DR(e),PR({pmRoot:r,rollbackId:n,options:e,global:t});let a=await qR({pmRoot:r,settings:o,options:e,global:t});if(i)return KR(a);let s=new Set(a.planRows.filter(w=>w.action==="close").map(w=>w.id)),c=A(),l=Yi(yd,c),p=await zR({context:a,options:e,closableIds:s,checkpointId:l,nowValue:c}),u={author:e.author,message:e.message??`close-many apply ${l}`,completedAt:e.completedAt,validateClose:a.validateCloseMode,force:a.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:f,closedIds:h}=await FR({pmRoot:r,checkpointId:l,matched:a.matched,closableIds:s,reason:a.reason,closeOptions:u,global:t}),_=f.filter(w=>w.status==="closed").length,g=f.filter(w=>w.status==="skipped").length,y=f.filter(w=>w.status==="failed").length;return{...gn({applied:_,skipped:g,failed:y,unmatched:a.unmatchedIds?.length??0}),mode:"apply",matched_count:a.matched.length,dry_run:!1,...a.reason!==void 0?{reason:a.reason}:{},filters:a.listed.filters,...a.validateCloseMode?{validate_close:a.validateCloseMode}:{},...p?{checkpoint:p}:{},closed_count:_,skipped_count:g,failed_count:y,rows:f,ids:h,...a.unmatchedIds!==void 0?{unmatched_ids:a.unmatchedIds,unmatched_count:a.unmatchedIds.length}:{}}}(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]="35e192f3-e22e-59bb-9dc8-7d652136c827")}catch{}})();function HR(e,t){return[...new Set([...Qo.filter(n=>e[n]!==void 0),...Object.keys(e).filter(n=>e[n]!==void 0),...t.length>0?["body"]:[]])].sort((n,r)=>n.localeCompare(r))}function BR(e,t){let n=`copied_from=${e}`;if(!t)return n;let r=t.trim();return r.length>0?`${r} | ${n}`:n}async function wd(e,t,n){let r=T(process.cwd(),n.path);await O(r);let o=await E(r),i=$(o,R()),a=await K(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await rt(r,e,o.id_prefix,i.type_to_folder);let s=await ne(a,{schema:o.schema}),c=s.document.metadata,l=A(),p=I(t.author,o.author_default),u=await eo(r,o.id_prefix,{tokenLength:o.ids.token_length,typeToFolder:i.type_to_folder,probeExisting:!1}),f=D(o.schema),h=t.title?.trim();if(h!==void 0&&h.length===0)throw new d("Copy --title must not be empty",m.USAGE);let _={...c,id:u,title:h??c.title,status:f.open_status,created_at:l,updated_at:l};delete _.closed_at,delete _.completed_at,delete _.close_reason,delete _.test_runs;let g=et(R()),y=_t({metadata:_,body:s.document.body},{schema:o.schema,extensionFieldNames:g}),w=await dr({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0?"off":o.governance.duplicate_detection_mode,threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:t.allowDuplicate}),v=HR(y.metadata,y.body),k=Et(r,y.metadata.type,u,o.item_format,i.type_to_folder),C=Xe(r,u),S=await mt(r,u,o.locks.ttl_seconds,p,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms),x={metadata:{},body:""},N,P;try{let Y=await Yt(r,p,{required:o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0});try{o.governance.duplicate_detection_mode==="strict"&&t.allowDuplicate!==!0&&await dr({title:y.metadata.title,description:y.metadata.description,body:y.body,excludeIds:[a.id]},{pmRoot:r,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1});let j=await K(r,u,o.id_prefix,o.item_format,i.type_to_folder);if(j)throw new d(`Cannot copy to ${u}: an item with that id already exists at ${j.itemPath}. Retry the copy to allocate a new id.`,m.CONFLICT,{code:"item_id_collision",why:`Allocated id ${u} already exists at ${j.itemPath}.`,recovery:{suggested_retry:`pm copy ${a.id}`}});await fn({pm_root:r,operation:"create",before:null,after:y,changed_fields:v,author:p,sdk:hn({pmRoot:r,settings:o,typeToFolder:i.type_to_folder})}),await re(k,ft(y,{format:o.item_format,schema:o.schema,extensionFieldNames:g}));try{let pe=Ke({nowIso:l,author:p,op:"create",before:x,after:y,message:BR(a.id,t.message)});await Bt(C,pe)}catch(pe){throw await jn(k),pe}P=await Jt({pmRoot:r,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:k,document:y})}finally{await Y()}N=[...await X({path:k,scope:"project",op:"create",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v}),...await X({path:C,scope:"project",op:"create:history",item_id:y.metadata.id,item_type:y.metadata.type,before:x,after:y,changed_fields:v})],Yn({id:y.metadata.id,op:"create",item_type:y.metadata.type,status:y.metadata.status,current:un(y.metadata,v),changed_fields:v})}finally{await S()}return{source_id:a.id,item:structuredClone(y.metadata),changed_fields:v,warnings:[...Ta(w),...P,...N],...w===void 0?{}:{similarity_advisory:w}}}(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]="e58f7cfe-1414-5205-9f1c-b667abf67702")}catch{}})();function vd(){return rl.map(e=>e.field).join(", ")}var WR=Object.freeze({fields:[],reason:void 0,optionKeys:new Set});function VR(e){return(e??[]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function bv(e,t){let n=Qn(t,"defer"),r=Qn(t,"defer-reason"),o=VR(e.defer),i=e.deferReason?.trim();if(o.length===0){if(i!==void 0&&i.length>0)throw new d(`${r} needs ${n}: name the fields whose values are not known yet.`,m.USAGE,{code:"create_deferral_fields_required",required:`Pass ${n} with ${r}, or drop ${r}.`,nextSteps:[`Deferrable fields: ${vd()}.`]});return WR}let a=new Map;for(let c of o){let l=ol(c);if(l===void 0)throw new d(`${n} cannot defer "${c}". Deferrable fields: ${vd()}.`,m.USAGE,{code:"create_deferral_field_unsupported",required:`Defer only ${vd()}; supply every other field, or clear a repeatable option with its --clear-* flag.`});a.set(l.field,l)}if(i===void 0||i.length===0)throw new d(`${n} requires ${r}: record why the deferred values are not known yet.`,m.USAGE,{code:"create_deferral_reason_required",required:`Pass ${r} "<why>", for example the system the record was imported from.`});let s=rl.filter(c=>a.has(c.field));return{fields:s,reason:i,optionKeys:new Set(s.map(c=>c.option))}}function bd(e,t,n,r,o={}){let i=e.fields.filter(c=>{let l=t[c.option];return typeof l=="string"&&l.trim().length>0||o[c.field]!==void 0||n.has(c.field)});if(i.length===0)return;let a=Qn(r,"defer"),s=i.map(c=>c.field).join(", ");throw new d(`Cannot both defer and set ${s}: ${a} records a value as not known yet.`,m.USAGE,{code:"create_deferral_conflict",required:`Drop ${a} for ${s}, or drop the value (or unset) you supplied for it.`})}function kv(e){if(e.fields.length!==0)return al(e.fields.map(t=>({field:t.field,reason:e.reason})))}function Sv(e,t=[]){let n=(Array.isArray(e)?e:e===void 0?[]:[e]).filter(i=>typeof i=="string").flatMap(i=>i.split(",")).map(i=>ol(i)).filter(i=>i!==void 0),r=new Set(n.map(i=>i.field)),o=t.filter(i=>i.commands.includes("create")&&r.has(i.metadata_key)).flatMap(i=>s_(i));return[...n.map(i=>i.option),...o]}function Ev(e,t,n,r,o={}){let i=new Set(t.fields.map(p=>p.field)),a=n.filter(p=>p.commands.includes("create")),s=p=>p.required!==!0&&i.has(p.metadata_key),c=new Set(a.filter(s).map(p=>`--${p.cli_flag}`)),l=new Set(a.filter(p=>!s(p)&&c_(p,r)&&ea(o,p)===void 0).map(p=>`--${p.cli_flag}`));return e.filter(p=>!c.has(p)||l.has(p))}(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]="b653115b-596b-5c07-b1f7-541fa1f04a33")}catch{}})();var YR="hierarchy-integrity";async function ss(e){let t=e.required?await mt(e.pmRoot,YR,e.ttlSeconds,e.author,!1,!1,e.waitMs,{waitPolicy:"progress"}):async()=>{},n=!1;return async()=>{n||(n=!0,await t())}}(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]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function cs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ls(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function ds(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(fc.includes(t))return t;let n=ge(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new d("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function ms(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new d("Regression must be one of true|false|1|0",m.USAGE)}(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]="9625fa5b-47ea-52b6-bf65-ac0f32ae616b")}catch{}})();var Av=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds","phase"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(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]="48513c82-4195-51fc-bd68-480148a54d10")}catch{}})();var JR=["documentAnnotationSnapshot","runtimeFieldCommands","ownershipMetadataBypass","ownershipDependencyBypass"];function ps(e){let t=Av.find(([r])=>r===e)?.[1]??e.replaceAll(/_([a-z])/gu,(r,o)=>o.toUpperCase()),n=[["update",Wc],["create",Bc]].flatMap(([r,o])=>o.flatMap(i=>{if(i.target!==t)return[];let a=i.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:r,flag:a}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(r=>r.flag))]}:{}},nextSteps:n.length>0?n.map(({command:r,flag:o})=>`Use the declared core mutation: pm ${r}${r==="update"?" <id>":""} ${o} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}var Cv={create:{name:"create",usage:"pm create",sdkScope:"create options"},update:{name:"update",usage:"pm update <id>",sdkScope:"update options"},update_many:{name:"update-many",usage:"pm update-many <selection flags>",sdkScope:"update options of the update-many request"}};function Tv(e){return e.flatMap(t=>[t.flag,...t.short===void 0?[]:[t.short],...t.aliases??[]])}function Iv(e){if(e==="update_many"){let o=Iv("update"),i=Tv(qe("update-many"));return{options:new Set([...o.options,...i.map(a=>tl(a))]),flags:new Set([...o.flags,...i])}}let t=e==="update"?Wc:Bc,n=Tv([...qe(e),...Kn]),r=[...t.flatMap(o=>[o.target,...o.keys]),...n.map(o=>tl(o)),...e==="update"?JR:[]];return{options:new Set(r),flags:new Set(n)}}function XR(e,t){let n=Cv[t];return e===void 0?`SDK: every option name for this field is shared with another declared field or an option of pm ${n.name}; no SDK option sets it alone.`:`SDK: pass ${e} in the ${n.sdkScope}.`}function QR(e,t,n,r){return e.definitions.some(o=>o.metadata_key===t.metadata_key&&o.commands.includes(n)&&ea(r,o)!==void 0)}function us(e,t,n){let r=Cv[t],o=n===void 0?void 0:Object.fromEntries(Object.entries(n).filter(([i])=>i!=="field"));return i=>{let a=ff(i),s=e.definitions.filter(h=>h.metadata_key===a||h.key===a),c=s.find(h=>h.commands.includes(t))??s[0];if(c===void 0)return;let l=`Inspect the value contract with: pm schema show-field ${c.key}`;if(!c.commands.includes(t))return{recovery:{provided_fields:[i]},nextSteps:[`The project schema declares "${c.key}" for ${c.commands.join(", ")} only; ${r.name} cannot set it.`,l]};if(o!==void 0&&QR(e,c,t,o))return{recovery:{provided_fields:[i]},nextSteps:[`This invocation already sets "${c.key}" through a declared flag or option; drop the --field ${i} assignment so the field receives one value.`,l]};let p=Iv(t),u=a_(c,e,p,t),f=u===void 0?`Every CLI spelling of "${c.key}" is shared with another declared field or an option of pm ${r.name}; give it a distinct cli_flag in the project schema.`:`Use the declared project-schema flag: ${r.usage} ${el(u)} <value>`;return{recovery:{provided_fields:[i],...u===void 0?{}:{suggested_flags:[el(u)]}},nextSteps:[f,XR(i_(c,e,p.options,t),t),l]}}}(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]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var ZR=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Rv(e,t,n,r){if(ZR.has(t.trim().toLowerCase())||n!==r.open_status)return;let o=It("in_progress",r);if(!(o===void 0||o===r.open_status))return{command:`pm claim ${e} --start`,to_status:o}}(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]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function xv(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new d(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function kd(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function it(e,t,n,r=n){if(!t.includes(e))throw new d(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:r,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var $v=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function eO(e,t){return t==="defined"?e!==void 0:!!e}function Ov(e,t,n){if(!eO(e,n))return;let r=ge(e,`event ${t}`);if(!Number.isInteger(r)||r<1)throw new d(`--event ${t} must be an integer >= 1`,m.USAGE);return r}function tO(e,t,n){let r=e?te(e,n,"event.recur_until"):void 0;if(r&&r<t)throw new d("--event recur_until must be at or after start",m.USAGE);return r}function nO(e){return Array.from(new Set(kd(e).map(t=>it(t.toLowerCase(),wp,"event weekday")))).sort((t,n)=>_c(t)-_c(n))}function rO(e){return Array.from(new Set(kd(e).map(t=>{let n=ge(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new d("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function oO(e,t){return Array.from(new Set(kd(e).map(n=>te(n,t,"event.recur_exdates")))).sort((n,r)=>n.localeCompare(r))}function Pv(e,t,n,r){let o=e.recur_freq?.trim(),i=e.recur_interval?.trim(),a=e.recur_count?.trim(),s=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),l=e.recur_by_month_day?.trim(),p=e.recur_exdates?.trim();if(![o,i,a,s,c,l,p].some(v=>v!==void 0))return;if(!o)throw new d("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=it(o.toLowerCase(),yp,"event recurrence frequency"),f=Ov(i,"recur_interval",r),h=Ov(a,"recur_count",r),_=tO(s,t,n),g=nO(c),y=rO(l),w=oO(p,n);return{freq:u,interval:f,count:h,until:_,by_weekday:g.length>0?g:void 0,by_month_day:y.length>0?y:void 0,exdates:w.length>0?w:void 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]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function kr(e,t=ot()){let n=t.resolve(e);if(n)return n.kind;let r=new Set(Xo),o=[...Xo,...t.list().filter(({kind:i})=>!r.has(i)).flatMap(({kind:i,aliases:a})=>[i,...a])];throw new d(`Invalid dependency kind value "${e}". Allowed: ${o.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:o},required:`dependency kind must be one of: ${o.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Lo(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new d(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function No(e,t,n=ot()){for(let r of t??[])try{Tp(e,r.id,r.kind,n)}catch(o){throw new d(dt(o),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${r.id} (${r.kind}) violates the active relationship-kind policy`})}}async function Lv(e,t){return(await ne(e,{schema:t})).document.metadata.created_at}async function iO(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await K(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Lv(n,t.schema)}function aO(e){let t=e.registry.require(e.dependency.kind);return new d(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function sO(e){let t=e.dependencies.filter(o=>e.registry.resolve(o.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(o.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:o,located:i})=>i===null?[]:[[o,i]])),r=new Map(await Promise.all([...new Set(t.map(({id:o})=>o))].map(async o=>[o,await Lv(n.get(o),e.context.schema)])));for(let o of e.holders){let i=await iO(o,e.context);if(i!==void 0)for(let a of t){let s=r.get(a.id),c=Date.parse(i),l=Date.parse(s);if(!(Number.isFinite(c)&&Number.isFinite(l)&&c>l))throw aO({holder:o,dependency:a,sourceCreatedAt:i,targetCreatedAt:s,registry:e.registry})}}}async function Rn(e){let t=e.registry??ot(),n=(e.dependencies??[]).filter(a=>!qf(a.source_kind)),r=[...new Set(n.map(a=>a.id))],o=await Promise.all(r.map(async a=>({target:a,located:await K(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),i=o.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,s)=>a<s?-1:1);if(i.length>0&&e.allowUnresolved!==!0)throw new d(`Dependency target${i.length===1?"":"s"} not found: ${i.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:i,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${i.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:i,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${i[0]}" --limit 10`}});return await sO({dependencies:n,missingTargets:i,resolutions:o,holders:e.holders??[],registry:t,context:e}),i.map(a=>`dependency_target_unresolved:${a}`)}(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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var cO={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function lO(e){return cO[e]}function Sd(e){return lO(e)!==void 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]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Nv="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",dO="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",mO=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,pO=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Mv=1e3,Ed=60*Mv,uO=60*Ed;function Fv(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new d(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function fO(e,t){let n=new Date(e),r=t.trim();if(/^[+-]?\d+m$/i.test(r))throw new d(`Event duration "${r}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let o=r.replace(/^([+-]?\d+)mo$/i,"$1m"),i=mO.exec(r);if(i){let c=i[1]==="-"?-1:1,l=Number.parseInt(i[2],10)*c;return Fv(n.getTime()+l*Ed,r)}let a=pO.exec(r);if(a){let[,c,l,p,u]=a;if(l||p||u){let f=c==="-"?-1:1,h=Number.parseInt(l??"0",10),_=Number.parseInt(p??"0",10),g=Number.parseInt(u??"0",10),y=h*uO+_*Ed+g*Mv;return Fv(n.getTime()+f*y,r)}}let s=o.startsWith("+")||o.startsWith("-")?o:`+${o}`;return te(s,n,"event.duration")}function Dv(e,t,n,r){if(t&&n)throw new d(dO,m.USAGE);if(n){let i=fO(e,n);if(i<e)throw new d(Nv,m.USAGE);return i===e?void 0:i}if(!t)return;let o=te(t,r,"event.end");if(o<e)throw new d(Nv,m.USAGE);if(o!==e)return o}(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]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var _O=["at","date","text","title"],hO=["start","date","end","duration","title","description","location","timezone","all_day",...$v],gO=["key","value"];function Uv(e,t){return t==="trimmed"?e?.trim():e}function yO(e,t){return t==="defined"?e!==void 0:!!e}function fs(e,t,n){return e.map(r=>{let o=fe(r,"--reminder");tt(o,"--reminder",_O);let i=Uv(o.at??o.date,n.valueMode),a=Uv(o.text??o.title,n.valueMode);if(!i||!a)throw new d("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let s=a.trim();if(!s)throw new d("--reminder text must not be empty",m.USAGE);return{at:te(i,t,"reminder.at"),text:s}})}function _s(e,t,n){return e.map(r=>{let o=fe(r,"--event");tt(o,"--event",hO);let i=(o.start??o.date)?.trim();if(!i)throw new d("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let a=te(i,t,"event.start"),s=o.end?.trim(),c=o.duration?.trim(),l=Dv(a,s,c,t),p=o.title,u=o.description,f=o.location,h=o.timezone,_=p?.trim(),g=u?.trim(),y=f?.trim(),w=h?.trim(),v=[["title",p,_],["description",u,g],["location",f,y],["timezone",h,w]];for(let[x,N,P]of v)if(N!==void 0&&!P)throw new d(`--event ${x} must not be empty`,m.USAGE);let k=o.all_day?.trim(),C=Pv(o,a,t,n.recurrenceEmptyNumericGuard),S=yO(k,n.allDayEmptyGuard)?xv(k,"--event all_day"):void 0;return{start_at:a,end_at:l,title:_,description:g,location:y,all_day:S,timezone:w,recurrence:C}})}function hs(e){let t={};for(let n of e){let r=n.trim();if(r.length===0)throw new d("--type-option values must not be empty",m.USAGE);let o,i;if(r.includes(",")||r.includes(`
21
+ `)||r.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(r)){let a=fe(r,"--type-option");tt(a,"--type-option",gO),o=a.key?.trim(),i=a.value?.trim()}else{let a=r.indexOf("="),s=r.indexOf(":"),c=a;if(a<=0&&s>0&&(c=s),c<=0||c===r.length-1)throw new d("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);o=r.slice(0,c).trim(),i=r.slice(c+1).trim()}if(!o||!i)throw new d("--type-option requires key and value",m.USAGE);t[o]=i}return Object.fromEntries(Object.entries(t).sort((n,r)=>n[0].localeCompare(r[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]="3ec13188-a9eb-5f37-84b6-6786571a9b13")}catch{}})();var wO=["strict","progressive"],vO=["lightweight"],Kv=new Set(["Reminder","Meeting","Event"]),bO=new Set(["author","created_at","text"]),gs=new Map(mh.map(e=>[e.optionKey,e.canonical]));function kO(e,t){let n=ae(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function SO(e,t){let n=e.default_status;if(n!==void 0){let r=ae(n,t);if(r)return r}return t.open_status}function Ad(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var EO=_a();function zv(e){if(pt(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i};so(t.template)&&(t.template=void 0);let r=new Set([...gs.keys(),"rank"]);for(let o of r){if(pt(e,o))continue;let i=t[o];if(typeof i!="string"||!so(i))continue;let a=o==="rank"?"order":gs.get(o)??o;n(a),t[o]=void 0}return le(e,ga(t,EO))}function Be(e){if(e!==void 0)return e}var jv=["id","kind","type","author","created_at","source_kind"],ys=["path","scope","note"];function AO(e,t,n,r){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(o=>{let i=o.trim(),a=ws(i,jv);Lo(i,a);let s=a?fe(o,"--dep"):{id:i,kind:"related"};a&&tt(s,"--dep",jv);let c=Be(s.id),l=TO(Be(s.kind??s.type));if(!c||!l)throw new d("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=uo(Be(s.source_kind)),u=Wn(s.author,"--dep author");return{id:fo(c,n,p),kind:kr(l),created_at:Ad(s.created_at,t),author:u??r,source_kind:p??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function TO(e){return typeof e=="string"?ot().resolve(e)?.kind??e.trim():e}function ws(e,t){return Xf(e,t)?!0:Hi(e)}function xn(e,t,n,r){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Fe(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(o=>{let i=o.trim(),a=()=>{if(i.length===0)throw new d(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:r,text:i}},s;try{s=fe(o,e)}catch(l){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw l}if(Object.keys(s).filter(l=>!bO.has(l)).length>0)return{created_at:Ad(s.created_at,n),author:Wn(s.author,`${e} author`)??r,text:i};let c=s.text??"";if(c==="")throw new d(`${e} requires text=<value>`,m.USAGE);return{created_at:Ad(s.created_at,n),author:Wn(s.author,`${e} author`)??r,text:c}}),explicitEmpty:!1})}function Td(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),r=ws(n,ys);Jc(n,"--file","file path",r);let o=r?fe(t,"--file"):{path:n};if(r&&tt(o,"--file",ys),!o.path)throw new d("--file requires path=<value> or a bare file path",m.USAGE);return{path:o.path,scope:it(o.scope??"project",kt,"file scope"),note:Be(o.note)}}),explicitEmpty:!1})}function Cd(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),r=ws(n,Ot);Jc(n,"--test","test command",r);let o=r?Wi(fe(t,"--test"),"--test"):{command:n},i=Be(o.command),a=Be(o.path);if(!i)throw new d("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let s=Be(o.timeout_seconds),c=Be(o.timeout);if(s&&c&&s!==c)throw new d("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let l=s??c;return{command:i,path:a,scope:it(o.scope??"project",kt,"test scope"),timeout_seconds:l?ge(l,"timeout_seconds"):void 0,pm_context_mode:Ya(o.pm_context_mode,"--test"),workspace_context_mode:Tn(o.workspace_context_mode,"--test"),env_set:To(o.env_set,"--test"),env_clear:Co(o.env_clear,"--test"),shared_host_safe:Va(o.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Cn(o.assert_stdout_contains),assert_stdout_regex:br(o.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Cn(o.assert_stderr_contains),assert_stderr_regex:br(o.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ja(o.assert_stdout_min_lines,"--test"),assert_json_field_equals:Xa(o.assert_json_field_equals,"--test"),assert_json_field_gte:Qa(o.assert_json_field_gte,"--test"),note:Be(o.note),phase:wr(o.phase,"--test")}}),explicitEmpty:!1})}function Id(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),r=ws(n,ys),o=r?fe(t,"--doc"):{path:n};if(r&&tt(o,"--doc",ys),!o.path)throw new d("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:o.path,scope:it(o.scope??"project",kt,"doc scope"),note:Be(o.note)}}),explicitEmpty:!1})}function CO(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--reminder","Use --clear-reminders to clear reminders."),{values:fs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function IO(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--event","Use --clear-events to clear linked events."),{values:_s(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function RO(e,t,n,r=[]){let o=[...Qo.filter(i=>e[i]!==void 0),...r.filter(i=>e[i]!==void 0),...t.length>0?["body"]:[],...n.map(i=>`unset:${i}`)];return Array.from(new Set(o))}function OO(e,t){let n=e??"";if(t.length===0)return n;let r=`explicit_unset=${t.join(",")}`;return n?`${n} | ${r}`:r}function Gv(e,t,n){let r=Nr("create",e);if(!r)throw new d(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return r}function xO(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function Hv(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function $O(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let r of e.required_create_fields)n.add(Gv(r,e.name,"required_create_fields"));for(let r of e.required_create_repeatables)n.add(Gv(r,e.name,"required_create_repeatables"));return n}function PO(e,t,n,r){for(let o of e)if(!(!Hv(t,o)&&!n.has(o)))throw new d(`Option ${xe("create",o)} is disabled for type "${r}" by command_option_policies`,m.USAGE)}function LO(e,t,n){if(t!=="strict")return;let r=e.filter(i=>n.has(i)&&!Sd(i));if(r.length===0)return;let o=[...new Set(r.map(i=>xe("create",i)))].sort((i,a)=>i.localeCompare(a));throw new d(`Strict create mode requires concrete values for ${o.join(", ")}; --unset cannot satisfy a required scalar option (only repeatable options accept an explicit --clear-* empty set)`,m.USAGE)}function NO(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Fe(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:hs(e),explicitEmpty:!1})}async function FO(e){return await Bi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function MO(e){return Rt(e)?await FO(e):e}function DO(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new d(`Invalid --create-mode value "${e}". Allowed: ${wO.join(", ")}`,m.USAGE)}function UO(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new d("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new d(`Invalid --schedule-preset value "${e}". Allowed: ${vO.join(", ")}`,m.USAGE)}function jO(e,t,n){let r=DO(e,n);if(t===void 0)return r;if(typeof e=="string"&&e.trim().length>0&&r==="strict")throw new d("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function GO(e,t,n,r,o,i){let a=e.name,s=xO(t),c=$O(e,n),l=Gn(e,"create",c);if(l.errors.length>0)throw new d(l.errors.join("; "),m.CONFLICT);PO(l.disabled,s,r,a),LO(l.required,n,r);let p=f=>f==="author"&&o!=="unknown"||f==="status"&&e.default_status!==void 0||i.has(f)||r.has(f)&&Sd(f)?!0:Hv(s,f),u=l.required.filter(f=>!p(f));return[...new Set(u.map(f=>xe("create",f)))].sort((f,h)=>f.localeCompare(h))}var Bv=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function qO(e,t){let n=[];for(let r of e){let o=r.match(Bv);o&&o[2]===t&&n.push(o[1])}return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}function KO(e,t){return e.filter(n=>{let r=n.match(Bv);return!r||r[2]!==t})}function zO(e,t,n,r){let o=KO(e,t);if(o.length===0)return;let i=Wv(n,[],[],r.open_status);throw new d(o.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[i],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function HO(e,t){let n=e.options.find(r=>r.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function BO(e,t,n){let r=e.split("/")[0];switch(r){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[r,'"<value>"']}}function Wv(e,t,n,r){let o=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],i=["--status","--priority","--message"],a=[...new Set([...i,...t])],s=new Set(["--title","--description","--type"]);for(let c of a){if(s.has(c))continue;let l=Yv[c];o.push(...l?[l]:BO(c,e.name,r)),s.add(c)}for(let c of n){let l=HO(e,c);o.push("--type-option",`${c}=${l}`)}return o.join(" ")}function Rd(e,t,n="cli"){let r=e?.trim();if(!r){let o=n==="sdk";throw t==="--title"?e!==void 0?new d(o?"Title cannot be empty or whitespace-only. Retry: pass a non-empty title.":"Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new d(o?'Missing required option title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass title (example: client.create({ type: "Issue", title: "Fix login bug" })).':'Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new d(`Missing required option ${o?Qn("sdk",t.replace(/^--/u,"")):t}`,m.USAGE)}return r}function WO(e,t,n){let r={};for(let[o,i]of Object.entries(e))r[o]=Array.isArray(i)?[...i]:i;for(let[o,i]of Object.entries(t))i!==void 0&&(r[o]=Array.isArray(i)?[...i]:i);return VO(r,t,n),le(t,r)}function VO(e,t,n){let r=[...kl(t.unset,n).optionKeys,...Sv(t.defer,n?.definitions)].flatMap(o=>o==="order"?[o,"rank"]:o==="tags"?[o,"addTags"]:[o]);for(let o of r)Reflect.get(t,o)===void 0&&Reflect.deleteProperty(e,o)}function YO(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function JO(){let e=R();return e?e.commands.some(t=>t.action==="templates-show"||YO(t.command)==="templates show"):!1}function XO(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new d(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let r={};for(let[o,i]of Object.entries(n)){if(typeof i=="string"||typeof i=="number"||typeof i=="boolean"){r[o]=i;continue}if(Array.isArray(i)&&i.every(a=>typeof a=="string")){r[o]=[...i];continue}throw new d(`Templates package returned unsupported option value for "${o}" in template "${t}".`,m.GENERIC_FAILURE)}return r}async function QO(e,t,n){if(!JO())throw new d("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let r=await Ui({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!r.handled)throw Object.hasOwn(r,"cause")?ua("templates show",r):new d(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.`,m.USAGE);return XO(r.result,e)}function V(e,t,n){return e.has(t)||n===void 0?void 0:Be(n)}function On(e,t,n,r){return e.has(t)||n===void 0?void 0:r(n)}var ZO=new Set(["milestone","meeting","reminder","event"]);function Vv(e,t,n,r){let o=t!==void 0,i=n!==void 0&&n.length>0,a=r!==void 0&&r.length>0;return ZO.has(e.toLowerCase())&&!o&&!i&&!a}function ex(e,t,n,r,o){let i=[];return e.toLowerCase()==="event"&&(o===void 0||o.length===0)&&i.push(`event_without_schedule:${t}:no_time_set`),Vv(e,n,r,o)&&i.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),i}async function tx(e,t,n,r){if(t.inheritFocus!==!0||e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let o=await Mi(r);return o===void 0?{parent:e,parentSource:void 0}:{parent:o,parentSource:"focus"}}async function nx(e,t,n,r,o,i,a){let s=cr(aa(o,a),t.id_prefix);if(Gi(s))return{parent:s,warnings:[]};if(ca(r,s,t.id_prefix,a),await K(e,s,t.id_prefix,t.item_format,n.type_to_folder))return{parent:s,warnings:[]};let c=Ne(s,t.id_prefix);return{parent:s,warnings:sa(c,i,a).warnings}}async function rx(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await nx(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy,e.audience)}async function ox(e){if(e.explicitId===void 0)return eo(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});gt(e.explicitId,"create","id");let t=e.explicitId.trim();if(t.length===0||I_(t))throw new d("--id must not be empty or use a placeholder token",m.USAGE);let n=Ne(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new d("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function qv(e,t,n,r,o,i){let a=V(e,t,n);if(a===void 0)return{value:void 0,warnings:[]};let s=la(r,a,o,i);return{value:s.value,warnings:s.warnings}}async function ix(e){let{pmRoot:t,settings:n,typeRegistry:r,statusRegistry:o,blockedBy:i,status:a,statusExplicit:s,nowValue:c,author:l}=e,p=e.dependencyValues;if(i===void 0)return{dependencyValues:p,status:a};let u=Ne(i,n.id_prefix),f=await K(t,u,n.id_prefix,n.item_format,r.type_to_folder);if(!f)return{dependencyValues:p,status:a};if((p??[]).some(_=>_.id===f.id&&_.kind==="blocked_by")||(p=[...p??[],{id:f.id,kind:"blocked_by",created_at:c,author:l,source_kind:"cli:create:blocked_by",author_source:"detected"}]),s)return{dependencyValues:p,status:a};let h=o.blocked_statuses.has("blocked")?"blocked":[...o.blocked_statuses].sort((_,g)=>_.localeCompare(g))[0]??o.open_status;return{dependencyValues:p,status:h}}function ax(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let r=t.governance.create_default_type?.trim();if(r&&r.length>0&&Te(r,n)){e.type=r;return}Te("Task",n)&&(e.type="Task")}function sx(e,t){return e.options.filter(n=>Nr("create",n.key)===void 0).flatMap(n=>{let r=t[n.key];if(r===void 0)return[];if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return[n];throw new d(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function cx(e,t,n,r,o){let i=e,a=[];if(i.template!==void 0){let _=i.template.trim();if(_.length===0)throw new d("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let g=await QO(_,t,n);i=zv(lo("create",WO(g,i,Qe(r.schema))))}if(i.type===void 0&&ax(i,r,o),i.type===void 0)throw new d("Missing required option --type <value>",m.USAGE);let s=Te(i.type,o);if(!s){let _=O_(i.type),g=_?Te(_,o):void 0;if(g)a.push(`type_coercion:${i.type.trim()}:${g}`),i.type=g,s=g;else throw new d(qt(i.type,o.types,Kt(n,r.schema)),m.USAGE)}let c=ti(s,o);if(!c)throw new d(`Invalid type value "${i.type}"`,m.USAGE);let l=c.name,p=sx(c,i),u=p.map(_=>`${_.key}=${String(i[_.key])}`);if(u.length>0){i.typeOption=[...u,...i.typeOption??[]];for(let _ of p)delete i[_.key]}let f=UO(i.schedulePreset);if(f!==void 0&&!Kv.has(l))throw new d(`--schedule-preset ${f} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let h=jO(i.createMode,f,r.governance.create_mode_default);return{resolvedOptions:i,typeDefinition:c,type:l,schedulePreset:f,createMode:h,warnings:a}}function lx(e,t){let n=new Set(t.metadataKeys),r=new Set(t.optionKeys),o=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let i of o)if(i.enabled){if(i.values&&i.values.length>0)throw new d(`Cannot combine ${i.clearFlag} with ${i.valueFlag}`,m.USAGE);n.add(i.metadataKey),r.add(i.optionKey)}return{explicitUnsets:n,clearOptionKeys:r}}function dx(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=gs.get(r)??r;throw new d(`Cannot combine --unset ${i} with ${xe("create",r)}`,m.USAGE)}}function mx(e){if(pt(e))return;let t=(n,r)=>{if(pt(e,r))return;let o=gs.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;ha(n,xe("create",r),i)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function px(e,t,n){for(let r of Object.keys(e))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let r of Object.keys(t.values??{}))if(n.metadataKeys.has(r))throw new d(`Cannot combine --unset ${r.replaceAll("_","-")} with its value flag`,m.USAGE)}var Yv={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function ux(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:r,missingRequiredTypeOptionKeys:o,openStatus:i,type:a,createMode:s,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let l=c.map(_=>{let g=_.type==="boolean"?"<true|false>":_.type==="array"?"<json-array>":_.type==="object"?"<json-object>":_.type==="number"?"<number>":_.type==="string_array"||_.repeatable?"<value>":"<string>";return{example:`--${_.cli_flag} ${g}`,description:`--${_.cli_flag} maps to ${_.metadata_key} (${_.type}${_.repeatable?", repeatable":""})`}}),p=[Wv(n,r,o,i),...l.map(_=>_.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(_=>_==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+").")];s==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),Kv.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),l.length>0&&u.push(`Required custom field formats: ${l.map(_=>_.description).join("; ")}.`);let f=[...new Set(t.flatMap(_=>{let g=_.split(" ",1)[0],y=Yv[g];return y?[y]:[]}))];f.length>0&&u.push(`If the truthful value is an empty collection, use ${f.join(", ")} instead of inventing metadata.`);let h=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new d(h,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...f.map(_=>`pm create --type ${a} ${_} ...`),p],nextSteps:u,recovery:s==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...f,...t,"--create-mode progressive"]}:void 0})}function fx(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?zt(t.tags):[];return er(n,t.addTags)}function _x(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new d("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,r=On(e,"order",n,o=>ge(o,"order"));if(r!==void 0&&!Number.isInteger(r))throw new d("Order must be an integer",m.USAGE);return r}function hx(e,t,n,r,o,i){if(r.completedAt!==void 0&&e!==t.close_status)throw new d("--completed-at requires a terminal create status.",m.USAGE);let a=e!==t.close_status?void 0:r.completedAt===void 0?i:te(r.completedAt,new Date(i),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let s=n.governance.require_close_reason?{explicit:r.closeReason??r.message,resolution:o}:{explicit:r.closeReason};return{closeReason:_d(s,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function gx(e){let{pmRoot:t,type:n,id:r,settings:o,typeRegistry:i,author:a,extensionFieldNames:s,afterDocument:c,beforeDocument:l,historyMessage:p,changedFields:u,nowValue:f,similarityCandidate:h,allowDuplicate:_}=e,g=Et(t,n,r,o.item_format,i.type_to_folder),y=Xe(t,r),w=ot(),v=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(x=>La(x.kind,w)),k=await ss({pmRoot:t,author:a,ttlSeconds:o.locks.ttl_seconds,waitMs:o.locks.wait_ms,required:v}),C=v,S=[];try{let x=await mt(t,r,o.locks.ttl_seconds,a,!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let N=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await ye(t,o.item_format,i.type_to_folder,void 0,o.schema):void 0,P=await K(t,r,o.id_prefix,o.item_format,i.type_to_folder);if(P)throw new d(`Item "${r}" already exists`,m.CONFLICT,{code:"item_already_exists",id:P.id,path:P.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${P.id}.`]});if(N){Na(N,[...N,c.metadata],w);let be=D(o.schema);Ea(N,[...N,c.metadata],r,Ae=>se(Ae,be),w)}let Y=await ro({pmRoot:t,settings:o,operation:"create",author:a,before:null,after:c});await fn({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,author:a,sdk:hn({pmRoot:t,settings:o,typeToFolder:i.type_to_folder})});let j=await Yt(t,a,{required:o.governance.duplicate_detection_mode==="strict"&&_!==!0}),pe=[];try{o.governance.duplicate_detection_mode==="strict"&&_!==!0&&await dr(h,{pmRoot:t,mode:"strict",threshold:o.governance.duplicate_detection_threshold,limit:o.governance.duplicate_detection_limit,allowDuplicate:!1}),await re(g,ft(c,{format:o.item_format,schema:o.schema,extensionFieldNames:s}));try{let be=Ke({nowIso:f,author:a,op:"create",before:l,after:c,message:p,context:Y.decisions.length===0?void 0:{workflow_policies:Y.decisions}});await Bt(y,be)}catch(be){throw await jn(g),be}C&&(await k(),C=!1),pe=await Jt({pmRoot:t,preferredFormat:o.item_format,typeToFolder:i.type_to_folder,schema:o.schema,itemPath:g,document:c})}finally{await j()}S=[...Y.warnings,...N?Pa(N,[...N,c.metadata],r):[],...pe,...await X({path:g,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:l,after:c,changed_fields:u}),...await X({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:l,after:c,changed_fields:u})],Yn({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:un(c.metadata,u),changed_fields:u})}finally{await x()}}finally{C&&await k()}return S}async function en(e,t){let n=lo("create",e),r=ut(n),o=zv(await MO(n)),i=T(process.cwd(),t.path);await O(i);let a=await E(i),s=D(a.schema),c=Qe(a.schema),l=$(a,R()),p=await cx(o,t,i,a,l);o=p.resolvedOptions;let{typeDefinition:u,type:f,createMode:h}=p,_=kl(o.unset,c),{explicitUnsets:g,clearOptionKeys:y}=lx(o,_);dx(o,_),mx(o);let w=bv(o,r);bd(w,o,_.metadataKeys,r);let v=I(Be(o.author),a.author_default),k=GO(u,o,h,y,v,w.optionKeys),C=A(),S=AO(o.dep,C,a.id_prefix,v),x=xn("--comment",o.comment,C,v),N=xn("--note",o.note,C,v),P=xn("--learning",o.learning,C,v),Y=Td(o.file),j=Cd(o.test);j.values=await pr(j.values,v,C);let pe=Id(o.doc),be=CO(o.reminder,C),Ae=IO(o.event,C),jt=NO(o.typeOption),q=Fr(f,jt.values,l),ue=R(),on=et(ue),an=Zo(o.field,ue,ps,us(c,"create",o)),lt=l_(o,c,f);bd(w,o,_.metadataKeys,r,lt.values),lt.missing_required_flags=Ev(lt.missing_required_flags,w,c.definitions,f,o);let Wo=new Set(lt.missing_required_flags),sn=c.definitions.filter(J=>Wo.has(`--${J.cli_flag}`));px(an,lt,_);let Or=qO(q.errors,f),ec=Or.map(J=>`--type-option ${J}=<value>`),tc=[...new Set([...k,...ec,...lt.missing_required_flags])].sort((J,dc)=>J.localeCompare(dc));ux({combinedMissingFlags:tc,typeDefinition:u,missingRequiredCreateFlags:k,missingRequiredTypeOptionKeys:Or,openStatus:s.open_status,type:f,createMode:h,missingRequiredRuntimeFields:sn}),zO(q.errors,f,u,s);let je=await ox({pmRoot:i,settings:a,typeRegistry:l,explicitId:o.id}),he=o.status!==void 0?kO(o.status,s):SO(u,s),cn=o.priority!==void 0?Vt(o.priority):2,F=_.metadataKeys,bt=fx(F,o),xr=On(F,"deadline",o.deadline,J=>te(J,new Date(C),"deadline")),Je=On(F,"estimated_minutes",o.estimatedMinutes,J=>tr(J,"estimated-minutes")),nc=V(F,"acceptance_criteria",o.acceptanceCriteria),Vo=V(F,"definition_of_ready",o.definitionOfReady),rc=_x(F,o),Yo=V(F,"goal",o.goal),TE=V(F,"objective",o.objective),CE=V(F,"value",o.value),IE=V(F,"impact",o.impact),RE=V(F,"outcome",o.outcome),OE=V(F,"why_now",o.whyNow),xE=V(F,"assignee",o.assignee),$E=F.has("author")?void 0:Be(o.author)??v,PE=V(F,"parent",o.parent),np=await tx(PE,o,F,i),oc=np.parent,LE=np.parentSource,NE=V(F,"reviewer",o.reviewer),FE=On(F,"risk",o.risk,J=>it(cs(J),$r,"risk")),ME=On(F,"confidence",o.confidence,J=>ds(J)),DE=o.allowMissingParent===!0&&a.validation.parent_reference==="strict_error"?"warn":a.validation.parent_reference,rp=a.validation.sprint_release_format,ln=[...p.warnings,...ex(f,je,xr,be.values,Ae.values)],op=await rx({itemId:je,parent:oc,pmRoot:i,settings:a,typeRegistry:l,policy:DE,audience:r});oc=op.parent,ln.push(...op.warnings);let ip=qv(F,"sprint",o.sprint,"sprint",rp,r),UE=ip.value;ln.push(...ip.warnings);let ap=qv(F,"release",o.release,"release",rp,r),jE=ap.value;ln.push(...ap.warnings);let sp=V(F,"blocked_by",o.blockedBy),cp=await ix({pmRoot:i,settings:a,typeRegistry:l,statusRegistry:s,blockedBy:sp,dependencyValues:S.values,status:he,statusExplicit:o.status!==void 0,nowValue:C,author:v}),ic=cp.dependencyValues;No(je,ic),ln.push(...await Rn({pmRoot:i,dependencies:ic,idPrefix:a.id_prefix,itemFormat:a.item_format,typeToFolder:l.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:je,createdAt:C}],schema:a.schema})),he=cp.status;let GE=V(F,"blocked_reason",o.blockedReason),qE=V(F,"unblock_note",o.unblockNote),KE=V(F,"reporter",o.reporter),zE=On(F,"severity",o.severity,J=>it(ls(J),Pr,"severity")),HE=V(F,"environment",o.environment),BE=V(F,"repro_steps",o.reproSteps),lp=V(F,"resolution",o.resolution),WE=V(F,"expected_result",o.expectedResult),VE=V(F,"actual_result",o.actualResult),YE=V(F,"affected_version",o.affectedVersion),JE=V(F,"fixed_version",o.fixedVersion),XE=V(F,"component",o.component),QE=On(F,"regression",o.regression,J=>ms(J)),ZE=V(F,"customer_impact",o.customerImpact),ac=Rd(o.title,"--title",r),sc=o.description??"",Jo=o.body??"",dp=await dr({title:ac,description:sc,body:Jo},{pmRoot:i,mode:a.governance.duplicate_detection_mode,threshold:a.governance.duplicate_detection_threshold,limit:a.governance.duplicate_detection_limit,allowDuplicate:o.allowDuplicate});ln.push(...Ta(dp));let cc=hx(he,s,a,o,lp,C),eA=cc.closeReason,tA=he===s.close_status?C:void 0,nA=cc.completedAt;ln.push(...cc.warnings);let Un=sl({id:je,title:ac,description:sc,type:f,type_options:q.normalized,status:he,closed_at:tA,completed_at:nA,close_reason:eA,priority:cn,tags:bt,created_at:C,updated_at:C,deadline:xr,assignee:xE,author:$E,estimated_minutes:Je,acceptance_criteria:nc,deferred_fields:kv(w),definition_of_ready:Vo,order:rc,goal:Yo,objective:TE,value:CE,impact:IE,outcome:RE,why_now:OE,parent:oc,reviewer:NE,risk:FE,confidence:ME,sprint:UE,release:jE,blocked_by:sp,blocked_reason:GE,unblock_note:qE,reporter:KE,severity:zE,environment:HE,repro_steps:BE,resolution:lp,expected_result:WE,actual_result:VE,affected_version:YE,fixed_version:JE,component:XE,regression:QE,customer_impact:ZE,dependencies:ic,comments:x.values,notes:N.values,learnings:P.values,files:Y.values,tests:j.values,docs:pe.values,reminders:be.values,events:Ae.values,...an,...lt.values});If(Un);try{ei(Un,ue)}catch(J){throw new d(J instanceof Error?J.message:"Invalid extension item field values",m.USAGE)}hl(Un,i);let rA=_t({metadata:Un,body:Jo},{schema:a.schema,extensionFieldNames:on}),oA={metadata:{},body:""},mp=[...g].sort((J,dc)=>J.localeCompare(dc)),iA=OO(o.message,mp),pp=RO(Un,Jo,mp,[...Object.keys(an),...Object.keys(lt.values??{})]),aA=await gx({pmRoot:i,type:f,id:je,settings:a,typeRegistry:l,author:v,extensionFieldNames:on,afterDocument:rA,beforeDocument:oA,historyMessage:iA,changedFields:pp,nowValue:C,similarityCandidate:{title:ac,description:sc,body:Jo},allowDuplicate:o.allowDuplicate}),lc=structuredClone(Un);h==="strict"&&g.has("dependencies")&&(lc.dependencies=[]);let sA=Rv(je,f,he,s);return Vv(f,xr,be.values,Ae.values)&&Gf(`[pm] warning: ${f} '${je}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${je} --deadline <ISO>' or 'pm update ${je} --event "start=<ISO>,end=<ISO>"'.`),{item:lc,changed_fields:pp,warnings:[...co("create",o,r==="sdk",lc),...ln,...aA],...Object.fromEntries([["parent_source",LE],["next_transition",sA],["similarity_advisory",dp]].filter(J=>J[1]!==void 0))}}import vs 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]="d29ab3a3-319f-506f-8289-78d786b95255")}catch{}})();async function Od(e,t,n){let r=T(process.cwd(),n.path);await O(r);let o=await E(r),i=I(t.author,o.author_default),a=await W_({pmRoot:r,settings:o,id:e,author:i,message:t.message,force:t.force,dryRun:t.dryRun}),s=a.targetPath?vs.relative(r,a.targetPath).split(vs.sep).join("/"):void 0;return{item:a.item,changed_fields:a.changedFields,dry_run:t.dryRun===!0,deleted:t.dryRun!==!0,outcome:t.dryRun===!0?"would_delete":"deleted",previous_status:a.item.status,...s?{target_path:s}:{},history_retained:vs.relative(r,Xe(r,a.item.id)).split(vs.sep).join("/"),tombstone_retention:"retain_append_only",warnings:a.warnings}}(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]="c7047beb-5c3a-5d97-acb9-7ddd15a223ec")}catch{}})();async function yx(e){await O(e)}async function xd(e,t,n){let r=T(process.cwd(),n.path);if(await yx(r),t.clear===!0){if(e!==void 0)throw new d("pm focus --clear does not take an item id. Use 'pm focus --clear' to clear focus or 'pm focus <id>' to set it.",m.USAGE);let p=await E(r),u=Vn(I(void 0,p.author_default));return await Tf(r),await Ml({pmRoot:r,settings:p,principal:u}),{action:"clear",focused_item:null,title:null,message:"Focus cleared. New items will not inherit a default parent."}}if(e===void 0){let p=await Mi(r);if(p===void 0)return{action:"show",focused_item:null,title:null,message:"No focus set. Use 'pm focus <id>' to set a default parent for new items."};let u=await wx(r,p);return{action:"show",focused_item:p,title:u,message:`Focused on ${p}${u?` (${u})`:""}. New items default --parent to it.`}}let o=await E(r),i=$(o,R()),a=await K(r,e,o.id_prefix,o.item_format,i.type_to_folder);if(!a)throw await rt(r,e,o.id_prefix,i.type_to_folder);let s=Ne(a.id,o.id_prefix),c=await ne(a,{schema:o.schema}),l=Jv(c.document.metadata.title);return await Af(r,s),await Ml({pmRoot:r,settings:o,principal:Vn(I(void 0,o.author_default)),itemId:s}),{action:"set",focused_item:s,title:l,message:`Focused on ${s}${l?` (${l})`:""}. New items default --parent to it (override with --parent or clear via 'pm focus --clear').`}}async function wx(e,t){let n=await E(e),r=$(n,R()),o=await K(e,t,n.id_prefix,n.item_format,r.type_to_folder);if(!o)return null;let i=await ne(o,{schema:n.schema});return Jv(i.document.metadata.title)}function Jv(e){return e.trim().length>0?e:null}(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]="d510588a-e45d-54ba-b9c0-153940bb6677")}catch{}})();var Xv="terminal_state_unchanged";function Qv(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function vx(e,t){return ae(e,t)===t.close_status}function bx(e){let t=n=>dh.includes(n.trim().toLowerCase());return ph(e.unset??[],t).some(t)}function Zv(e){!e.settings.governance.require_close_reason||!bx(e.options)||Po({explicit:e.options.closeReason},!0)}function $d(e,t,n,r=!1){if(!vx(e.status,n))return!1;let o=Qv(t.closeReason);return r&&t.closeReason!==void 0&&o===void 0||o!==void 0&&o!==Qv(e.close_reason)?!1:t.completedAt===void 0||te(t.completedAt,new Date,"completed-at")===e.completed_at}async function eb(e){let t=await K(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await rt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema});return n.metadata}async function tb(e,t,n,r,o){if(n.length===0)return{item:t,changed_fields:[],warnings:[...e.workflowTransitionWarnings,Xv]};let i=le(e.options,{...e.options,status:void 0,closeReason:void 0,completedAt:void 0}),a=await r(e.id,i,e.global);return $d(a.item,e.options,e.statusRegistry,e.settings.governance.require_close_reason)?{item:a.item,changed_fields:a.changed_fields,warnings:[...e.workflowTransitionWarnings,...a.warnings,Xv]}:o(a)}(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]="f5a434fe-8703-515c-b823-c8cd3589bbb0")}catch{}})();function bs(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",r=e.created_at?.trim()??"",o=Date.parse(r),i=Number.isFinite(o)?new Date(o).toISOString():r;return[e.id.trim().toLowerCase(),e.kind,t,n,i].join("\0")}function Pd(e,t){return!(t.id!==void 0&&e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function nb(e,t,n){let r=t.filter(o=>!e.some(i=>Pd(i,o)));if(r.length!==0)throw new d(`Dependency removal did not match ${r.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:r.map(o=>({...o,id:o.id??"*"})),available_dependencies:e.map(o=>({id:o.id,kind:o.kind,source_kind:o.source_kind,author:o.author,created_at:o.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function rb(e,t){if(!Array.isArray(e)||e.length===0)return;let n=i=>(Array.isArray(i)?i:[]).filter(a=>typeof a=="object"&&a!==null&&typeof a.id=="string"),r=new Map;for(let i of n(t)){let a=bs(i);r.set(a,(r.get(a)??0)+1)}let o=[];for(let i of n(e)){let a=bs(i),s=r.get(a)??0;s>0?r.set(a,s-1):o.push(`${i.id}/${i.kind}`)}return o.length>0?o.join(","):void 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]="fc1c1ca1-43e9-5019-bb3b-85b8972f090b")}catch{}})();var kx=(()=>{let e=new Map;for(let t of ya)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ks=new Map(ya.map(e=>[e.optionKey,e.canonical])),Sx=ya.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),Ex=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),Ax=_a({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function pb(e){if(pt(e))return e;let t={...e,unset:e.unset?[...e.unset]:void 0},n=o=>{let i=t.unset?[...t.unset]:[];i.includes(o)||i.push(o),t.unset=i},r=new Set([...ks.keys(),"rank"]);for(let o of r){if(pt(e,o))continue;let i=t[o];if(typeof i!="string"||!so(i))continue;let a=o==="rank"?"order":ks.get(o)??o;n(a),t[o]=void 0}return le(e,ga(t,Ax))}function Md(e,t,n,r=["update"]){return[...Dd([...e],t,n,r).metadataKeys]}function Dd(e,t,n=[],r=["update"]){return uh({raw:e,supportedFields:Sx,resolveDefinition:o=>{let i=n.find(a=>{let s=a.toLowerCase();return s===o||s.replaceAll("_","-")===o||s.replaceAll("-","_")===o});return kx.get(o)??r.map(a=>bl(o,a,t)).find(a=>a!==void 0)??(i?{optionKey:"field",metadataKey:i}:void 0)}})}var ob=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function ib(e){let t=e.disallowedFlags.flatMap(r=>{let o=ob.get(r);return o?[o(e.id)]:[]}),n=e.disallowedFlags.flatMap(r=>{let o=ob.get(r);return o?[`Replace ${r} with: ${o(e.id)}`]:[]});return new d(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function Tx(e,t,n){let r=t.ownershipMetadataBypass===!0,o=t.ownershipDependencyBypass===!0;if(!r&&!o)return;if(r&&o)throw new d("Choose only one package-provided ownership bypass mode.",m.USAGE);let i=(c,l,p)=>{c&&p.push(l)};if(o){let c=[];if(i(t.title!==void 0,"--title",c),i(t.description!==void 0,"--description",c),i(t.body!==void 0,"--body",c),i(t.status!==void 0,"--status",c),i(t.closeReason!==void 0,"--close-reason",c),i(t.priority!==void 0,"--priority",c),i(t.type!==void 0,"--type",c),i(t.tags!==void 0,"--tags",c),i(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),i(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),i(t.deadline!==void 0,"--deadline",c),i(t.estimatedMinutes!==void 0,"--estimate",c),i(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),i(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),i(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),i(t.definitionOfReady!==void 0,"--definition-of-ready",c),i(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),i(t.goal!==void 0,"--goal",c),i(t.objective!==void 0,"--objective",c),i(t.value!==void 0,"--value",c),i(t.impact!==void 0,"--impact",c),i(t.outcome!==void 0,"--outcome",c),i(t.whyNow!==void 0,"--why-now",c),i(t.assignee!==void 0,"--assignee",c),i(t.parent!==void 0,"--parent",c),i(t.reviewer!==void 0,"--reviewer",c),i(t.risk!==void 0,"--risk",c),i(t.confidence!==void 0,"--confidence",c),i(t.sprint!==void 0,"--sprint",c),i(t.release!==void 0,"--release",c),i(t.blockedBy!==void 0,"--blocked-by",c),i(t.blockedReason!==void 0,"--blocked-reason",c),i(t.unblockNote!==void 0,"--unblock-note",c),i(t.reporter!==void 0,"--reporter",c),i(t.severity!==void 0,"--severity",c),i(t.environment!==void 0,"--environment",c),i(t.reproSteps!==void 0,"--repro-steps",c),i(t.resolution!==void 0,"--resolution",c),i(t.expectedResult!==void 0,"--expected-result",c),i(t.actualResult!==void 0,"--actual-result",c),i(t.affectedVersion!==void 0,"--affected-version",c),i(t.fixedVersion!==void 0,"--fixed-version",c),i(t.component!==void 0,"--component",c),i(t.regression!==void 0,"--regression",c),i(t.customerImpact!==void 0,"--customer-impact",c),i(t.depRemove!==void 0,"--dep-remove",c),i(t.replaceDeps===!0,"--replace-deps",c),i(t.replaceTests===!0,"--replace-tests",c),i(t.replaceFiles===!0,"--replace-files",c),i(t.replaceDocs===!0,"--replace-docs",c),i(t.comment!==void 0,"--comment",c),i(t.note!==void 0,"--note",c),i(t.learning!==void 0,"--learning",c),i(t.file!==void 0,"--file",c),i(t.test!==void 0,"--test",c),i(t.doc!==void 0,"--doc",c),i(t.reminder!==void 0,"--reminder",c),i(t.event!==void 0,"--event",c),i(t.typeOption!==void 0,"--type-option",c),i(t.clearDeps===!0,"--clear-deps",c),i(t.clearComments===!0,"--clear-comments",c),i(t.clearNotes===!0,"--clear-notes",c),i(t.clearLearnings===!0,"--clear-learnings",c),i(t.clearFiles===!0,"--clear-files",c),i(t.clearTests===!0,"--clear-tests",c),i(t.clearDocs===!0,"--clear-docs",c),i(t.clearReminders===!0,"--clear-reminders",c),i(t.clearEvents===!0,"--clear-events",c),i(t.clearTypeOptions===!0,"--clear-type-options",c),i(t.force===!0,"--force",c),i(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new d("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw ib({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let a=[];i(t.status!==void 0,"--status",a),i(t.closeReason!==void 0,"--close-reason",a),i(t.assignee!==void 0,"--assignee",a),i(t.parent!==void 0,"--parent",a),i(t.blockedBy!==void 0,"--blocked-by",a),i(t.blockedReason!==void 0,"--blocked-reason",a),i(t.unblockNote!==void 0,"--unblock-note",a),i(t.dep!==void 0,"--dep",a),i(t.depRemove!==void 0,"--dep-remove",a),i(t.replaceDeps===!0,"--replace-deps",a),i(t.replaceTests===!0,"--replace-tests",a),i(t.replaceFiles===!0,"--replace-files",a),i(t.replaceDocs===!0,"--replace-docs",a),i(t.note!==void 0,"--note",a),i(t.learning!==void 0,"--learning",a),i(t.test!==void 0,"--test",a),i(t.reminder!==void 0,"--reminder",a),i(t.event!==void 0,"--event",a),i(t.clearDeps===!0,"--clear-deps",a),i(t.clearComments===!0,"--clear-comments",a),i(t.clearNotes===!0,"--clear-notes",a),i(t.clearLearnings===!0,"--clear-learnings",a),i(t.clearFiles===!0,"--clear-files",a),i(t.clearTests===!0,"--clear-tests",a),i(t.clearDocs===!0,"--clear-docs",a),i(t.clearReminders===!0,"--clear-reminders",a),i(t.clearEvents===!0,"--clear-events",a);let s=[...n].filter(c=>Ex.has(c)).sort((c,l)=>c.localeCompare(l)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...s),a.length>0)throw ib({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${a.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:a})}function Cx(e,t){let n=ae(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e,allowed:r})}return n}function Ix(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ub(e)}function ub(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new d(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function $n(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Rx=["id","kind","type","author","created_at","source_kind"],Ox=["id","kind","type","author","created_at","source_kind"];function fb(e){return e.startsWith("```")||e.includes(`
22
+ `)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Hi(e)}function Ud(e){return typeof e=="string"?ot().resolve(e)?.kind??e.trim():e}function Es(e,t,n,r){return e?(Fe(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(o=>{let i=o.trim(),a=fb(i);Lo(i,a);let s=a?fe(o,"--dep"):{id:i,kind:"related"};a&&tt(s,"--dep",Rx);let c=s.id?.trim(),l=Ud((s.kind??s.type)?.trim());if(!c||!l)throw new d("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new d(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let p=uo($n(s.source_kind)),u=$n(s.author);return{id:fo(c,t,p),kind:kr(l),created_at:Ix(s.created_at,n),author:u??r,source_kind:p??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function xx(e,t){return e?(Fe(e,"--dep-remove"),e.map(n=>{let r=n.trim();if(!r)throw new d("--dep-remove requires id or key/value selectors",m.USAGE);let o=fb(r);if(Lo(r,o,"--dep-remove"),o){let i=fe(r,"--dep-remove");tt(i,"--dep-remove",Ox);let a=i.id?.trim();if(i.id===void 0)return $x(i);if(!a)throw new d("--dep-remove key/value form requires a non-empty id=<value>",m.USAGE);if(a.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${a}"`,m.USAGE);let s=Ud($n(i.kind??i.type)),c=uo($n(i.source_kind)),l=$n(i.author),p=$n(i.created_at);return{id:fo(a,t,c),kind:s?kr(s):void 0,source_kind:c,author:l,created_at:p?ub(p):void 0}}if(r.toLowerCase()==="undefined")throw new d(`--dep-remove id must not use placeholder token "${r}"`,m.USAGE);return{id:Ne(r,t)}})):[]}function $x(e){let t=Ud($n(e.kind??e.type)),n=Object.keys(e).filter(r=>r!=="kind"&&r!=="type");if(!t||n.length>0||e.kind!==void 0&&e.type!==void 0)throw new d("--dep-remove key/value form requires id=<value>, or kind=<kind> alone to remove every row of that kind",m.USAGE);return{kind:kr(t)}}function Ss(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function Px(e,t,n,r,o){let i=[...e??[]],a=!1;if(t===void 0){let s=i.filter(c=>o===void 0||!zl(c,o.value,o.idPrefix));return s.length!==i.length&&(i=s,a=!0),a?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}return i.some(s=>s.kind==="blocked_by"&&s.id===t)||(i.push({id:t,kind:"blocked_by",created_at:n,author:r,source_kind:"cli:update:blocked_by",author_source:"detected"}),a=!0),a?{dependencies:i.length>0?i:void 0,changed:!0}:{dependencies:e,changed:!1}}async function Lx(e,t,n,r,o,i){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let s=await K(n,Ne(a,r),r,o,i);return s?{id:s.id}:{unresolved:a}}function Nx(e,t,n,r,o,i){let a=Px(e.dependencies,t,n,r,i);a.changed&&(a.dependencies===void 0?delete e.dependencies:e.dependencies=a.dependencies,o.includes("dependencies")||o.push("dependencies"))}function Fx(e){return`${e.path}::${e.scope}`}function Mx(e){return`${e.path}::${e.scope}`}function Dx(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function ab(e,t){let n=Nr("update",e);if(!n)throw new d(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function Ux(e,t,n){let r=new Set,o=(i,a)=>{a&&r.add(i)};if(o("title",e.title!==void 0),o("description",e.description!==void 0),o("body",e.body!==void 0),o("status",e.status!==void 0),o("closeReason",e.closeReason!==void 0),o("priority",e.priority!==void 0),o("type",e.type!==void 0),o("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),o("deadline",e.deadline!==void 0),o("estimatedMinutes",e.estimatedMinutes!==void 0),o("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),o("definitionOfReady",e.definitionOfReady!==void 0),o("order",e.order!==void 0||e.rank!==void 0),o("goal",e.goal!==void 0),o("objective",e.objective!==void 0),o("value",e.value!==void 0),o("impact",e.impact!==void 0),o("outcome",e.outcome!==void 0),o("whyNow",e.whyNow!==void 0),o("author",e.author!==void 0),o("message",e.message!==void 0),o("assignee",e.assignee!==void 0),o("parent",e.parent!==void 0),o("reviewer",e.reviewer!==void 0),o("risk",e.risk!==void 0),o("confidence",e.confidence!==void 0),o("sprint",e.sprint!==void 0),o("release",e.release!==void 0),o("blockedBy",e.blockedBy!==void 0),o("blockedReason",e.blockedReason!==void 0),o("unblockNote",e.unblockNote!==void 0),o("reporter",e.reporter!==void 0),o("severity",e.severity!==void 0),o("environment",e.environment!==void 0),o("reproSteps",e.reproSteps!==void 0),o("resolution",e.resolution!==void 0),o("expectedResult",e.expectedResult!==void 0),o("actualResult",e.actualResult!==void 0),o("affectedVersion",e.affectedVersion!==void 0),o("fixedVersion",e.fixedVersion!==void 0),o("component",e.component!==void 0),o("regression",e.regression!==void 0),o("customerImpact",e.customerImpact!==void 0),o("dep",e.dep!==void 0),o("depRemove",e.depRemove!==void 0),o("dep",e.replaceDeps===!0),o("comment",e.comment!==void 0),o("note",e.note!==void 0),o("learning",e.learning!==void 0),o("file",e.file!==void 0),o("test",e.test!==void 0),o("test",e.replaceTests===!0),o("file",e.replaceFiles===!0),o("doc",e.replaceDocs===!0),o("doc",e.doc!==void 0),o("reminder",e.reminder!==void 0),o("event",e.event!==void 0),o("typeOption",e.typeOption!==void 0),o("field",e.field!==void 0),o("force",e.force===!0),o("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),o("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),o("dep",e.clearDeps===!0),o("comment",e.clearComments===!0),o("note",e.clearNotes===!0),o("learning",e.clearLearnings===!0),o("file",e.clearFiles===!0),o("test",e.clearTests===!0),o("doc",e.clearDocs===!0),o("reminder",e.clearReminders===!0),o("event",e.clearEvents===!0),o("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let i=Dd(e.unset,t,n,e.runtimeFieldCommands);for(let a of i.optionKeys)o(a,!0)}return r}function jx(e,t,n,r,o){let i=ti(e,n);if(!i)throw new d(`Invalid type value "${e}"`,m.USAGE);let a=Gn(i,"update",[]);if(a.errors.length>0)throw new d(a.errors.join("; "),m.CONFLICT);let s=Ux(t,r,o);for(let c of a.disabled)if(s.has(ab(c,e)))throw new d(`Option ${xe("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of a.required)if(!s.has(ab(c,e)))throw new d(`Missing required option ${xe("update",c)} for type "${e}"`,m.USAGE)}var Gx=new Set(["order","rank"]),qx=Sc.filter(e=>!Gx.has(e)),_b=["tags","closeReason",...qx],Kx=["title","description","body","status","closeReason","completedAt","priority","type",...Sc,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],zx=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>te(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>tr(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],Hx=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>it(cs(e),$r,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>ds(e)}],Bx=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>it(ls(e),Pr,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>ms(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Fd(e,t,n){for(let r of e){let o=t[r.optionKey],i=n.clearItemMetadataKeys.has(r.metadataKey);if(!(o===void 0&&!i)){if(i){delete n.metadataRecord[r.metadataKey],n.changedFields.push(r.metadataKey);continue}if(typeof o!="string")throw new d(`${xe("update",String(r.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[r.metadataKey]=r.transform?r.transform(o,n):o.trim(),n.changedFields.push(r.metadataKey)}}}async function Wx(e){return pb(await Bi(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function jd(e){let t=lo("update",e);return Rt(t)?await Wx(t):pb(t)}function Vx(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function Ld(e){if(e.enabled&&(!e.values||e.values.length===0))throw new d(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new d(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function Gd(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new d("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new d("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new d("--replace-deps cannot be combined with --dep-remove",m.USAGE);Ld({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Ld({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Ld({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function Yx(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new d(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function Jx(e){let t={};for(let n of _b)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function Xx(e,t){let n=Jx(e);for(let[r,o]of Object.entries(n)){if(!o||!t.optionKeys.has(r))continue;let i=ks.get(r)??r;throw new d(`Cannot combine --unset ${i} with ${xe("update",r)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new d("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new d("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new d("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function Qx(e){if(pt(e))return;let t=(n,r)=>{if(pt(e,r))return;let o=ks.get(r),i=o?`Use --unset ${o} to clear this field.`:void 0;ha(n,xe("update",r),i)};for(let n of _b)t(e[n],String(n));t(e.order??e.rank,"order"),Fe(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Fe(e.event,"--event","Use --clear-events to clear linked events.")}function Zx(e,t){let n={};for(let r of Kx)n[String(r)]=e[r]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function e$(e){let t=await K(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await rt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function t$(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return ye(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function n$(e){e.before&&(Na(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Ea(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>se(t,e.statusRegistry),ot()))}function r$(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new d("--order and --rank must match when both are provided",m.USAGE)}async function o$(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=ut(e.options),n=cr(aa(e.options.parent,t),e.settings.id_prefix);if(Gi(n))return{resolvedParentValue:n,warnings:[]};if(ca(e.id,n,e.settings.id_prefix,t),await K(e.pmRoot,n,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:n,warnings:[]};let r=Ne(n,e.settings.id_prefix);return{resolvedParentValue:n,warnings:sa(r,e.parentReferencePolicy,t).warnings}}function i$(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function a$(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await K(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await rt(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await ne(t,{schema:e.settings.schema}),r=e.options.type!==void 0?Te(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",o=_r({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:r,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return o?[o]:[]}async function s$(e){if(!e.fieldFlags.status||ae(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;Zv(e);let t=Object.entries(e.fieldFlags).filter(([o,i])=>i&&o!=="status"&&o!=="closeReason"&&o!=="completedAt").map(([o])=>o),n=await eb(e);if($d(n,e.options,e.statusRegistry,e.settings.governance.require_close_reason))return tb(e,n,t,at,o=>sb(e,o));let r;if(t.length>0){let o=le(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0});r=await at(e.id,o,e.global)}return sb(e,r)}async function sb(e,t){let n=await Mt(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),r=[...co("update",e.options,ut(e.options)==="sdk",n.item),...e.workflowTransitionWarnings,...(t?.warnings??[]).filter(o=>!o.startsWith("literal_sentinel_stored:")),...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...t?.changed_fields??[],...n.changed_fields],warnings:r}}function c$(e,t,n,r){return t.title!==void 0&&(e.metadata.title=Rd(t.title,"--title",ut(t)),r.push("title")),t.description!==void 0&&(e.metadata.description=t.description,r.push("description")),t.body!==void 0&&(e.body=t.body,r.push("body")),ae(e.metadata.status,n)??e.metadata.status}var l$=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function d$(e,t){for(let n of l$)e[n]!==void 0&&(delete e[n],t.push(n))}function m$(e,t,n,r,o){let i=Cx(n,t.statusRegistry);if(e.metadata.status=i,o.push("status"),i===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,o.push("closed_at","completed_at");return}!se(i,t.statusRegistry)&&se(r,t.statusRegistry)&&d$(e.metadata,o)}function p$(e,t,n,r){if(t.options.status!==void 0&&m$(e,t,t.options.status,n,r),t.options.completedAt!==void 0){if(!se(e.metadata.status,t.statusRegistry))throw new d("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=te(t.options.completedAt,new Date(t.nowIso),"completed-at"),r.push("completed_at")}}function u$(e,t,n,r){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let o=t.options.closeReason?.trim()??"";if(o.length===0)throw new d(Yc(ut(t.options),"close-reason"),m.USAGE);e.metadata.close_reason=o}r.push("close_reason");return}t.options.status!==void 0&&se(n,t.statusRegistry)&&!se(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,r.push("close_reason"))}function f$(e,t,n,r){p$(e,t,n,r),u$(e,t,n,r)}function _$(e,t,n){let r=Te(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=Vt(t.options.priority),n.push("priority")),t.options.type!==void 0){let o=Te(t.options.type,t.typeRegistry);if(!o)throw new d(qt(t.options.type,t.typeRegistry.types,Kt(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=o,r=o,n.push("type")}return jx(r,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),h$(e,t,r,n),r}function h$(e,t,n,r){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let i=hs(t.options.typeOption??[]),a=Fr(n,i,t.typeRegistry);if(a.errors.length>0)throw new d(a.errors.join("; "),m.USAGE);e.metadata.type_options=a.normalized}r.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let o=Fr(n,e.metadata.type_options,t.typeRegistry);if(o.errors.length>0)throw new d(`Current type options are incompatible with type "${n}". ${o.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=o.normalized}function g$(e,t){let n=new Set(t.map(o=>Ss(o))),r=new Set;return e.filter(o=>{if(!n.has(Ss(o)))return!0;let i=bs(o);return r.has(i)?!1:(r.add(i),!0)})}function y$(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let r=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){r=g$(r,t.dependencyUpdates.additions);let o=new Set(r.map(i=>Ss(i)));for(let i of t.dependencyUpdates.additions){let a=Ss(i);o.has(a)||(r.push(i),o.add(a))}}t.dependencyRemovals.length>0&&(nb(r,t.dependencyRemovals,e.metadata.id),r=r.filter(o=>!t.dependencyRemovals.some(i=>Pd(o,i)))),r.length===0?delete e.metadata.dependencies:e.metadata.dependencies=r,n.push("dependencies")}function w$(e,t,n){Nd(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Nd(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Nd(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Nd(e,t,n,r,o,i){n===void 0&&!o.has(t)||(o.has(t)||!r||r.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...r],i.push(t))}function v$(e,t,n){cb(e,"files",t.options.file,t.fileUpdates.values,Fx,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),b$(e,t,n),cb(e,"docs",t.options.doc,t.docUpdates.values,Mx,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function cb(e,t,n,r,o,i,a,s){if(!(n===void 0&&!a.has(t))){if(i)e.metadata[t]=r;else if(a.has(t)||!r||r.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],l=new Set(c.map(p=>o(p)));for(let p of r){let u=o(p);l.has(u)||(c.push(p),l.add(u))}e.metadata[t]=c}s.push(t)}}function b$(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=lb(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=lb([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function lb(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let r of e){let o=Dx(r);n.has(o)||(t.push(r),n.add(o))}return t}function k$(e,t,n){let r=t.options.addTags,o=t.options.removeTags,i=Array.isArray(r)&&r.length>0||Array.isArray(o)&&o.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||i){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?zt(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=zi(er(a,r),o),n.changedFields.push("tags")}Fd(zx,t.options,n),E$(e,t,n.changedFields)}function S$(e,t,n){let r=t.options.addAc,o=t.options.removeAc;if(!(Array.isArray(r)&&r.length>0)&&!(Array.isArray(o)&&o.length>0))return;let i=Ki(Zn(e.metadata.acceptance_criteria),r,o);if(i.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${i.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:i.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let a=i.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function E$(e,t,n){let r=t.options.order??t.options.rank;if(!(r===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let o=ge(r??"","order");if(!Number.isInteger(o))throw new d("Order must be an integer",m.USAGE);e.metadata.order=o}n.push("order")}}function A$(e,t,n,r){T$(e,t,n.changedFields),C$(e,t,n.changedFields),Fd(Hx,t.options,n),db(e,t,"sprint",r,n.changedFields),db(e,t,"release",r,n.changedFields),I$(e,t,n.changedFields),Fd(Bx,t.options,n)}function T$(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let r=t.options.assignee?.trim()??"";if(r==="")throw new d(Yc(ut(t.options),"assignee",". Use --unset assignee to clear it."),m.USAGE);Cf(r,"--assignee"),e.metadata.assignee=r}n.push("assignee")}}function C$(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function db(e,t,n,r,o){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let i=la(n,t.options[n]??"",t.settings.validation.sprint_release_format,ut(t.options));e.metadata[n]=i.value,r.push(...i.warnings)}o.push(n)}}function I$(e,t,n){if(t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by"))return;let r=t.clearItemMetadataKeys.has("blocked_by")?e.metadata.blocked_by:void 0;t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&Nx(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n,{value:r,idPrefix:t.settings.id_prefix})}function R$(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=fs(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=_s(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function O$(e,t,n){mb(e,t.runtimeFieldRegistry.definitions.map(o=>o.metadata_key),t.clearItemMetadataKeys,n),mb(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[o,i]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(o)){let a=o.replaceAll("_","-"),s=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===o)?.cli_flag??a;throw new d(`Cannot combine --unset ${a} with --${s}`,m.USAGE)}ie(e[o],i)||(e[o]=i,n.push(o))}let r=Zo(t.options.field,t.extensionRegistrations,ps,us(t.runtimeFieldRegistry,(t.options.runtimeFieldCommands??[]).includes("update_many")?"update_many":"update",t.options));for(let o of Object.keys(r))if(t.clearItemMetadataKeys.has(o))throw new d(`Cannot combine --unset ${o.replaceAll("_","-")} with --field ${o}=...`,m.USAGE);for(let[o,i]of Object.entries(r))ie(e[o],i)||(e[o]=i,n.push(o))}function mb(e,t,n,r){for(let o of t)!n.has(o)||e[o]===void 0||(delete e[o],r.push(o))}function x$(e,t){if(t===void 0)return;let n=e.metadata,r=["comments","notes","learnings"].find(o=>{let i=t[o];return i!==void 0&&(!Array.isArray(i)||!ie(i,n[o]??[]))});if(r!==void 0)throw new d(`Full-item --stdin-json update changed persisted ${r}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${r}_requires_annotation_command`,required:`Use pm ${r} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${r} with pm ${r} ${e.metadata.id}.`,`Apply the correction with pm ${r} ${e.metadata.id} --edit <index> --add <text>.`]})}function $$(e,t){x$(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),r=e.body,o=[],i=[],a=c$(e,t.options,t.statusRegistry,o),s=e.metadata,c={metadataRecord:s,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:o,nowValue:t.nowValue};f$(e,t,a,o),_$(e,t,o),y$(e,t,o),w$(e,t,o),v$(e,t,o),k$(e,t,c),S$(e,t,c),A$(e,t,c,i),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&No(e.metadata.id,e.metadata.dependencies),ae(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,o.includes("assignee")||o.push("assignee")),R$(e,t,o),O$(s,t,o);try{ei(s,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(f){throw new d(f instanceof Error?f.message:"Invalid extension item field values",m.USAGE)}let l=e.metadata,p=[...new Set(o)].filter(f=>f==="body"?e.body!==r:!ie(n[f],l[f])),u=rb(n.dependencies,l.dependencies);return u!==void 0&&i.push(`dependencies_removed:${e.metadata.id}:${u}`),t.options.acceptanceCriteria!==void 0&&p.includes("acceptance_criteria")&&i.push(`acceptance_criteria_replaced:${Zn(n.acceptance_criteria).length}:${Zn(l.acceptance_criteria).length}`),{changedFields:p,warnings:i}}async function hb(e,t,n,r={}){gt(e,"update","id");let o=await jd(t),i=T(process.cwd(),n.path);await O(i);let a=await E(i),s=D(a.schema),c=Qe(a.schema),l=R(),p=et(l),u=$(a,l),f=a.governance.workflow_enforcement??"off",h=f==="off"?[]:Hn(a.schema),_=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(o.allowMissingParent===!0)][a.validation.parent_reference],g=Dd(o.unset,c,p,o.runtimeFieldCommands),y=new Set(g.optionKeys),w=new Set(g.metadataKeys);Gd(o),Yx({definitions:Vx(o),options:o,clearOptionKeys:y,clearItemMetadataKeys:w}),Tx(e,o,w),Xx(o,g),Qx(o);let v=I(o.author,a.author_default),k=new Date,C=k.toISOString(),S=Es(o.dep,a.id_prefix,C,v);No(e,S.additions);let x=await Rn({pmRoot:i,dependencies:S.additions,idPrefix:a.id_prefix,itemFormat:a.item_format,typeToFolder:u.type_to_folder,allowUnresolved:o.allowUnresolvedDeps,holders:[{id:e}],schema:a.schema}),N=xx(o.depRemove,a.id_prefix),P=xn("--comment",o.comment,C,v),Y=o.ownershipMetadataBypass===!0&&P.values?{...P,values:P.values.map(he=>({...he,author:v}))}:P,j=xn("--note",o.note,C,v),pe=xn("--learning",o.learning,C,v),be=Td(o.file),Ae=Cd(o.test);Ae.values=await pr(Ae.values,v,C);let jt=Id(o.doc),q=[],ue=await o$({id:e,options:o,unsetTargets:g,pmRoot:i,settings:a,typeRegistry:u,parentReferencePolicy:_}),on=await Lx(o.blockedBy,w.has("blocked_by"),i,a.id_prefix,a.item_format,u.type_to_folder),an=on.id,lt=[...ue.warnings,...i$(on)],Wo=ta(o,c,o.runtimeFieldCommands),sn=Zx(o,Wo);if(!Object.values(sn).some(Boolean))return e$({pmRoot:i,id:e,settings:a,typeRegistry:u});q.push(...await a$({options:o,fieldFlags:sn,workflowEnforcement:f,typeWorkflows:h,statusRegistry:s,typeRegistry:u,pmRoot:i,id:e,settings:a}));let Or=await s$({options:o,fieldFlags:sn,statusRegistry:s,workflowTransitionWarnings:q,global:n,id:e,pmRoot:i,settings:a,typeRegistry:u});if(Or)return Or;r$(o);let ec=ot(),tc=sn.parent&&!w.has("parent")||S.additions.some(he=>La(he.kind,ec)),je=await ss({pmRoot:i,author:v,ttlSeconds:a.locks.ttl_seconds,waitMs:a.locks.wait_ms,required:tc});try{let he=await t$({fieldFlags:sn,clearedMetadataKeys:w,pmRoot:i,settings:a,typeToFolder:u.type_to_folder}),cn,F,bt=await ir({pmRoot:i,settings:a,typeToFolder:u.type_to_folder,id:e,op:P$(o,r),author:v,message:o.message,resolveHistoryContext:()=>F,force:o.force,bypassAssigneeConflict:o.ownershipMetadataBypass===!0||o.ownershipDependencyBypass===!0,extensionFieldNames:p,skipNoop:!0,async mutate(Je){let nc=Je.metadata.status;cn=L$({document:Je,recurrenceReason:r.recurrenceReason,requestedStatus:o.status,statusRegistry:s}),F=cn?{recurrence:cn}:void 0,he=he?.map(Yo=>Yo.id===Je.metadata.id?structuredClone(Je.metadata):Yo);let Vo=$$(Je,{options:o,settings:a,typeRegistry:u,statusRegistry:s,runtimeFieldRegistry:c,extensionRegistrations:l,extensionFieldNames:p,clearItemMetadataKeys:w,dependencyUpdates:S,dependencyRemovals:N,commentUpdates:Y,noteUpdates:j,learningUpdates:pe,fileUpdates:be,testUpdates:Ae,docUpdates:jt,resolvedParentValue:ue.resolvedParentValue,resolvedBlockedByDependencyId:an,runtimeFieldUpdates:Wo,nowValue:k,nowIso:C,author:v,pmRoot:i});n$({before:he,document:Je,statusRegistry:s});let rc=await Ka({pmRoot:i,settings:a,metadata:Je.metadata,fromStatus:nc,registry:s,force:o.force===!0});return{...Vo,warnings:[...Vo.warnings,...rc]}}});await je();let xr=he?Pa(he,he.map(Je=>Je.id===bt.item.id?bt.item:Je),bt.item.id):[];return{item:bt.item,changed_fields:bt.changedFields,warnings:[...co("update",o,ut(o)==="sdk",bt.item),...q,...lt,...x,...xr,...bt.warnings],...cn===void 0?{}:{lifecycle_transition:cn}}}finally{await je()}}function P$(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function L$(e){if(e.recurrenceReason===void 0)return;let t=ae(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!se(t,e.statusRegistry))throw new d(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,r=ae(n,e.statusRegistry)??n,o=e.document.metadata,i=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let s=o[a];return typeof s=="string"?[[a,s]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:r,previous_terminal:i}}async function at(e,t,n){return hb(e,t,n)}async function gb(e,t,n,r){gt(r,"reopen","reason");let o=await hb(e,t,n,{recurrenceReason:r});if(o.lifecycle_transition===void 0)throw new d(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...o,lifecycle_transition:o.lifecycle_transition}}(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]="72dfe5b1-a1dd-573a-9f38-e66bf4e88100")}catch{}})();async function qd(e,t,n,r){gt(e,"reopen","id"),gt(t,"reopen","reason"),hh(n);let o=t.trim();if(o.length===0)throw new d("pm item reopen requires a non-empty recurrence reason.",m.USAGE,{code:"reopen_reason_required",required:"Describe why the terminal work became active again.",recovery:{suggested_retry:`pm item reopen ${e} "<recurrence reason>"`,suggested_retry_args:["item","reopen",e,"<recurrence reason>"]}});let i=T(process.cwd(),r.path),a=n.expectedResult?.trim();if(a!==void 0&&a.length===0)throw new d("Reopen expected result must describe the current active outcome.",m.USAGE);let s=D((await E(i)).schema),c=s.open_status,l=Lt(s),p=n.status??c,u=ae(p,s)??p;if(u!==c&&u!==l)throw new d(`Reopen target status must be ${c} or ${l}; received ${p}.`,m.USAGE,{code:"reopen_target_status_invalid",required:"Choose the workspace open or in-progress lifecycle status.",recovery:{allowed_values:[...new Set([c,l])],suggested_retry:`pm item reopen ${e} "${o}" --status ${c}`,suggested_retry_args:["item","reopen",e,o,"--status",c]}});let f=await gb(e,{status:u,expectedResult:a,unset:["close-reason","resolution",...a===void 0?["expected-result"]:[],"actual-result","fixed-version"],author:n.author,message:n.message,force:n.force},r,o);return{item:f.item,changed_fields:f.changed_fields,warnings:f.warnings,recurrence:f.lifecycle_transition,...a===void 0?{recovery:{missing:["expected_result"],suggested_retry_args:["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"],suggested_retry:L(["--pm-path",i,"update",e,"--expected-result","<current expected outcome>"])}}:{}}}(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]="35d9d28d-68f5-5a6d-b3e8-02424b81a4d4")}catch{}})();async function Kd(e,t,n){try{return await n()}catch(r){let o=r instanceof d?r.context:{},i=new d(r instanceof Error?r.message:String(r),r instanceof d?r.exitCode:m.GENERIC_FAILURE,{...o,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${o.why?` ${o.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...o.nextSteps??[]]});throw i.cause=r,i}}async function zd(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new d("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let r=await E(T(process.cwd(),n.path)),o=Lt(D(r.schema));return Ty(async()=>{let i=await Eo(e,t.force===!0,n,yt(t,{},["start"])),a=i.item.id,s=await Kd(a,"claim",()=>at(a,yt(t,{status:o},["assignee","start","next","ifAvailable","maxAttempts"]),n)).catch(async c=>{throw await N$(c,i,n,t.author)});return{id:a,action:"start_task",claim:i,update:s}})}async function N$(e,t,n,r){if(!(e instanceof d)||e.code!==qa||t.previous_assignee!==null)return e;let o=String(t.item.id);try{await F_({pmRoot:T(process.cwd(),n.path),id:o,validate:a=>{if(a.metadata.assignee!==t.claimed_by||a.metadata.claim_principal!==t.item.claim_principal)throw new d("The claim this start took is no longer its own.",m.CONFLICT)}},()=>gr(o,!1,n,{author:r,message:"Release the claim: a blocker opened before its start could be recorded"}))}catch{return e}let i=e.cause instanceof d?e.cause:e;return new d(i.message,i.exitCode,{...i.context,why:`${i.context.why??""} A blocker opened after this start's claim, so the claim was released and no ownership remains.`.trim()})}async function Hd(e,t,n){let r=await E(T(process.cwd(),n.path)),o=D(r.schema);ja({...t,pause:!0},o);let i=o.open_status,a=await at(e,yt(t,{status:i},["assignee","pause"]),n),s=a.item.id,c=await Kd(s,"update",()=>gr(s,t.force===!0,n,t));return{id:s,action:"pause_task",update:a,release:c}}async function Bd(e,t,n,r){let o=await Mt(e,t,n,r),i=o.item.id,a=await Kd(i,"close",()=>gr(i,n.force===!0,r,n));return{id:i,action:"close_task",close:o,release:a}}(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]="513b9fa5-5887-5d96-a137-ddf961f37dc8")}catch{}})();async function yb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=e.force===!0||r.force===!0,i={...e.args,...r},a=r.next===!0,s=e.id??b(r,"id");if(i.start===!0){if(s)return Pn(e,"start_task");Py(s,a,!0)}let c=a?await Ly(o,e.global,i,i):await Eo(Fo(e,r),o,e.global,i);return Ie(c,{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function Fo(e,t){let n=e.id??b(t,"id");if(!n)throw new d("Missing required argument: id",64);return n}function Wd(e,t){return b(e.args,"reason")??b(e.args,"text")??b(t,"reason")??b(t,"text")}async function wb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return r.releaseAssignment===!0?Pn(e,"close_task"):Ie(await Mt(Fo(e,r),Wd(e,r),{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function Pn(e,t){let{changedFields:n,idOnly:r,runnerOptions:o}=we(e.args,e.options),i=Fo(e,o),a=yt(o,{force:e.force===!0||o.force===!0}),s=t==="start_task"?await zd(i,a,e.global):t==="pause_task"?await Hd(i,a,e.global):await Bd(i,Wd(e,o),a,e.global);return Ie(s,{changedFields:n,idOnly:r,compactEnvelope:n==="compact"&&!r})}async function vb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=yt(r,{message:b(Object.hasOwn(r,"message")?r:e.args,"message")});if(o.pause===!0)return Pn({...e,options:o},"pause_task");let i=await gr(Fo(e,o),e.force===!0||o.force===!0,e.global,o);return Ie(i,{changedFields:t,idOnly:n,compactEnvelope:t==="compact"&&!n})}async function bb(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ie(await qd(Fo(e,r),Wd(e,r)??"",{...r,force:e.force===!0||r.force===!0},e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly: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]="0a610a47-2af8-51b7-a8ab-2557eaf611e2")}catch{}})();function As(e,t){let n=L(["plan","show",e.plan.id,"--depth","deep",...t===void 0?[]:["--pm-path",t]]);return{kind:"plan_mutation",action:e.action,id:e.plan.id,status:e.plan.status,mode:e.plan.mode,steps_summary:e.plan.steps_summary,...e.step===void 0?{}:{step:{id:e.step.id,order:e.step.order,status:e.step.status}},materialized_count:e.materialized?.length??0,skipped_count:e.materialize_skipped?.length??0,warning_count:e.warnings.length,warnings:e.warnings.slice(0,3).map(r=>r.slice(0,160)),warnings_truncated:e.warnings.length>3||e.warnings.some(r=>r.length>160),next_action:e.next_actions?.[0]===void 0?n:t===void 0?e.next_actions[0]:`${e.next_actions[0]} --pm-path ${Sf(t)}`,inspection_command:n,omission_receipt:{has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with: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]="caead750-d1ce-5727-a028-5d310494f6ea")}catch{}})();var F$=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Eb="plan-step-",Zd="draft",Qd=["bug-investigation","feature-implementation","refactoring-sprint"],kb={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function M$(e){let t=e.trim().toLowerCase(),n=Object.prototype.hasOwnProperty.call(kb,t)?kb[t]:void 0;if(!n)throw new d(`Unknown plan template "${e}". Allowed: ${Qd.join(", ")}`,m.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${Qd[0]}`]});return n.map(r=>({...r}))}function D$(e,t){return t>0?Math.round(e/t*100):0}function Ab(e){return(Array.isArray(e)?e:e==null?[]:[e]).filter(t=>t!=null).map(t=>(typeof t=="string"?t:String(t)).trim()).filter(t=>t.length>0)}function Ze(e){return Array.isArray(e)?e.flatMap(t=>ar(t,{unique:!1})):typeof e=="string"&&e.trim().length>0?ar(e,{unique:!1}):[]}function De(e){return Array.isArray(e)?e.map(t=>t.trim()).filter(Boolean):typeof e=="string"&&e.trim().length>0?[e.trim()]:[]}function Tb(e,t=Zd){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=hc.find(o=>o===n);if(!r)throw new d(`Invalid plan mode "${e}". Allowed: ${hc.join(", ")}`,m.USAGE);return r}function em(e,t="pending"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=gc.find(o=>o===n);if(!r)throw new d(`Invalid step status "${e}". Allowed: ${gc.join(", ")}`,m.USAGE);return r}function Cb(e,t="related"){if(e===void 0)return t;let n=e.trim().toLowerCase(),r=wc.find(o=>o===n);if(!r)throw new d(`Invalid step link kind "${e}". Allowed: ${wc.join(", ")}`,m.USAGE);return r}function U$(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)return;let n=yc.find(r=>r===t);if(!n)throw new d(`Invalid plan harness "${e}". Allowed: ${yc.join(", ")}`,m.USAGE);return n}function j$(e){if(e===void 0)return"brief";let t=e.trim().toLowerCase(),n=Ic.find(r=>r===t);if(!n)throw new d(`Invalid --depth "${e}". Allowed: ${Ic.join(", ")}`,m.USAGE);return n}function G$(e){if(e===void 0)return null;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new d("Plan --fields requires a comma-separated list of plan field names",m.USAGE);return t}var Vd=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function q$(e,t){let n=e,r={},o=[];for(let i of t){let a=i.startsWith("plan.")?i.slice(5):i;if(a.length!==0){if(!Vd.has(a)){o.push(i);continue}Object.prototype.hasOwnProperty.call(n,a)&&(r[a]=n[a])}}if(o.length>0)throw new d(`Unknown Plan --fields value(s): ${o.join(", ")}`,m.USAGE,{nextSteps:[`Use --fields ${[...Vd].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:o,suggested_retry:`pm plan show <id> --fields ${[...Vd].join(",")}`}});return r}function tm(e,t){let n={};for(let r of e.split(",")){let o=r.trim();if(o.length===0)continue;let i=o.indexOf("=");if(i<=0)throw new d(`Invalid ${t} entry "${o}"; expected key=value`,m.USAGE,{code:"malformed_plan_step_evidence",required:`${t} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']});n[o.slice(0,i).trim().toLowerCase()]=o.slice(i+1).trim()}return n}function nm(e){let t=tm(e,"--file");if(!t.path)throw new d("--file requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function rm(e){let t=tm(e,"--test");if(!t.command&&!t.path)throw new d("--test requires at least command=<value> or path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."});let n={};return t.command&&(n.command=t.command),t.path&&(n.path=t.path),t.note&&(n.note=t.note),n}function om(e){let t=tm(e,"--doc");if(!t.path)throw new d("--doc requires path=<value>",m.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."});let n={path:t.path};return(t.scope==="global"||t.scope==="project")&&(n.scope=t.scope),t.note&&(n.note=t.note),n}function K$(e){let t={total:e.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(let n of e)t[n.status]+=1;return t.completion_pct=D$(t.completed,t.total),t}function z$(e){let t=new Set(e.map(n=>n.id));for(let n=e.length+1;n<e.length+1024;n+=1){let r=`${Eb}${String(n).padStart(3,"0")}`;if(!t.has(r))return r}throw new d("Could not allocate step id (limit reached)",m.GENERIC_FAILURE)}function Sr(e,t){let n=t.trim();if(n.length===0)throw new d("Step reference cannot be empty",m.USAGE);let r=e.find(o=>o.id===n);if(r)return r;if(/^\d+$/.test(n)){let o=Number.parseInt(n,10),i=e.find(a=>a.order===o);if(i)return i}throw new d(`Step "${t}" not found in plan`,m.NOT_FOUND)}function Sb(e){if(e.status==="completed")return{reason:"already_completed"};let t=(e.linked_items??[]).find(n=>n.kind==="implements");if(t)return{reason:"already_materialized",existing_id:t.id}}function H$(e,t){let n=t.filter(a=>a.trim().toLowerCase()==="all"),r=[],o=[];if(n.length>0){if(t.length>n.length)throw new d("pm plan materialize --steps all cannot be combined with other step refs",m.USAGE);for(let a of e.slice().sort((s,c)=>s.order-c.order)){let s=Sb(a);if(s){o.push({from_step:a.id,...s});continue}r.push(a)}return{targets:r,skipped:o}}let i=new Set;for(let a of t){let s=Sr(e,a);if(i.has(s.id))continue;i.add(s.id);let c=Sb(s);if(c){o.push({from_step:s.id,...c});continue}r.push(s)}return{targets:r,skipped:o}}function B$(e,t){let n=e==="decision"?t.decisionText:e==="discovery"?t.discoveryText:t.validationText,r=e==="decision"?t.decision:e==="discovery"?t.discovery:t.validation;return n?.trim()||r?.trim()||void 0}function W$(e){return e.find(t=>t.status==="in_progress")??e.find(t=>t.status==="pending")}function V$(e){return e.filter(t=>t.status==="blocked").map(t=>({id:t.id,order:t.order,title:t.title,blocked_reason:t.blocked_reason}))}function We(e,t="brief"){let n=(e.plan_steps??[]).slice().sort((a,s)=>a.order-s.order),r=K$(n),o=W$(n),i={id:e.id,title:e.title,status:e.status,mode:e.plan_mode??Zd,scope:e.plan_scope,harness:e.plan_harness,parent:e.parent,resume_context:e.plan_resume_context,steps_summary:r,current_step:o?{id:o.id,order:o.order,title:o.title,status:o.status}:void 0,blocked_steps:V$(n),linked_items:(e.dependencies??[]).map(a=>({id:a.id,kind:a.kind}))};return(t==="standard"||t==="deep")&&(i.steps=n),t==="deep"&&(i.decisions=e.plan_decisions??[],i.discoveries=e.plan_discoveries??[],i.validation=e.plan_validation??[]),i}function Ve(e,t){let n=[];return t.steps_summary.total===0&&n.push(`pm plan add-step ${e} --step-title "First step"`),t.current_step&&n.push(`pm plan update-step ${e} ${t.current_step.id} --step-status in_progress`,`pm plan complete-step ${e} ${t.current_step.id} --step-evidence "..."`),t.steps_summary.blocked>0&&n.push(`pm plan show ${e} --depth standard`),(t.mode==="draft"||t.mode==="research")&&n.push(`pm plan approve ${e} --message "ready to execute"`),t.steps_summary.completed===t.steps_summary.total&&t.steps_summary.total>0&&!yl(t.mode)&&t.status!=="closed"&&t.status!=="canceled"&&n.push(`pm close ${e} "plan complete"`),n}function Ib(e){if((e.type??"").trim().toLowerCase()!=="plan")throw new d(`Item ${e.id} is type ${e.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,m.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${e.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}async function Y$(e){let t=T(process.cwd(),e.path);await O(t);let n=await E(t);return{pmRoot:t,settings:n}}async function Rb(e,t){let n=$(e.settings,R()),r=await K(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,n.type_to_folder);if(!r)throw new d(`Plan ${t} not found`,m.NOT_FOUND);let o=await ne(r,{schema:e.settings.schema});return Ib(o.document.metadata),{document:o.document,itemId:r.id}}function J$(e){let t=[];for(let n of Ze(e.related))t.push(`id=${n},kind=related`);for(let n of Ze(e.blocks))t.push(`id=${n},kind=blocks`);for(let n of Ze(e.blockedBy))t.push(`id=${n},kind=blocked_by`);return t.length>0?t:void 0}function X$(e){let t=e.validationText?.trim(),n=e.validationCommand?.trim(),r=e.validationExpected?.trim();if(!(!t&&!n&&!r))return{text:t||n||"Validation check",command:n||void 0,expected:r||void 0}}function Q$(e){return!!e.stepBody?.trim()||!!e.stepOwner?.trim()||!!e.stepStatus?.trim()||!!e.stepEvidence?.trim()||!!e.stepBlockedReason?.trim()||!!e.stepReplacement?.trim()||Ze(e.dependsOn).length>0||Ze(e.link).length>0}function Z$(e){let t=e.stepTitle?.trim()||void 0,n=Ab(e.step),r=e.template?.trim()?M$(e.template):[];return{repeatedStepTitles:n,stepTitleFlag:t,stepTitles:[...t?[t]:[],...n,...r.map(o=>o.title)],templateSteps:r}}function eP(e,t){if((e.stepTitleFlag||e.repeatedStepTitles.length>0)&&e.templateSteps.length>0)throw new d("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",m.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${Qd[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']});if(e.stepTitles.length>1&&t)throw new d("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",m.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}function tP(e,t){let n=em(e.stepStatus,"pending"),r=im(e,"depends_on"),o=De(e.file).map(nm),i=De(e.test).map(rm),a=De(e.doc).map(om),s=A();return{id:"plan-step-001",order:1,title:t,body:e.stepBody?.trim()||void 0,status:n,owner:am(e.stepOwner),evidence:e.stepEvidence?.trim()||void 0,blocked_reason:n==="blocked"?e.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n==="completed"?s:void 0}}function nP(e){let t=Z$(e),n=Q$(e);if(eP(t,n),t.stepTitles.length===0)return{steps:[],hasPerStepDetailOptions:n};if(t.stepTitles.length===1)return{steps:[tP(e,t.stepTitles[0])],hasPerStepDetailOptions:n};let r=A();return{steps:t.stepTitles.map((o,i)=>({id:`${Eb}${String(i+1).padStart(3,"0")}`,order:i+1,title:o,body:t.templateSteps[i]?.body,status:"pending",created_at:r,updated_at:r})),hasPerStepDetailOptions:n}}function Ob(e,t,n=[]){le(e,t),n.length>0&&Zf(t,n)}async function rP(e,t,n){let r=e.title?.trim();if(!r)throw new d("pm plan create requires --title",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']});let o=Tb(e.mode,Zd),i=U$(e.harness),a=e.fromSearch?.trim(),s=X$(e),{steps:c,hasPerStepDetailOptions:l}=nP(e);if(c.length===0&&l)throw new d("pm plan create step options require --step-title (or a single --step)",m.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']});let p=e.description?.trim()??e.scope?.trim()??r,u=e.claim?I(e.author,n.settings.author_default):e.assignee?.trim()||void 0,f={...e,title:r,description:p,type:"Plan",template:void 0,file:De(e.file),test:De(e.test),doc:De(e.doc),field:De(e.field),assignee:I(e.author,n.settings.author_default),blockedBy:void 0,dep:J$(e),message:e.message??(a?`plan create (search: ${a})`:"plan create")};Ob(e,f);let h=await en(f,t),_=await _e({pmRoot:n.pmRoot,settings:n.settings,id:h.item.id,op:"plan_create_metadata",author:I(e.author,n.settings.author_default),message:"seed plan metadata",mutate(y){let w=["plan_mode"];y.metadata.plan_mode=o,i&&(y.metadata.plan_harness=i,w.push("plan_harness"));let v=e.scope?.trim();v&&(y.metadata.plan_scope=v,w.push("plan_scope"));let k=e.resumeContext?.trim();return k&&(y.metadata.plan_resume_context=k,w.push("plan_resume_context")),y.metadata.plan_steps=c,w.push("plan_steps"),s&&(y.metadata.plan_validation=[...y.metadata.plan_validation??[],s],w.push("plan_validation")),u&&(y.metadata.assignee=u,w.push("assignee")),{changedFields:w}}}),g=We(_.item,"brief");return{action:"create",plan:g,step:c[0],next_actions:Ve(h.item.id,g),warnings:[...h.warnings],generated_at:A()}}async function oP(e,t,n){let r=j$(t.depth),o=G$(t.fields),{document:i,itemId:a}=await Rb(n,e),s=We(i.metadata,o===null?r:"deep");return{action:"show",plan:o===null?s:q$(s,o),next_actions:Ve(a,s),warnings:[],generated_at:A()}}function iP(e,t){let n=new Map(Object.entries(t).filter(([r])=>r.startsWith("plan_")).map(([r,o])=>[r,JSON.stringify(o)]));return[...new Set([...e.keys(),...n.keys()])].filter(r=>e.get(r)!==n.get(r))}async function vt(e){let t=I(e.options.author,e.ctx.settings.author_default),n,r=await _e({pmRoot:e.ctx.pmRoot,settings:e.ctx.settings,id:e.id,op:e.op,author:t,message:e.options.message??e.message,force:e.options.force,mutate(o){Ib(o.metadata);let i=D(e.ctx.settings.schema);if(se(o.metadata.status,i)||yl(o.metadata.plan_mode))throw new d(`Plan ${o.metadata.id} is terminal (status=${o.metadata.status}, plan_mode=${o.metadata.plan_mode??"unset"}) and cannot be mutated.`,m.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."});let a=(o.metadata.plan_steps??[]).slice(),s=new Map(Object.entries(o.metadata).filter(([u])=>u.startsWith("plan_")).map(([u,f])=>[u,JSON.stringify(f)])),c=e.mutator(a,o);n=c.resultStep;let l=a.slice().sort((u,f)=>u.order-f.order).map((u,f)=>({...u,order:f+1}));o.metadata.plan_steps=l;let p=iP(s,o.metadata);return p.length===0&&c.changedSteps.length===0?{changedFields:[]}:{changedFields:p.length>0?p:["plan_steps"]}}});return{document:{metadata:r.item,body:r.body},resultStep:n,itemId:r.item.id}}async function aP(e,t,n){let r=t.stepTitle?.trim();if(!r)throw new d("pm plan add-step requires --step-title",m.USAGE);let o=em(t.stepStatus,"pending"),i=t.allowMultipleActive===!0,{document:a,resultStep:s,itemId:c}=await vt({id:e,options:t,ctx:n,op:"plan_add_step",message:`plan add-step "${r}"`,mutator(p){let u=p.length+1;xb(p,void 0,o,i);let f=sP(p,t,{order:u,title:r,status:o});return p.push(f),{changedSteps:[f.id],resultStep:f}}}),l=We(a.metadata,"standard");return{action:"add-step",plan:l,step:s,next_actions:Ve(c,l),warnings:[],generated_at:A()}}function xb(e,t,n,r){if(n!=="in_progress"||r)return;let o=e.find(i=>i.id!==t&&i.status==="in_progress");if(o)throw new d(`Plan already has step ${o.id} in_progress. Pass --allow-multiple-active or update that step first.`,m.CONFLICT)}function sP(e,t,n){let r=im(t,"depends_on"),o=De(t.file).map(nm),i=De(t.test).map(rm),a=De(t.doc).map(om),s=A();return{id:z$(e),order:n.order,title:n.title,body:t.stepBody?.trim()||void 0,status:n.status,owner:am(t.stepOwner),evidence:t.stepEvidence?.trim()||void 0,blocked_reason:n.status==="blocked"?t.stepBlockedReason?.trim()||"":void 0,linked_items:r.length>0?r:void 0,files:o.length>0?o:void 0,tests:i.length>0?i:void 0,docs:a.length>0?a:void 0,created_at:s,updated_at:s,completed_at:n.status==="completed"?s:void 0}}function im(e,t){let n=Ze(e.dependsOn).map(p=>({id:p,kind:t})),r=Ze(e.related).map(p=>({id:p,kind:"related"})),o=Ze(e.blocks).map(p=>({id:p,kind:"blocks"})),i=Ze(e.blockedBy).map(p=>({id:p,kind:"blocked_by"})),a=Ze(e.link),s=Cb(e.linkKind,t),c=e.linkNote?.trim(),l=a.map(p=>{let u={id:p,kind:s};return c&&(u.note=c),u});return[...n,...r,...o,...i,...l]}async function Yd(e,t,n,r){let{document:o,resultStep:i,itemId:a}=await vt({id:e,options:t,ctx:n,op:r.op,message:t.message??`${r.op} ${r.stepRef}`,mutator(c,l){let p=Sr(c,r.stepRef),u=A(),f=r.finalStatus??em(t.stepStatus,p.status),h=t.allowMultipleActive===!0||r.allowMultipleActive===!0;return xb(c,p.status==="in_progress"?p.id:void 0,f,h),cP(p,t,f,u),l.metadata.updated_at=u,{changedSteps:[p.id],resultStep:p}}}),s=We(o.metadata,"standard");return{action:r.op==="plan_complete_step"?"complete-step":r.op==="plan_block_step"?"block-step":"update-step",plan:s,step:i,next_actions:Ve(a,s),warnings:[],generated_at:A()}}function am(e){return Wn(e?.trim(),"--step-owner")||void 0}function cP(e,t,n,r){lP(e,t,n),dP(e,t),e.status=n,e.updated_at=r,mP(e,n,r)}function lP(e,t,n){if(!(n!=="blocked"||t.stepBlockedReason?.trim()||e.blocked_reason))throw new d("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",m.USAGE)}function dP(e,t){let n=t.stepTitle?.trim();n&&(e.title=n),t.stepBody!==void 0&&(e.body=t.stepBody.trim()||void 0),t.stepOwner!==void 0&&(e.owner=am(t.stepOwner)),t.stepEvidence!==void 0&&(e.evidence=t.stepEvidence.trim()||void 0),t.stepBlockedReason!==void 0&&(e.blocked_reason=t.stepBlockedReason.trim()||void 0),t.stepReplacement!==void 0&&(e.superseded_by=t.stepReplacement.trim()||void 0);let r=De(t.file).map(nm),o=De(t.test).map(rm),i=De(t.doc).map(om);r.length>0&&(e.files=Jd(e.files,r)),o.length>0&&(e.tests=Jd(e.tests,o)),i.length>0&&(e.docs=Jd(e.docs,i))}function Jd(e,t){let n=[...e??[]],r=new Set(n.map(o=>JSON.stringify(o)));for(let o of t){let i=JSON.stringify(o);r.has(i)||(r.add(i),n.push(o))}return n}function mP(e,t,n){if(t==="completed"&&!e.completed_at){e.completed_at=n;return}t!=="completed"&&(e.completed_at=void 0)}async function pP(e,t,n,r,o){let{document:i,itemId:a,resultStep:s}=await vt({id:e,options:t,ctx:n,op:"plan_reorder_step",message:t.message??`plan reorder-step ${r} -> ${o}`,mutator(l){let p=Sr(l,r),u=l.filter(h=>h.id!==p.id),f=Math.max(1,Math.min(o,u.length+1));return u.splice(f-1,0,p),u.forEach((h,_)=>{h.order=_+1,h.updated_at=A()}),l.length=0,l.push(...u),{changedSteps:[p.id],resultStep:p}}}),c=We(i.metadata,"standard");return{action:"reorder-step",plan:c,step:s,next_actions:Ve(a,c),warnings:[],generated_at:A()}}async function uP(e,t,n,r){let{document:o,itemId:i,resultStep:a}=await vt({id:e,options:t,ctx:n,op:"plan_remove_step",message:t.message??`plan remove-step ${r}`,mutator(c){let l=Sr(c,r),p=c.filter(u=>u.id!==l.id);return p.forEach((u,f)=>{u.order=f+1}),c.length=0,c.push(...p),{changedSteps:[l.id],resultStep:l}}}),s=We(o.metadata,"standard");return{action:"remove-step",plan:s,step:a,next_actions:Ve(i,s),warnings:[],generated_at:A()}}async function fP(e,t,n,r){let o=im(t,Cb(t.linkKind,"related"));if(o.length===0)throw new d("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",m.USAGE);let i=t.promoteToItemDep===!0,{document:a,itemId:s,resultStep:c}=await vt({id:e,options:t,ctx:n,op:"plan_link_step",message:t.message??`plan link ${r}`,mutator(p,u){let f=Sr(p,r),h=f.linked_items??[],_=y=>`${y.kind}:${y.id}`,g=new Set(h.map(_));for(let y of o){let w=_(y);g.has(w)||(h.push(y),g.add(w))}if(f.linked_items=h,f.updated_at=A(),i){let y=u.metadata.dependencies??[],w=k=>`${k.kind}:${k.id}`,v=new Set(y.map(w));for(let k of o){let C=k.kind==="depends_on"?"blocked_by":k.kind,S={id:k.id,kind:C,created_at:A(),author:I(t.author,n.settings.author_default)};v.has(w(S))||(y.push(S),v.add(w(S)))}u.metadata.dependencies=y}return{changedSteps:[f.id],resultStep:f}}}),l=We(a.metadata,"standard");return{action:"link",plan:l,step:c,next_actions:Ve(s,l),warnings:[],generated_at:A()}}async function _P(e,t,n,r){let o=Ze(t.link);if(o.length===0)throw new d("pm plan unlink requires --link <id> to remove",m.USAGE);let{document:i,itemId:a,resultStep:s}=await vt({id:e,options:t,ctx:n,op:"plan_unlink_step",message:t.message??`plan unlink ${r}`,mutator(l){let p=Sr(l,r),u=(p.linked_items??[]).filter(f=>!o.includes(f.id));return p.linked_items=u.length>0?u:void 0,p.updated_at=A(),{changedSteps:[p.id],resultStep:p}}}),c=We(i.metadata,"standard");return{action:"unlink",plan:c,step:s,next_actions:Ve(a,c),warnings:[],generated_at:A()}}async function Xd(e,t,n,r){let o=B$(r,t);if(!o){let l=`--${r}-text`,p=`--${r}`;throw new d(`pm plan ${r} requires ${l}`,m.USAGE,{code:"missing_required_option",examples:[`pm plan ${r} <plan-id> ${l} "..."`,`pm plan ${r} <plan-id> ${p} "..."`],recovery:{suggested_retry:`pm plan ${r} <plan-id> ${l} <value>`}})}let i=I(t.author,n.settings.author_default),{document:a,itemId:s}=await vt({id:e,options:t,ctx:n,op:`plan_append_${r}`,message:t.message??`plan ${r} append`,mutator(l,p){let u=A();if(r==="decision"){let h=p.metadata.plan_decisions??[];return h.push({ts:u,author:i,decision:o,rationale:t.decisionRationale?.trim()||void 0,evidence:t.decisionEvidence?.trim()||void 0}),p.metadata.plan_decisions=h,{changedSteps:[]}}if(r==="discovery"){let h=p.metadata.plan_discoveries??[];return h.push({ts:u,author:i,text:o}),p.metadata.plan_discoveries=h,{changedSteps:[]}}let f=p.metadata.plan_validation??[];return f.push({text:o,command:t.validationCommand?.trim()||void 0,expected:t.validationExpected?.trim()||void 0}),p.metadata.plan_validation=f,{changedSteps:[]}}}),c=We(a.metadata,"deep");return{action:r,plan:c,next_actions:Ve(s,c),warnings:[],generated_at:A()}}async function hP(e,t,n){let r=t.resumeContext?.trim();if(!r)throw new d("pm plan resume requires --resume-context <text>",m.USAGE);let{document:o,itemId:i}=await vt({id:e,options:t,ctx:n,op:"plan_resume",message:t.message??"plan resume context update",mutator(s,c){c.metadata.plan_resume_context=r;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),a=We(o.metadata,"brief");return{action:"resume",plan:a,next_actions:Ve(i,a),warnings:[],generated_at:A()}}async function gP(e,t,n){let r=Tb(t.mode??"approved","approved"),{document:o,itemId:i}=await vt({id:e,options:t,ctx:n,op:"plan_approve",message:t.message??`plan approve mode=${r}`,mutator(s,c){c.metadata.plan_mode=r;let l=t.scope?.trim();return l&&(c.metadata.plan_scope=l),{changedSteps:[]}}}),a=We(o.metadata,"brief");return{action:"approve",plan:a,next_actions:Ve(i,a),warnings:[],generated_at:A()}}function $b(e){return e.map(t=>`plan_materialize_skipped:${t.from_step}:${t.reason}${t.existing_id?`:${t.existing_id}`:""}`)}function yP(e,t){let n=We(e.document.metadata,"standard");return{action:"materialize",plan:n,materialized:[],materialize_skipped:t,next_actions:Ve(e.itemId,n),warnings:$b(t),generated_at:A()}}function wP(e,t,n){let r=[`id=${e},kind=parent`,`id=${t},kind=discovered_from`];for(let o of n.linked_items??[]){let i=o.kind==="blocked_by"||o.kind==="blocks"||o.kind==="related"||o.kind==="discovered_from"?o.kind:"related";r.push(`id=${o.id},kind=${i}`)}return r}async function vP(e){let t=[],n={},r=new Set(["title","description","type","parent","tags","author","message","dep"]);for(let o of De(e.options.field)){let i=o.indexOf("=");if(i<=0)throw new d(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let a=o.slice(0,i).trim(),s=o.slice(i+1).trim();if(a.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let c=a.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(f=>f.toLowerCase());if(c.length===0)throw new d(`Invalid --field entry "${o}"; expected name=value`,m.USAGE);let[l,...p]=c,u=`${l}${p.map(f=>`${f.slice(0,1).toUpperCase()}${f.slice(1)}`).join("")}`;if(r.has(u))throw new d(`Invalid --field entry "${o}"; "${u}" is reserved by materialize and cannot be overridden`,m.USAGE);n[u]=s}for(let o of e.targets){let i={...n,title:o.title,description:o.body?.trim()||o.title,type:e.resolvedTypeName,parent:e.parent,tags:e.tags,author:e.options.author,message:e.options.message??`materialized from plan ${e.planItemId} step ${o.id}`,dep:wP(e.parent,e.planItemId,o)};Ob(e.options,i,["description",...Object.keys(n)]);let a=await en(i,{path:e.pmRoot});t.push({id:a.item.id,title:a.item.title,type:e.resolvedTypeName,parent:a.item.parent,tags:a.item.tags??[],from_step:o.id})}return t}function bP(e,t,n){for(let r of t){let o=n.find(s=>s.from_step===r.id);if(!o)continue;let i=e.find(s=>s.id===r.id);if(!i)continue;let a=i.linked_items??[];a.push({id:o.id,kind:"implements",note:`materialized as ${o.type}`}),i.linked_items=a,i.updated_at=A()}}async function kP(e,t,n){let r=Ze(t.steps);if(r.length===0)throw new d("pm plan materialize requires --steps <ids|orders|all>",m.USAGE);let o=t.materializeType?.trim()||"Task",i=$(n.settings,R()),a=Te(o,i);if(!a)throw new d(`Invalid --materialize-type "${o}"`,m.USAGE);let s=t.materializeParent?.trim()||e,c=t.materializeTags,l=await Rb(n,e),p=(l.document.metadata.plan_steps??[]).slice(),{targets:u,skipped:f}=H$(p,r);if(u.length===0){if(f.length>0)return yP(l,f);throw new d("No matching plan steps found for --steps",m.NOT_FOUND)}let h=await vP({targets:u,parent:s,planItemId:l.itemId,resolvedTypeName:a,tags:c,options:t,pmRoot:n.pmRoot}),{document:_,itemId:g}=await vt({id:e,options:t,ctx:n,op:"plan_materialize",message:t.message??`plan materialize ${r.join(",")}`,mutator(w){return bP(w,u,h),{changedSteps:u.map(v=>v.id)}}}),y=We(_.metadata,"standard");return{action:"materialize",plan:y,materialized:h,...f.length>0?{materialize_skipped:f}:{},next_actions:Ve(g,y),warnings:$b(f),generated_at:A()}}function SP(e){if(e.subcommand==="create")return e;let t=Ab(e.options.step);if(t.length>1)throw new d(`pm plan ${e.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,m.USAGE);return t.length===1&&!e.options.stepTitle?.trim()?{...e,options:le(e.options,{...e.options,stepTitle:t[0]})}:e}function Dt(e,t){if(!e.id)throw new d(`pm plan ${t} requires a plan id`,m.USAGE);return e.id}function Ln(e,t){let n=Dt(e,t);if(!e.stepRef)throw new d(`pm plan ${t} requires <plan-id> <step>`,m.USAGE);return{id:n,stepRef:e.stepRef}}function EP(e){let t=Ln(e,"reorder-step");if(e.reorderTo===void 0)throw new d("pm plan reorder-step requires <plan-id> <step> <new-order>",m.USAGE);return{...t,reorderTo:e.reorderTo}}var AP={create:(e,t)=>rP(e.options,e.global,t),show:(e,t)=>oP(Dt(e,"show"),e.options,t),"add-step":(e,t)=>aP(Dt(e,"add-step"),e.options,t),"update-step":(e,t)=>{let n=Ln(e,"update-step");return Yd(n.id,e.options,t,{stepRef:n.stepRef,op:"plan_update_step"})},"complete-step":(e,t)=>{let n=Ln(e,"complete-step");return Yd(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(e,t)=>{let n=Ln(e,"block-step");return Yd(n.id,e.options,t,{stepRef:n.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(e,t)=>{let n=EP(e);return pP(n.id,e.options,t,n.stepRef,n.reorderTo)},"remove-step":(e,t)=>{let n=Ln(e,"remove-step");return uP(n.id,e.options,t,n.stepRef)},link:(e,t)=>{let n=Ln(e,"link");return fP(n.id,e.options,t,n.stepRef)},unlink:(e,t)=>{let n=Ln(e,"unlink");return _P(n.id,e.options,t,n.stepRef)},decision:(e,t)=>Xd(Dt(e,"decision"),e.options,t,"decision"),discovery:(e,t)=>Xd(Dt(e,"discovery"),e.options,t,"discovery"),validation:(e,t)=>Xd(Dt(e,"validation"),e.options,t,"validation"),resume:(e,t)=>hP(Dt(e,"resume"),e.options,t),approve:(e,t)=>gP(Dt(e,"approve"),e.options,t),materialize:(e,t)=>kP(Dt(e,"materialize"),e.options,t)};function TP(e){let t=AP[e];if(!t)throw Le({command_path:"plan",token:e,allowed:F$});return t}async function Pb(e){let t=await Y$(e.global),n=SP(e),r=await TP(n.subcommand)(n,t);return r.action==="show"?r:{...r,mutation_receipt:As(r,t.pmRoot)}}import CP from"fast-json-patch";import sm from"node:fs/promises";(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]="918ea579-30e4-59d4-9427-f0db30fd06cc")}catch{}})();async function Lb(e,t,n){let r=await z_(e,{schema:t.schema});return r.error===null?{raw:r.raw,document:r.document}:{raw:r.raw,document:Nb(n),recovered:!0}}function IP(e,t){return L_(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Nb(e){let t=or(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:_t(ht(t))}async function RP(e,t,n,r){let o=await yn(e,t,n,r),i=o.located?await A_({pmRoot:e,settings:n,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function OP(e,t){let n=Zr(e),r=Zr(t),o=CP.compare(n,r),i=new Set;for(let a of o){if(a.path==="/body"||a.path.startsWith("/body/")){i.add("body");continue}let s=a.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(s.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((a,s)=>a.localeCompare(s))}async function xP(e){let t=await Ng({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:n=>Lb(n,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function $P(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Nb(t),originalRaw:null}}function PP(e){let t=e.document.metadata.assignee?.trim(),n=t&&t!==e.author&&!e.force,r=Br(t);if(!n)return[];if(e.enforcement==="strict")throw new d(`Item ${e.resolvedId} is assigned to ${r}. Use --force to override.`,m.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${r}`]:[]}async function LP(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await re(e.existingItemPath,e.resolvedOriginalRaw),await sm.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await re(e.existingItemPath,e.resolvedOriginalRaw);return}await sm.rm(e.restoredItemPath,{force:!0})}async function NP(e){return[...await X({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await X({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function cm(e,t,n,r){let o=T(process.cwd(),r.path);await O(o);let i=await E(o),a=$(i,R()),s=await RP(o,e,i,a.type_to_folder),c=s.id,{raw:l,entries:p}=await h_(s.historyPath,c);if(p.length===0)throw new d(`No history exists for ${c}; restore is unavailable.`,m.NOT_FOUND);let u=IP(t,p),f=N_(or(p,u.historyIndex),u),h=Qr(f,{schema:i.schema});if(h.metadata.id!==c)throw new d(`Restore target resolved to item ${h.metadata.id}, expected ${c}.`,m.GENERIC_FAILURE);let _=(s.located?await Lb(s.located,i,p):null)?.raw??null,g=I(n.author,i.author_default),y=await Hr(o,c,i.locks.ttl_seconds,g,!!n.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),w=y.release;try{let{loadedItemUnderLock:v,existingItemPath:k}=await xP({pmRoot:o,subject:s,settings:i,typeRegistry:a,historyRawBeforeLock:l,currentItemRawBeforeLock:_,history:p}),C="toon",S=$P(v,p);v?.recovered===!0&&D_(o,c,v.raw),j_(o,v?.document??bp,c),h.metadata.pm_format_version=nl(Math.max(na(h.metadata),na(S.document.metadata))),q_(ni(o),na(h.metadata));let x=PP({document:S.document,author:g,force:n.force,enforcement:i.governance.ownership_enforcement,resolvedId:c}),N=OP(S.document,h),P=await ro({pmRoot:o,settings:i,operation:"restore",author:g,before:S.document,after:h});await fn({pm_root:o,operation:"restore",before:S.document,after:h,changed_fields:N,author:g,sdk:hn({pmRoot:o,settings:i,typeToFolder:a.type_to_folder})});let Y=ft(h,{format:C,schema:i.schema}),j=Et(o,h.metadata.type,c,C,a.type_to_folder),pe=await y.fence(async()=>{let q=await Yt(o,g),ue;try{await re(j,Y),k&&j!==k&&await sm.rm(k);let on=Ke({nowIso:A(),author:g,op:"restore",before:S.document,after:h,message:n.message,context:P.decisions.length===0?void 0:{workflow_policies:P.decisions}});try{await Bt(s.historyPath,on)}catch(an){throw await LP({existingItemPath:k,resolvedOriginalRaw:S.originalRaw,restoredItemPath:j}),an}ue=await Jt({pmRoot:o,preferredFormat:i.item_format,typeToFolder:a.type_to_folder,schema:i.schema,itemPath:j,previousItemPath:k??void 0,document:h})}finally{await q()}return ue});G_(o,h,c);let be=await NP({restoredItemPath:j,historyPath:s.historyPath,before:S.document,after:h});Yn({id:h.metadata.id,op:"restore",item_type:h.metadata.type,previous_status:S.document.metadata.status,status:h.metadata.status,previous:un(S.document.metadata,N),current:un(h.metadata,N),changed_fields:N});let Ae=p[u.historyIndex],jt=nr(p,!0);return{item:h.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:jt===null?null:jt+u.historyIndex+1,entry_ts:Ae.ts,entry_op:Ae.op},changed_fields:N,warnings:[...P.warnings,...v?.recovered?["restore_unreadable_item_recovered"]:[],...s.historyPolicyWarnings,...x,...pe,...be]}}finally{await w()}}(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]="06b0780c-92aa-5b21-a4bb-0abb54b74b2f")}catch{}})();var Mb=2,dm="update-many",FP=new Set(["author","message","force","ownershipMetadataBypass","ownershipDependencyBypass","allowUnresolvedDeps"]),MP=["--status","--priority","--type","--tags","--description","--body","--deadline","--estimate","--assignee","--dep","--dep-remove","--comment","--note","--learning","--file","--test","--doc","--replace-deps","--replace-tests","--replace-files","--replace-docs","--unset","--clear-*"].join(", "),DP={title:"title",description:"description",body:"body",status:"status",closeReason:"close_reason",priority:"priority",type:"type",deadline:"deadline",estimatedMinutes:"estimated_minutes",acceptanceCriteria:"acceptance_criteria",definitionOfReady:"definition_of_ready",order:"order",goal:"goal",objective:"objective",value:"value",impact:"impact",outcome:"outcome",whyNow:"why_now",assignee:"assignee",parent:"parent",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release",blockedBy:"blocked_by",blockedReason:"blocked_reason",unblockNote:"unblock_note",reporter:"reporter",severity:"severity",environment:"environment",reproSteps:"repro_steps",resolution:"resolution",expectedResult:"expected_result",actualResult:"actual_result",affectedVersion:"affected_version",fixedVersion:"fixed_version",component:"component",regression:"regression",customerImpact:"customer_impact"},UP=[{field:"dependencies",addKey:"dep",removeKey:"depRemove",clearKey:"clearDeps",replaceKey:"replaceDeps"},{field:"comments",addKey:"comment",clearKey:"clearComments"},{field:"notes",addKey:"note",clearKey:"clearNotes"},{field:"learnings",addKey:"learning",clearKey:"clearLearnings"},{field:"files",addKey:"file",clearKey:"clearFiles",replaceKey:"replaceFiles"},{field:"tests",addKey:"test",clearKey:"clearTests",replaceKey:"replaceTests"},{field:"docs",addKey:"doc",clearKey:"clearDocs",replaceKey:"replaceDocs"},{field:"reminders",addKey:"reminder",clearKey:"clearReminders"},{field:"events",addKey:"event",clearKey:"clearEvents"},{field:"type_options",addKey:"typeOption",clearKey:"clearTypeOptions"}],Db=e=>{let t={};for(let[n,r]of Object.entries(e))FP.has(n)||r!==void 0&&(t[n]=r);return t},jP=e=>Object.keys(Db(e)).length>0,Ub=e=>typeof e=="string"?e.trim():e,GP=e=>{let t=String(e).trim(),n=Number(t);return Number.isInteger(n)?n:t},lm=e=>{let t=String(e).trim(),n=Number(t);return Number.isFinite(n)?n:t},qP=e=>{let t=String(e).trim().toLowerCase();return new Map([["true",!0],["1",!0],["false",!1],["0",!1]]).get(t)??Ub(e)},KP={priority:GP,estimatedMinutes:lm,order:lm,rank:lm,regression:qP},zP=(e,t)=>{if(t!==void 0)return(KP[e]??Ub)(t)},Ts=(e,t)=>ie(e,t),HP=(e,t)=>t!==void 0?t:e==="type_options"?{}:[],BP=(e,t)=>Array.isArray(t)?t.length:e==="type_options"&&t&&typeof t=="object"?Object.keys(t).length:0,WP=e=>e.replace?"replace":e.clear?"clear_or_reset":e.removeCount>0?"merge_remove":"append",Fb=(e,t)=>t===void 0?void 0:e[t],Er=e=>Array.isArray(e)?e.length:0,VP=(e,t,n)=>{let r=n[e.addKey],o=Fb(n,e.removeKey),i=Er(r),a=Er(o),s=n[e.clearKey]===!0,c=Fb(n,e.replaceKey)===!0;if(![s,c,i>0,a>0].includes(!0))return;let l=HP(e.field,t[e.field]);return{field:e.field,before:l,after:{operation:WP({replace:c,clear:s,removeCount:a}),clear:s,replace:c,add_count:i,remove_count:a,before_count:BP(e.field,l)}}},YP=(e,t)=>{let n=[];for(let r of UP){let o=VP(r,e,t);o!==void 0&&n.push(o)}return n},JP=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],XP=(e,t)=>{if(![t.tags!==void 0,Er(t.addTags)>0,Er(t.removeTags)>0].includes(!0))return;let n=JP(e.tags),r=t.tags===void 0?n:zt(t.tags),o=er(r,t.addTags),i=zi(o,t.removeTags).slice().sort((s,c)=>s.localeCompare(c)),a=n.slice().sort((s,c)=>s.localeCompare(c));if(!Ts(a,i))return{field:"tags",before:n,after:i}},QP=(e,t)=>{let n=e.acceptance_criteria,r=Ki(Zn(n),t.addAc,t.removeAc);if(r.unmatchedRemovals.length>0)throw new d(`Acceptance criteria removal did not match: ${r.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:r.unmatchedRemovals});let o=r.criteria.join("; ");if(!Ts(typeof n=="string"?n:"",o))return{field:"acceptance_criteria",before:n,after:o}},ZP=(e,t,n)=>{for(let[r,o]of Object.entries(DP)){let i=n[r];if(i===void 0)continue;let a=t[o],s=zP(r,i);Ts(a,s)||e.push({field:o,before:a,after:s})}},eL=(e,t,n,r)=>{let o=ta(n,r,["update_many"]);for(let[i,a]of Object.entries(o)){let s=t[i];Ts(s,a)||e.push({field:i,before:s,after:a})}},tL=(e,t,n,r)=>{if(n===void 0||n.length===0)return;let o=Md(n,r,et(R()),["update_many"]);for(let i of o){let a=t[i];a!==void 0&&e.push({field:i,before:a,after:null})}},nL=(e,t,n={})=>{let r=e,o=[],i=XP(r,n);if(i&&o.push(i),ZP(o,r,n),Er(n.addAc)>0||Er(n.removeAc)>0){let a=QP(r,n);a!==void 0&&o.push(a)}return o.push(...YP(r,n)),eL(o,r,n,t),tL(o,r,n.unset,t),{id:e.id,changes:o}},rL=(e,t)=>R_(e,t,{strict:!0,flagLabel:"--filter-status"}),oL=e=>{if(e?.ids!=null&&String(e.ids).trim().length===0)throw new d("--ids requires at least one non-empty item ID",m.USAGE)},iL=[({update:e})=>{e.priority!==void 0&&Vt(e.priority)},({update:e,settings:t})=>{e.unset!==void 0&&e.unset.length>0&&Md(e.unset,Qe(t.schema),et(R()),["update_many"])},({update:e,settings:t,pmRoot:n})=>{if(e.type===void 0)return;let r=$(t,R());if(!Te(e.type,r))throw new d(qt(e.type,r.types,Kt(n,t.schema)),m.USAGE)},({update:e,statusRegistry:t})=>{if(e.status!==void 0&&!ae(e.status,t)){let n=t.definitions.map(r=>r.id);throw new d(`Invalid status value "${e.status}". Allowed: ${n.join(", ")}`,m.USAGE,{code:"invalid_argument_value",field:"status",value:e.status,allowed:n})}},({update:e})=>{e.deadline!==void 0&&te(e.deadline,new Date,"deadline")},({update:e})=>{e.estimatedMinutes!==void 0&&tr(e.estimatedMinutes,"estimated-minutes")}],aL=(e,t,n,r)=>{let o={update:e,settings:t,statusRegistry:n,pmRoot:r};for(let i of iL)i(o)},sL=async e=>{let t=await Xi(e.pmRoot,dm,e.rollbackId,Mb),n=e.options.update?.message??`Rollback update-many checkpoint ${t.id}`,r=await is(e.pmRoot,t,{author:e.options.update?.author,message:n,force:e.options.update?.force}),o=r.rows.filter(i=>i.status==="skipped").length;return{...gn({applied:r.restored_ids.length,skipped:o,failed:r.failed_count,unmatched:0}),mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm update-many --rollback ${t.id}`},restored_count:r.restored_ids.length,skipped_count:o,failed_count:r.failed_count,rows:r.rows,ids:r.restored_ids}},cL=async e=>{let t={schema_version:Mb,rollback_strategy:"guarded_inverse",id:e.checkpointId,created_at:e.nowValue,author:I(e.options.update?.author,"unknown"),status_filter:e.statusFilter??null,list_filters:e.filters,update_options:e.updateSummary,items:e.checkpointItems},n=await Ji(e.pmRoot,dm,e.checkpointId,t);return{id:e.checkpointId,created_at:e.nowValue,path:n,rollback_command:`pm update-many --rollback ${e.checkpointId}`}},lL=(e,t)=>{if(e==null)return;let n=[...new Set(String(e).split(",").map(o=>o.trim()).filter(o=>o.length>0))],r=new Set(t.map(o=>o.id));return n.filter(o=>!r.has(o))},mm=e=>e.unmatchedIds===void 0?{}:{unmatched_ids:e.unmatchedIds,unmatched_count:e.unmatchedIds.length},dL=async e=>{let t=T(process.cwd(),e.path);await O(t);let n=await E(t);return{pmRoot:t,settings:n,statusRegistry:D(n.schema),runtimeFieldRegistry:Qe(n.schema)}},mL=e=>{if(e.options.dryRun===!0)throw new d("--dry-run cannot be combined with --rollback",m.USAGE);if(wo(e.options.list,e.options.status))throw new d("Rollback mode does not accept filter options",m.USAGE);if(Object.keys(e.updateSummary).length>0)throw new d("Rollback mode does not accept update mutation flags",m.USAGE);return sL({pmRoot:e.runtime.pmRoot,rollbackId:e.rollbackId,options:e.options,global:e.global})},pL=async e=>{rL(e.options.status,e.runtime.statusRegistry);let t=await Pt(void 0,{...e.options.list,status:e.options.status,compact:void 0,brief:void 0,fields:void 0,includeBody:!0,full:!0},e.global),n=t.items.map(o=>{let i=nL(o,e.runtime.runtimeFieldRegistry,e.options.update);return e.dependencyWarnings.length===0?i:{...i,warnings:[...e.dependencyWarnings]}}),r=e.options.list?.ids==null?[]:(await Pt(void 0,{ids:e.options.list.ids,noTruncate:!0,full:!0},e.global)).items;return{listed:t,planned:n,actionable:n.filter(o=>o.changes.length>0),updateSummary:e.updateSummary,unmatchedIds:lL(e.options.list?.ids,r)}},uL=e=>({outcome:"effect",exit_code:m.SUCCESS,mode:"dry_run",matched_count:e.listed.items.length,dry_run:!0,filters:e.listed.filters,planned_update_options:e.updateSummary,item_plans:e.planned,ids:[],...mm(e)}),fL=e=>({...gn({applied:0,skipped:e.listed.items.length,failed:0,unmatched:e.unmatchedIds?.length??0}),mode:"apply",matched_count:e.listed.items.length,dry_run:!1,filters:e.listed.filters,planned_update_options:e.updateSummary,updated_count:0,skipped_count:e.listed.items.length,failed_count:0,rows:e.planned.map(t=>({id:t.id,status:"skipped"})),ids:[],...mm(e)}),_L=async e=>{let t=[],n=[],r=e.options.update.message??`update-many apply ${e.checkpointId}`,o=new Set(e.plans.filter(i=>i.changes.length>0).map(i=>i.id));for(let i of e.items){if(!o.has(i.id)){t.push({id:i.id,status:"skipped"});continue}try{let a=Xc(le(e.options.update,{...e.options.update,message:r,runtimeFieldCommands:["update_many"]})),s=await ma({pmRoot:e.pmRoot,itemId:i.id,checkpointId:e.checkpointId},()=>at(i.id,a,e.global));t.push({id:i.id,status:"updated",changed_fields:s.changed_fields,warnings:s.warnings}),n.push(i.id)}catch(a){let s=await as(a,i.id,e.pmRoot);if(s!==void 0){t.push({id:i.id,status:"updated",...s}),n.push(i.id);continue}t.push({id:i.id,status:"failed",error:dt(a),...await wt(a,e.pmRoot)})}}return{rows:t,updatedIds:n}},hL=async e=>{if(e.plan.actionable.length===0)return fL(e.plan);let t=A(),n=Yi(dm,t),r=new Set(e.plan.actionable.map(u=>u.id)),o=e.plan.listed.items.filter(u=>r.has(u.id)).map(u=>({id:u.id,target_updated_at:u.updated_at})),i=e.options.checkpoint===!1?void 0:await cL({pmRoot:e.runtime.pmRoot,checkpointId:n,nowValue:t,options:e.options,statusFilter:e.options.status,filters:e.plan.listed.filters,updateSummary:e.plan.updateSummary,checkpointItems:o}),a=await _L({pmRoot:e.runtime.pmRoot,items:e.plan.listed.items,plans:e.plan.planned,options:e.options,global:e.global,checkpointId:n}),s=u=>a.rows.filter(f=>f.status===u).length,c=s("updated"),l=s("skipped"),p=s("failed");return{...gn({applied:c,skipped:l,failed:p,unmatched:e.plan.unmatchedIds?.length??0}),mode:"apply",matched_count:e.plan.listed.items.length,dry_run:!1,filters:e.plan.listed.filters,planned_update_options:e.plan.updateSummary,...i?{checkpoint:i}:{},updated_count:c,skipped_count:l,failed_count:p,rows:a.rows,ids:a.updatedIds,...mm(e.plan)}},jb=async(e,t)=>{let n=Vi(e.rollback),r=await dL(t);n===void 0&&(e={...e,update:Xc(await jd(e.update))});let o=Db(e.update);if(oL(e.list),n!==void 0)return mL({runtime:r,rollbackId:n,options:e,global:t,updateSummary:o});if(!jP(e.update)&&e.dryRun!==!0)throw new d(`No update-many mutation flags provided. Add at least one mutation flag (for example: ${MP}), or pass --dry-run for a filter-only preview.`,m.USAGE);aL(e.update,r.settings,r.statusRegistry,r.pmRoot),Gd(e.update);let i=await Rn({pmRoot:r.pmRoot,dependencies:Es(e.update.dep,r.settings.id_prefix,A(),I(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps}),a=await pL({options:e,global:t,runtime:r,updateSummary:o,dependencyWarnings:i});return await Rn({pmRoot:r.pmRoot,dependencies:Es(e.update.dep,r.settings.id_prefix,A(),I(e.update.author,r.settings.author_default)).additions,idPrefix:r.settings.id_prefix,itemFormat:r.settings.item_format,typeToFolder:$(r.settings,R()).type_to_folder,allowUnresolved:e.update.allowUnresolvedDeps,holders:a.listed.items.map(s=>({id:s.id,createdAt:s.created_at})),schema:r.settings.schema}),e.dryRun===!0?uL(a):hL({runtime:r,options:e,global:t,plan:a})};(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]="be7de7b1-db32-543c-a3ae-c4958ee3b395")}catch{}})();function gL(e){if(e===void 0)return;if(e.trim().length===0)throw new d("--add-json must contain a JSON value",m.USAGE,{code:"structured_event_json_empty"});let t;try{t=JSON.parse(e)}catch{throw new d("--add-json must be valid JSON",m.USAGE,{code:"structured_event_json_invalid"})}return t}function yL(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.type;return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function wL(e){if(e===void 0)return;let t=Date.parse(e);if(!Number.isFinite(t))throw new d("--since must be a valid ISO timestamp",m.USAGE,{code:"structured_event_since_invalid"});return t}function Gb(e){return Object.prototype.toString.call(e)==="[object Object]"?e:{}}async function qb(e,t,n){let r=gL(t.addJson),o=[t.add!==void 0,t.stdin===!0,t.file!==void 0,t.edit!==void 0,t.delete!==void 0].includes(!0);if(r!==void 0&&o)throw new d("--add-json cannot be combined with text, edit, delete, stdin, or file inputs",m.USAGE,{code:"structured_event_input_conflict"});let i=r===void 0?void 0:At(r),a=[t.since,t.eventType].some(_=>_!==void 0),s=wL(t.since),c=to(t.limit),l=await fr(e,{...t,...a?{limit:void 0}:{},includeMeta:[t.includeMeta===!0,a].includes(!0)},n,{input:await Ua(i===void 0?t:{add:i},"note"),collectionKey:"notes",op:"note_add",editOp:"note_edit",deleteOp:"note_delete",parseText:_=>ur(_),createEntry:_=>r===void 0?_:{..._,format:"json",data:r,event_type:yL(r)},bypassOwnershipConflict:!![t.edit===void 0,t.delete===void 0,t.ownershipAppendBypass===!0].every(Boolean),conflictGuidance:{required:"Strict ownership also protects annotations. Ask the current owner to run pm release <id>, then run pm claim <id>; use --force only for an explicitly approved override.",examples:["pm claim <id>"],nextSteps:["For an approved append without reassignment: pm package install governance-audit --project; then pm notes --help lists the package-owned append bypass. Edit/delete still require ownership.","For a non-terminal handoff, the current owner runs pm release <id>; then you run pm claim <id> before retrying. Claim refuses work still held by another owner; --force requires an explicitly approved override."]}}),p=t.eventType?.trim(),u=l.notes.filter(_=>{let g=Gb(_),y=[g.format==="json",g.data!==void 0].every(Boolean),w=[s===void 0,Date.parse(g.created_at??"")>=(s??Number.POSITIVE_INFINITY)].includes(!0),v=[!p,g.event_type===p].includes(!0);return[!a,[y,w,v].every(Boolean)].includes(!0)}),f=a?ql(u,c):u,h=f.filter(_=>Gb(_).format==="json").length;return{...l,notes:f,count:f.length,...a?{total_count:u.length,returned_count:f.length,has_more:f.length<u.length,...c===void 0?{}:{limit:c},structured_event_count:h}:t.includeMeta===!0?{structured_event_count:h}:{}}}import $L from"node:path";import vL from"node:fs/promises";import Kb 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]="4e476a2f-8735-53e9-88c3-b43bfc34e1f5")}catch{}})();var bL="templates",kL=".json",SL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,EL=qi.map(e=>e.target).filter(e=>e!=="acceptanceCriteria"),AL=new Set(EL);function TL(e){let t=e.trim();if(!SL.test(t))throw new d(`Invalid template name "${e}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,m.USAGE);return t}function zb(e){return Kb.join(e,bL)}function Hb(e,t){return Kb.join(zb(e),`${t}${kL}`)}async function CL(e){await O(e)}function Bb(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))}function IL(e){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0){if(n==="priority"){t[n]=String(Vt(r));continue}if(AL.has(n)){if(typeof r=="string"){t[n]=[r];continue}if(!Array.isArray(r))continue;let o=r.filter(i=>typeof i=="string");o.length>0&&(t[n]=o);continue}if(typeof r=="string"){t[n]=r;continue}Array.isArray(r)&&r.every(o=>typeof o=="string")&&(t[n]=[...r])}return Bb(t)}function RL(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new d(`Template "${t}" has invalid options payload.`,m.GENERIC_FAILURE);let n=e,r={};for(let[o,i]of Object.entries(n)){let a=o.trim();if(a.length===0)throw new d(`Template "${t}" contains an empty option key.`,m.GENERIC_FAILURE);if(typeof i=="string"){r[a]=i;continue}if(Array.isArray(i)&&i.every(s=>typeof s=="string")){r[a]=[...i];continue}throw new d(`Template "${t}" contains invalid value for option "${a}".`,m.GENERIC_FAILURE)}return Bb(r)}function OL(e,t){let n;try{n=JSON.parse(e)}catch{throw new d(`Template "${t}" contains invalid JSON.`,m.GENERIC_FAILURE)}if(typeof n!="object"||n===null||Array.isArray(n))throw new d(`Template "${t}" has invalid document shape.`,m.GENERIC_FAILURE);let r=n,o=RL(r.options,t),i=A();return{name:typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():t,created_at:typeof r.created_at=="string"?r.created_at:i,updated_at:typeof r.updated_at=="string"?r.updated_at:i,options:o}}async function xL(e,t){let n=await ee(Hb(e,t));if(n===null)throw new d(`Template "${t}" not found`,m.NOT_FOUND);return OL(n,t)}async function pm(e,t,n){let r=T(process.cwd(),n.path);await CL(r);let o=TL(e),i=IL(t);if(Object.keys(i).length===0)throw new d("templates save requires at least one create option flag",m.USAGE);let a=A(),s=Hb(r,o),c=a;await B(s)&&(c=(await xL(r,o)).created_at);let l={name:o,created_at:c,updated_at:a,options:i},p=await E(r);return await vL.mkdir(zb(r),{recursive:!0}),await nt({pmRoot:r,filePath:s,raw:`${JSON.stringify(l,null,2)}
23
+ `,op:"templates:save",author:I(void 0,p.author_default),lockTtlSeconds:p.locks.ttl_seconds,lockWaitMs:p.locks.wait_ms}),{name:l.name,created_at:l.created_at,updated_at:l.updated_at,path:s,options:l.options}}(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]="aa4e2ff3-dc3b-5688-bf40-bdd71c65320b")}catch{}})();var Jb=["list","show","apply","lint"],PL="schema-types",LL="schema-statuses",NL="schema-fields";function Cs(){let e=R();return e===null?[]:e.profiles.map(t=>({name:t.name,profile:t.profile}))}function Xb(){let{profiles:e,warnings:t}=uf(Cs());return{action:"list",profiles:e.map(n=>({name:n.definition.name,title:n.definition.title,summary:n.definition.summary,source:n.source,...n.package!==void 0?{package:n.package}:{},composition:yf(n.definition)})),warnings:t,generated_at:A()}}function Qb(e){let t;try{t=$i(e,Cs())}catch(r){throw new d(r instanceof Error?r.message:String(r),m.USAGE)}let{resolved:n}=t;return{action:"show",...wf(n.definition),source:n.source,...n.package!==void 0?{package:n.package}:{},warnings:t.warnings,generated_at:A()}}function Zb(e){let t;try{t=$i(e,Cs())}catch(o){throw new d(o instanceof Error?o.message:String(o),m.USAGE)}let{resolved:n}=t,r=Vf(n.definition);return{action:"lint",name:n.definition.name,title:n.definition.title,source:n.source,...n.package!==void 0?{package:n.package}:{},ok:r.ok,error_count:r.errorCount,warning_count:r.warningCount,findings:r.findings,warnings:t.warnings,generated_at:A()}}function FL(e,t){return $L.join(e,"templates",`${t}.json`)}async function ML(e,t){let n=await ee(FL(e,t));if(n!==null)try{let r=JSON.parse(n);if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let o=r.options;if(o!==null&&typeof o=="object"&&!Array.isArray(o))return o}}catch{}}async function Wb(e,t,n,r){let o=new Map;for(let i of r.templates){let a=await ML(e,i.name);a!==void 0&&o.set(i.name,a)}return{typesRaw:await ee(Ct(e,t.files.types,Tt.types)),statusesRaw:await ee(Ct(e,t.files.statuses,Tt.statuses)),fieldsRaw:await ee(Ct(e,t.files.fields,Tt.fields)),workflows:n.schema.type_workflows??[],settings:n,templates:o,installedPackages:new Set}}function Ar(e){let t=[],n=[],r=[];for(let o of e)(o.status==="add"?t:o.status==="update"?n:r).push(o.key);return{added:t,updated:n,unchanged:r}}function Vb(e,t,n,r,o){return{action:"apply",name:e.name,title:e.title,applied:n,dry_run:r,changed:t.changed,types:Ar(t.types.changes),statuses:Ar(t.statuses.changes),fields:Ar(t.fields.changes),workflows:Ar(t.workflows.changes.map(i=>({key:i.type,status:i.status}))),config:Ar(t.config.changes),templates:Ar(t.templates.changes.map(i=>({key:i.name,status:i.status}))),packages:t.packages,warnings:[...new Set(o)].sort((i,a)=>i.localeCompare(a)),generated_at:A()}}async function DL(e){await O(e)}function UL(e){try{let t=$i(e,Cs());return{profile:t.resolved.definition,warnings:t.warnings}}catch(t){throw new d(t instanceof Error?t.message:String(t),m.USAGE)}}async function ek(e,t,n){let r=T(process.cwd(),n.path);await DL(r);let o=UL(e),i=o.profile,a=o.warnings,s=t.dryRun===!0,c=await E(r),l=Pi(c.schema);if(s){let w=await Wb(r,l,c,i),v=Yb(i,w);return Vb(i,v,!1,!0,[...a])}let p=I(t.author,c.author_default),u=$_(c),f=!!t.force,h=[...a],_=[],g=async w=>{_.push(await mt(r,w,c.locks.ttl_seconds,p,f,u.force_required_for_stale_lock,c.locks.wait_ms))},y;try{await g(PL),await g(LL),await g(NL);let w=await Wb(r,l,c,i);if(y=Yb(i,w),y.types.changed){let v=Ct(r,l.files.types,Tt.types);await nt({pmRoot:r,filePath:v,raw:xi(y.types.file),op:"profile:apply-types",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms});let k=new Set(i.types.map(S=>sf(S).name)),C=y.types.file.definitions.filter(S=>k.has(S.name));await Xh(r,C,h,"profile:apply-type-folder"),h.push(...await X({path:v,scope:"project",op:"profile:apply-types"}))}if(y.statuses.changed){let v=Ct(r,l.files.statuses,Tt.statuses);await nt({pmRoot:r,filePath:v,raw:gf(y.statuses.file),op:"profile:apply-statuses",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await X({path:v,scope:"project",op:"profile:apply-statuses"}))}if(y.fields.changed){let v=Ct(r,l.files.fields,Tt.fields);await nt({pmRoot:r,filePath:v,raw:_f(y.fields.file),op:"profile:apply-fields",author:p,lockTtlSeconds:c.locks.ttl_seconds,lockWaitMs:c.locks.wait_ms}),h.push(...await X({path:v,scope:"project",op:"profile:apply-fields"}))}if(y.config.changed||y.workflows.changed){for(let v of y.config.changes){if(v.status==="unchanged")continue;let k=zr(v.key);k!==void 0&&Ni(c,k,v.value)}c.schema.type_workflows=y.workflows.result,await Re(r,c,"profile:apply-config")}for(let v of y.templates.changes)v.status!=="unchanged"&&await pm(v.name,{...v.options},n)}finally{for(let w of _.reverse())try{await w()}catch{}}return Vb(i,y,y.changed,!1,h)}function Yb(e,t){try{return Yf(e,t)}catch(n){throw new d(n instanceof Error?n.message:String(n),m.USAGE)}}import BL 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]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var nk=10,Nn="https://schema.unbrained.dev/pm/eval-query-set/v1";var Is={schema:Nn,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},st=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},jL=new Set(["keyword","semantic","hybrid"]);function tk(e,t){let n=0,r=Math.min(t,e.length);for(let o=0;o<r;o+=1)n+=e[o]/Math.log2(o+2);return n}function GL(e,t,n){if(t.size===0)return 0;let r=e.map(s=>t.has(s)?1:0),o=tk(r,n),i=Array.from({length:t.size},()=>1),a=tk(i,n);return a===0?0:o/a}function qL(e,t,n){let r=Math.min(n,e.length);for(let o=0;o<r;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function um(e,t,n){let r=Math.min(n,e.length),o=0;for(let i=0;i<r;i+=1)t.has(e[i])&&(o+=1);return o}function KL(e,t,n){return n<=0?0:um(e,t,n)/n}function zL(e,t,n){return t.size===0?0:um(e,t,n)/t.size}function rk(e,t,n){return{ndcg:GL(e,t,n),mrr:qL(e,t,n),precision:KL(e,t,n),recall:zL(e,t,n),relevant_total:t.size,retrieved_relevant:um(e,t,n)}}function ok(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let n=e.reduce((r,o)=>({ndcg:r.ndcg+o.ndcg,mrr:r.mrr+o.mrr,precision:r.precision+o.precision,recall:r.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:n.ndcg/t,mrr:n.mrr/t,precision:n.precision/t,recall:n.recall/t,query_count:t}}function HL(e,t){if(typeof e!="object"||e===null)throw new st(`Eval query at index ${t} must be an object`);let n=e,r=typeof n.query=="string"?n.query.trim():"";if(r.length===0)throw new st(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(n.relevant_ids))throw new st(`Eval query at index ${t} must have a "relevant_ids" array`);if(n.relevant_ids.some(i=>typeof i!="string"))throw new st(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(n.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new st(`Eval query at index ${t} must list at least one relevant id`);if(n.mode!==void 0&&(typeof n.mode!="string"||!jL.has(n.mode)))throw new st(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:r,relevant_ids:o,...n.minimum===void 0?{}:{minimum:my(n.minimum)},...n.mode!==void 0?{mode:n.mode}:{},...typeof n.description=="string"&&n.description.trim().length>0?{description:n.description.trim()}:{}}}function fm(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==Nn)throw new st(`Unsupported eval query set schema; expected "${Nn}"`);let n=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(n))throw new st('Eval query set must be an array of queries or an object with a "queries" array');if(n.length===0)throw new st("Eval query set must contain at least one query");return{schema:Nn,queries:n.map((r,o)=>HL(r,o))}}(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]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var WL=_m.join("search","eval-queries.json"),hm={schema:Nn,examples:[JSON.stringify(Is)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},VL=new Set(["keyword","semantic","hybrid"]),YL=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!VL.has(t))throw new d("Eval --mode must be one of keyword|semantic|hybrid",m.USAGE);return t},JL=e=>{if(e===void 0||e==="")return nk;let t=Ip(e);if(t===null)throw new d("Eval --k must be a positive integer",m.USAGE);return t},XL=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),n=Number(t);if([t.length===0,!Number.isFinite(n),n<0,n>1].includes(!0))throw new d("Eval --fail-under must be a number in the range [0, 1]",m.USAGE);return n},tn=e=>Math.round(e*1e4)/1e4,QL=async e=>{try{return await BL.readFile(e,"utf8")}catch{throw new d(`Eval query set not found at ${e}`,m.NOT_FOUND,{...hm,examples:[`echo '${JSON.stringify(Is)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},ZL=(e,t)=>{try{return JSON.parse(e)}catch(n){throw new d(`Eval query set at ${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,m.USAGE,hm)}},eN=e=>{try{return fm(e)}catch(t){throw new d(t instanceof Error?t.message:String(t),m.USAGE,hm)}},tN=async e=>eN(ZL(await QL(e),e)),nN=async(e,t,n,r)=>{let o=e.mode??t,i=(await bo(e.query,{mode:o,limit:String(n),fields:"id"},r)).items.map(s=>s.id).filter(s=>typeof s=="string"),a=rk(i,new Set(e.relevant_ids),n);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:py(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:tn(a.ndcg),mrr:tn(a.mrr),precision:tn(a.precision),recall:tn(a.recall)}}},rN=(e,t,n,r)=>{let o=ok(n);return{k:e,query_count:t.length,aggregate:{ndcg:tn(o.ndcg),mrr:tn(o.mrr),precision:tn(o.precision),recall:tn(o.recall)},queries:t,...r!==void 0?{fail_under:r}:{},passed:(r===void 0||o.ndcg>=r)&&t.every(i=>(i.violations?.length??0)===0)}},ik=async(e,t)=>{let n=T(process.cwd(),t.path);await O(n);let r=JL(e.k),o=YL(e.mode),i=XL(e.failUnder),a=e.queries?_m.resolve(process.cwd(),e.queries):_m.join(n,WL),s=await tN(a),c=[],l=[];for(let p of s.queries){let{report:u,metrics:f}=await nN(p,o,r,t);l.push(f),c.push(u)}return rN(r,c,l,i)};import{readFile as oN,writeFile as ck}from"node:fs/promises";import iN 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]="74f8a3ee-f0dc-568d-86d1-8c0b9649e2e2")}catch{}})();var ak=["item","history","relationship","json"];function aN(e){let t=e.trim().toLowerCase();if(ak.includes(t))return t;throw new d(`Unknown merge artifact "${e}". Supported values: ${ak.join(", ")}.`,m.USAGE)}function sN(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new d(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,m.USAGE)}async function gm(e,t){try{return await oN(e,"utf8")}catch{throw new d(`Cannot read merge ${t} file at ${e}.`,m.NOT_FOUND)}}async function cN(e){let t=T(process.cwd(),e.path);return await B(oe(t))?E(t):null}function lN(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function sk(e,t){try{return e()}catch(n){if(n instanceof d&&n.context?.code==="item_identity_conflict"){let r=o=>o.endsWith(`
24
+ `)?o:`${o}
25
+ `;throw await ck(t.outputPath,`<<<<<<< pm ours
26
+ ${r(t.oursRaw)}||||||| pm base
27
+ ${r(t.baseRaw)}=======
28
+ ${r(t.theirsRaw)}>>>>>>> pm theirs
29
+ `,"utf8"),new d(`Unresolved identity for ${t.itemPath}: both snapshots remain in conflict markers. ${n.message}`,n.exitCode,{...n.context,recovery:{suggested_retry:"git status --short"},nextSteps:["Preserve both source snapshots and establish item identity before resolving. Do not stage conflict markers as a completed merge; pm health and storage validation reject them."]})}throw n}}async function lk(e,t){let n=aN(e.artifact),r=sN(e.prefer),o=iN.resolve(e.outputPath??e.oursPath),[i,a,s]=await Promise.all([gm(e.basePath,"base"),gm(e.oursPath,"ours"),gm(e.theirsPath,"theirs")]),c,l,p=[],u={},f={baseRaw:i,oursRaw:a,theirsRaw:s,outputPath:o,itemPath:e.itemPath??o};if(n==="history"){let _=await sk(()=>vg(i,a,s),f);c=_.merged,u.history={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="relationship"){let _=bg(i,a,s);c=_.merged,u.relationship={strategy:_.strategy,common_entries:_.common_entries,entries_from_ours:_.entries_from_ours,entries_from_theirs:_.entries_from_theirs,entries_total:_.entries_total,reanchored:_.reanchored}}else if(n==="item"){let _=await cN(t),g=lN(e.itemPath??o,_),y=et(R()),w=await sk(()=>kg(i,a,s,{format:g,schema:_?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"latest_document_update"}),f);if(c=w.merged,p.push(...w.conflict_fields),u.item={fields_from_theirs:w.fields_from_theirs,union_fields:w.union_fields,conflict_resolution:"latest_document_update",requested_preference_applied:!1},e.itemPath!==void 0){let v=f_(c,{format:g,schema:_?.schema,extensionFieldNames:y}),k=v.metadata,C=[...new Set([...w.fields_from_theirs,...w.union_fields,...w.conflict_decisions.map(S=>S.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"latest_document_update",fieldsFromTheirs:w.fields_from_theirs,unionFields:w.union_fields,mergedFieldHashes:Object.fromEntries(C.map(S=>[S,wg(S==="body"?v.body:k[S])])),decisions:w.conflict_decisions,operation:await Eg(process.cwd(),e.itemPath,a)}}}else{let _=Sg(i,a,s,{preferred:r});c=_.merged,p.push(..._.conflict_paths),u.json={paths_from_theirs:_.paths_from_theirs}}if(await ck(o,c,"utf8"),l!==void 0){let _=await Tg(l);_!==null&&(u.receipt=wn(_))}let h=[];if(p.length>0){let _=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;h.push(`Both branches changed ${p.join(", ")}; the item driver kept the value from the later document update, with stable value order only as an equal-timestamp tie-break. --prefer does not apply to convergent item scalar conflicts. ${_} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&h.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:p.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:p,...u,guidance:h,generated_at:A()}}(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]="3fe6f853-6742-5305-b722-0cc74547f367")}catch{}})();async function dk(e){if(e.cwd===null)return[];let t=[];for(let n of e.receipts){if(n.operation===void 0||!await Ag(e.cwd,n.item_path,n.operation))continue;let r={gitWorkspaceRoot:e.cwd,receipt:n};await Xt(n.item_id,{dryRun:!0,mergeAbandonmentProof:r},e.global),e.dryRun||(await Xt(n.item_id,{author:e.author??e.global.author,mergeAbandonmentProof:r,message:e.message??`Settle ${n.operation.kind} receipt after exact original Git state restoration`,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{abandoned_receipts:[{...wn(n),reason:"original_git_state_restored",operation:n.operation}]}}},e.global),await Ca(e.cwd,n,{requireExisting:!0,settlement:"original_git_state_restored"})),t.push(n.id)}return t}import{readFile as dN}from"node:fs/promises";import mN 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]="4d506b3c-f1c1-5642-a258-45d93ba64d81")}catch{}})();var pN=4;function mk(e){let t=e.checks.find(s=>s.name==="integrity"),n=t?.details.counts,r=typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.missing_merge_receipt_history_references=="number"?n.missing_merge_receipt_history_references:0,o=t?.details.missing_merge_receipt_history_reference_details,i=t?.details.missing_merge_receipt_history_reference_details_truncated===!0,a=Array.isArray(o)?o.flatMap(s=>{if(typeof s!="object"||s===null||Array.isArray(s))return[];let c=s;return typeof c.item_id=="string"&&typeof c.history_line=="number"&&Number.isSafeInteger(c.history_line)&&typeof c.receipt_id=="string"?[{item_id:c.item_id,history_line:c.history_line,receipt_id:c.receipt_id}]:[]}):[];return{count:r,truncated:i,coordinates:a}}async function uN(e,t){let n=[];for(let r of t){let o;try{o=await dN(mN.join(e,"history",`${r.item_id}.jsonl`),"utf8")}catch{continue}let i=o.split(/\r?\n/)[r.history_line-1];if(i===void 0||i.trim().length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}let s=$g(a,r.item_id).find(c=>c.receiptId===r.receipt_id);s===void 0||!xg(s)||s.eventTimestamp===void 0||Fi(s.eventTimestamp,Og)>=0||n.push({...r,original_event_ts:s.eventTimestamp})}return n}async function fN(e){if(e.options.dryRun===!0||e.options.force!==!0||e.candidates.length===0)return 0;let t=new Map;for(let n of e.candidates){let r=t.get(n.item_id)??[];r.push(n),t.set(n.item_id,r)}for(let[n,r]of t)await Xt(n,{author:e.options.author??e.global.author,message:e.options.message??"accept unrecoverable pre-durable merge receipt references",force:!0,auditOperation:"merge_reconcile",forceAuditEntry:!0,auditContext:{merge:{missing_receipt_dispositions:r.map(o=>({receipt_id:o.receipt_id,original_history_line:o.history_line,original_event_ts:o.original_event_ts,reason:"legacy_clone_local_only"}))}}},e.global);return e.candidates.length}async function _N(e){try{return{status:"fulfilled",value:await Xt(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function hN(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function gN(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Ca(e.receiptWorkspaceRoot,r,{requireExisting:!0}))),n.length}function yN(e,t){if(!(e===0||t))return'If receipt proof is unavailable or competing values were discarded, first review receipts.summaries and repair.streams and re-apply intended values. Only with explicit authority to accept that review, run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>". This appends an audit event; it does not restore missing evidence or discarded values.'}async function wN(e,t){if(e.force===!0)throw new d("Automatic staging cannot accept forced reconciliation.",m.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let n={...e,stage:!1},{stageLosslessMergeReconciliation:r,resolveMergeSettlementGlobal:o}=await import("./stage-F3YJGNRK.js"),i=await o(t),a=await Rs({...n,dryRun:!0},i);return r({preview:a,dryRun:e.dryRun===!0,global:i,apply:()=>Rs({...n,dryRun:!1},i)})}async function Rs(e,t){return e.stage===!0?wN(e,t):vN(e,t)}async function vN(e,t){let n=e.dryRun===!0,r=T(process.cwd(),t.path),o=await go(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),i=mk(o),a=await uN(r,i.coordinates),s=await Aa(r),c=s??r,l=await Cg(c,{includeLossless:!0,pmRoot:r});if(l.invalid_evidence_count>0)throw new d(`Merge reconciliation refused ${l.invalid_evidence_count} invalid receipt evidence file(s).`,m.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});Ig(l.receipts.map(q=>q.id),l,n);let p=await fN({candidates:a,options:e,global:t}),u=l.receipts,f=await dk({cwd:s,receipts:u,dryRun:n,author:e.author,message:e.message,global:t}),h=new Set(f),_=new Map;for(let q of u.filter(ue=>!h.has(ue.id))){let ue=_.get(q.item_id)??[];ue.push(q),_.set(q.item_id,ue)}let g=Object.fromEntries([..._].map(([q,ue])=>[q,{merge:{receipts:ue.map(wn)}}])),y=Object.fromEntries([..._].map(([q,ue])=>[q,{gitWorkspaceRoot:s,receipts:ue}])),w=await Ra({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:g,...u.length>0?{mergeReceiptProofById:y}:{}},t),v=new Set(w.streams.map(q=>q.id)),k=[..._.keys()].filter(q=>!v.has(q)),C=await lg(k,pN,q=>_N({id:q,dryRun:n,options:e,global:t,auditContext:g[q],mergeReceiptProof:y[q]}));hN({receiptOnlyIds:k,results:C,repair:w});let S=await gN({dryRun:n,pendingReceipts:u,repair:w,receiptWorkspaceRoot:c}),x=await $a({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),N=p===0?o:await go(t,{checkOnly:!0,full:!0,skipVectors:!0,skipDrift:!0}),P=mk(N),Y=x.checks.every(q=>q.status==="ok"),j=n?u.length===0:S+f.length===u.length,pe=[w.totals.failed===0,Y,j,P.count===0,!P.truncated].every(Boolean),be=i.truncated||P.truncated?"Missing receipt coordinates exceed the bounded detail response; each reviewed --force pass can disposition only the reported eligible batch. Repeat dry-run and --force passes until receipts.missing_history_references_after=0 and pm merge reconcile returns ok=true.":void 0,Ae=yN(u.length,pe),jt=(n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.",be,Ae,"No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:pe?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.",be,Ae,...a.length>0&&p===0?["Pre-durable clone-local-only receipt references are eligible for an audited disposition; rerun with --force after reviewing receipts.legacy_disposition_eligible."]:[],"Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."]).filter(q=>q!==void 0);return{ok:pe,dry_run:n,repair:w,receipts:{pending_before:u.length,reconciled:S,abandoned:f.length,summaries:u.map(wn),unstaged_durable_receipt_ids:l.unstaged_durable_receipt_ids,missing_history_references_before:i.count,legacy_disposition_eligible:a.length,legacy_disposition_recorded:p,missing_history_references_after:P.count},validation:x,guidance:jt,generated_at:x.generated_at}}import{createHash as bN}from"node:crypto";(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]="c583f859-9204-565b-b143-59aba53c3e9c")}catch{}})();var _k=1,hk=/^[A-Za-z0-9_-]+$/,kN=100,pk=1e3;var Q4=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function ct(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,o)=>r.localeCompare(o));return n.length===0?void 0:n}function SN(e){return bN("sha256").update(At({type:ct(e.type),author:ct(e.author),item:ct(e.item),harness:ct(e.harness),agent_instance:ct(e.agentInstance),provenance:ct(e.provenanceFilter)})).digest("hex").slice(0,24)}function uk(e,t){let n={version:_k,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function EN(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===_k,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function AN(e,t){let n=e.trim();if(n.length===0||n.length>4096||!hk.test(n))throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new d("Invalid mutation event cursor.",m.USAGE,{code:"invalid_event_cursor"})}if(!EN(r,t))throw new d("Mutation event cursor does not match this query.",m.USAGE,{code:"event_cursor_query_mismatch"});return r}function TN(e){let t=e??kN;if(!Number.isSafeInteger(t)||t<0||t>pk)throw new d(`Mutation event limit must be an integer from 0 to ${pk}.`,m.USAGE,{code:"invalid_event_limit"});return t}function CN(e,t){let n=e?.trim();if(!n)return{};if(hk.test(n))return{cursor:AN(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new d("Mutation event --since must be an event cursor or ISO timestamp.",m.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function IN(e,t){if(t.verify)return fk(e,t);let n=await cl(e,t),r=n.result;if(r===null&&n.repair_needed)try{await g_(e,{lockWaitMs:0})&&(r=(await cl(e,t)).result)}catch{}return r===null?fk(e,t):{...r,source:"derived_index"}}async function fk(e,t){try{return{...await y_(e,t),source:"authoritative_history"}}catch(n){throw n instanceof d?n:new d("Mutation events are unavailable because authoritative history could not be read.",m.GENERIC_FAILURE,{code:"event_index_unavailable",why:dt(n)})}}function RN(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new d("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Os(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=TN(e.limit),r=RN(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new d("Mutation event projections are mutually exclusive. Use --provenance or --full.",m.USAGE);let o=await E(t),i=o.agent_identity.identity_vocabulary,a=oy(o.agent_identity.harness_signals),s=iy({provenance:e.provenanceFilter},a),c=ct(e.harness),l=SN(e),{cursor:p,sinceTimestamp:u}=CN(e.since,l),f={verify:e.verify===!0,...p?{after_ts:p.ts,after_stream_id:p.stream_id,after_stream_offset:p.stream_offset}:u?{since_ts:u}:{},ops:ct(e.type),authors:ct(e.author),harnesses:c,harness_alias_authors:c?Object.entries(i.aliases).filter(([,g])=>c.includes(g)).map(([g])=>g):void 0,agent_instances:ct(e.agentInstance),provenance:[...s].map(([g,y])=>({dimension:g,values:[...y]})),stream_ids:ct(e.item),limit:n},h=await IN(t,f),_=h.events.map(g=>({...r==="row"?{cursor:uk(g,l)}:{},item_id:g.stream_id,version:g.stream_offset+1,ts:g.entry.ts,author:g.entry.author,type:g.entry.op,...g.entry.message===void 0?{}:{message:g.entry.message},patch_count:g.entry.patch.length,...e.full===!0?{entry:structuredClone(g.recorded_entry??g.entry)}:{},...e.provenance===!0?{provenance:ay(g.entry,i,{itemId:g.stream_id,version:g.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...h.verified_streams===void 0?{}:{verified_streams:h.verified_streams},events:_,count:_.length,has_more:h.has_more,cursor_mode:r,...h.events.length===0?{}:{next_cursor:uk(h.events[h.events.length-1],l)},source:h.source,...e.provenanceSummary===!0?{provenance_summary:sy(h.events.map(g=>g.entry),i,a)}:{}}}(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]="8e3b8e8c-5c05-5c68-bfe2-cb3ca0a17a20")}catch{}})();var ON="1h",xN="now",$N="+1d";function nn(e,t,n){n!==void 0&&e.push(`${t}="${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function gk(e,t,n){let r={type:e,title:t,schedulePreset:"lightweight",parent:n.parent,inheritFocus:n.inheritFocus,allowMissingParent:n.allowMissingParent,tags:n.tags,priority:n.priority,body:n.body,description:n.description,author:n.author,message:n.message};return le(n,r)}async function yk(e,t,n,r){let o=gk(e,t,n),i=[];return nn(i,"start",n.start??xN),n.end!==void 0?nn(i,"end",n.end):nn(i,"duration",n.duration??ON),nn(i,"location",n.location),nn(i,"timezone",n.timezone),n.allDay===!0&&nn(i,"all_day","true"),o.event=[i.join(",")],en(o,r)}function wk(e,t,n){return yk("Meeting",e,t,n)}function vk(e,t,n){return yk("Event",e,t,n)}function bk(e,t,n){let r=gk("Reminder",e,t),o=[];return nn(o,"at",t.at??$N),nn(o,"text",t.text??e),r.reminder=[o.join(",")],en(r,n)}import Mo from"node:crypto";import{cp as kk,lstat as PN,mkdir as Fn,readFile as Cr,readdir as wm,rename as Ak,rm as bm,writeFile as xs}from"node:fs/promises";import U 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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();(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]="66cb8c82-3760-5628-a1de-69e417cf0292")}catch{}})();var Tk="https://schema.unbrained.dev/pm/workspace-snapshot/v1";var Ck=U.join("runtime","workspace-snapshots"),LN=new Set(["checkpoints","locks","runtime","search","transactions"]),NN=/^[a-z0-9][a-z0-9._-]*$/,Tr="sdk-workspace-transaction",ym={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},Ik={renameEntry:Ak,removeEntry:async e=>{await bm(e,{recursive:!0,force:!0})}},vm=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,r){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(r*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=await Ef(this.lockPath,Tr);if(t===null)throw new Error("Workspace writer lock cleanup gate stayed held");try{let n=JSON.parse(await Cr(this.lockPath,"utf8"));if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("Workspace writer lock has invalid structure");let r=n;if(r.id!==Tr||r.owner!==this.owner||r.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await re(this.lockPath,`${JSON.stringify({...r,created_at:new Date().toISOString()},null,2)}
30
+ `)}finally{await t()}}};async function Rk(e,t=""){let n=await wm(U.join(e,t),{withFileTypes:!0}),r=[];for(let o of n.sort((i,a)=>i.name.localeCompare(a.name))){if(t.length===0&&LN.has(o.name))continue;let i=U.posix.join(t.replaceAll(U.sep,"/"),o.name);if(o.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${i}`);if(o.isDirectory())r.push(...await Rk(e,i));else if(o.isFile())r.push(i);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${i}`)}return r}async function Ok(e){let t=await Rk(e),n=Mo.createHash("sha256"),r=[],o=0;for(let a of t){let s=await Cr(U.join(e,a));r.push(s),o+=s.byteLength,n.update(a),n.update("\0"),n.update(String(s.byteLength)),n.update("\0"),n.update(s)}let i=n.digest("hex");return{manifest:{schema:Tk,fingerprint:i,files:t,bytes:o},contents:r}}function Sk(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
31
+ `).filter(t=>t.trim().length>0).length}async function FN(e,t){let n=new Map;for(let r=0;r<t.length;r+=32){let o=t.slice(r,r+32),i=await Promise.all(o.map(async a=>[a,await Cr(U.join(e,a))]));for(let[a,s]of i)n.set(a,s)}return n}function km(e){if(!NN.test(e))throw new d("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function xk(e,t){return Mr(`workspace_snapshot_${e}`,t,{codes:{capacity:ym.capacity.code,permission:ym.permission.code,resource:ym.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function Mn(e){return U.join(e,Ck)}function $k(e){return new d(`Unknown workspace snapshot: ${e}`,m.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Pk(e,t){try{return JSON.parse(await Cr(e,"utf8"))}catch(n){throw Ge(n)?$k(t):n}}async function Ek(e,t,n){try{await bm(e,{recursive:n})}catch(r){throw Ge(r)?$k(t):r}}async function MN(e,t,n=Ik){try{return await n.renameEntry(e,t),!1}catch(r){if(!(r instanceof Error&&"code"in r&&(r.code==="EEXIST"||r.code==="ENOTEMPTY")))throw r;return await n.removeEntry(e),!0}}async function DN(e,t,n,r,o){await r.renameEntry(t,n);try{await r.renameEntry(e,t),await o?.()}catch(i){throw await r.renameEntry(n,t),await r.removeEntry(e),i}await r.removeEntry(n)}async function UN(e,t){return km(t),/^[a-f0-9]{64}$/.test(t)?t:(await Pk(U.join(Mn(e),"refs",`${t}.json`),t)).fingerprint}async function Sm(e,t={}){if(t.name!==void 0&&(km(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new d("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:r}=await Ok(e),o=Mn(e),i=U.join(o,"objects",n.fingerprint),a=!1;try{a=(await PN(i)).isDirectory()}catch(s){if(!(s instanceof Error&&"code"in s&&Ge(s)))throw s}if(!a){let s=U.join(o,"objects",`.create-${process.pid}-${Mo.randomUUID()}`);await xk("create_object",async()=>{await Fn(U.join(s,"files"),{recursive:!0});for(let[c,l]of n.files.entries()){let p=U.join(s,"files",l);await Fn(U.dirname(p),{recursive:!0}),await xs(p,r[c])}await xs(U.join(s,"manifest.json"),`${JSON.stringify(n,null,2)}
32
+ `,"utf8"),await Fn(U.dirname(i),{recursive:!0})}),a=await MN(s,i)}if(t.name!==void 0){let s={name:t.name,fingerprint:n.fingerprint},c=U.join(o,"refs");await Fn(c,{recursive:!0});let l=U.join(c,`.ref-${process.pid}-${Mo.randomUUID()}`);await xs(l,`${JSON.stringify(s,null,2)}
33
+ `,"utf8"),await Ak(l,U.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function Do(e,t){let n=await UN(e,t),r=await Pk(U.join(Mn(e),"objects",n,"manifest.json"),t);if(r.schema!==Tk||r.fingerprint!==n)throw new d(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return r}async function Em(e){let t=Mn(e),n=await wm(U.join(t,"objects")).catch(o=>{if(o instanceof Error&&"code"in o&&Ge(o))return[];throw o}),r=await wm(U.join(t,"refs")).catch(o=>{if(o instanceof Error&&"code"in o&&Ge(o))return[];throw o});return{objects:await Promise.all(n.filter(o=>/^[a-f0-9]{64}$/.test(o)).sort().map(o=>Do(e,o))),references:await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(async o=>JSON.parse(await Cr(U.join(t,"refs",o),"utf8"))))}}async function Am(e,t){let n=await Do(e,t),{manifest:r,contents:o}=await Ok(e),i=new Map(r.files.map((u,f)=>[u,o[f]])),a=await FN(U.join(Mn(e),"objects",n.fingerprint,"files"),n.files),s=new Set(r.files),c=new Set(n.files),l=new Set([...s,...c]);for(let u of l){let f=i.get(u),h=a.get(u);f!==void 0&&h!==void 0&&f.equals(h)&&l.delete(u)}let p=r.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let f=Sk(i.get(u)),h=Sk(a.get(u));return{path:u,current_entries:f,target_entries:h,removed_entries:Math.max(0,f-h)}}).filter(u=>u.removed_entries>0).sort((u,f)=>u.path.localeCompare(f.path));return{target_fingerprint:n.fingerprint,current_fingerprint:r.fingerprint,changed_file_count:l.size,removed_file_count:[...s].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!s.has(u)).length,removed_item_count:[...s].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:p.length,removed_history_entry_count:p.reduce((u,f)=>u+f.removed_entries,0),affected_history_streams:p,changes_authoritative_state:r.fingerprint!==n.fingerprint}}async function Lk(e,t,n={}){if(n.force!==!0)throw new d("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let r=n.author?.trim()||"pm-sdk",o=n.lockTtlSeconds??60,i=n.lockWaitMs??5e3,a=await Hr(e,Tr,o,r,!1,!1,i),s=a.release,c=new vm(ri(e,Tr),r,o);c.start(),await c.refreshNow();let l,p=!1,u=!1;try{let f=await Am(e,t),h=await Do(e,t),_=await Sm(e),g=h.fingerprint,y=Mn(e),w=U.join(y,"objects",g,"files"),v=U.dirname(e),k=U.basename(e);l=U.join(v,`.${k}.restore-${Mo.randomUUID()}`);let C=U.join(v,`.${k}.backup-${Mo.randomUUID()}`);await xk("restore_stage",async()=>{await Fn(l,{recursive:!0}),await kk(w,l,{recursive:!0,force:!1}),await Fn(U.join(l,"runtime"),{recursive:!0}),await kk(y,U.join(l,Ck),{recursive:!0,force:!1})});let S=await C_({pmRoot:l,op:"workspace_snapshot_restore",author:r,message:n.message??`Restore workspace snapshot ${g}; recovery snapshot ${_.manifest.fingerprint}`,context:{target_fingerprint:g,pre_restore_fingerprint:_.manifest.fingerprint,changed_file_count:f.changed_file_count,removed_file_count:f.removed_file_count,removed_item_count:f.removed_item_count,affected_history_stream_count:f.affected_history_stream_count,removed_history_entry_count:f.removed_history_entry_count},lockTtlSeconds:o,lockWaitMs:i}),x=U.relative(l,S.historyPath).replaceAll("\\","/");await c.stop(),u=!0;let N=ri(l,Tr),P=l;return await a.fence(async()=>{await Fn(U.dirname(N),{recursive:!0}),await xs(N,await Cr(ri(e,Tr)),{flag:"wx"}),p=!0,await DN(P,e,C,Ik,async()=>{c.start(),u=!1,await c.refreshNow()})}),await c.stop(),u=!0,{manifest:h,plan:f,recovery_fingerprint:_.manifest.fingerprint,audit_history_path:x,audit_operation:"workspace_snapshot_restore"}}catch(f){throw l!==void 0&&!p&&await Promise.allSettled([bm(l,{recursive:!0,force:!0})]),f}finally{try{u||await c.stop()}catch{}finally{await s()}}}async function Nk(e,t){km(t);let n=Mn(e);if(!/^[a-f0-9]{64}$/.test(t))return await Ek(U.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:r}=await Em(e);if(r.some(o=>o.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await Ek(U.join(n,"objects",t),t,!0),{deleted:"object",target:t}}(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]="d755ad5c-14c7-567f-8467-63b3fce6796d")}catch{}})();function Uo(e){let t={...e.args,...e.options};return le(e.options,t)}function Ut(e,t){let n=b(e,t);if(n!==void 0)return n;throw new d(`Missing required parameter: ${t}`,m.USAGE)}function Ir(e){return typeof e=="string"?[e]:ke(e)}function Fk(e){return ik(Uo(e),e.global)}function Mk(e){let t=Uo(e),n=t.cursorMode;if(n!==void 0&&n!=="batch"&&n!=="row")throw new d("Mutation event cursor mode must be batch or row.",m.USAGE,{code:"invalid_event_cursor_mode"});let r=n;return Os({cwd:b(t,"cwd"),pmRoot:b(t,"path"),since:b(t,"since"),type:Ir(t.type),author:Ir(t.author),item:Ir(t.item),limit:t.limit===void 0?void 0:ze(t.limit,"limit"),full:t.full===!0,...t.verify===!0?{verify:!0}:{},...r===void 0?{}:{cursorMode:r},...t.provenance===void 0?{}:{provenance:t.provenance===!0},...t.provenanceSummary===void 0?{}:{provenanceSummary:t.provenanceSummary===!0},...t.harness===void 0?{}:{harness:Ir(t.harness)},...t.agentInstance===void 0?{}:{agentInstance:Ir(t.agentInstance)},...t.provenanceFilter===void 0?{}:{provenanceFilter:Ir(t.provenanceFilter)}})}function Dk(e){let t=Uo(e),n=Ut(t,"subcommand");if(n==="install")return zh({dryRun:t.dryRun===!0,preCommitHook:t.preCommitHook===!0},e.global);if(n==="reconcile")return Rs({dryRun:t.dryRun===!0,author:b(t,"author"),message:b(t,"message"),force:t.force===!0,stage:t.stage===!0},e.global);if(n==="report")return Rg({includeReconciled:t.includeReconciled===!0,cwd:b(t,"cwd")});if(n==="driver")return lk({artifact:Ut(t,"artifact"),basePath:Ut(t,"basePath"),oursPath:Ut(t,"oursPath"),theirsPath:Ut(t,"theirsPath"),outputPath:b(t,"outputPath")??b(t,"output"),itemPath:b(t,"itemPath"),prefer:b(t,"prefer")},e.global);throw Le({command_path:"merge",token:n,allowed:["install","reconcile","report","driver"],display_name:"merge"})}function Uk(e){let t=Uo(e),n=Ut(t,"subcommand");if(n==="position")return uy(e.global);if(n!=="snapshot")throw Le({command_path:"workspace",token:n,allowed:["position","snapshot"],display_name:"workspace"});let r=b(t,"snapshotAction")??Ut(t,"snapshot_action"),o=T(process.cwd(),e.global.path);if(r==="create")return Sm(o,{name:b(t,"name")});if(r==="list")return Em(o);let i=Ut(t,"target");if(r==="inspect")return Do(o,i);if(r==="delete")return Nk(o,i);if(r==="restore")return t.dryRun===!0?Am(o,i):Lk(o,i,{force:t.force===!0,author:b(t,"author"),message:b(t,"message"),lockTtlSeconds:ze(t.lockTtlSeconds,"lockTtlSeconds"),lockWaitMs:ze(t.lockWaitMs,"lockWaitMs")});throw Le({command_path:"workspace snapshot",token:r,allowed:["create","list","inspect","restore","delete"],display_name:"workspace snapshot",token_kind:"action"})}function $s(e){let t=Uo(e),n=Ut(t,"title");return e.action==="meet"?wk(n,t,e.global):e.action==="event"?vk(n,t,e.global):bk(n,t,e.global)}(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]="27bbfaed-a594-5b3b-84ba-431be02e002e")}catch{}})();function jk(e){return{includeEmpty:e.includeEmpty===!0,storage:e.storage===!0,metadataCoverage:e.metadataCoverage===!0,fieldUtilization:e.fieldUtilization===!0,byAssignee:e.byAssignee===!0,byTag:e.byTag===!0,byPriority:e.byPriority===!0,tagPrefix:typeof e.tagPrefix=="string"?e.tagPrefix:void 0,measurements:e.measurements===!0,metric:b(e,"metric"),measurementLimit:typeof e.measurementLimit=="number"?e.measurementLimit:void 0,observe:ke(e.observe),direction:typeof e.improvementDirection=="string"?e.improvementDirection:void 0,measurementSource:b(e,"measurementSource"),measurementItem:b(e,"measurementItem"),measurementRevision:b(e,"measurementRevision"),author:b(e,"author"),message:b(e,"message"),provenanceCoverage:e.provenanceCoverage===!0,fleetAttribution:e.fleetAttribution===!0,since:b(e,"since"),eventLimit:typeof e.eventLimit=="number"?e.eventLimit:void 0,minimumSample:typeof e.minimumSample=="number"?e.minimumSample:void 0}}import gF from"node:fs/promises";import rS 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]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function Ps(e,t,n,r,o,i="min"){let a=o==="min"?e-t:t-e,s=i==="min"?n.localeCompare(r??n):(r??n).localeCompare(n);return a<0||a===0&&r!==null&&s<0}function jN(e,t){let n=Buffer.byteLength(t,"utf8"),r=0,o=null,i=null,a=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let l=c.trim();if(l==="")continue;r+=1;let p;try{p=JSON.parse(l)}catch{continue}if(p===null||typeof p!="object"||!("ts"in p)||typeof p.ts!="string")continue;let u=p.ts,f=Date.parse(u);Number.isNaN(f)||(Ps(f,a,u,o,"min")&&(a=f,o=u),Ps(f,s,u,i,"max","max")&&(s=f,i=u))}return{id:e,bytes:n,lines:r,oldest_ts:o,newest_ts:i}}function Gk(e,t){let n=t?.topN??5,r=Math.max(0,Math.floor(n)),o=e.map(({id:h,raw:_})=>jN(h,_)),i=0,a=0,s=null,c=null,l=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY;for(let h of o){if(i+=h.lines,a+=h.bytes,h.oldest_ts!==null){let _=Date.parse(h.oldest_ts);Ps(_,l,h.id,s?.id??null,"min")&&(l=_,s={id:h.id,ts:h.oldest_ts})}if(h.newest_ts!==null){let _=Date.parse(h.newest_ts);Ps(_,p,h.id,c?.id??null,"max")&&(p=_,c={id:h.id,ts:h.newest_ts})}}let u=r===0?[]:[...o].sort((h,_)=>_.bytes-h.bytes||h.id.localeCompare(_.id)).slice(0,r),f=r===0?[]:[...o].sort((h,_)=>_.lines-h.lines||h.id.localeCompare(_.id)).slice(0,r);return{total_streams:e.length,total_lines:i,total_bytes:a,largest_by_bytes:u,deepest_by_lines:f,oldest_entry:s,newest_entry:c}}import{createHash as qN}from"node:crypto";import{execFile as KN}from"node:child_process";import zk from"node:path";import{promisify as zN}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]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var qk=1;function GN(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function Tm(e){if(e===null)return{format_version:qk,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new d("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==qk||!Array.isArray(t.observations))throw new d("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let r of n)if(!GN(r))throw new d("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return t}(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]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var HN=zN(KN),BN=50,Kk=1e3,WN=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Hk(e){let t=e.trim().toLowerCase();if(!WN.test(t))throw new d(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function VN(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new d("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function jo(e,t){let n=e?.trim();if(n){if(n.length>256)throw new d(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function YN(e){let t=e??BN;if(!Number.isSafeInteger(t)||t<0||t>Kk)throw new d(`Improvement observation limit must be an integer from 0 to ${Kk}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Bk(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new d(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function JN(e,t,n){if(!Number.isFinite(n.value))throw new d("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let r=Hk(n.metric),o=VN(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||o==="target"&&n.threshold===void 0)throw new d("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let i=await QN(e,n.revision),a=jo(n.source,"source"),s=jo(n.itemId,"itemId"),c=jo(n.unit,"unit"),l=jo(n.idempotencyKey,"idempotencyKey")??(i.revision_source==="unversioned"?void 0:[i.revision,r,a??"manual",s??"workspace"].join(":")),p={metric:r,value:n.value,direction:o,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Bk(n.observedAt??A(),"observedAt"),...i,author:I(n.author,t.author_default),...s===void 0?{}:{item_id:s},...a===void 0?{}:{source:a},...l===void 0?{}:{idempotency_key:l}};return{id:qN("sha256").update(At(p)).digest("hex").slice(0,24),...p}}function XN(e,t){let n=t.idempotency_key?e.observations.find(o=>o.idempotency_key===t.idempotency_key):e.observations.find(o=>o.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new d(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let r=e.observations.find(o=>o.metric===t.metric);if(r&&(r.direction!==t.direction||r.unit!==t.unit||t.direction==="target"&&r.threshold!==t.threshold))throw new d(`Metric ${t.metric} is already declared with direction ${r.direction} and unit ${r.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function QN(e,t){let n=jo(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await HN("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:ni(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function ZN(e){let t=e[0],n=e[e.length-1],r=n.value-t.value,o=n.direction==="higher"?r>0:n.direction==="lower"?r<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:r,improved:o,sample_count:e.length}}async function Wk(e,t={}){let n=T(process.cwd(),t.path);await O(n);let r=await E(n),o=await JN(n,r,e),i=zk.join(n,"improvement-ledger.json"),a=await oa({pmRoot:n,filePath:i,op:"improvement_observe",author:o.author,lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,message:e.message??`Record ${o.metric}=${String(e.value)} improvement observation`,mutate:s=>{let c=Tm(s),l=XN(c,o);return l?{raw:s,result:l}:(c.observations.push(o),c.observations.sort((p,u)=>p.observed_at.localeCompare(u.observed_at)||p.metric.localeCompare(u.metric)||p.id.localeCompare(u.id)),{raw:`${At(c)}
34
+ `,result:o})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function Vk(e={}){let t=T(e.cwd??process.cwd(),e.pmRoot);await O(t);let n=e.metric===void 0?void 0:Hk(e.metric),r=e.since===void 0?void 0:Bk(e.since,"since"),o=YN(e.limit),i=Tm(await ee(zk.join(t,"improvement-ledger.json"))).observations.filter(s=>(n===void 0||s.metric===n)&&(e.itemId===void 0||s.item_id===e.itemId)&&(r===void 0||s.observed_at>=r)),a=new Map;for(let s of i){let c=a.get(s.metric)??[];c.push(s),a.set(s.metric,c)}return{observations:[...i].reverse().slice(0,o),total:i.length,truncated:i.length>o,trends:[...a].map(([,s])=>ZN(s)).sort((s,c)=>s.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var eF=1e4,Yk=1e5,tF=1e3,nF=30,rF=["append","comment","docs","file","learning","note","test_run"];function oF(e){let t=e??eF;if(!Number.isSafeInteger(t)||t<1||t>Yk)throw new d(`History analytics event limit must be an integer from 1 to ${Yk}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Jk(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new d("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function iF(e){let t=e?.trim();if(!t)return new Date(Date.now()-nF*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let o=Number(n[1]),i=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(o)||o<1)throw new d("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-o*i).toISOString()}let r=Date.parse(t);if(!Number.isFinite(r))throw new d("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(r).toISOString()}async function Xk(e,t){let n=oF(t.eventLimit),r=iF(t.since),o=[],i=r,a=!1;for(;o.length<n;){let s=await Os({pmRoot:e,since:i,limit:Math.min(tF,n-o.length),full:!0}),c=s.events.map(l=>({item_id:l.item_id,entry:l.entry}));if(o.push(...c),a=s.has_more,i=s.next_cursor,!s.has_more)break}return{events:o,receipt:{since:r,events:o.length,truncated:a,...a?{next_cursor:i}:{},source:"history_event_index"}}}function aF(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function sF(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function cF(e){return rF.some(t=>e.startsWith(t))}function Qk(e,t){let n=e.get(t);if(n)return n;let r={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,r),r}function lF(e,t,n){let r=new Map,o=new Map,i=new Map;for(let a of t){let s=aF(a.entry,e),c=sF(a.entry),l=o.get(a.item_id)===!0,p=c===void 0?l:n.has(c);if(c!==void 0&&o.set(a.item_id,p),!s)continue;let u=Qk(r,s);u.events+=1,cF(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!l&&p?(u.closes+=1,i.set(a.item_id,s)):c!==void 0&&l&&!p&&(u.reopens+=1)}return{buckets:r,lastCloseValue:i}}function dF(e,t,n){for(let r of n){if(r.type!=="Issue")continue;let o=new Set((r.dependencies??[]).filter(i=>i.kind==="discovered_from").map(i=>i.id));for(let i of o){let a=t.get(i);a&&(Qk(e,a).defectEscapes+=1)}}}function mF(e,t,n,r){let o=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:o==="available"?t.closes/r:null,rework_rate:o==="available"?t.reopens/t.closes:null,defect_escape_rate:o==="available"?t.defectEscapes/t.closes:null,sample_status:o}}function pF(e,t,n,r,o,i){let{buckets:a,lastCloseValue:s}=lF(e,t,r);return dF(a,s,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,l])=>mF(c,l,o,i)).sort((c,l)=>l.events-c.events||c.value.localeCompare(l.value))}}function uF(e,t){let n=e[0]?.entry.ts??t,r=e[e.length-1]?.entry.ts??n,o=Date.parse(n),i=Date.parse(r);return!Number.isFinite(o)||!Number.isFinite(i)?1:Math.max(1,(i-o)/864e5)}function fF(e,t,n){let r=Ny(t),o=Fy(e,Wr,n),i=o.filter(s=>s.inert).map(s=>({harness:s.harness,dimension:s.dimension,explicit_samples:s.observed+s.unavailable})),a=r.filter(s=>!s.covered).map(s=>s.dimension);return{descriptors:r,observations:o,inert:i,undeclared:a,warnings:[...i.map(s=>`provenance_dimension_inert:${s.harness}:${s.dimension}:${String(s.explicit_samples)}`),...a.map(s=>`provenance_dimension_undeclared:${s}`)]}}function Zk(e,t=Di,n={}){let r=Jk(n.minimumSample);return{...fF(e.events.map(o=>o.entry),t,r),window:e.receipt}}function eS(e,t,n,r={}){let o=Jk(r.minimumSample),i=uF(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>pF(a,e.events,t,n,o,i)),minimum_sample:o,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(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]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var _F=32;function hF(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let i=o.slice(0,o.indexOf("=")).trim();r.length>0&&i!=="unit"&&i!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function Go(e,t){let n=hF(e).map(r=>{let[o,...i]=r.split(","),a=o.indexOf("="),s=o.slice(0,a).trim(),c=o.slice(a+1).trim(),l=Number(c);if(a<=0||s.length===0||c.length===0||!Number.isFinite(l))throw new d(`Invalid --measure "${r}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let p,u;for(let f of i){let h=f.indexOf("="),_=f.slice(0,h).trim(),g=f.slice(h+1).trim();if(_==="unit"&&g.length>0)p=g;else if(_==="threshold"&&g.length>0&&Number.isFinite(Number(g)))u=Number(g);else throw new d(`Invalid --measure attribute "${f}"`,m.USAGE)}return{name:s,value:l,unit:p,threshold:u,recorded_at:t}});return[...new Map(n.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,_F)}function tS(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function nS(e,t){let n=e.flatMap(i=>i.measurements??[]).filter(i=>i.name===t).sort((i,a)=>a.recorded_at.localeCompare(i.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}(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]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function yF(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function wF(e,t,n,r,o){let i=po(e,"type",r),a=new Set(i.rows.map(u=>u.key)),s=t.filter(u=>!a.has(u)),c=(o?[...i.rows,...s.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:i.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),l=yF([...n]);for(let u of e)l[u.status]+=1;let p=Object.fromEntries(Object.entries(l).filter(([,u])=>o||u>0));return{byType:c,byStatus:p,omitted:o?0:s.length+Object.values(l).filter(u=>u===0).length}}function vF(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function bF(e){let t=rS.join(e,"history");if(!await B(t))return[];await Jn({path:t,scope:"project"});let n=(await gF.readdir(t)).filter(o=>o.endsWith(".jsonl")).sort((o,i)=>o.localeCompare(i)),r=[];for(let o of n){let i=rS.join(t,o),a=await ee(i);a!==null&&(await Jn({path:i,scope:"project"}),r.push({id:o.slice(0,-6),raw:a}))}return r}async function kF(e,t){let n=[],r=A();for(let o of Go(t.observe,r))n.push(await Wk({metric:o.name,value:o.value,direction:t.direction,unit:o.unit,threshold:o.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:r,author:t.author,message:t.message},e));return n}function SF(e,t,n){let r={};return t.byAssignee&&(r.assignee=po(e,"assignee",n)),t.byTag&&(r.tag=po(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(r.priority=po(e,"priority",n)),r}async function EF(e,t,n,r,o){let i={since:o.since,eventLimit:o.eventLimit,minimumSample:o.minimumSample},a=o.provenanceCoverage||o.fleetAttribution?await Xk(e,i):void 0;return{provenanceCoverage:o.provenanceCoverage&&a?Zk(a,n.agent_identity?.harness_signals,i):void 0,fleetAttribution:o.fleetAttribution&&a?eS(a,t,r,i):void 0}}function AF(e,t,n,r,o){let i=Object.keys(o.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:r,...o.metadataCoverage?{metadata_coverage:o.metadataCoverage}:{},...i?{breakdowns:o.breakdowns}:{},...o.storage?{storage:o.storage}:{},...o.fieldUtilization?{field_utilization:o.fieldUtilization}:{},...o.improvementLedger?{improvement_ledger:o.improvementLedger}:{},...o.recordedObservations.length>0?{recorded_observations:o.recordedObservations}:{},...o.provenanceCoverage?{provenance_coverage:o.provenanceCoverage}:{},...o.fleetAttribution?{fleet_attribution:o.fleetAttribution}:{},generated_at:A()}}async function Cm(e,t={}){let n=T(process.cwd(),e.path);await O(n);let r=await E(n),o=await kF(e,t),i=$(r,R()),a=D(r.schema),s=t.fieldUtilization?await H_(n,r.item_format,i.type_to_folder,void 0,r.schema):await ye(n,r.item_format,i.type_to_folder,void 0,r.schema);await T_({pmRoot:n,settings:r,itemIds:s.map(k=>k.id),commandLabel:"stats"});let c=Sa(a),l=wF(s,i.types,a.definitions.map(k=>k.id),c,t.includeEmpty===!0),p=await bF(n),u=0;for(let k of p)u+=vF(k.raw);let f=t.storage?Gk(p):void 0,h=t.metadataCoverage?Oh(s,c):void 0,_=SF(s,t,c),g=t.fieldUtilization?xh(s):void 0,y=t.measurements===!0||o.length>0?await Vk({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:w,fleetAttribution:v}=await EF(n,s,r,a.terminal_statuses,t);return AF({items:s.length,history_streams:p.length,history_entries:u},l.byType,l.byStatus,l.omitted,{metadataCoverage:h,breakdowns:_,storage:f,fieldUtilization:g,improvementLedger:y,recordedObservations:o,provenanceCoverage:w,fleetAttribution:v})}import TF from"node:fs/promises";import rn 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]="bc3145a3-5949-5c61-b275-a5376881b91f")}catch{}})();var CF=rn.join("runtime","telemetry","state.json"),qo=rn.join("runtime","telemetry"),IF=20,lS=mn.filter(e=>e.lifecycle==="deprecated"),oS=["status","flush","stats","clear"],iS=(e,t)=>{let n=Math.ceil(t*e.length),r=Math.min(e.length-1,Math.max(0,n-1));return e[r]},Im=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,aS=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},RF=e=>({command:Im(e.event.command,"<unknown>"),eventType:Im(e.event.event_type,"unknown"),eventSchemaVersion:aS(e.event.schema_version),clientSchemaVersion:aS(e.client_schema_version)}),OF=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),xF=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},$F=e=>{let t=e?.command_resolution;return Im(t,"")||void 0},dS=(e,t)=>{e[t]=(e[t]??0)+1},PF=(e,t)=>{let n=xF(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let r=$F(t);r!==void 0&&dS(e.resolution_counts,r)},LF=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,sS=(e,t)=>{t!==void 0&&e.add(t)},NF=(e,t)=>{let n=RF(t),r=e.get(n.command)??OF();r.count+=1,r.max_attempts=Math.max(r.max_attempts,LF(t.attempts)),dS(r.event_type_counts,n.eventType),sS(r.event_schema_versions,n.eventSchemaVersion),sS(r.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&PF(r,t.event.payload),e.set(n.command,r)},FF=(e,t)=>{let n=t.ok_count+t.error_count,r=[...t.finish_durations_ms].sort((i,a)=>i-a),o=Object.entries(t.resolution_counts).sort((i,a)=>i[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((i,a)=>i[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((i,a)=>i-a),client_schema_versions:[...t.client_schema_versions].sort((i,a)=>i-a),...r.length>0?{duration_p50_ms:iS(r,.5),duration_p95_ms:iS(r,.95),duration_max_ms:r[r.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...o.length>0?{command_resolution_counts:Object.fromEntries(o)}:{}}},MF=e=>{let t=(e??"status").trim().toLowerCase();if(oS.includes(t))return t;throw Le({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:oS,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},Om=()=>{throw new d("--limit must be a positive integer",m.USAGE)},mS=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?Om():e,DF=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?Om():mS(Number.parseInt(t,10))},UF=e=>e===void 0?IF:typeof e=="number"?mS(e):typeof e=="string"?DF(e):Om(),jF=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},GF=e=>{try{let t=JSON.parse(e);return jF(t)?t:void 0}catch{return}},qF=e=>e===null?[]:e.split(`
35
+ `).map(t=>t.trim()).filter(t=>t.length>0),pS=e=>{let t=qF(e),n=[],r=0;for(let o of t){let i=GF(o);i===void 0?r+=1:n.push(i)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:r,entries:n}},KF=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zF=e=>{try{let t=JSON.parse(e);return KF(t)?t:{}}catch{return{}}},Rm=async e=>{let t=await ee(e);return t===null||t.trim().length===0?{}:zF(t)};function HF(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function BF(e,t,n){let r=Object.create(null);for(let[o,i]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(o)||o<t||o>n||typeof i!="object"||i===null||Array.isArray(i))continue;let a=i;!Number.isSafeInteger(a.count)||a.count<1||typeof a.last_seen!="string"||!a.last_seen.startsWith(o)||(r[o]={count:a.count,last_seen:a.last_seen})}return r}function cS(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let r=e,o=new Date().toISOString().slice(0,10);for(let i of lS){let a=r[i.alias];if(typeof a!="object"||a===null||Array.isArray(a))continue;let s=a;if(s.canonical!==i.canonical||typeof s.days!="object"||s.days===null||Array.isArray(s.days))continue;let c=BF(s.days,t,o);Object.keys(c).length>0&&(n[i.alias]={canonical:i.canonical,days:c})}return n}async function WF(e,t,n){let r=HF(n),o=await Rm(t),i=cS(o.alias_usage,r);if(JSON.stringify(o.alias_usage??{})===JSON.stringify(i))return i;try{await wl(async()=>{let a=await Rm(t);if(a.alias_usage===void 0)return;let s=cS(a.alias_usage,r);JSON.stringify(a.alias_usage)!==JSON.stringify(s)&&await re(t,`${JSON.stringify({...a,alias_usage:s},null,2)}
36
+ `)},e,250)}catch{}return i}var Ls=e=>e??null,Ns=async e=>{let t=await E(e),n=rn.join(e,qo,oo("events.jsonl")),r=rn.join(e,qo,oo("state.json")),o=await ee(n),i=pS(o),a=await Rm(r),s=pa();return{enabled:t.telemetry.enabled&&!s.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:s,endpoint:V_(Y_(t.telemetry.endpoint)),queue_path:n,state_path:r,queue_rows_total:i.rows_total,queue_entries:i.valid_entries,queue_invalid_rows:i.invalid_rows,queue_size_bytes:Buffer.byteLength(o??"","utf8"),last_attempted_flush_at:Ls(a.last_attempted_flush_at),last_successful_flush_at:Ls(a.last_successful_flush_at),last_failed_flush_at:Ls(a.last_failed_flush_at),last_failed_flush_error:Ls(a.last_failed_flush_error)}},VF=e=>{let t=new Map;for(let n of e)NF(t,n);return[...t.entries()].map(([n,r])=>FF(n,r)).sort((n,r)=>r.count-n.count||n.command.localeCompare(r.command))},YF=async(e,t)=>({action:"telemetry",subcommand:"status",status:await Ns(t.globalPmRoot),generated_at:A()}),JF=async(e,t)=>{let n=await Ns(t.globalPmRoot);await th(t.globalPmRoot);let r=await Ns(t.globalPmRoot),o=Math.max(0,n.queue_entries-r.queue_entries),i=r.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:r.queue_entries,queue_entries_drained:o,queue_progressed:o>0,queue_empty:i,queue_drained:i,status:r,generated_at:A()}},XF=async(e,t)=>{let n=UF(e.limit),r=await ee(t.queuePath),o=pS(r),i=VF(o.entries),a=i.slice(0,n),s=await E(t.globalPmRoot),c=await WF(t.globalPmRoot,rn.join(t.globalPmRoot,CF),s.telemetry.retention_days),l=Object.entries(c).map(([p,u])=>{let f=Object.values(u.days);return{alias:p,canonical:u.canonical,count:f.reduce((h,_)=>Math.min(Number.MAX_SAFE_INTEGER,h+_.count),0),last_seen:f.map(h=>h.last_seen).sort().at(-1)}}).sort((p,u)=>u.count-p.count||p.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:i.length,queue_entries:o.valid_entries,queue_invalid_rows:o.invalid_rows,queue_rows_total:o.rows_total,truncated:i.length>a.length,stats:a,alias_usage:l,zero_use_aliases:lS.map(p=>p.alias).filter(p=>c[p]===void 0),alias_usage_retention_days:s.telemetry.retention_days,generated_at:A()}},QF=async(e,t)=>wl(async()=>{let n=await E(t.globalPmRoot),r=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",r&&await Re(t.globalPmRoot,n,"telemetry:clear");let o=rn.join(t.globalPmRoot,qo),i=await B(o);return await TF.rm(o,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:r,runtime_dir_removed:i&&!await B(o),queue_exists_after:await B(t.queuePath),state_exists_after:await B(t.statePath),status:await Ns(t.globalPmRoot),generated_at:A()}},t.globalPmRoot),ZF={status:YF,flush:JF,stats:XF,clear:QF};async function uS(e,t){let n=MF(e.subcommand),r=$e(process.cwd());return ZF[n](e,{globalPmRoot:r,queuePath:rn.join(r,qo,oo("events.jsonl")),statePath:rn.join(r,qo,oo("state.json"))})}(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]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var fS=20;function eM(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return fS;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?fS:t}function xm(e){let t=[...e].filter(r=>r.run_id.trim().length>0&&r.started_at.trim().length>0&&r.finished_at.trim().length>0&&r.recorded_at.trim().length>0).sort((r,o)=>{let i=Fi(r.recorded_at,o.recorded_at);if(i!==0)return i;let a=r.run_id.localeCompare(o.run_id);return a!==0?a:r.kind.localeCompare(o.kind)}),n=eM();return t.length>n?t.slice(t.length-n):t}async function Fs(e){await _e({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=xm([...n,e.entry]),{changedFields:["test_runs"]}}})}(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]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function _S(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function $m(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=_S(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let i of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof i=="number"&&(!Array.isArray(o)||i>=o.length))return{found:!1,value:void 0};let a=Object.getOwnPropertyDescriptor(o,i);if(!a||!Object.hasOwn(a,"value"))return{found:!1,value:void 0};o=a.value}return{found:!0,value:o}}(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]="626315a0-7ee9-500d-bb7a-9bcd33eae209")}catch{}})();var tM=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],nM=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function Ms(e,t){let n=`${e}
37
+ ${t}`;for(let r of tM)if(r.regex.test(n))return{code:r.code};return null}function hS(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=nM.find(i=>i.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}function gS(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function yS(e,t={}){let n=t.trackerPath?.trim();return L(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}import{cp as cM,lstat as lM,mkdir as dM,readlink as mM,realpath as Nm,stat as pM,symlink as bS}from"node:fs/promises";import{execFile as uM}from"node:child_process";import z from"node:path";import{promisify as fM}from"node:util";import{execFile as rM}from"node:child_process";import{readdir as oM,realpath as iM}from"node:fs/promises";import aM from"node:path";import{promisify as sM}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]="e67d1a06-77f7-5e86-8f15-bde8b6db0d5a")}catch{}})();var Pm=sM(rM),wS=".agents/pm/merge-receipts";async function vS(e,t,n){let r=aM.join(n,"merge-receipts"),o=(await oM(r).catch(c=>{if(Ge(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-LSBWMXKS.js"),a=o.length===0?new Map:await i(e,r,o,Kh,await iM(r),{failOnReadError:!0}),s={cwd:t,env:qh(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await Pm("git",["rm","-q","-r","--cached","--ignore-unmatch","--",wS],s);for(let[c,l]of a){let p=Pm("git",["hash-object","-w","--stdin"],s),u=p.child.stdin;u!==null&&(u.on("error",()=>{p.child.kill()}),u.end(l));let f=(await p).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(f))throw new Error("Invalid snapshot receipt object identity.");await Pm("git",["update-index","--add","--cacheinfo","100644",f,`${wS}/${c}`],s)}}(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]="6638f21c-6cf5-5dec-a0d9-91ae323afce3")}catch{}})();var _M=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),Ds=fM(uM);async function hM(e,t){let n=await Us(z.join(e,".git"));if(!n||n.isDirectory()&&!await Us(z.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await Ds("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await Ds("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await Ds("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await Ds("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function gM(e,t,n,r){await hM(e,t)&&n&&r!==!1&&await vS(e,t,n)}function Lm(e){return e.split(z.sep).some(t=>_M.has(t.toLowerCase()))}function Ko(e){return e===".."||e.startsWith(`..${z.sep}`)||z.isAbsolute(e)}async function Us(e){try{return await pM(e)}catch(t){if(!Ge(t))throw t;return}}async function js(e){let t=[],n=e;for(;z.dirname(n)!==n;)try{return z.join(await Nm(n),...t)}catch(r){if(!Ge(r))throw r;t.unshift(z.basename(n)),n=z.dirname(n)}return z.join(await Nm(n),...t)}async function yM(e,t,n){let r=z.relative(t,await js(e));if(!Ko(r))return r;let o=[],i=e;for(;z.dirname(i)!==i;){let a=await js(i),s=n.find(([,c])=>c===a);if(s)return z.join(s[0],...o);o.unshift(z.basename(i)),i=z.dirname(i)}return r}async function kS(e,t,n,r){let o=[],i=[],a=await Nm(e),s=await js(z.resolve(t));if(![z.relative(a,s),z.relative(s,a)].every(Ko))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await dM(z.dirname(t),{recursive:!0}),await gM(a,t,n,r),await cM(a,t,{recursive:!0,force:!0,async filter(c){let l=z.relative(a,c);if(!l)return!0;if(Lm(l))return!1;if(z.basename(c).toLowerCase()==="node_modules"){if((await Us(c))?.isDirectory()){let p=await js(c),u=z.relative(a,p);if(!Ko(z.relative(p,a))||!Ko(u)&&(Lm(u)||!u.split(z.sep).some(f=>f.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${l}`);o.push([l,p])}return!1}return(await lM(c)).isSymbolicLink()?(i.push([l,z.resolve(z.dirname(c),await mM(c)),(await Us(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of o)await bS(z.resolve(a,c),z.join(t,c),"junction");for(let[c,l,p]of i){let u=await yM(l,a,o);if(Ko(u)||Lm(u))throw new Error(`Source symlink must target included workspace source: ${c}`);await bS(z.resolve(t,u),z.join(t,c),p)}}import{execFile as wM}from"node:child_process";import{constants as SS}from"node:fs";import{access as vM,open as bM}from"node:fs/promises";import ES from"node:path";import{promisify as kM}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]="b42f8889-4b5a-5391-b8e4-b68084e20a49")}catch{}})();var SM=kM(wM);function EM(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function AM(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function TM(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await bM(ES.resolve(t,n),SS.O_RDONLY|SS.O_NONBLOCK),o;try{let a=Buffer.alloc(256),{bytesRead:s}=await r.read(a,0,a.length,0);if(o=a.toString("utf8",0,s),s===a.length&&!o.includes(`
38
+ `))return!1}finally{await r.close()}let i=o.match(/^#![ \t]*(\/[^ \t\n]+)(?:[ \t\n]|$)/u)?.[1];if(!i)return!1;try{return await vM(i),!1}catch(a){return St(a)}}catch{return!1}}async function AS(e,t,n,r){if(/[;&|<>()`$\r\n]/u.test(e))return!1;let o=EM(e);if(!o||!AM(o,t.exitCode,t.stderr))return!1;let i=process.platform==="win32",a=i?ES.join(n.SystemRoot??"C:\\Windows","System32","where.exe"):"/bin/sh",s=i?[o]:["-c",'command -v "$1"',"pm-linked-test-resolution",o];try{let{stdout:c}=await SM(a,s,{env:n,cwd:r,timeout:1e3,windowsHide:!0});return!i&&TM(c,r)}catch(c){let l=c;if(l.killed||l.signal)return!1;let p=l.code;return p===1||!i&&p===127}}import{spawn as GS}from"node:child_process";import{cp as CS,mkdir as jm,mkdtemp as qS,open as Mm,readdir as Dm,rm as Ho,symlink as CM}from"node:fs/promises";import{tmpdir as KS}from"node:os";import ce 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]="47772627-d807-55f3-95b3-69e3b00c6522")}catch{}})();function TS(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(a=>a.phase!=="setup"&&typeof a.stdout=="string"&&a.failure_category!=="spawn_error"&&a.failure_category!=="empty_run"&&Ms(a.stdout,a.stderr??"")===null))return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new d("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:L(i),suggested_retry_args:i}})}function Fm(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let i=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],a=[...i,...gh(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],s=t.acknowledgeLinkedTests?[...i,"test",e,"--help"]:a,c=[...i,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new d("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${L([...i,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${L(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${L(a)}`]}:{},recovery:{missing:["--run"],suggested_retry:L(s),suggested_retry_args:s}})}(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]="36de91bf-47b8-5755-ad92-6ed1a1bbcd82")}catch{}})();var Ks=20*1024*1024,IM=3e3,RM=1e4,OM=5e3,IS=120,xM=new Set(["locks","extensions","runtime"]),$M=new Set(["history","index","search","extensions","locks","runtime"]),PM=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],LM=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,NM=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,FM=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Gm(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0?t:r}function MM(){return Gm("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",IM)}function DM(){return Gm("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",RM)}function UM(){return Gm("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",OM)}function jM(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function GM(e){let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"||o.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}}function qm(e){let t=0,n=0,r=0,o=0;for(let i of e){let a=i.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(r+=1),a.auto_pm_context_applied===!0&&(o+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:r,auto_remediated:o}}function qM(e){let t=e??"project";if(!kt.includes(t))throw new d(`Invalid scope "${e}"`,m.USAGE);return t}function Hs(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(En.includes(t))return t;throw new d(`Invalid --pm-context value "${e}". Expected one of: ${En.join(", ")}`,m.USAGE)}function zS(e){return Tn(e??"source","--workspace-context")}function HS(e,t,n){return n?t:Tn(e.workspace_context_mode,"linked test")??t}function BS(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:Hs(e.pm_context_mode)}function WS(e,t){return e==="auto"?t?"tracker":"schema":e}function KM(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function zM(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:r}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&r==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function HM(e,t){let n={};if(!e)return n;for(let r of e){let o=To(r,t);if(o)for(let[i,a]of Object.entries(o))n[i]=a}return n}function BM(e,t){if(!e)return[];let n=[];for(let r of e){let o=Co(r,t);o&&n.push(...o)}return[...new Set(n)]}function WM(e){let t=xa(e);return Oa(t).some(n=>Ll(n)!==null)}function VS(e){let t=xa(e);return Oa(t).some(n=>{let r=Ll(n);if(!r)return!1;let o=Bg(r);return o?FM.has(o.subcommand):!1})}function Gs(e){if(e)return Gg.has(e.subcommand)?mr(e.args,qg)?.subcommand:e.subcommand}function RS(e,t){if(e==="npx"||e==="bunx")return Nl(t)?.command;if(e==="pnpm")return Gs(mr(t,Mg));if(e==="npm")return Gs(mr(t,Dg));if(e==="yarn")return Gs(mr(t,Ug));if(e==="bun")return Gs(mr(t,jg))}function qs(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function YS(e){let t=e.split(" ").filter(a=>a.length>0),n=Kg(t);if(n.length===0)return!1;let[r,...o]=n,i=Wg.get(r);if(i){let a=o.findIndex(s=>i.test(s));return a>=0&&YS(o.slice(a+1).join(" "))}return r==="vitest"||r.endsWith("/vitest")||r.endsWith("/vitest.mjs")?!0:r==="node"?VM(o):YM(r,o)}function VM(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function YM(e,t){return e==="npx"||e==="bunx"?qs(Nl(t)?.command):e==="pnpm"||e==="npm"?qs((e==="pnpm"?zg(t):Hg(t))?.command)||qs(RS(e,t)):(e==="yarn"||e==="bun")&&qs(RS(e,t))}function JM(e){if(Vg(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function XM(e){return e?e.map(QM):[]}function QM(e){let t=e.trim(),n=t_(t)?Wi(fe(e,"--add"),"--add"):{command:t},r=ve(n.command);if(!r)throw new d("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return yo(r),{command:r,path:ve(n.path),scope:qM(n.scope),timeout_seconds:ZM(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Ya(ve(n.pm_context_mode),"--add"),workspace_context_mode:Tn(ve(n.workspace_context_mode),"--add"),env_set:To(ve(n.env_set),"--add"),env_clear:Co(ve(n.env_clear),"--add"),shared_host_safe:Va(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Cn(ve(n.assert_stdout_contains)),assert_stdout_regex:br(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Cn(ve(n.assert_stderr_contains)),assert_stderr_regex:br(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ja(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Xa(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Qa(ve(n.assert_json_field_gte),"--add"),note:ve(n.note),phase:wr(n.phase,"--add")}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function ZM(e,t){if(e&&t&&e!==t)throw new d("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let r=Math.floor(ge(n,"timeout_seconds"));if(r<=0)throw new d("--add timeout_seconds must be a positive integer",m.USAGE);return r}function eD(e){return e?e.flatMap(t=>{let n=Io(t,"--add-json");for(let r of n){let o=r.command;if(!o)throw new d("--add-json requires a non-empty command string",m.USAGE);yo(o)}return n}):[]}function tD(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new d("--remove requires command or path value",m.USAGE);let r=/^(command|path)\s*=/i.exec(n);if(r){let o=n.slice(r[0].length).trim();if(!o)throw new d("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:r[1].toLowerCase(),value:o}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new d("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let o=fe(n,"--remove"),i=o.path!==void 0?"path":"command",a=o.path??o.command;if(!a?.trim())throw new d("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:i,value:a.trim()}}return{kind:"either",value:n}}):[]}function nD(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new d("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function rD(e){try{e.stdin?.end()}catch{}}function JS(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=IS?t:`${t.slice(0,IS-3)}...`}function XS(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Um(e){try{process.stderr.write(`${e}
39
+ `)}catch{}}function oD(e,t){if(!XS(t))return null;let n=JS(e.command),r=Date.now();Um(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let o=setInterval(()=>{let i=Date.now()-r;Um(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${i} command="${n}"`)},DM());return o.unref?.(),o}function iD(e,t,n,r){if(!XS(r))return;let o=JS(e.command),i=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",s=[];t.timedOut&&s.push("reason=timeout"),t.maxBufferExceeded&&s.push("reason=max_buffer"),t.outputTruncated&&s.push("output=truncated"),t.signal&&s.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),l=s.length>0?` ${s.join(" ")}`:"";Um(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${c} elapsed_ms=${i}${l} command="${o}"`)}async function OS(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=GS("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function aD(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function sD(e,t){let n=!1;return async()=>{if(n)return;n=!0;let r=e.pid;if(!r||r<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await OS(r);return}try{process.kill(-r,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{OS(r)},MM()),t.forceKillTimer.unref?.()}}function cD(e){return new Promise(t=>{let n=!1,r=null,o=(i,a=!1)=>{n||(n=!0,r&&(clearTimeout(r),r=null),a&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(i))};e.on("exit",(i,a)=>{n||(r=setTimeout(()=>{o({code:i,signal:a},!0)},UM()),r.unref?.())}),e.on("close",(i,a)=>{o({code:i,signal:a})})})}function lD(e,t,n,r,o){return GS(e,{cwd:o,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,r]})}async function xS(e){let t=await Mm(e,"r");try{let n=(await t.stat()).size,r=Math.min(n,Ks),o=Buffer.alloc(r);return r>0&&await t.read(o,0,r,0),{text:o.toString("utf8"),truncated:n>Ks}}finally{await t.close()}}async function dD(e,t,n,r,o,i=process.cwd()){let a=Date.now(),s=await qS(ce.join(KS(),"pm-linked-test-output-"));try{let c=ce.join(s,"stdout.log"),l=ce.join(s,"stderr.log"),[p,u]=await Promise.all([Mm(c,"w"),Mm(l,"w")]),f;try{f=lD(e,n,p.fd,u.fd,i)}catch(Y){throw await Promise.all([p.close(),u.close()]),Y}let h=cD(f),_;f.on("error",Y=>{_=Y.message}),await Promise.all([p.close(),u.close()]),rD(f);let g={heartbeat:oD(r,o),forceKillTimer:null,timedOutTimer:null},y=sD(f,g),w=!1;g.timedOutTimer=setTimeout(()=>{w=!0,y()},t),g.timedOutTimer.unref?.();let{code:v,signal:k}=await h;aD(g);let[C,S]=await Promise.all([xS(c),xS(l)]),x=C.truncated||S.truncated,N=x?`
40
+ [pm linked-test output truncated at ${Ks} bytes per stream; the child process continued to completion]
41
+ `:"";!_&&await AS(e,{exitCode:v,stderr:S.text},n,i)&&(_="Linked test executable was not found. Install the tool or update the linked command before retrying.");let P={stdout:`${C.text}${N}`,stderr:S.text,exitCode:v,signal:k,timedOut:w,maxBufferExceeded:!1,outputTruncated:x,spawnError:_};return iD(r,P,a,o),P}finally{await Ho(s,{recursive:!0,force:!0})}}function mD(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${Ks} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function pD(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
42
+ `);return PM.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>LM.test(n)&&NM.test(n))}function uD(e){return pD(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function $S(e,t){for(let[n,r]of Object.entries(t.env_set))An.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)An.has(n.toUpperCase())||delete e[n]}function fD(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function _D(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function QS(e,t,n){return{env_set:HM(e,"--env-set"),env_clear:BM(t,"--env-clear"),shared_host_safe:n===!0}}async function zo(e,t,n=!1,r=jm){if(await B(e))try{await Mr("seed_linked_test",async()=>{if(await r(ce.dirname(t),{recursive:!0}),n){await CS(e,t,{recursive:!0,force:!0});return}await CS(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&Ge(o))return;throw o}}async function PS(e,t,n,r=!1){for(let[o,i]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let a=await ee(oe(o));if(a!==null){let s=await E(i);await nt({pmRoot:i,filePath:oe(i),raw:a,op:"settings:write",author:I(void 0,s.author_default),lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await zo(oe(o),oe(i));await zo(ce.join(n.projectPmRoot,"extensions"),ce.join(e,"extensions"),!0),await zo(ce.join(n.globalPmRoot,"extensions"),ce.join(t,"extensions"),!0)}async function LS(e,t){if(!await B(e))return;let n=await Dm(e,{withFileTypes:!0});for(let r of n){if(xM.has(r.name))continue;let o=ce.join(e,r.name),i=ce.join(t,r.name);if(r.isDirectory()){await zo(o,i,!0);continue}r.isFile()&&await zo(o,i)}}async function NS(e,t){let n=await ee(oe(e));if(n===null||await B(pl(e)))return;let r=await E(t);await Ho(pl(t),{force:!0}),await Ho(oe(t),{force:!0}),await nt({pmRoot:t,filePath:oe(t),raw:n,op:"settings:write",author:I(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Rr(e){if(!await B(e))return 0;let t=0,n=await Dm(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||$M.has(r.name))continue;let o=ce.join(e,r.name),i;try{i=await Dm(o,{withFileTypes:!0})}catch{continue}for(let a of i)a.isFile()&&Rp.some(s=>a.name.toLowerCase().endsWith(s))&&(t+=1)}return t}function hD(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function gD(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function yD(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?ie(e,t):Object.is(e,t)}function wD(e,t,n){let r=[];r.push(...FS("stdout",t,e.assert_stdout_contains)),r.push(...MS("stdout",t,e.assert_stdout_regex)),r.push(...FS("stderr",n,e.assert_stderr_contains)),r.push(...MS("stderr",n,e.assert_stderr_regex)),r.push(...vD(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},i=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(i).length>0))return r;let a;try{a=JSON.parse(t)}catch(s){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${s instanceof Error?s.message:String(s)}`),r}for(let[s,c]of Object.entries(o)){let l=$m(a,s);if(!l.found){r.push(`assert_json_field_equals missing path "${s}"`);continue}let p=gD(c);yD(l.value,p)||r.push(`assert_json_field_equals mismatch at "${s}" (expected=${JSON.stringify(p)} actual=${JSON.stringify(l.value)})`)}for(let[s,c]of Object.entries(i)){let l=$m(a,s);if(!l.found){r.push(`assert_json_field_gte missing path "${s}"`);continue}if(typeof l.value!="number"||!Number.isFinite(l.value)){r.push(`assert_json_field_gte path "${s}" resolved to non-numeric value`);continue}l.value<c&&r.push(`assert_json_field_gte failed at "${s}" (expected >= ${c}, actual ${l.value})`)}return r}function FS(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function MS(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(i){r.push(`${e} regex assertion is invalid: /${o}/ (${i instanceof Error?i.message:String(i)})`)}return r}function vD(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function bD(e){let t=xa(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Oa(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&YS(n))}function kD(e){return{root:e,schemaProjectPmPath:ce.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:ce.join(e,"schema","global"),trackerProjectPmPath:ce.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:ce.join(e,"tracker","global"),workspaceSnapshotRoot:ce.join(e,"workspace","project"),workspaceIsolatedRoot:ce.join(e,"workspace","isolated")}}function SD(e,t,n){return e.some(r=>HS(r,t,n)==="snapshot")}async function ED(e,t){let n=ce.join(e,".agents"),r=ce.join(n,"pm");await jm(n,{recursive:!0}),await Ho(r,{recursive:!0,force:!0}),await CM(t,r,process.platform==="win32"?"junction":"dir")}async function AD(e,t=$o,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function TD(e,t,n){t&&(await PS(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await PS(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await LS(t.projectPmRoot,e.trackerProjectPmPath),await LS(t.globalPmRoot,e.trackerGlobalPmPath),await NS(t.projectPmRoot,e.trackerProjectPmPath),await NS(t.globalPmRoot,e.trackerGlobalPmPath)))}function CD(e,t,n){return e.some(r=>{let o=r.command??"",i=o.length>0&&VS(o),a=n?.autoPmContext===!0&&i?"auto":BS(r,t,n?.overrideLinkedPmContext===!0);return WS(a,i)==="tracker"})}async function ID(e,t){return{sourceProjectItemCount:t?await Rr(t.projectPmRoot):0,sourceGlobalItemCount:t?await Rr(t.globalPmRoot):0,schemaProjectItemCount:await Rr(e.schemaProjectPmPath),schemaGlobalItemCount:await Rr(e.schemaGlobalPmPath),trackerProjectItemCount:await Rr(e.trackerProjectPmPath),trackerGlobalItemCount:await Rr(e.trackerGlobalPmPath)}}function RD(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,i=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,s=e.workspaceContextMode==="isolated"?"":a;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:i,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==i),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:s,trust:e.trust}}async function OD(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?Hs(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?WM(n):!1,o=r&&n?VS(n):!1,i=e.options?.autoPmContext===!0&&o,a=i?"auto":BS(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),s=WS(a,o),c=s==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await ED(e.layout.workspaceSnapshotRoot,c);let l=e.options?.pmRoot?await Fl(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Fl(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:RD({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:a,effectivePmContextMode:s,autoPmContextApplied:i,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:l})}}function DS(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function xD(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function $D(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function PD(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return $D(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function LD(e){if(!e.linkedTest.command)return DS(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=JM(e.linkedTest.command);return t?DS(e.linkedTest,e.executionContext,t):null}function ND(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?zs(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?zs(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function zs(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function FD(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=zM({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return zs(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function MD(e){return LD(e)||PD(e)||ND(e)||FD(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!KM(e.linkedTest)?zs(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function DD(e){let t=_D(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return $S(n,e.runtimeDirectives),$S(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&fD(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ho]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ho]="read_only"),n}function UD(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function US(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function jD(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:hD(e.execution),failure_category:uD(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:mD(e.execution,e.timeoutMs)}}function GD(e){let t=hS(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&bD(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=Ms(e.execution.stdout,e.execution.stderr);if(o)return US({...e,emptyRunSignal:o});if(n&&!t)return US({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=wD(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?xD(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):UD(e.linkedTest,e.executionContext,e.execution,t)}async function qD(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await dD(t,n,DD(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?GD({...e,execution:r}):jD({...e,execution:r,timeoutMs:n})}async function Km(e,t,n){let r=za(e);for(let y of r)Vr(y.command);let o=[],i=await qS(ce.join(KS(),"pm-linked-test-")),a=kD(i),s=Hs(n?.pmContext),c=zS(n?.workspaceContext),l=n?.progress===!0?"always":"auto",p=QS(n?.envSet,n?.envClear,n?.sharedHostSafe),u=n?.sourceRoots,f=Jg(),h=CD(r,s,n),_=SD(r,c,n?.overrideLinkedWorkspaceContext===!0),g=await Yg(f);try{await AD(a,$o,h),await jm(a.workspaceIsolatedRoot,{recursive:!0}),await TD(a,u,h),_&&await kS(f,a.workspaceSnapshotRoot,u?.projectPmRoot,h);let y=await ID(a,u),w=Ao(),v=S=>HS(S,c,n?.overrideLinkedWorkspaceContext===!0),k=new Set(r.filter(S=>!Oe(S)).map(v)),C=async(S,x)=>{let N=w.options(S,n),P=v(S),Y=Gy(S,P,k);if(Y)return Y;let j=await OD({linkedTest:S,layout:a,counts:y,sourceRoots:u,runLevelPmContextMode:s,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:P,currentSourceRef:g,sourceWorkspaceRoot:f});return MD({linkedTest:S,executionContext:j.executionContext,runLevelPmContextMode:s,linkedOverridePmContextMode:j.linkedOverridePmContextMode,options:N})??await qD({linkedTest:S,index:x,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:p,progressMode:l,executionContext:j.executionContext,options:N})};for(let S=0;S<r.length;S+=1){let x=r[S];o.push(w.blocked(x)??w.record(x,await C(x,S)))}}finally{await Ho(a.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return o}function KD(e,t){let n=[...t];return e.filter(r=>{let o=n.findIndex(i=>Yr(i,r));return o>=0&&n.splice(o,1),o<0}).length}async function zD(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,i=await K(n,t,r.id_prefix,r.item_format,o);if(!i)throw new d(`Item ${t} not found`,m.NOT_FOUND);let a=await ne(i,{schema:r.schema});return{itemId:i.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function HD(e,t){let n=[...e];for(let r of t)n.some(o=>Yr(o,r))||n.push(r);return n}function BD(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((i,a)=>r.has(a+1)?!1:!t.some(s=>s.kind==="command"?i.command===s.value:s.kind==="path"?i.path===s.value:i.command===s.value||i.path===s.value));return{tests:o,removed:e.length-o.length}}function WD(e,t,n,r){return BD(HD(e,t),n,r)}function VD(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function ZS(e){if(VD(e)&&e.run!==!0)throw new d("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new d("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new d("--match, --only-index, and --only-last require --run",m.USAGE)}async function YD(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:i,adds:a,removes:s,removeIndexes:c}=e;if(a.length===0&&s.length===0&&c.length===0)return zD({id:t,pmRoot:r,settings:o,typeToFolder:i});let l=0,p=[],u=await _e({pmRoot:r,settings:o,id:t,op:a.length>0?"tests_add":"tests_remove",author:I(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(h){let _=h.metadata.tests??[],g=WD(_,a,s,c);if(Qc(()=>eE(n,g.tests)),l=g.removed,(s.length>0||c.length>0)&&l===0)throw new d("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...s.map(y=>`${y.kind}=${y.value}`),...c.map(y=>`index=${y}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return h.metadata.tests=g.tests,p=_,{changedFields:ie(_,g.tests)?[]:["tests"]}}}),f=u.item.tests??[];return{itemId:u.item.id,tests:f,testRuns:u.item.test_runs??[],changed:u.changedFields.length>0,removed:l,written:u.changedFields.length>0?fg(p,f):[],storedRemoved:KD(p,f)}}function eE(e,t){let n=Hs(e.pmContext);zS(e.workspaceContext),QS(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:yr(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:ge(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new d(`--timeout must be a positive number (got "${e.timeout}")`,m.USAGE);ZS(e);let i=e.run===!0?jy(Uy(t,r),t):void 0;if(i)for(let a of i.selected)Vr(a.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:i,testsToRun:i?.selected??t}}async function JD(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await Km(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:$e(process.cwd())}})}function XD(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=qm(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function QD(e){let t=GM(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=A(),i=Go(e.options.measure,o);return{run_id:jM("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:i.length>0?i:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function ZD(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:i,runResults:a,failOnSkippedTriggered:s,warnings:c}=e;if(t.run!==!0||!i)return;let l=QD({options:t,runStartedAt:i,runResults:a,failOnSkippedTriggered:s});if(r.testing.record_results_to_items!==!0)return{entry:l,receipt:{recorded:!1,reason:"tracking_disabled",run_id:l.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Fs({pmRoot:n,settings:r,itemId:o,author:I(t.author,r.author_default),message:`Track test run summary (${l.run_id})`,entry:l}),{entry:l,receipt:{recorded:!0,reason:"recorded",run_id:l.run_id}}}catch(p){if(vn(p))throw p;return c.push(`test_result_tracking_failed:${o}:${p instanceof Error?p.message:String(p)}`),{entry:l,receipt:{recorded:!1,reason:"write_failed",run_id:l.run_id}}}}function jS(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),i=e.metricBelow.slice(0,o).trim(),a=e.metricBelow.slice(o+1).trim(),s=Number(a);if(o<=0||i.length===0||a.length===0||!Number.isFinite(s))throw new d("--metric-below must use name=value",m.USAGE);r=tS(t,i,s)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:nS(t,e.metricDiff)}}async function eU(e,t,n){if(e.acknowledgeLinkedTests===!0)return Xg(t,n,A())}function tU(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:i,warnings:a,recording:s,measurementProjection:c,restoreScope:l}=e,p=rU(t,e.fullHistory),u=nU(t,o,p,l),{counts:f,receipts:h}=Ol(p);return{ok:n.every(_=>_.status!=="failed"&&_.status!=="refused")&&i!==!0,id:t.itemId,tests:u.tests,...u.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count,...o.setup_indexes?{setup_indexes:o.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:i?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||s?.receipt.recorded===!0,...s?{evidence_recording:s.receipt}:{},count:u.count,...t.removed>0?{removed:t.removed}:{},...f,...c,...h}}function nU(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:yS(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function rU(e,t){if(e.written!==void 0)return Rl({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function oU(e,t){let n=e.tests[e.updated_index-1],r=Rl({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:o,receipts:i}=Ol(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...o,...i}}async function Bs(e,t,n){let r=zy(t);if(r){Hy(t),ZS(t),Fm(e,t,n,T(process.cwd(),n.path));let j=await Wy(e,{...r,author:t.author,message:t.message,force:t.force},n);return oU(j,t.fullHistory===!0)}let o=Ht(),i=T(process.cwd(),n.path);await O(i);let a=await E(i);Fm(e,t,n,i),Go(t.measure,"validation"),jS(t,[],void 0);let s=$(a,R()),c=await o.resolveList(t.add,"--add"),l=await o.resolveList(t.addJson,"--add-json"),p=await o.resolveList(t.remove,"--remove"),u=[...XM(c),...eD(l)],f=await pr(u,I(t.author,a.author_default),A())??[],h=tD(p),_=nD(t.removeIndex),g=await YD({id:e,options:t,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,adds:f,removes:h,removeIndexes:_}),y=Qc(()=>eE(t,g.tests)),w=await eU(t,i,g.tests),v=t.run===!0?A():void 0,k=await JD({options:t,runOptions:y,pmRoot:i,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});TS(e,t,n,i,k);let C=vr(k),S=t.run===!0&&t.failOnSkipped===!0&&k.some(j=>j.status==="skipped"),x=XD(t,k);w&&x.push(`linked_test_trust_acknowledged:${w.acknowledged}`);let N=await ZD({options:t,pmRoot:i,settings:a,itemId:g.itemId,runStartedAt:v,runResults:k,failOnSkippedTriggered:S,warnings:x}),P=N?.receipt.recorded?xm([...g.testRuns,N.entry]):g.testRuns,Y=jS(t,P,N?.entry);return tU({item:g,runResults:k,failureCategories:C,runSelection:y.runSelection,failOnSkippedTriggered:S,warnings:x,recording:N,measurementProjection:Y,restoreScope:gS(n,i),ran:t.run===!0,fullHistory:t.fullHistory===!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]="bc840a99-3b4c-5386-81e2-5480897f2d19")}catch{}})();var iU=(e,t)=>{if(e===void 0)return;let n=ae(e,t);if(!n){let r=t.definitions.map(o=>o.id);throw new d(`Invalid --status value "${e}". Allowed: ${r.join(", ")}`,m.USAGE)}return n},aU=e=>{if(e===void 0)return;let t=ge(e,"timeout");if(t<=0)throw new d("timeout must be a positive number",m.USAGE);return t},tE=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new d(`${t} must be a non-negative integer`,m.USAGE);return n},sU=e=>e instanceof Error?e.message:String(e),cU=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},lU=e=>e.trim().replaceAll(/\s+/g," "),dU=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),mU=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),pU=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},uU=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ws=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),nE=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),fU=e=>typeof e=="number"?e:void 0,_U=e=>{let t={assert_stdout_contains:Ws(e.assert_stdout_contains),assert_stdout_regex:Ws(e.assert_stdout_regex),assert_stderr_contains:Ws(e.assert_stderr_contains),assert_stderr_regex:Ws(e.assert_stderr_regex),assert_stdout_min_lines:fU(e.assert_stdout_min_lines),assert_json_field_equals:nE(e.assert_json_field_equals),assert_json_field_gte:nE(e.assert_json_field_gte)};return JSON.stringify(t)},hU=e=>{let t=Hm(e.command);return t!==void 0?`command:${e.scope}:${lU(t)}`:`path:${e.scope}:${Hm(e.path)??""}`},zm=e=>{let t=dU(e.env_set),n=mU(e.env_clear),r=pU(e.pm_context_mode),o=uU(e.workspace_context_mode),i=e.shared_host_safe===!0?"true":"false",a=_U(e);return`${hU(e)}:${t}:${n}:${r}:${o}:${i}:${a}`},gU=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,yU=e=>{let t=0,n=0,r=0;for(let o of e){if(o.status==="passed"){t+=1;continue}if(o.status==="failed"||o.status==="refused"){n+=1;continue}r+=1}return{passed:t,failed:n,skipped:r}},wU=(e,t)=>{for(let[n,r]of Object.entries(t))e[n]+=r},Vs=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
43
+ `)}catch{}},vU=async(e,t,n)=>{let r=[],o=0;for(let i of e){let a=await Bs(i.id,{run:!1},{...t,path:n});o+=a.tests.length,r.push({item:i,tests:a.tests})}return{itemTests:r,linkedTests:o}},bU=async e=>{let t=D(e.settings.schema),n=$(e.settings,R()),r=iU(e.options.status,t),o=tE(e.options.limit,"--limit"),i=tE(e.options.offset,"--offset")??0,a=(await ye(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(s=>r?s.status===r:!0).sort((s,c)=>s.id.localeCompare(c.id));return{filteredItems:o===void 0?a.slice(i):a.slice(i,i+o),statusFilter:r,limitFilter:o,offsetFilter:i}},rE=e=>{let t=e.filter(Oe).map(({provenance:n,provenance_invalid:r,updated_by:o,updated_at:i,note:a,timeout_seconds:s,...c})=>c);return t.length===0?"":At(t)},oE=(e,t)=>t.length===0?zm(e):`${zm(e)}:setup[${t}]`,kU=e=>{let t=new Map;for(let{tests:n}of e){let r=rE(n);for(let o of n){if(Oe(o))continue;let i=oE(o,r);if(!t.has(i)){t.set(i,o.timeout_seconds);continue}t.set(i,gU(t.get(i),o.timeout_seconds))}}return t};function SU(e,t){try{Vr(e.command);return}catch(n){if(!(n instanceof d)||n.code!=="linked_test_command_not_executable")throw n;return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Linked test refused for ${t}: ${n.message}`}}}var EU=(e,t)=>{let n=[],r=[],o=za(e.tests),i=rE(o),a=Ao();return{plans:o.map(s=>{let c=Oe(s),l=c?zm(s):oE(s,i),p=a.blocked(s);if(p)return{test:s,key:l,duplicate:!1,refusal:p};let u=SU(s,e.item.id);if(u)return{test:s,key:l,duplicate:!1,refusal:a.record(s,u)};if(c)return n.push(s),{test:s,key:l,duplicate:!1,refusal:void 0};if(t.seenTestKeys.has(l))return{test:s,key:l,duplicate:!0,refusal:void 0};t.seenTestKeys.add(l),r.push(l);let f=t.effectiveTimeoutByKey.get(l);return n.push(f===void 0?s:{...s,timeout_seconds:f}),{test:s,key:l,duplicate:!1,refusal:void 0}}),testsToRun:n,reservedKeys:r}},AU=(e,t,n)=>{if(e.some(r=>r.phase==="setup"&&r.status!=="passed"))for(let r of t)n.seenTestKeys.delete(r)},TU=async(e,t)=>{let{plans:n,testsToRun:r,reservedKeys:o}=EU(e,t),i=r.length>0?await Km(r,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[];AU(i,o,t);let a=0,s=Ao(),c=n.map(({test:f,key:h,duplicate:_,refusal:g})=>{if(g)return s.blocked(f)??g;if(!_){let y=i[a];return a+=1,s.blocked(f)??s.record(f,y)}return s.blocked(f)??{command:f.command,path:f.path,status:"skipped",error:`Duplicate linked test skipped (key=${h}).`}}),l=yU(c),p=vr(c),u=await RU(e,l,c,t);return{passed:l.passed,failed:l.failed,skipped:l.skipped,trackingWarnings:u,failureCategories:p,result:{ok:l.failed===0&&!(t.options.failOnSkipped===!0&&l.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:l.passed,failed:l.failed,skipped:l.skipped,run_results:c,failure_categories:p}}},CU=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),IU=e=>e?!0:void 0,RU=async(e,t,n,r)=>{if(!r.trackingEnabled)return[];try{let o=CU(t,r.options);await Fs({pmRoot:r.pmRoot,settings:r.settings,itemId:e.item.id,author:r.trackingAuthor,message:`Track test-all run summary (${r.trackingRunId})`,entry:{run_id:r.trackingRunId,kind:"test-all",status:o?"failed":"passed",started_at:r.runStartedAt,finished_at:A(),recorded_at:A(),attempt:r.trackingAttempt,resumed_from:r.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:IU(r.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}})}catch(o){return vn(o)?(r.revisionConflicts.push(o),[]):[`test_result_tracking_failed:${e.item.id}:${sU(o)}`]}return[]},OU=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Hm=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},xU=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:$e(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:kU(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:I(e.options.author,e.settings.author_default),trackingRunId:cU(),trackingAttempt:OU(),trackingResumedFrom:Hm(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt,revisionConflicts:[]}),$U=(e,t,n)=>{let r={results:[],passed:0,failed:0,skipped:0,failureCategories:vr([]),trackingWarnings:[]},o=e.failOnEmptyTestRun===!0&&t===0;return o&&(r.failed+=1,r.failureCategories.empty_run+=1,r.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:r,failOnEmptyTestRunTriggered:o}},PU=async(e,t,n)=>{for(let[o,i]of e.entries()){Vs(t.options,`item ${o+1}/${e.length} start id=${i.item.id} linked_tests=${i.tests.length}`);let a=await TU(i,t);wU(n.failureCategories,a.failureCategories),n.passed+=a.passed,n.failed+=a.failed,n.skipped+=a.skipped,n.trackingWarnings.push(...a.trackingWarnings),n.results.push(a.result),Vs(t.options,`item ${o+1}/${e.length} end id=${i.item.id} status=${a.failed===0?"passed":"failed"} passed=${a.passed} failed=${a.failed} skipped=${a.skipped}`)}let[r]=t.revisionConflicts;if(r!==void 0)throw r},LU=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(o=>o.run_results),r=qm(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)},NU=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),FU=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),MU=async(e,t)=>{let n=T(process.cwd(),t.path);await O(n);let r=await E(n),o=await bU({pmRoot:n,settings:r,options:e}),i=aU(e.timeout),a=A(),s=await vU(o.filteredItems,t,n);return Vs(e,FU({...o,linkedTests:s.linkedTests})),{pmRoot:n,settings:r,filteredItems:o.filteredItems,itemTests:s.itemTests,linkedTests:s.linkedTests,defaultTimeoutSeconds:i,runStartedAt:a}},DU=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},iE=async(e,t)=>{let n=await MU(e,t),{accumulation:r,failOnEmptyTestRunTriggered:o}=$U(e,n.linkedTests,n.filteredItems),i=xU({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await PU(n.itemTests,i,r),LU(e,r);let a=DU({options:e,accumulation:r,failOnEmptyTestRunTriggered:o});return Vs(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${r.passed} failed=${r.failed} skipped=${r.skipped}`),NU({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:r,failOnSkippedTriggered:a.failOnSkippedTriggered,failOnEmptyTestRunTriggered:o})};(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]="920b5725-710a-5839-86e3-dbdbc8a602a8")}catch{}})();function aE(e,t,n){let r;if(typeof e.lines=="string")r=$l(e.lines);else if(e.lineRange!==void 0){if(e.lineRange===null||typeof e.lineRange!="object"||Array.isArray(e.lineRange))throw new RangeError("Source line range must be an object with numeric start and end values.");r=$l(`${String(Reflect.get(e.lineRange,"start"))}:${String(Reflect.get(e.lineRange,"end"))}`)}return{paths:t,scope:e.scope==="project"||e.scope==="global"?e.scope:void 0,limit:n(e.limit,"files lookup limit"),offset:n(e.offset,"files lookup offset"),noTruncate:e.noTruncate===!0,strictRead:e.strictRead===!0,explain:e.explain===!0,lineRange:r,decisionDepth:n(e.decisionDepth,"files lookup decision depth")}}(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]="09fa5b5c-d44a-55e4-9365-a08702d8a952")}catch{}})();function Ue(e,t){let n=b(e,t);if(!n)throw new d(`Missing required argument: ${t}`,64);return n}function Dn(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 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]="9a4dbe8d-9341-55f1-8c4a-d476c2b338e5")}catch{}})();function UU(e){let t=b(e.args,"subcommand")??Ue(e.options,"subcommand"),n=e.args.alias??e.options.alias;return{ctx:e,subcommand:t.trim().toLowerCase(),name:b(e.args,"name")??b(e.options,"name"),author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0,aliases:n===void 0?void 0:ke(n)}}function jU(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=Dn({list:()=>eg(t.global),show:()=>tg(r,t.global),"show-status":()=>ng(r,t.global),"list-fields":()=>ig(t.global),"show-field":()=>ag(r,t.global),"remove-type":()=>Jh(r,{author:o,force:i},t.global),"remove-field":()=>og(r,{author:o,force:i},t.global),"remove-status":()=>Zh(r,{author:o,force:i},t.global),"apply-preset":()=>sg(b(t.args,"typePreset")??b(t.options,"typePreset"),{author:o,force:i},t.global)},n);return a?a():null}function GU(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.commands??t.options.commands,s=t.args.requiredTypes??t.options.requiredTypes;return rg(n,{type:b(t.args,"fieldType")??b(t.options,"fieldType"),commands:a===void 0?void 0:ke(a),description:b(t.args,"description")??b(t.options,"description"),cliFlag:b(t.args,"cliFlag")??b(t.options,"cliFlag"),alias:i,required:t.args.required===!0||t.options.required===!0,requiredOnCreate:t.args.requiredOnCreate===!0||t.options.requiredOnCreate===!0,allowUnset:!(t.args.allowUnset===!1||t.options.allowUnset===!1),requiredTypes:s===void 0?void 0:ke(s),author:r,force:o},t.global)}function qU(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e,a=t.args.role??t.options.role;return Qh(n,{role:a===void 0?void 0:ke(a),alias:i,description:b(t.args,"description")??b(t.options,"description"),order:ze(t.args.order??t.options.order,"schema add-status order"),author:r,force:o},t.global)}function KU(e){let{ctx:t,name:n,author:r,force:o,aliases:i}=e;return Yh(n,{description:b(t.args,"description")??b(t.options,"description"),defaultStatus:b(t.args,"defaultStatus")??b(t.args,"default_status")??b(t.options,"defaultStatus")??b(t.options,"default_status"),folder:b(t.args,"folder")??b(t.options,"folder"),alias:i,author:r,force:o},t.global)}function zU(e){let{ctx:t,subcommand:n,name:r,author:o,force:i}=e,a=b(t.args,"to")??Ue(t.options,"to"),s=b(t.args,"migrationId")??b(t.args,"migration_id")??b(t.options,"migrationId")??b(t.options,"migration_id"),c=b(t.args,"fieldTypeScope")??b(t.options,"fieldTypeScope")??b(t.args,"type")??b(t.options,"type"),l=n==="rename-type"?{kind:"rename-type",from:r??"",to:a}:n==="rename-field"?{kind:"rename-field",from:r??"",to:a,...c===void 0?{}:{type:c}}:{kind:"remap-status",from:r??"",to:a};return Wh(l,{migrationId:s,dryRun:t.args.dryRun===!0||t.options.dryRun===!0,author:o,force:i},t.global)}function sE(e){let t=UU(e);Jf(t.subcommand,e.args.dryRun===!0||e.options.dryRun===!0);let n=qn.find(o=>o===t.subcommand);if(n)return Bh(n,t.name,{definition:e.args.definition??e.options.definition,policy:b(e.args,"policy")??b(e.options,"policy"),message:b(e.args,"message")??b(e.options,"message"),author:t.author,dryRun:e.args.dryRun===!0||e.options.dryRun===!0},e.global);let r=jU(t);if(r!==null)return r;if(["rename-type","rename-field","remap-status"].includes(t.subcommand))return zU(t);if(t.subcommand==="add-field")return GU(t);if(t.subcommand==="add-status")return qU(t);if(t.subcommand==="add-type")return e.args.infer===!0||e.options.infer===!0?cg({minCount:ze(e.args.minCount??e.options.minCount,"schema infer minCount"),apply:e.args.apply===!0||e.options.apply===!0,author:t.author,force:t.force},e.global):KU(t);throw Le({command_path:"schema",token:t.subcommand,allowed:Vh,exit_code:64})}(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]="6d51b67b-2f13-580b-aa6a-eb3b840a1784")}catch{}})();function Ys(e){return b(e.args,"target")??b(e.options,"target")}function Ee(e,t=e.options){return e.id??Ue(t,"id")}async function HU(e){let t=Xn("list",e.options);return t.compact===void 0&&t.brief===void 0&&t.full===void 0&&t.fields===void 0&&t.includeBody===void 0&&(t.compact=!0),nd(await Pt(b(e.args,"status")??b(t,"status"),t,e.global),t)}async function BU(e){let t=b(e.args,"query")??b(e.args,"keywords")??Ue(e.args,"query"),n=Xn("search",e.options,[t]);return n.compact===void 0&&n.full===void 0&&n.fields===void 0&&(n.compact=!0),nd(await bo(t,n,e.global),n)}async function WU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ie(await en(r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function VU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o={...r,...r.title===void 0&&typeof e.args.title=="string"?{title:e.args.title}:{},...r.message===void 0&&typeof e.args.message=="string"?{message:e.args.message}:{}};return Ie(await wd(Ee(e,o),o,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function YU(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ie(await at(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function JU(e){let t=kn(e.options);return t.add===void 0&&t.stdin===void 0&&t.file===void 0&&t.edit===void 0&&t.delete===void 0&&(t.includeMeta=!0),xw(Ee(e),t,e.global)}function cE(e,t){return gg(aE(e.options,t,ze),e.global)}function XU(e){let t=ke(e.options.lookupPath);if(t&&t.length>0)return cE(e,t);let n=Ee(e);return e.options.discover===!0?Pl(n,va(e.options),e.global):hg(n,mo(kn(e.options)),e.global)}function QU(e){return uS({subcommand:b(e.args,"subcommand")??b(e.options,"subcommand"),limit:bh(e.args,e.options)},e.global)}function ZU(e){let t={...e.options};return t.brief===void 0&&t.summary===void 0&&t.full===void 0&&(t.summary=!0),go(e.global,t)}function ej(e){let t=b(e.args,"configAction")??b(e.options,"configAction")??b(e.options,"action");if(t===void 0)throw new d("Missing required argument: configAction",64);let n=b(e.args,"value")??b(e.options,"value"),r=b(e.options,"policy")!==void 0&&n!==void 0?{...e.options,value:n}:e.options,o=b(e.args,"key")??b(e.options,"key");return Qw(b(e.args,"scope")??b(e.options,"scope")??o_(o),t,o,r,e.global,b(e.options,"policy")===void 0?n:void 0)}function tj(e){let t=e.options;return ly(cy(t),e.global)}function nj(e,t){if(typeof e=="number"){if(!Number.isFinite(e)||!Number.isInteger(e))throw new d(`${t} must be a finite integer.`,64);return e}if(typeof e=="string"&&e.trim().length>0){let n=e.trim();if(!/^[+-]?\d+(?:st|nd|rd|th)?$/i.test(n))throw new d(`${t} must be a finite integer.`,64);let r=Number.parseInt(n,10);if(!Number.isInteger(r))throw new d(`${t} must be a finite integer.`,64);return r}}async function rj(e){let t=b(e.args,"subcommand")??Ue(e.options,"subcommand"),n=e.options,{changedFields:r,idOnly:o}=we(e.args,e.options),i=await Pb({subcommand:t,id:typeof e.id=="string"?e.id:typeof n.id=="string"?n.id:void 0,stepRef:oj(e),reorderTo:nj(n.reorderTo??e.args.reorderTo,"plan reorderTo"),options:e.options,global:e.global});return t!=="show"&&yh(e.args)&&(i.mutation_receipt=As(i,void 0)),t==="show"?i:Ie(i,{changedFields:r,idOnly:o,compactEnvelope:r==="compact"&&!o})}function oj(e){return typeof e.options.stepRef=="string"?e.options.stepRef:typeof e.args.stepRef=="string"?e.args.stepRef:void 0}function ij(e){let t=b(e.args,"subcommand")??Ue(e.options,"subcommand"),n=t.trim().toLowerCase(),r=b(e.args,"name")??b(e.options,"name"),o=Dn({list:()=>Xb(),show:()=>Qb(r),lint:()=>Zb(r),apply:()=>ek(r,{dryRun:e.args.dryRun===!0||e.options.dryRun===!0,author:b(e.args,"author")??b(e.options,"author"),force:e.args.force===!0||e.options.force===!0},e.global)},n);if(!o)throw Le({command_path:"profile",token:t,allowed:Jb,exit_code:64});return o()}async function aj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options);return Ie(await mv(Ee(e,r),r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}async function sj(e){let{changedFields:t,runnerOptions:n}=we(e.args,e.options);return Ie(await jb(ka(n),e.global),{changedFields:t})}async function cj(e){let{changedFields:t,runnerOptions:n}=we(e.args,e.options),r=b(e.args,"reason"),o=r!==void 0&&n.reason===void 0?{...n,reason:r}:{...n};return e.force&&o.force===void 0&&(o.force=!0),Ie(await vv(ba(o),e.global),{changedFields:t})}async function lj(e){let{changedFields:t,idOnly:n,runnerOptions:r}=we(e.args,e.options),o=b(r,"target")??Ue(e.args,"target");return Ie(await cm(Ee(e,r),o,r,e.global),{changedFields:t,compactEnvelope:t==="compact"&&!n,idOnly:n})}function dj(e){let t={...e.args,...e.options};return yg(Ue(t,"subcommand"),b(t,"id")??e.id,b(t,"target"),Th(t),e.global)}function mj(e){return pg(T(process.cwd(),e.global.path),{...e.args,...e.options})}var lE={init:e=>$o(b(e.args,"prefix"),e.global,e.options),context:e=>Dl(Xn("context",e.options),e.global),next:e=>vo(Xn("next",e.options),e.global),eval:Fk,events:Mk,merge:Dk,workspace:Uk,meet:$s,event:$s,remind:$s,list:HU,get:e=>{let t=Ee(e);return jl(t,e.global,Xn("get",e.options,[t]))},search:BU,duplicates:e=>{let t=typeof e.options.status=="string"?[e.options.status]:ke(e.options.status);return xl(e.global,{exhaustive:e.options.exhaustive===!0,...t.length===0?{}:{status:t},since:b(e.options,"since"),threshold:typeof e.options.threshold=="number"?e.options.threshold:void 0,limit:e.options.limit==="default"?void 0:ze(e.options.limit,"limit")})},create:WU,copy:VU,focus:e=>xd(e.id,{clear:e.options.clear===!0||e.args.clear===!0},e.global),update:YU,"item-reopen":bb,restore:lj,claim:yb,release:vb,"start-task":e=>Pn(e,"start_task"),"pause-task":e=>Pn(e,"pause_task"),"close-task":e=>Pn(e,"close_task"),close:wb,comments:JU,notes:e=>qb(Ee(e),kn(e.options),e.global),learnings:e=>dv(Ee(e),kn(e.options),e.global),files:XU,docs:e=>_g(Ee(e),mo(kn(e.options)),e.global),test:e=>Bs(Ee(e),kn(e.options),e.global),"test-all":e=>iE(e.options,e.global),telemetry:QU,validate:e=>$a(e.options,e.global,{runUpdate:(t,n,r)=>at(t,n,r)}),health:ZU,assurance:e=>Qg(e.args,e.options,e.global),contracts:e=>Ql(e.options,e.global),config:ej,activity:tj,aggregate:e=>Ul(e.options,e.global),extension:e=>lr(Ys(e),e.options,e.global),package:e=>lr(Ys(e),e.options,e.global),install:e=>lr(Ys(e),{...e.options,install:!0},e.global),upgrade:e=>ey(Ys(e),e.options,e.global),delete:e=>Od(Ee(e),e.options,e.global),deps:e=>ug(Ee(e),e.options,e.global),graph:dj,"files-discover":e=>Pl(Ee(e),e.options,e.global),"files-lookup":e=>cE(e,ke(e.options.paths)),history:e=>dy(Ee(e),{...e.options,compact:e.options.full===!0||e.options.provenance===!0?!1:e.options.compact!==!1},e.global),"history-redact":e=>lv(Ee(e),e.options,e.global),"history-repair":ov,"history-compact":iv,"history-attest":e=>ty(e.options,e.global),"history-author-acknowledge":mj,plan:rj,schema:sE,profile:ij,stats:e=>Cm(e.global,jk(e.options)),append:aj,"update-many":sj,"close-many":cj,gc:e=>Zg(e.global,e.options)};(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]="96234a42-d25c-5221-a12b-a992925a13ba")}catch{}})();var pj=new Map;function Bm(){pj.clear()}(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]="69f9c792-7ee1-5e4b-9900-38e1c887c4d4")}catch{}})();(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]="5417c092-2e52-5b18-bcb6-da34f07f595f")}catch{}})();(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]="ba66cac9-25d6-559e-95d1-71db5c404807")}catch{}})();(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]="59f6a03b-a7d4-5f20-a1c7-40ab140a8355")}catch{}})();var mE=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:ch().flatMap(({commands:e})=>e.map(t=>`pm ${t}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<reason>" --resolution "<change>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks (repository checkout only; excluded from the npm package).",optional:!0},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes (repository checkout only; excluded from the npm package).",optional:!0},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering (repository checkout only; not in the npm package).",optional:!0}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],dE=new Map;for(let e of mE){dE.set(e.id,e);for(let t of e.aliases)dE.set(t,e)}function Wm(){return mE.map(e=>e.id)}(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]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();(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]="ebe25271-7465-5536-a4d8-ee402b0b3848")}catch{}})();var R7=[...mc],O7=[...pc],Vm=new Set(mn.filter(e=>e.hidden).map(e=>e.alias)),pE=sh("full").filter(e=>!e.includes(" ")&&!Vm.has(e)),uj=M(ii),fj=M(ai),_j=M(ui),hj=M(yi),uE=ao("restore",qe("restore")),fE=ao("history-attest",qe("history-attest")),gj=M(wi),yj=M(Hu),wj=M(Bu),vj=M(gi),bj=M(Si),kj=M(vi),Sj=M(bi),Ej=M(pi),Ym=[...new Set(Ce.map(e=>e.canonical_argv[0]))],_E=[...new Set(Ce.flatMap(e=>e.canonical_argv.slice(0,-1).map((t,n)=>e.canonical_argv.slice(0,n+1).join(" "))))],x7=new Set(oi.filter(e=>e.disposition==="package_owned").map(e=>W(e.command))),hE=Ce.filter(e=>e.canonical_argv[0]==="history"),Aj=hE.map(e=>e.canonical_argv[1]).join(" ");var Tj=hE.map(e=>({...e,flags:M(qe(e.alias))})),Cj=M(si),Ij=M(ci,!1),Rj=M(ki),Oj=M(qr),xj=M(Kr),$j=M(Ci),Pj=M(Ai),Lj=M(_i),Nj=M(Ti),Fj=M(Ei),Mj=M(Ii),Dj=M(fi),Uj=M(hi),jj=M(di),Gj=M(Ri),qj=M(li),Jm=`${qn.join(" ")} list show show-status add-type remove-type add-status remove-status add-field remove-field list-fields show-field apply-preset rename-type rename-field remap-status`;var Kj=M(Oi),zj=`${Kj} bash zsh fish`,Xm=Xs(Wm()),Js="init scaffold install uninstall explore manage describe reload doctor catalog adopt adopt-all activate deactivate migrate",Qm=`${Js} upgrade`,Hj=M(mi),Bj=M(jr),Wj=M(Gr);var Vj=M(qe("close")),Yj=M(qe("close-task")),Jj=M(qe("release")),Xj=M(qe("claim"));var gE=Kn.flatMap(e=>[e.short,e.flag,...e.aliases??[]]).filter(e=>!!e).join(" "),Zm=[...ji].join("|"),ep=[...ji].map(e=>`${e}=*`).join("|"),tp=[...gE.split(" ").filter(e=>!ji.has(e)),"-h","-V"].join("|");function Xs(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n)).join(" ")}(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]="51e29808-0fda-5e25-af31-a6f81c48dbe1")}catch{}})();(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]="8b943e04-8a01-5c76-be00-46c5ebda43a1")}catch{}})();(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]="d731ee3e-64df-5a9f-a684-699ccad4a6b1")}catch{}})();(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]="a7cfbd72-3010-53e7-946b-e65842ee4ceb")}catch{}})();(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]="7a7096c6-a9c3-5d8e-96e4-ed1b0218234e")}catch{}})();(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]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();(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]="21f305ed-dd88-5b62-8cfa-b55e1b3f01dd")}catch{}})();var Bo=Symbol("pm.active-extension-host-context");function Ye(e){return{fullChangedFields:!0,options:e}}var H=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[Bo]=!0,n}run(t,n={}){return pG({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let r=T(this.defaults.cwd??process.cwd(),this.defaults.path),o=async()=>{let a=await no(r,()=>E(r));return t({pmRoot:r,author:I(this.defaults.author,a.author_default)})};if(this.defaults[Bo]===!0||Zs.getStore()===!0)return o();let i=()=>aG({...this.defaults,path:r},o);return n?no(r,i):i()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-7A3Q4CAJ.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-7A3Q4CAJ.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,r)=>this.withItemTransactionContext(async o=>(await import("./item-transaction-7A3Q4CAJ.js")).abandonItemTransaction({...r,...o,transactionId:n}));return{status:n=>this.withItemTransactionContext(async r=>(await import("./item-transaction-7A3Q4CAJ.js")).readItemTransaction(r.pmRoot,n),!0),abandon:t,supersede:(n,r,o)=>t(n,{...o,supersededBy:r})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-YO7YGQYE.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let r=await import("./item-revision-YO7YGQYE.js"),o="",i=await this.withItemTransactionContext(({pmRoot:s})=>(o=s,r.bindExpectedItemRevisions(t,{pmRoot:s}))),a=this.defaults.noExtensions===!0&&this.defaults[Bo]!==!0;return r.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",o,...a?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Cw(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Il(await this.list(Cl(t)),t)}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},r={}){return this.runTyped("graph",{subcommand:t,...n,options:r})}async append(t,n,r={}){return fh(r,"append"),await this.runTyped("append",{id:t,...Ye(yt(r,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,r,o,i={}){return this.runTyped("config",{scope:t,configAction:n,...r===void 0?{}:{key:r},...o===void 0?{}:{value:o},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,r={}){return this.runTyped("schema",{name:n,options:{...r,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:r,...o}=n;return this.runTyped("schema",{name:t,options:{...o,fieldType:r,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,r,o){return this.runTyped("schema",{name:t,options:{...r,subcommand:"rename-field",to:n,...o?{fieldTypeScope:o}:{}}})}schemaRemapStatus(t,n,r){return this.runTyped("schema",{name:t,options:{...r,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,r={},o,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...o===void 0?{}:{stepRef:o},...i===void 0?{}:{reorderTo:i},options:yt(r,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,r){return this.plan("update-step",t,r,n)}planCompleteStep(t,n,r={}){return this.plan("complete-step",t,r,n)}planBlockStep(t,n,r){return this.plan("block-step",t,r,n)}planReorderStep(t,n,r,o={}){return this.plan("reorder-step",t,o,n,r)}planRemoveStep(t,n,r={}){return this.plan("remove-step",t,r,n)}planLink(t,n,r){return this.plan("link",t,r,n)}planUnlink(t,n,r){return this.plan("unlink",t,r,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Ye(t))}update(t,n={}){return this.runTyped("update",{id:t,...Ye(n)})}reopen(t,n,r={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:r})}close(t,n,r={}){return this.runTyped("close",{id:t,reason:n,...Ye(r)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Ye(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Ye(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Ye(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Ye(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Ye(n)})}restore(t,n,r={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...r,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Ye(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Ye(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Ye(n)})}closeTask(t,n,r={}){return this.runTyped("close-task",{id:t,reason:n,...Ye(r)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function PZ(e={},t={}){return new H(t).context(e)}function LZ(e={},t={}){return new H(t).list(e)}function NZ(e={},t={}){return new H(t).listAllComplete(e)}function FZ(e,t={},n={}){return new H(n).search(e,t)}function MZ(e,t={},n={}){return new H(n).get(e,t)}function DZ(e={},t={}){return new H(t).next(e)}function UZ(e={},t={}){return new H(t).aggregate(e)}function jZ(e,t={},n={}){return new H(n).comments(e,t)}function GZ(e,t={},n={}){return new H(n).notes(e,t)}function qZ(e,t={},n={}){return new H(n).learnings(e,t)}function KZ(e,t={},n={}){return new H(n).files(e,t)}function zZ(e,t={},n={}){return new H(n).filesDiscover(e,t)}function HZ(e,t={},n={}){return new H(n).docs(e,t)}function BZ(e,t={},n={}){return new H(n).deps(e,t)}function WZ(e,t={},n={},r={}){return new H(r).graph(e,t,n)}function VZ(e,t,n={},r={}){return new H(r).append(e,t,n)}function YZ(e={},t={}){return new H(t).create(e)}function JZ(e,t={},n={}){return new H(n).update(e,t)}function XZ(e,t,n={},r={}){return new H(r).reopen(e,t,n)}function QZ(e,t,n={},r={}){return new H(r).close(e,t,n)}function ZZ(e,t={},n={}){return new H(n).claim(e,t)}function eee(e={},t={}){return new H(t).claimNext(e)}function tee(e,t={},n={}){return new H(n).release(e,t)}function nee(e,t={},n={}){return new H(n).copy(e,t)}function ree(e,t={},n={}){return new H(n).delete(e,t)}function oee(e,t,n={},r={}){return new H(r).restore(e,t,n)}function iee(e,t={},n={}){return new H(n).focus(e,t)}var bE=kf(),Zs=new iG;function Qs(){Dc(jp()),Uc(Gp()),jc(qp()),Gc(Kp()),qc(zp()),Kc(Hp()),zc(Bp())}async function EE(e,t,n,r){return Mc(()=>t===void 0?bE.read(()=>kE(e,n,r)):bE.write(()=>lG(t,()=>kE(e,n,r))))}async function aG(e,t){let n=e.cwd;if(Zs.getStore()===!0&&n===void 0&&e.noExtensions===!0){let o=T(process.cwd(),e.path);return Mc(()=>Ma({pmRoot:o},t))}let r=n??process.cwd();return EE(wa({path:e.path,noExtensions:e.noExtensions}),n,r,()=>Zs.run(!0,t))}function sG(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:J_(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function kE(e,t,n){let r=T(t,e.path);if(e.noExtensions)return Qs(),Ma({pmRoot:r},()=>n(null));if(!await B(oe(r)))return Qs(),n(null);let o=null,i;try{let a=await E(r),s=await Dr({pmRoot:r,settings:a,cwd:t,noExtensions:!1}),c=await Ur({...s,loaded:s.loaded});i={loadResult:s,activationResult:c},Dc(c.hooks),Uc(c.commands),jc(c.parsers),Gc(c.preflight),qc(c.services),Kc(c.renderers),zc(c.registrations),o={registrations:c.registrations,commands:c.commands,pmRoot:r,packages:s.loaded}}catch(a){Qs(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",sG(a))}try{return await Ma({pmRoot:r,packages:o?.packages},()=>n(o))}finally{Qs(),i&&await Cc(i.loadResult,i.activationResult).catch(()=>{})}}function AE(e,t){let n=sr(e);return t?.registrations.commands.find(r=>sr(r.action)===n)?.command??t?.commands.handlers.find(r=>sr(r.command)===n)?.command}async function cG(e,t,n,r,o){if(!o)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let i=AE(e,o);if(!i)throw new d(`Unsupported native pm action: ${e}`,m.USAGE);let a=typeof n.author=="string"?n.author:r.author,s=El(i),c=rh(Al(t,n),nh(o.registrations,s),s,bw(s)),l=await Ui({command:s,args:ke(n.args??t.args),options:c,global:{...r,author:a},pm_root:o.pmRoot,sdk:vw(o.pmRoot,H.forActiveExtensionHost({pmRoot:o.pmRoot,author:a}),a,s)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw ua(i,l);let p=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new d(`Unsupported native pm action: ${e}${p}`,m.USAGE)}return l.result}async function lG(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function dG(e){let t=Ue(e,"action"),n=sr(t),r=Dn(Rw,n),o=r?.action??n,i={...e,action:o};return r?.options!==void 0&&(i.options={...r.options,...Lr(e.options)}),o==="package"&&(i.options={...Lr(i.options),vocabulary:"package"}),{action:o,args:i}}function mG(e,t,n,r){let o=e[Bo]===!0,i=t.noExtensions===!0&&!o?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",T(r,t.path),...i];let a=Pe(t,r);return[...t.noExtensions===!0?a.slice(0,-1):a,...i]}async function pG(e){let t=dG(e),n=wa(t.args);Rf(n);let r=Eh(t.action),o=b(t.args,"cwd"),i=o??process.cwd();t.action==="init"&&(n[td]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=T(i,n.path));let{expectHash:a,dispatchArgs:s}=Ih(t.args),c=async l=>{if(a===void 0)return SE(t.action,s,n,l);let{dispatchWithExpectedItemRevisions:p}=await import("./item-revision-YO7YGQYE.js");return p({action:t.action,expectHash:a,defaultId:b(s,"id")??b(Lr(s.options),"id"),options:Lr(s.options),background:s.background,pmRoot:T(i,n.path),invocation:{scopeArgs:mG(e,n,o,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>SE(t.action,s,n,l)})};try{return t.action==="history-attest"?await c(null):e[Bo]===!0||Zs.getStore()===!0?await c(null):await EE(n,o,i,l=>c(l))}finally{r&&Bm()}}async function SE(e,t,n,r){let o=Dn(lE,e),i=Sl(t,e,{nativeAction:o!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:p}=await import("./mutation-admission-G565NLPE.js");await p(e,t,i,n.path,kh[e])}let a=o?void 0:AE(e,r),s=a===void 0?e:`extension:${a}`;Lf(s,i),Ff(s,i);let c={action:e,args:t,options:i,id:b(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:r},l=o?await o(c):await cG(e,t,i,n,r);if(e==="history-attest")return l;{let p=jf(s,i,l);return await ww(T(process.cwd(),n.path),p),p}}var uG={closeManyOptionsFromFlat:ba,extensionOptionsFromArgs:Al,globalOptions:wa,mutationListOptions:Ah,normalizeActionName:sr,normalizeCommandPath:El,normalizeMcpUpdateOptions:Ch,normalizeMcpOptionsArrays:Sh,optionsWithAuthor:Sl,readRequiredString:Ue,readScalarString:wh,readScalarStringAllowBlank:vh,readStringArray:ke,updateManyOptionsFromFlat:ka,withAddNoteOption:mo,withFilesDiscoveryOptions:va,withMutationCompaction:we};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=uG);export{Gl as a,NA as b,zA as c,Ny as d,x1 as e,Fy as f,$1 as g,P1 as h,Wy as i,hT as j,H as k,PZ as l,LZ as m,NZ as n,FZ as o,MZ as p,DZ as q,UZ as r,jZ as s,GZ as t,qZ as u,KZ as v,zZ as w,HZ as x,BZ as y,WZ as z,VZ as A,YZ as B,JZ as C,XZ as D,QZ as E,ZZ as F,eee as G,tee as H,nee as I,ree as J,oee as K,iee as L,aG as M,pG as N};
44
+ //# sourceMappingURL=chunk-FK2X6MJY.js.map