@unbrained/pm-cli 2026.11.28 → 2026.11.29

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 (190) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +4 -4
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/linked-resource-value-list.js +2 -0
  5. package/dist/cli-bundle/bundle-manifest.json +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-YEMFOKFG.js → chunk-3AZOATC2.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-LMDIKSDZ.js → chunk-3E53F7QY.js} +8 -8
  8. package/dist/cli-bundle/chunks/{chunk-OFIYA3PI.js → chunk-3TK2YOVB.js} +3 -3
  9. package/dist/cli-bundle/chunks/{chunk-C4O5TZY3.js → chunk-3US5T6B2.js} +60 -60
  10. package/dist/cli-bundle/chunks/chunk-4EBHZBM2.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-MGJMQSN4.js → chunk-4QA5O64H.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-5EFS7K7Y.js +1 -0
  13. package/dist/cli-bundle/chunks/chunk-CNZOC6JD.js +2 -0
  14. package/dist/cli-bundle/chunks/{chunk-TWRUA2NH.js → chunk-CV2B4JUB.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-DBASKWBO.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-Q6BGQRCB.js → chunk-EYEQC3L2.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-O2SWNEBW.js → chunk-FRYNDVLN.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-GSLOAEY2.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-T7RZPIOB.js → chunk-JFPCL45G.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-CTM26LUE.js → chunk-JQHLOSSS.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-JV7LREUF.js +3 -0
  22. package/dist/cli-bundle/chunks/chunk-K3MVVDLN.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-6OIHST4I.js → chunk-K672XXGQ.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-T7UTG56V.js → chunk-KCR4NF2A.js} +3 -3
  25. package/dist/cli-bundle/chunks/chunk-L7HON3BE.js +23 -0
  26. package/dist/cli-bundle/chunks/chunk-LQEB6GSY.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-ZXERHBMA.js → chunk-NLHNB2L3.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-FG4TNQQM.js → chunk-NRCGGNOE.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-KHFUHGL3.js → chunk-OGVSGXQX.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-CATRDGAB.js → chunk-PY6A7ULK.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-O2WNNIKK.js → chunk-Q6GIFUCW.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-CDUV7DFD.js → chunk-R6M5OGJH.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-RWHS77ME.js +113 -0
  34. package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +2 -0
  35. package/dist/cli-bundle/chunks/chunk-TE6FBDHP.js +4 -0
  36. package/dist/cli-bundle/chunks/{chunk-LRGYV6QQ.js → chunk-VI3A7UZ2.js} +2 -2
  37. package/dist/cli-bundle/chunks/{chunk-E2LQ6LCJ.js → chunk-WLZ5KVM2.js} +2 -2
  38. package/dist/cli-bundle/chunks/chunk-WNB62BGK.js +10 -0
  39. package/dist/cli-bundle/chunks/chunk-X5D5YUHR.js +2 -0
  40. package/dist/cli-bundle/chunks/chunk-ZK4CY24V.js +2 -0
  41. package/dist/cli-bundle/chunks/{chunk-JQYPSABI.js → chunk-ZSBPE36C.js} +2 -2
  42. package/dist/cli-bundle/chunks/field-definition-losses-XKE4DRUA.js +2 -0
  43. package/dist/cli-bundle/chunks/{field-option-collisions-G4LQ2646.js → field-option-collisions-OZE43TOH.js} +2 -2
  44. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-H3MMNXXG.js → indexed-receipt-blobs-DR3FDHND.js} +2 -2
  45. package/dist/cli-bundle/chunks/{item-revision-O7L3AA2W.js → item-revision-3WXNNFLP.js} +2 -2
  46. package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +2 -0
  47. package/dist/cli-bundle/chunks/linked-resource-value-list-2655COY2.js +2 -0
  48. package/dist/cli-bundle/chunks/{mutation-actor-A45DFDEO.js → mutation-actor-QOKPDYM4.js} +2 -2
  49. package/dist/cli-bundle/chunks/mutation-admission-JNJHB3E6.js +2 -0
  50. package/dist/cli-bundle/chunks/{register-list-query-FCPGG2UT.js → register-list-query-YGVUE4YZ.js} +2 -2
  51. package/dist/cli-bundle/chunks/{register-mutation-VD3JX23I.js → register-mutation-3JVZQDHH.js} +2 -2
  52. package/dist/cli-bundle/chunks/register-operations-LCHUHKRA.js +2 -0
  53. package/dist/cli-bundle/chunks/{register-setup-EWAZZWPL.js → register-setup-IJ7M3VUK.js} +2 -2
  54. package/dist/cli-bundle/chunks/runtime-schema-OAIUNQRL.js +2 -0
  55. package/dist/cli-bundle/chunks/{settlement-hook-KWBOSRDZ.js → settlement-hook-BIVNGBZF.js} +2 -2
  56. package/dist/cli-bundle/chunks/{stage-UIDZMTE5.js → stage-7BD7U2BX.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/chunk-26P6C6OO.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-2CQFGJQ6.js +8 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-42SU4LK3.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/{chunk-7P6OGPEG.js → chunk-5NSWNLFE.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-Y7EC2L2G.js → chunk-ACTBMSCH.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-BPBKHY6H.js +100 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-YC3PFFDE.js → chunk-BPOU2S44.js} +57 -57
  64. package/dist/cli-bundle/focused-chunks/chunk-BZ3PUUPG.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/{chunk-AHCOSTL7.js → chunk-CWQLW4ZO.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{chunk-7EKKUYN5.js → chunk-EUDAUT6T.js} +3 -3
  67. package/dist/cli-bundle/focused-chunks/chunk-GTUPHXKR.js +2 -0
  68. package/dist/cli-bundle/focused-chunks/{chunk-NGFDPEP7.js → chunk-IRYNVGKH.js} +3 -3
  69. package/dist/cli-bundle/focused-chunks/chunk-JFICNN4T.js +4 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-J4V3J5MC.js → chunk-KLOHZNJ4.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/chunk-KPASZGBL.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/{chunk-Q6JCMFGU.js → chunk-KWKPX36T.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-ZYHGQIQ7.js → chunk-LKTRICZR.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-OEMI52ZS.js → chunk-LSVRZ4KQ.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/chunk-MYWUMVCZ.js +4 -0
  76. package/dist/cli-bundle/focused-chunks/{chunk-CQLOYNJY.js → chunk-NNLENKU7.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/chunk-NO5MUY4I.js +2 -0
  78. package/dist/cli-bundle/focused-chunks/{chunk-XVCMYFQU.js → chunk-NZA2LP4Y.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{chunk-HCWDMFWA.js → chunk-PPCBCPIZ.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/chunk-QTV6UE2Q.js +44 -0
  81. package/dist/cli-bundle/focused-chunks/{chunk-VNU3IFBL.js → chunk-S4AC7OMI.js} +2 -2
  82. package/dist/cli-bundle/focused-chunks/{chunk-YX75PQFO.js → chunk-S5VG7RFY.js} +2 -2
  83. package/dist/cli-bundle/focused-chunks/{chunk-JD45Y2BR.js → chunk-TSZVCALS.js} +2 -2
  84. package/dist/cli-bundle/focused-chunks/{chunk-O33WUEAF.js → chunk-TX24L7RQ.js} +2 -2
  85. package/dist/cli-bundle/focused-chunks/chunk-WJAUHPXD.js +2 -0
  86. package/dist/cli-bundle/focused-chunks/{chunk-4SX2BN4V.js → chunk-XR6MLUVW.js} +2 -2
  87. package/dist/cli-bundle/focused-chunks/field-definition-losses-GGA6FUHD.js +2 -0
  88. package/dist/cli-bundle/focused-chunks/{field-option-collisions-63YQ2J3N.js → field-option-collisions-HABQYZMQ.js} +2 -2
  89. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-PG2VJ3MB.js → indexed-receipt-blobs-EUYZJR5R.js} +2 -2
  90. package/dist/cli-bundle/focused-chunks/{item-revision-PV5O6F5Y.js → item-revision-YH5R7YPW.js} +2 -2
  91. package/dist/cli-bundle/focused-chunks/item-transaction-YZ2PUPGM.js +2 -0
  92. package/dist/cli-bundle/focused-chunks/{mutation-actor-2AAUJG2Z.js → mutation-actor-DJ2VRLKG.js} +2 -2
  93. package/dist/cli-bundle/focused-chunks/mutation-admission-3SECKVKY.js +2 -0
  94. package/dist/cli-bundle/focused-chunks/runtime-schema-IDRXWCC4.js +2 -0
  95. package/dist/cli-bundle/focused-chunks/{settlement-hook-4MGRERCT.js → settlement-hook-Q6MJQKIE.js} +2 -2
  96. package/dist/cli-bundle/focused-chunks/{stage-56RYPMBK.js → stage-FEJT2UCG.js} +2 -2
  97. package/dist/cli-bundle/main.js +26 -26
  98. package/dist/cli-bundle/sdk-authoring.js +1 -1
  99. package/dist/cli-bundle/sdk-contracts.js +1 -1
  100. package/dist/cli-bundle/sdk-core.js +1 -1
  101. package/dist/cli-bundle/sdk-governance.js +1 -1
  102. package/dist/cli-bundle/sdk-graph.js +1 -1
  103. package/dist/cli-bundle/sdk-merge.js +63 -63
  104. package/dist/cli-bundle/sdk-query.js +1 -1
  105. package/dist/cli-bundle/sdk-runtime.js +1 -1
  106. package/dist/cli-bundle/sdk-testing.js +1 -1
  107. package/dist/cli-bundle/sdk.js +1 -1
  108. package/dist/core/extensions/item-fields.d.ts +18 -1
  109. package/dist/core/extensions/item-fields.js +1 -1
  110. package/dist/core/extensions/loader.js +1 -1
  111. package/dist/core/fs/fs-utils.d.ts +8 -0
  112. package/dist/core/fs/fs-utils.js +2 -2
  113. package/dist/core/item/item-type-inspection.js +2 -0
  114. package/dist/core/item/type-registry.js +1 -1
  115. package/dist/core/schema/runtime-schema.d.ts +19 -0
  116. package/dist/core/schema/runtime-schema.js +2 -2
  117. package/dist/core/store/settings.d.ts +7 -0
  118. package/dist/core/store/settings.js +5 -5
  119. package/dist/sdk/extension-command-context.js +2 -2
  120. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  121. package/dist/sdk/governance/validate.js +1 -1
  122. package/dist/sdk/public-surface.json +1 -1
  123. package/dist/sdk/runtime/schema.js +1 -1
  124. package/dist/sdk/schema/field-definition-losses.js +1 -1
  125. package/dist/sdk/schema/schema-file-entry-losses.js +2 -0
  126. package/dist/sdk/test/execution.d.ts +9 -1
  127. package/dist/sdk/test/execution.js +4 -4
  128. package/docs/COMMANDS.md +3 -1
  129. package/docs/CONFIGURATION.md +1 -1
  130. package/docs/EXTENSIONS.md +1 -1
  131. package/docs/SDK_AUDITED_MUTATIONS.md +9 -0
  132. package/marketplace.json +1 -1
  133. package/node_modules/fast-json-patch/README.md +2 -2
  134. package/node_modules/fast-json-patch/dist/fast-json-patch.js +604 -818
  135. package/node_modules/fast-json-patch/dist/fast-json-patch.min.js +4 -8
  136. package/node_modules/fast-json-patch/package.json +14 -17
  137. package/package.json +2 -2
  138. package/packages/pm-beads/package.json +1 -1
  139. package/packages/pm-calendar/package.json +1 -1
  140. package/packages/pm-command-kit/package.json +1 -1
  141. package/packages/pm-digital-twin/package.json +1 -1
  142. package/packages/pm-governance-audit/package.json +1 -1
  143. package/packages/pm-guide-shell/package.json +1 -1
  144. package/packages/pm-kanban/package.json +1 -1
  145. package/packages/pm-lifecycle-hooks/package.json +1 -1
  146. package/packages/pm-linked-test-adapters/package.json +1 -1
  147. package/packages/pm-search-advanced/package.json +1 -1
  148. package/packages/pm-templates/package.json +1 -1
  149. package/packages/pm-todos/package.json +1 -1
  150. package/packages/pm-vcs/package.json +1 -1
  151. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  152. package/plugins/pm-claude/package.json +1 -1
  153. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  154. package/plugins/pm-codex/package.json +1 -1
  155. package/plugins/pm-codex/plugin.json +1 -1
  156. package/runtime-dependencies.json +1 -1
  157. package/dist/cli-bundle/chunks/chunk-2YD2AERA.js +0 -2
  158. package/dist/cli-bundle/chunks/chunk-54AQJTUH.js +0 -3
  159. package/dist/cli-bundle/chunks/chunk-56DKWGHE.js +0 -2
  160. package/dist/cli-bundle/chunks/chunk-56GUDMXN.js +0 -113
  161. package/dist/cli-bundle/chunks/chunk-5ECCMDSU.js +0 -2
  162. package/dist/cli-bundle/chunks/chunk-6RBD2AKU.js +0 -2
  163. package/dist/cli-bundle/chunks/chunk-D3I5AHNN.js +0 -2
  164. package/dist/cli-bundle/chunks/chunk-MO6PPUI6.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-RGE3XW3A.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-SP6CDM6B.js +0 -31
  167. package/dist/cli-bundle/chunks/chunk-WKDKBS4P.js +0 -4
  168. package/dist/cli-bundle/chunks/chunk-YLS2N4SN.js +0 -2
  169. package/dist/cli-bundle/chunks/field-definition-losses-JFMMMVTV.js +0 -2
  170. package/dist/cli-bundle/chunks/item-transaction-4XC74ULD.js +0 -2
  171. package/dist/cli-bundle/chunks/mutation-admission-SIUIMAEO.js +0 -2
  172. package/dist/cli-bundle/chunks/register-operations-KHJD4GFZ.js +0 -2
  173. package/dist/cli-bundle/chunks/runtime-schema-3RAXYNG5.js +0 -2
  174. package/dist/cli-bundle/focused-chunks/chunk-5MZXU6HB.js +0 -2
  175. package/dist/cli-bundle/focused-chunks/chunk-64DSKZJN.js +0 -100
  176. package/dist/cli-bundle/focused-chunks/chunk-A5B43EWU.js +0 -2
  177. package/dist/cli-bundle/focused-chunks/chunk-E4C6T3NL.js +0 -2
  178. package/dist/cli-bundle/focused-chunks/chunk-KMGI5GZP.js +0 -2
  179. package/dist/cli-bundle/focused-chunks/chunk-MSLRDKWL.js +0 -4
  180. package/dist/cli-bundle/focused-chunks/chunk-RBOWKXFV.js +0 -8
  181. package/dist/cli-bundle/focused-chunks/chunk-TF57RHS2.js +0 -2
  182. package/dist/cli-bundle/focused-chunks/chunk-X5ZVPFK7.js +0 -4
  183. package/dist/cli-bundle/focused-chunks/chunk-Z4FWJGQG.js +0 -2
  184. package/dist/cli-bundle/focused-chunks/chunk-ZHHFOQSL.js +0 -44
  185. package/dist/cli-bundle/focused-chunks/chunk-ZUAPUBJK.js +0 -2
  186. package/dist/cli-bundle/focused-chunks/field-definition-losses-NUZO3JCP.js +0 -2
  187. package/dist/cli-bundle/focused-chunks/item-transaction-S5QXBGAT.js +0 -2
  188. package/dist/cli-bundle/focused-chunks/mutation-admission-X7HHNERR.js +0 -2
  189. package/dist/cli-bundle/focused-chunks/runtime-schema-5J2ONRNV.js +0 -2
  190. package/node_modules/fast-json-patch/webpack.config.js +0 -63
@@ -1,15 +1,15 @@
1
- import{a as Sa}from"./chunks/chunk-HZZLSBIJ.js";import"./chunks/chunk-SLFRSZK6.js";import{A as va,B as Ca,C as Wn,E as xa,F as ba,H as ka,I as Bn,a as jn,d as N,e as j,f as $,g as S,h as E,i as Br,n as pe,o as Tt,p as Vr,q as Jr,r as Qr,v as ea,w as ha,x as ya,y as _a,z as wa}from"./chunks/chunk-2YD2AERA.js";import{Wa as ga,f as Gr,k as zr}from"./chunks/chunk-C4O5TZY3.js";import"./chunks/chunk-O2WNNIKK.js";import{A as aa,B as sa,C as Nt,F as ca,G as la,H as Q,I as da,Qc as pa,Rd as fa,b as Te,ca as ma,l as Zr,q as Hn,r as Gn,s as oa,t as ia,u as ra,v as zn,w as $t,x as Qe}from"./chunks/chunk-SP6CDM6B.js";import"./chunks/chunk-T7UTG56V.js";import"./chunks/chunk-MO6PPUI6.js";import"./chunks/chunk-6H36ZHMI.js";import"./chunks/chunk-MGJMQSN4.js";import"./chunks/chunk-LRGYV6QQ.js";import"./chunks/chunk-TWRUA2NH.js";import{k as Wr}from"./chunks/chunk-T7RZPIOB.js";import{d as ua}from"./chunks/chunk-CTM26LUE.js";import"./chunks/chunk-OFIYA3PI.js";import"./chunks/chunk-KHFUHGL3.js";import"./chunks/chunk-AA52P34H.js";import{Ka as na,a as Kr,b as Yr,d as Xr,ma as It,na as Pt,oa as Un,pa as Ze,qa as A,ra as ta,sa as qn,wa as W}from"./chunks/chunk-CDUV7DFD.js";import{A as Ur,B as qr,C as Dn,D as Hr,n as Mn,p as Dr,u as Fn,w as jr}from"./chunks/chunk-56DKWGHE.js";import"./chunks/chunk-E2LQ6LCJ.js";import"./chunks/chunk-PZA7QECY.js";import{Ac as Nn,Bc as Ir,Cc as Oe,Fc as Pr,Jc as $r,K as Ni,Xb as An,bc as Cr,ec as xr,fc as br,hc as kr,id as Ye,lc as Sr,ld as Nr,mb as kt,mc as Er,nb as vr,nc as Rn,pc as Ar,qc as me,rc as On,rd as Lr,sc as Tn,tc as In,uc as Pn,vc as St,wc as $n,wd as Ln,xc as Rr,xd as Mr,yc as Or,yd as Fr,zc as Tr}from"./chunks/chunk-CATRDGAB.js";import{l as bt,o as yr,p as _r,s as Re,t as F,u as wr}from"./chunks/chunk-LMDIKSDZ.js";import"./chunks/chunk-YEMFOKFG.js";import{$g as Sn,Ge as Z,Ib as wt,Ig as ar,Jd as Ui,Jg as Je,Kd as qi,Lg as Ke,Md as Hi,Mg as sr,Nd as Gi,Od as zi,Pd as Wi,Pe as Yi,Q as Ee,Qd as Bi,Qe as ie,R as We,Rd as Vi,Rf as tr,Sf as nr,T as Be,Ue as kn,Ve as x,Vg as cr,Wg as lr,X as Ve,Xg as dr,Yg as mr,Zg as re,_g as ur,ah as le,ba as gn,bh as pr,ch as vt,fg as or,fh as Ae,ga as _t,gh as de,ja as hn,jh as fr,kh as Ct,ld as _n,md as wn,nd as Di,od as ji,pe as Ji,pf as Xi,qd as vn,qf as Zi,r as ze,rd as Cn,rf as Qi,sd as xn,sf as er,te as Ki,tg as ir,th as En,ud as bn,uh as xt,vg as rr,vh as gr,wh as hr,xb as Mi,yb as Fi}from"./chunks/chunk-56GUDMXN.js";import{e as mn,h as ce,j as Oi,k as yt,n as un,o as Ti,p as P,r as Ii,s as X}from"./chunks/chunk-D3I5AHNN.js";import"./chunks/chunk-5ECCMDSU.js";import{E as Rt,F as ue,mb as Ot,nb as G,p as Et,r as Xe,s as At}from"./chunks/chunk-FG4TNQQM.js";import{G as Pi,H as $i,I as J,Z as Li,h as M,j as V,k as H,m as K,n as dn,o as D,p as Ai,x as _,y as pn,z as fn}from"./chunks/chunk-54AQJTUH.js";import{Y as yn,a as Ri}from"./chunks/chunk-WKDKBS4P.js";import{A as g,B as ht,C as I,E as Y}from"./chunks/chunk-6OIHST4I.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as Jc}from"node:async_hooks";var Ie=new Jc;function Ea(e){let t=Ie.getStore();return t===void 0?e:t!==null}function fe(e,t=`warning:${e}`){let n=Ie.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):x(t)}function et(e){let t=Ie.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([a,s])=>s!==`warning:${a}`).map(([a,s])=>({code:a,message:s})),i=Reflect.get(e,"warning_details"),r={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),r}function Vn(e){if(!Ie.getStore()?.size)return e;let{token_accounting:t,...n}=et(JSON.parse(e));return JSON.stringify(t===void 0?n:Z(n,o=>`${JSON.stringify(o,null,2)}
2
- `),null,2)}async function Aa(e,t){if(!e){await Ie.run(null,t);return}let n=new Map;await Ie.run(n,async()=>{await t(),n.size>0&&ie(`${JSON.stringify(et({type:"warning"}))}
3
- `)})}import{AsyncLocalStorage as Kc}from"node:async_hooks";var Jn=new Kc,Ra=new WeakMap;function Yc(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:Ee(e),outputArgs:t}}var Oa=new WeakMap;function Xc(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function Kn(e,t){return t.some(n=>n.path!==e.path||n.args.length!==e.args.length||n.args.some((o,i)=>o!==e.args[i]))}async function Yn(e){if(e.expectHash===void 0)return;let t=Mn(e.expectHash),n=e.commandPath.trim().toLowerCase();if(Dn(n,e.commandOptions),e.rewritten===!0)throw Fn();let o=Jn.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await Dr(e.pmRoot,t,Xc(e.command,e.commandArgs));Qi(o,e.pmRoot,i),Oa.set(o,n),e.globalOptions!==void 0&&Ra.set(o,Yc(e.globalOptions))}function Xn(e,t,n){let o=Jn.getStore(),i=o===void 0?void 0:Oa.get(o);if(i!==void 0){if(Kn(e,[t]))throw Fn();Dn(i,n)}}function Ta(e,t){if(t!==void 0)throw Mn(t),Hr(e)}function Zc(e){for(let t of er(e).unchecked)fe(qr(t))}async function Qc(e,t){return e.pmRoot===void 0?t:jr(t,e.pmRoot,Ra.get(e))}async function Ia(e){let t=Xi();try{await e(n=>Jn.run(t,()=>Zi(t,n)))}catch(n){throw await Qc(t,n)}Zc(t)}import{Command as hi,CommanderError as gc}from"commander";function B(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ge(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return B(t)}function ee(e){let t=new Set,n=[];for(let o of e){let i=ge(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}var Zn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Lt=new Set(["--full","--brief","--compact"]);function el(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function Qn(e,t=E([...e])){let n=G(t),o=new Set([...Kr,...Yr,...Xr].flatMap(s=>s.keys.map(c=>`--${c.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),i=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,s.flag]))),r=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,el(s,o)])));for(let s of Zn)r.set(s,!0);for(let s of Lt)r.set(s,!1);let a=new Map;for(let s=0;s<e.length;s+=1){let c=e[s];if(c==="--")break;if(!c.startsWith("-"))continue;let l=c.split("=")[0];if(!r.has(l)&&!c.includes("="))return;let d=r.get(l)===!0&&!c.includes("=");a.set(s,{flag:i.get(l)??l,consumesValue:d}),d&&(s+=1)}return a}function tl(e){let t=Qn(e);return t===void 0?void 0:new Map([...t].map(([n,{flag:o}])=>[n,o]))}function Pa(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),Zn.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function nl(e,t){let n=t.find(i=>Lt.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Lt.has(i));return o.length===1?o[0]:n}function $a(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let r=tl(e);if(!r)return i;let a;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let c=[...r].find(([l,d])=>d==="--fields")?.[0]??-1;if(c<0)return i;a=Pa(e,r,new Set(["--fields"])),a.splice(c,0,"--fields",o[s+1])}else{let s=nl(r,o);if(s===void 0||![...r.values()].includes(s))return i;let c=new Set([...Zn,...Lt].filter(l=>l!==s));a=Pa(e,r,c)}return{...n,suggested_retry:_(a),suggested_retry_args:a}}var Na=new Set(Gi);function ol(e){return e.includes("@")&&e.includes(":")}function il(e){let t=S([...e]);if(t===void 0)return;let n=e[t+1],o=n===void 0||n.startsWith("-")?void 0:`${e[t]} ${n}`;return o!==void 0&&Ot(o)?o:e[t]}function rl(e){let t=Te(e??"",G(e));return new Set(t.filter(n=>n.takes_value).flatMap(n=>[n.flag,...n.aliases??[]]))}function La(e,t,n,o=[],i=()=>!1){if(t!==Hi)return n;let r=n===void 0?void 0:{...n,suggested_retry:void 0,suggested_retry_args:void 0},a=il(e),s=Qn(e,a);if(s===void 0||o===null||e.some(ol)||i())return r;let c=al(e,s,rl(a));if(c===void 0||c.size===0)return r;let l=[...o,...e.filter((d,m)=>!c.has(m))];return{...n,suggested_retry:_(l),suggested_retry_args:l}}function al(e,t,n){let o=new Set;for(let[r,{flag:a,consumesValue:s}]of t){if(!Na.has(a))continue;let c=e[r-1];if(c!==void 0&&!c.includes("=")&&n.has(c)||s&&e[r+1]?.startsWith("-")===!0)return;o.add(r),s&&o.add(r+1)}return e.some((r,a)=>!o.has(a)&&Na.has(r.split("=",1)[0]))?void 0:o}var sl=new Set(["normalized_args","suggested_retry_args","provided_fields","parsed_positionals","normalizedInvocationArgs","providedOptionFlags","suggestedRetryArgs"]),cl=new Set(["code","original_code","type","recovery_mode","option_scope","diagnostic_class"]),Ma=`URL credentials in this invocation were replaced with ${pn}; restore them before replaying any command shown here.`;function ll(e){return`URL credentials in this invocation were replaced with ${pn}. Those in ${e} caused this refusal, so do not restore them: give ${e} a value without URL credentials, and restore any other redacted credentials before replaying.`}function he(e){return e.map(fn)}function dl(e,t){return e==="producer"||t==="details"?"producer":e==="schema"&&t==="recovery"?"schema":"typed"}function ml(e,t,n){let o=J(e);o!==e&&(n.changed=!0);let i=o;for(let r=2;Object.hasOwn(t,i);r+=1)i=`${o} (${r})`;return i}function ul(e,t,n){let o=J(n?fn(e):e);return o!==e&&(t.changed=!0),o}function pl(e,t,n){return e!=="schema"?!1:t==="urlCredentialsRejected"||cl.has(t)&&typeof n=="string"}function eo(e,t,n,o){if(typeof e=="string"&&t.ownSteps.has(e))return e;if(typeof e=="string")return ul(e,t,n);if(typeof e!="object"||e===null)return e;let i=t.copies.get(e);if(i!==void 0)return i;if(Array.isArray(e)){let a=[];t.copies.set(e,a);for(let s of e)a.push(eo(s,t,n,o));return a}let r={};t.copies.set(e,r);for(let[a,s]of Object.entries(e)){if(pl(o,a,s)){r[a]=s;continue}let c=o==="producer"?ml(a,r,t):a;r[c]=eo(s,t,n||sl.has(a),dl(o,a))}return r}function Mt(e){let t=e.urlCredentialsRejected,n=t===void 0?Ma:ll(t.source),o=new Set([Ma,n]),i={copies:new Map,changed:!1,ownSteps:o},r=eo(e,i,!1,"schema");if(!i.changed&&!$i())return e;r.recovery&&(r.recovery={...r.recovery,suggested_retry:void 0,suggested_retry_args:void 0});let a=(r.nextSteps??[]).filter(s=>!o.has(s));return r.nextSteps=[n,...a],r}var fl="project_schema_field_requires_declared_flag";function gl(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function Fa(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==fl||n===void 0||i===void 0)return o;let r=gl(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(r.length!==1)return o;let[a]=r,s=a.assignment.trim(),c=s.slice(s.indexOf("=")+1),l=[...e.slice(0,a.index),i,c,...e.slice(a.index+a.width)];return{...o,suggested_retry:_(l),suggested_retry_args:l}}var to=Zr;function hl(e,t,n,o,i){let r=[],a=e.indexOf(n,t);if(a<0||e.slice(t,a).some(s=>s.startsWith("-")))return r;for(let s=a+1;s<e.length;s+=1){let c=e[s];if(c==="--")break;c===`${o}=${i}`?r.push({index:s,width:1}):c===o&&e[s+1]===i&&(r.push({index:s,width:2}),s+=1)}return r}function Da(e,t,n,o,i=[]){let r=o?.suggested_flags?.[0];if(t!==to||n===void 0||r===void 0||o.suggested_retry_args===void 0)return o;let a={...o,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||i===null)return a;let c=o.suggested_retry_args,l=hl(e,s,c[0],n,r);if(l.length!==1)return a;let{index:d,width:m}=l[0],u=[...e.slice(0,d),r,...e.slice(d+m)];if(!yl(u,d,n,r,c))return a;let p=[...i,...u];return{...o,suggested_retry:_(p),suggested_retry_args:p}}function yl(e,t,n,o,i){let r=i.lastIndexOf(o);return r<0||i.slice(r).some((a,s)=>e[t+s]!==a)?!1:!e.some((a,s)=>s!==t&&(a===n||a.startsWith(`${n}=`)))}var no="close_validation_missing_fields";function _l(e,t,n,o){let i=e.slice(t+1);if(!i.includes("--"))return[...e,...o];if(!i.some(r=>n.has(r.split("=",1)[0])))return[...e.slice(0,t+1),...o,...i]}function wl(e,t){let n=e.slice(0,e.length-2*t),o=n.length;for(;o>0&&n[o-1].startsWith("--expect-hash=");)o-=1;return n.slice(o)}function ja(e,t,n,o=[]){let i=n?.missing;if(t!==no||i===void 0||i.length===0)return n;let r=n.suggested_retry_args;if(r===void 0)return n;let a={...n,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||o===null)return a;let c=G(e[s].trim().toLowerCase()),l=i.map(f=>c.find(y=>y.flag===f||y.aliases?.includes(f)===!0));if(l.some(f=>f===void 0))return a;let d=new Set(l.flatMap(f=>[f.flag,...f.aliases??[]])),m=wl(r,i.length),u=_l(e,s,d,[...i.flatMap(f=>[f,"<value>"]),...m]);if(u===void 0)return a;let p=[...o,...u];return{...n,suggested_retry:_(p),suggested_retry_args:p}}async function Ua(e,t){await Mr(e,{ok:t.ok,error:t.error,result:de(),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 qa(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Ji({pmRoot:e.pmRoot,result:de()})}catch(o){t=o}let n=await F(e.pmRoot);if(await Ki({pmRoot:e.pmRoot,author:wt(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}var Ha=new WeakMap;function Ft(e,t){Ha.set(e,t)}function ye(e){return Ha.get(e)}function Ga(e){return e.length>0?[e[0]]:[]}function vl(e){let t=["","Intent:",` ${e.why}`],n=Ga(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(`
4
- `)}function Cl(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(`
5
- `)}function za(e,t){return t==="detailed"?Cl(e):vl(e)}function U(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var xl={cal:"calendar",ctx:"context"};function bl(e,t){return e.commands.find(n=>n.name()===t)??null}function kl(e,t){let n=e;for(let o of t){let i=bl(n,o);if(!i)return null;n=i}return n}function oo(e,t,n,o){let i=kl(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",za(n,o))}function io(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var _e={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},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 package install ./my-package --project","pm package 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 package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package 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 package 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 package 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 package 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 package 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 catalog --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","pm package list shows the packages installed in the selected scope; catalog shows what pm bundles.","External npm package discovery still belongs to npm search."]},"package inventory":{why:"Lists the packages installed in the selected scope (alias: pm package list) from manifests and saved state, without activating extension code, with the newer version the last pm package manage check observed.",examples:["pm package list","pm package list --global --fields name,version,update","pm package list pm-changelog"],tips:["update is null until pm package manage has checked the registry for that installed version; manage is the live check.","Use pm package catalog for the bundled first-party packages and pm package describe to map what a package registers."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --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 package install ./my-extension --project","pm package --install --project ./my-extension","pm package 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 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 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 inventory":{why:"Compatibility view of the installed package inventory (alias: pm extension list); it reads manifests and saved state without activating extension code.",examples:["pm package list","pm package list --global --fields name,version,update"],tips:["Prefer pm package list in new user-facing workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package 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 package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package 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 package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package 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.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},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 --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status 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 --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status 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 package 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?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",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:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","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 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','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 --start",'pm claim pm-a1b2 --takeover-stale --message "Take over an abandoned claim"','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 is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","The refusal reports the holder's claim age, last activity and idle hours. --takeover-stale takes over only a claim idle for at least mutation_guard.stale_in_progress_hours (default 72), refuses an active one with stale_claim_takeover_refused, and records the previous holder and idle time in the claim's history entry.","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 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment 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."]}};for(let{alias:e,canonical:t}of M){let n=_e[e];n&&(_e[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Pe={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status 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."]},Wa=K.filter(e=>e.lifecycle==="deprecated");for(let e of Wa){let t=_e[e.alias];_e[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Pe,...Object.values(_e)])e.examples=e.examples.map(t=>{for(let n of Wa){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Sl(e){let t=U(e??"");return t?xl[t]??t:""}function ro(e){let t=Sl(e);return t?_e[t]??Pe:Pe}function Ba(e,t){let n=ro(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Ga(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function El(){let e=K.filter(({lifecycle:n})=>n==="permanent"),t=K.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${Ai(n)})`)].join(`
6
- `)}function Al(e,t,n,o){let i=new Set(ca);e.configureHelp({visibleCommands(a){let s=t.visibleCommands(a);return n?s.filter(c=>(ye(c)??Q(c.name()))!=="internal"):a!==e?s:s.filter(c=>o.has(c))},visibleOptions(a){let s=t.visibleOptions(a);return a!==e||n?s:s.filter(c=>i.has(c.flags))}});let r=e.options.filter(a=>a.long==="--output-cursor");for(let a of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(a.name())&&a.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...r]})}function Rl(e,t,n,o){let i=new Set(da("core")),r=e.createHelp();r.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${r.formatHelp(e,r)}${o}
7
- `,s=t.visibleCommands(e);for(let c of s)ye(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)ye(c)==="core"&&(n.add(c),la(a()).within_budget||n.delete(c))}function Va(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ae(t),i=new Set;Al(e,n,o,i);let r=io(t),a=za(Pe,r);e.addHelpText("after",a),o&&e.addHelpText("after",El()),Rl(e,n,i,a);for(let[d,m]of Object.entries(_e))oo(e,d,m,r);let s=U($(t).commandPathTokens.join(" ")),c=Xe(s);if(c){oo(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,At(c.accepted_flags)]},r);return}let l=Et.filter(({parent:d})=>d===s);l.length>0&&oo(e,s,{why:`Dispatches one declared positional action: ${l.map(({action:d})=>d).join("|")}.`,examples:l.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},r)}function ao(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of M){if(t&&!M.some(l=>l.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(l=>l.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let l of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===l)??s.command(l).description(`Discover ${l} operations.`);let c=i[i.length-1];if(s.commands.some(l=>l.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(c),Ft(a,Q(o)),s.enablePositionalOptions(),s.addCommand(a)}}function jt(e){let{title:t,...n}=e;Cn(n.why)&&delete n.why,vn(n.required)&&delete n.required;let o=xn(n.examples);o.length>0?n.examples=o:delete n.examples;let i=bn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var Ol=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Tl(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Ol.has(e.code)}function ts(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:ts(e.code)}}var $e={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Ja={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ka={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Dt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Il={guide:$e,shell:$e,completion:$e,"completion-statuses":$e,"completion-tags":$e,"completion-types":$e,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Ja,cal:Ja,reindex:Ka,"search-advanced":Ka,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Dt,"dedupe-audit":Dt,"dedupe-merge":Dt,normalize:Dt};function Pl(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Il[t]}function lo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function $l(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 Nl(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 so(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function ns(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function te(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"||t==="allowed_values"){let i=ns(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(r=>({role:typeof r?.role=="string"?r.role.trim():"",value:typeof r?.value=="string"?r.value.trim():""})).filter(r=>r.role.length>0&&r.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=$l(n);o&&(e[t]=o)}function Ll(e,t){if(!kr(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}}var os=["retry_after_ms","waited_ms","owner_handoffs"];function Ml(e,t){for(let n of os)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function Fl(e,t){for(let n of os){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function Ce(e){if(!e||typeof e!="object")return;let t={};Ll(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),so(t,"attempted_command",e.attempted_command),te(t,"normalized_args",e.normalized_args),te(t,"parsed_positionals",e.parsed_positionals),te(t,"provided_fields",e.provided_fields),te(t,"missing",e.missing),te(t,"missing_required_fields",e.missing_required_fields),te(t,"suggested_flags",e.suggested_flags),te(t,"allowed_values",e.allowed_values),te(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),so(t,"suggested_retry",e.suggested_retry),te(t,"suggested_retry_args",e.suggested_retry_args),Fl(t,e);let n=Nl(e.fallback_candidates);return n&&(t.fallback_candidates=n),so(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function co(e,t,n){n&&e.push(` ${t}: ${n}`)}function we(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}var mo=8,Dl=12,is=Number.POSITIVE_INFINITY;function jl(e,t,n){let o=t!==void 0&&n===is&&t.length<=Dl?t.length:Math.min(n,mo),i=t?.slice(0,o).map(r=>/^[\p{L}\p{N}._:/@=-]+$/u.test(r)?r:JSON.stringify(r));we(e,"allowed_values",i,", "),t&&t.length>o&&e.push(` allowed_values_omitted: ${t.length-o} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function Ul(e,t){let n=Ce(e);if(!n)return[];let o=["Recovery bundle:"];if(n.token_budget){let i=n.token_budget;o.push(` requested_token_budget: ${i.requested_tokens}`,` feasible_token_budget: ${i.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${i.minimum_feasible_tokens??"not established"}`)}if(co(o,"suggested_retry",n.suggested_retry),co(o,"attempted_command",n.attempted_command),we(o,"normalized_args",n.attempted_command?void 0:n.normalized_args," "),n.parsed_positionals&&n.parsed_positionals.length>0){o.push(" parsed_positionals:");for(let i of n.parsed_positionals)o.push(` - ${i.role}: ${i.value}`)}if(we(o,"provided_fields",n.provided_fields,", "),we(o,"missing",n.missing,", "),we(o,"missing_required_fields",n.missing_required_fields,", "),we(o,"suggested_flags",n.suggested_flags,", "),jl(o,n.allowed_values,t),we(o,"candidate_commands",n.candidate_commands,", "),typeof n.candidate_commands_total=="number"&&o.push(` candidate_commands_total: ${String(n.candidate_commands_total)}`),n.candidate_commands_truncated===!0&&o.push(" candidate_commands_truncated: true"),n.option_scope!==void 0&&o.push(` option_scope: ${n.option_scope}`),Ml(o,n),co(o,"next_best_command",n.next_best_command),n.fallback_candidates&&n.fallback_candidates.length>0){o.push(" fallback_candidates:");for(let i of n.fallback_candidates)o.push(` - ${i.source}: ${i.command} (${i.reason})`)}return o}var Ya=120;function ql(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>Ya?`${n.slice(0,Ya).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})${zl(e.claimActivity)}`}function Hl(e){return e.history_unreadable===!0?"history unreadable":e.unproven_activity!==void 0?`idleness unproven: ${e.unproven_activity}`:e.last_activity_at===null?"no valid activity time":"idle time not measurable"}function Gl(e){return e.state!==void 0?e.state:e.history_unreadable===!0||e.unproven_activity!==void 0||!Number.isFinite(e.idle_hours)?"unknown":e.stale_policy.stale?"stale":"active"}function zl(e){if(e===void 0)return"";let t=`${e.stale_policy.setting}=${e.stale_policy.threshold_hours}`,n=Gl(e);if(n==="unknown"){let o=Number.isFinite(e.idle_hours)?`, last recorded activity ${e.idle_hours}h ago`:"";return`; activity unknown under ${t} (${Hl(e)}${o})`}return`; idle ${e.idle_hours}h, ${n} under ${t}`}function Wl(e,t){let n=[`Error: ${e.title}`];e.code==="close_validation_missing_fields"&&e.recovery?.suggested_retry&&n.push(`Run: ${e.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!t||!vn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...lo("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=ql(e);return o!==void 0&&n.push("",o),n}function Bl(e,t){let n=[];e.why&&!(t&&Cn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?xn(e.examples):e.examples??[];o.length>0&&n.push("",...lo("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...lo("Verification errors:",i)),n.push(...Vl(e)),n}function Vl(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
8
- `).map(i=>` ${i}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function Jl(e,t={}){return rs(e,t,is)}function rs(e,t,n){let o=t.lean===!0,i=[...Wl(e,o),...Bl(e,o||e.code==="close_validation_missing_fields")],r=e.code==="close_validation_missing_fields"&&e.recovery?{...e.recovery,suggested_retry:void 0}:e.recovery,a=Ul(o?bn(r):r,n);return a.length>0&&(i.push(""),i.push(...a)),i.join(`
9
- `)}var Kl="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",Yl=400,Xa=320;function Xl(e){let t=Ce(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=Yl&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.allowed_values&&(n.allowed_values=t.allowed_values),t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function Za(e,t){if(e.code!=="close_validation_missing_fields"||!e.recovery?.suggested_retry||t.recovery?.suggested_retry)return t.nextSteps;let n=t.recovery?.next_best_command?["Run recovery.next_best_command with real evidence, then repeat the original close."]:[...t.nextSteps,"Retrieve the complete retry from SDK error.context.recovery.suggested_retry; replace placeholders with real evidence before executing it."];return Ne(n,e.partialLegalDomainNotice)}function Zl(e,t={}){let n=Jl(e,t),o=wn("error").default_max_estimated_tokens_by_format.text,i=u=>_n(Buffer.byteLength(u,"utf8"))<=o;if(i(n))return n;let r={...e,why:void 0},a=Ne(e.nextSteps?.slice(0,1)??[],e.partialLegalDomainNotice),s={...r,details:void 0,examples:e.examples?.slice(0,1),nextSteps:a,verificationErrors:e.verificationErrors?.slice(0,3)},c={...s,recovery:Xl(e.recovery)};c.nextSteps=Za(e,c);let l=Array.from(e.happened),d={...c,examples:void 0,happened:l.length>Xa?`${l.slice(0,Xa).join("")}...`:e.happened},m={code:e.code,type:e.type,title:e.title,happened:d.happened,required:e.required,nextSteps:Ne([],e.partialLegalDomainNotice)};m.nextSteps=Za(e,m);for(let[u,p]of[[r,mo],[s,mo],[c,3],[d,3],...e.partialLegalDomainNotice?[[m,3],[{...m,happened:e.title},3],[{...m,required:"Correct the producer metadata before relying on a complete legal domain."},3]]:[]]){let f=`${rs(u,t,p)}
1
+ import{a as Aa}from"./chunks/chunk-HZZLSBIJ.js";import"./chunks/chunk-5EFS7K7Y.js";import"./chunks/chunk-SLFRSZK6.js";import{a as qn,b as ta,f as na,g as _a,h as wa,i as va,j as Ca,k as xa,l as ba,m as Vn,o as ka,p as Sa,r as Ea,s as Jn}from"./chunks/chunk-ZK4CY24V.js";import{c as L,d as j,e as P,f as S,g as E,h as Jr,m as pe,n as It,o as Kr,p as Yr}from"./chunks/chunk-DBASKWBO.js";import{Wa as ya,f as Wr,k as Br}from"./chunks/chunk-3US5T6B2.js";import"./chunks/chunk-CV2B4JUB.js";import"./chunks/chunk-Q6GIFUCW.js";import{A as ca,B as la,C as Nt,F as da,G as ma,H as Q,I as ua,Wc as ha,Zb as ga,b as Te,ca as pa,l as ea,q as zn,r as Wn,s as ra,t as aa,u as sa,v as Bn,w as Lt,x as Qe}from"./chunks/chunk-L7HON3BE.js";import"./chunks/chunk-KCR4NF2A.js";import"./chunks/chunk-X5D5YUHR.js";import"./chunks/chunk-4QA5O64H.js";import"./chunks/chunk-VI3A7UZ2.js";import"./chunks/chunk-WNB62BGK.js";import{k as Vr}from"./chunks/chunk-JFPCL45G.js";import{d as fa}from"./chunks/chunk-JQHLOSSS.js";import"./chunks/chunk-6H36ZHMI.js";import"./chunks/chunk-3TK2YOVB.js";import"./chunks/chunk-OGVSGXQX.js";import"./chunks/chunk-AA52P34H.js";import{Ka as ia,a as Xr,b as Zr,d as Qr,ma as $t,na as Pt,oa as Hn,pa as Ze,qa as A,ra as oa,sa as Gn,wa as W}from"./chunks/chunk-R6M5OGJH.js";import{A as Hr,B as Gr,C as Un,D as zr,n as Dn,p as Ur,u as jn,w as qr}from"./chunks/chunk-4EBHZBM2.js";import"./chunks/chunk-WLZ5KVM2.js";import"./chunks/chunk-PZA7QECY.js";import{Ac as Mn,Bc as Pr,Cc as Oe,Fc as Lr,Jc as Nr,K as Mi,Xb as On,bc as br,ec as kr,fc as Sr,hc as Er,id as Ye,lc as Ar,ld as Mr,mb as St,mc as Rr,nb as xr,nc as Tn,pc as Or,qc as me,rc as In,rd as Fr,sc as $n,tc as Pn,uc as Ln,vc as Et,wc as Nn,wd as Fn,xc as Tr,xd as Dr,yc as Ir,yd as jr,zc as $r}from"./chunks/chunk-PY6A7ULK.js";import{l as kt,o as wr,p as vr,t as Re,u as F,v as Cr}from"./chunks/chunk-3E53F7QY.js";import"./chunks/chunk-3AZOATC2.js";import{$g as An,Ge as Z,Ib as vt,Ig as cr,Jd as Hi,Jg as Je,Kd as Gi,Lg as Ke,Md as zi,Mg as lr,Nd as Wi,Od as Bi,Pd as Vi,Pe as Zi,Q as Ee,Qd as Ji,Qe as ie,R as We,Rd as Ki,Rf as or,Sf as ir,T as Be,Ue as En,Ve as x,Vg as dr,Wg as mr,X as Ve,Xg as ur,Yg as pr,Zg as re,_g as fr,ah as le,ba as yn,bh as gr,ch as Ct,fg as rr,fh as Ae,ga as wt,gh as de,ja as _n,jh as hr,kh as xt,ld as vn,md as Cn,nd as Ui,od as qi,pe as Yi,pf as Qi,qd as xn,qf as er,r as ze,rd as bn,rf as tr,sd as kn,sf as nr,te as Xi,tg as ar,th as Rn,ud as Sn,uh as bt,vg as sr,vh as yr,wh as _r,xb as Di,yb as ji}from"./chunks/chunk-RWHS77ME.js";import{d as un,g as ce,i as Ii,j as yt,m as pn,n as $i,o as $,q as Pi,r as X}from"./chunks/chunk-GSLOAEY2.js";import"./chunks/chunk-CNZOC6JD.js";import{E as Ot,F as ue,mb as Tt,nb as z,p as At,r as Xe,s as Rt}from"./chunks/chunk-NRCGGNOE.js";import{G as Ni,H as _t,I as J,Z as Fi,h as M,j as V,k as G,m as K,n as mn,o as D,p as Oi,r as Li,v as fn,x as _,y as gn,z as hn}from"./chunks/chunk-JV7LREUF.js";import{a as Ti,da as wn}from"./chunks/chunk-TE6FBDHP.js";import{A as g,B as ht,C as I,E as Y}from"./chunks/chunk-K672XXGQ.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as Yc}from"node:async_hooks";var Ie=new Yc;function Ra(e){let t=Ie.getStore();return t===void 0?e:t!==null}function fe(e,t=`warning:${e}`){let n=Ie.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):x(t)}function et(e){let t=Ie.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([a,s])=>s!==`warning:${a}`).map(([a,s])=>({code:a,message:s})),i=Reflect.get(e,"warning_details"),r={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),r}function Kn(e){if(!Ie.getStore()?.size)return e;let{token_accounting:t,...n}=et(JSON.parse(e));return JSON.stringify(t===void 0?n:Z(n,o=>`${JSON.stringify(o,null,2)}
2
+ `),null,2)}async function Oa(e,t){if(!e){await Ie.run(null,t);return}let n=new Map;await Ie.run(n,async()=>{await t(),n.size>0&&ie(`${JSON.stringify(et({type:"warning"}))}
3
+ `)})}import{AsyncLocalStorage as Xc}from"node:async_hooks";var Yn=new Xc,Ta=new WeakMap;function Zc(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:Ee(e),outputArgs:t}}var Ia=new WeakMap;function Qc(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function Xn(e,t){return t.some(n=>n.path!==e.path||n.args.length!==e.args.length||n.args.some((o,i)=>o!==e.args[i]))}async function Zn(e){if(e.expectHash===void 0)return;let t=Dn(e.expectHash),n=e.commandPath.trim().toLowerCase();if(Un(n,e.commandOptions),e.rewritten===!0)throw jn();let o=Yn.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await Ur(e.pmRoot,t,Qc(e.command,e.commandArgs));tr(o,e.pmRoot,i),Ia.set(o,n),e.globalOptions!==void 0&&Ta.set(o,Zc(e.globalOptions))}function Qn(e,t,n){let o=Yn.getStore(),i=o===void 0?void 0:Ia.get(o);if(i!==void 0){if(Xn(e,[t]))throw jn();Un(i,n)}}function $a(e,t){if(t!==void 0)throw Dn(t),zr(e)}function el(e){for(let t of nr(e).unchecked)fe(Gr(t))}async function tl(e,t){return e.pmRoot===void 0?t:qr(t,e.pmRoot,Ta.get(e))}async function Pa(e){let t=Qi();try{await e(n=>Yn.run(t,()=>er(t,n)))}catch(n){throw await tl(t,n)}el(t)}import{Command as _i,CommanderError as yc}from"commander";function B(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ge(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return B(t)}function ee(e){let t=new Set,n=[];for(let o of e){let i=ge(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}var eo=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Mt=new Set(["--full","--brief","--compact"]);function nl(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function to(e,t=E([...e])){let n=z(t),o=new Set([...Xr,...Zr,...Qr].flatMap(s=>s.keys.map(c=>`--${c.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),i=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,s.flag]))),r=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,nl(s,o)])));for(let s of eo)r.set(s,!0);for(let s of Mt)r.set(s,!1);let a=new Map;for(let s=0;s<e.length;s+=1){let c=e[s];if(c==="--")break;if(!c.startsWith("-"))continue;let l=c.split("=")[0];if(!r.has(l)&&!c.includes("="))return;let d=r.get(l)===!0&&!c.includes("=");a.set(s,{flag:i.get(l)??l,consumesValue:d}),d&&(s+=1)}return a}function ol(e){let t=to(e);return t===void 0?void 0:new Map([...t].map(([n,{flag:o}])=>[n,o]))}function La(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),eo.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function il(e,t){let n=t.find(i=>Mt.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Mt.has(i));return o.length===1?o[0]:n}function Na(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let r=ol(e);if(!r)return i;let a;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let c=[...r].find(([l,d])=>d==="--fields")?.[0]??-1;if(c<0)return i;a=La(e,r,new Set(["--fields"])),a.splice(c,0,"--fields",o[s+1])}else{let s=il(r,o);if(s===void 0||![...r.values()].includes(s))return i;let c=new Set([...eo,...Mt].filter(l=>l!==s));a=La(e,r,c)}return{...n,suggested_retry:_(a),suggested_retry_args:a}}var Ma=new Set(Wi);function rl(e){return e.includes("@")&&e.includes(":")}function al(e){let t=S([...e]);if(t===void 0)return;let n=e[t+1],o=n===void 0||n.startsWith("-")?void 0:`${e[t]} ${n}`;return o!==void 0&&Tt(o)?o:e[t]}function sl(e){let t=Te(e??"",z(e));return new Set(t.filter(n=>n.takes_value).flatMap(n=>[n.flag,...n.aliases??[]]))}function Fa(e,t,n,o=[],i=()=>!1){if(t!==zi)return n;let r=n===void 0?void 0:{...n,suggested_retry:void 0,suggested_retry_args:void 0},a=al(e),s=to(e,a);if(s===void 0||o===null||e.some(rl)||i())return r;let c=cl(e,s,sl(a));if(c===void 0||c.size===0)return r;let l=[...o,...e.filter((d,m)=>!c.has(m))];return{...n,suggested_retry:_(l),suggested_retry_args:l}}function cl(e,t,n){let o=new Set;for(let[r,{flag:a,consumesValue:s}]of t){if(!Ma.has(a))continue;let c=e[r-1];if(c!==void 0&&!c.includes("=")&&n.has(c)||s&&e[r+1]?.startsWith("-")===!0)return;o.add(r),s&&o.add(r+1)}return e.some((r,a)=>!o.has(a)&&Ma.has(r.split("=",1)[0]))?void 0:o}var ll=new Set(["normalized_args","suggested_retry_args","provided_fields","parsed_positionals","normalizedInvocationArgs","providedOptionFlags","suggestedRetryArgs"]),dl=new Set(["code","original_code","type","recovery_mode","option_scope","diagnostic_class"]),Da=`URL credentials in this invocation were replaced with ${gn}; restore them before replaying any command shown here.`;function ml(e){return`URL credentials in this invocation were replaced with ${gn}. Those in ${e} caused this refusal, so do not restore them: give ${e} a value without URL credentials, and restore any other redacted credentials before replaying.`}function he(e){return e.map(hn)}function ul(e,t){return e==="producer"||t==="details"?"producer":e==="schema"&&t==="recovery"?"schema":"typed"}function pl(e,t,n){let o=J(e);o!==e&&(n.changed=!0);let i=o;for(let r=2;Object.hasOwn(t,i);r+=1)i=`${o} (${r})`;return i}function fl(e,t,n){let o=J(n?hn(e):e);return o!==e&&(t.changed=!0),o}function gl(e,t,n){return e!=="schema"?!1:t==="urlCredentialsRejected"||dl.has(t)&&typeof n=="string"}function no(e,t,n,o){if(typeof e=="string"&&t.ownSteps.has(e))return e;if(typeof e=="string")return fl(e,t,n);if(typeof e!="object"||e===null)return e;let i=t.copies.get(e);if(i!==void 0)return i;if(Array.isArray(e)){let a=[];t.copies.set(e,a);for(let s of e)a.push(no(s,t,n,o));return a}let r={};t.copies.set(e,r);for(let[a,s]of Object.entries(e)){if(gl(o,a,s)){r[a]=s;continue}let c=o==="producer"?pl(a,r,t):a;r[c]=no(s,t,n||ll.has(a),ul(o,a))}return r}function Ft(e){let t=e.urlCredentialsRejected,n=t===void 0?Da:ml(t.source),o=new Set([Da,n]),i={copies:new Map,changed:!1,ownSteps:o},r=no(e,i,!1,"schema");if(!i.changed&&!_t())return e;r.recovery&&(r.recovery={...r.recovery,suggested_retry:void 0,suggested_retry_args:void 0});let a=(r.nextSteps??[]).filter(s=>!o.has(s));return r.nextSteps=[n,...a],r}var hl="project_schema_field_requires_declared_flag";function yl(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function ja(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==hl||n===void 0||i===void 0)return o;let r=yl(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(r.length!==1)return o;let[a]=r,s=a.assignment.trim(),c=s.slice(s.indexOf("=")+1),l=[...e.slice(0,a.index),i,c,...e.slice(a.index+a.width)];return{...o,suggested_retry:_(l),suggested_retry_args:l}}var oo=ea;function _l(e,t,n,o,i){let r=[],a=e.indexOf(n,t);if(a<0||e.slice(t,a).some(s=>s.startsWith("-")))return r;for(let s=a+1;s<e.length;s+=1){let c=e[s];if(c==="--")break;c===`${o}=${i}`?r.push({index:s,width:1}):c===o&&e[s+1]===i&&(r.push({index:s,width:2}),s+=1)}return r}function Ua(e,t,n,o,i=[]){let r=o?.suggested_flags?.[0];if(t!==oo||n===void 0||r===void 0||o.suggested_retry_args===void 0)return o;let a={...o,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||i===null)return a;let c=o.suggested_retry_args,l=_l(e,s,c[0],n,r);if(l.length!==1)return a;let{index:d,width:m}=l[0],u=[...e.slice(0,d),r,...e.slice(d+m)];if(!wl(u,d,n,r,c))return a;let p=[...i,...u];return{...o,suggested_retry:_(p),suggested_retry_args:p}}function wl(e,t,n,o,i){let r=i.lastIndexOf(o);return r<0||i.slice(r).some((a,s)=>e[t+s]!==a)?!1:!e.some((a,s)=>s!==t&&(a===n||a.startsWith(`${n}=`)))}var io="close_validation_missing_fields";function vl(e,t,n,o){let i=e.slice(t+1);if(!i.includes("--"))return[...e,...o];if(!i.some(r=>n.has(r.split("=",1)[0])))return[...e.slice(0,t+1),...o,...i]}function Cl(e,t){let n=e.slice(0,e.length-2*t),o=n.length;for(;o>0&&n[o-1].startsWith("--expect-hash=");)o-=1;return n.slice(o)}function qa(e,t,n,o=[]){let i=n?.missing;if(t!==io||i===void 0||i.length===0)return n;let r=n.suggested_retry_args;if(r===void 0)return n;let a={...n,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||o===null)return a;let c=z(e[s].trim().toLowerCase()),l=i.map(f=>c.find(y=>y.flag===f||y.aliases?.includes(f)===!0));if(l.some(f=>f===void 0))return a;let d=new Set(l.flatMap(f=>[f.flag,...f.aliases??[]])),m=Cl(r,i.length),u=vl(e,s,d,[...i.flatMap(f=>[f,"<value>"]),...m]);if(u===void 0)return a;let p=[...o,...u];return{...n,suggested_retry:_(p),suggested_retry_args:p}}async function Ha(e,t){await Dr(e,{ok:t.ok,error:t.error,result:de(),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 Ga(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Yi({pmRoot:e.pmRoot,result:de()})}catch(o){t=o}let n=await F(e.pmRoot);if(await Xi({pmRoot:e.pmRoot,author:vt(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}var za=new WeakMap;function Dt(e,t){za.set(e,t)}function ye(e){return za.get(e)}function Wa(e){return e.length>0?[e[0]]:[]}function xl(e){let t=["","Intent:",` ${e.why}`],n=Wa(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(`
4
+ `)}function bl(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(`
5
+ `)}function Ba(e,t){return t==="detailed"?bl(e):xl(e)}function U(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var kl={cal:"calendar",ctx:"context"};function Sl(e,t){return e.commands.find(n=>n.name()===t)??null}function El(e,t){let n=e;for(let o of t){let i=Sl(n,o);if(!i)return null;n=i}return n}function ro(e,t,n,o){let i=El(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",Ba(n,o))}function ao(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var _e={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},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 package install ./my-package --project","pm package 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 package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package 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 package 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 package 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 package 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 package 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 catalog --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","pm package list shows the packages installed in the selected scope; catalog shows what pm bundles.","External npm package discovery still belongs to npm search."]},"package inventory":{why:"Lists the packages installed in the selected scope (alias: pm package list) from manifests and saved state, without activating extension code, with the newer version the last pm package manage check observed.",examples:["pm package list","pm package list --global --fields name,version,update","pm package list pm-changelog"],tips:["update is null until pm package manage has checked the registry for that installed version; manage is the live check.","Use pm package catalog for the bundled first-party packages and pm package describe to map what a package registers."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --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 package install ./my-extension --project","pm package --install --project ./my-extension","pm package 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 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 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 inventory":{why:"Compatibility view of the installed package inventory (alias: pm extension list); it reads manifests and saved state without activating extension code.",examples:["pm package list","pm package list --global --fields name,version,update"],tips:["Prefer pm package list in new user-facing workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package 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 package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package 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 package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package 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.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},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 --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status 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 --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status 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 package 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?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",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:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","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 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','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 --start",'pm claim pm-a1b2 --takeover-stale --message "Take over an abandoned claim"','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 is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","The refusal reports the holder's claim age, last activity and idle hours. --takeover-stale takes over only a claim idle for at least mutation_guard.stale_in_progress_hours (default 72), refuses an active one with stale_claim_takeover_refused, and records the previous holder and idle time in the claim's history entry.","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 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment 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."]}};for(let{alias:e,canonical:t}of M){let n=_e[e];n&&(_e[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var $e={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status 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."]},Va=K.filter(e=>e.lifecycle==="deprecated");for(let e of Va){let t=_e[e.alias];_e[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[$e,...Object.values(_e)])e.examples=e.examples.map(t=>{for(let n of Va){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Al(e){let t=U(e??"");return t?kl[t]??t:""}function so(e){let t=Al(e);return t?_e[t]??$e:$e}function Ja(e,t){let n=so(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Wa(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Rl(){let e=K.filter(({lifecycle:n})=>n==="permanent"),t=K.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${Oi(n)})`)].join(`
6
+ `)}function Ol(e,t,n,o){let i=new Set(da);e.configureHelp({visibleCommands(a){let s=t.visibleCommands(a);return n?s.filter(c=>(ye(c)??Q(c.name()))!=="internal"):a!==e?s:s.filter(c=>o.has(c))},visibleOptions(a){let s=t.visibleOptions(a);return a!==e||n?s:s.filter(c=>i.has(c.flags))}});let r=e.options.filter(a=>a.long==="--output-cursor");for(let a of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(a.name())&&a.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...r]})}function Tl(e,t,n,o){let i=new Set(ua("core")),r=e.createHelp();r.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${r.formatHelp(e,r)}${o}
7
+ `,s=t.visibleCommands(e);for(let c of s)ye(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)ye(c)==="core"&&(n.add(c),ma(a()).within_budget||n.delete(c))}function Ka(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ae(t),i=new Set;Ol(e,n,o,i);let r=ao(t),a=Ba($e,r);e.addHelpText("after",a),o&&e.addHelpText("after",Rl()),Tl(e,n,i,a);for(let[d,m]of Object.entries(_e))ro(e,d,m,r);let s=U(P(t).commandPathTokens.join(" ")),c=Xe(s);if(c){ro(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,Rt(c.accepted_flags)]},r);return}let l=At.filter(({parent:d})=>d===s);l.length>0&&ro(e,s,{why:`Dispatches one declared positional action: ${l.map(({action:d})=>d).join("|")}.`,examples:l.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},r)}function co(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of M){if(t&&!M.some(l=>l.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(l=>l.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let l of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===l)??s.command(l).description(`Discover ${l} operations.`);let c=i[i.length-1];if(s.commands.some(l=>l.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(c),Dt(a,Q(o)),s.enablePositionalOptions(),s.addCommand(a)}}function Ut(e){let{title:t,...n}=e;bn(n.why)&&delete n.why,xn(n.required)&&delete n.required;let o=kn(n.examples);o.length>0?n.examples=o:delete n.examples;let i=Sn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var Il=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function $l(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Il.has(e.code)}function os(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:os(e.code)}}var Pe={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Ya={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Xa={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},jt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Pl={guide:Pe,shell:Pe,completion:Pe,"completion-statuses":Pe,"completion-tags":Pe,"completion-types":Pe,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Ya,cal:Ya,reindex:Xa,"search-advanced":Xa,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":jt,"dedupe-audit":jt,"dedupe-merge":jt,normalize:jt};function Ll(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Pl[t]}function uo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Nl(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 Ml(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 lo(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function is(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function te(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"||t==="allowed_values"){let i=is(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(r=>({role:typeof r?.role=="string"?r.role.trim():"",value:typeof r?.value=="string"?r.value.trim():""})).filter(r=>r.role.length>0&&r.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=Nl(n);o&&(e[t]=o)}function Fl(e,t){if(!Er(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}}var rs=["retry_after_ms","waited_ms","owner_handoffs"];function Dl(e,t){for(let n of rs)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function jl(e,t){for(let n of rs){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function Ce(e){if(!e||typeof e!="object")return;let t={};Fl(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),lo(t,"attempted_command",e.attempted_command),te(t,"normalized_args",e.normalized_args),te(t,"parsed_positionals",e.parsed_positionals),te(t,"provided_fields",e.provided_fields),te(t,"missing",e.missing),te(t,"missing_required_fields",e.missing_required_fields),te(t,"suggested_flags",e.suggested_flags),te(t,"allowed_values",e.allowed_values),te(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),lo(t,"suggested_retry",e.suggested_retry),te(t,"suggested_retry_args",e.suggested_retry_args),jl(t,e);let n=Ml(e.fallback_candidates);return n&&(t.fallback_candidates=n),lo(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function mo(e,t,n){n&&e.push(` ${t}: ${n}`)}function we(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}var po=8,Ul=12,as=Number.POSITIVE_INFINITY;function ql(e,t,n){let o=t!==void 0&&n===as&&t.length<=Ul?t.length:Math.min(n,po),i=t?.slice(0,o).map(r=>/^[\p{L}\p{N}._:/@=-]+$/u.test(r)?r:JSON.stringify(r));we(e,"allowed_values",i,", "),t&&t.length>o&&e.push(` allowed_values_omitted: ${t.length-o} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function Hl(e,t){let n=Ce(e);if(!n)return[];let o=["Recovery bundle:"];if(n.token_budget){let i=n.token_budget;o.push(` requested_token_budget: ${i.requested_tokens}`,` feasible_token_budget: ${i.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${i.minimum_feasible_tokens??"not established"}`)}if(mo(o,"suggested_retry",n.suggested_retry),mo(o,"attempted_command",n.attempted_command),we(o,"normalized_args",n.attempted_command?void 0:n.normalized_args," "),n.parsed_positionals&&n.parsed_positionals.length>0){o.push(" parsed_positionals:");for(let i of n.parsed_positionals)o.push(` - ${i.role}: ${i.value}`)}if(we(o,"provided_fields",n.provided_fields,", "),we(o,"missing",n.missing,", "),we(o,"missing_required_fields",n.missing_required_fields,", "),we(o,"suggested_flags",n.suggested_flags,", "),ql(o,n.allowed_values,t),we(o,"candidate_commands",n.candidate_commands,", "),typeof n.candidate_commands_total=="number"&&o.push(` candidate_commands_total: ${String(n.candidate_commands_total)}`),n.candidate_commands_truncated===!0&&o.push(" candidate_commands_truncated: true"),n.option_scope!==void 0&&o.push(` option_scope: ${n.option_scope}`),Dl(o,n),mo(o,"next_best_command",n.next_best_command),n.fallback_candidates&&n.fallback_candidates.length>0){o.push(" fallback_candidates:");for(let i of n.fallback_candidates)o.push(` - ${i.source}: ${i.command} (${i.reason})`)}return o}var Za=120;function Gl(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>Za?`${n.slice(0,Za).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})${Bl(e.claimActivity)}`}function zl(e){return e.history_unreadable===!0?"history unreadable":e.unproven_activity!==void 0?`idleness unproven: ${e.unproven_activity}`:e.last_activity_at===null?"no valid activity time":"idle time not measurable"}function Wl(e){return e.state!==void 0?e.state:e.history_unreadable===!0||e.unproven_activity!==void 0||!Number.isFinite(e.idle_hours)?"unknown":e.stale_policy.stale?"stale":"active"}function Bl(e){if(e===void 0)return"";let t=`${e.stale_policy.setting}=${e.stale_policy.threshold_hours}`,n=Wl(e);if(n==="unknown"){let o=Number.isFinite(e.idle_hours)?`, last recorded activity ${e.idle_hours}h ago`:"";return`; activity unknown under ${t} (${zl(e)}${o})`}return`; idle ${e.idle_hours}h, ${n} under ${t}`}function Vl(e,t){let n=[`Error: ${e.title}`];e.code==="close_validation_missing_fields"&&e.recovery?.suggested_retry&&n.push(`Run: ${e.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!t||!xn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...uo("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=Gl(e);return o!==void 0&&n.push("",o),n}function Jl(e,t){let n=[];e.why&&!(t&&bn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?kn(e.examples):e.examples??[];o.length>0&&n.push("",...uo("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...uo("Verification errors:",i)),n.push(...Kl(e)),n}function Kl(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
8
+ `).map(i=>` ${i}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function Yl(e,t={}){return ss(e,t,as)}function ss(e,t,n){let o=t.lean===!0,i=[...Vl(e,o),...Jl(e,o||e.code==="close_validation_missing_fields")],r=e.code==="close_validation_missing_fields"&&e.recovery?{...e.recovery,suggested_retry:void 0}:e.recovery,a=Hl(o?Sn(r):r,n);return a.length>0&&(i.push(""),i.push(...a)),i.join(`
9
+ `)}var Xl="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",Zl=400,Qa=320;function Ql(e){let t=Ce(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=Zl&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.allowed_values&&(n.allowed_values=t.allowed_values),t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function es(e,t){if(e.code!=="close_validation_missing_fields"||!e.recovery?.suggested_retry||t.recovery?.suggested_retry)return t.nextSteps;let n=t.recovery?.next_best_command?["Run recovery.next_best_command with real evidence, then repeat the original close."]:[...t.nextSteps,"Retrieve the complete retry from SDK error.context.recovery.suggested_retry; replace placeholders with real evidence before executing it."];return Le(n,e.partialLegalDomainNotice)}function ed(e,t={}){let n=Yl(e,t),o=Cn("error").default_max_estimated_tokens_by_format.text,i=u=>vn(Buffer.byteLength(u,"utf8"))<=o;if(i(n))return n;let r={...e,why:void 0},a=Le(e.nextSteps?.slice(0,1)??[],e.partialLegalDomainNotice),s={...r,details:void 0,examples:e.examples?.slice(0,1),nextSteps:a,verificationErrors:e.verificationErrors?.slice(0,3)},c={...s,recovery:Ql(e.recovery)};c.nextSteps=es(e,c);let l=Array.from(e.happened),d={...c,examples:void 0,happened:l.length>Qa?`${l.slice(0,Qa).join("")}...`:e.happened},m={code:e.code,type:e.type,title:e.title,happened:d.happened,required:e.required,nextSteps:Le([],e.partialLegalDomainNotice)};m.nextSteps=es(e,m);for(let[u,p]of[[r,po],[s,po],[c,3],[d,3],...e.partialLegalDomainNotice?[[m,3],[{...m,happened:e.title},3],[{...m,required:"Correct the producer metadata before relying on a complete legal domain."},3]]:[]]){let f=`${ss(u,t,p)}
10
10
 
11
- ${Kl}`;if(i(f))return f}return n}function Ql(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",t.claimActivity!==void 0&&(e.claim_activity=t.claimActivity),e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function as(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),Ql(e,t),Tl(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function ed(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return j([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i))}function td(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(r=>r===n||r.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function nd(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=j(e.recovery?.normalized_args??[]),o=V(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=ed(e,i),a=td(e,i,r);return{surface:r??e.recovery?.missing?.[0]??Wn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function od(e,t){let n=as({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:nd(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function uo(e,t){let n=Mt(e),o=n.recovery,r=!!o?.suggested_retry||!!o?.suggested_retry_args?.length||!!o?.allowed_values?.length||!!o?.candidate_commands?.length||!!n.nextSteps?.length?"recovery_bundle":"error";return Di(id(od(n,t),r),{diagnosticClass:r})}function id(e,t){if(e.details===void 0)return e;let n=wn(t).default_max_estimated_tokens_by_format.json;if(_n(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:Cr.max_bytes}}}function po(e){return as({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Ut(e){return e.replace(/\(outputHelp\)/g,"").trim()}function rd(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 ve(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 Qa(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function ad(e){return Wn(e?.normalized_args)}function sd(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 cd(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let r of o){let a=n.findIndex(s=>s===r);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=i,_(s)}}}function ld(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function dd(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function md(e,t,n,o){if(t==="close_validation_missing_fields")return"Close is missing required evidence";let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?ld(o):void 0)??e.title}function ud(e){let t=br(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var pd=400;function fd(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=pd&&t.push(o)}return t}function gd(e){let t=e?.allowed_values;if(t===void 0||Array.isArray(t)&&t.every(a=>typeof a=="string"))return;let n=Array.isArray(t)?t.filter(a=>typeof a=="string"):[],o=fd(n),i=o.join(", ")||"none shown",r=n.length>o.length?` (${n.length-o.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${i}${r}. Correct the producer metadata before relying on a complete domain.`}function hd(e,t,n){let o=Ce(t),i=o&&e?Ce({...e,...o}):o??e;if(!n)return i;let{allowed_values:r,...a}=i??{};return Object.keys(a).length>0?a:void 0}function ne(e,t,n){if(!n)return e;let o=Ut(t),i=tt(n.code,e.code),r=tt(n.type,ts(i)),a=ve(n.examples)??e.examples,s=ve(n.nextSteps)??e.nextSteps,c=gd(n.recovery),l=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,d=ve(n.verification_errors)??e.verificationErrors,m=hd(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:md(e,i,n,o),happened:o.length>0?o:e.happened,required:tt(n.required,e.required),why:tt(n.why,e.why),examples:a,nextSteps:l,urlCredentialsRejected:n.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:c,verificationErrors:d,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:dd(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,claimActivity:n.claim_activity,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:m,...ud(n)}}function yd(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=Ti(process.cwd(),i);return ne(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,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 ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{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 _d(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ne(b({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function wd(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ne(b({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 vd(e,t,n){if(!t.includes("is locked"))return null;let o=ns(n?.recovery?.normalized_args),i=o?_(o):void 0,r=ne(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(r.recovery={...r.recovery,suggested_retry:i,suggested_retry_args:[...o]}),r}function Cd(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",c=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ne(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"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 xd(e,t,n){return t.startsWith("No update flags provided")?ne(b({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 bd(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=tt(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function kd(e,t,n){if(!bd(t,n))return null;let o=Ce(n?.recovery),i=ad(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??sd(t),s=Ce({...o,allowed_values:o?.allowed_values??a}),c=cd(o,a),l=c?[c,r]:[r,"pm contracts --command <command> --flags-only --json"],d=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ne(b({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:l,nextSteps:d,recovery:s}),e,n)}function fo(e,t){let n=Ut(e),o=yd(e,n,t)??_d(e,n,t)??wd(e,n,t)??vd(e,n,t)??Cd(e,n,t)??xd(e,n,t)??kd(e,n,t);return o||ne(b({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 Sd(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 Ed(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ad(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function go(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 z(e,t={}){let n=go(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ad(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Ce({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Ne(e,t){return!t||e.includes(t)?e:[...e,t]}var Rd=new Set(["--add","--add-json","--remove"]),Od=new Set(["command","cmd","path"]);function Td(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(Rd.has(o))return o}}function Id(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 i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!Od.has(r))return;let a=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;a.push(d)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return _(c)}}function Pd(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Ed(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,c=go(o?.providedOptionFlags),l=[r],d=Sd(t,r,n),m=s?Ne(d,s):d,u=a?[`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.`],p=s?Ne(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?Ne(p,`Already provided options: ${c.join(", ")}`):p;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--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:f,recovery:z(o,{missing:l})})}function $d(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:z(n,{missing:[i]})})}function Nd(e,t,n){return b({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:z(t,{suggested_flags:n})})}var Ld={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Md(e){let t=ve(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Fd(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:Dd(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,cs(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var ss=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function Dd(e,t){if(t===void 0||!ss.includes(e.split("=",1)[0]))return;let n=ya(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${_a(n)}.`}function jd(e,t,n){let o=wa(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...ss,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function cs(e){return/\s/u.test(e)}function Ud(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...j(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function qd(e,t,n){if(cs(t))return Ud(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=jd(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(va(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let r=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(r<0||i.includes("--")||!i[r]?.includes("=")&&r!==i.length-1&&i[r+1]?.startsWith("-")!==!0)return{};let a=j(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function Hd(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=go(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=qd(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return Nd(r,n,a);let l=Md(i),d=Fd(r,t,a,l,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${D(t)?.canonical??t} --help`:"pm --help --all"].filter(u=>typeof u=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Ld[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:z(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:l.otherCommands,candidate_commands_total:l.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:l.optionScope})})}function Gd(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({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:Qa([t.installCommand,...n]),nextSteps:Qa([r,...a]),recovery:z(i)})}function zd(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ve(t?.unknownCommandExamples),r=ve(t?.unknownCommandNextSteps),a=Pl(o),s=i??["pm --help"],c=r??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!d||!l.has(d))?Gd(o,a,s,c,t):b({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:z(t)})}function Wd(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ve(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${D(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:z(e,{allowed_values:o,suggested_retry:i})})}function Bd(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Td(o);if(!i)return null;let r=Id(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} 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:[...r?[r]:[],'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:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:z(n,r?{suggested_retry:r}:{})})}var Vd=new Set(["comments","docs","files","learnings","notes","test"]);function Jd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Ni(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,r=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return b({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${r}.`,examples:[i??r],recovery:z(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function Kd(e,t,n){if(!/too many arguments/i.test(e)||!Vd.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>l===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:z(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var Yd=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"]),es=new Set(["context","ctx"]);function Xd(e,t,n){if(!/too many arguments/i.test(e)||!es.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>es.has(l)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(r)){if(l){l=!1;continue}let m=d.split("=")[0];if(Yd.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({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:z(n,{suggested_retry:c})})}function ho(e,t,n,o){let i=Ut(e),r=Pd(i,t,n,o)??$d(i,t,o)??Hd(i,t,o)??zd(i,o)??Wd(o)??Kd(i,t,o)??Bd(i,t,o)??Jd(i,t,o)??Xd(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:z(o)})}function ls(e,t,n={}){let o=Mt(fo(e,t));return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
12
- `):ds(o,n)}function ds(e,t){let n=Mt(e),o=a=>ji(Zl(n,a),n.required).output,i=o(t);if(t.lean!==!0)return i;let r=o({});return Buffer.byteLength(r,"utf8")<Buffer.byteLength(i,"utf8")?r:i}function ms(e,t){return po(fo(e,t))}function yo(e,t,n){return uo(fo(e,n),t)}function us(e,t,n,o,i={}){let r=ho(e,t,n,o);return ds(r,i)}function _o(e,t,n,o){return po(ho(e,t,n,o))}function qt(e,t,n,o,i){return uo(ho(e,t,n,i),o)}function ps(e,t){let n=fs(e);return uo(n,t)}function fs(e){let t=Ut(e);return rd(t)?b({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."]}):b({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 gs(e){return po(fs(e))}var nt=Ri.join("|"),Zd={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"},Qd={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"]}},hs=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function em(e,t){let n=Qd[e];if(!n)return[];let o=B(t);for(let[i,r]of Object.entries(n))if(B(i)===o)return r;return[]}function wo(e,t,n){if(n.length===0)return e;let o=n.map(s=>({...s,name:J(s.name),error:J(s.error),...s.recovery_commands?{recovery_commands:s.recovery_commands.map(J)}:{}}));if(t){let s=o.find(m=>m.declared_command_match===!0),{token_accounting:c,...l}=JSON.parse(e),d={...l,...s?{extension_command_failure:{code:"extension_command_activation_failed",extension:s.name,layer:s.layer,error:s.error,recovery_commands:s.recovery_commands??[]}}:{},failed_extensions:o};return JSON.stringify(c===void 0?d:Z(d,m=>`${JSON.stringify(m,null,2)}
11
+ ${Xl}`;if(i(f))return f}return n}function td(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",t.claimActivity!==void 0&&(e.claim_activity=t.claimActivity),e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function cs(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),td(e,t),$l(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function nd(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return j([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i))}function od(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(r=>r===n||r.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function id(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=j(e.recovery?.normalized_args??[]),o=V(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=nd(e,i),a=od(e,i,r);return{surface:r??e.recovery?.missing?.[0]??Vn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function rd(e,t){let n=cs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:id(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function fo(e,t){let n=Ft(e),o=n.recovery,r=!!o?.suggested_retry||!!o?.suggested_retry_args?.length||!!o?.allowed_values?.length||!!o?.candidate_commands?.length||!!n.nextSteps?.length?"recovery_bundle":"error";return Ui(ad(rd(n,t),r),{diagnosticClass:r})}function ad(e,t){if(e.details===void 0)return e;let n=Cn(t).default_max_estimated_tokens_by_format.json;if(vn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:br.max_bytes}}}function go(e){return cs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function qt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function sd(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 ve(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 ts(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function cd(e){return Vn(e?.normalized_args)}function ld(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 dd(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let r of o){let a=n.findIndex(s=>s===r);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=i,_(s)}}}function md(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function ud(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function pd(e,t,n,o){if(t==="close_validation_missing_fields")return"Close is missing required evidence";let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?md(o):void 0)??e.title}function fd(e){let t=Sr(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var gd=400;function hd(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=gd&&t.push(o)}return t}function yd(e){let t=e?.allowed_values;if(t===void 0||Array.isArray(t)&&t.every(a=>typeof a=="string"))return;let n=Array.isArray(t)?t.filter(a=>typeof a=="string"):[],o=hd(n),i=o.join(", ")||"none shown",r=n.length>o.length?` (${n.length-o.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${i}${r}. Correct the producer metadata before relying on a complete domain.`}function _d(e,t,n){let o=Ce(t),i=o&&e?Ce({...e,...o}):o??e;if(!n)return i;let{allowed_values:r,...a}=i??{};return Object.keys(a).length>0?a:void 0}function ne(e,t,n){if(!n)return e;let o=qt(t),i=tt(n.code,e.code),r=tt(n.type,os(i)),a=ve(n.examples)??e.examples,s=ve(n.nextSteps)??e.nextSteps,c=yd(n.recovery),l=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,d=ve(n.verification_errors)??e.verificationErrors,m=_d(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:pd(e,i,n,o),happened:o.length>0?o:e.happened,required:tt(n.required,e.required),why:tt(n.why,e.why),examples:a,nextSteps:l,urlCredentialsRejected:n.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:c,verificationErrors:d,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:ud(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,claimActivity:n.claim_activity,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:m,...fd(n)}}function wd(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=$i(process.cwd(),i);return ne(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,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 ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{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 vd(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ne(b({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Cd(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ne(b({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 xd(e,t,n){if(!t.includes("is locked"))return null;let o=is(n?.recovery?.normalized_args),i=o?_(o):void 0,r=ne(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(r.recovery={...r.recovery,suggested_retry:i,suggested_retry_args:[...o]}),r}function bd(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",c=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ne(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"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 kd(e,t,n){return t.startsWith("No update flags provided")?ne(b({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 Sd(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=tt(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function Ed(e,t,n){if(!Sd(t,n))return null;let o=Ce(n?.recovery),i=cd(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??ld(t),s=Ce({...o,allowed_values:o?.allowed_values??a}),c=dd(o,a),l=c?[c,r]:[r,"pm contracts --command <command> --flags-only --json"],d=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ne(b({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:l,nextSteps:d,recovery:s}),e,n)}function ho(e,t){let n=qt(e),o=wd(e,n,t)??vd(e,n,t)??Cd(e,n,t)??xd(e,n,t)??bd(e,n,t)??kd(e,n,t)??Ed(e,n,t);return o||ne(b({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 Ad(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 Rd(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Od(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function yo(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=yo(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Od(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Ce({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Le(e,t){return!t||e.includes(t)?e:[...e,t]}var Td=new Set(["--add","--add-json","--remove"]),Id=new Set(["command","cmd","path"]);function $d(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(Td.has(o))return o}}function Pd(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 i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!Id.has(r))return;let a=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;a.push(d)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return _(c)}}function Ld(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Rd(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,c=yo(o?.providedOptionFlags),l=[r],d=Ad(t,r,n),m=s?Le(d,s):d,u=a?[`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.`],p=s?Le(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?Le(p,`Already provided options: ${c.join(", ")}`):p;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--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:f,recovery:q(o,{missing:l})})}function Nd(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} 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:[i]})})}function Md(e,t,n){return b({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})})}var Fd={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Dd(e){let t=ve(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function jd(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:Ud(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,ds(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var ls=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function Ud(e,t){if(t===void 0||!ls.includes(e.split("=",1)[0]))return;let n=wa(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${va(n)}.`}function qd(e,t,n){let o=Ca(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...ls,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function ds(e){return/\s/u.test(e)}function Hd(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...j(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function Gd(e,t,n){if(ds(t))return Hd(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=qd(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(xa(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let r=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(r<0||i.includes("--")||!i[r]?.includes("=")&&r!==i.length-1&&i[r+1]?.startsWith("-")!==!0)return{};let a=j(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function zd(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=yo(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=Gd(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return Md(r,n,a);let l=Dd(i),d=jd(r,t,a,l,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${D(t)?.canonical??t} --help`:"pm --help --all"].filter(u=>typeof u=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Fd[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:q(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:l.otherCommands,candidate_commands_total:l.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:l.optionScope})})}function Wd(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({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:ts([t.installCommand,...n]),nextSteps:ts([r,...a]),recovery:q(i)})}function Bd(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ve(t?.unknownCommandExamples),r=ve(t?.unknownCommandNextSteps),a=Ll(o),s=i??["pm --help"],c=r??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!d||!l.has(d))?Wd(o,a,s,c,t):b({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 Vd(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ve(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${D(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:q(e,{allowed_values:o,suggested_retry:i})})}function Jd(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=$d(o);if(!i)return null;let r=Pd(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} 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:[...r?[r]:[],'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:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:q(n,r?{suggested_retry:r}:{})})}var Kd=new Set(["comments","docs","files","learnings","notes","test"]);function Yd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Mi(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,r=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return b({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${r}.`,examples:[i??r],recovery:q(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function Xd(e){return[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)}function Zd(e){let t=_t()?void 0:e.retryArgs,n=process.platform==="win32"||Li(process.platform)==="cmd",o=t?.some(i=>Xd(i)||n&&fn(i,process.platform,"cmd")!==i)===!0;return{retryArgs:t,argvOnly:o,retry:t&&!o?_(t):void 0}}function Qd(e,t,n){let o=n?.linkedResourceValueList;if(!/too many arguments/i.test(e)||o===void 0)return null;let i=o.flags[0],r=o.flags.join(", "),{retryArgs:a,argvOnly:s,retry:c}=Zd(o),l=t!=="test"&&o.flags.includes("--add"),d=`pm ${t} ${o.itemId} ${i} <value> ${i} <value>`,m=o.extraValues.length;return b({code:"linked_resource_value_list",title:`Repeat ${i} once per value${l?" (or use --add-glob)":""}`,happened:`${m} more value${m===1?"":"s"} followed the value of ${r}. pm ${t} takes one value per occurrence, so they were read as extra positional arguments and nothing was changed.`,required:c?`Retry with one ${i} per value: ${c}`:s?`Retry with one ${i} per value by replaying recovery.suggested_retry_args (shown with --json): a value holds a control character, or needs cmd.exe quoting that a copied command cannot carry exactly.`:o.readsStdin?`Write one ${i} per value and pipe the same input again, because the command reads stdin: ${d}`:`Write one ${i} per value, and quote a value that contains spaces or commas so the shell passes it as one argument: ${d}`,why:`Each occurrence of a repeatable flag takes exactly one value, so an item id written after the flag (pm ${t} ${i} <value> <id>) stays unambiguous.`,examples:[c??d,...l?[`pm ${t} ${o.itemId} --add-glob "<pattern>"`]:[],`pm ${t} --help`],recovery:q(n,{suggested_retry:c,suggested_retry_args:a})})}function em(e,t,n){if(!/too many arguments/i.test(e)||!Kd.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>l===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:q(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var tm=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"]),ns=new Set(["context","ctx"]);function nm(e,t,n){if(!/too many arguments/i.test(e)||!ns.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>ns.has(l)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(r)){if(l){l=!1;continue}let m=d.split("=")[0];if(tm.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({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 _o(e,t,n,o){let i=qt(e),r=Ld(i,t,n,o)??Nd(i,t,o)??zd(i,t,o)??Bd(i,o)??Vd(o)??em(i,t,o)??Qd(i,t,o)??Jd(i,t,o)??Yd(i,t,o)??nm(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,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 ms(e,t,n={}){let o=Ft(ho(e,t));return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
12
+ `):us(o,n)}function us(e,t){let n=Ft(e),o=a=>qi(ed(n,a),n.required).output,i=o(t);if(t.lean!==!0)return i;let r=o({});return Buffer.byteLength(r,"utf8")<Buffer.byteLength(i,"utf8")?r:i}function ps(e,t){return go(ho(e,t))}function wo(e,t,n){return fo(ho(e,n),t)}function fs(e,t,n,o,i={}){let r=_o(e,t,n,o);return us(r,i)}function vo(e,t,n,o){return go(_o(e,t,n,o))}function Ht(e,t,n,o,i){return fo(_o(e,t,n,i),o)}function gs(e,t){let n=hs(e);return fo(n,t)}function hs(e){let t=qt(e);return sd(t)?b({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."]}):b({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 ys(e){return go(hs(e))}var nt=Ti.join("|"),om={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"},im={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"]}},_s=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function rm(e,t){let n=im[e];if(!n)return[];let o=B(t);for(let[i,r]of Object.entries(n))if(B(i)===o)return r;return[]}function Co(e,t,n){if(n.length===0)return e;let o=n.map(s=>({...s,name:J(s.name),error:J(s.error),...s.recovery_commands?{recovery_commands:s.recovery_commands.map(J)}:{}}));if(t){let s=o.find(m=>m.declared_command_match===!0),{token_accounting:c,...l}=JSON.parse(e),d={...l,...s?{extension_command_failure:{code:"extension_command_activation_failed",extension:s.name,layer:s.layer,error:s.error,recovery_commands:s.recovery_commands??[]}}:{},failed_extensions:o};return JSON.stringify(c===void 0?d:Z(d,m=>`${JSON.stringify(m,null,2)}
13
13
  `),null,2)}let i=o.map(s=>`- ${s.layer}:${s.name}: ${s.error}`).join(`
14
14
  `),r=o.find(s=>s.declared_command_match===!0);if(!r)return`${e}
15
15
  Extension activation failures:
@@ -21,24 +21,24 @@ ${a}`:""}
21
21
 
22
22
  ${e}
23
23
  Extension activation failures:
24
- ${i}`}function vo(e){return $(e).commandPathTokens[0]??E(e)??"<command>"}function Cs(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=U(A(i)),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r),o.push(...i.commands)}for(let i of t.keys()){let r=U(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function ys(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let r=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of i){let c=hn(s,o,r);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function _s(e){return B(e).slice(2).replace(/-/g,"")}function Co(e){return _(e)}function tm(e){let t=D(e)?.canonical??dn[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=Zd[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function ws(e){let t=ua(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function nm(e,t){let n=ws(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let r=new Set,a=i.source;if(a)for(let c of[a.name,a.package]){let l=ws(c??"");l.length>0&&r.add(l)}if(r.size===0)continue;[...r].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(i.command)}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function ot(e,t){let n=new Set,o=t??G(e);for(let i of o){i.flag.startsWith("--")&&n.add(B(i.flag));for(let r of i.aliases??[])r.startsWith("--")&&n.add(B(r))}return[...n].sort((i,r)=>i.localeCompare(r))}function om(e,t){if(!e.startsWith("--"))return[];let n=_s(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=_s(r);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){i.push({flag:r,rank:0,distance:a.length-n.length});continue}let s=hn(n,a,o);s===null||s<=0||i.push({flag:r,rank:1,distance:s})}return i.sort((r,a)=>r.rank!==a.rank?r.rank-a.rank:r.distance!==a.distance?r.distance-a.distance:r.flag.localeCompare(a.flag)).map(r=>r.flag).slice(0,3)}var Ht,im=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 rm(){if(Ht)return Ht;let e=new Map;for(let t of ze)if(!im.has(t))for(let n of ot(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Ht=e,Ht}function am(e,t){if(!e.startsWith("--"))return[];let n=rm().get(B(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(ot(o));return[...new Set(n.filter(r=>r!==o).map(r=>({command:r,sharedFlagCount:ot(r).filter(a=>i.has(a)).length})).sort((r,a)=>r.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-r.sharedFlagCount:r.command.localeCompare(a.command)).map(({command:r})=>D(r)?.canonical??r))]}function sm(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let r=i.indexOf("="),a=r>=0?i.slice(0,r):i;if(B(a)!==B(t))continue;let s=[...e];return s[o]=r>=0?`${n}${i.slice(r)}`:n,s}}function cm(e){let t=new Set(e.commandPaths),n=r=>Math.min(ys(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?ys(r,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(r,a)=>{if(!Number.isFinite(a)||!t.has(r))return;let s=o.get(r);(s===void 0||a<s)&&o.set(r,a)};for(let r of e.commandPaths)i(r,n(r));for(let[r,a]of Object.entries(dn))r!=="read"&&i(a,n(r));return[...o.entries()].sort(([r,a],[s,c])=>a!==c?a-c:r.localeCompare(s)).map(([r])=>r)}function lm(e){let t=D(e.normalizedUnknown),n=ka(e.commandPaths,e.primaryToken),o=cm(e),i=nm(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return Bn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(r=>!e.normalizedUnknown.includes(" ")||r!==e.normalizedUnknown)}function dm(e,t,n){let[o,...i]=e.split(" ");if(n.includes(o)||D(o)!==void 0)return;let r=o.endsWith("s")?o.slice(0,-1):`${o}s`,a=D(r),s=a&&n.includes(a.canonical)?a.canonical:n.includes(r)?r:void 0;if(s===void 0)return;let c=s,l=["package","packages","extension"].includes(s)?[Tt(um(t))??""].filter(d=>d.length>0):pm(t,i.length);for(let d of[...i,...l]){let m=`${c} ${d}`,u=D(m);if(!n.includes(m)&&!(u!==void 0&&!u.hidden&&n.includes(u.canonical)))break;c=m}return c}function mm(e,t,n,o){let i=dm(e,t,n),r=ba(e,n)??i,a=o.length>0||i!==void 0,s=a?[]:Bn(fm(n),n),c=[...new Set([...r?[r]:[],...o.length>0?o:s])].slice(0,3);return{misnestedPath:r,hasConcreteCandidates:a,suggestedPaths:c}}function um(e){let t=S([...e]);return t===void 0?[]:e.slice(t+1)}function pm(e,t){let n=[],o=S([...e]);for(;o!==void 0;){let i=S(e.slice(o+1));o=i===void 0?void 0:o+1+i,o!==void 0&&n.push(e[o])}return n.slice(t)}function fm(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function gm(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function hm(e,t,n){let o=S([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let r=S(t.slice(o+1));o=r===void 0?void 0:o+1+r}return e}function vs(e,t){if(!e)return;let n=N([...t]);return[...Ee(n),...e.split(" "),"--help"]}function xo(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let r=Cs(t,n),a=hm(i[1],o,r),s=U(a);if(s.length===0||r.length===0)return;let c=ha(s,r);if(c){let R=vs("update",o),O=R.slice(0,-2);return{suggestedRetryCommand:_(R),suggestedRetryArgs:R,unknownCommandExamples:[_(R),...c.examples.map(k=>_([...O,...k]))],unknownCommandNextSteps:c.nextSteps}}let l=tm(s);if(l&&!r.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let d=s.split(" ")[0],m=lm({commandPaths:r,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),{misnestedPath:u,hasConcreteCandidates:p,suggestedPaths:f}=mm(s,o,r,m),y=vs(u,o),h=gm(f,p),C=p?`Did you mean: ${f.join(", ")}?`:null;return{...y?{suggestedRetryCommand:_(y),suggestedRetryArgs:y}:{},unknownCommandExamples:y?[_(y),...h.slice(1)]:h,unknownCommandNextSteps:[...C?[C]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...C?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function ym(e){return Array.from(new Set(e))}function _m(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
25
- `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function wm(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 vm(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(r=>r.trim().toLowerCase()===n))}function Le(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=vm(n,i);if(!r){let a=n.registeredArguments;return a.length>0&&(n.commands.length===0||a[0]?.required===!0)&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=r}return!0}async function Cm(e,t,n,o){try{let i=P(process.cwd(),e.path);if(!await Y(X(i)))return{allowedTypes:nt};let r=await F(i),a=e.noExtensions?void 0:le(),s=ce(r,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await kt(i,d,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):nt,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:nt}}}function xm(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?ym([...em(t,n[1]),...om(n[1],ot(t))]).filter(a=>Ca(n[1],a)):void 0,i=n?am(n[1],t):[],r=n!==null&&ot(t).includes(B(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:r?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function bm(e,t,n){if(!t||!n||n.length===0)return;let o=sm(e,t[1],n[0]);return o?Co(o):void 0}function km(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?wm(_m(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=E(t);if(i)return xa(t,i,[o])}function Sm(e,t){if(!/too many arguments/i.test(e))return;let n=S(t),o=V(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,r=t[i+1]?.trim().toLowerCase(),a=t[i+2]?.trim().toLowerCase();if(!r||!a)return;let s=`${r}-${a}`;if(!hs.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[...hs],suggestedRetryCommand:Co(c)}}function Em(e,t,n,o){let i=S(t),r=V(t.slice(i))?.alias??E(t);if(!/unknown option /i.test(e)||r===void 0)return r;let a=D(r)?.canonical??r;return ze.some(s=>s===r)||Cs(n,o).includes(a)?r:void 0}async function it(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",s=pe([...i]).argv,c=he(s),l=N(s),d=Em(a,c,t,n),m=Co(c),u=ee(c),p=await Cm(l,a,c,d),f=p.allowedTypes,y=xo(a,t,n,c),h=xm(a,d),C=Sm(a,c),R=C?.suggestedRetryCommand??bm(c,h.match,h.suggestions)??km(a,c);return{message:a,commandName:d,allowedTypes:f,attemptedCommand:m,normalizedInvocationArgs:[...c],providedOptionFlags:u,unknownOptionSuggestions:h.suggestions,unknownOptionOtherCommands:h.otherCommands.length>0?h.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:h.otherCommands.length>0?h.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:h.otherCommands.length>12||void 0,unknownOptionScope:h.scope,suggestedRetryCommand:R,verifiedCollectionItemId:p.verifiedCollectionItemId,...C,...y,...o}}async function bo(e,t,n,o={},i=process.argv.slice(2)){let r=await it(e,t,n,o,i),{message:a,commandName:s,allowedTypes:c,...l}=r,d=N(r.normalizedInvocationArgs).lean,m=us(a,s,c,l,{lean:d}),u=await hr("help_format",{message:m,command:s,allowed_types:c});return u.handled&&typeof u.result=="string"?u.result:m}async function ko(e,t,n,o=!1,i={},r=process.argv.slice(2)){let a=await it(e,t,n,i,r),s=qt(a.message,a.commandName,a.allowedTypes,g.USAGE,a),c=o?jt(s):s,l=N(a.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?Z(c,d=>`${JSON.stringify(d,null,2)}
26
- `):c,null,2)}async function xs(e,t,n,o){if(n)return null;let i=e.some(a=>a==="--for"||a.startsWith("--for=")),r=E(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as Am}from"commander";function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ks(e,t){let n=new Map;for(let o of e){let i=v(o.command);for(let r of t){if(r.layer!==o.layer||r.name!==o.name)continue;let a=v(r.command),s=a.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&i===d){n.set(i,a);break}}}return n}function So(e,t,n,o){if(!t||!n)return;let i,r=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 u=d.split(" ");u.length>r&&u.every((p,f)=>l[f]===p)&&(i=m,r=u.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return Rm(a).takesValue}function zt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Gt(e){return typeof e=="boolean"?e:void 0}function Rm(e){let t=_t(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function Om(e){let t=Be(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=Eo(e);return n?`${n} ${Ao(e)}`:null}function Ss(e){let t=[...new Set(e.map(Om).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
24
+ ${i}`}function xo(e){return P(e).commandPathTokens[0]??E(e)??"<command>"}function bs(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=U(A(i)),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r),o.push(...i.commands)}for(let i of t.keys()){let r=U(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function ws(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let r=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of i){let c=_n(s,o,r);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function vs(e){return B(e).slice(2).replace(/-/g,"")}function bo(e){return _(e)}function am(e){let t=D(e)?.canonical??mn[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=om[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Cs(e){let t=fa(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function sm(e,t){let n=Cs(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let r=new Set,a=i.source;if(a)for(let c of[a.name,a.package]){let l=Cs(c??"");l.length>0&&r.add(l)}if(r.size===0)continue;[...r].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(i.command)}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function ot(e,t){let n=new Set,o=t??z(e);for(let i of o){i.flag.startsWith("--")&&n.add(B(i.flag));for(let r of i.aliases??[])r.startsWith("--")&&n.add(B(r))}return[...n].sort((i,r)=>i.localeCompare(r))}function cm(e,t){if(!e.startsWith("--"))return[];let n=vs(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=vs(r);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){i.push({flag:r,rank:0,distance:a.length-n.length});continue}let s=_n(n,a,o);s===null||s<=0||i.push({flag:r,rank:1,distance:s})}return i.sort((r,a)=>r.rank!==a.rank?r.rank-a.rank:r.distance!==a.distance?r.distance-a.distance:r.flag.localeCompare(a.flag)).map(r=>r.flag).slice(0,3)}var Gt,lm=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 dm(){if(Gt)return Gt;let e=new Map;for(let t of ze)if(!lm.has(t))for(let n of ot(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Gt=e,Gt}function mm(e,t){if(!e.startsWith("--"))return[];let n=dm().get(B(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(ot(o));return[...new Set(n.filter(r=>r!==o).map(r=>({command:r,sharedFlagCount:ot(r).filter(a=>i.has(a)).length})).sort((r,a)=>r.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-r.sharedFlagCount:r.command.localeCompare(a.command)).map(({command:r})=>D(r)?.canonical??r))]}function um(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let r=i.indexOf("="),a=r>=0?i.slice(0,r):i;if(B(a)!==B(t))continue;let s=[...e];return s[o]=r>=0?`${n}${i.slice(r)}`:n,s}}function pm(e){let t=new Set(e.commandPaths),n=r=>Math.min(ws(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?ws(r,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(r,a)=>{if(!Number.isFinite(a)||!t.has(r))return;let s=o.get(r);(s===void 0||a<s)&&o.set(r,a)};for(let r of e.commandPaths)i(r,n(r));for(let[r,a]of Object.entries(mn))r!=="read"&&i(a,n(r));return[...o.entries()].sort(([r,a],[s,c])=>a!==c?a-c:r.localeCompare(s)).map(([r])=>r)}function fm(e){let t=D(e.normalizedUnknown),n=Ea(e.commandPaths,e.primaryToken),o=pm(e),i=sm(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return Jn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(r=>!e.normalizedUnknown.includes(" ")||r!==e.normalizedUnknown)}function gm(e,t,n){let[o,...i]=e.split(" ");if(n.includes(o)||D(o)!==void 0)return;let r=o.endsWith("s")?o.slice(0,-1):`${o}s`,a=D(r),s=a&&n.includes(a.canonical)?a.canonical:n.includes(r)?r:void 0;if(s===void 0)return;let c=s,l=["package","packages","extension"].includes(s)?[It(ym(t))??""].filter(d=>d.length>0):_m(t,i.length);for(let d of[...i,...l]){let m=`${c} ${d}`,u=D(m);if(!n.includes(m)&&!(u!==void 0&&!u.hidden&&n.includes(u.canonical)))break;c=m}return c}function hm(e,t,n,o){let i=gm(e,t,n),r=Sa(e,n)??i,a=o.length>0||i!==void 0,s=a?[]:Jn(wm(n),n),c=[...new Set([...r?[r]:[],...o.length>0?o:s])].slice(0,3);return{misnestedPath:r,hasConcreteCandidates:a,suggestedPaths:c}}function ym(e){let t=S([...e]);return t===void 0?[]:e.slice(t+1)}function _m(e,t){let n=[],o=S([...e]);for(;o!==void 0;){let i=S(e.slice(o+1));o=i===void 0?void 0:o+1+i,o!==void 0&&n.push(e[o])}return n.slice(t)}function wm(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function vm(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Cm(e,t,n){let o=S([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let r=S(t.slice(o+1));o=r===void 0?void 0:o+1+r}return e}function xs(e,t){if(!e)return;let n=L([...t]);return[...Ee(n),...e.split(" "),"--help"]}function ko(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let r=bs(t,n),a=Cm(i[1],o,r),s=U(a);if(s.length===0||r.length===0)return;let c=_a(s,r);if(c){let R=xs("update",o),O=R.slice(0,-2);return{suggestedRetryCommand:_(R),suggestedRetryArgs:R,unknownCommandExamples:[_(R),...c.examples.map(k=>_([...O,...k]))],unknownCommandNextSteps:c.nextSteps}}let l=am(s);if(l&&!r.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let d=s.split(" ")[0],m=fm({commandPaths:r,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),{misnestedPath:u,hasConcreteCandidates:p,suggestedPaths:f}=hm(s,o,r,m),y=xs(u,o),h=vm(f,p),C=p?`Did you mean: ${f.join(", ")}?`:null;return{...y?{suggestedRetryCommand:_(y),suggestedRetryArgs:y}:{},unknownCommandExamples:y?[_(y),...h.slice(1)]:h,unknownCommandNextSteps:[...C?[C]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...C?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function xm(e){return Array.from(new Set(e))}function bm(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
25
+ `||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function km(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 Sm(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(r=>r.trim().toLowerCase()===n))}function Ne(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=Sm(n,i);if(!r){let a=n.registeredArguments;return a.length>0&&(n.commands.length===0||a[0]?.required===!0)&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=r}return!0}async function Em(e,t,n,o){try{let i=$(process.cwd(),e.path);if(!await Y(X(i)))return{allowedTypes:nt};let r=await F(i),a=e.noExtensions?void 0:le(),s=ce(r,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await St(i,d,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):nt,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:nt}}}function Am(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?xm([...rm(t,n[1]),...cm(n[1],ot(t))]).filter(a=>ba(n[1],a)):void 0,i=n?mm(n[1],t):[],r=n!==null&&ot(t).includes(B(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:r?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Rm(e,t,n){if(!t||!n||n.length===0)return;let o=um(e,t[1],n[0]);return o?bo(o):void 0}function Om(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?km(bm(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=E(t);if(i)return ka(t,i,[o])}function Tm(e,t){if(!/too many arguments/i.test(e))return;let n=S(t),o=V(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,r=t[i+1]?.trim().toLowerCase(),a=t[i+2]?.trim().toLowerCase();if(!r||!a)return;let s=`${r}-${a}`;if(!_s.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[..._s],suggestedRetryCommand:bo(c)}}function Im(e,t,n,o){let i=S(t),r=V(t.slice(i))?.alias??E(t);if(!/unknown option /i.test(e)||r===void 0)return r;let a=D(r)?.canonical??r;return ze.some(s=>s===r)||bs(n,o).includes(a)?r:void 0}async function it(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",s=pe([...i]).argv,c=he(s),l=L(s),d=Im(a,c,t,n),m=bo(c),u=ee(c),p=await Em(l,a,c,d),f=p.allowedTypes,y=ko(a,t,n,c),h=Am(a,d),C=Tm(a,c),R=C?.suggestedRetryCommand??Rm(c,h.match,h.suggestions)??Om(a,c);return{message:a,commandName:d,allowedTypes:f,attemptedCommand:m,normalizedInvocationArgs:[...c],providedOptionFlags:u,unknownOptionSuggestions:h.suggestions,unknownOptionOtherCommands:h.otherCommands.length>0?h.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:h.otherCommands.length>0?h.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:h.otherCommands.length>12||void 0,unknownOptionScope:h.scope,suggestedRetryCommand:R,verifiedCollectionItemId:p.verifiedCollectionItemId,linkedResourceValueList:await $m(a,d,t,c),...C,...y,...o}}async function $m(e,t,n,o){if(!/too many arguments/i.test(e))return;let{resolveUsageValueListRecovery:i}=await import("./chunks/linked-resource-value-list-2655COY2.js");return i(t,n,o)}async function So(e,t,n,o={},i=process.argv.slice(2)){let r=await it(e,t,n,o,i),{message:a,commandName:s,allowedTypes:c,...l}=r,d=L(r.normalizedInvocationArgs).lean,m=fs(a,s,c,l,{lean:d}),u=await _r("help_format",{message:m,command:s,allowed_types:c});return u.handled&&typeof u.result=="string"?u.result:m}async function Eo(e,t,n,o=!1,i={},r=process.argv.slice(2)){let a=await it(e,t,n,i,r),s=Ht(a.message,a.commandName,a.allowedTypes,g.USAGE,a),c=o?Ut(s):s,l=L(a.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?Z(c,d=>`${JSON.stringify(d,null,2)}
26
+ `):c,null,2)}async function ks(e,t,n,o){if(n)return null;let i=e.some(a=>a==="--for"||a.startsWith("--for=")),r=E(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as Pm}from"commander";function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Es(e,t){let n=new Map;for(let o of e){let i=v(o.command);for(let r of t){if(r.layer!==o.layer||r.name!==o.name)continue;let a=v(r.command),s=a.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&i===d){n.set(i,a);break}}}return n}function Ao(e,t,n,o){if(!t||!n)return;let i,r=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 u=d.split(" ");u.length>r&&u.every((p,f)=>l[f]===p)&&(i=m,r=u.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return Lm(a).takesValue}function Wt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function zt(e){return typeof e=="boolean"?e:void 0}function Lm(e){let t=wt(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function Nm(e){let t=Be(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=Ro(e);return n?`${n} ${Oo(e)}`:null}function As(e){let t=[...new Set(e.map(Nm).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
27
27
  Extension-provided flags:
28
28
  ${t.join(`
29
- `)}`}function Es(e){let t=new Map;for(let i of e){let r=v(i.target_command);if(r.length===0)continue;let a=t.get(r)??[];a.push(...i.flags),t.set(r,a)}let n=[...t.entries()].sort(([i],[r])=>i.localeCompare(r)),o=new Map;for(let[i,r]of n){let a=Ss(r);a&&o.set(i,a)}return o}function As(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function bs(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Tm(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 Im(e){let t=new Map;for(let n of e){let o=v(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,r=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:As(o,n.action),description:i,intent:r,examples:bs(n.examples),failure_hints:bs(n.failure_hints),arguments:Tm(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",...n.read_output===void 0?{}:{read_output_declared:!0},source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function Pm(e){let t=new Map;for(let n of e){let o=v(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function $m(e,t,n){let o=new Set;for(let i of e){let r=v(i);r.length>0&&o.add(r)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Nm(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Rs(e,t,n,o=new Map){let i=Im(t),r=Pm(n),a=$m(e,i,r),s=new Map,c=[...a].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Nm(l,i,o)??i.get(l),m=r.get(l)??(d?r.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:As(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Lm(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Os(e,t){for(let n of t.arguments)e.argument(Lm(n),n.description??"Extension argument.")}function Mm(e){if(Gt(e.visible)===!1)return null;let n=Be(e.long),o=zt(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=n&&n.startsWith("--")&&n.length>2?n:null,a=[i,r].filter(s=>s!==null);return a.length>0?a:null}function Eo(e){let t=Mm(e);if(!t)return null;let{value_name:n,value_arity:o}=_t(e),r=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${r}`}function Fm(e){return Eo(e)}function Ao(e){let t=zt(e.description)??"Extension-provided option.",n=[];Gt(e.required)===!0&&n.push("required"),Gt(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function Ts(e,t){let n=Be(t.long),o=zt(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function Ro(e,t){for(let n of t){if(Ts(e,n))continue;let o=Fm(n);if(!o)continue;let i=Ao(n),r=new Am(o,i);if(r.negate=!1,n.list!==!0){e.addOption(r);continue}e.addOption(r.argParser((a,s=[])=>[...Array.isArray(s)?s:[s],a??!0]))}}function Oo(e,t){return Ss(t.filter(n=>!Ts(e,n)))}function Dm(e){let t=Eo(e);if(!t)return null;let n=Be(e.long),o=zt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=_t(e),s=Gt(e.required)===!0;return{flags:t,long:i,short:r,description:Ao(e),takes_value:a.value_arity!=="none",value_required:a.value_arity==="required",value_name:a.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{},owner:"extension",...jm($t(e))}}function jm(e){return e===null?{}:{sdk_option:e}}function To(e){return Te(e.command,Rt({readOutput:e.read_output_declared===!0})).map(t=>({flags:t.takes_value?`${t.flag} <${t.value_name}>`:t.flag,long:t.flag,short:null,description:t.description,takes_value:t.takes_value,value_required:t.value_required,value_name:t.takes_value?t.value_name:null,variadic:!1,required:!1,aliases:[...t.aliases??[]],alias_for:null,owner:"host"}))}function Io(e){return["","Inherited host flags (delivered through context.global):",` ${To(e).map(n=>n.flags).join(", ")}`,` Run pm contracts --command ${e.command} --flags-only --json for each flag's owner and sdk_option key.`].join(`
30
- `)}function Is(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=Dm(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function Ps(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{},...o.owner===void 0?{}:{owner:o.owner},...o.sdk_option===void 0?{}:{sdk_option:o.sdk_option}}:o)}return[...n.values()]}function $s(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:`
29
+ `)}`}function Rs(e){let t=new Map;for(let i of e){let r=v(i.target_command);if(r.length===0)continue;let a=t.get(r)??[];a.push(...i.flags),t.set(r,a)}let n=[...t.entries()].sort(([i],[r])=>i.localeCompare(r)),o=new Map;for(let[i,r]of n){let a=As(r);a&&o.set(i,a)}return o}function Os(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Ss(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Mm(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 Fm(e){let t=new Map;for(let n of e){let o=v(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,r=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Os(o,n.action),description:i,intent:r,examples:Ss(n.examples),failure_hints:Ss(n.failure_hints),arguments:Mm(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",...n.read_output===void 0?{}:{read_output_declared:!0},source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function Dm(e){let t=new Map;for(let n of e){let o=v(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function jm(e,t,n){let o=new Set;for(let i of e){let r=v(i);r.length>0&&o.add(r)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function Um(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Ts(e,t,n,o=new Map){let i=Fm(t),r=Dm(n),a=jm(e,i,r),s=new Map,c=[...a].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Um(l,i,o)??i.get(l),m=r.get(l)??(d?r.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:Os(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function qm(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Is(e,t){for(let n of t.arguments)e.argument(qm(n),n.description??"Extension argument.")}function Hm(e){if(zt(e.visible)===!1)return null;let n=Be(e.long),o=Wt(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=n&&n.startsWith("--")&&n.length>2?n:null,a=[i,r].filter(s=>s!==null);return a.length>0?a:null}function Ro(e){let t=Hm(e);if(!t)return null;let{value_name:n,value_arity:o}=wt(e),r=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${r}`}function Gm(e){return Ro(e)}function Oo(e){let t=Wt(e.description)??"Extension-provided option.",n=[];zt(e.required)===!0&&n.push("required"),zt(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function $s(e,t){let n=Be(t.long),o=Wt(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function To(e,t){for(let n of t){if($s(e,n))continue;let o=Gm(n);if(!o)continue;let i=Oo(n),r=new Pm(o,i);if(r.negate=!1,n.list!==!0){e.addOption(r);continue}e.addOption(r.argParser((a,s=[])=>[...Array.isArray(s)?s:[s],a??!0]))}}function Io(e,t){return As(t.filter(n=>!$s(e,n)))}function zm(e){let t=Ro(e);if(!t)return null;let n=Be(e.long),o=Wt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=wt(e),s=zt(e.required)===!0;return{flags:t,long:i,short:r,description:Oo(e),takes_value:a.value_arity!=="none",value_required:a.value_arity==="required",value_name:a.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{},owner:"extension",...Wm(Lt(e))}}function Wm(e){return e===null?{}:{sdk_option:e}}function $o(e){return Te(e.command,Ot({readOutput:e.read_output_declared===!0})).map(t=>({flags:t.takes_value?`${t.flag} <${t.value_name}>`:t.flag,long:t.flag,short:null,description:t.description,takes_value:t.takes_value,value_required:t.value_required,value_name:t.takes_value?t.value_name:null,variadic:!1,required:!1,aliases:[...t.aliases??[]],alias_for:null,owner:"host"}))}function Po(e){return["","Inherited host flags (delivered through context.global):",` ${$o(e).map(n=>n.flags).join(", ")}`,` Run pm contracts --command ${e.command} --flags-only --json for each flag's owner and sdk_option key.`].join(`
30
+ `)}function Ps(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=zm(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function Ls(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{},...o.owner===void 0?{}:{owner:o.owner},...o.sdk_option===void 0?{}:{sdk_option:o.sdk_option}}:o)}return[...n.values()]}function Ns(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:`
31
31
  Extension command metadata:
32
32
  ${t.join(`
33
- `)}`}function Po(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 rt(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Po(o).includes(n))??null}function oe(e,t){let n=e;for(let o of t){let i=rt(n,o);if(!i)return null;n=i}return n}var Wt=new WeakSet;function at(e){return Wt.has(e)}function Ns(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&M.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=rt(n,i);if(r){n=r;continue}let a=n.command(i);Wt.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Um(e,t){let n=t.join(" "),o=M.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=rt(i,a);if(!s)return null;r.push(a);let c=s.commands.length>0||M.some(l=>l.canonical.startsWith(`${r.join(" ")} `));if(!Wt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function qm(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Um(e,r),s=oe(e,r),c=M.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Wt.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let l=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${l}`}function Ls(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=qm(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Ms(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import Me from"node:path";async function $o(e,t={},n=[]){let o={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:un,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let c=(r.effective??[]).find(u=>u.layer===s.layer&&u.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(U).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),d=n.map(U),m=l.some(u=>d.some(p=>p===u||p.startsWith(`${u} `)));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(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function Fs(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await $o(t,n,o),r={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:un,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(Me.resolve(a)===Me.resolve(t))return i;let[s,c]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[l,d]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(p=>p.activation?.commands??[])),u=[...new Set(d.loaded.flatMap(p=>p.activation?.commands??[]))].filter(p=>!m.has(p)).sort((p,f)=>p.localeCompare(f));if(u.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Me.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${Me.resolve(a)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${u.length} workspace command path(s): ${u.slice(0,8).join(", ")}${u.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Me.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${Me.resolve(t)} install <package> --project".`})}catch{}return i}var Ds={core:0,standard:1,full:2,internal:3};function js(e,t,n=!0){let o=t.get(H(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,c)=>Ds[c.tier]<Ds[s]?c.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function Us(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(H(o)!==o||!ze.some(i=>i===o)&&!Ot(o)&&!Xe(o)&&!Le(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=oe(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function Hm(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function qs(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 Gm(e){let t=new Map;for(let n of e){let o=n,i=qs(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function zm(e){return _(e)}function Wm(e){let t=e.options??[],n=Gm(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=qs(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),d=a.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,u=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),p=r.includes("<"),f=p||r.includes("["),y={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:f,value_required:p,value_name:Hm(r),variadic:i.variadic===!0,required:u,aliases:l,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function Bm(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 i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Vm(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function Jm(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(ye(r)??Q(r.name()))!=="internal").map(r=>{let a=U(A(r)),s=a,c=ye(r),l=js(a,t,c!==void 0),d=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Po(r),description:r.description().trim(),tier:l?.tier??c??Q(s),family:l?.family??Nt(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function Km(e,t,n){if(!n)return t;let o=n.examples??[],i=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"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function Ym(e,t,n,o,i){let r=e!==void 0&&ro(e)===Pe,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ba(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Km(n,a,o),intentSource:s}}function Xm(e,t){return e===void 0?null:t?.tier??Q(e)}function Zm(e,t){return e===void 0?null:t?.family??Nt(e)}function Qm(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Us(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function eu(e,t,n,o,i=new Map,r=!1){if(!e){let s=Vm(t),c=Jm(t,i,r),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...Et.filter(({parent:d,action:m})=>d===n&&!l.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Q(n.split(" ")[0]),family:Nt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:l,value_kind:d,polymorphic:m})=>({name:s,required:c,variadic:l,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&a.has(s)||c.some(l=>a.has(l))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:l})=>{let d=l?`${s}...`:s;return c?`<${d}>`:`[${d}]`})].join(" ")}}function tu(e,t){return t!==void 0&&at(e)?{inherited_options:To(t)}:{}}function nu(e,t,n,o,i){let r=io(n),a=ae(n),s=U(A(t)),c=U(o.join(" ")),l=c.length>s.length?c:s,d=Xe(l),m=d?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(H(u)):void 0,y=u?js(u,i,ye(t)!==void 0):void 0,{narrative:h,intentSource:C}=Ym(u,t.description().trim(),r,f,d!==void 0),R=Bm(Ps(Wm(t),Is(f))),O=eu(d,t,m,R,i,a),k=Qm(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:Xm(p,y),capability_family:Zm(p,y),description:d?.description??t.description(),usage:O.usage,intent:d?.description??h.intent,intent_source:C,examples:d?[d.example]:h.examples,tips:d?[At(d.accepted_flags)]:h.tips,arguments:O.arguments,options:O.options,...tu(t,f),subcommands:O.subcommands,has_subcommands:O.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function Hs(e,t,n,o=t){let i=N(t);if(!i.json)return!1;let r=$(t);if(!r.requested)return!1;let a=Us(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=he(t),c=`unknown command '${he(r.commandPathTokens).join(" ")}'`,l=xo(c,e,n,s),d=qt(c,"help",nt,g.USAGE,{...l,attemptedCommand:zm(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(d,u=>`${JSON.stringify(u,null,2)}
33
+ `)}`}function Lo(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 rt(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Lo(o).includes(n))??null}function oe(e,t){let n=e;for(let o of t){let i=rt(n,o);if(!i)return null;n=i}return n}var Bt=new WeakSet;function at(e){return Bt.has(e)}function Ms(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&M.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=rt(n,i);if(r){n=r;continue}let a=n.command(i);Bt.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Bm(e,t){let n=t.join(" "),o=M.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=rt(i,a);if(!s)return null;r.push(a);let c=s.commands.length>0||M.some(l=>l.canonical.startsWith(`${r.join(" ")} `));if(!Bt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function Vm(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Bm(e,r),s=oe(e,r),c=M.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bt.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let l=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${l}`}function Fs(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=Vm(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Ds(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import Me from"node:path";async function No(e,t={},n=[]){let o={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:pn,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let c=(r.effective??[]).find(u=>u.layer===s.layer&&u.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(U).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),d=n.map(U),m=l.some(u=>d.some(p=>p===u||p.startsWith(`${u} `)));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(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function js(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await No(t,n,o),r={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:pn,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(Me.resolve(a)===Me.resolve(t))return i;let[s,c]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[l,d]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(p=>p.activation?.commands??[])),u=[...new Set(d.loaded.flatMap(p=>p.activation?.commands??[]))].filter(p=>!m.has(p)).sort((p,f)=>p.localeCompare(f));if(u.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Me.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${Me.resolve(a)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${u.length} workspace command path(s): ${u.slice(0,8).join(", ")}${u.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Me.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${Me.resolve(t)} install <package> --project".`})}catch{}return i}var Us={core:0,standard:1,full:2,internal:3};function qs(e,t,n=!0){let o=t.get(G(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,c)=>Us[c.tier]<Us[s]?c.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function Hs(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(G(o)!==o||!ze.some(i=>i===o)&&!Tt(o)&&!Xe(o)&&!Ne(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=oe(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function Jm(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Gs(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 Km(e){let t=new Map;for(let n of e){let o=n,i=Gs(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function Ym(e){return _(e)}function Xm(e){let t=e.options??[],n=Km(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=Gs(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),d=a.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,u=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),p=r.includes("<"),f=p||r.includes("["),y={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:f,value_required:p,value_name:Jm(r),variadic:i.variadic===!0,required:u,aliases:l,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function Zm(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 i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Qm(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function eu(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(ye(r)??Q(r.name()))!=="internal").map(r=>{let a=U(A(r)),s=a,c=ye(r),l=qs(a,t,c!==void 0),d=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Lo(r),description:r.description().trim(),tier:l?.tier??c??Q(s),family:l?.family??Nt(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function tu(e,t,n){if(!n)return t;let o=n.examples??[],i=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"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function nu(e,t,n,o,i){let r=e!==void 0&&so(e)===$e,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ja(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:tu(n,a,o),intentSource:s}}function ou(e,t){return e===void 0?null:t?.tier??Q(e)}function iu(e,t){return e===void 0?null:t?.family??Nt(e)}function ru(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Hs(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function au(e,t,n,o,i=new Map,r=!1){if(!e){let s=Qm(t),c=eu(t,i,r),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...At.filter(({parent:d,action:m})=>d===n&&!l.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Q(n.split(" ")[0]),family:Nt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:l,value_kind:d,polymorphic:m})=>({name:s,required:c,variadic:l,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&a.has(s)||c.some(l=>a.has(l))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:l})=>{let d=l?`${s}...`:s;return c?`<${d}>`:`[${d}]`})].join(" ")}}function su(e,t){return t!==void 0&&at(e)?{inherited_options:$o(t)}:{}}function cu(e,t,n,o,i){let r=ao(n),a=ae(n),s=U(A(t)),c=U(o.join(" ")),l=c.length>s.length?c:s,d=Xe(l),m=d?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(G(u)):void 0,y=u?qs(u,i,ye(t)!==void 0):void 0,{narrative:h,intentSource:C}=nu(u,t.description().trim(),r,f,d!==void 0),R=Zm(Ls(Xm(t),Ps(f))),O=au(d,t,m,R,i,a),k=ru(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:ou(p,y),capability_family:iu(p,y),description:d?.description??t.description(),usage:O.usage,intent:d?.description??h.intent,intent_source:C,examples:d?[d.example]:h.examples,tips:d?[Rt(d.accepted_flags)]:h.tips,arguments:O.arguments,options:O.options,...su(t,f),subcommands:O.subcommands,has_subcommands:O.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function zs(e,t,n,o=t){let i=L(t);if(!i.json)return!1;let r=P(t);if(!r.requested)return!1;let a=Hs(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=he(t),c=`unknown command '${he(r.commandPathTokens).join(" ")}'`,l=ko(c,e,n,s),d=Ht(c,"help",nt,g.USAGE,{...l,attemptedCommand:Ym(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(d,u=>`${JSON.stringify(u,null,2)}
34
34
  `):d;ie(`${JSON.stringify(m,null,2)}
35
- `)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=nu(e,a,t,r.commandPathTokens,n),c=$(o).commandPathTokens;s.requested_path=c;let l=D(c.join(" "));l&&(s.resolved_path=l.canonical),a===e&&!ae(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Yi(`${JSON.stringify(s,null,2)}
36
- `)}return process.exitCode=g.SUCCESS,!0}function ou(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(`
37
- `)}function iu(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)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function ru(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function au(e,t,n,o){let i=new Set(n),r=o.filter(c=>!i.has(c)),a=c=>c.length>0?c.map(l=>mn("create",l)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(pa).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function su(e,t,n){let o=Jr(n);if(!o)return ou(e,t);let i=Oi(o,t);if(!i){let y=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${y}`].join(`
38
- `)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(y=>y==="--create-mode"||y.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=ru(e,i),m=yt(i,e,d.progressive),u=yt(i,e,l?d.strict:d.progressive),p=y=>y.length>0?y.map(h=>mn(e,h)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${p(u.required)}`,` disabled: ${p(u.disabled)}`,` hidden: ${p(u.hidden)}`];if(e==="create"){let y=yt(i,e,d.strict);au(f,i,m.required,y.required)}return iu(f,i),u.errors.length>0&&f.push(` config errors: ${u.errors.join("; ")}`),f.join(`
39
- `)}function Gs(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let i=rt(e,o);i&&i.addHelpText("after",su(o,t,n))}function cu(e,t){let n=Ve(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function lu(e){return Ve(e.status)?.toLowerCase()??"pending"}function du(e){return e.mandatory===!0}function mu(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 Bs(e){let t=[];return e.forEach((n,o)=>{if(!du(n.definition))return;let i=lu(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:cu(n.definition,o),status:i})}),t.sort(mu),t}function zs(e){return Array.isArray(e)&&e.length>0}var uu=new Set(["create","beads import","todos import"]),pu=new Set(["restore","update","close","delete","append","claim","release"]),fu=new Set(["comments","notes","learnings"]),gu=new Set(["files","docs","test"]),hu=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 No(e,t){let n=t.force===!0;return uu.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:pu.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:fu.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:gu.has(e)?{isMutation:zs(t.add)||zs(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function yu(e,t,n){if(No(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return $r(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>hu.has(i.trim().toLowerCase())):!1}function Ws(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function _u(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Ve(t[1])||i.push("source"),Ve(n.to)||i.push("--to"),i.length!==0)throw new I(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.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:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function wu(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Ws(n.status)!==Ws(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ce(i,le()),s=await kt(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await vr(s,{schema:i.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)||x(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function Lo(e,t,n,o,i){if(!yu(e,t,n)||(_u(e,t,n),!await Y(X(i))))return;let r=await Re(i);Ea(o.json===!0)||await wu(e,t,n,i,r.settings);let a=Pr({author:wt(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)fe(s)}function Vs(e,t,n){if(n.length===0)return;let o=No(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new I(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function Mo(e,t,n,o){if(!No(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await Y(X(n)))return;let{settings:r,metadata:a,warnings:s}=await Re(n);for(let c of s)fe(c);if(!_r(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(yr(r),await wr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=ce(r,le());await Nr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function Fo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function De(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of Fo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,H(i)]))]}function Do(e,t){let n=v(e);if(n.length===0)return!1;let o=De(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Vt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...L(n.commands),...L(n.command_handlers),...L(n.command_overrides),...L(n.flag_commands),...L(n.parser_overrides),...Js(n.preflight_ownership),...Js(n.renderer_ownership)]:[]}function L(e){return e??[]}function Js(e){return L(e).flatMap(t=>t.commands)}function st(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Ks=new Set(["hooks","parser","preflight","renderers"]),Ys=new Set(["commands","schema","services","importers"]),vu=new Set(["reindex","search","search-advanced"]),Cu=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function jo(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return vu.has(n??t)}function Uo(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 Jt(e){return v(e.commandPath??"")==="create"&&Uo(e,Cu)}function qo(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Bt(e,t){return e.some(n=>Do(n,t))||Jt(t)&&qo(e)}function Ho(e){return[L(e.hooks).length,(e.preflight_overrides??0)-L(e.preflight_ownership).length,L(e.item_types).length,L(e.item_fields).length,L(e.relationship_kinds).length,L(e.service_overrides).length,L(e.assurance_providers).length,L(e.renderer_overrides).length-L(e.renderer_ownership).length].some(n=>n>0)}function Go(e,t){let n=e.activation?.commands??[];if(n.length>0)return Bt(n,t);let o=Vt(e);if(Bt(o,t)||st(e).has("search")&&jo(t.commandPath))return!0;if(e.contributions)return Ho(e.contributions)}function Kt(e,t){let n=Go(e,t);if(n!==void 0)return n;let o=st(e);return!!(Fe(o,Ks)||Fe(o,Ys))}function ct(e,t){return e.effective.length===0?!1:lt(t)!=="all"?e.effective.some(o=>Kt(o,t)):e.effective.some(o=>{let i=st(o);return Vt(o).length>0||Fe(i,Ks)||Fe(i,Ys)||i.has("search")})}function lt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=De(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Jt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function zo(e){return lt(e)==="all"?void 0:t=>Kt(t,e)}function je(e){let t=$(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=j(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Wo(e){let t=e.args.map(String);if(v(A(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Yt=Symbol.for("pm.readOutputInvocationProvenance"),xu=new Map(ue.filter(e=>e.reservation_scope==="root_only").map(e=>[$t({long:e.flag}),e.flag]));function se(e,t){let n=Reflect.get(e,Yt);n!==void 0&&Reflect.set(t,Yt,n)}function Bo(e,t,n){let o=qi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(ee(r.slice(2))),s=Ui.find(d=>d.command===o),c=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,Yt);Reflect.set(n,Yt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),se(n,e)}function bu(e){let t=e.optsWithGlobals(),n=A(e);if(H(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of i.options){let a=r.attributeName(),s=i.getOptionValueSource(a)==="cli";if(s&&!e.options.some(c=>c.long===r.long))throw new I(`Unknown option '${r.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:r.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(a)!=="cli"){let c=i.getOptionValue(a);e.setOptionValueWithSource(a,c,"cli")}a in o?t[a]=o[a]:delete t[a]}return t}function Vo(e,t,n,o){Bo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Vi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;se(o,e);let s=Bi(t);for(let l of a){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=r.length>0?r.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Pt(e,n)}function Ue(e,t,n=[],o){let r={...bu(e)};se(e,r),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,delete r.expectHash;let a=ia(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=Hn(n),c=G(A(e)).map(u=>({long:u.flag,short:u.short,aliases:u.aliases})),l={...a};for(let u of s)r[u]!==void 0&&(l[u]=r[u]);Gn(l,[...c,...n],A(e),o);let d=sa(a,nc(e),n),m=oa(r,n,d,A(e));return se(r,m),m}return r}function Qs(e,t,n){let o=Hn(t.map(({long:a})=>({long:a}))),i=[...xu].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new I(`Unknown option '${r}' for extension command '${n}'. ${r} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:r,required:`Remove ${r}, or use it on the root command (pm --help ${r}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function dt(e,t,n){let o=Qe(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=Qe(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function Xt(e){return e.arguments??[]}function Xs(e){let t=Xt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Jo(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}var ec=Symbol("pm.commandOptionTokens"),Zs=Symbol("pm.capturesOptionTokens");function tc(e){if(Reflect.get(e,Zs)===!0)return;Reflect.set(e,Zs,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,ec,[...n]),t(n))}function ku(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function Su(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function nc(e){let t=[];for(let o=e;o?.parent;o=o.parent)t.unshift(o);let n=[];for(let o of t){let i=Reflect.get(o,ec);if(i===void 0)continue;let r=ku(o),a=[];for(let s=o;s;s=s.parent)a.push(s);n.push({tokens:i,optionOf:s=>r.get(s),includesLooseFlags:o===e,negativeNumbersAreValues:!a.some(s=>s.options.some(c=>c.short!==void 0&&/^-\d$/u.test(c.short))),...Su(o)})}return n}function oc(e,t,n){t.length!==0&&aa(nc(e),t,n)}function Ko(e,t){let n=Xt(e),o=n.filter(c=>c.required).length,r=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new I(`Missing required argument for extension command '${e.command}'. Usage: ${Xs(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new I(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Xs(e)}${s}`,g.USAGE)}}function Eu(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Zt(e,t){return{definitions:e,inheritedFlags:Rt({readOutput:t}).map(n=>n.flag)}}function Au(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map(Eu);if(o.length===0)return;let{inheritedFlags:i}=Zt([],n);throw new I(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Ru(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Gn(t,n,e.command,Zt(n,o));return}Au(t,e.command,o)}function Yo(e,t,n,o){e&&(Ko(e,t),Ru(e,n,o))}import{Command as ic}from"commander";var Ou=new Set(["--version","-V"]);function mt(e){let t;try{t=pe(e).argv}catch{return!1}let n=Vr(t),o=S(n);return o===void 0?!1:["package","packages","extension"].includes(n[o])&&["inventory","list"].includes(Tt(n.slice(o+1))??"")}function rc(e){if(j(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new ic().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of ue)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Tu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Xo=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"]),ac=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Iu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Pu=new Set(["claim","close-task","pause-task","release","start-task","test"]),xe={setup:!0,listQuery:!0,mutation:!0,operation:!0},$u=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 ut(e){return e.some(t=>Ou.has(t))}function Nu(e,t){if(!M.some(o=>o.canonical_argv[0]===t))return;let n=new ic().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Te(t,G(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let r of[o.flag,o.short,...o.aliases??[]])r!==void 0&&n.option(`${r}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return xe;let i=V([t,...o.operands])?.alias;if(M.some(r=>r.alias===i))return{...xe,targetCommandName:i}}catch{return xe}}function Zo(e){if(ut(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||$(e).requested)return xe;let t=E(e);if(!t)return xe;let n=t.trim().toLowerCase(),o=j(e),i=V(o)?.alias;if(M.some(a=>a.alias===i))return{...xe,targetCommandName:i};let r=Nu(o,n==="ctx"?"context":n);return r||(Tu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Xo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:ac.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Iu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:xe)}function Qo(e){return e.length===0||$(e).requested||e.includes("--explain")&&E(e)===void 0}function ei(e,t){return mt(t)||ut(t)?!1:ae(t)||$(t).requested?!0:!!E(t)}function ti(e){if(ut(e))return!1;let t=E(e);return t?$u.has(t):!1}function Lu(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),r=i?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${i}${l.slice(d)}`:i:l}):e.argv,a=We(r),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ni(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),i=o.length>0?o.join(" "):"the canonical flag",r=ac.has(t)||Pu.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=Lu({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new I(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:a,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}var Mu=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"]),Fu=new Set(["parse","preflight","execute","unknown"]),Du=new Set(["usage","validation","conflict","runtime","unknown"]);function be(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function oi(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Qt(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 ii(e){if(!e)return;let t=e.trim().toLowerCase();if(Mu.has(t))return t}function ri(e){if(!e)return;let t=e.trim().toLowerCase();if(Fu.has(t))return t}function ai(e){if(!e)return;let t=e.trim().toLowerCase();if(Du.has(t))return t}function si(e){let t=be(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(oi(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=Qt(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>gn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function ci(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function li(){let e=gn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Qt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=ma(o),r=be(e,"error_code","errorCode")??ci(i,o),a=ai(be(e,"error_category","errorCategory"))??(i?void 0:ht(r)),s=i?void 0:si(e)??`command_exit_${o}`,c=ii(be(e,"command_resolution","commandResolution"))??St({ok:i,errorCode:r,errorCategory:a}),l=ri(be(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,command_resolution:c,resolution_stage:l}}var di="PM_CLI_PACKAGE_ROOT",hc=Symbol("pm.deprecatedAliasInvocation"),nn=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=nn.get(t)??[];n.push(e),nn.set(t,n)}for(let e of nn.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function ju(){return tr(import.meta.url,["../.."])}(typeof process.env[di]!="string"||process.env[di]?.trim().length===0)&&(process.env[di]=ju());var Se=null,q=null,on=null;function Uu(e){Se=e}function qu(e){T=e}var pt=null,ke=null,T=new Map,yi=250,Hu=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Gu=new Set(["1","true","yes","on"]),zu=Ye(()=>import("./chunks/register-setup-EWAZZWPL.js")),Wu=Ye(()=>import("./chunks/register-list-query-FCPGG2UT.js")),Bu=Ye(()=>import("./chunks/register-mutation-VD3JX23I.js")),Vu=Ye(()=>import("./chunks/register-operations-KHJD4GFZ.js"));function tn(e){return _(e)}function yc(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=>ge(o)??o))];return n.length>0?n:void 0}function Ju(e,t,n,o){if(n?.suggested_retry||o===no||o===to||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=ee(t),r=new Set(i.map(m=>ge(m)??m)),a=yc(e),s=t.find(m=>w.commands.some(u=>u.name()===m)),c=s?w.commands.find(m=>m.name()===s):void 0,l=new Set([...w.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(u=>ge(u)).filter(u=>u!==void 0))),d=a?.filter(m=>{let u=ge(m)??m;return r.has(u)?!1:l.has(u)||So(t,s,u,T)!==void 0});return d&&d.length>0?d:void 0}function Ku(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?ge(i):void 0,a=e.find(u=>w.commands.some(p=>p.name()===u)),s=a?w.commands.find(u=>u.name()===a):void 0,c=r?s?.options.find(u=>u.flags.split(/[ ,|]+/).includes(r)):void 0,l=So(e,a,r,T),d=r?c?.isBoolean()===!0||l===!1?[r]:[r,"<value>"]:[],m=r?tn([...e,...d]):t;return m===t?void 0:m}function Yu(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!==void 0&&(o==="allowed_values"||i!==null)&&(n[o]=i)}return n}function Xu(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,...Yu(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function sc(e,t){return{...e,recovery:t}}function Zu(e,t){if(t===void 0)return;let n=Fa(e,t.code,t.field,$a(e,t.code,t.recovery)),o=Qu(e),i=Da(e,t.code,t.field,n,o),r=La(e,t.code,i,o,()=>Ur(P(process.cwd(),N(e).path)));return ja(e,t.code,r,o)}var cc=" ";function Qu(e){let t=e.map(i=>i===""?cc:/^--(?:pm-)?path=$/u.test(i)?`${i}${cc}`:i),n=N(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Ee({});return n!==void 0&&o.length>0?null:o}function _c(e,t,n){let o=We(t),i=j(o),r=S(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:xr(e);let l=Zu(o,e),d=l&&(a==="history-redact"||a==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:tn(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:tn(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return sc(e,d);let m=tn(o),u=ee(o),p=Ju(n,o,d,e?.code),f=Ku(o,m,p,d),y=Xu({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:d});return sc(e,y)}async function ft(e){let t=q;q=null,await Ua(t,e);let n=Se;if(Se=null,!n){Ct();return}let o=[],i=fr();try{await qa({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await rr(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:de(),affected:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{Ct()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${W(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${W(o)}`)}async function wc(e,t){await Er();let n=q,o=Se,i=n?.command??o?.commandName??e,r=n??An(o?.globalOptions??t),a=T.get(v(i))?.source;$n(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??He,extension:a})}function vc(e){return Gu.has((process.env[e]??"").trim().toLowerCase())}function Cc(e){return vc("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Hu.has(Math.trunc(e))}async function rn(e,t){return Cc(e.exit_code)?(await wc(e.command,t),Ir({...e,source_context:e.source_context??An(t).source_context}),!0):!1}async function xc(e){let t=J(me(e.error)),n=gs(t);e.bootstrapGlobal.json?x(JSON.stringify(et(ps(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await wc(e.attemptedCommand,e.bootstrapGlobal),Nn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,await cn(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to report error: ${me(r)}`)}try{await ft({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to run error hooks: ${me(r)}`)}try{await Oe()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${me(r)}`)}}var ep={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"},mi=new Map;function ui(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function bc(e,t){return e.options.some(n=>n.long===t)}function kc(e,t){return e.options.some(n=>n.short===t)}function pi(e,t,n,o){let i=t.trim();if(!i||!Li(i))return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(kc(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,qn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!bc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,qn);return}e.option(`${a} <value>`,r)}}async function Sc(e,t){let n=ep[e];if(!n)return[];let o=`${t}:${n}`,i=mi.get(o);if(i)return i;if(!await Y(X(t)))return mi.set(o,[]),[];let r=await F(t),s=(yn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:ui(c.type),value_type:ui(c.type)})));return mi.set(o,s),s}async function Ec(e,t){let n=N(t),o=P(process.cwd(),n.path);if(!await Y(X(o)))return;let i=ke?.key===vi(o)?ke.snapshot:null,r=i===null?await F(o):i.settings,a=yn(r.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=oe(e,c.path.split(" "));if(l)for(let d of a.command_to_fields.get(c.command)??[]){let m=d.description??"";pi(l,d.cli_flag,m,d.repeatable);for(let u of d.cli_aliases)pi(l,u,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function _i(e,t,n,o,i){let r=E(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await F(t),s=ce(a,o);Gs(e,s,n)}catch{}}function fi(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Ac(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function wi(e){return e.some(t=>t==="--profile")}function vi(e){return`pm-root:${e}`}function gi(e){for(let t of e)t.startsWith("settings_read_")&&fe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Rc(e,t){e.profile&&(x(`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&&x(`profile:extensions activation_warnings=${W(t.activationWarnings)}`))}function an(e,t,n){if(!e)return;let o=v(n.commandPath??"")||"<none>";x(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function sn(e,t=Re){let n=vi(e);if(ke?.key===n)return ke.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await ar({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return ke={key:n,snapshot:s},s}catch{return ke={key:n,snapshot:null},null}}async function Ge(e,t,n=F){let o=t?lt(t):"all",i=Ac(e,o);if(pt?.key===i)return pt.snapshot;try{let r=await n(e),a=await Je({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?zo(t):void 0}),s=await Ke({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(p=>v(p.command)))].filter(p=>p.length>0).sort((p,f)=>p.localeCompare(f)),l=Es(s.registrations.flags),d=ks(s.commands.handlers,s.registrations.commands),m=Rs(c,s.registrations.commands,s.registrations.flags,d),u={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:r,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:p,module:f})=>({name:p,module:f}))};return pt={key:i,snapshot:u},u}catch{return pt={key:i,snapshot:null},null}}async function Oc(e){let t=Ze(e);if(t.noExtensions){let a=P(process.cwd(),t.path);return await Y(X(a))&&gi((await Re(a)).warnings),null}let n=P(process.cwd(),t.path),o=await sn(n);if(!o)return null;gi(o.settingsReadWarnings);let i={commandPath:A(e),commandArgs:Wo(e)};if(!ct(o.discovery,i))return an(t.profile,o,i),null;let r=await Ge(n,i);return r?(Rc(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function Ci(e){let t=await Ge(e);return t?new Map(t.commandDescriptors):T}async function tp(e,t){return!e.requested||t.noExtensions||Le(w,e.commandPathTokens)?T:Ci(P(process.cwd(),t.path))}async function Tc(e,t){return(await Wr({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 Ic(e,t,n){let o=t.author;return zr(e,ga.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Pc(e,t,n,o=[]){let i=A(e),r=zn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=P(process.cwd(),n.path),l={args:[...r],path:n.path},d=await xt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&x(`profile:extensions parser_warnings=${W(d.warnings)}`),r=d.context.args,a=d.context.options,s=d.context.global,Xn(l,{args:r,path:s.path},a),Yo(T.get(v(i)),r,a,o),Ae(void 0),vt({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await En({command:i,args:r,options:a,global:s,pm_root:c,sdk:Ic(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${W(m.warnings)}`),!m.handled)throw m.warnings.length>0?Ar(i,m):new I(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Ae(m.result),m.result}var lc=Symbol("pm.wrappedActionHandler");function np(e,t){let n=e[e.length-1];return n instanceof hi?n:t}function dc(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${W(n)}`)}function op(e){let t=T.get(v(e.commandPath));if(!t||!Jo(e.activeRegistrations,e.commandPath))return;let n=Xt(t).length===0?ra(e.commandArgs):zn(e.commandArgs,e.extensionFlagDefinitions);Ko(t,n)}function ip(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 xi(e,t,n){if(!at(e))return;let o=T.get(v(t))?.read_output_declared===!0;return Zt(n,o)}function $c(e){let t=n=>{let o=n;if(tc(n),typeof o._actionHandler=="function"&&o[lc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=np(a,n),c=Date.now();Un(s);let l=Ze(s),d=H(A(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return Ta(d,l.expectHash),await i.apply(this,a);let m=P(process.cwd(),l.path),u=s.args.map(String),p=le(),f=p?dt(p,d,u):[],y=await Sc(d,m),h=xi(s,d,f),C=Ue(s,u,[...f,...y],h);oc(s,f,d),T.has(v(d))&&delete C.author,h!==void 0&&Qs(C,f,d);let R={args:[...u],path:l.path},O=await xt({command:d,args:u,options:C,global:l,pm_root:m});dc(l.profile,"parser_warnings",O.warnings),u=O.context.args,C=O.context.options,se(s,C),l=O.context.global,Xn(R,{args:u,path:l.path},C),op({activeRegistrations:p,commandPath:d,commandArgs:u,extensionFlagDefinitions:f}),l=await ta(l),Pt(s,l),ip(s,a,u),It(s,C),Ae(void 0),vt({command:d,args:u,options:{...C},global:{...l},pm_root:m});let k=await En({command:d,args:u,options:C,global:l,pm_root:m,sdk:Ic(m,l,d)});if(dc(l.profile,"command_handler_warnings",k.warnings),k.handled){Ae(k.result),kn(k.result,{...l,command:d,commandArgs:u,commandOptions:C,pmRoot:m}),l.profile&&x(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await i.apply(this,a)},o[lc]=!0}for(let i of n.commands)t(i)};t(e)}async function en(e){T=new Map,re({overrides:[]}),e&&await _i(e.rootProgram,e.pmRoot,e.invocationArgv,or(),e.settings)}function rp(e,t,n,o){if(t?.flags&&t.flags.length>0){Ro(e,t.flags);let i=Oo(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&at(e)&&e.addHelpText("after",Io(t)),o&&e.addHelpText("after",o)}function ap(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Io(n)),o&&e.addHelpText("after",o)}function Nc(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),l=c.length===0?"standard":c.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");Ft(r,l);for(let d of r.commands)i(d,[...a,d.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function Lc(e,t){let n=N(t),o=P(process.cwd(),n.path);if(n.noExtensions){await en({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await sn(o),r=je(t);if(!i){await en();return}if(!ct(i.discovery,r)){await en({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),an(wi(t),i,r);return}let a=await Ge(o,r);if(!a){await en({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),T=new Map(a.commandDescriptors),await _i(e,o,t,a.registrations,a.settings);let s=Ls(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Ms(a.activationWarnings,x,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(R=>R.length>0),u=a.commandDescriptors.get(d),p=oe(e,m),f=a.commandFlagHelp.get(d),y=u?$s(u):null;if(p){rp(p,u,f,y);return}let h=Ns(e,m);u?.description&&h.description(u.description);let C=f;u&&(Os(h,u),u.flags.length>0&&(Ro(h,u.flags),C=Oo(h,u.flags)??void 0)),ap(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let O=R[R.length-1],k=O instanceof hi?O:h,gt=Ze(k),Vc=Date.now(),ln=dt(a.registrations,d,k.args.map(String)),Si=Ue(k,k.args.map(String),ln,xi(k,d,ln)),Ei=await Pc(k,Si,gt,ln);await na(gt,Ei),kn(Ei,{...gt,command:d,commandArgs:k.args.map(String),commandOptions:Si,pmRoot:o}),gt.profile&&x(`profile:command=${d} took_ms=${Date.now()-Vc}`)})};for(let d of s)l(d);Nc(e,c,a.commandDescriptors)}var He=nr(import.meta.url,["../.."])??"0.0.0",w=jn(He);async function mc(e){if(!q)return;let t=Reflect.get(e,hc);typeof t=="string"&&await fa(t)}async function uc(e,t,n){let o=A(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function pc(e,t,n){!q||!await Rn(!0)||($n(e,t,n,{source_context:q.source_context,source_context_source:q.source_context_source}),Rr(e),on=q)}async function cn(e,t,n){let o=on;if(!o)return;on=null;let i=!1;try{let r=await F(o.global_pm_root);i=r.telemetry.enabled&&r.telemetry.installation_id===o.installation_id}catch{}await Rn(i)?Tr(e,t,n):Or()}async function sp(e){let t=await Oc(e);return Sn(t?.registrations??null),t}function Mc(e,t){t&&mt(t)||(e.hook("preAction",async(n,o)=>{Se=null,q=null,on=null,Ct(),Un(o);let i=o.optsWithGlobals(),r=Ze(o),a=H(A(o)),s=o.args.map(String),c={args:[...s],path:r.path},l=Ue(o,s),d={...r},m=P(process.cwd(),r.path),u=await sp(o);if(Wi(a,{...l,...zi(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Vo(o,a,d,l),await uc(o,void 0,()=>Lr(a,d)),!u){Se=sr({commandName:a,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),q=await Ln({command:a,pm_version:He,args:s,options:l,global:d,pm_root:m}),await mc(e),await pc(a,s,l),await Mo(a,l,m,fi()),await Lo(a,s,l,d,m),await Yn({command:o,commandPath:a,commandArgs:s,commandOptions:l,expectHash:r.expectHash,pmRoot:m,globalOptions:d});return}cr(u.hooks),lr(u.commands),dr(u.parsers),mr(u.preflight),re(u.services),ur(u.renderers),Sn(u.registrations);let p=dt(u.registrations,a,s);l=Ue(o,s,p,xi(o,a,p)),Vo(o,a,d,l);let f=await xt({command:a,args:s,options:l,global:d,pm_root:u.pmRoot});d.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${W(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),d=f.context.global;let y={args:[...s],path:d.path};It(o,l);let h=await gr({command:a,args:s,options:l,global:d,pm_root:u.pmRoot,decision:fi()});d.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${W(h.warnings)}`),s=h.context.args,l=h.context.options,se(o,l),d=h.context.global,It(o,l);let C=h.decision;await Mo(a,l,u.pmRoot,C),await Lo(a,s,l,d,u.pmRoot),await Yn({command:o,commandPath:a,commandArgs:c.args,commandOptions:l,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:Kn(c,[y,{args:s,path:d.path}]),globalOptions:{...d,path:r.path,noExtensions:r.noExtensions}});let R=C.run_extension_migrations?await uc(o,[],()=>Tc(u.registrations.migrations,u.pmRoot)):[];d.profile&&R.length>0&&x(`profile:extensions migration_warnings=${W(R)}`);let O=Bs(u.registrations.migrations);Se={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:u.pmRoot,profileEnabled:!!d.profile,migrationBlockers:O},Ae(void 0),vt({command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot}),q=await Ln({command:a,pm_version:He,args:s,options:l,global:d,pm_root:u.pmRoot}),await mc(e),await pc(a,s,l);let k=await ir(u.hooks,{command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot});d.profile&&k.length>0&&x(`profile:extensions hook_warnings=${W(k)}`),C.enforce_mandatory_migration_gate&&Vs(a,l,O)}),e.hook("postAction",async()=>{let n=li();await cn(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await ft(n),await Oe()}))}Mc(w);var fc=Symbol("pmCliIdempotentTopLevelRegistration");function Fc(e){let t=e;if(t[fc])return;t[fc]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new hi(r):n(o,...i)})}async function cp(e,t){if(Fc(e),t.setup){let{registerSetupCommands:n}=await zu();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Wu(),o=typeof t.targetCommandName=="string"&&Xo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Bu();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Vu();n(e)}}function qe(e){return e.rawInvocationArgv??e.invocationArgv}function lp(e){return async t=>{let n=ht(t.errorCode),o=St({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Fr({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:He,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 Dc(e){if(e.bootstrapGlobal.noExtensions||mt(e.invocationArgv))return;let t=je(e.invocationArgv),n=await sn(e.bootstrapPmRoot);if(n&&ct(n.discovery,t)){let o=await Ge(e.bootstrapPmRoot,t);jc(o);return}n&&an(wi(e.invocationArgv),n,t),re({overrides:[]})}function jc(e){if(!e){re({overrides:[]});return}re(e.services)}async function bi(e){await cn(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await ft({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 Uc(){await cn(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await ft({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function qc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof I)&&(In(e.error)||!n))return!1;let o=J(me(e.error)),i=e.error instanceof I?e.error.exitCode:Tn(t),r=e.error instanceof I||Sr(e.error)?e.error.context:void 0,a=_c(r,e.invocationArgv,o),s=ms(o,a),c=et(e.bootstrapGlobal.lean?jt(yo(o,i,a)):yo(o,i,a)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Z(c,p=>`${JSON.stringify(p,null,2)}
40
- `):c,null,2):ls(o,a,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?ie(`${l}
41
- `):x(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),u=await rn({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:q?.source_context},e.bootstrapGlobal);return await bi({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),u&&(Nn(Pn(e.error,o)),await Oe(yi)),process.exitCode=i,!0}async function Hc(e,t){let n=$(e.invocationArgv).commandPathTokens.join(" ")||vo(e.invocationArgv),o=H(n),i=`unknown command '${n}'`,r=P(process.cwd(),e.bootstrapGlobal.path),a=e.bootstrapGlobal.noExtensions?T:await Ci(r),s=je(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await $o(r,{},De(s)),l=await it({message:i},w,a,{failedExtensions:c},qe(e)),d=_o(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:u}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await rn({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:u,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await ko({message:i},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:c},qe(e)):await bo({message:i},w,a,{failedExtensions:c},qe(e)),y=wo(f,e.jsonErrors,c);await bi({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:u,resolutionStage:"parse"}),e.jsonErrors?ie(`${Vn(y)}
42
- `):x(y),p&&await Oe(yi),process.exitCode=g.USAGE}async function Gc(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=$(e.invocationArgv);return i.requested&&!Le(w,i.commandPathTokens)?(await Hc(e,t),!0):(await Uc(),!0)}async function zc(e,t){let n=await it(e.error,w,T,{},qe(e)),o=_o(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:i,commandResolution:r}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await rn({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:r,resolution_stage:"parse",source_context:q?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await ko(e.error,w,T,e.bootstrapGlobal.lean===!0,{},qe(e)):await bo(e.error,w,T,{},qe(e)),c=await Fs(o.code,e.bootstrapPmRoot,{},De(je(e.invocationArgv))),l=wo(s,e.jsonErrors,c);await bi({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?ie(`${Vn(l)}
43
- `):x(l),a&&await Oe(yi),process.exitCode=g.USAGE}function Wc(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 Bc(e){let t=e.error.code,n=String(e.error.message??"");if(!await Gc(e,t,n)){if(t==="commander.version"){await Uc();return}await zc(e,t)}}async function ki(e){let t=N(e.invocationArgv),n=P(process.cwd(),t.path),o=he(e.invocationArgv),i={error:e.error,invocationArgv:o,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:E(o)??"<unknown>",emitTelemetryCommandError:lp({invocationArgv:o,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Dc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await qc(i,On(e.error))){if(Wc(e.error)){await Bc(i);return}await xc({error:e.error,attemptedCommand:i.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:i.emitTelemetryCommandError})}}function dp(e,t,n){let o=n.requested?n.commandPathTokens:j(t),i=V(o);if(i&&!oe(e,[...i.canonical_argv]))throw new gc(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function mp(e,t){let n=S(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=S(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=nn.get(t[n]),i=t.slice(n).filter(a=>!["--global","--project","--local"].includes(a)),r=o?.find(a=>a.alias.split(" ").every((s,c)=>i[c]===s));r?.lifecycle==="deprecated"&&Reflect.set(e,hc,r.alias)}function up(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function pp(e,t){w=jn(He),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(A(a))&&a.optsWithGlobals().dryRun===!0}),Mc(w,e),pt=null,ke=null,T=new Map,pr();let n=[...e],o,i;try{let r=pe(e);n=r.argv,Sa(r.trace),mp(w,e);let a=up(n),s=n.length===0,c=N(n);if(c.authorMissingValue)throw new I("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Qr(c.author),ni(r),i=Br(n);let l=Zo(n);await cp(w,l),ao(w,!0),ei(w,n)?await Lc(w,n):(T=new Map,re({overrides:[]})),ti(n)&&await Ec(w,n),ao(w);let m=$(n);dp(w,n,m),Qo(n)&&Va(w,n),$c(w);let u=await tp(m,c);if(await Hs(w,n,u,e))return;if(m.requested&&!Le(w,m.commandPathTokens))throw new gc(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ae(n)&&E(n)===void 0){w.outputHelp();return}if(mt(n)){await w.parseAsync(a);return}let f=P(process.cwd(),c.path),y=await F(f),h=await xs(n,f,c.noExtensions,Ge);await Ia(C=>Gr({pmRoot:f,packages:h?.contextIntentPackages},()=>Mi({env:{...process.env,PM_PATH:f},argv:a,cwd:process.cwd()},()=>Fi(y.agent_identity.harness_signals,()=>C(()=>w.parseAsync(a)),{probesEnabled:y.agent_identity?.probes_enabled}))))}catch(r){await ki({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function Fh(e=process.argv.slice(2)){let t=e;try{t=pe(e).argv}catch{}await Pi([...e,...t],()=>fp(e,t))}async function fp(e,t){let n=rc(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=()=>Aa(N(t).json,async()=>{try{await ea(process.env,()=>pp(e,o))}catch(a){await ki({error:a,invocationArgv:[...e]})}});if(n!==void 0){let a=P(process.cwd(),N(t).path),s=P(process.cwd(),n.path),c=Ii(process.cwd());await bt(a,()=>bt(s,()=>bt(c,r,i),i),i)}else await r()}var Dh={activationCommandMatchesProbe:Do,applyDynamicExtensionRootHelpVisibility:Nc,bootstrapProfileEnabled:wi,buildBootstrapActivationProbe:je,buildPostActionTelemetryOutcome:li,buildPmCliRecoveryContext:_c,buildRuntimeExtensionDiscoverySnapshotCacheKey:vi,buildRuntimeExtensionActivationScope:lt,buildRuntimeExtensionSnapshotCacheKey:Ac,buildRuntimeExtensionFilterForProbe:zo,addRuntimeFieldOption:pi,collectActivationCommandCandidates:De,collectExtensionFlagDefinitionsForCommand:Qe,collectExtensionFlagDefinitionsForInvocation:dt,collectLeadingCommandArgs:Fo,collectParsedActivationCommandArgs:Wo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Sc,commandHasLongOption:bc,commandHasShortOption:kc,commandPathNeedsSearchExtensions:jo,commandPathNeedsTemplateExtensions:Jt,describeUnknownError:me,defaultPreflightDecision:fi,discoveryNeedsActivationForProbe:ct,emitExtensionProfile:Rc,emitExtensionSkippedProfile:an,emitSettingsReadWarnings:gi,ensureIdempotentTopLevelCommandRegistration:Fc,enforceExplicitRetryForFlagTypos:ni,envFlagEnabled:vc,executeRegisteredRuntimeMigrations:Tc,extractCommandScopedOptions:Ue,extensionActivationCommands:Vt,extensionCapabilities:st,extensionNeedsActivationForProbe:Kt,extensionProvidesTemplatesRuntime:qo,hasAnyCapability:Fe,hasGlobalExtensionContributions:Ho,handleGenericRunPmCliError:xc,handleRunPmCliCommanderError:Bc,handleRunPmCliError:ki,handleRunPmCliHelpDisplayError:Gc,handleRunPmCliKnownError:qc,handleRunPmCliCommanderUsageError:zc,handleUnknownHelpCommandError:Hc,inferMissingFieldsFromErrorMessage:yc,inferPostActionErrorCode:ci,inferPostActionFailureMessage:si,invocationRequestsVersion:ut,isCommanderError:In,loadRuntimeExtensionCommandDescriptorsForRecovery:Ci,loadRuntimeExtensionDiscoverySnapshot:sn,loadRuntimeExtensionSnapshot:Ge,maybeLoadRuntimeExtensions:Oc,maybeAttachCreateUpdatePolicyHelpText:_i,maybeLogHandledCliErrorToSentry:rn,matchesStaticExtensionCommand:Bt,normalizeTelemetryCommandResolution:ii,normalizeTelemetryErrorCategory:ai,normalizeTelemetryResolutionStage:ri,normalizeThrownExitCode:Tn,probeUsesAnyFlag:Uo,prepareExtensionServicesForRunPmCliError:Dc,readRecordBoolean:oi,readRecordNumber:Qt,readRecordString:be,recordCliReadOutputInvocationProvenance:Bo,registerDynamicExtensionCommandPaths:Lc,registerRuntimeSchemaFieldFlags:Ec,resolveCoreCommandRegistrationSelection:Zo,resolveStaticExtensionActivationDecision:Go,resolveUnknownHelpToken:vo,readThrownExitCode:On,runAndClearAfterCommandHooks:ft,runRequiredExtensionCommand:Pc,shouldAttachRichHelpTextForInvocation:Qo,shouldLogHandledErrorToSentry:Cc,shouldRegisterDynamicExtensionPaths:ei,shouldRegisterRuntimeSchemaFlags:ti,shouldHandleRunPmCliCommanderError:Wc,setActiveExtensionHookContextForTest:Uu,setActiveRuntimeExtensionCommandDescriptorsForTest:qu,setRecoveredExtensionServices:jc,toLooseFieldDefinitionType:ui,isImporterOrExporterCommandPath:Jo,validateDynamicExtensionCommandInvocation:Yo,wrapProgramActionsForExtensionHandlers:$c,wrapThrownErrorForSentry:Pn};export{Dh as _testOnly,Fh as runPmCli};
35
+ `)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=cu(e,a,t,r.commandPathTokens,n),c=P(o).commandPathTokens;s.requested_path=c;let l=D(c.join(" "));l&&(s.resolved_path=l.canonical),a===e&&!ae(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Zi(`${JSON.stringify(s,null,2)}
36
+ `)}return process.exitCode=g.SUCCESS,!0}function lu(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(`
37
+ `)}function du(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)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function mu(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function uu(e,t,n,o){let i=new Set(n),r=o.filter(c=>!i.has(c)),a=c=>c.length>0?c.map(l=>un("create",l)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(ga).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function pu(e,t,n){let o=Yr(n);if(!o)return lu(e,t);let i=Ii(o,t);if(!i){let y=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${y}`].join(`
38
+ `)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(y=>y==="--create-mode"||y.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=mu(e,i),m=yt(i,e,d.progressive),u=yt(i,e,l?d.strict:d.progressive),p=y=>y.length>0?y.map(h=>un(e,h)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${p(u.required)}`,` disabled: ${p(u.disabled)}`,` hidden: ${p(u.hidden)}`];if(e==="create"){let y=yt(i,e,d.strict);uu(f,i,m.required,y.required)}return du(f,i),u.errors.length>0&&f.push(` config errors: ${u.errors.join("; ")}`),f.join(`
39
+ `)}function Ws(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let i=rt(e,o);i&&i.addHelpText("after",pu(o,t,n))}function fu(e,t){let n=Ve(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function gu(e){return Ve(e.status)?.toLowerCase()??"pending"}function hu(e){return e.mandatory===!0}function yu(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 Js(e){let t=[];return e.forEach((n,o)=>{if(!hu(n.definition))return;let i=gu(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:fu(n.definition,o),status:i})}),t.sort(yu),t}function Bs(e){return Array.isArray(e)&&e.length>0}var _u=new Set(["create","beads import","todos import"]),wu=new Set(["restore","update","close","delete","append","claim","release"]),vu=new Set(["comments","notes","learnings"]),Cu=new Set(["files","docs","test"]),xu=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 Mo(e,t){let n=t.force===!0;return _u.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:wu.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:vu.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Cu.has(e)?{isMutation:Bs(t.add)||Bs(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function bu(e,t,n){if(Mo(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Nr(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>xu.has(i.trim().toLowerCase())):!1}function Vs(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function ku(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Ve(t[1])||i.push("source"),Ve(n.to)||i.push("--to"),i.length!==0)throw new I(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.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:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function Su(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Vs(n.status)!==Vs(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ce(i,le()),s=await St(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await xr(s,{schema:i.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)||x(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function Fo(e,t,n,o,i){if(!bu(e,t,n)||(ku(e,t,n),!await Y(X(i))))return;let r=await Re(i);Ra(o.json===!0)||await Su(e,t,n,i,r.settings);let a=Lr({author:vt(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)fe(s)}function Ks(e,t,n){if(n.length===0)return;let o=Mo(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new I(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function Do(e,t,n,o){if(!Mo(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await Y(X(n)))return;let{settings:r,metadata:a,warnings:s}=await Re(n);for(let c of s)fe(c);if(!vr(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(wr(r),await Cr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=ce(r,le());await Mr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function jo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function De(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of jo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,G(i)]))]}function Uo(e,t){let n=v(e);if(n.length===0)return!1;let o=De(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Jt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...N(n.commands),...N(n.command_handlers),...N(n.command_overrides),...N(n.flag_commands),...N(n.parser_overrides),...Ys(n.preflight_ownership),...Ys(n.renderer_ownership)]:[]}function N(e){return e??[]}function Ys(e){return N(e).flatMap(t=>t.commands)}function st(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Xs=new Set(["hooks","parser","preflight","renderers"]),Zs=new Set(["commands","schema","services","importers"]),Eu=new Set(["reindex","search","search-advanced"]),Au=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function qo(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Eu.has(n??t)}function Ho(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 Kt(e){return v(e.commandPath??"")==="create"&&Ho(e,Au)}function Go(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Vt(e,t){return e.some(n=>Uo(n,t))||Kt(t)&&Go(e)}function zo(e){return[N(e.hooks).length,(e.preflight_overrides??0)-N(e.preflight_ownership).length,N(e.item_types).length,N(e.item_fields).length,N(e.relationship_kinds).length,N(e.service_overrides).length,N(e.assurance_providers).length,N(e.renderer_overrides).length-N(e.renderer_ownership).length].some(n=>n>0)}function Wo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Vt(n,t);let o=Jt(e);if(Vt(o,t)||st(e).has("search")&&qo(t.commandPath))return!0;if(e.contributions)return zo(e.contributions)}function Yt(e,t){let n=Wo(e,t);if(n!==void 0)return n;let o=st(e);return!!(Fe(o,Xs)||Fe(o,Zs))}function ct(e,t){return e.effective.length===0?!1:lt(t)!=="all"?e.effective.some(o=>Yt(o,t)):e.effective.some(o=>{let i=st(o);return Jt(o).length>0||Fe(i,Xs)||Fe(i,Zs)||i.has("search")})}function lt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=De(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Kt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Bo(e){return lt(e)==="all"?void 0:t=>Yt(t,e)}function je(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=j(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Vo(e){let t=e.args.map(String);if(v(A(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Xt=Symbol.for("pm.readOutputInvocationProvenance"),Ru=new Map(ue.filter(e=>e.reservation_scope==="root_only").map(e=>[Lt({long:e.flag}),e.flag]));function se(e,t){let n=Reflect.get(e,Xt);n!==void 0&&Reflect.set(t,Xt,n)}function Jo(e,t,n){let o=Gi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(ee(r.slice(2))),s=Hi.find(d=>d.command===o),c=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,Xt);Reflect.set(n,Xt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),se(n,e)}function Ou(e){let t=e.optsWithGlobals(),n=A(e);if(G(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of i.options){let a=r.attributeName(),s=i.getOptionValueSource(a)==="cli";if(s&&!e.options.some(c=>c.long===r.long))throw new I(`Unknown option '${r.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:r.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(a)!=="cli"){let c=i.getOptionValue(a);e.setOptionValueWithSource(a,c,"cli")}a in o?t[a]=o[a]:delete t[a]}return t}function Ko(e,t,n,o){Jo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Ki(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;se(o,e);let s=Ji(t);for(let l of a){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=r.length>0?r.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Pt(e,n)}function Ue(e,t,n=[],o){let r={...Ou(e)};se(e,r),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,delete r.expectHash;let a=aa(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=zn(n),c=z(A(e)).map(u=>({long:u.flag,short:u.short,aliases:u.aliases})),l={...a};for(let u of s)r[u]!==void 0&&(l[u]=r[u]);Wn(l,[...c,...n],A(e),o);let d=la(a,ic(e),n),m=ra(r,n,d,A(e));return se(r,m),m}return r}function tc(e,t,n){let o=zn(t.map(({long:a})=>({long:a}))),i=[...Ru].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new I(`Unknown option '${r}' for extension command '${n}'. ${r} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:r,required:`Remove ${r}, or use it on the root command (pm --help ${r}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function dt(e,t,n){let o=Qe(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=Qe(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function Zt(e){return e.arguments??[]}function Qs(e){let t=Zt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Yo(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}var nc=Symbol("pm.commandOptionTokens"),ec=Symbol("pm.capturesOptionTokens");function oc(e){if(Reflect.get(e,ec)===!0)return;Reflect.set(e,ec,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,nc,[...n]),t(n))}function Tu(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function Iu(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function ic(e){let t=[];for(let o=e;o?.parent;o=o.parent)t.unshift(o);let n=[];for(let o of t){let i=Reflect.get(o,nc);if(i===void 0)continue;let r=Tu(o),a=[];for(let s=o;s;s=s.parent)a.push(s);n.push({tokens:i,optionOf:s=>r.get(s),includesLooseFlags:o===e,negativeNumbersAreValues:!a.some(s=>s.options.some(c=>c.short!==void 0&&/^-\d$/u.test(c.short))),...Iu(o)})}return n}function rc(e,t,n){t.length!==0&&ca(ic(e),t,n)}function Xo(e,t){let n=Zt(e),o=n.filter(c=>c.required).length,r=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new I(`Missing required argument for extension command '${e.command}'. Usage: ${Qs(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new I(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Qs(e)}${s}`,g.USAGE)}}function $u(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Qt(e,t){return{definitions:e,inheritedFlags:Ot({readOutput:t}).map(n=>n.flag)}}function Pu(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map($u);if(o.length===0)return;let{inheritedFlags:i}=Qt([],n);throw new I(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Lu(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Wn(t,n,e.command,Qt(n,o));return}Pu(t,e.command,o)}function Zo(e,t,n,o){e&&(Xo(e,t),Lu(e,n,o))}import{Command as ac}from"commander";var Nu=new Set(["--version","-V"]);function mt(e){let t;try{t=pe(e).argv}catch{return!1}let n=Kr(t),o=S(n);return o===void 0?!1:["package","packages","extension"].includes(n[o])&&["inventory","list"].includes(It(n.slice(o+1))??"")}function sc(e){if(j(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new ac().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of ue)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Mu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Qo=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"]),cc=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Fu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Du=new Set(["claim","close-task","pause-task","release","start-task","test"]),xe={setup:!0,listQuery:!0,mutation:!0,operation:!0},ju=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 ut(e){return e.some(t=>Nu.has(t))}function Uu(e,t){if(!M.some(o=>o.canonical_argv[0]===t))return;let n=new ac().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Te(t,z(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let r of[o.flag,o.short,...o.aliases??[]])r!==void 0&&n.option(`${r}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return xe;let i=V([t,...o.operands])?.alias;if(M.some(r=>r.alias===i))return{...xe,targetCommandName:i}}catch{return xe}}function ei(e){if(ut(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return xe;let t=E(e);if(!t)return xe;let n=t.trim().toLowerCase(),o=j(e),i=V(o)?.alias;if(M.some(a=>a.alias===i))return{...xe,targetCommandName:i};let r=Uu(o,n==="ctx"?"context":n);return r||(Mu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Qo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:cc.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Fu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:xe)}function ti(e){return e.length===0||P(e).requested||e.includes("--explain")&&E(e)===void 0}function ni(e,t){return mt(t)||ut(t)?!1:ae(t)||P(t).requested?!0:!!E(t)}function oi(e){if(ut(e))return!1;let t=E(e);return t?ju.has(t):!1}function qu(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),r=i?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${i}${l.slice(d)}`:i:l}):e.argv,a=We(r),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ii(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),i=o.length>0?o.join(" "):"the canonical flag",r=cc.has(t)||Du.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=qu({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new I(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:a,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}var Hu=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"]),Gu=new Set(["parse","preflight","execute","unknown"]),zu=new Set(["usage","validation","conflict","runtime","unknown"]);function be(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function ri(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function en(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 ai(e){if(!e)return;let t=e.trim().toLowerCase();if(Hu.has(t))return t}function si(e){if(!e)return;let t=e.trim().toLowerCase();if(Gu.has(t))return t}function ci(e){if(!e)return;let t=e.trim().toLowerCase();if(zu.has(t))return t}function li(e){let t=be(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(ri(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=en(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>yn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function di(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function mi(){let e=yn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=en(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=pa(o),r=be(e,"error_code","errorCode")??di(i,o),a=ci(be(e,"error_category","errorCategory"))??(i?void 0:ht(r)),s=i?void 0:li(e)??`command_exit_${o}`,c=ai(be(e,"command_resolution","commandResolution"))??Et({ok:i,errorCode:r,errorCategory:a}),l=si(be(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,command_resolution:c,resolution_stage:l}}var ui="PM_CLI_PACKAGE_ROOT",_c=Symbol("pm.deprecatedAliasInvocation"),on=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=on.get(t)??[];n.push(e),on.set(t,n)}for(let e of on.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Wu(){return or(import.meta.url,["../.."])}(typeof process.env[ui]!="string"||process.env[ui]?.trim().length===0)&&(process.env[ui]=Wu());var Se=null,H=null,rn=null;function Bu(e){Se=e}function Vu(e){T=e}var pt=null,ke=null,T=new Map,wi=250,Ju=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Ku=new Set(["1","true","yes","on"]),Yu=Ye(()=>import("./chunks/register-setup-IJ7M3VUK.js")),Xu=Ye(()=>import("./chunks/register-list-query-YGVUE4YZ.js")),Zu=Ye(()=>import("./chunks/register-mutation-3JVZQDHH.js")),Qu=Ye(()=>import("./chunks/register-operations-LCHUHKRA.js"));function nn(e){return _(e)}function wc(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=>ge(o)??o))];return n.length>0?n:void 0}function ep(e,t,n,o){if(n?.suggested_retry||o===io||o===oo||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=ee(t),r=new Set(i.map(m=>ge(m)??m)),a=wc(e),s=t.find(m=>w.commands.some(u=>u.name()===m)),c=s?w.commands.find(m=>m.name()===s):void 0,l=new Set([...w.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(u=>ge(u)).filter(u=>u!==void 0))),d=a?.filter(m=>{let u=ge(m)??m;return r.has(u)?!1:l.has(u)||Ao(t,s,u,T)!==void 0});return d&&d.length>0?d:void 0}function tp(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?ge(i):void 0,a=e.find(u=>w.commands.some(p=>p.name()===u)),s=a?w.commands.find(u=>u.name()===a):void 0,c=r?s?.options.find(u=>u.flags.split(/[ ,|]+/).includes(r)):void 0,l=Ao(e,a,r,T),d=r?c?.isBoolean()===!0||l===!1?[r]:[r,"<value>"]:[],m=r?nn([...e,...d]):t;return m===t?void 0:m}function np(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!==void 0&&(o==="allowed_values"||i!==null)&&(n[o]=i)}return n}function op(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,...np(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function lc(e,t){return{...e,recovery:t}}function ip(e,t){if(t===void 0)return;let n=ja(e,t.code,t.field,Na(e,t.code,t.recovery)),o=rp(e),i=Ua(e,t.code,t.field,n,o),r=Fa(e,t.code,i,o,()=>Hr($(process.cwd(),L(e).path)));return qa(e,t.code,r,o)}var dc=" ";function rp(e){let t=e.map(i=>i===""?dc:/^--(?:pm-)?path=$/u.test(i)?`${i}${dc}`:i),n=L(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Ee({});return n!==void 0&&o.length>0?null:o}function vc(e,t,n){let o=We(t),i=j(o),r=S(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:kr(e);let l=ip(o,e),d=l&&(a==="history-redact"||a==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:nn(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:nn(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return lc(e,d);let m=nn(o),u=ee(o),p=ep(n,o,d,e?.code),f=tp(o,m,p,d),y=op({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:d});return lc(e,y)}async function ft(e){let t=H;H=null,await Ha(t,e);let n=Se;if(Se=null,!n){xt();return}let o=[],i=hr();try{await Ga({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await sr(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:de(),affected:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{xt()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${W(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${W(o)}`)}async function Cc(e,t){await Rr();let n=H,o=Se,i=n?.command??o?.commandName??e,r=n??On(o?.globalOptions??t),a=T.get(v(i))?.source;Nn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??He,extension:a})}function xc(e){return Ku.has((process.env[e]??"").trim().toLowerCase())}function bc(e){return xc("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Ju.has(Math.trunc(e))}async function an(e,t){return bc(e.exit_code)?(await Cc(e.command,t),Pr({...e,source_context:e.source_context??On(t).source_context}),!0):!1}async function kc(e){let t=J(me(e.error)),n=ys(t);e.bootstrapGlobal.json?x(JSON.stringify(et(gs(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Cc(e.attemptedCommand,e.bootstrapGlobal),Mn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,await ln(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to report error: ${me(r)}`)}try{await ft({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to run error hooks: ${me(r)}`)}try{await Oe()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${me(r)}`)}}var ap={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"},pi=new Map;function fi(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Sc(e,t){return e.options.some(n=>n.long===t)}function Ec(e,t){return e.options.some(n=>n.short===t)}function gi(e,t,n,o){let i=t.trim();if(!i||!Fi(i))return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Ec(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,Gn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!Sc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,Gn);return}e.option(`${a} <value>`,r)}}async function Ac(e,t){let n=ap[e];if(!n)return[];let o=`${t}:${n}`,i=pi.get(o);if(i)return i;if(!await Y(X(t)))return pi.set(o,[]),[];let r=await F(t),s=(wn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:fi(c.type),value_type:fi(c.type)})));return pi.set(o,s),s}async function Rc(e,t){let n=L(t),o=$(process.cwd(),n.path);if(!await Y(X(o)))return;let i=ke?.key===xi(o)?ke.snapshot:null,r=i===null?await F(o):i.settings,a=wn(r.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=oe(e,c.path.split(" "));if(l)for(let d of a.command_to_fields.get(c.command)??[]){let m=d.description??"";gi(l,d.cli_flag,m,d.repeatable);for(let u of d.cli_aliases)gi(l,u,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function vi(e,t,n,o,i){let r=E(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await F(t),s=ce(a,o);Ws(e,s,n)}catch{}}function hi(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Oc(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ci(e){return e.some(t=>t==="--profile")}function xi(e){return`pm-root:${e}`}function yi(e){for(let t of e)t.startsWith("settings_read_")&&fe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Tc(e,t){e.profile&&(x(`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&&x(`profile:extensions activation_warnings=${W(t.activationWarnings)}`))}function sn(e,t,n){if(!e)return;let o=v(n.commandPath??"")||"<none>";x(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function cn(e,t=Re){let n=xi(e);if(ke?.key===n)return ke.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await cr({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return ke={key:n,snapshot:s},s}catch{return ke={key:n,snapshot:null},null}}async function Ge(e,t,n=F){let o=t?lt(t):"all",i=Oc(e,o);if(pt?.key===i)return pt.snapshot;try{let r=await n(e),a=await Je({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Bo(t):void 0}),s=await Ke({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(p=>v(p.command)))].filter(p=>p.length>0).sort((p,f)=>p.localeCompare(f)),l=Rs(s.registrations.flags),d=Es(s.commands.handlers,s.registrations.commands),m=Ts(c,s.registrations.commands,s.registrations.flags,d),u={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:r,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:p,module:f})=>({name:p,module:f}))};return pt={key:i,snapshot:u},u}catch{return pt={key:i,snapshot:null},null}}async function Ic(e){let t=Ze(e);if(t.noExtensions){let a=$(process.cwd(),t.path);return await Y(X(a))&&yi((await Re(a)).warnings),null}let n=$(process.cwd(),t.path),o=await cn(n);if(!o)return null;yi(o.settingsReadWarnings);let i={commandPath:A(e),commandArgs:Vo(e)};if(!ct(o.discovery,i))return sn(t.profile,o,i),null;let r=await Ge(n,i);return r?(Tc(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function bi(e){let t=await Ge(e);return t?new Map(t.commandDescriptors):T}async function sp(e,t){return!e.requested||t.noExtensions||Ne(w,e.commandPathTokens)?T:bi($(process.cwd(),t.path))}async function $c(e,t){return(await Vr({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 Pc(e,t,n){let o=t.author;return Br(e,ya.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Lc(e,t,n,o=[]){let i=A(e),r=Bn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=$(process.cwd(),n.path),l={args:[...r],path:n.path},d=await bt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&x(`profile:extensions parser_warnings=${W(d.warnings)}`),r=d.context.args,a=d.context.options,s=d.context.global,Qn(l,{args:r,path:s.path},a),Zo(T.get(v(i)),r,a,o),Ae(void 0),Ct({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await Rn({command:i,args:r,options:a,global:s,pm_root:c,sdk:Pc(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${W(m.warnings)}`),!m.handled)throw m.warnings.length>0?Or(i,m):new I(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Ae(m.result),m.result}var mc=Symbol("pm.wrappedActionHandler");function cp(e,t){let n=e[e.length-1];return n instanceof _i?n:t}function uc(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${W(n)}`)}function lp(e){let t=T.get(v(e.commandPath));if(!t||!Yo(e.activeRegistrations,e.commandPath))return;let n=Zt(t).length===0?sa(e.commandArgs):Bn(e.commandArgs,e.extensionFlagDefinitions);Xo(t,n)}function dp(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 ki(e,t,n){if(!at(e))return;let o=T.get(v(t))?.read_output_declared===!0;return Qt(n,o)}function Nc(e){let t=n=>{let o=n;if(oc(n),typeof o._actionHandler=="function"&&o[mc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=cp(a,n),c=Date.now();Hn(s);let l=Ze(s),d=G(A(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return $a(d,l.expectHash),await i.apply(this,a);let m=$(process.cwd(),l.path),u=s.args.map(String),p=le(),f=p?dt(p,d,u):[],y=await Ac(d,m),h=ki(s,d,f),C=Ue(s,u,[...f,...y],h);rc(s,f,d),T.has(v(d))&&delete C.author,h!==void 0&&tc(C,f,d);let R={args:[...u],path:l.path},O=await bt({command:d,args:u,options:C,global:l,pm_root:m});uc(l.profile,"parser_warnings",O.warnings),u=O.context.args,C=O.context.options,se(s,C),l=O.context.global,Qn(R,{args:u,path:l.path},C),lp({activeRegistrations:p,commandPath:d,commandArgs:u,extensionFlagDefinitions:f}),l=await oa(l),Pt(s,l),dp(s,a,u),$t(s,C),Ae(void 0),Ct({command:d,args:u,options:{...C},global:{...l},pm_root:m});let k=await Rn({command:d,args:u,options:C,global:l,pm_root:m,sdk:Pc(m,l,d)});if(uc(l.profile,"command_handler_warnings",k.warnings),k.handled){Ae(k.result),En(k.result,{...l,command:d,commandArgs:u,commandOptions:C,pmRoot:m}),l.profile&&x(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await i.apply(this,a)},o[mc]=!0}for(let i of n.commands)t(i)};t(e)}async function tn(e){T=new Map,re({overrides:[]}),e&&await vi(e.rootProgram,e.pmRoot,e.invocationArgv,rr(),e.settings)}function mp(e,t,n,o){if(t?.flags&&t.flags.length>0){To(e,t.flags);let i=Io(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&at(e)&&e.addHelpText("after",Po(t)),o&&e.addHelpText("after",o)}function up(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Po(n)),o&&e.addHelpText("after",o)}function Mc(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),l=c.length===0?"standard":c.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");Dt(r,l);for(let d of r.commands)i(d,[...a,d.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function Fc(e,t){let n=L(t),o=$(process.cwd(),n.path);if(n.noExtensions){await tn({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await cn(o),r=je(t);if(!i){await tn();return}if(!ct(i.discovery,r)){await tn({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),sn(Ci(t),i,r);return}let a=await Ge(o,r);if(!a){await tn({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),T=new Map(a.commandDescriptors),await vi(e,o,t,a.registrations,a.settings);let s=Fs(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Ds(a.activationWarnings,x,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(R=>R.length>0),u=a.commandDescriptors.get(d),p=oe(e,m),f=a.commandFlagHelp.get(d),y=u?Ns(u):null;if(p){mp(p,u,f,y);return}let h=Ms(e,m);u?.description&&h.description(u.description);let C=f;u&&(Is(h,u),u.flags.length>0&&(To(h,u.flags),C=Io(h,u.flags)??void 0)),up(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let O=R[R.length-1],k=O instanceof _i?O:h,gt=Ze(k),Kc=Date.now(),dn=dt(a.registrations,d,k.args.map(String)),Ai=Ue(k,k.args.map(String),dn,ki(k,d,dn)),Ri=await Lc(k,Ai,gt,dn);await ia(gt,Ri),En(Ri,{...gt,command:d,commandArgs:k.args.map(String),commandOptions:Ai,pmRoot:o}),gt.profile&&x(`profile:command=${d} took_ms=${Date.now()-Kc}`)})};for(let d of s)l(d);Mc(e,c,a.commandDescriptors)}var He=ir(import.meta.url,["../.."])??"0.0.0",w=qn(He);async function pc(e){if(!H)return;let t=Reflect.get(e,_c);typeof t=="string"&&await ha(t)}async function fc(e,t,n){let o=A(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function gc(e,t,n){!H||!await Tn(!0)||(Nn(e,t,n,{source_context:H.source_context,source_context_source:H.source_context_source}),Tr(e),rn=H)}async function ln(e,t,n){let o=rn;if(!o)return;rn=null;let i=!1;try{let r=await F(o.global_pm_root);i=r.telemetry.enabled&&r.telemetry.installation_id===o.installation_id}catch{}await Tn(i)?$r(e,t,n):Ir()}async function pp(e){let t=await Ic(e);return An(t?.registrations??null),t}function Dc(e,t){t&&mt(t)||(e.hook("preAction",async(n,o)=>{Se=null,H=null,rn=null,xt(),Hn(o);let i=o.optsWithGlobals(),r=Ze(o),a=G(A(o)),s=o.args.map(String),c={args:[...s],path:r.path},l=Ue(o,s),d={...r},m=$(process.cwd(),r.path),u=await pp(o);if(Vi(a,{...l,...Bi(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Ko(o,a,d,l),await fc(o,void 0,()=>Fr(a,d)),!u){Se=lr({commandName:a,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),H=await Fn({command:a,pm_version:He,args:s,options:l,global:d,pm_root:m}),await pc(e),await gc(a,s,l),await Do(a,l,m,hi()),await Fo(a,s,l,d,m),await Zn({command:o,commandPath:a,commandArgs:s,commandOptions:l,expectHash:r.expectHash,pmRoot:m,globalOptions:d});return}dr(u.hooks),mr(u.commands),ur(u.parsers),pr(u.preflight),re(u.services),fr(u.renderers),An(u.registrations);let p=dt(u.registrations,a,s);l=Ue(o,s,p,ki(o,a,p)),Ko(o,a,d,l);let f=await bt({command:a,args:s,options:l,global:d,pm_root:u.pmRoot});d.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${W(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),d=f.context.global;let y={args:[...s],path:d.path};$t(o,l);let h=await yr({command:a,args:s,options:l,global:d,pm_root:u.pmRoot,decision:hi()});d.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${W(h.warnings)}`),s=h.context.args,l=h.context.options,se(o,l),d=h.context.global,$t(o,l);let C=h.decision;await Do(a,l,u.pmRoot,C),await Fo(a,s,l,d,u.pmRoot),await Zn({command:o,commandPath:a,commandArgs:c.args,commandOptions:l,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:Xn(c,[y,{args:s,path:d.path}]),globalOptions:{...d,path:r.path,noExtensions:r.noExtensions}});let R=C.run_extension_migrations?await fc(o,[],()=>$c(u.registrations.migrations,u.pmRoot)):[];d.profile&&R.length>0&&x(`profile:extensions migration_warnings=${W(R)}`);let O=Js(u.registrations.migrations);Se={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:u.pmRoot,profileEnabled:!!d.profile,migrationBlockers:O},Ae(void 0),Ct({command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot}),H=await Fn({command:a,pm_version:He,args:s,options:l,global:d,pm_root:u.pmRoot}),await pc(e),await gc(a,s,l);let k=await ar(u.hooks,{command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot});d.profile&&k.length>0&&x(`profile:extensions hook_warnings=${W(k)}`),C.enforce_mandatory_migration_gate&&Ks(a,l,O)}),e.hook("postAction",async()=>{let n=mi();await ln(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await ft(n),await Oe()}))}Dc(w);var hc=Symbol("pmCliIdempotentTopLevelRegistration");function jc(e){let t=e;if(t[hc])return;t[hc]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new _i(r):n(o,...i)})}async function fp(e,t){if(jc(e),t.setup){let{registerSetupCommands:n}=await Yu();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Xu(),o=typeof t.targetCommandName=="string"&&Qo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Zu();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Qu();n(e)}}function qe(e){return e.rawInvocationArgv??e.invocationArgv}function gp(e){return async t=>{let n=ht(t.errorCode),o=Et({ok:!1,errorCode:t.errorCode,errorCategory:n});return await jr({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:He,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 Uc(e){if(e.bootstrapGlobal.noExtensions||mt(e.invocationArgv))return;let t=je(e.invocationArgv),n=await cn(e.bootstrapPmRoot);if(n&&ct(n.discovery,t)){let o=await Ge(e.bootstrapPmRoot,t);qc(o);return}n&&sn(Ci(e.invocationArgv),n,t),re({overrides:[]})}function qc(e){if(!e){re({overrides:[]});return}re(e.services)}async function Si(e){await ln(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await ft({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 Hc(){await ln(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await ft({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Gc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof I)&&(Pn(e.error)||!n))return!1;let o=J(me(e.error)),i=e.error instanceof I?e.error.exitCode:$n(t),r=e.error instanceof I||Ar(e.error)?e.error.context:void 0,a=vc(r,e.invocationArgv,o),s=ps(o,a),c=et(e.bootstrapGlobal.lean?Ut(wo(o,i,a)):wo(o,i,a)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Z(c,p=>`${JSON.stringify(p,null,2)}
40
+ `):c,null,2):ms(o,a,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?ie(`${l}
41
+ `):x(l);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),u=await an({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:H?.source_context},e.bootstrapGlobal);return await Si({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),u&&(Mn(Ln(e.error,o)),await Oe(wi)),process.exitCode=i,!0}async function zc(e,t){let n=P(e.invocationArgv).commandPathTokens.join(" ")||xo(e.invocationArgv),o=G(n),i=`unknown command '${n}'`,r=$(process.cwd(),e.bootstrapGlobal.path),a=e.bootstrapGlobal.noExtensions?T:await bi(r),s=je(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await No(r,{},De(s)),l=await it({message:i},w,a,{failedExtensions:c},qe(e)),d=vo(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:u}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await an({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:u,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await Eo({message:i},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:c},qe(e)):await So({message:i},w,a,{failedExtensions:c},qe(e)),y=Co(f,e.jsonErrors,c);await Si({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:u,resolutionStage:"parse"}),e.jsonErrors?ie(`${Kn(y)}
42
+ `):x(y),p&&await Oe(wi),process.exitCode=g.USAGE}async function Wc(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=P(e.invocationArgv);return i.requested&&!Ne(w,i.commandPathTokens)?(await zc(e,t),!0):(await Hc(),!0)}async function Bc(e,t){let n=await it(e.error,w,T,{},qe(e)),o=vo(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:i,commandResolution:r}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await an({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:r,resolution_stage:"parse",source_context:H?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await Eo(e.error,w,T,e.bootstrapGlobal.lean===!0,{},qe(e)):await So(e.error,w,T,{},qe(e)),c=await js(o.code,e.bootstrapPmRoot,{},De(je(e.invocationArgv))),l=Co(s,e.jsonErrors,c);await Si({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?ie(`${Kn(l)}
43
+ `):x(l),a&&await Oe(wi),process.exitCode=g.USAGE}function Vc(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 Jc(e){let t=e.error.code,n=String(e.error.message??"");if(!await Wc(e,t,n)){if(t==="commander.version"){await Hc();return}await Bc(e,t)}}async function Ei(e){let t=L(e.invocationArgv),n=$(process.cwd(),t.path),o=he(e.invocationArgv),i={error:e.error,invocationArgv:o,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:E(o)??"<unknown>",emitTelemetryCommandError:gp({invocationArgv:o,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Uc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Gc(i,In(e.error))){if(Vc(e.error)){await Jc(i);return}await kc({error:e.error,attemptedCommand:i.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:i.emitTelemetryCommandError})}}function hp(e,t,n){let o=n.requested?n.commandPathTokens:j(t),i=V(o);if(i&&!oe(e,[...i.canonical_argv]))throw new yc(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function yp(e,t){let n=S(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=S(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=on.get(t[n]),i=t.slice(n).filter(a=>!["--global","--project","--local"].includes(a)),r=o?.find(a=>a.alias.split(" ").every((s,c)=>i[c]===s));r?.lifecycle==="deprecated"&&Reflect.set(e,_c,r.alias)}function _p(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function wp(e,t){w=qn(He),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(A(a))&&a.optsWithGlobals().dryRun===!0}),Dc(w,e),pt=null,ke=null,T=new Map,gr();let n=[...e],o,i;try{let r=pe(e);n=r.argv,Aa(r.trace),yp(w,e);let a=_p(n),s=n.length===0,c=L(n);if(c.authorMissingValue)throw new I("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=ta(c.author),ii(r),i=Jr(n);let l=ei(n);await fp(w,l),co(w,!0),ni(w,n)?await Fc(w,n):(T=new Map,re({overrides:[]})),oi(n)&&await Rc(w,n),co(w);let m=P(n);hp(w,n,m),ti(n)&&Ka(w,n),Nc(w);let u=await sp(m,c);if(await zs(w,n,u,e))return;if(m.requested&&!Ne(w,m.commandPathTokens))throw new yc(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ae(n)&&E(n)===void 0){w.outputHelp();return}if(mt(n)){await w.parseAsync(a);return}let f=$(process.cwd(),c.path),y=await F(f),h=await ks(n,f,c.noExtensions,Ge);await Pa(C=>Wr({pmRoot:f,packages:h?.contextIntentPackages},()=>Di({env:{...process.env,PM_PATH:f},argv:a,cwd:process.cwd()},()=>ji(y.agent_identity.harness_signals,()=>C(()=>w.parseAsync(a)),{probesEnabled:y.agent_identity?.probes_enabled}))))}catch(r){await Ei({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function qh(e=process.argv.slice(2)){let t=e;try{t=pe(e).argv}catch{}await Ni([...e,...t],()=>vp(e,t))}async function vp(e,t){let n=sc(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=()=>Oa(L(t).json,async()=>{try{await na(process.env,()=>wp(e,o))}catch(a){await Ei({error:a,invocationArgv:[...e]})}});if(n!==void 0){let a=$(process.cwd(),L(t).path),s=$(process.cwd(),n.path),c=Pi(process.cwd());await kt(a,()=>kt(s,()=>kt(c,r,i),i),i)}else await r()}var Hh={activationCommandMatchesProbe:Uo,applyDynamicExtensionRootHelpVisibility:Mc,bootstrapProfileEnabled:Ci,buildBootstrapActivationProbe:je,buildPostActionTelemetryOutcome:mi,buildPmCliRecoveryContext:vc,buildRuntimeExtensionDiscoverySnapshotCacheKey:xi,buildRuntimeExtensionActivationScope:lt,buildRuntimeExtensionSnapshotCacheKey:Oc,buildRuntimeExtensionFilterForProbe:Bo,addRuntimeFieldOption:gi,collectActivationCommandCandidates:De,collectExtensionFlagDefinitionsForCommand:Qe,collectExtensionFlagDefinitionsForInvocation:dt,collectLeadingCommandArgs:jo,collectParsedActivationCommandArgs:Vo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Ac,commandHasLongOption:Sc,commandHasShortOption:Ec,commandPathNeedsSearchExtensions:qo,commandPathNeedsTemplateExtensions:Kt,describeUnknownError:me,defaultPreflightDecision:hi,discoveryNeedsActivationForProbe:ct,emitExtensionProfile:Tc,emitExtensionSkippedProfile:sn,emitSettingsReadWarnings:yi,ensureIdempotentTopLevelCommandRegistration:jc,enforceExplicitRetryForFlagTypos:ii,envFlagEnabled:xc,executeRegisteredRuntimeMigrations:$c,extractCommandScopedOptions:Ue,extensionActivationCommands:Jt,extensionCapabilities:st,extensionNeedsActivationForProbe:Yt,extensionProvidesTemplatesRuntime:Go,hasAnyCapability:Fe,hasGlobalExtensionContributions:zo,handleGenericRunPmCliError:kc,handleRunPmCliCommanderError:Jc,handleRunPmCliError:Ei,handleRunPmCliHelpDisplayError:Wc,handleRunPmCliKnownError:Gc,handleRunPmCliCommanderUsageError:Bc,handleUnknownHelpCommandError:zc,inferMissingFieldsFromErrorMessage:wc,inferPostActionErrorCode:di,inferPostActionFailureMessage:li,invocationRequestsVersion:ut,isCommanderError:Pn,loadRuntimeExtensionCommandDescriptorsForRecovery:bi,loadRuntimeExtensionDiscoverySnapshot:cn,loadRuntimeExtensionSnapshot:Ge,maybeLoadRuntimeExtensions:Ic,maybeAttachCreateUpdatePolicyHelpText:vi,maybeLogHandledCliErrorToSentry:an,matchesStaticExtensionCommand:Vt,normalizeTelemetryCommandResolution:ai,normalizeTelemetryErrorCategory:ci,normalizeTelemetryResolutionStage:si,normalizeThrownExitCode:$n,probeUsesAnyFlag:Ho,prepareExtensionServicesForRunPmCliError:Uc,readRecordBoolean:ri,readRecordNumber:en,readRecordString:be,recordCliReadOutputInvocationProvenance:Jo,registerDynamicExtensionCommandPaths:Fc,registerRuntimeSchemaFieldFlags:Rc,resolveCoreCommandRegistrationSelection:ei,resolveStaticExtensionActivationDecision:Wo,resolveUnknownHelpToken:xo,readThrownExitCode:In,runAndClearAfterCommandHooks:ft,runRequiredExtensionCommand:Lc,shouldAttachRichHelpTextForInvocation:ti,shouldLogHandledErrorToSentry:bc,shouldRegisterDynamicExtensionPaths:ni,shouldRegisterRuntimeSchemaFlags:oi,shouldHandleRunPmCliCommanderError:Vc,setActiveExtensionHookContextForTest:Bu,setActiveRuntimeExtensionCommandDescriptorsForTest:Vu,setRecoveredExtensionServices:qc,toLooseFieldDefinitionType:fi,isImporterOrExporterCommandPath:Yo,validateDynamicExtensionCommandInvocation:Zo,wrapProgramActionsForExtensionHandlers:Nc,wrapThrownErrorForSentry:Ln};export{Hh as _testOnly,qh as runPmCli};
44
44
  //# sourceMappingURL=main.js.map