@unbrained/pm-cli 2026.8.7 → 2026.8.8

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 (226) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +35 -0
  3. package/dist/cli/main.js +4 -3
  4. package/dist/cli/register-annotations.d.ts +11 -0
  5. package/dist/cli/register-annotations.js +195 -0
  6. package/dist/cli/register-history-author.js +7 -30
  7. package/dist/cli/register-mutation.js +25 -206
  8. package/dist/cli/runtime-compatibility-boundary.d.ts +17 -0
  9. package/dist/cli/runtime-compatibility-boundary.js +43 -0
  10. package/dist/cli-bundle/bundle-manifest.json +155 -691
  11. package/dist/cli-bundle/chunks/chunk-2ZMXX3Q6.js +2068 -0
  12. package/dist/cli-bundle/chunks/chunk-ALDHXLPS.js +3 -0
  13. package/dist/cli-bundle/chunks/chunk-CBLA33YK.js +8 -0
  14. package/dist/cli-bundle/chunks/chunk-GKA54IJM.js +5 -0
  15. package/dist/cli-bundle/chunks/chunk-KRY7SRUO.js +2 -0
  16. package/dist/cli-bundle/chunks/chunk-MNJ4NNSY.js +26 -0
  17. package/dist/cli-bundle/chunks/chunk-NUXRRNAB.js +77 -0
  18. package/dist/cli-bundle/chunks/chunk-OJPCFDDY.js +13 -0
  19. package/dist/cli-bundle/chunks/chunk-PFSD3DAN.js +194 -0
  20. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +2 -0
  21. package/dist/cli-bundle/chunks/chunk-SQ7QZFQ6.js +2 -0
  22. package/dist/cli-bundle/chunks/{register-list-query-FJZCJ67O.js → register-list-query-WFZAMJHZ.js} +8 -8
  23. package/dist/cli-bundle/chunks/register-mutation-SOKKOTHQ.js +20 -0
  24. package/dist/cli-bundle/chunks/register-operations-5XQETS6E.js +2 -0
  25. package/dist/cli-bundle/chunks/register-setup-2HL5ZHMK.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/chunk-54EU2UVO.js +2 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-VZFU2R4M.js → chunk-5FLBTZJQ.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-5GJ57YKN.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/{chunk-HNL6IFGS.js → chunk-ANTMGYLI.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-CMDS3KYT.js +14 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-NBJKQP4S.js → chunk-DMKOMTTY.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-CIXVQPB7.js → chunk-F5B3HBEZ.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-R2LEMEV5.js → chunk-FI6DWU2M.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-3K4XV2BF.js → chunk-FNOKJG6N.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-RW5IYD4J.js → chunk-FPDYXZBK.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-QHRTT7WT.js → chunk-GWI6YIKJ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-MHMTKV5V.js → chunk-HCUC62AB.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-MOTJFQ3F.js → chunk-HGNKPSCB.js} +12 -12
  39. package/dist/cli-bundle/focused-chunks/{chunk-4VJQTS3P.js → chunk-IAS7PMLG.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-TIKDBG4D.js → chunk-PL2EYDJK.js} +27 -27
  41. package/dist/cli-bundle/focused-chunks/chunk-SM2PJGP3.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-RPNYG5MO.js → chunk-TCSAPH33.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-U646T7Z6.js +18 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-YKPE4PPY.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-YZEZAPJK.js → chunk-YSAHYUXX.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-73JUDYXT.js → chunk-ZOLDTUU7.js} +2 -2
  47. package/dist/cli-bundle/main.js +13 -13
  48. package/dist/cli-bundle/sdk-authoring.js +1 -1
  49. package/dist/cli-bundle/sdk-contracts.js +1 -1
  50. package/dist/cli-bundle/sdk-core.js +38 -38
  51. package/dist/cli-bundle/sdk-governance.js +1 -1
  52. package/dist/cli-bundle/sdk-graph.js +1 -1
  53. package/dist/cli-bundle/sdk-merge.js +1 -1
  54. package/dist/cli-bundle/sdk-query.js +1 -1
  55. package/dist/cli-bundle/sdk-runtime.js +1 -1
  56. package/dist/cli-bundle/sdk-testing.js +1 -1
  57. package/dist/cli-bundle/sdk.js +2 -1
  58. package/dist/cli.js +14 -4
  59. package/dist/core/output/output.js +9 -2
  60. package/dist/core/sentry/helpers.d.ts +10 -0
  61. package/dist/core/sentry/helpers.js +59 -4
  62. package/dist/core/shared/constants.d.ts +2 -0
  63. package/dist/core/shared/constants.js +4 -2
  64. package/dist/sdk/annotations.d.ts +40 -0
  65. package/dist/sdk/annotations.js +61 -9
  66. package/dist/sdk/author-attribution.d.ts +12 -0
  67. package/dist/sdk/author-attribution.js +73 -11
  68. package/dist/sdk/cli-contracts/command-exit-contracts.d.ts +118 -0
  69. package/dist/sdk/cli-contracts/command-exit-contracts.js +152 -0
  70. package/dist/sdk/cli-contracts/completeness.js +5 -3
  71. package/dist/sdk/cli-contracts/flag-contracts.js +5 -2
  72. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +11 -0
  73. package/dist/sdk/cli-contracts/runtime-contracts.js +29 -2
  74. package/dist/sdk/cli-contracts/tool-parameter-tables.js +15 -2
  75. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  76. package/dist/sdk/cli-contracts/tool-schema.js +6 -3
  77. package/dist/sdk/comments.d.ts +7 -0
  78. package/dist/sdk/comments.js +2 -2
  79. package/dist/sdk/completion.js +9 -5
  80. package/dist/sdk/contracts.d.ts +1 -0
  81. package/dist/sdk/contracts.js +3 -2
  82. package/dist/sdk/environment/host-environment-errors.d.ts +27 -0
  83. package/dist/sdk/environment/host-environment-errors.js +124 -0
  84. package/dist/sdk/environment/project-runtime-compatibility.d.ts +65 -0
  85. package/dist/sdk/environment/project-runtime-compatibility.js +385 -0
  86. package/dist/sdk/environment/source-context.d.ts +23 -0
  87. package/dist/sdk/environment/source-context.js +29 -0
  88. package/dist/sdk/error-code-catalog.d.ts +6 -0
  89. package/dist/sdk/error-code-catalog.js +62 -8
  90. package/dist/sdk/generated-error-code-catalog.js +629 -3
  91. package/dist/sdk/governance/health.d.ts +11 -3
  92. package/dist/sdk/governance/health.js +5 -5
  93. package/dist/sdk/index.d.ts +7 -3
  94. package/dist/sdk/index.js +9 -5
  95. package/dist/sdk/learnings.d.ts +15 -0
  96. package/dist/sdk/learnings.js +2 -2
  97. package/dist/sdk/lifecycle/close-many.d.ts +6 -1
  98. package/dist/sdk/lifecycle/close-many.js +43 -5
  99. package/dist/sdk/lifecycle/update-many.d.ts +2 -1
  100. package/dist/sdk/lifecycle/update-many.js +29 -5
  101. package/dist/sdk/merge/index.d.ts +1 -1
  102. package/dist/sdk/merge/index.js +3 -3
  103. package/dist/sdk/merge/install.d.ts +21 -0
  104. package/dist/sdk/merge/install.js +50 -20
  105. package/dist/sdk/notes.d.ts +7 -0
  106. package/dist/sdk/notes.js +2 -2
  107. package/dist/sdk/read-output-contracts.js +83 -4
  108. package/dist/sdk/runtime.d.ts +1 -1
  109. package/dist/sdk/runtime.js +9 -25
  110. package/dist/sdk/test/execution.js +4 -2
  111. package/dist/sdk/test/parsers.js +5 -2
  112. package/dist/sdk/workspace-snapshot.d.ts +9 -0
  113. package/dist/sdk/workspace-snapshot.js +48 -16
  114. package/docs/AGENT_RUNTIME_PRIMITIVES.md +11 -4
  115. package/docs/README.md +1 -0
  116. package/docs/RELEASING.md +27 -2
  117. package/docs/SCRIPTING.md +27 -1
  118. package/docs/SDK_CONTEXT_INTEGRITY.md +66 -0
  119. package/docs/SDK_RUNTIME_BOUNDARIES.md +58 -0
  120. package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
  121. package/docs/TESTING.md +17 -0
  122. package/marketplace.json +2 -2
  123. package/package.json +5 -3
  124. package/packages/pm-beads/package.json +1 -1
  125. package/packages/pm-calendar/package.json +1 -1
  126. package/packages/pm-command-kit/package.json +1 -1
  127. package/packages/pm-digital-twin/package.json +1 -1
  128. package/packages/pm-governance-audit/package.json +1 -1
  129. package/packages/pm-guide-shell/package.json +1 -1
  130. package/packages/pm-kanban/package.json +1 -1
  131. package/packages/pm-lifecycle-hooks/package.json +1 -1
  132. package/packages/pm-linked-test-adapters/package.json +1 -1
  133. package/packages/pm-search-advanced/package.json +1 -1
  134. package/packages/pm-templates/package.json +1 -1
  135. package/packages/pm-todos/package.json +1 -1
  136. package/packages/pm-vcs/package.json +1 -1
  137. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  138. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  139. package/sdk/public-surface.json +529 -34
  140. package/dist/cli-bundle/chunks/append-7BXBFDGD.js +0 -2
  141. package/dist/cli-bundle/chunks/chunk-2AXF3VSK.js +0 -2
  142. package/dist/cli-bundle/chunks/chunk-2XS43CCV.js +0 -2
  143. package/dist/cli-bundle/chunks/chunk-3A6KWB72.js +0 -8
  144. package/dist/cli-bundle/chunks/chunk-3ISTDB42.js +0 -8
  145. package/dist/cli-bundle/chunks/chunk-4MTI7XOV.js +0 -5
  146. package/dist/cli-bundle/chunks/chunk-6BX5UDCN.js +0 -3
  147. package/dist/cli-bundle/chunks/chunk-6QPO7KLR.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-7MXHZHSQ.js +0 -5
  149. package/dist/cli-bundle/chunks/chunk-7ZPMJW4U.js +0 -2
  150. package/dist/cli-bundle/chunks/chunk-A6KGKEWT.js +0 -2
  151. package/dist/cli-bundle/chunks/chunk-AGYNSNCI.js +0 -2
  152. package/dist/cli-bundle/chunks/chunk-B4H7FEFH.js +0 -5
  153. package/dist/cli-bundle/chunks/chunk-B4KLBBMN.js +0 -2
  154. package/dist/cli-bundle/chunks/chunk-BXCSXK4J.js +0 -2
  155. package/dist/cli-bundle/chunks/chunk-CALJHNBL.js +0 -23
  156. package/dist/cli-bundle/chunks/chunk-CFIGP5LY.js +0 -2
  157. package/dist/cli-bundle/chunks/chunk-CHOQ2VAW.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-CS6MRHG7.js +0 -2
  159. package/dist/cli-bundle/chunks/chunk-CUGNQQKH.js +0 -2
  160. package/dist/cli-bundle/chunks/chunk-D4FPS43D.js +0 -164
  161. package/dist/cli-bundle/chunks/chunk-E2ZSLTOP.js +0 -2
  162. package/dist/cli-bundle/chunks/chunk-FB7G2HY2.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-H5Y5YE6A.js +0 -2
  164. package/dist/cli-bundle/chunks/chunk-H5Y6UV6E.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-H7KGWPDF.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-HFSD77TQ.js +0 -2
  167. package/dist/cli-bundle/chunks/chunk-HX2GTA6L.js +0 -2
  168. package/dist/cli-bundle/chunks/chunk-J2IEKAVR.js +0 -2
  169. package/dist/cli-bundle/chunks/chunk-JC6FKIFM.js +0 -2
  170. package/dist/cli-bundle/chunks/chunk-K44PYFXH.js +0 -2
  171. package/dist/cli-bundle/chunks/chunk-K4KGEEBT.js +0 -2
  172. package/dist/cli-bundle/chunks/chunk-KFLK5TRH.js +0 -21
  173. package/dist/cli-bundle/chunks/chunk-KL6IEBV2.js +0 -2
  174. package/dist/cli-bundle/chunks/chunk-KWQZDZSS.js +0 -2
  175. package/dist/cli-bundle/chunks/chunk-KZ4X3DGU.js +0 -3
  176. package/dist/cli-bundle/chunks/chunk-LD77HJMQ.js +0 -13
  177. package/dist/cli-bundle/chunks/chunk-LEPJJ6QC.js +0 -2
  178. package/dist/cli-bundle/chunks/chunk-ME2JJ4LA.js +0 -3
  179. package/dist/cli-bundle/chunks/chunk-NE5VRDAI.js +0 -2
  180. package/dist/cli-bundle/chunks/chunk-NFLJ3FHD.js +0 -2
  181. package/dist/cli-bundle/chunks/chunk-NG6OXIBR.js +0 -19
  182. package/dist/cli-bundle/chunks/chunk-NYIGHWQY.js +0 -8
  183. package/dist/cli-bundle/chunks/chunk-NZ75GNSA.js +0 -2
  184. package/dist/cli-bundle/chunks/chunk-PCJWJNC2.js +0 -2
  185. package/dist/cli-bundle/chunks/chunk-PD3225AM.js +0 -2
  186. package/dist/cli-bundle/chunks/chunk-PDEGKG7P.js +0 -2
  187. package/dist/cli-bundle/chunks/chunk-PIE5HBNA.js +0 -2
  188. package/dist/cli-bundle/chunks/chunk-PW2H7YJR.js +0 -56
  189. package/dist/cli-bundle/chunks/chunk-RSIC5OPE.js +0 -2
  190. package/dist/cli-bundle/chunks/chunk-TPKN3S7S.js +0 -2
  191. package/dist/cli-bundle/chunks/chunk-TPXAXTCO.js +0 -2
  192. package/dist/cli-bundle/chunks/chunk-UFWUJO4V.js +0 -2
  193. package/dist/cli-bundle/chunks/chunk-UQLZQVFW.js +0 -55
  194. package/dist/cli-bundle/chunks/chunk-VT3Z5G7D.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-WOD3WWUN.js +0 -2
  196. package/dist/cli-bundle/chunks/chunk-WSJEIGJF.js +0 -3
  197. package/dist/cli-bundle/chunks/chunk-WYNUU7ZW.js +0 -2008
  198. package/dist/cli-bundle/chunks/chunk-YGPNCCXZ.js +0 -2
  199. package/dist/cli-bundle/chunks/close-CMY3BAUG.js +0 -2
  200. package/dist/cli-bundle/chunks/close-many-SA4XZCTK.js +0 -2
  201. package/dist/cli-bundle/chunks/comments-EZ556ZD3.js +0 -2
  202. package/dist/cli-bundle/chunks/copy-ZSGPA52X.js +0 -2
  203. package/dist/cli-bundle/chunks/create-I5DVV4YG.js +0 -2
  204. package/dist/cli-bundle/chunks/delete-RL3JACSW.js +0 -2
  205. package/dist/cli-bundle/chunks/deps-S7UBCECS.js +0 -2
  206. package/dist/cli-bundle/chunks/docs-ZZNVBBYO.js +0 -2
  207. package/dist/cli-bundle/chunks/files-27C337VT.js +0 -2
  208. package/dist/cli-bundle/chunks/focus-5Z2SG7LU.js +0 -2
  209. package/dist/cli-bundle/chunks/history-compact-HJQK67CZ.js +0 -2
  210. package/dist/cli-bundle/chunks/history-redact-PWC6PDWA.js +0 -2
  211. package/dist/cli-bundle/chunks/history-repair-N3CY4WBF.js +0 -2
  212. package/dist/cli-bundle/chunks/learnings-4FH23XDT.js +0 -2
  213. package/dist/cli-bundle/chunks/profile-5Y5XXH5N.js +0 -2
  214. package/dist/cli-bundle/chunks/register-mutation-YGYPW3BL.js +0 -20
  215. package/dist/cli-bundle/chunks/register-operations-WMDSUMQF.js +0 -2
  216. package/dist/cli-bundle/chunks/register-setup-DL7FFABC.js +0 -2
  217. package/dist/cli-bundle/chunks/restore-6KYBV5BY.js +0 -2
  218. package/dist/cli-bundle/chunks/schema-EQGKBYXJ.js +0 -2
  219. package/dist/cli-bundle/chunks/update-QVTYOD6I.js +0 -2
  220. package/dist/cli-bundle/chunks/update-many-DJSBU525.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-2ECLECMK.js +0 -12
  222. package/dist/cli-bundle/focused-chunks/chunk-4EX25PXM.js +0 -8
  223. package/dist/cli-bundle/focused-chunks/chunk-DLTS3IHM.js +0 -2
  224. package/dist/cli-bundle/focused-chunks/chunk-DQ6FKGL3.js +0 -14
  225. package/dist/cli-bundle/focused-chunks/chunk-JLG2C4EQ.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-ZJIMJHDB.js +0 -2
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{a as B,b as yt,c as wt,d as xt,e as _t,f as U,g as _o,h as F,i as T,j as bo,o as Me,p as vo,q as ko,r as bt}from"./chunks/chunk-UFWUJO4V.js";import{f as mo,ka as xo,u as po}from"./chunks/chunk-WYNUU7ZW.js";import"./chunks/chunk-CS6MRHG7.js";import"./chunks/chunk-KFLK5TRH.js";import"./chunks/chunk-HFSD77TQ.js";import"./chunks/chunk-PCJWJNC2.js";import"./chunks/chunk-4MTI7XOV.js";import"./chunks/chunk-UQLZQVFW.js";import"./chunks/chunk-2XS43CCV.js";import"./chunks/chunk-J2IEKAVR.js";import"./chunks/chunk-KL6IEBV2.js";import"./chunks/chunk-WSJEIGJF.js";import"./chunks/chunk-7ZPMJW4U.js";import"./chunks/chunk-AGYNSNCI.js";import"./chunks/chunk-HX2GTA6L.js";import"./chunks/chunk-H5Y6UV6E.js";import"./chunks/chunk-PDEGKG7P.js";import"./chunks/chunk-KWQZDZSS.js";import"./chunks/chunk-ME2JJ4LA.js";import"./chunks/chunk-6BX5UDCN.js";import{b as fo,s as go}from"./chunks/chunk-PW2H7YJR.js";import"./chunks/chunk-CHOQ2VAW.js";import"./chunks/chunk-CALJHNBL.js";import"./chunks/chunk-B4H7FEFH.js";import{C as uo}from"./chunks/chunk-LD77HJMQ.js";import"./chunks/chunk-TPXAXTCO.js";import"./chunks/chunk-WYRZZ5ZE.js";import{B as wo,b as De,c as ho,d as gt,e as pe,f as O,g as yo,h as ht,n as P}from"./chunks/chunk-3ISTDB42.js";import{a as co}from"./chunks/chunk-PIE5HBNA.js";import"./chunks/chunk-NFLJ3FHD.js";import"./chunks/chunk-7MXHZHSQ.js";import"./chunks/chunk-CUGNQQKH.js";import"./chunks/chunk-NE5VRDAI.js";import"./chunks/chunk-TPKN3S7S.js";import"./chunks/chunk-CFIGP5LY.js";import"./chunks/chunk-K44PYFXH.js";import"./chunks/chunk-2AXF3VSK.js";import{c as R,d as Fe}from"./chunks/chunk-JC6FKIFM.js";import"./chunks/chunk-FB7G2HY2.js";import"./chunks/chunk-NZ75GNSA.js";import"./chunks/chunk-B4KLBBMN.js";import"./chunks/chunk-H7KGWPDF.js";import"./chunks/chunk-PD3225AM.js";import"./chunks/chunk-H5Y5YE6A.js";import{Ha as lo,Ia as Ne}from"./chunks/chunk-WOD3WWUN.js";import"./chunks/chunk-YGPNCCXZ.js";import"./chunks/chunk-E2ZSLTOP.js";import{$ as dt,Aa as ro,Da as ao,Ia as ft,Ja as io,Ka as so,_ as eo,aa as mt,ba as pt,ca as le,da as ut,ea as to,fa as de,la as no,ma as oo,ya as me}from"./chunks/chunk-NG6OXIBR.js";import"./chunks/chunk-VT3Z5G7D.js";import"./chunks/chunk-RSIC5OPE.js";import"./chunks/chunk-K4KGEEBT.js";import"./chunks/chunk-A6KGKEWT.js";import"./chunks/chunk-NYIGHWQY.js";import"./chunks/chunk-KZ4X3DGU.js";import{A as f,Aa as An,Ac as Ie,B as ot,Bc as Gn,C as v,Cc as Wn,Da as G,E as ae,Eb as $n,Fa as Rn,Ga as Tn,Gb as Pn,Ja as at,Je as Pe,K as rt,Ka as On,La as C,Lf as Yn,Mf as Q,Nf as A,Oa as L,Of as Xn,Pc as ct,Ub as Nn,Vb as ie,W as vn,X as kn,Xb as se,Yb as Fn,Yf as Qn,Z as Cn,Zf as Zn,_ as En,aa as Sn,af as Kn,b as M,bb as it,bf as Jn,df as lt,ec as Dn,ef as h,fc as Mn,gc as Ln,hc as Un,ic as H,jc as jn,kc as qn,lc as W,mc as zn,nc as Te,oc as X,oe as Vn,pc as ce,sc as Hn,sd as Bn,tc as Oe,yb as In,zc as st,zd as $e}from"./chunks/chunk-D4FPS43D.js";import{Command as sn}from"commander";(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]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var ja=new Set(["__proto__","prototype","constructor"]),Co=Symbol("looseOptionOccurrences");function ue(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function qa(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function vt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let i=n.indexOf("=");if(i>=0)return{consumed:1,key:n.slice(1,i).trim(),value:n.slice(i+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),a=e[t+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:r,value:a}:{consumed:1,key:r,value:!0}}function Le(e){return ja.has(e)}function Eo(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return vn(t)}function fe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=ue(n.slice(2));r.length>0&&!Le(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=ue(o.slice(1));r.length>0&&!Le(r)&&t.push(r)}return[...new Set(t)]}function So(e){let t=new Set;for(let n of e)for(let o of fe(n))t.add(o);return t}function za(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=ue(t.slice(2));if(n.length>0&&!Le(n))return n}return fe(e)[0]??null}function Ha(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function kt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,a=[],i=[];for(let s of t){let c=fe(s),l=Ha(s);l!==null&&i.push(l);for(let d of c)o.add(d),s.enabled===!1&&r.set(d,l);s.required===!0&&s.enabled!==!1&&c.length>0&&a.push({keys:c,label:l})}for(let s of Object.keys(e)){if(!o.has(s)){let l=i.length>0?` Expected one of: ${[...new Set(i)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${l}`,f.USAGE)}let c=r.get(s);if(c)throw new v(`Option '${c}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of a)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Ga(e){return typeof e=="string"||e==null?e:String(e)}function Wa(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function Ba(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var Va={string:Ga,number:Wa,boolean:Ba};function Ue(e,t){return Array.isArray(e)?e.map(n=>Ue(n,t)):Va[t](e)}function Ao(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):kn(e);return t?o.map(r=>Ue(r,t)):o}function Ka(e,t,n,o){return n?Ao(e,t,o):t?Ue(e,t):e}function Ja(e,t,n){let o=e[Co];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(a=>r.has(a.key)).map(a=>a.value)}function Ro(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))o[r]=a;for(let r of t){let a=za(r);if(!a)continue;let i=r.list===!0,s=fe(r);for(let d of s)if(!(d===a||!Object.hasOwn(o,d))){if(Object.hasOwn(o,a)){if(!i){delete o[d];continue}let m=o[a],p=o[d];o[a]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[a]=o[d],delete o[d]}let c=Eo(r),l=r.repeatable===!0;if(!Object.hasOwn(o,a)){r.default!==void 0&&(o[a]=Ka(r.default,c,i,l));continue}if(i){o[a]=Ao(Ja(n,s,o[a]),c,l);continue}c&&(o[a]=Ue(o[a],c))}return o}function To(e){let t=Object.create(null),n=[];Object.defineProperty(t,Co,{value:n});let o=0;for(;o<e.length;){let r=vt(e,o);if(!r){o+=1;continue}let a=ue(r.key);if(a.length===0||Le(a)){o+=r.consumed;continue}qa(t,a,r.value),n.push({...r,key:a}),o+=r.consumed}return t}function Oo(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=vt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Ct(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let i of t){let s=Eo(i);for(let c of fe(i))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],a=0;for(;a<e.length;){if(e[a]==="--"){r.push(...e.slice(a+1));break}let i=vt(e,a);if(i){let s=ue(i.key);if(n.has(s)){let c=e[a],l=o.has(s)&&!c.includes("=")?1:i.consumed;a+=l;continue}}r.push(e[a]),a+=1}return 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]="a97a61f2-df10-5c2b-8497-f8de17a6222d")}catch{}})();function Io(e){return e.length>0?[e[0]]:[]}function Ya(e){let t=["","Intent:",` ${e.why}`],n=Io(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
3
- `)}function Xa(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
4
- `)}function $o(e,t){return t==="detailed"?Xa(e):Ya(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Qa={cal:"calendar",ctx:"context"};function Za(e,t){return e.commands.find(n=>n.name()===t)??null}function ei(e,t){let n=e;for(let o of t){let r=Za(n,o);if(!r)return null;n=r}return n}function ti(e,t,n,o){let r=ei(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",$o(n,o))}function St(e){return e.includes("--explain")?"detailed":"compact"}var Po={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},Et={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function ni(e){let t=N(e??"");return t?Qa[t]??t:""}function oi(e){let t=ni(e);return t?Po[t]??Et:Et}function No(e,t){let n=oi(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Io(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Fo(e,t=process.argv.slice(2)){let n=St(t);e.addHelpText("after",$o(Et,n));for(let[o,r]of Object.entries(Po))ti(e,o,r,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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function Do(e,t){await io(e,{ok:t.ok,error:t.error,result:ce(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function Mo(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await A(e.pmRoot);await uo({pmRoot:e.pmRoot,author:$e(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(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]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function D(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function V(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return D(t)}function K(e){let t=new Set,n=[];for(let o of e){let r=V(o);r&&(t.has(r)||n.push(r),t.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]="d9d3d041-587b-5660-a909-d0759998248d")}catch{}})();function ze(e){let{required:t,why:n,title:o,...r}=e;return r}var ri=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ho(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!ri.has(e.code)}function Go(e){return`urn:pm-cli:error:${e}`}function _(e){return{...e,type:Go(e.code)}}var Z={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Lo={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Uo={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},je={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},ai={guide:Z,shell:Z,completion:Z,"completion-statuses":Z,"completion-tags":Z,"completion-types":Z,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Lo,cal:Lo,reindex:Uo,"search-advanced":Uo,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":je,"dedupe-audit":je,"dedupe-merge":je,normalize:je};function ii(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return ai[t]}function jo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function si(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function ci(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function At(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function ge(e,t,n){let o=si(n);o&&(e[t]=o)}function He(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),At(t,"attempted_command",e.attempted_command),ge(t,"normalized_args",e.normalized_args),ge(t,"provided_fields",e.provided_fields),ge(t,"missing",e.missing),ge(t,"missing_required_fields",e.missing_required_fields),ge(t,"suggested_flags",e.suggested_flags),At(t,"suggested_retry",e.suggested_retry),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=ci(e.fallback_candidates);return n&&(t.fallback_candidates=n),At(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Rt(e,t,n){n&&e.push(` ${t}: ${n}`)}function he(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function li(e){let t=He(e);if(!t)return[];let n=["Recovery bundle:"];if(Rt(n,"attempted_command",t.attempted_command),he(n,"normalized_args",t.normalized_args," "),he(n,"provided_fields",t.provided_fields,", "),he(n,"missing",t.missing,", "),he(n,"missing_required_fields",t.missing_required_fields,", "),he(n,"suggested_flags",t.suggested_flags,", "),Rt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Rt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function Wo(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...jo("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...jo("Next steps:",e.nextSteps)));let n=li(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
5
- `)}function Ot(e,t){let n={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t};return Ho(e)&&(n.why=e.why),e.examples&&e.examples.length>0&&(n.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(n.next_steps=e.nextSteps),e.recovery&&(n.recovery=e.recovery),n}function It(e){let t={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required};return Ho(e)&&(t.why=e.why),e.examples&&e.examples.length>0&&(t.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(t.next_steps=e.nextSteps),e.recovery&&(t.recovery=e.recovery),t}function Ge(e){return e.replace(/\(outputHelp\)/g,"").trim()}function di(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function ye(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function qo(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function mi(e){let t=e?.normalized_args;return!Array.isArray(t)||t.length===0?void 0:t.find(o=>o.trim().length>0&&!o.startsWith("-"))?.trim()}function pi(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function ui(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,R(s)}}}function fi(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function qe(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function j(e,t,n){if(!n)return e;let o=Ge(t),r=qe(n.code,e.code),a=qe(n.type,Go(r)),i=ye(n.examples)??e.examples,s=ye(n.nextSteps)??e.nextSteps,c=e.code==="command_failed"&&n.code?fi(o):void 0,l=He(n.recovery)??e.recovery;return{...e,code:r,type:a,title:c??e.title,happened:o.length>0?o:e.happened,required:qe(n.required,e.required),why:qe(n.why,e.why),examples:i,nextSteps:s,recovery:l}}function gi(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. Run pm init first\.$/);if(!o)return null;let r=o[1],a=On(process.cwd(),r);return j(_(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function hi(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return j(_({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list-open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list-open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function yi(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:j(_({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function wi(e,t,n){return t.includes("is locked")?j(_({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function xi(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return j(_({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function _i(e,t,n){return t.startsWith("No update flags provided")?j(_({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function bi(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=He(n?.recovery),r=mi(o),a=r?`pm ${r} --help`:"pm <command> --help",i=pi(t),s=ui(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return j(_({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function $t(e,t){let n=Ge(e),o=gi(e,n,t)??hi(e,n,t)??yi(e,n,t)??wi(e,n,t)??xi(e,n,t)??_i(e,n,t)??bi(e,n,t);return o||j(_({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function vi(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function ki(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ci(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function Pt(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function q(e,t={}){let n=Pt(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ci(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return He({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Tt(e,t){return!t||e.includes(t)?e:[...e,t]}var Ei=new Set(["--add","--add-json","--remove"]),Si=new Set(["command","cmd","path"]);function Ai(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Ei.has(o))return o}}function Ri(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Si.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return R(c)}}function Ti(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=ki(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=Pt(o?.providedOptionFlags),l=[a],d=vi(t,a,n),m=s?Tt(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Tt(p,`Replay with preserved arguments: ${s}`):p,g=c&&c.length>0?Tt(u,`Already provided options: ${c.join(", ")}`):u;return _({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:q(o,{missing:l})})}function Oi(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return _({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:q(n,{missing:[r]})})}function Ii(e,t,n){return _({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:q(t,{suggested_flags:n})})}function $i(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=o[1],a=Pt(n?.unknownOptionSuggestions),i=n?.suggestedRetryCommand;if(t==="update"&&(r==="--file"||r==="--doc"))return Ii(r,n,a);let s=ye(n?.unknownOptionOtherCommands),c=["Run command help to confirm the exact option contracts for this command path.",...a&&a.length>0?[`Nearest supported options: ${a.join(", ")}`]:[],...s&&s.length>0?[`${r} is a valid option on: ${s.join(", ")}. If you meant one of those, run that command instead.`]:[],...i?[`Replay with suggested correction: ${i}`]:[]],l=[...i?[i]:[],`pm ${t??"<command>"} --help`];return _({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:"Use supported options only, or move option to the correct subcommand.",why:"Option contracts are command-specific and intentionally validated.",examples:l,nextSteps:c,recovery:q(n,{suggested_flags:a})})}function Pi(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return _({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:qo([t.installCommand,...n]),nextSteps:qo([a,...i]),recovery:q(r)})}function Ni(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ye(t?.unknownCommandExamples),a=ye(t?.unknownCommandNextSteps),i=ii(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?Pi(o,i,s,c,t):_({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:q(t)})}function Fi(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Ai(o);if(!r)return null;let a=Ri(o);return _({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:q(n,a?{suggested_retry:a}:{})})}var Di=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),zo=new Set(["context","ctx"]);function Mi(e,t,n){if(!/too many arguments/i.test(e)||!zo.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>zo.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(Di.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return _({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:q(n,{suggested_retry:c})})}function Nt(e,t,n,o){let r=Ge(e),a=Ti(r,t,n,o)??Oi(r,t,o)??$i(r,t,o)??Ni(r,o)??Fi(r,t,o)??Mi(r,t,o);return a||_({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:q(o)})}function Bo(e,t){return Wo($t(e,t))}function Vo(e,t){return It($t(e,t))}function Ft(e,t,n){return Ot($t(e,n),t)}function Ko(e,t,n,o){return Wo(Nt(e,t,n,o))}function Dt(e,t,n,o){return It(Nt(e,t,n,o))}function We(e,t,n,o,r){return Ot(Nt(e,t,n,r),o)}function Jo(e,t){let n=Yo(e);return Ot(n,t)}function Yo(e){let t=Ge(e);return di(t)?_({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):_({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Xo(e){return It(Yo(e))}import{Option as Li}from"commander";(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]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function y(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Zo(e,t){let n=new Map;for(let o of e){let r=y(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=y(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function Mt(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,g)=>l[g]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return Be(i).takesValue}function E(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function z(e){return typeof e=="boolean"?e:void 0}function Be(e){let t=E(e.value_type)??E(e.type),n=E(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||z(e.required)===!0||z(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Ui(e){if(z(e.visible)===!1)return null;let n=E(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=E(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=E(e.value_name),i=a?` <${a}>`:"",s=E(e.description)??"Extension-provided option.",c=[];z(e.required)===!0&&c.push("required"),z(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function er(e){let t=[...new Set(e.map(Ui).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
2
+ import{a as B,b as yt,c as wt,d as xt,e as _t,f as U,g as bo,h as F,i as T,j as vo,o as Me,p as ko,q as Co,r as bt}from"./chunks/chunk-SQ7QZFQ6.js";import{Za as _o,f as mo,u as po}from"./chunks/chunk-2ZMXX3Q6.js";import"./chunks/chunk-ALDHXLPS.js";import"./chunks/chunk-GKA54IJM.js";import{x as fo}from"./chunks/chunk-MNJ4NNSY.js";import{Fa as ho,j as R,k as Fe,oa as go}from"./chunks/chunk-NUXRRNAB.js";import{qa as uo}from"./chunks/chunk-OJPCFDDY.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as Cn,A as f,Ac as Ie,Ad as $e,Ah as eo,B as ot,Bc as Gn,Bh as dt,C as v,Ca as An,Cc as Wn,Ch as mt,Dg as Yn,Dh as pt,E as ae,Eb as $n,Eg as Q,Eh as le,Fa as G,Fg as A,Fh as ut,Gb as Pn,Gg as Xn,Gh as to,Ha as Rn,Hh as de,I as rt,Ia as Tn,Ke as Pe,La as at,Ma as On,Na as C,Nh as no,Nk as De,Oh as oo,Ok as yo,Pk as gt,Qa as L,Qk as pe,Rk as O,Sc as ct,Sk as wo,Tk as ht,Ub as Nn,Ug as Qn,Vb as ie,Vg as Zn,Xb as se,Y as vn,Yb as Fn,Z as kn,Zk as P,_h as me,aa as En,bf as Kn,bi as ro,c as M,ca as Sn,cb as it,cf as Jn,ec as Dn,ef as lt,ei as ao,fc as Mn,ff as h,gc as Ln,hc as Un,ic as H,jc as jn,ji as ft,kc as qn,ki as io,lc as W,li as so,ll as xo,mc as zn,mi as co,nc as Te,oc as X,pc as ce,pe as Vn,sc as Hn,tc as Oe,td as Bn,xk as lo,yb as In,yk as Ne,zc as st}from"./chunks/chunk-PFSD3DAN.js";import{Command as sn}from"commander";(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]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var qa=new Set(["__proto__","prototype","constructor"]),Eo=Symbol("looseOptionOccurrences");function ue(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function za(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function vt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let i=n.indexOf("=");if(i>=0)return{consumed:1,key:n.slice(1,i).trim(),value:n.slice(i+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),a=e[t+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:r,value:a}:{consumed:1,key:r,value:!0}}function Le(e){return qa.has(e)}function So(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return vn(t)}function fe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=ue(n.slice(2));r.length>0&&!Le(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=ue(o.slice(1));r.length>0&&!Le(r)&&t.push(r)}return[...new Set(t)]}function Ao(e){let t=new Set;for(let n of e)for(let o of fe(n))t.add(o);return t}function Ha(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=ue(t.slice(2));if(n.length>0&&!Le(n))return n}return fe(e)[0]??null}function Ga(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function kt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,a=[],i=[];for(let s of t){let c=fe(s),l=Ga(s);l!==null&&i.push(l);for(let d of c)o.add(d),s.enabled===!1&&r.set(d,l);s.required===!0&&s.enabled!==!1&&c.length>0&&a.push({keys:c,label:l})}for(let s of Object.keys(e)){if(!o.has(s)){let l=i.length>0?` Expected one of: ${[...new Set(i)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${l}`,f.USAGE)}let c=r.get(s);if(c)throw new v(`Option '${c}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of a)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Wa(e){return typeof e=="string"||e==null?e:String(e)}function Ba(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function Va(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var Ka={string:Wa,number:Ba,boolean:Va};function Ue(e,t){return Array.isArray(e)?e.map(n=>Ue(n,t)):Ka[t](e)}function Ro(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):kn(e);return t?o.map(r=>Ue(r,t)):o}function Ja(e,t,n,o){return n?Ro(e,t,o):t?Ue(e,t):e}function Ya(e,t,n){let o=e[Eo];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(a=>r.has(a.key)).map(a=>a.value)}function To(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))o[r]=a;for(let r of t){let a=Ha(r);if(!a)continue;let i=r.list===!0,s=fe(r);for(let d of s)if(!(d===a||!Object.hasOwn(o,d))){if(Object.hasOwn(o,a)){if(!i){delete o[d];continue}let m=o[a],p=o[d];o[a]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[a]=o[d],delete o[d]}let c=So(r),l=r.repeatable===!0;if(!Object.hasOwn(o,a)){r.default!==void 0&&(o[a]=Ja(r.default,c,i,l));continue}if(i){o[a]=Ro(Ya(n,s,o[a]),c,l);continue}c&&(o[a]=Ue(o[a],c))}return o}function Oo(e){let t=Object.create(null),n=[];Object.defineProperty(t,Eo,{value:n});let o=0;for(;o<e.length;){let r=vt(e,o);if(!r){o+=1;continue}let a=ue(r.key);if(a.length===0||Le(a)){o+=r.consumed;continue}za(t,a,r.value),n.push({...r,key:a}),o+=r.consumed}return t}function Io(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=vt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Ct(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let i of t){let s=So(i);for(let c of fe(i))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],a=0;for(;a<e.length;){if(e[a]==="--"){r.push(...e.slice(a+1));break}let i=vt(e,a);if(i){let s=ue(i.key);if(n.has(s)){let c=e[a],l=o.has(s)&&!c.includes("=")?1:i.consumed;a+=l;continue}}r.push(e[a]),a+=1}return 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]="a97a61f2-df10-5c2b-8497-f8de17a6222d")}catch{}})();function $o(e){return e.length>0?[e[0]]:[]}function Xa(e){let t=["","Intent:",` ${e.why}`],n=$o(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
3
+ `)}function Qa(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
4
+ `)}function Po(e,t){return t==="detailed"?Qa(e):Xa(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Za={cal:"calendar",ctx:"context"};function ei(e,t){return e.commands.find(n=>n.name()===t)??null}function ti(e,t){let n=e;for(let o of t){let r=ei(n,o);if(!r)return null;n=r}return n}function ni(e,t,n,o){let r=ti(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",Po(n,o))}function St(e){return e.includes("--explain")?"detailed":"compact"}var No={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},Et={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function oi(e){let t=N(e??"");return t?Za[t]??t:""}function ri(e){let t=oi(e);return t?No[t]??Et:Et}function Fo(e,t){let n=ri(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:$o(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Do(e,t=process.argv.slice(2)){let n=St(t);e.addHelpText("after",Po(Et,n));for(let[o,r]of Object.entries(No))ni(e,o,r,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]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function Mo(e,t){await io(e,{ok:t.ok,error:t.error,result:ce(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function Lo(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await A(e.pmRoot);await uo({pmRoot:e.pmRoot,author:$e(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(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]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function D(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function V(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return D(t)}function K(e){let t=new Set,n=[];for(let o of e){let r=V(o);r&&(t.has(r)||n.push(r),t.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]="d9d3d041-587b-5660-a909-d0759998248d")}catch{}})();function ze(e){let{required:t,why:n,title:o,...r}=e;return r}var ai=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Go(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!ai.has(e.code)}function Wo(e){return`urn:pm-cli:error:${e}`}function _(e){return{...e,type:Wo(e.code)}}var Z={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Uo={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},jo={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},je={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},ii={guide:Z,shell:Z,completion:Z,"completion-statuses":Z,"completion-tags":Z,"completion-types":Z,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Uo,cal:Uo,reindex:jo,"search-advanced":jo,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":je,"dedupe-audit":je,"dedupe-merge":je,normalize:je};function si(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return ii[t]}function qo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function ci(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function li(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function At(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function ge(e,t,n){let o=ci(n);o&&(e[t]=o)}function He(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),At(t,"attempted_command",e.attempted_command),ge(t,"normalized_args",e.normalized_args),ge(t,"provided_fields",e.provided_fields),ge(t,"missing",e.missing),ge(t,"missing_required_fields",e.missing_required_fields),ge(t,"suggested_flags",e.suggested_flags),At(t,"suggested_retry",e.suggested_retry),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=li(e.fallback_candidates);return n&&(t.fallback_candidates=n),At(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Rt(e,t,n){n&&e.push(` ${t}: ${n}`)}function he(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function di(e){let t=He(e);if(!t)return[];let n=["Recovery bundle:"];if(Rt(n,"attempted_command",t.attempted_command),he(n,"normalized_args",t.normalized_args," "),he(n,"provided_fields",t.provided_fields,", "),he(n,"missing",t.missing,", "),he(n,"missing_required_fields",t.missing_required_fields,", "),he(n,"suggested_flags",t.suggested_flags,", "),Rt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Rt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function Bo(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...qo("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...qo("Next steps:",e.nextSteps)));let n=di(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
5
+ `)}function Ot(e,t){let n={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t};return Go(e)&&(n.why=e.why),e.examples&&e.examples.length>0&&(n.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(n.next_steps=e.nextSteps),e.recovery&&(n.recovery=e.recovery),n}function It(e){let t={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required};return Go(e)&&(t.why=e.why),e.examples&&e.examples.length>0&&(t.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(t.next_steps=e.nextSteps),e.recovery&&(t.recovery=e.recovery),t}function Ge(e){return e.replace(/\(outputHelp\)/g,"").trim()}function mi(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function ye(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function zo(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function pi(e){let t=e?.normalized_args;return!Array.isArray(t)||t.length===0?void 0:t.find(o=>o.trim().length>0&&!o.startsWith("-"))?.trim()}function ui(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function fi(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,R(s)}}}function gi(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function qe(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function j(e,t,n){if(!n)return e;let o=Ge(t),r=qe(n.code,e.code),a=qe(n.type,Wo(r)),i=ye(n.examples)??e.examples,s=ye(n.nextSteps)??e.nextSteps,c=e.code==="command_failed"&&n.code?gi(o):void 0,l=He(n.recovery)??e.recovery;return{...e,code:r,type:a,title:c??e.title,happened:o.length>0?o:e.happened,required:qe(n.required,e.required),why:qe(n.why,e.why),examples:i,nextSteps:s,recovery:l}}function hi(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. Run pm init first\.$/);if(!o)return null;let r=o[1],a=On(process.cwd(),r);return j(_(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function yi(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return j(_({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list-open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list-open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function wi(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:j(_({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function xi(e,t,n){return t.includes("is locked")?j(_({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function _i(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return j(_({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function bi(e,t,n){return t.startsWith("No update flags provided")?j(_({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function vi(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=He(n?.recovery),r=pi(o),a=r?`pm ${r} --help`:"pm <command> --help",i=ui(t),s=fi(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return j(_({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function $t(e,t){let n=Ge(e),o=hi(e,n,t)??yi(e,n,t)??wi(e,n,t)??xi(e,n,t)??_i(e,n,t)??bi(e,n,t)??vi(e,n,t);return o||j(_({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function ki(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function Ci(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ei(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function Pt(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function q(e,t={}){let n=Pt(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ei(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return He({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Tt(e,t){return!t||e.includes(t)?e:[...e,t]}var Si=new Set(["--add","--add-json","--remove"]),Ai=new Set(["command","cmd","path"]);function Ri(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Si.has(o))return o}}function Ti(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Ai.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return R(c)}}function Oi(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=Ci(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=Pt(o?.providedOptionFlags),l=[a],d=ki(t,a,n),m=s?Tt(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Tt(p,`Replay with preserved arguments: ${s}`):p,g=c&&c.length>0?Tt(u,`Already provided options: ${c.join(", ")}`):u;return _({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:q(o,{missing:l})})}function Ii(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return _({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:q(n,{missing:[r]})})}function $i(e,t,n){return _({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:q(t,{suggested_flags:n})})}function Pi(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=o[1],a=Pt(n?.unknownOptionSuggestions),i=n?.suggestedRetryCommand;if(t==="update"&&(r==="--file"||r==="--doc"))return $i(r,n,a);let s=ye(n?.unknownOptionOtherCommands),c=["Run command help to confirm the exact option contracts for this command path.",...a&&a.length>0?[`Nearest supported options: ${a.join(", ")}`]:[],...s&&s.length>0?[`${r} is a valid option on: ${s.join(", ")}. If you meant one of those, run that command instead.`]:[],...i?[`Replay with suggested correction: ${i}`]:[]],l=[...i?[i]:[],`pm ${t??"<command>"} --help`];return _({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:"Use supported options only, or move option to the correct subcommand.",why:"Option contracts are command-specific and intentionally validated.",examples:l,nextSteps:c,recovery:q(n,{suggested_flags:a})})}function Ni(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return _({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:zo([t.installCommand,...n]),nextSteps:zo([a,...i]),recovery:q(r)})}function Fi(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ye(t?.unknownCommandExamples),a=ye(t?.unknownCommandNextSteps),i=si(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?Ni(o,i,s,c,t):_({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:q(t)})}function Di(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Ri(o);if(!r)return null;let a=Ti(o);return _({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:q(n,a?{suggested_retry:a}:{})})}var Mi=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),Ho=new Set(["context","ctx"]);function Li(e,t,n){if(!/too many arguments/i.test(e)||!Ho.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>Ho.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(Mi.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return _({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:q(n,{suggested_retry:c})})}function Nt(e,t,n,o){let r=Ge(e),a=Oi(r,t,n,o)??Ii(r,t,o)??Pi(r,t,o)??Fi(r,o)??Di(r,t,o)??Li(r,t,o);return a||_({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:q(o)})}function Vo(e,t){return Bo($t(e,t))}function Ko(e,t){return It($t(e,t))}function Ft(e,t,n){return Ot($t(e,n),t)}function Jo(e,t,n,o){return Bo(Nt(e,t,n,o))}function Dt(e,t,n,o){return It(Nt(e,t,n,o))}function We(e,t,n,o,r){return Ot(Nt(e,t,n,r),o)}function Yo(e,t){let n=Xo(e);return Ot(n,t)}function Xo(e){let t=Ge(e);return mi(t)?_({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):_({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Qo(e){return It(Xo(e))}import{Option as Ui}from"commander";(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]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function y(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function er(e,t){let n=new Map;for(let o of e){let r=y(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=y(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function Mt(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,g)=>l[g]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return Be(i).takesValue}function E(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function z(e){return typeof e=="boolean"?e:void 0}function Be(e){let t=E(e.value_type)??E(e.type),n=E(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||z(e.required)===!0||z(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function ji(e){if(z(e.visible)===!1)return null;let n=E(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=E(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=E(e.value_name),i=a?` <${a}>`:"",s=E(e.description)??"Extension-provided option.",c=[];z(e.required)===!0&&c.push("required"),z(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function tr(e){let t=[...new Set(e.map(ji).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
6
6
  Extension-provided flags:
7
7
  ${t.join(`
8
- `)}`}function tr(e){let t=new Map;for(let r of e){let a=y(r.target_command);if(a.length===0)continue;let i=t.get(a)??[];i.push(...r.flags),t.set(a,i)}let n=[...t.entries()].sort(([r],[a])=>r.localeCompare(a)),o=new Map;for(let[r,a]of n){let i=er(a);i&&o.set(r,i)}return o}function nr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Qo(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function ji(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function qi(e){let t=new Map;for(let n of e){let o=y(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:nr(o,n.action),description:r,intent:a,examples:Qo(n.examples),failure_hints:Qo(n.failure_hints),arguments:ji(n.arguments),flags:[],source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function zi(e){let t=new Map;for(let n of e){let o=y(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function Hi(e,t,n){let o=new Set;for(let r of e){let a=y(r);a.length>0&&o.add(a)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function Gi(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function or(e,t,n,o=new Map){let r=qi(t),a=zi(n),i=Hi(e,r,a),s=new Map,c=[...i].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Gi(l,r,o)??r.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:nr(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m})}return s}function Wi(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function rr(e,t){for(let n of t.arguments)e.argument(Wi(n),n.description??"Extension argument.")}function ar(e){if(z(e.visible)===!1)return null;let n=E(e.long),o=E(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=n&&n.startsWith("--")&&n.length>2?n:null,i=[r,a].filter(s=>s!==null);return i.length>0?i:null}function Bi(e){let t=ar(e);if(!t)return null;let{valueName:n}=Be(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Vi(e){let t=ar(e);if(!t)return null;let{valueName:n}=Be(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function ir(e){let t=E(e.description)??"Extension-provided option.",n=[];z(e.required)===!0&&n.push("required"),z(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function sr(e,t){let n=E(t.long),o=E(t.short);return e.options.some(r=>{let a=r;return n!==null&&a.long===n||o!==null&&a.short===o})}function Lt(e,t){for(let n of t){if(sr(e,n))continue;let o=Vi(n);if(!o)continue;let r=ir(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Li(o,r).argParser((a,i=[])=>[...Array.isArray(i)?i:[i],a]))}}function Ut(e,t){return er(t.filter(n=>!sr(e,n)))}function Ki(e){let t=Bi(e);if(!t)return null;let n=E(e.long),o=E(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:i,valueName:s}=Be(e),c=z(e.required)===!0;return{flags:t,long:r,short:a,description:ir(e),takes_value:i,value_required:i,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function cr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=Ki(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function lr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function dr(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
8
+ `)}`}function nr(e){let t=new Map;for(let r of e){let a=y(r.target_command);if(a.length===0)continue;let i=t.get(a)??[];i.push(...r.flags),t.set(a,i)}let n=[...t.entries()].sort(([r],[a])=>r.localeCompare(a)),o=new Map;for(let[r,a]of n){let i=tr(a);i&&o.set(r,i)}return o}function or(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Zo(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function qi(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function zi(e){let t=new Map;for(let n of e){let o=y(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:or(o,n.action),description:r,intent:a,examples:Zo(n.examples),failure_hints:Zo(n.failure_hints),arguments:qi(n.arguments),flags:[],source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function Hi(e){let t=new Map;for(let n of e){let o=y(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function Gi(e,t,n){let o=new Set;for(let r of e){let a=y(r);a.length>0&&o.add(a)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function Wi(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function rr(e,t,n,o=new Map){let r=zi(t),a=Hi(n),i=Gi(e,r,a),s=new Map,c=[...i].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Wi(l,r,o)??r.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:or(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m})}return s}function Bi(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function ar(e,t){for(let n of t.arguments)e.argument(Bi(n),n.description??"Extension argument.")}function ir(e){if(z(e.visible)===!1)return null;let n=E(e.long),o=E(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=n&&n.startsWith("--")&&n.length>2?n:null,i=[r,a].filter(s=>s!==null);return i.length>0?i:null}function Vi(e){let t=ir(e);if(!t)return null;let{valueName:n}=Be(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Ki(e){let t=ir(e);if(!t)return null;let{valueName:n}=Be(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function sr(e){let t=E(e.description)??"Extension-provided option.",n=[];z(e.required)===!0&&n.push("required"),z(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function cr(e,t){let n=E(t.long),o=E(t.short);return e.options.some(r=>{let a=r;return n!==null&&a.long===n||o!==null&&a.short===o})}function Lt(e,t){for(let n of t){if(cr(e,n))continue;let o=Ki(n);if(!o)continue;let r=sr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Ui(o,r).argParser((a,i=[])=>[...Array.isArray(i)?i:[i],a]))}}function Ut(e,t){return tr(t.filter(n=>!cr(e,n)))}function Ji(e){let t=Vi(e);if(!t)return null;let n=E(e.long),o=E(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:i,valueName:s}=Be(e),c=z(e.required)===!0;return{flags:t,long:r,short:a,description:sr(e),takes_value:i,value_required:i,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function lr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=Ji(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function dr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function mr(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
9
9
  Extension command metadata:
10
10
  ${t.join(`
11
- `)}`}function jt(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function we(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:jt(o).includes(n))??null}function ee(e,t){let n=e;for(let o of t){let r=we(n,o);if(!r)return null;n=r}return n}var mr=new WeakSet;function pr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],a=we(n,r);if(a){n=a;continue}let i=n.command(r);mr.add(i),o<t.length-1?(i.description("Extension-provided command group."),i.action(()=>{i.help()})):i.description("Extension-provided command path."),n=i}return n}function Ji(e,t){let n=e,o=[];for(let r of t){let a=we(n,r);if(!a)return null;if(o.push(r),!mr.has(a))return{core_path:o.join(" "),extension_path:t.join(" ")};n=a}return null}function Yi(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),a=Ji(e,r);if(!a||a.core_path===t&&!n.has(t))return null;let i=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${i}`}function ur(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,i)=>a.localeCompare(i)).filter(a=>{let i=Yi(e,a,o,n.get(a));return i?(r(i),!1):!0})}function fr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(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]="c0186e30-9c25-5539-b778-1ef2ee21764a")}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]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function Xi(e,t){let n=ae(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Qi(e){return ae(e.status)?.toLowerCase()??"pending"}function Zi(e){return e.mandatory===!0}function es(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function yr(e){let t=[];return e.forEach((n,o)=>{if(!Zi(n.definition))return;let r=Qi(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:Xi(n.definition,o),status:r})}),t.sort(es),t}function gr(e){return Array.isArray(e)&&e.length>0}var ts=new Set(["create","beads import","todos import"]),ns=new Set(["restore","update","close","delete","append","claim","release"]),os=new Set(["comments","notes","learnings"]),rs=new Set(["files","docs","test"]),as=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function qt(e,t){let n=t.force===!0;return ts.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:ns.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:os.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:rs.has(e)?{isMutation:gr(t.add)||gr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function is(e,t,n){if(qt(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return oo(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>as.has(r.trim().toLowerCase())):!1}function hr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function ss(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(ae(t[1])||r.push("source"),ae(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:r.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:r,suggested_flags:r.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function cs(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||hr(n.status)!==hr(r.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let i=G(r,W()),s=await Qn(o,a,r.id_prefix,r.item_format,i.type_to_folder);if(!s)return;let c=await Zn(s,{schema:r.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||h(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function zt(e,t,n,o,r){if(!is(e,t,n)||(ss(e,t,n),!await M(L(r))))return;let a=await Q(r);o.json!==!0&&await cs(e,t,n,r,a.settings);let i=no({author:$e(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of i.warnings)h(`warning:${s}`)}function wr(e,t,n){if(n.length===0)return;let o=qt(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(i=>`extension_migration_blocking:${i.layer}:${i.name}:${i.id}:${i.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${a}`,f.CONFLICT)}async function Ht(e,t,n,o){if(!qt(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await M(L(n)))return;let{settings:a,metadata:i,warnings:s}=await Q(n);for(let c of s)h(`warning:${c}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Yn(a),await Xn(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=G(a,W());await ro(n,a.item_format,"item_format:pre_mutation_sync",c.type_to_folder,a.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]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}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]="042ecf17-9265-5496-bbee-4e7a07371618")}catch{}})();var xe=Sn.join("|"),ls={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},ds={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}};function ms(e,t){let n=ds[e];if(!n)return[];let o=D(t);for(let[r,a]of Object.entries(n))if(D(r)===o)return a;return[]}function Gt(e,t,n){if(n.length===0)return e;if(t){let i=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...i?{extension_command_failure:{code:"extension_command_activation_failed",extension:i.name,layer:i.layer,error:i.error,recovery_commands:i.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(i=>`- ${i.layer}:${i.name}: ${i.error}`).join(`
11
+ `)}`}function jt(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function we(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:jt(o).includes(n))??null}function ee(e,t){let n=e;for(let o of t){let r=we(n,o);if(!r)return null;n=r}return n}var pr=new WeakSet;function ur(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],a=we(n,r);if(a){n=a;continue}let i=n.command(r);pr.add(i),o<t.length-1?(i.description("Extension-provided command group."),i.action(()=>{i.help()})):i.description("Extension-provided command path."),n=i}return n}function Yi(e,t){let n=e,o=[];for(let r of t){let a=we(n,r);if(!a)return null;if(o.push(r),!pr.has(a))return{core_path:o.join(" "),extension_path:t.join(" ")};n=a}return null}function Xi(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),a=Yi(e,r);if(!a||a.core_path===t&&!n.has(t))return null;let i=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${i}`}function fr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,i)=>a.localeCompare(i)).filter(a=>{let i=Xi(e,a,o,n.get(a));return i?(r(i),!1):!0})}function gr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(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]="c0186e30-9c25-5539-b778-1ef2ee21764a")}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]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function Qi(e,t){let n=ae(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Zi(e){return ae(e.status)?.toLowerCase()??"pending"}function es(e){return e.mandatory===!0}function ts(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function wr(e){let t=[];return e.forEach((n,o)=>{if(!es(n.definition))return;let r=Zi(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:Qi(n.definition,o),status:r})}),t.sort(ts),t}function hr(e){return Array.isArray(e)&&e.length>0}var ns=new Set(["create","beads import","todos import"]),os=new Set(["restore","update","close","delete","append","claim","release"]),rs=new Set(["comments","notes","learnings"]),as=new Set(["files","docs","test"]),is=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function qt(e,t){let n=t.force===!0;return ns.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:os.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:rs.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:as.has(e)?{isMutation:hr(t.add)||hr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function ss(e,t,n){if(qt(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return oo(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>is.has(r.trim().toLowerCase())):!1}function yr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function cs(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(ae(t[1])||r.push("source"),ae(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:r.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:r,suggested_flags:r.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function ls(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||yr(n.status)!==yr(r.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let i=G(r,W()),s=await Qn(o,a,r.id_prefix,r.item_format,i.type_to_folder);if(!s)return;let c=await Zn(s,{schema:r.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||h(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function zt(e,t,n,o,r){if(!ss(e,t,n)||(cs(e,t,n),!await M(L(r))))return;let a=await Q(r);o.json!==!0&&await ls(e,t,n,r,a.settings);let i=no({author:$e(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of i.warnings)h(`warning:${s}`)}function xr(e,t,n){if(n.length===0)return;let o=qt(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(i=>`extension_migration_blocking:${i.layer}:${i.name}:${i.id}:${i.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${a}`,f.CONFLICT)}async function Ht(e,t,n,o){if(!qt(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await M(L(n)))return;let{settings:a,metadata:i,warnings:s}=await Q(n);for(let c of s)h(`warning:${c}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Yn(a),await Xn(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=G(a,W());await ro(n,a.item_format,"item_format:pre_mutation_sync",c.type_to_folder,a.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]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}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]="042ecf17-9265-5496-bbee-4e7a07371618")}catch{}})();var xe=Sn.join("|"),ds={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},ms={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}};function ps(e,t){let n=ms[e];if(!n)return[];let o=D(t);for(let[r,a]of Object.entries(n))if(D(r)===o)return a;return[]}function Gt(e,t,n){if(n.length===0)return e;if(t){let i=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...i?{extension_command_failure:{code:"extension_command_activation_failed",extension:i.name,layer:i.layer,error:i.error,recovery_commands:i.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(i=>`- ${i.layer}:${i.name}: ${i.error}`).join(`
12
12
  `),r=n.find(i=>i.declared_command_match===!0);if(!r)return`${e}
13
13
  Extension activation failures:
14
14
  ${o}`;let a=(r.recovery_commands??[]).map(i=>`- ${i}`).join(`
@@ -19,11 +19,11 @@ ${a}`:""}
19
19
 
20
20
  ${e}
21
21
  Extension activation failures:
22
- ${o}`}function Wt(e){return F(e).commandPathTokens[0]??T(e)??"<command>"}function ps(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let a=N(O(r)),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a),o.push(...r.commands)}for(let r of t.keys()){let a=N(r),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a)}return[...n].sort((r,a)=>r.localeCompare(a))}function xr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,i=Number.POSITIVE_INFINITY;for(let s of r){let c=it(s,o,a);c!==null&&(i=Math.min(i,c))}return Number.isFinite(i)?4+i:Number.POSITIVE_INFINITY}function _r(e){return D(e).slice(2).replace(/-/g,"")}function Bt(e){return R(e)}function us(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=ls[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function br(e){let t=fo(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function fs(e,t){let n=br(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let a=new Set,i=r.source;if(i)for(let c of[i.name,i.package]){let l=br(c??"");l.length>0&&a.add(l)}if(a.size===0)continue;[...a].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,a)=>r.localeCompare(a))}function vr(e,t){let n=new Set,o=t??Ne(e);for(let r of o){r.flag.startsWith("--")&&n.add(D(r.flag));for(let a of r.aliases??[])a.startsWith("--")&&n.add(D(a))}return[...n].sort((r,a)=>r.localeCompare(a))}function gs(e,t){if(!e.startsWith("--"))return[];let n=_r(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let a of t){let i=_r(a);if(i===n)continue;if(n.length>=3&&i.startsWith(n)){r.push({flag:a,rank:0,distance:i.length-n.length});continue}let s=it(n,i,o);s===null||s<=0||r.push({flag:a,rank:1,distance:s})}return r.sort((a,i)=>a.rank!==i.rank?a.rank-i.rank:a.distance!==i.distance?a.distance-i.distance:a.flag.localeCompare(i.flag)).map(a=>a.flag).slice(0,3)}var Ve,hs=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function ys(){if(Ve)return Ve;let e=new Map;for(let t of Pe)if(!hs.has(t))for(let n of vr(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Ve=e,Ve}function ws(e,t){if(!e.startsWith("--"))return[];let n=ys().get(D(e));if(!n)return[];let o=t?.trim().toLowerCase();return n.filter(r=>r!==o).slice(0,3)}function xs(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let a=r.indexOf("="),i=a>=0?r.slice(0,a):r;if(D(i)!==D(t))continue;let s=[...e];return s[o]=a>=0?`${n}${r.slice(a)}`:n,s}}function _s(e){let t=new Set(e.commandPaths),n=a=>Math.min(xr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?xr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(a,i)=>{if(!Number.isFinite(i)||!t.has(a))return;let s=o.get(a);(s===void 0||i<s)&&o.set(a,i)};for(let a of e.commandPaths)r(a,n(a));for(let[a,i]of Object.entries(co))a!=="read"&&r(i,n(a));return[...o.entries()].sort(([a,i],[s,c])=>i!==c?i-c:a.localeCompare(s)).map(([a])=>a)}function bs(e){let t=_s(e),n=fs(e.primaryToken,e.extensionDescriptors).filter(o=>e.commandPaths.includes(o));return kr([...t,...n])}function vs(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function ks(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function Vt(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=N(o[1]);if(r.length===0)return;let a=ps(t,n);if(a.length===0)return;let i=r.split(" ")[0],s=bs({commandPaths:a,normalizedUnknown:r,primaryToken:i,extensionDescriptors:n}),c=vs(a),l=(s.length>0?s:c).slice(0,3),d=ks(l,s.length>0),m=us(r),p=s.length>0?`Did you mean: ${l.join(", ")}?`:null;return{unknownCommandExamples:d,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function kr(e){return Array.from(new Set(e))}function Cs(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
23
- `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Es(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function Ss(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function Cr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=Ss(n,r);if(!a)return o;o=!0,n=a}return o}async function As(e){try{let t=C(process.cwd(),e.path);if(!await M(L(t)))return xe;let n=await A(t),o=e.noExtensions?void 0:W(),r=G(n,o);return r.types.length>0?r.types.join("|"):xe}catch{return xe}}function Rs(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?kr([...ms(t,n[1]),...gs(n[1],vr(t))]):void 0;return{match:n,suggestions:o,otherCommands:n?ws(n[1],t):[]}}function Ts(e,t,n){if(!t||!n||n.length===0)return;let o=xs(e,t[1],n[0]);return o?Bt(o):void 0}function Os(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Es(Cs(n[1].trim())):void 0;return o?.startsWith("--")?t.some(a=>a===o||a.startsWith(`${o}=`))?void 0:Bt([...t,o,"<value>"]):void 0}async function _e(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=Me(process.argv.slice(2)).argv,s=U(i),c=T(i),l=Bt(i),d=K(i),m=await As(s),p=Vt(a,t,n),u=Rs(a,c),g=Ts(i,u.match,u.suggestions)??Os(a,i);return{message:a,commandName:c,allowedTypes:m,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:u.suggestions,unknownOptionOtherCommands:u.otherCommands.length>0?u.otherCommands:void 0,suggestedRetryCommand:g,...p,...o}}async function Kt(e,t,n,o={}){let r=await _e(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,suggestedRetryCommand:b,failedExtensions:x}=r,k=Ko(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,suggestedRetryCommand:b,failedExtensions:x}),$=await Wn("help_format",{message:k,command:i,allowed_types:s});return $.handled&&typeof $.result=="string"?$.result:k}async function Jt(e,t,n,o=!1,r={}){let a=await _e(e,t,n,r),i=We(a.message,a.commandName,a.allowedTypes,f.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,suggestedRetryCommand:a.suggestedRetryCommand,failedExtensions:a.failedExtensions});return JSON.stringify(o?ze(i):i,null,2)}import te 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]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function Yt(e,t={},n=[]){let o={readSettings:A,loadExtensions:ie,activateExtensions:se,resolveImplicitPmRoot:at,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(N),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function Er(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await Yt(t,n,o),a={readSettings:A,loadExtensions:ie,activateExtensions:se,resolveImplicitPmRoot:at,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(te.resolve(i)===te.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${te.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${te.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${te.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${te.resolve(t)} install <package> --project".`})}catch{}return 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]="a33bada3-c1a1-5343-8a77-51dc76dd5a11")}catch{}})();function Is(e,t){if(t.length===0)return e;let n=ee(e,t);if(n)return n;let o=t.join(" ");if(!Pe.some(r=>r===o)&&!lo(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ee(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function $s(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Sr(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function Ps(e){let t=new Map;for(let n of e){let o=n,r=Sr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function Ns(e){return R(e)}function Fs(e){let t=e.options??[],n=Ps(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Sr(o),l=(s?n.get(s)??[]:[]).filter(x=>x!==r.long).map(x=>x.trim()).filter(x=>x.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),g=u||a.includes("["),b={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:g,value_required:u,value_name:$s(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(b.default_value=r.defaultValue),b})}function Ds(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Ms(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0,variadic:o.variadic===!0,description:a}})}function Ls(e){return e.commands.map(t=>({name:t.name().trim(),aliases:jt(t),description:t.description().trim()})).sort((t,n)=>t.name.localeCompare(n.name))}function Us(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function js(e,t,n,o,r){let a=St(n),i=N(O(t)),s=N(o.join(" ")),c=s.length>i.length?s:i,l=c.length>0?c:void 0,d=No(l,a),m=l?r.get(l):void 0,p=Us(a,d,m),u=Ds(lr(Fs(t),cr(m))),g=Ls(t);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:c.length>0?c:e.name(),description:t.description(),usage:t.usage(),intent:p.intent,examples:p.examples,tips:p.tips,arguments:Ms(t),options:u,subcommands:g,has_subcommands:g.length>0}}async function Ar(e,t,n){let o=U(t);if(!o.json)return!1;let r=F(t);if(!r.requested)return!1;let a=Is(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=Vt(i,e,n),c=We(i,"help",xe,f.USAGE,{...s,attemptedCommand:Ns(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});h(JSON.stringify(c,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let i=js(e,a,t,r.commandPathTokens,n);Jn(`${JSON.stringify(i,null,2)}
24
- `)}return process.exitCode=f.SUCCESS,!0}function qs(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
25
- `)}function zs(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Hs(e,t,n){let o=vo(n);if(!o)return qs(e,t);let r=Rn(o,t);if(!r){let l=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${l}`].join(`
26
- `)}let a=e==="create"?new Set(["title","description","type",...r.required_create_fields,...r.required_create_repeatables]):new Set,i=Tn(r,e,a),s=l=>l.length>0?l.map(d=>An(e,d)).join(", "):"none",c=["",`Type-aware option policies for ${r.name}:`,` required: ${s(i.required)}`,` disabled: ${s(i.disabled)}`,` hidden: ${s(i.hidden)}`];return e==="create"&&["Reminder","Meeting","Event"].includes(r.name)&&(c.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),c.push(" strict parity remains available via --create-mode strict.")),zs(c,r),i.errors.length>0&&c.push(` config errors: ${i.errors.join("; ")}`),c.join(`
27
- `)}function Rr(e,t,n){let o=T(n);if(o!=="create"&&o!=="update")return;let r=we(e,o);r&&r.addHelpText("after",Hs(o,t,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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function Tr(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=T(e)==="contracts"&&e.includes("--full");return r||a?await o(t):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]="bb6049e8-1185-5702-b8c1-3a30a98db516")}catch{}})();var Xt="PM_CLI_PACKAGE_ROOT";function Gs(){return Cn(import.meta.url,["../.."])}(typeof process.env[Xt]!="string"||process.env[Xt]?.trim().length===0)&&(process.env[Xt]=Gs());var oe=null,I=null;function Ws(e){oe=e}function Bs(e){S=e}var Vs=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),Ks=new Set(["parse","preflight","execute","unknown"]),Js=new Set(["usage","validation","conflict","runtime","unknown"]),be=null,J=null,S=new Map,cn=250,Ys=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),Xs=new Set(["1","true","yes","on"]),Qs=me(()=>import("./chunks/register-setup-DL7FFABC.js")),Zs=me(()=>import("./chunks/register-list-query-FJZCJ67O.js")),ec=me(()=>import("./chunks/register-mutation-YGYPW3BL.js")),tc=me(()=>import("./chunks/register-operations-WMDSUMQF.js"));function Je(e){return R(e)}function Nr(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>V(o)??o))];return n.length>0?n:void 0}function nc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(d=>V(d)??d)),a=Nr(e),i=t.find(d=>w.commands.some(m=>m.name()===d)),s=i?w.commands.find(d=>d.name()===i):void 0,c=new Set([...w.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>V(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=V(d)??d;return r.has(m)?!1:c.has(m)||Mt(t,i,m,S)!==void 0});return l&&l.length>0?l:void 0}function oc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?V(r):void 0,i=e.find(p=>w.commands.some(u=>u.name()===p)),s=i?w.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=Mt(e,i,a,S),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?Je([...e,...d]):t;return m===t?void 0:m}function rc(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function ac(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...rc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Fr(e,t,n){let o=Fe(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:Je(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:Je(o)}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=Je(o),c=K(o),l=nc(n,o,i),d=oc(o,s,l,i),m=ac({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function ne(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function Dr(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function ln(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function Mr(e){if(!e)return;let t=e.trim().toLowerCase();if(Vs.has(t))return t}function Lr(e){if(!e)return;let t=e.trim().toLowerCase();if(Ks.has(t))return t}function Ur(e){if(!e)return;let t=e.trim().toLowerCase();if(Js.has(t))return t}function jr(e){let t=ne(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(Dr(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=ln(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>rt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function qr(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function zr(){let e=rt(ce()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=ln(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=o===f.SUCCESS,a=ne(e,"error_code","errorCode")??qr(r,o),i=Ur(ne(e,"error_category","errorCategory"))??(r?void 0:ot(a)),s=r?void 0:jr(e)??`command_exit_${o}`,c=Mr(ne(e,"command_resolution","commandResolution"))??dt({ok:r,errorCode:a,errorCategory:i}),l=Lr(ne(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Ee(e){let t=I;I=null,await Do(t,e);let n=oe;if(oe=null,!n){Oe();return}let o=[],r=Hn();try{await Mo({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Pn(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:ce(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Oe()}!n.globalOptions.json&&o.length>0&&h(`[pm] warning: afterCommand hook_warnings=${P(o)}`),n.profileEnabled&&o.length>0&&h(`profile:extensions hook_warnings=${P(o)}`)}async function Hr(){await eo()}function Gr(e){return Xs.has((process.env[e]??"").trim().toLowerCase())}function Wr(e){return Gr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Ys.has(Math.trunc(e))}async function Ye(e){return Wr(e.exit_code)?(await Hr(),to(e),!0):!1}async function Br(e){let t=B(e.error),n=Xo(t);e.bootstrapGlobal.json?h(JSON.stringify(Jo(t,f.GENERIC_FAILURE),null,2)):h(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Hr(),ut(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,le(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||h(`Failed to report error: ${B(a)}`)}try{await Ee({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||h(`Failed to run error hooks: ${B(a)}`)}try{await de()}catch(a){e.bootstrapGlobal.json||h(`Failed to flush error reporting: ${B(a)}`)}}function ve(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=To(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=So(n),s=Ne(O(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return kt(c,[...s,...n],O(e)),Ro(r,n,a)}return r}function en(e,t){let n=y(t);return n.length===0?[]:e.flags.filter(o=>y(o.target_command)===n).flatMap(o=>o.flags)}function Xe(e,t,n){let o=en(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=en(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function dn(e){return e.arguments??[]}function Or(e){let t=dn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Vr(e,t){if(!e)return!1;let n=y(t);return e.importers.some(o=>y(`${o.importer} import`)===n)||e.exporters.some(o=>y(`${o.exporter} export`)===n)}function Kr(e,t){let n=dn(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${Or(e)}${s}`,f.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Or(e)}${s}`,f.USAGE)}}function ic(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function sc(e,t,n){if(n.length>0){kt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(ic).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Jr(e,t,n,o){e&&(Kr(e,t),sc(e,n,o))}var cc={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},Qt=new Map;function tn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Yr(e,t){return e.options.some(n=>n.long===t)}function Xr(e,t){return e.options.some(n=>n.short===t)}function nn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Xr(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,ht);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!Yr(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,ht);return}e.option(`${i} <value>`,a)}}async function Qr(e,t){let n=cc[e];if(!n)return[];let o=`${t}:${n}`,r=Qt.get(o);if(r)return r;if(!await M(L(t)))return Qt.set(o,[]),[];let a=await A(t),s=(ct(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:tn(c.type),value_type:tn(c.type)})));return Qt.set(o,s),s}async function Zr(e,t){let n=U(t),o=C(process.cwd(),n.path);if(!await M(L(o)))return;let r=J?.key===un(o)?J.snapshot:null,a=r===null?await A(o):r.settings,i=ct(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ee(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";nn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)nn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function mn(e,t,n,o,r){let a=T(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await A(t),s=G(i,o);Rr(e,s,n)}catch{}}function on(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ea(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function pn(e){return e.some(t=>t==="--profile")}function un(e){return`pm-root:${e}`}function ta(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=y(n);o.length!==0&&t.push(o)}return t}function Se(e){let t=y(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of ta(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function na(e,t){let n=y(e);if(n.length===0)return!1;let o=Se(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function fn(e){return e.activation?.commands??[...e.contributions?.commands??[],...e.contributions?.command_handlers??[],...e.contributions?.command_overrides??[],...e.contributions?.flag_commands??[],...e.contributions?.parser_overrides??[],...e.contributions?.renderer_ownership?.flatMap(t=>t.commands)??[]]}function Qe(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var oa=new Set(["hooks","parser","preflight","renderers"]),ra=new Set(["commands","schema","services","importers"]),lc=new Set(["reindex","search","search-advanced"]),dc=new Set(["--template"]);function ke(e,t){for(let n of t)if(e.has(n))return!0;return!1}function aa(e){let t=y(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return lc.has(n??t)}function ia(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function gn(e){return y(e.commandPath??"")==="create"&&ia(e,dc)}function sa(e){return e.some(t=>{let n=y(t);return n==="templates"||n.startsWith("templates ")})}function rn(e,t){return e.some(n=>na(n,t))||gn(t)&&sa(e)}function ca(e){return[e.hooks?.length??0,e.preflight_overrides??0,e.item_types?.length??0,e.item_fields?.length??0,e.relationship_kinds?.length??0,e.service_overrides?.length??0,(e.renderer_overrides?.length??0)-(e.renderer_ownership?.length??0)].some(n=>n>0)}function la(e,t){let n=e.activation?.commands??[];if(n.length>0)return rn(n,t);let o=fn(e);if(rn(o,t)||Qe(e).has("search")&&aa(t.commandPath))return!0;if(e.contributions)return ca(e.contributions)}function hn(e,t){let n=la(e,t);if(n!==void 0)return n;let o=Qe(e);return!!(ke(o,oa)||ke(o,ra))}function Ze(e,t){return e.effective.length===0?!1:y(t.commandPath??"").length>0?e.effective.some(o=>hn(o,t)):e.effective.some(o=>{let r=Qe(o);return fn(o).length>0||ke(r,oa)||ke(r,ra)||r.has("search")})}function yn(e){let t=Se(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??y(e.commandPath??"");if(t.length===0)return"all";let n=gn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function da(e){return yn(e)==="all"?void 0:t=>hn(t,e)}function Ae(e){let t=F(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=_o(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function ma(e){let t=e.args.map(String);if(y(O(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function an(e){for(let t of e)t.startsWith("settings_read_")&&h(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function pa(e,t){e.profile&&(h(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&h(`profile:extensions activation_warnings=${P(t.activationWarnings)}`))}function et(e,t,n){if(!e)return;let o=y(n.commandPath??"")||"<none>";h(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function tt(e,t=Q){let n=un(e);if(J?.key===n)return J.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Nn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return J={key:n,snapshot:s},s}catch{return J={key:n,snapshot:null},null}}async function re(e,t,n=A){let o=t?yn(t):"all",r=ea(e,o);if(be?.key===r)return be.snapshot;try{let a=await n(e),i=await ie({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?da(t):void 0}),s=await se({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>y(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),l=tr(s.registrations.flags),d=Zo(s.commands.handlers,s.registrations.commands),m=or(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return be={key:r,snapshot:p},p}catch{return be={key:r,snapshot:null},null}}async function ua(e){let t=pe(e);if(t.noExtensions){let i=C(process.cwd(),t.path);return await M(L(i))&&an((await Q(i)).warnings),null}let n=C(process.cwd(),t.path),o=await tt(n);if(!o)return null;an(o.settingsReadWarnings);let r={commandPath:O(e),commandArgs:ma(e)};if(!Ze(o.discovery,r))return et(t.profile,o,r),null;let a=await re(n,r);return a?(pa(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function fa(e){let t=await re(e);return t?new Map(t.commandDescriptors):S}async function ga(e,t){return(await go({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function ha(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return mo(e,xo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ya(e,t,n,o=[]){let r=O(e),a=Ct(e.args.map(String),o),i={...t},s={...n},c=C(process.cwd(),n.path),l=await Ie({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&h(`profile:extensions parser_warnings=${P(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,Jr(S.get(y(r)),a,i,o),X(void 0),Te({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await st({command:r,args:a,options:i,global:s,pm_root:c,sdk:ha(c,s)});if(s.profile&&d.warnings.length>0&&h(`profile:extensions command_handler_warnings=${P(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),X(d.result),d.result}var Ir=Symbol("pm.wrappedActionHandler");function mc(e,t){let n=e[e.length-1];return n instanceof sn?n:t}function $r(e,t,n){e&&n.length>0&&h(`profile:extensions ${t}=${P(n)}`)}function pc(e){let t=S.get(y(e.commandPath));if(!t||!Vr(e.activeRegistrations,e.commandPath))return;let n=dn(t).length===0?Oo(e.commandArgs):Ct(e.commandArgs,e.extensionFlagDefinitions);Kr(t,n)}function uc(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function wa(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Ir]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=mc(i,n),c=Date.now();gt(s);let l=pe(s),d=O(s),m=C(process.cwd(),l.path),p=s.args.map(String),u=W(),g=u?Xe(u,d,p):[],b=await Qr(d,m),x=ve(s,p,[...g,...b]),k=await Ie({command:d,args:p,options:x,global:l,pm_root:m});$r(l.profile,"parser_warnings",k.warnings),p=k.context.args,x=k.context.options,l=k.context.global,pc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:g}),l=await yo(l),ho(s,l),uc(s,i,p),De(s,x),X(void 0),Te({command:d,args:p,options:{...x},global:{...l},pm_root:m});let $=await st({command:d,args:p,options:x,global:l,pm_root:m,sdk:ha(m,l)});if($r(l.profile,"command_handler_warnings",$.warnings),$.handled){X($.result),lt($.result,{...l,command:d,commandArgs:p,commandOptions:x,pmRoot:m}),l.profile&&h(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[Ir]=!0}for(let r of n.commands)t(r)};t(e)}async function Ke(e){S=new Map,H({overrides:[]}),e&&await mn(e.rootProgram,e.pmRoot,e.invocationArgv,In(),e.settings)}function fc(e,t,n,o){if(t?.flags&&t.flags.length>0){Lt(e,t.flags);let r=Ut(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function xa(e,t){let n=U(t),o=C(process.cwd(),n.path);if(n.noExtensions){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await tt(o),a=Ae(t);if(!r){await Ke();return}if(!Ze(r.discovery,a)){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),et(pn(t),r,a);return}let i=await re(o,a);if(!i){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}H(i.services),S=new Map(i.commandDescriptors),await mn(e,o,t,i.registrations,i.settings);let s=ur(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>fr(i.activationWarnings,h,l)),c=l=>{let d=l.split(" ").filter(k=>k.length>0),m=i.commandDescriptors.get(l),p=ee(e,d),u=i.commandFlagHelp.get(l),g=m?dr(m):null;if(p){fc(p,m,u,g);return}let b=pr(e,d);m?.description&&b.description(m.description);let x=u;m&&(rr(b,m),m.flags.length>0&&(Lt(b,m.flags),x=Ut(b,m.flags)??void 0)),x&&b.addHelpText("after",x),g&&b.addHelpText("after",g),b.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...k)=>{let $=k[k.length-1],Y=$ instanceof sn?$:b,Re=pe(Y),Ua=Date.now(),xn=Xe(i.registrations,l,Y.args.map(String)),_n=ve(Y,Y.args.map(String),xn),bn=await ya(Y,_n,Re,xn);await wo(Re,bn),lt(bn,{...Re,command:l,commandArgs:Y.args.map(String),commandOptions:_n,pmRoot:o}),Re.profile&&h(`profile:command=${l} took_ms=${Date.now()-Ua}`)})};for(let l of s)c(l)}var Ce=En(import.meta.url,["../.."])??"0.0.0",w=bt(Ce);function _a(e){e.hook("preAction",async(t,n)=>{oe=null,I=null,Oe(),gt(n);let o=n.optsWithGlobals(),r=pe(n),a=O(n),i=n.args.map(String),s=ve(n,i),c={...r};Vn(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession}),await ao(a,c);let l=C(process.cwd(),r.path),d=await ua(n);if(!d){oe=Fn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),I=await ft({command:a,pm_version:Ce,args:i,options:s,global:c,pm_root:l}),mt(a,i,s,{source_context:I?.source_context,source_context_source:I?.source_context_source}),pt(a),await Ht(a,s,l,on()),await zt(a,i,s,c,l);return}Dn(d.hooks),Mn(d.commands),Ln(d.parsers),Un(d.preflight),H(d.services),jn(d.renderers),qn(d.registrations);let m=Xe(d.registrations,a,i);s=ve(n,i,m);let p=await Ie({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&h(`profile:extensions parser_warnings=${P(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,De(n,s);let u=await Gn({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:on()});c.profile&&u.warnings.length>0&&h(`profile:extensions preflight_warnings=${P(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,De(n,s);let g=u.decision;await Ht(a,s,d.pmRoot,g),await zt(a,i,s,c,d.pmRoot);let b=g.run_extension_migrations?await ga(d.registrations.migrations,d.pmRoot):[];c.profile&&b.length>0&&h(`profile:extensions migration_warnings=${P(b)}`);let x=yr(d.registrations.migrations);oe={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:x},X(void 0),Te({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),I=await ft({command:a,pm_version:Ce,args:i,options:s,global:c,pm_root:d.pmRoot}),mt(a,i,s,{source_context:I?.source_context,source_context_source:I?.source_context_source}),pt(a);let k=await $n(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&k.length>0&&h(`profile:extensions hook_warnings=${P(k)}`),g.enforce_mandatory_migration_gate&&wr(a,s,x)}),e.hook("postAction",async()=>{let t=zr();le(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Ee(t)})}_a(w);var gc=new Set(["--version","-V"]),hc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ba=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),va=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),yc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),wc=new Set(["claim","close-task","pause-task","release","start-task","test"]),Zt={setup:!0,listQuery:!0,mutation:!0,operation:!0},xc=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function nt(e){return e.some(t=>gc.has(t))}function ka(e){if(nt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||F(e).requested)return Zt;let t=T(e);if(!t)return Zt;let n=t.trim().toLowerCase();return hc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ba.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:va.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:yc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:Zt}function Ca(e){return e.length===0||F(e).requested}var Pr=Symbol("pmCliIdempotentTopLevelRegistration");function Ea(e){let t=e;if(t[Pr])return;t[Pr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new sn(a):n(o,...r)})}async function _c(e,t){if(Ea(e),t.setup){let{registerSetupCommands:n}=await Qs();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Zs(),o=typeof t.targetCommandName=="string"&&ba.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await ec();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await tc();n(e)}}function Sa(e,t){return nt(t)?!1:F(t).requested?!0:!!T(t)}function Aa(e){if(nt(e))return!1;let t=T(e);return t?xc.has(t):!1}function bc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=Fe(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function Ra(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=va.has(t)||wc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=bc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:i,examples:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function vc(e){return async t=>{let n=ot(t.errorCode),o=dt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await so({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Ce,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Ta(e){if(e.bootstrapGlobal.noExtensions)return;let t=Ae(e.invocationArgv),n=await tt(e.bootstrapPmRoot);if(n&&Ze(n.discovery,t)){let o=await re(e.bootstrapPmRoot,t);Oa(o);return}n&&et(pn(e.invocationArgv),n,t),H({overrides:[]})}function Oa(e){if(!e){H({overrides:[]});return}H(e.services)}async function wn(e){le(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Ee({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Ia(){le(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Ee({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function $a(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(xt(e.error)||!n))return!1;let o=B(e.error),r=e.error instanceof v?e.error.exitCode:wt(t),a=e.error instanceof v?e.error.context:void 0,i=Fr(a,e.invocationArgv,o),s=Vo(o,i),c=e.bootstrapGlobal.lean?ze(Ft(o,r,i)):Ft(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Kn(c,u=>`${JSON.stringify(u,null,2)}
28
- `):c,null,2):Bo(o,i);h(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Ye({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:I?.source_context});return await wn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(ut(_t(e.error,o)),await de(cn)),process.exitCode=r,!0}async function Pa(e,t){let n=Wt(e.invocationArgv),o=`unknown command '${n}'`,r=C(process.cwd(),e.bootstrapGlobal.path),a=await fa(r),i=Ae(e.invocationArgv),s=await Yt(r,{},Se(i)),c=await _e({message:o},w,a,{failedExtensions:s}),l=Dt(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:l.code,errorMessage:l.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await Ye({command:n,error_code:l.code,error_category:d,exit_code:f.USAGE,error_message:l.detail,command_resolution:m,resolution_stage:"parse",source_context:I?.source_context}),u=e.jsonErrors?await Jt({message:o},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await Kt({message:o},w,a,{failedExtensions:s}),g=Gt(u,e.jsonErrors,s);await wn({errorMessage:o,exitCode:f.USAGE,classificationCode:l.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),h(g),p&&await de(cn),process.exitCode=f.USAGE}async function Na(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=F(e.invocationArgv);return r.requested&&!Cr(w,r.commandPathTokens)?(await Pa(e,t),!0):(await Ia(),!0)}async function Fa(e,t){let n=await _e(e.error,w,S),o=Dt(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:r,commandResolution:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),i=await Ye({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:f.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:I?.source_context}),s=e.jsonErrors?await Jt(e.error,w,S,e.bootstrapGlobal.lean===!0):await Kt(e.error,w,S),c=await Er(o.code,e.bootstrapPmRoot,{},Se(Ae(e.invocationArgv))),l=Gt(s,e.jsonErrors,c);await wn({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:a,resolutionStage:"parse"}),h(l),i&&await de(cn),process.exitCode=f.USAGE}function Da(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function Ma(e){let t=e.error.code,n=String(e.error.message??"");if(!await Na(e,t,n)){if(t==="commander.version"){await Ia();return}await Fa(e,t)}}async function La(e){let t=U(e.invocationArgv),n=C(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:T(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:vc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Ta({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await $a(o,yt(e.error))){if(Da(e.error)){await Ma(o);return}await Br({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function jl(e=process.argv.slice(2)){w=bt(Ce),_a(w),be=null,J=null,S=new Map,zn();let t=Me(e),n=t.argv,o=[process.argv[0],process.argv[1],...n],r=n.length===0,a,i;try{let s=U(n);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});a=ko(s.author),Ra(t),i=bo(n);let c=ka(n);if(await _c(w,c),Ca(n)&&Fo(w,n),Sa(w,n)?await xa(w,n):(S=new Map,H({overrides:[]})),Aa(n)&&await Zr(w,n),wa(w),await Ar(w,n,S))return;if(r){w.outputHelp();return}let m=await A(C(process.cwd(),s.path)),p=await Tr(n,C(process.cwd(),s.path),s.noExtensions,re);await po({pmRoot:C(process.cwd(),s.path),packages:p?.contextIntentPackages},()=>Bn(m.agent_identity.harness_signals,()=>w.parseAsync(o),{probesEnabled:m.agent_identity?.probes_enabled}))}catch(s){await La({error:s,invocationArgv:n})}finally{i?.(),a?.()}}var ql={activationCommandMatchesProbe:na,bootstrapProfileEnabled:pn,buildBootstrapActivationProbe:Ae,buildPostActionTelemetryOutcome:zr,buildPmCliRecoveryContext:Fr,buildRuntimeExtensionDiscoverySnapshotCacheKey:un,buildRuntimeExtensionActivationScope:yn,buildRuntimeExtensionSnapshotCacheKey:ea,buildRuntimeExtensionFilterForProbe:da,addRuntimeFieldOption:nn,collectActivationCommandCandidates:Se,collectExtensionFlagDefinitionsForCommand:en,collectExtensionFlagDefinitionsForInvocation:Xe,collectLeadingCommandArgs:ta,collectParsedActivationCommandArgs:ma,collectRuntimeFieldLooseFlagDefinitionsForCommand:Qr,commandHasLongOption:Yr,commandHasShortOption:Xr,commandPathNeedsSearchExtensions:aa,commandPathNeedsTemplateExtensions:gn,describeUnknownError:B,defaultPreflightDecision:on,discoveryNeedsActivationForProbe:Ze,emitExtensionProfile:pa,emitExtensionSkippedProfile:et,emitSettingsReadWarnings:an,ensureIdempotentTopLevelCommandRegistration:Ea,enforceExplicitRetryForFlagTypos:Ra,envFlagEnabled:Gr,executeRegisteredRuntimeMigrations:ga,extractCommandScopedOptions:ve,extensionActivationCommands:fn,extensionCapabilities:Qe,extensionNeedsActivationForProbe:hn,extensionProvidesTemplatesRuntime:sa,hasAnyCapability:ke,hasGlobalExtensionContributions:ca,handleGenericRunPmCliError:Br,handleRunPmCliCommanderError:Ma,handleRunPmCliError:La,handleRunPmCliHelpDisplayError:Na,handleRunPmCliKnownError:$a,handleRunPmCliCommanderUsageError:Fa,handleUnknownHelpCommandError:Pa,inferMissingFieldsFromErrorMessage:Nr,inferPostActionErrorCode:qr,inferPostActionFailureMessage:jr,invocationRequestsVersion:nt,isCommanderError:xt,loadRuntimeExtensionCommandDescriptorsForRecovery:fa,loadRuntimeExtensionDiscoverySnapshot:tt,loadRuntimeExtensionSnapshot:re,maybeLoadRuntimeExtensions:ua,maybeAttachCreateUpdatePolicyHelpText:mn,maybeLogHandledCliErrorToSentry:Ye,matchesStaticExtensionCommand:rn,normalizeTelemetryCommandResolution:Mr,normalizeTelemetryErrorCategory:Ur,normalizeTelemetryResolutionStage:Lr,normalizeThrownExitCode:wt,probeUsesAnyFlag:ia,prepareExtensionServicesForRunPmCliError:Ta,readRecordBoolean:Dr,readRecordNumber:ln,readRecordString:ne,registerDynamicExtensionCommandPaths:xa,registerRuntimeSchemaFieldFlags:Zr,resolveCoreCommandRegistrationSelection:ka,resolveStaticExtensionActivationDecision:la,resolveUnknownHelpToken:Wt,readThrownExitCode:yt,runAndClearAfterCommandHooks:Ee,runRequiredExtensionCommand:ya,shouldAttachRichHelpTextForInvocation:Ca,shouldLogHandledErrorToSentry:Wr,shouldRegisterDynamicExtensionPaths:Sa,shouldRegisterRuntimeSchemaFlags:Aa,shouldHandleRunPmCliCommanderError:Da,setActiveExtensionHookContextForTest:Ws,setActiveRuntimeExtensionCommandDescriptorsForTest:Bs,setRecoveredExtensionServices:Oa,toLooseFieldDefinitionType:tn,isImporterOrExporterCommandPath:Vr,validateDynamicExtensionCommandInvocation:Jr,wrapProgramActionsForExtensionHandlers:wa,wrapThrownErrorForSentry:_t};export{ql as _testOnly,jl as runPmCli};
22
+ ${o}`}function Wt(e){return F(e).commandPathTokens[0]??T(e)??"<command>"}function us(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let a=N(O(r)),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a),o.push(...r.commands)}for(let r of t.keys()){let a=N(r),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a)}return[...n].sort((r,a)=>r.localeCompare(a))}function _r(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,i=Number.POSITIVE_INFINITY;for(let s of r){let c=it(s,o,a);c!==null&&(i=Math.min(i,c))}return Number.isFinite(i)?4+i:Number.POSITIVE_INFINITY}function br(e){return D(e).slice(2).replace(/-/g,"")}function Bt(e){return R(e)}function fs(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=ds[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function vr(e){let t=go(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function gs(e,t){let n=vr(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let a=new Set,i=r.source;if(i)for(let c of[i.name,i.package]){let l=vr(c??"");l.length>0&&a.add(l)}if(a.size===0)continue;[...a].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,a)=>r.localeCompare(a))}function kr(e,t){let n=new Set,o=t??Ne(e);for(let r of o){r.flag.startsWith("--")&&n.add(D(r.flag));for(let a of r.aliases??[])a.startsWith("--")&&n.add(D(a))}return[...n].sort((r,a)=>r.localeCompare(a))}function hs(e,t){if(!e.startsWith("--"))return[];let n=br(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let a of t){let i=br(a);if(i===n)continue;if(n.length>=3&&i.startsWith(n)){r.push({flag:a,rank:0,distance:i.length-n.length});continue}let s=it(n,i,o);s===null||s<=0||r.push({flag:a,rank:1,distance:s})}return r.sort((a,i)=>a.rank!==i.rank?a.rank-i.rank:a.distance!==i.distance?a.distance-i.distance:a.flag.localeCompare(i.flag)).map(a=>a.flag).slice(0,3)}var Ve,ys=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function ws(){if(Ve)return Ve;let e=new Map;for(let t of Pe)if(!ys.has(t))for(let n of kr(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Ve=e,Ve}function xs(e,t){if(!e.startsWith("--"))return[];let n=ws().get(D(e));if(!n)return[];let o=t?.trim().toLowerCase();return n.filter(r=>r!==o).slice(0,3)}function _s(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let a=r.indexOf("="),i=a>=0?r.slice(0,a):r;if(D(i)!==D(t))continue;let s=[...e];return s[o]=a>=0?`${n}${r.slice(a)}`:n,s}}function bs(e){let t=new Set(e.commandPaths),n=a=>Math.min(_r(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?_r(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(a,i)=>{if(!Number.isFinite(i)||!t.has(a))return;let s=o.get(a);(s===void 0||i<s)&&o.set(a,i)};for(let a of e.commandPaths)r(a,n(a));for(let[a,i]of Object.entries(co))a!=="read"&&r(i,n(a));return[...o.entries()].sort(([a,i],[s,c])=>i!==c?i-c:a.localeCompare(s)).map(([a])=>a)}function vs(e){let t=bs(e),n=gs(e.primaryToken,e.extensionDescriptors).filter(o=>e.commandPaths.includes(o));return Cr([...t,...n])}function ks(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Cs(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function Vt(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=N(o[1]);if(r.length===0)return;let a=us(t,n);if(a.length===0)return;let i=r.split(" ")[0],s=vs({commandPaths:a,normalizedUnknown:r,primaryToken:i,extensionDescriptors:n}),c=ks(a),l=(s.length>0?s:c).slice(0,3),d=Cs(l,s.length>0),m=fs(r),p=s.length>0?`Did you mean: ${l.join(", ")}?`:null;return{unknownCommandExamples:d,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function Cr(e){return Array.from(new Set(e))}function Es(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
23
+ `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Ss(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function As(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function Er(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=As(n,r);if(!a)return o;o=!0,n=a}return o}async function Rs(e){try{let t=C(process.cwd(),e.path);if(!await M(L(t)))return xe;let n=await A(t),o=e.noExtensions?void 0:W(),r=G(n,o);return r.types.length>0?r.types.join("|"):xe}catch{return xe}}function Ts(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Cr([...ps(t,n[1]),...hs(n[1],kr(t))]):void 0;return{match:n,suggestions:o,otherCommands:n?xs(n[1],t):[]}}function Os(e,t,n){if(!t||!n||n.length===0)return;let o=_s(e,t[1],n[0]);return o?Bt(o):void 0}function Is(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Ss(Es(n[1].trim())):void 0;return o?.startsWith("--")?t.some(a=>a===o||a.startsWith(`${o}=`))?void 0:Bt([...t,o,"<value>"]):void 0}async function _e(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=Me(process.argv.slice(2)).argv,s=U(i),c=T(i),l=Bt(i),d=K(i),m=await Rs(s),p=Vt(a,t,n),u=Ts(a,c),g=Os(i,u.match,u.suggestions)??Is(a,i);return{message:a,commandName:c,allowedTypes:m,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:u.suggestions,unknownOptionOtherCommands:u.otherCommands.length>0?u.otherCommands:void 0,suggestedRetryCommand:g,...p,...o}}async function Kt(e,t,n,o={}){let r=await _e(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,suggestedRetryCommand:b,failedExtensions:x}=r,k=Jo(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,suggestedRetryCommand:b,failedExtensions:x}),$=await Wn("help_format",{message:k,command:i,allowed_types:s});return $.handled&&typeof $.result=="string"?$.result:k}async function Jt(e,t,n,o=!1,r={}){let a=await _e(e,t,n,r),i=We(a.message,a.commandName,a.allowedTypes,f.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,suggestedRetryCommand:a.suggestedRetryCommand,failedExtensions:a.failedExtensions});return JSON.stringify(o?ze(i):i,null,2)}import te 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]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function Yt(e,t={},n=[]){let o={readSettings:A,loadExtensions:ie,activateExtensions:se,resolveImplicitPmRoot:at,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(N),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function Sr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await Yt(t,n,o),a={readSettings:A,loadExtensions:ie,activateExtensions:se,resolveImplicitPmRoot:at,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(te.resolve(i)===te.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${te.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${te.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${te.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${te.resolve(t)} install <package> --project".`})}catch{}return 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]="a33bada3-c1a1-5343-8a77-51dc76dd5a11")}catch{}})();function $s(e,t){if(t.length===0)return e;let n=ee(e,t);if(n)return n;let o=t.join(" ");if(!Pe.some(r=>r===o)&&!lo(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ee(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function Ps(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Ar(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function Ns(e){let t=new Map;for(let n of e){let o=n,r=Ar(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function Fs(e){return R(e)}function Ds(e){let t=e.options??[],n=Ns(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Ar(o),l=(s?n.get(s)??[]:[]).filter(x=>x!==r.long).map(x=>x.trim()).filter(x=>x.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),g=u||a.includes("["),b={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:g,value_required:u,value_name:Ps(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(b.default_value=r.defaultValue),b})}function Ms(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Ls(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0,variadic:o.variadic===!0,description:a}})}function Us(e){return e.commands.map(t=>({name:t.name().trim(),aliases:jt(t),description:t.description().trim()})).sort((t,n)=>t.name.localeCompare(n.name))}function js(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function qs(e,t,n,o,r){let a=St(n),i=N(O(t)),s=N(o.join(" ")),c=s.length>i.length?s:i,l=c.length>0?c:void 0,d=Fo(l,a),m=l?r.get(l):void 0,p=js(a,d,m),u=Ms(dr(Ds(t),lr(m))),g=Us(t);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:c.length>0?c:e.name(),description:t.description(),usage:t.usage(),intent:p.intent,examples:p.examples,tips:p.tips,arguments:Ls(t),options:u,subcommands:g,has_subcommands:g.length>0}}async function Rr(e,t,n){let o=U(t);if(!o.json)return!1;let r=F(t);if(!r.requested)return!1;let a=$s(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=Vt(i,e,n),c=We(i,"help",xe,f.USAGE,{...s,attemptedCommand:Fs(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});h(JSON.stringify(c,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let i=qs(e,a,t,r.commandPathTokens,n);Jn(`${JSON.stringify(i,null,2)}
24
+ `)}return process.exitCode=f.SUCCESS,!0}function zs(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
25
+ `)}function Hs(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Gs(e,t,n){let o=ko(n);if(!o)return zs(e,t);let r=Rn(o,t);if(!r){let l=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${l}`].join(`
26
+ `)}let a=e==="create"?new Set(["title","description","type",...r.required_create_fields,...r.required_create_repeatables]):new Set,i=Tn(r,e,a),s=l=>l.length>0?l.map(d=>An(e,d)).join(", "):"none",c=["",`Type-aware option policies for ${r.name}:`,` required: ${s(i.required)}`,` disabled: ${s(i.disabled)}`,` hidden: ${s(i.hidden)}`];return e==="create"&&["Reminder","Meeting","Event"].includes(r.name)&&(c.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),c.push(" strict parity remains available via --create-mode strict.")),Hs(c,r),i.errors.length>0&&c.push(` config errors: ${i.errors.join("; ")}`),c.join(`
27
+ `)}function Tr(e,t,n){let o=T(n);if(o!=="create"&&o!=="update")return;let r=we(e,o);r&&r.addHelpText("after",Gs(o,t,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]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function Or(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=T(e)==="contracts"&&e.includes("--full");return r||a?await o(t):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]="52c705ab-a5c4-5b94-b806-4eaac31b6e9c")}catch{}})();var Xt="PM_CLI_PACKAGE_ROOT";function Ws(){return Cn(import.meta.url,["../.."])}(typeof process.env[Xt]!="string"||process.env[Xt]?.trim().length===0)&&(process.env[Xt]=Ws());var oe=null,I=null;function Bs(e){oe=e}function Vs(e){S=e}var Ks=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),Js=new Set(["parse","preflight","execute","unknown"]),Ys=new Set(["usage","validation","conflict","runtime","unknown"]),be=null,J=null,S=new Map,cn=250,Xs=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),Qs=new Set(["1","true","yes","on"]),Zs=me(()=>import("./chunks/register-setup-2HL5ZHMK.js")),ec=me(()=>import("./chunks/register-list-query-WFZAMJHZ.js")),tc=me(()=>import("./chunks/register-mutation-SOKKOTHQ.js")),nc=me(()=>import("./chunks/register-operations-5XQETS6E.js"));function Je(e){return R(e)}function Fr(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>V(o)??o))];return n.length>0?n:void 0}function oc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(d=>V(d)??d)),a=Fr(e),i=t.find(d=>w.commands.some(m=>m.name()===d)),s=i?w.commands.find(d=>d.name()===i):void 0,c=new Set([...w.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>V(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=V(d)??d;return r.has(m)?!1:c.has(m)||Mt(t,i,m,S)!==void 0});return l&&l.length>0?l:void 0}function rc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?V(r):void 0,i=e.find(p=>w.commands.some(u=>u.name()===p)),s=i?w.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=Mt(e,i,a,S),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?Je([...e,...d]):t;return m===t?void 0:m}function ac(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function ic(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...ac(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Dr(e,t,n){let o=Fe(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:Je(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:Je(o)}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=Je(o),c=K(o),l=oc(n,o,i),d=rc(o,s,l,i),m=ic({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function ne(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function Mr(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function ln(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function Lr(e){if(!e)return;let t=e.trim().toLowerCase();if(Ks.has(t))return t}function Ur(e){if(!e)return;let t=e.trim().toLowerCase();if(Js.has(t))return t}function jr(e){if(!e)return;let t=e.trim().toLowerCase();if(Ys.has(t))return t}function qr(e){let t=ne(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(Mr(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=ln(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>rt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function zr(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Hr(){let e=rt(ce()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=ln(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=fo(o),a=ne(e,"error_code","errorCode")??zr(r,o),i=jr(ne(e,"error_category","errorCategory"))??(r?void 0:ot(a)),s=r?void 0:qr(e)??`command_exit_${o}`,c=Lr(ne(e,"command_resolution","commandResolution"))??dt({ok:r,errorCode:a,errorCategory:i}),l=Ur(ne(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Ee(e){let t=I;I=null,await Mo(t,e);let n=oe;if(oe=null,!n){Oe();return}let o=[],r=Hn();try{await Lo({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Pn(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:ce(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Oe()}!n.globalOptions.json&&o.length>0&&h(`[pm] warning: afterCommand hook_warnings=${P(o)}`),n.profileEnabled&&o.length>0&&h(`profile:extensions hook_warnings=${P(o)}`)}async function Gr(){await eo()}function Wr(e){return Qs.has((process.env[e]??"").trim().toLowerCase())}function Br(e){return Wr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Xs.has(Math.trunc(e))}async function Ye(e){return Br(e.exit_code)?(await Gr(),to(e),!0):!1}async function Vr(e){let t=B(e.error),n=Qo(t);e.bootstrapGlobal.json?h(JSON.stringify(Yo(t,f.GENERIC_FAILURE),null,2)):h(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Gr(),ut(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,le(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||h(`Failed to report error: ${B(a)}`)}try{await Ee({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||h(`Failed to run error hooks: ${B(a)}`)}try{await de()}catch(a){e.bootstrapGlobal.json||h(`Failed to flush error reporting: ${B(a)}`)}}function ve(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=Oo(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=Ao(n),s=Ne(O(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return kt(c,[...s,...n],O(e)),To(r,n,a)}return r}function en(e,t){let n=y(t);return n.length===0?[]:e.flags.filter(o=>y(o.target_command)===n).flatMap(o=>o.flags)}function Xe(e,t,n){let o=en(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=en(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function dn(e){return e.arguments??[]}function Ir(e){let t=dn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Kr(e,t){if(!e)return!1;let n=y(t);return e.importers.some(o=>y(`${o.importer} import`)===n)||e.exporters.some(o=>y(`${o.exporter} export`)===n)}function Jr(e,t){let n=dn(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${Ir(e)}${s}`,f.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Ir(e)}${s}`,f.USAGE)}}function sc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function cc(e,t,n){if(n.length>0){kt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(sc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Yr(e,t,n,o){e&&(Jr(e,t),cc(e,n,o))}var lc={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},Qt=new Map;function tn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Xr(e,t){return e.options.some(n=>n.long===t)}function Qr(e,t){return e.options.some(n=>n.short===t)}function nn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Qr(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,ht);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!Xr(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,ht);return}e.option(`${i} <value>`,a)}}async function Zr(e,t){let n=lc[e];if(!n)return[];let o=`${t}:${n}`,r=Qt.get(o);if(r)return r;if(!await M(L(t)))return Qt.set(o,[]),[];let a=await A(t),s=(ct(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:tn(c.type),value_type:tn(c.type)})));return Qt.set(o,s),s}async function ea(e,t){let n=U(t),o=C(process.cwd(),n.path);if(!await M(L(o)))return;let r=J?.key===un(o)?J.snapshot:null,a=r===null?await A(o):r.settings,i=ct(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ee(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";nn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)nn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function mn(e,t,n,o,r){let a=T(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await A(t),s=G(i,o);Tr(e,s,n)}catch{}}function on(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function ta(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function pn(e){return e.some(t=>t==="--profile")}function un(e){return`pm-root:${e}`}function na(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=y(n);o.length!==0&&t.push(o)}return t}function Se(e){let t=y(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of na(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function oa(e,t){let n=y(e);if(n.length===0)return!1;let o=Se(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function fn(e){return e.activation?.commands??[...e.contributions?.commands??[],...e.contributions?.command_handlers??[],...e.contributions?.command_overrides??[],...e.contributions?.flag_commands??[],...e.contributions?.parser_overrides??[],...e.contributions?.renderer_ownership?.flatMap(t=>t.commands)??[]]}function Qe(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var ra=new Set(["hooks","parser","preflight","renderers"]),aa=new Set(["commands","schema","services","importers"]),dc=new Set(["reindex","search","search-advanced"]),mc=new Set(["--template"]);function ke(e,t){for(let n of t)if(e.has(n))return!0;return!1}function ia(e){let t=y(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return dc.has(n??t)}function sa(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function gn(e){return y(e.commandPath??"")==="create"&&sa(e,mc)}function ca(e){return e.some(t=>{let n=y(t);return n==="templates"||n.startsWith("templates ")})}function rn(e,t){return e.some(n=>oa(n,t))||gn(t)&&ca(e)}function la(e){return[e.hooks?.length??0,e.preflight_overrides??0,e.item_types?.length??0,e.item_fields?.length??0,e.relationship_kinds?.length??0,e.service_overrides?.length??0,(e.renderer_overrides?.length??0)-(e.renderer_ownership?.length??0)].some(n=>n>0)}function da(e,t){let n=e.activation?.commands??[];if(n.length>0)return rn(n,t);let o=fn(e);if(rn(o,t)||Qe(e).has("search")&&ia(t.commandPath))return!0;if(e.contributions)return la(e.contributions)}function hn(e,t){let n=da(e,t);if(n!==void 0)return n;let o=Qe(e);return!!(ke(o,ra)||ke(o,aa))}function Ze(e,t){return e.effective.length===0?!1:y(t.commandPath??"").length>0?e.effective.some(o=>hn(o,t)):e.effective.some(o=>{let r=Qe(o);return fn(o).length>0||ke(r,ra)||ke(r,aa)||r.has("search")})}function yn(e){let t=Se(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??y(e.commandPath??"");if(t.length===0)return"all";let n=gn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function ma(e){return yn(e)==="all"?void 0:t=>hn(t,e)}function Ae(e){let t=F(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=bo(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function pa(e){let t=e.args.map(String);if(y(O(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function an(e){for(let t of e)t.startsWith("settings_read_")&&h(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function ua(e,t){e.profile&&(h(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&h(`profile:extensions activation_warnings=${P(t.activationWarnings)}`))}function et(e,t,n){if(!e)return;let o=y(n.commandPath??"")||"<none>";h(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function tt(e,t=Q){let n=un(e);if(J?.key===n)return J.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Nn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return J={key:n,snapshot:s},s}catch{return J={key:n,snapshot:null},null}}async function re(e,t,n=A){let o=t?yn(t):"all",r=ta(e,o);if(be?.key===r)return be.snapshot;try{let a=await n(e),i=await ie({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?ma(t):void 0}),s=await se({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>y(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),l=nr(s.registrations.flags),d=er(s.commands.handlers,s.registrations.commands),m=rr(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return be={key:r,snapshot:p},p}catch{return be={key:r,snapshot:null},null}}async function fa(e){let t=pe(e);if(t.noExtensions){let i=C(process.cwd(),t.path);return await M(L(i))&&an((await Q(i)).warnings),null}let n=C(process.cwd(),t.path),o=await tt(n);if(!o)return null;an(o.settingsReadWarnings);let r={commandPath:O(e),commandArgs:pa(e)};if(!Ze(o.discovery,r))return et(t.profile,o,r),null;let a=await re(n,r);return a?(ua(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function ga(e){let t=await re(e);return t?new Map(t.commandDescriptors):S}async function ha(e,t){return(await ho({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function ya(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return mo(e,_o.forActiveExtensionHost({pmRoot:e,author:n}))}async function wa(e,t,n,o=[]){let r=O(e),a=Ct(e.args.map(String),o),i={...t},s={...n},c=C(process.cwd(),n.path),l=await Ie({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&h(`profile:extensions parser_warnings=${P(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,Yr(S.get(y(r)),a,i,o),X(void 0),Te({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await st({command:r,args:a,options:i,global:s,pm_root:c,sdk:ya(c,s)});if(s.profile&&d.warnings.length>0&&h(`profile:extensions command_handler_warnings=${P(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),X(d.result),d.result}var $r=Symbol("pm.wrappedActionHandler");function pc(e,t){let n=e[e.length-1];return n instanceof sn?n:t}function Pr(e,t,n){e&&n.length>0&&h(`profile:extensions ${t}=${P(n)}`)}function uc(e){let t=S.get(y(e.commandPath));if(!t||!Kr(e.activeRegistrations,e.commandPath))return;let n=dn(t).length===0?Io(e.commandArgs):Ct(e.commandArgs,e.extensionFlagDefinitions);Jr(t,n)}function fc(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function xa(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[$r]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=pc(i,n),c=Date.now();gt(s);let l=pe(s),d=O(s),m=C(process.cwd(),l.path),p=s.args.map(String),u=W(),g=u?Xe(u,d,p):[],b=await Zr(d,m),x=ve(s,p,[...g,...b]),k=await Ie({command:d,args:p,options:x,global:l,pm_root:m});Pr(l.profile,"parser_warnings",k.warnings),p=k.context.args,x=k.context.options,l=k.context.global,uc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:g}),l=await wo(l),yo(s,l),fc(s,i,p),De(s,x),X(void 0),Te({command:d,args:p,options:{...x},global:{...l},pm_root:m});let $=await st({command:d,args:p,options:x,global:l,pm_root:m,sdk:ya(m,l)});if(Pr(l.profile,"command_handler_warnings",$.warnings),$.handled){X($.result),lt($.result,{...l,command:d,commandArgs:p,commandOptions:x,pmRoot:m}),l.profile&&h(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[$r]=!0}for(let r of n.commands)t(r)};t(e)}async function Ke(e){S=new Map,H({overrides:[]}),e&&await mn(e.rootProgram,e.pmRoot,e.invocationArgv,In(),e.settings)}function gc(e,t,n,o){if(t?.flags&&t.flags.length>0){Lt(e,t.flags);let r=Ut(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function _a(e,t){let n=U(t),o=C(process.cwd(),n.path);if(n.noExtensions){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await tt(o),a=Ae(t);if(!r){await Ke();return}if(!Ze(r.discovery,a)){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),et(pn(t),r,a);return}let i=await re(o,a);if(!i){await Ke({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}H(i.services),S=new Map(i.commandDescriptors),await mn(e,o,t,i.registrations,i.settings);let s=fr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>gr(i.activationWarnings,h,l)),c=l=>{let d=l.split(" ").filter(k=>k.length>0),m=i.commandDescriptors.get(l),p=ee(e,d),u=i.commandFlagHelp.get(l),g=m?mr(m):null;if(p){gc(p,m,u,g);return}let b=ur(e,d);m?.description&&b.description(m.description);let x=u;m&&(ar(b,m),m.flags.length>0&&(Lt(b,m.flags),x=Ut(b,m.flags)??void 0)),x&&b.addHelpText("after",x),g&&b.addHelpText("after",g),b.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...k)=>{let $=k[k.length-1],Y=$ instanceof sn?$:b,Re=pe(Y),ja=Date.now(),xn=Xe(i.registrations,l,Y.args.map(String)),_n=ve(Y,Y.args.map(String),xn),bn=await wa(Y,_n,Re,xn);await xo(Re,bn),lt(bn,{...Re,command:l,commandArgs:Y.args.map(String),commandOptions:_n,pmRoot:o}),Re.profile&&h(`profile:command=${l} took_ms=${Date.now()-ja}`)})};for(let l of s)c(l)}var Ce=En(import.meta.url,["../.."])??"0.0.0",w=bt(Ce);function ba(e){e.hook("preAction",async(t,n)=>{oe=null,I=null,Oe(),gt(n);let o=n.optsWithGlobals(),r=pe(n),a=O(n),i=n.args.map(String),s=ve(n,i),c={...r};Vn(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession}),await ao(a,c);let l=C(process.cwd(),r.path),d=await fa(n);if(!d){oe=Fn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),I=await ft({command:a,pm_version:Ce,args:i,options:s,global:c,pm_root:l}),mt(a,i,s,{source_context:I?.source_context,source_context_source:I?.source_context_source}),pt(a),await Ht(a,s,l,on()),await zt(a,i,s,c,l);return}Dn(d.hooks),Mn(d.commands),Ln(d.parsers),Un(d.preflight),H(d.services),jn(d.renderers),qn(d.registrations);let m=Xe(d.registrations,a,i);s=ve(n,i,m);let p=await Ie({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&h(`profile:extensions parser_warnings=${P(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,De(n,s);let u=await Gn({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:on()});c.profile&&u.warnings.length>0&&h(`profile:extensions preflight_warnings=${P(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,De(n,s);let g=u.decision;await Ht(a,s,d.pmRoot,g),await zt(a,i,s,c,d.pmRoot);let b=g.run_extension_migrations?await ha(d.registrations.migrations,d.pmRoot):[];c.profile&&b.length>0&&h(`profile:extensions migration_warnings=${P(b)}`);let x=wr(d.registrations.migrations);oe={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:x},X(void 0),Te({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),I=await ft({command:a,pm_version:Ce,args:i,options:s,global:c,pm_root:d.pmRoot}),mt(a,i,s,{source_context:I?.source_context,source_context_source:I?.source_context_source}),pt(a);let k=await $n(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&k.length>0&&h(`profile:extensions hook_warnings=${P(k)}`),g.enforce_mandatory_migration_gate&&xr(a,s,x)}),e.hook("postAction",async()=>{let t=Hr();le(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Ee(t)})}ba(w);var hc=new Set(["--version","-V"]),yc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),va=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),ka=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),wc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),xc=new Set(["claim","close-task","pause-task","release","start-task","test"]),Zt={setup:!0,listQuery:!0,mutation:!0,operation:!0},_c=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function nt(e){return e.some(t=>hc.has(t))}function Ca(e){if(nt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||F(e).requested)return Zt;let t=T(e);if(!t)return Zt;let n=t.trim().toLowerCase();return yc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:va.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:ka.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:wc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:Zt}function Ea(e){return e.length===0||F(e).requested}var Nr=Symbol("pmCliIdempotentTopLevelRegistration");function Sa(e){let t=e;if(t[Nr])return;t[Nr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new sn(a):n(o,...r)})}async function bc(e,t){if(Sa(e),t.setup){let{registerSetupCommands:n}=await Zs();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await ec(),o=typeof t.targetCommandName=="string"&&va.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await tc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await nc();n(e)}}function Aa(e,t){return nt(t)?!1:F(t).requested?!0:!!T(t)}function Ra(e){if(nt(e))return!1;let t=T(e);return t?_c.has(t):!1}function vc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=Fe(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function Ta(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=ka.has(t)||xc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=vc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:i,examples:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function kc(e){return async t=>{let n=ot(t.errorCode),o=dt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await so({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Ce,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Oa(e){if(e.bootstrapGlobal.noExtensions)return;let t=Ae(e.invocationArgv),n=await tt(e.bootstrapPmRoot);if(n&&Ze(n.discovery,t)){let o=await re(e.bootstrapPmRoot,t);Ia(o);return}n&&et(pn(e.invocationArgv),n,t),H({overrides:[]})}function Ia(e){if(!e){H({overrides:[]});return}H(e.services)}async function wn(e){le(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Ee({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function $a(){le(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Ee({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function Pa(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(xt(e.error)||!n))return!1;let o=B(e.error),r=e.error instanceof v?e.error.exitCode:wt(t),a=e.error instanceof v?e.error.context:void 0,i=Dr(a,e.invocationArgv,o),s=Ko(o,i),c=e.bootstrapGlobal.lean?ze(Ft(o,r,i)):Ft(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Kn(c,u=>`${JSON.stringify(u,null,2)}
28
+ `):c,null,2):Vo(o,i);h(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Ye({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:I?.source_context});return await wn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(ut(_t(e.error,o)),await de(cn)),process.exitCode=r,!0}async function Na(e,t){let n=Wt(e.invocationArgv),o=`unknown command '${n}'`,r=C(process.cwd(),e.bootstrapGlobal.path),a=await ga(r),i=Ae(e.invocationArgv),s=await Yt(r,{},Se(i)),c=await _e({message:o},w,a,{failedExtensions:s}),l=Dt(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:l.code,errorMessage:l.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await Ye({command:n,error_code:l.code,error_category:d,exit_code:f.USAGE,error_message:l.detail,command_resolution:m,resolution_stage:"parse",source_context:I?.source_context}),u=e.jsonErrors?await Jt({message:o},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await Kt({message:o},w,a,{failedExtensions:s}),g=Gt(u,e.jsonErrors,s);await wn({errorMessage:o,exitCode:f.USAGE,classificationCode:l.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),h(g),p&&await de(cn),process.exitCode=f.USAGE}async function Fa(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=F(e.invocationArgv);return r.requested&&!Er(w,r.commandPathTokens)?(await Na(e,t),!0):(await $a(),!0)}async function Da(e,t){let n=await _e(e.error,w,S),o=Dt(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:r,commandResolution:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),i=await Ye({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:f.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:I?.source_context}),s=e.jsonErrors?await Jt(e.error,w,S,e.bootstrapGlobal.lean===!0):await Kt(e.error,w,S),c=await Sr(o.code,e.bootstrapPmRoot,{},Se(Ae(e.invocationArgv))),l=Gt(s,e.jsonErrors,c);await wn({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:a,resolutionStage:"parse"}),h(l),i&&await de(cn),process.exitCode=f.USAGE}function Ma(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function La(e){let t=e.error.code,n=String(e.error.message??"");if(!await Fa(e,t,n)){if(t==="commander.version"){await $a();return}await Da(e,t)}}async function Ua(e){let t=U(e.invocationArgv),n=C(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:T(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:kc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Oa({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Pa(o,yt(e.error))){if(Ma(e.error)){await La(o);return}await Vr({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function zl(e=process.argv.slice(2)){w=bt(Ce),ba(w),be=null,J=null,S=new Map,zn();let t=Me(e),n=t.argv,o=[process.argv[0],process.argv[1],...n],r=n.length===0,a,i;try{let s=U(n);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});a=Co(s.author),Ta(t),i=vo(n);let c=Ca(n);if(await bc(w,c),Ea(n)&&Do(w,n),Aa(w,n)?await _a(w,n):(S=new Map,H({overrides:[]})),Ra(n)&&await ea(w,n),xa(w),await Rr(w,n,S))return;if(r){w.outputHelp();return}let m=await A(C(process.cwd(),s.path)),p=await Or(n,C(process.cwd(),s.path),s.noExtensions,re);await po({pmRoot:C(process.cwd(),s.path),packages:p?.contextIntentPackages},()=>Bn(m.agent_identity.harness_signals,()=>w.parseAsync(o),{probesEnabled:m.agent_identity?.probes_enabled}))}catch(s){await Ua({error:s,invocationArgv:n})}finally{i?.(),a?.()}}var Hl={activationCommandMatchesProbe:oa,bootstrapProfileEnabled:pn,buildBootstrapActivationProbe:Ae,buildPostActionTelemetryOutcome:Hr,buildPmCliRecoveryContext:Dr,buildRuntimeExtensionDiscoverySnapshotCacheKey:un,buildRuntimeExtensionActivationScope:yn,buildRuntimeExtensionSnapshotCacheKey:ta,buildRuntimeExtensionFilterForProbe:ma,addRuntimeFieldOption:nn,collectActivationCommandCandidates:Se,collectExtensionFlagDefinitionsForCommand:en,collectExtensionFlagDefinitionsForInvocation:Xe,collectLeadingCommandArgs:na,collectParsedActivationCommandArgs:pa,collectRuntimeFieldLooseFlagDefinitionsForCommand:Zr,commandHasLongOption:Xr,commandHasShortOption:Qr,commandPathNeedsSearchExtensions:ia,commandPathNeedsTemplateExtensions:gn,describeUnknownError:B,defaultPreflightDecision:on,discoveryNeedsActivationForProbe:Ze,emitExtensionProfile:ua,emitExtensionSkippedProfile:et,emitSettingsReadWarnings:an,ensureIdempotentTopLevelCommandRegistration:Sa,enforceExplicitRetryForFlagTypos:Ta,envFlagEnabled:Wr,executeRegisteredRuntimeMigrations:ha,extractCommandScopedOptions:ve,extensionActivationCommands:fn,extensionCapabilities:Qe,extensionNeedsActivationForProbe:hn,extensionProvidesTemplatesRuntime:ca,hasAnyCapability:ke,hasGlobalExtensionContributions:la,handleGenericRunPmCliError:Vr,handleRunPmCliCommanderError:La,handleRunPmCliError:Ua,handleRunPmCliHelpDisplayError:Fa,handleRunPmCliKnownError:Pa,handleRunPmCliCommanderUsageError:Da,handleUnknownHelpCommandError:Na,inferMissingFieldsFromErrorMessage:Fr,inferPostActionErrorCode:zr,inferPostActionFailureMessage:qr,invocationRequestsVersion:nt,isCommanderError:xt,loadRuntimeExtensionCommandDescriptorsForRecovery:ga,loadRuntimeExtensionDiscoverySnapshot:tt,loadRuntimeExtensionSnapshot:re,maybeLoadRuntimeExtensions:fa,maybeAttachCreateUpdatePolicyHelpText:mn,maybeLogHandledCliErrorToSentry:Ye,matchesStaticExtensionCommand:rn,normalizeTelemetryCommandResolution:Lr,normalizeTelemetryErrorCategory:jr,normalizeTelemetryResolutionStage:Ur,normalizeThrownExitCode:wt,probeUsesAnyFlag:sa,prepareExtensionServicesForRunPmCliError:Oa,readRecordBoolean:Mr,readRecordNumber:ln,readRecordString:ne,registerDynamicExtensionCommandPaths:_a,registerRuntimeSchemaFieldFlags:ea,resolveCoreCommandRegistrationSelection:Ca,resolveStaticExtensionActivationDecision:da,resolveUnknownHelpToken:Wt,readThrownExitCode:yt,runAndClearAfterCommandHooks:Ee,runRequiredExtensionCommand:wa,shouldAttachRichHelpTextForInvocation:Ea,shouldLogHandledErrorToSentry:Br,shouldRegisterDynamicExtensionPaths:Aa,shouldRegisterRuntimeSchemaFlags:Ra,shouldHandleRunPmCliCommanderError:Ma,setActiveExtensionHookContextForTest:Bs,setActiveRuntimeExtensionCommandDescriptorsForTest:Vs,setRecoveredExtensionServices:Ia,toLooseFieldDefinitionType:tn,isImporterOrExporterCommandPath:Kr,validateDynamicExtensionCommandInvocation:Yr,wrapProgramActionsForExtensionHandlers:xa,wrapThrownErrorForSentry:_t};export{Hl as _testOnly,zl as runPmCli};
29
29
  //# sourceMappingURL=main.js.map